xref: /openbmc/qemu/hw/core/loader.c (revision db76ec62)
1 /*
2  * QEMU Executable loader
3  *
4  * Copyright (c) 2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  *
24  * Gunzip functionality in this file is derived from u-boot:
25  *
26  * (C) Copyright 2008 Semihalf
27  *
28  * (C) Copyright 2000-2005
29  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
30  *
31  * This program is free software; you can redistribute it and/or
32  * modify it under the terms of the GNU General Public License as
33  * published by the Free Software Foundation; either version 2 of
34  * the License, or (at your option) any later version.
35  *
36  * This program is distributed in the hope that it will be useful,
37  * but WITHOUT ANY WARRANTY; without even the implied warranty of
38  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
39  * GNU General Public License for more details.
40  *
41  * You should have received a copy of the GNU General Public License along
42  * with this program; if not, see <http://www.gnu.org/licenses/>.
43  */
44 
45 #include "hw/hw.h"
46 #include "disas/disas.h"
47 #include "monitor/monitor.h"
48 #include "sysemu/sysemu.h"
49 #include "uboot_image.h"
50 #include "hw/loader.h"
51 #include "hw/nvram/fw_cfg.h"
52 #include "exec/memory.h"
53 #include "exec/address-spaces.h"
54 
55 #include <zlib.h>
56 
57 bool option_rom_has_mr = false;
58 bool rom_file_has_mr = true;
59 
60 static int roms_loaded;
61 
62 /* return the size or -1 if error */
63 int get_image_size(const char *filename)
64 {
65     int fd, size;
66     fd = open(filename, O_RDONLY | O_BINARY);
67     if (fd < 0)
68         return -1;
69     size = lseek(fd, 0, SEEK_END);
70     close(fd);
71     return size;
72 }
73 
74 /* return the size or -1 if error */
75 /* deprecated, because caller does not specify buffer size! */
76 int load_image(const char *filename, uint8_t *addr)
77 {
78     int fd, size;
79     fd = open(filename, O_RDONLY | O_BINARY);
80     if (fd < 0)
81         return -1;
82     size = lseek(fd, 0, SEEK_END);
83     lseek(fd, 0, SEEK_SET);
84     if (read(fd, addr, size) != size) {
85         close(fd);
86         return -1;
87     }
88     close(fd);
89     return size;
90 }
91 
92 /* read()-like version */
93 ssize_t read_targphys(const char *name,
94                       int fd, hwaddr dst_addr, size_t nbytes)
95 {
96     uint8_t *buf;
97     ssize_t did;
98 
99     buf = g_malloc(nbytes);
100     did = read(fd, buf, nbytes);
101     if (did > 0)
102         rom_add_blob_fixed("read", buf, did, dst_addr);
103     g_free(buf);
104     return did;
105 }
106 
107 /* return the size or -1 if error */
108 int load_image_targphys(const char *filename,
109                         hwaddr addr, uint64_t max_sz)
110 {
111     int size;
112 
113     size = get_image_size(filename);
114     if (size > max_sz) {
115         return -1;
116     }
117     if (size > 0) {
118         rom_add_file_fixed(filename, addr, -1);
119     }
120     return size;
121 }
122 
123 void pstrcpy_targphys(const char *name, hwaddr dest, int buf_size,
124                       const char *source)
125 {
126     const char *nulp;
127     char *ptr;
128 
129     if (buf_size <= 0) return;
130     nulp = memchr(source, 0, buf_size);
131     if (nulp) {
132         rom_add_blob_fixed(name, source, (nulp - source) + 1, dest);
133     } else {
134         rom_add_blob_fixed(name, source, buf_size, dest);
135         ptr = rom_ptr(dest + buf_size - 1);
136         *ptr = 0;
137     }
138 }
139 
140 /* A.OUT loader */
141 
142 struct exec
143 {
144   uint32_t a_info;   /* Use macros N_MAGIC, etc for access */
145   uint32_t a_text;   /* length of text, in bytes */
146   uint32_t a_data;   /* length of data, in bytes */
147   uint32_t a_bss;    /* length of uninitialized data area, in bytes */
148   uint32_t a_syms;   /* length of symbol table data in file, in bytes */
149   uint32_t a_entry;  /* start address */
150   uint32_t a_trsize; /* length of relocation info for text, in bytes */
151   uint32_t a_drsize; /* length of relocation info for data, in bytes */
152 };
153 
154 static void bswap_ahdr(struct exec *e)
155 {
156     bswap32s(&e->a_info);
157     bswap32s(&e->a_text);
158     bswap32s(&e->a_data);
159     bswap32s(&e->a_bss);
160     bswap32s(&e->a_syms);
161     bswap32s(&e->a_entry);
162     bswap32s(&e->a_trsize);
163     bswap32s(&e->a_drsize);
164 }
165 
166 #define N_MAGIC(exec) ((exec).a_info & 0xffff)
167 #define OMAGIC 0407
168 #define NMAGIC 0410
169 #define ZMAGIC 0413
170 #define QMAGIC 0314
171 #define _N_HDROFF(x) (1024 - sizeof (struct exec))
172 #define N_TXTOFF(x)							\
173     (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) :	\
174      (N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
175 #define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
176 #define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
177 
178 #define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
179 
180 #define N_DATADDR(x, target_page_size) \
181     (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
182      : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
183 
184 
185 int load_aout(const char *filename, hwaddr addr, int max_sz,
186               int bswap_needed, hwaddr target_page_size)
187 {
188     int fd;
189     ssize_t size, ret;
190     struct exec e;
191     uint32_t magic;
192 
193     fd = open(filename, O_RDONLY | O_BINARY);
194     if (fd < 0)
195         return -1;
196 
197     size = read(fd, &e, sizeof(e));
198     if (size < 0)
199         goto fail;
200 
201     if (bswap_needed) {
202         bswap_ahdr(&e);
203     }
204 
205     magic = N_MAGIC(e);
206     switch (magic) {
207     case ZMAGIC:
208     case QMAGIC:
209     case OMAGIC:
210         if (e.a_text + e.a_data > max_sz)
211             goto fail;
212 	lseek(fd, N_TXTOFF(e), SEEK_SET);
213 	size = read_targphys(filename, fd, addr, e.a_text + e.a_data);
214 	if (size < 0)
215 	    goto fail;
216 	break;
217     case NMAGIC:
218         if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)
219             goto fail;
220 	lseek(fd, N_TXTOFF(e), SEEK_SET);
221 	size = read_targphys(filename, fd, addr, e.a_text);
222 	if (size < 0)
223 	    goto fail;
224         ret = read_targphys(filename, fd, addr + N_DATADDR(e, target_page_size),
225                             e.a_data);
226 	if (ret < 0)
227 	    goto fail;
228 	size += ret;
229 	break;
230     default:
231 	goto fail;
232     }
233     close(fd);
234     return size;
235  fail:
236     close(fd);
237     return -1;
238 }
239 
240 /* ELF loader */
241 
242 static void *load_at(int fd, int offset, int size)
243 {
244     void *ptr;
245     if (lseek(fd, offset, SEEK_SET) < 0)
246         return NULL;
247     ptr = g_malloc(size);
248     if (read(fd, ptr, size) != size) {
249         g_free(ptr);
250         return NULL;
251     }
252     return ptr;
253 }
254 
255 #ifdef ELF_CLASS
256 #undef ELF_CLASS
257 #endif
258 
259 #define ELF_CLASS   ELFCLASS32
260 #include "elf.h"
261 
262 #define SZ		32
263 #define elf_word        uint32_t
264 #define elf_sword        int32_t
265 #define bswapSZs	bswap32s
266 #include "hw/elf_ops.h"
267 
268 #undef elfhdr
269 #undef elf_phdr
270 #undef elf_shdr
271 #undef elf_sym
272 #undef elf_note
273 #undef elf_word
274 #undef elf_sword
275 #undef bswapSZs
276 #undef SZ
277 #define elfhdr		elf64_hdr
278 #define elf_phdr	elf64_phdr
279 #define elf_note	elf64_note
280 #define elf_shdr	elf64_shdr
281 #define elf_sym		elf64_sym
282 #define elf_word        uint64_t
283 #define elf_sword        int64_t
284 #define bswapSZs	bswap64s
285 #define SZ		64
286 #include "hw/elf_ops.h"
287 
288 const char *load_elf_strerror(int error)
289 {
290     switch (error) {
291     case 0:
292         return "No error";
293     case ELF_LOAD_FAILED:
294         return "Failed to load ELF";
295     case ELF_LOAD_NOT_ELF:
296         return "The image is not ELF";
297     case ELF_LOAD_WRONG_ARCH:
298         return "The image is from incompatible architecture";
299     case ELF_LOAD_WRONG_ENDIAN:
300         return "The image has incorrect endianness";
301     default:
302         return "Unknown error";
303     }
304 }
305 
306 /* return < 0 if error, otherwise the number of bytes loaded in memory */
307 int load_elf(const char *filename, uint64_t (*translate_fn)(void *, uint64_t),
308              void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
309              uint64_t *highaddr, int big_endian, int elf_machine, int clear_lsb)
310 {
311     int fd, data_order, target_data_order, must_swab, ret = ELF_LOAD_FAILED;
312     uint8_t e_ident[EI_NIDENT];
313 
314     fd = open(filename, O_RDONLY | O_BINARY);
315     if (fd < 0) {
316         perror(filename);
317         return -1;
318     }
319     if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))
320         goto fail;
321     if (e_ident[0] != ELFMAG0 ||
322         e_ident[1] != ELFMAG1 ||
323         e_ident[2] != ELFMAG2 ||
324         e_ident[3] != ELFMAG3) {
325         ret = ELF_LOAD_NOT_ELF;
326         goto fail;
327     }
328 #ifdef HOST_WORDS_BIGENDIAN
329     data_order = ELFDATA2MSB;
330 #else
331     data_order = ELFDATA2LSB;
332 #endif
333     must_swab = data_order != e_ident[EI_DATA];
334     if (big_endian) {
335         target_data_order = ELFDATA2MSB;
336     } else {
337         target_data_order = ELFDATA2LSB;
338     }
339 
340     if (target_data_order != e_ident[EI_DATA]) {
341         ret = ELF_LOAD_WRONG_ENDIAN;
342         goto fail;
343     }
344 
345     lseek(fd, 0, SEEK_SET);
346     if (e_ident[EI_CLASS] == ELFCLASS64) {
347         ret = load_elf64(filename, fd, translate_fn, translate_opaque, must_swab,
348                          pentry, lowaddr, highaddr, elf_machine, clear_lsb);
349     } else {
350         ret = load_elf32(filename, fd, translate_fn, translate_opaque, must_swab,
351                          pentry, lowaddr, highaddr, elf_machine, clear_lsb);
352     }
353 
354  fail:
355     close(fd);
356     return ret;
357 }
358 
359 static void bswap_uboot_header(uboot_image_header_t *hdr)
360 {
361 #ifndef HOST_WORDS_BIGENDIAN
362     bswap32s(&hdr->ih_magic);
363     bswap32s(&hdr->ih_hcrc);
364     bswap32s(&hdr->ih_time);
365     bswap32s(&hdr->ih_size);
366     bswap32s(&hdr->ih_load);
367     bswap32s(&hdr->ih_ep);
368     bswap32s(&hdr->ih_dcrc);
369 #endif
370 }
371 
372 
373 #define ZALLOC_ALIGNMENT	16
374 
375 static void *zalloc(void *x, unsigned items, unsigned size)
376 {
377     void *p;
378 
379     size *= items;
380     size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
381 
382     p = g_malloc(size);
383 
384     return (p);
385 }
386 
387 static void zfree(void *x, void *addr)
388 {
389     g_free(addr);
390 }
391 
392 
393 #define HEAD_CRC	2
394 #define EXTRA_FIELD	4
395 #define ORIG_NAME	8
396 #define COMMENT		0x10
397 #define RESERVED	0xe0
398 
399 #define DEFLATED	8
400 
401 /* This is the usual maximum in uboot, so if a uImage overflows this, it would
402  * overflow on real hardware too. */
403 #define UBOOT_MAX_GUNZIP_BYTES (64 << 20)
404 
405 static ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src,
406                       size_t srclen)
407 {
408     z_stream s;
409     ssize_t dstbytes;
410     int r, i, flags;
411 
412     /* skip header */
413     i = 10;
414     flags = src[3];
415     if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
416         puts ("Error: Bad gzipped data\n");
417         return -1;
418     }
419     if ((flags & EXTRA_FIELD) != 0)
420         i = 12 + src[10] + (src[11] << 8);
421     if ((flags & ORIG_NAME) != 0)
422         while (src[i++] != 0)
423             ;
424     if ((flags & COMMENT) != 0)
425         while (src[i++] != 0)
426             ;
427     if ((flags & HEAD_CRC) != 0)
428         i += 2;
429     if (i >= srclen) {
430         puts ("Error: gunzip out of data in header\n");
431         return -1;
432     }
433 
434     s.zalloc = zalloc;
435     s.zfree = zfree;
436 
437     r = inflateInit2(&s, -MAX_WBITS);
438     if (r != Z_OK) {
439         printf ("Error: inflateInit2() returned %d\n", r);
440         return (-1);
441     }
442     s.next_in = src + i;
443     s.avail_in = srclen - i;
444     s.next_out = dst;
445     s.avail_out = dstlen;
446     r = inflate(&s, Z_FINISH);
447     if (r != Z_OK && r != Z_STREAM_END) {
448         printf ("Error: inflate() returned %d\n", r);
449         return -1;
450     }
451     dstbytes = s.next_out - (unsigned char *) dst;
452     inflateEnd(&s);
453 
454     return dstbytes;
455 }
456 
457 /* Load a U-Boot image.  */
458 static int load_uboot_image(const char *filename, hwaddr *ep, hwaddr *loadaddr,
459                             int *is_linux, uint8_t image_type)
460 {
461     int fd;
462     int size;
463     hwaddr address;
464     uboot_image_header_t h;
465     uboot_image_header_t *hdr = &h;
466     uint8_t *data = NULL;
467     int ret = -1;
468     int do_uncompress = 0;
469 
470     fd = open(filename, O_RDONLY | O_BINARY);
471     if (fd < 0)
472         return -1;
473 
474     size = read(fd, hdr, sizeof(uboot_image_header_t));
475     if (size < 0)
476         goto out;
477 
478     bswap_uboot_header(hdr);
479 
480     if (hdr->ih_magic != IH_MAGIC)
481         goto out;
482 
483     if (hdr->ih_type != image_type) {
484         fprintf(stderr, "Wrong image type %d, expected %d\n", hdr->ih_type,
485                 image_type);
486         goto out;
487     }
488 
489     /* TODO: Implement other image types.  */
490     switch (hdr->ih_type) {
491     case IH_TYPE_KERNEL:
492         address = hdr->ih_load;
493         if (loadaddr) {
494             *loadaddr = hdr->ih_load;
495         }
496 
497         switch (hdr->ih_comp) {
498         case IH_COMP_NONE:
499             break;
500         case IH_COMP_GZIP:
501             do_uncompress = 1;
502             break;
503         default:
504             fprintf(stderr,
505                     "Unable to load u-boot images with compression type %d\n",
506                     hdr->ih_comp);
507             goto out;
508         }
509 
510         if (ep) {
511             *ep = hdr->ih_ep;
512         }
513 
514         /* TODO: Check CPU type.  */
515         if (is_linux) {
516             if (hdr->ih_os == IH_OS_LINUX) {
517                 *is_linux = 1;
518             } else {
519                 *is_linux = 0;
520             }
521         }
522 
523         break;
524     case IH_TYPE_RAMDISK:
525         address = *loadaddr;
526         break;
527     default:
528         fprintf(stderr, "Unsupported u-boot image type %d\n", hdr->ih_type);
529         goto out;
530     }
531 
532     data = g_malloc(hdr->ih_size);
533 
534     if (read(fd, data, hdr->ih_size) != hdr->ih_size) {
535         fprintf(stderr, "Error reading file\n");
536         goto out;
537     }
538 
539     if (do_uncompress) {
540         uint8_t *compressed_data;
541         size_t max_bytes;
542         ssize_t bytes;
543 
544         compressed_data = data;
545         max_bytes = UBOOT_MAX_GUNZIP_BYTES;
546         data = g_malloc(max_bytes);
547 
548         bytes = gunzip(data, max_bytes, compressed_data, hdr->ih_size);
549         g_free(compressed_data);
550         if (bytes < 0) {
551             fprintf(stderr, "Unable to decompress gzipped image!\n");
552             goto out;
553         }
554         hdr->ih_size = bytes;
555     }
556 
557     rom_add_blob_fixed(filename, data, hdr->ih_size, address);
558 
559     ret = hdr->ih_size;
560 
561 out:
562     if (data)
563         g_free(data);
564     close(fd);
565     return ret;
566 }
567 
568 int load_uimage(const char *filename, hwaddr *ep, hwaddr *loadaddr,
569                 int *is_linux)
570 {
571     return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL);
572 }
573 
574 /* Load a ramdisk.  */
575 int load_ramdisk(const char *filename, hwaddr addr, uint64_t max_sz)
576 {
577     return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK);
578 }
579 
580 /*
581  * Functions for reboot-persistent memory regions.
582  *  - used for vga bios and option roms.
583  *  - also linux kernel (-kernel / -initrd).
584  */
585 
586 typedef struct Rom Rom;
587 
588 struct Rom {
589     char *name;
590     char *path;
591 
592     /* datasize is the amount of memory allocated in "data". If datasize is less
593      * than romsize, it means that the area from datasize to romsize is filled
594      * with zeros.
595      */
596     size_t romsize;
597     size_t datasize;
598 
599     uint8_t *data;
600     MemoryRegion *mr;
601     int isrom;
602     char *fw_dir;
603     char *fw_file;
604 
605     hwaddr addr;
606     QTAILQ_ENTRY(Rom) next;
607 };
608 
609 static FWCfgState *fw_cfg;
610 static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms);
611 
612 static void rom_insert(Rom *rom)
613 {
614     Rom *item;
615 
616     if (roms_loaded) {
617         hw_error ("ROM images must be loaded at startup\n");
618     }
619 
620     /* list is ordered by load address */
621     QTAILQ_FOREACH(item, &roms, next) {
622         if (rom->addr >= item->addr)
623             continue;
624         QTAILQ_INSERT_BEFORE(item, rom, next);
625         return;
626     }
627     QTAILQ_INSERT_TAIL(&roms, rom, next);
628 }
629 
630 static void *rom_set_mr(Rom *rom, Object *owner, const char *name)
631 {
632     void *data;
633 
634     rom->mr = g_malloc(sizeof(*rom->mr));
635     memory_region_init_ram(rom->mr, owner, name, rom->datasize);
636     memory_region_set_readonly(rom->mr, true);
637     vmstate_register_ram_global(rom->mr);
638 
639     data = memory_region_get_ram_ptr(rom->mr);
640     memcpy(data, rom->data, rom->datasize);
641 
642     return data;
643 }
644 
645 int rom_add_file(const char *file, const char *fw_dir,
646                  hwaddr addr, int32_t bootindex,
647                  bool option_rom)
648 {
649     Rom *rom;
650     int rc, fd = -1;
651     char devpath[100];
652 
653     rom = g_malloc0(sizeof(*rom));
654     rom->name = g_strdup(file);
655     rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
656     if (rom->path == NULL) {
657         rom->path = g_strdup(file);
658     }
659 
660     fd = open(rom->path, O_RDONLY | O_BINARY);
661     if (fd == -1) {
662         fprintf(stderr, "Could not open option rom '%s': %s\n",
663                 rom->path, strerror(errno));
664         goto err;
665     }
666 
667     if (fw_dir) {
668         rom->fw_dir  = g_strdup(fw_dir);
669         rom->fw_file = g_strdup(file);
670     }
671     rom->addr     = addr;
672     rom->romsize  = lseek(fd, 0, SEEK_END);
673     rom->datasize = rom->romsize;
674     rom->data     = g_malloc0(rom->datasize);
675     lseek(fd, 0, SEEK_SET);
676     rc = read(fd, rom->data, rom->datasize);
677     if (rc != rom->datasize) {
678         fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
679                 rom->name, rc, rom->datasize);
680         goto err;
681     }
682     close(fd);
683     rom_insert(rom);
684     if (rom->fw_file && fw_cfg) {
685         const char *basename;
686         char fw_file_name[FW_CFG_MAX_FILE_PATH];
687         void *data;
688 
689         basename = strrchr(rom->fw_file, '/');
690         if (basename) {
691             basename++;
692         } else {
693             basename = rom->fw_file;
694         }
695         snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
696                  basename);
697         snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
698 
699         if ((!option_rom || option_rom_has_mr) && rom_file_has_mr) {
700             data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);
701         } else {
702             data = rom->data;
703         }
704 
705         fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
706     } else {
707         snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);
708     }
709 
710     add_boot_device_path(bootindex, NULL, devpath);
711     return 0;
712 
713 err:
714     if (fd != -1)
715         close(fd);
716     g_free(rom->data);
717     g_free(rom->path);
718     g_free(rom->name);
719     g_free(rom);
720     return -1;
721 }
722 
723 void *rom_add_blob(const char *name, const void *blob, size_t len,
724                    hwaddr addr, const char *fw_file_name,
725                    FWCfgReadCallback fw_callback, void *callback_opaque)
726 {
727     Rom *rom;
728     void *data = NULL;
729 
730     rom           = g_malloc0(sizeof(*rom));
731     rom->name     = g_strdup(name);
732     rom->addr     = addr;
733     rom->romsize  = len;
734     rom->datasize = len;
735     rom->data     = g_malloc0(rom->datasize);
736     memcpy(rom->data, blob, len);
737     rom_insert(rom);
738     if (fw_file_name && fw_cfg) {
739         char devpath[100];
740 
741         snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
742 
743         if (rom_file_has_mr) {
744             data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);
745         } else {
746             data = rom->data;
747         }
748 
749         fw_cfg_add_file_callback(fw_cfg, fw_file_name,
750                                  fw_callback, callback_opaque,
751                                  data, rom->romsize);
752     }
753     return data;
754 }
755 
756 /* This function is specific for elf program because we don't need to allocate
757  * all the rom. We just allocate the first part and the rest is just zeros. This
758  * is why romsize and datasize are different. Also, this function seize the
759  * memory ownership of "data", so we don't have to allocate and copy the buffer.
760  */
761 int rom_add_elf_program(const char *name, void *data, size_t datasize,
762                         size_t romsize, hwaddr addr)
763 {
764     Rom *rom;
765 
766     rom           = g_malloc0(sizeof(*rom));
767     rom->name     = g_strdup(name);
768     rom->addr     = addr;
769     rom->datasize = datasize;
770     rom->romsize  = romsize;
771     rom->data     = data;
772     rom_insert(rom);
773     return 0;
774 }
775 
776 int rom_add_vga(const char *file)
777 {
778     return rom_add_file(file, "vgaroms", 0, -1, true);
779 }
780 
781 int rom_add_option(const char *file, int32_t bootindex)
782 {
783     return rom_add_file(file, "genroms", 0, bootindex, true);
784 }
785 
786 static void rom_reset(void *unused)
787 {
788     Rom *rom;
789 
790     QTAILQ_FOREACH(rom, &roms, next) {
791         if (rom->fw_file) {
792             continue;
793         }
794         if (rom->data == NULL) {
795             continue;
796         }
797         if (rom->mr) {
798             void *host = memory_region_get_ram_ptr(rom->mr);
799             memcpy(host, rom->data, rom->datasize);
800         } else {
801             cpu_physical_memory_write_rom(&address_space_memory,
802                                           rom->addr, rom->data, rom->datasize);
803         }
804         if (rom->isrom) {
805             /* rom needs to be written only once */
806             g_free(rom->data);
807             rom->data = NULL;
808         }
809         /*
810          * The rom loader is really on the same level as firmware in the guest
811          * shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
812          * that the instruction cache for that new region is clear, so that the
813          * CPU definitely fetches its instructions from the just written data.
814          */
815         cpu_flush_icache_range(rom->addr, rom->datasize);
816     }
817 }
818 
819 int rom_load_all(void)
820 {
821     hwaddr addr = 0;
822     MemoryRegionSection section;
823     Rom *rom;
824 
825     QTAILQ_FOREACH(rom, &roms, next) {
826         if (rom->fw_file) {
827             continue;
828         }
829         if (addr > rom->addr) {
830             fprintf(stderr, "rom: requested regions overlap "
831                     "(rom %s. free=0x" TARGET_FMT_plx
832                     ", addr=0x" TARGET_FMT_plx ")\n",
833                     rom->name, addr, rom->addr);
834             return -1;
835         }
836         addr  = rom->addr;
837         addr += rom->romsize;
838         section = memory_region_find(get_system_memory(), rom->addr, 1);
839         rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
840         memory_region_unref(section.mr);
841     }
842     qemu_register_reset(rom_reset, NULL);
843     return 0;
844 }
845 
846 void rom_load_done(void)
847 {
848     roms_loaded = 1;
849 }
850 
851 void rom_set_fw(FWCfgState *f)
852 {
853     fw_cfg = f;
854 }
855 
856 static Rom *find_rom(hwaddr addr)
857 {
858     Rom *rom;
859 
860     QTAILQ_FOREACH(rom, &roms, next) {
861         if (rom->fw_file) {
862             continue;
863         }
864         if (rom->mr) {
865             continue;
866         }
867         if (rom->addr > addr) {
868             continue;
869         }
870         if (rom->addr + rom->romsize < addr) {
871             continue;
872         }
873         return rom;
874     }
875     return NULL;
876 }
877 
878 /*
879  * Copies memory from registered ROMs to dest. Any memory that is contained in
880  * a ROM between addr and addr + size is copied. Note that this can involve
881  * multiple ROMs, which need not start at addr and need not end at addr + size.
882  */
883 int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
884 {
885     hwaddr end = addr + size;
886     uint8_t *s, *d = dest;
887     size_t l = 0;
888     Rom *rom;
889 
890     QTAILQ_FOREACH(rom, &roms, next) {
891         if (rom->fw_file) {
892             continue;
893         }
894         if (rom->mr) {
895             continue;
896         }
897         if (rom->addr + rom->romsize < addr) {
898             continue;
899         }
900         if (rom->addr > end) {
901             break;
902         }
903 
904         d = dest + (rom->addr - addr);
905         s = rom->data;
906         l = rom->datasize;
907 
908         if ((d + l) > (dest + size)) {
909             l = dest - d;
910         }
911 
912         if (l > 0) {
913             memcpy(d, s, l);
914         }
915 
916         if (rom->romsize > rom->datasize) {
917             /* If datasize is less than romsize, it means that we didn't
918              * allocate all the ROM because the trailing data are only zeros.
919              */
920 
921             d += l;
922             l = rom->romsize - rom->datasize;
923 
924             if ((d + l) > (dest + size)) {
925                 /* Rom size doesn't fit in the destination area. Adjust to avoid
926                  * overflow.
927                  */
928                 l = dest - d;
929             }
930 
931             if (l > 0) {
932                 memset(d, 0x0, l);
933             }
934         }
935     }
936 
937     return (d + l) - dest;
938 }
939 
940 void *rom_ptr(hwaddr addr)
941 {
942     Rom *rom;
943 
944     rom = find_rom(addr);
945     if (!rom || !rom->data)
946         return NULL;
947     return rom->data + (addr - rom->addr);
948 }
949 
950 void do_info_roms(Monitor *mon, const QDict *qdict)
951 {
952     Rom *rom;
953 
954     QTAILQ_FOREACH(rom, &roms, next) {
955         if (rom->mr) {
956             monitor_printf(mon, "%s"
957                            " size=0x%06zx name=\"%s\"\n",
958                            rom->mr->name,
959                            rom->romsize,
960                            rom->name);
961         } else if (!rom->fw_file) {
962             monitor_printf(mon, "addr=" TARGET_FMT_plx
963                            " size=0x%06zx mem=%s name=\"%s\"\n",
964                            rom->addr, rom->romsize,
965                            rom->isrom ? "rom" : "ram",
966                            rom->name);
967         } else {
968             monitor_printf(mon, "fw=%s/%s"
969                            " size=0x%06zx name=\"%s\"\n",
970                            rom->fw_dir,
971                            rom->fw_file,
972                            rom->romsize,
973                            rom->name);
974         }
975     }
976 }
977