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