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