xref: /qemu/hw/core/loader.c (revision d072cdf3)
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 /* This simply prevents g_malloc in the function below from allocating
581  * a huge amount of memory, by placing a limit on the maximum
582  * uncompressed image size that load_image_gzipped will read.
583  */
584 #define LOAD_IMAGE_MAX_GUNZIP_BYTES (256 << 20)
585 
586 /* Load a gzip-compressed kernel. */
587 int load_image_gzipped(const char *filename, hwaddr addr, uint64_t max_sz)
588 {
589     uint8_t *compressed_data = NULL;
590     uint8_t *data = NULL;
591     gsize len;
592     ssize_t bytes;
593     int ret = -1;
594 
595     if (!g_file_get_contents(filename, (char **) &compressed_data, &len,
596                              NULL)) {
597         goto out;
598     }
599 
600     /* Is it a gzip-compressed file? */
601     if (len < 2 ||
602         compressed_data[0] != 0x1f ||
603         compressed_data[1] != 0x8b) {
604         goto out;
605     }
606 
607     if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) {
608         max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES;
609     }
610 
611     data = g_malloc(max_sz);
612     bytes = gunzip(data, max_sz, compressed_data, len);
613     if (bytes < 0) {
614         fprintf(stderr, "%s: unable to decompress gzipped kernel file\n",
615                 filename);
616         goto out;
617     }
618 
619     rom_add_blob_fixed(filename, data, bytes, addr);
620     ret = bytes;
621 
622  out:
623     g_free(compressed_data);
624     g_free(data);
625     return ret;
626 }
627 
628 /*
629  * Functions for reboot-persistent memory regions.
630  *  - used for vga bios and option roms.
631  *  - also linux kernel (-kernel / -initrd).
632  */
633 
634 typedef struct Rom Rom;
635 
636 struct Rom {
637     char *name;
638     char *path;
639 
640     /* datasize is the amount of memory allocated in "data". If datasize is less
641      * than romsize, it means that the area from datasize to romsize is filled
642      * with zeros.
643      */
644     size_t romsize;
645     size_t datasize;
646 
647     uint8_t *data;
648     MemoryRegion *mr;
649     int isrom;
650     char *fw_dir;
651     char *fw_file;
652 
653     hwaddr addr;
654     QTAILQ_ENTRY(Rom) next;
655 };
656 
657 static FWCfgState *fw_cfg;
658 static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms);
659 
660 static void rom_insert(Rom *rom)
661 {
662     Rom *item;
663 
664     if (roms_loaded) {
665         hw_error ("ROM images must be loaded at startup\n");
666     }
667 
668     /* list is ordered by load address */
669     QTAILQ_FOREACH(item, &roms, next) {
670         if (rom->addr >= item->addr)
671             continue;
672         QTAILQ_INSERT_BEFORE(item, rom, next);
673         return;
674     }
675     QTAILQ_INSERT_TAIL(&roms, rom, next);
676 }
677 
678 static void *rom_set_mr(Rom *rom, Object *owner, const char *name)
679 {
680     void *data;
681 
682     rom->mr = g_malloc(sizeof(*rom->mr));
683     memory_region_init_ram(rom->mr, owner, name, rom->datasize);
684     memory_region_set_readonly(rom->mr, true);
685     vmstate_register_ram_global(rom->mr);
686 
687     data = memory_region_get_ram_ptr(rom->mr);
688     memcpy(data, rom->data, rom->datasize);
689 
690     return data;
691 }
692 
693 int rom_add_file(const char *file, const char *fw_dir,
694                  hwaddr addr, int32_t bootindex,
695                  bool option_rom)
696 {
697     Rom *rom;
698     int rc, fd = -1;
699     char devpath[100];
700 
701     rom = g_malloc0(sizeof(*rom));
702     rom->name = g_strdup(file);
703     rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
704     if (rom->path == NULL) {
705         rom->path = g_strdup(file);
706     }
707 
708     fd = open(rom->path, O_RDONLY | O_BINARY);
709     if (fd == -1) {
710         fprintf(stderr, "Could not open option rom '%s': %s\n",
711                 rom->path, strerror(errno));
712         goto err;
713     }
714 
715     if (fw_dir) {
716         rom->fw_dir  = g_strdup(fw_dir);
717         rom->fw_file = g_strdup(file);
718     }
719     rom->addr     = addr;
720     rom->romsize  = lseek(fd, 0, SEEK_END);
721     rom->datasize = rom->romsize;
722     rom->data     = g_malloc0(rom->datasize);
723     lseek(fd, 0, SEEK_SET);
724     rc = read(fd, rom->data, rom->datasize);
725     if (rc != rom->datasize) {
726         fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
727                 rom->name, rc, rom->datasize);
728         goto err;
729     }
730     close(fd);
731     rom_insert(rom);
732     if (rom->fw_file && fw_cfg) {
733         const char *basename;
734         char fw_file_name[FW_CFG_MAX_FILE_PATH];
735         void *data;
736 
737         basename = strrchr(rom->fw_file, '/');
738         if (basename) {
739             basename++;
740         } else {
741             basename = rom->fw_file;
742         }
743         snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
744                  basename);
745         snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
746 
747         if ((!option_rom || option_rom_has_mr) && rom_file_has_mr) {
748             data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);
749         } else {
750             data = rom->data;
751         }
752 
753         fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
754     } else {
755         snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);
756     }
757 
758     add_boot_device_path(bootindex, NULL, devpath);
759     return 0;
760 
761 err:
762     if (fd != -1)
763         close(fd);
764     g_free(rom->data);
765     g_free(rom->path);
766     g_free(rom->name);
767     g_free(rom);
768     return -1;
769 }
770 
771 void *rom_add_blob(const char *name, const void *blob, size_t len,
772                    hwaddr addr, const char *fw_file_name,
773                    FWCfgReadCallback fw_callback, void *callback_opaque)
774 {
775     Rom *rom;
776     void *data = NULL;
777 
778     rom           = g_malloc0(sizeof(*rom));
779     rom->name     = g_strdup(name);
780     rom->addr     = addr;
781     rom->romsize  = len;
782     rom->datasize = len;
783     rom->data     = g_malloc0(rom->datasize);
784     memcpy(rom->data, blob, len);
785     rom_insert(rom);
786     if (fw_file_name && fw_cfg) {
787         char devpath[100];
788 
789         snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
790 
791         if (rom_file_has_mr) {
792             data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);
793         } else {
794             data = rom->data;
795         }
796 
797         fw_cfg_add_file_callback(fw_cfg, fw_file_name,
798                                  fw_callback, callback_opaque,
799                                  data, rom->romsize);
800     }
801     return data;
802 }
803 
804 /* This function is specific for elf program because we don't need to allocate
805  * all the rom. We just allocate the first part and the rest is just zeros. This
806  * is why romsize and datasize are different. Also, this function seize the
807  * memory ownership of "data", so we don't have to allocate and copy the buffer.
808  */
809 int rom_add_elf_program(const char *name, void *data, size_t datasize,
810                         size_t romsize, hwaddr addr)
811 {
812     Rom *rom;
813 
814     rom           = g_malloc0(sizeof(*rom));
815     rom->name     = g_strdup(name);
816     rom->addr     = addr;
817     rom->datasize = datasize;
818     rom->romsize  = romsize;
819     rom->data     = data;
820     rom_insert(rom);
821     return 0;
822 }
823 
824 int rom_add_vga(const char *file)
825 {
826     return rom_add_file(file, "vgaroms", 0, -1, true);
827 }
828 
829 int rom_add_option(const char *file, int32_t bootindex)
830 {
831     return rom_add_file(file, "genroms", 0, bootindex, true);
832 }
833 
834 static void rom_reset(void *unused)
835 {
836     Rom *rom;
837 
838     QTAILQ_FOREACH(rom, &roms, next) {
839         if (rom->fw_file) {
840             continue;
841         }
842         if (rom->data == NULL) {
843             continue;
844         }
845         if (rom->mr) {
846             void *host = memory_region_get_ram_ptr(rom->mr);
847             memcpy(host, rom->data, rom->datasize);
848         } else {
849             cpu_physical_memory_write_rom(&address_space_memory,
850                                           rom->addr, rom->data, rom->datasize);
851         }
852         if (rom->isrom) {
853             /* rom needs to be written only once */
854             g_free(rom->data);
855             rom->data = NULL;
856         }
857         /*
858          * The rom loader is really on the same level as firmware in the guest
859          * shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
860          * that the instruction cache for that new region is clear, so that the
861          * CPU definitely fetches its instructions from the just written data.
862          */
863         cpu_flush_icache_range(rom->addr, rom->datasize);
864     }
865 }
866 
867 int rom_load_all(void)
868 {
869     hwaddr addr = 0;
870     MemoryRegionSection section;
871     Rom *rom;
872 
873     QTAILQ_FOREACH(rom, &roms, next) {
874         if (rom->fw_file) {
875             continue;
876         }
877         if (addr > rom->addr) {
878             fprintf(stderr, "rom: requested regions overlap "
879                     "(rom %s. free=0x" TARGET_FMT_plx
880                     ", addr=0x" TARGET_FMT_plx ")\n",
881                     rom->name, addr, rom->addr);
882             return -1;
883         }
884         addr  = rom->addr;
885         addr += rom->romsize;
886         section = memory_region_find(get_system_memory(), rom->addr, 1);
887         rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
888         memory_region_unref(section.mr);
889     }
890     qemu_register_reset(rom_reset, NULL);
891     return 0;
892 }
893 
894 void rom_load_done(void)
895 {
896     roms_loaded = 1;
897 }
898 
899 void rom_set_fw(FWCfgState *f)
900 {
901     fw_cfg = f;
902 }
903 
904 static Rom *find_rom(hwaddr addr)
905 {
906     Rom *rom;
907 
908     QTAILQ_FOREACH(rom, &roms, next) {
909         if (rom->fw_file) {
910             continue;
911         }
912         if (rom->mr) {
913             continue;
914         }
915         if (rom->addr > addr) {
916             continue;
917         }
918         if (rom->addr + rom->romsize < addr) {
919             continue;
920         }
921         return rom;
922     }
923     return NULL;
924 }
925 
926 /*
927  * Copies memory from registered ROMs to dest. Any memory that is contained in
928  * a ROM between addr and addr + size is copied. Note that this can involve
929  * multiple ROMs, which need not start at addr and need not end at addr + size.
930  */
931 int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
932 {
933     hwaddr end = addr + size;
934     uint8_t *s, *d = dest;
935     size_t l = 0;
936     Rom *rom;
937 
938     QTAILQ_FOREACH(rom, &roms, next) {
939         if (rom->fw_file) {
940             continue;
941         }
942         if (rom->mr) {
943             continue;
944         }
945         if (rom->addr + rom->romsize < addr) {
946             continue;
947         }
948         if (rom->addr > end) {
949             break;
950         }
951 
952         d = dest + (rom->addr - addr);
953         s = rom->data;
954         l = rom->datasize;
955 
956         if ((d + l) > (dest + size)) {
957             l = dest - d;
958         }
959 
960         if (l > 0) {
961             memcpy(d, s, l);
962         }
963 
964         if (rom->romsize > rom->datasize) {
965             /* If datasize is less than romsize, it means that we didn't
966              * allocate all the ROM because the trailing data are only zeros.
967              */
968 
969             d += l;
970             l = rom->romsize - rom->datasize;
971 
972             if ((d + l) > (dest + size)) {
973                 /* Rom size doesn't fit in the destination area. Adjust to avoid
974                  * overflow.
975                  */
976                 l = dest - d;
977             }
978 
979             if (l > 0) {
980                 memset(d, 0x0, l);
981             }
982         }
983     }
984 
985     return (d + l) - dest;
986 }
987 
988 void *rom_ptr(hwaddr addr)
989 {
990     Rom *rom;
991 
992     rom = find_rom(addr);
993     if (!rom || !rom->data)
994         return NULL;
995     return rom->data + (addr - rom->addr);
996 }
997 
998 void do_info_roms(Monitor *mon, const QDict *qdict)
999 {
1000     Rom *rom;
1001 
1002     QTAILQ_FOREACH(rom, &roms, next) {
1003         if (rom->mr) {
1004             monitor_printf(mon, "%s"
1005                            " size=0x%06zx name=\"%s\"\n",
1006                            memory_region_name(rom->mr),
1007                            rom->romsize,
1008                            rom->name);
1009         } else if (!rom->fw_file) {
1010             monitor_printf(mon, "addr=" TARGET_FMT_plx
1011                            " size=0x%06zx mem=%s name=\"%s\"\n",
1012                            rom->addr, rom->romsize,
1013                            rom->isrom ? "rom" : "ram",
1014                            rom->name);
1015         } else {
1016             monitor_printf(mon, "fw=%s/%s"
1017                            " size=0x%06zx name=\"%s\"\n",
1018                            rom->fw_dir,
1019                            rom->fw_file,
1020                            rom->romsize,
1021                            rom->name);
1022         }
1023     }
1024 }
1025