xref: /qemu/hw/core/loader.c (revision c5955f4f)
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 "qemu/osdep.h"
46 #include "qemu/datadir.h"
47 #include "qapi/error.h"
48 #include "qapi/qapi-commands-machine.h"
49 #include "qapi/type-helpers.h"
50 #include "trace.h"
51 #include "hw/hw.h"
52 #include "disas/disas.h"
53 #include "migration/vmstate.h"
54 #include "monitor/monitor.h"
55 #include "sysemu/reset.h"
56 #include "sysemu/sysemu.h"
57 #include "uboot_image.h"
58 #include "hw/loader.h"
59 #include "hw/nvram/fw_cfg.h"
60 #include "exec/memory.h"
61 #include "hw/boards.h"
62 #include "qemu/cutils.h"
63 #include "sysemu/runstate.h"
64 
65 #include <zlib.h>
66 
67 static int roms_loaded;
68 
69 /* return the size or -1 if error */
70 int64_t get_image_size(const char *filename)
71 {
72     int fd;
73     int64_t size;
74     fd = open(filename, O_RDONLY | O_BINARY);
75     if (fd < 0)
76         return -1;
77     size = lseek(fd, 0, SEEK_END);
78     close(fd);
79     return size;
80 }
81 
82 /* return the size or -1 if error */
83 ssize_t load_image_size(const char *filename, void *addr, size_t size)
84 {
85     int fd;
86     ssize_t actsize, l = 0;
87 
88     fd = open(filename, O_RDONLY | O_BINARY);
89     if (fd < 0) {
90         return -1;
91     }
92 
93     while ((actsize = read(fd, addr + l, size - l)) > 0) {
94         l += actsize;
95     }
96 
97     close(fd);
98 
99     return actsize < 0 ? -1 : l;
100 }
101 
102 /* read()-like version */
103 ssize_t read_targphys(const char *name,
104                       int fd, hwaddr dst_addr, size_t nbytes)
105 {
106     uint8_t *buf;
107     ssize_t did;
108 
109     buf = g_malloc(nbytes);
110     did = read(fd, buf, nbytes);
111     if (did > 0)
112         rom_add_blob_fixed("read", buf, did, dst_addr);
113     g_free(buf);
114     return did;
115 }
116 
117 int load_image_targphys(const char *filename,
118                         hwaddr addr, uint64_t max_sz)
119 {
120     return load_image_targphys_as(filename, addr, max_sz, NULL);
121 }
122 
123 /* return the size or -1 if error */
124 int load_image_targphys_as(const char *filename,
125                            hwaddr addr, uint64_t max_sz, AddressSpace *as)
126 {
127     int size;
128 
129     size = get_image_size(filename);
130     if (size < 0 || size > max_sz) {
131         return -1;
132     }
133     if (size > 0) {
134         if (rom_add_file_fixed_as(filename, addr, -1, as) < 0) {
135             return -1;
136         }
137     }
138     return size;
139 }
140 
141 int load_image_mr(const char *filename, MemoryRegion *mr)
142 {
143     int size;
144 
145     if (!memory_access_is_direct(mr, false)) {
146         /* Can only load an image into RAM or ROM */
147         return -1;
148     }
149 
150     size = get_image_size(filename);
151 
152     if (size < 0 || size > memory_region_size(mr)) {
153         return -1;
154     }
155     if (size > 0) {
156         if (rom_add_file_mr(filename, mr, -1) < 0) {
157             return -1;
158         }
159     }
160     return size;
161 }
162 
163 void pstrcpy_targphys(const char *name, hwaddr dest, int buf_size,
164                       const char *source)
165 {
166     const char *nulp;
167     char *ptr;
168 
169     if (buf_size <= 0) return;
170     nulp = memchr(source, 0, buf_size);
171     if (nulp) {
172         rom_add_blob_fixed(name, source, (nulp - source) + 1, dest);
173     } else {
174         rom_add_blob_fixed(name, source, buf_size, dest);
175         ptr = rom_ptr(dest + buf_size - 1, sizeof(*ptr));
176         *ptr = 0;
177     }
178 }
179 
180 /* A.OUT loader */
181 
182 struct exec
183 {
184   uint32_t a_info;   /* Use macros N_MAGIC, etc for access */
185   uint32_t a_text;   /* length of text, in bytes */
186   uint32_t a_data;   /* length of data, in bytes */
187   uint32_t a_bss;    /* length of uninitialized data area, in bytes */
188   uint32_t a_syms;   /* length of symbol table data in file, in bytes */
189   uint32_t a_entry;  /* start address */
190   uint32_t a_trsize; /* length of relocation info for text, in bytes */
191   uint32_t a_drsize; /* length of relocation info for data, in bytes */
192 };
193 
194 static void bswap_ahdr(struct exec *e)
195 {
196     bswap32s(&e->a_info);
197     bswap32s(&e->a_text);
198     bswap32s(&e->a_data);
199     bswap32s(&e->a_bss);
200     bswap32s(&e->a_syms);
201     bswap32s(&e->a_entry);
202     bswap32s(&e->a_trsize);
203     bswap32s(&e->a_drsize);
204 }
205 
206 #define N_MAGIC(exec) ((exec).a_info & 0xffff)
207 #define OMAGIC 0407
208 #define NMAGIC 0410
209 #define ZMAGIC 0413
210 #define QMAGIC 0314
211 #define _N_HDROFF(x) (1024 - sizeof (struct exec))
212 #define N_TXTOFF(x)							\
213     (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) :	\
214      (N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
215 #define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
216 #define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
217 
218 #define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
219 
220 #define N_DATADDR(x, target_page_size) \
221     (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
222      : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
223 
224 
225 int load_aout(const char *filename, hwaddr addr, int max_sz,
226               int bswap_needed, hwaddr target_page_size)
227 {
228     int fd;
229     ssize_t size, ret;
230     struct exec e;
231     uint32_t magic;
232 
233     fd = open(filename, O_RDONLY | O_BINARY);
234     if (fd < 0)
235         return -1;
236 
237     size = read(fd, &e, sizeof(e));
238     if (size < 0)
239         goto fail;
240 
241     if (bswap_needed) {
242         bswap_ahdr(&e);
243     }
244 
245     magic = N_MAGIC(e);
246     switch (magic) {
247     case ZMAGIC:
248     case QMAGIC:
249     case OMAGIC:
250         if (e.a_text + e.a_data > max_sz)
251             goto fail;
252         lseek(fd, N_TXTOFF(e), SEEK_SET);
253         size = read_targphys(filename, fd, addr, e.a_text + e.a_data);
254         if (size < 0)
255             goto fail;
256         break;
257     case NMAGIC:
258         if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)
259             goto fail;
260         lseek(fd, N_TXTOFF(e), SEEK_SET);
261         size = read_targphys(filename, fd, addr, e.a_text);
262         if (size < 0)
263             goto fail;
264         ret = read_targphys(filename, fd, addr + N_DATADDR(e, target_page_size),
265                             e.a_data);
266         if (ret < 0)
267             goto fail;
268         size += ret;
269         break;
270     default:
271         goto fail;
272     }
273     close(fd);
274     return size;
275  fail:
276     close(fd);
277     return -1;
278 }
279 
280 /* ELF loader */
281 
282 static void *load_at(int fd, off_t offset, size_t size)
283 {
284     void *ptr;
285     if (lseek(fd, offset, SEEK_SET) < 0)
286         return NULL;
287     ptr = g_malloc(size);
288     if (read(fd, ptr, size) != size) {
289         g_free(ptr);
290         return NULL;
291     }
292     return ptr;
293 }
294 
295 #ifdef ELF_CLASS
296 #undef ELF_CLASS
297 #endif
298 
299 #define ELF_CLASS   ELFCLASS32
300 #include "elf.h"
301 
302 #define SZ		32
303 #define elf_word        uint32_t
304 #define elf_sword        int32_t
305 #define bswapSZs	bswap32s
306 #include "hw/elf_ops.h"
307 
308 #undef elfhdr
309 #undef elf_phdr
310 #undef elf_shdr
311 #undef elf_sym
312 #undef elf_rela
313 #undef elf_note
314 #undef elf_word
315 #undef elf_sword
316 #undef bswapSZs
317 #undef SZ
318 #define elfhdr		elf64_hdr
319 #define elf_phdr	elf64_phdr
320 #define elf_note	elf64_note
321 #define elf_shdr	elf64_shdr
322 #define elf_sym		elf64_sym
323 #define elf_rela        elf64_rela
324 #define elf_word        uint64_t
325 #define elf_sword        int64_t
326 #define bswapSZs	bswap64s
327 #define SZ		64
328 #include "hw/elf_ops.h"
329 
330 const char *load_elf_strerror(ssize_t error)
331 {
332     switch (error) {
333     case 0:
334         return "No error";
335     case ELF_LOAD_FAILED:
336         return "Failed to load ELF";
337     case ELF_LOAD_NOT_ELF:
338         return "The image is not ELF";
339     case ELF_LOAD_WRONG_ARCH:
340         return "The image is from incompatible architecture";
341     case ELF_LOAD_WRONG_ENDIAN:
342         return "The image has incorrect endianness";
343     case ELF_LOAD_TOO_BIG:
344         return "The image segments are too big to load";
345     default:
346         return "Unknown error";
347     }
348 }
349 
350 void load_elf_hdr(const char *filename, void *hdr, bool *is64, Error **errp)
351 {
352     int fd;
353     uint8_t e_ident_local[EI_NIDENT];
354     uint8_t *e_ident;
355     size_t hdr_size, off;
356     bool is64l;
357 
358     if (!hdr) {
359         hdr = e_ident_local;
360     }
361     e_ident = hdr;
362 
363     fd = open(filename, O_RDONLY | O_BINARY);
364     if (fd < 0) {
365         error_setg_errno(errp, errno, "Failed to open file: %s", filename);
366         return;
367     }
368     if (read(fd, hdr, EI_NIDENT) != EI_NIDENT) {
369         error_setg_errno(errp, errno, "Failed to read file: %s", filename);
370         goto fail;
371     }
372     if (e_ident[0] != ELFMAG0 ||
373         e_ident[1] != ELFMAG1 ||
374         e_ident[2] != ELFMAG2 ||
375         e_ident[3] != ELFMAG3) {
376         error_setg(errp, "Bad ELF magic");
377         goto fail;
378     }
379 
380     is64l = e_ident[EI_CLASS] == ELFCLASS64;
381     hdr_size = is64l ? sizeof(Elf64_Ehdr) : sizeof(Elf32_Ehdr);
382     if (is64) {
383         *is64 = is64l;
384     }
385 
386     off = EI_NIDENT;
387     while (hdr != e_ident_local && off < hdr_size) {
388         size_t br = read(fd, hdr + off, hdr_size - off);
389         switch (br) {
390         case 0:
391             error_setg(errp, "File too short: %s", filename);
392             goto fail;
393         case -1:
394             error_setg_errno(errp, errno, "Failed to read file: %s",
395                              filename);
396             goto fail;
397         }
398         off += br;
399     }
400 
401 fail:
402     close(fd);
403 }
404 
405 /* return < 0 if error, otherwise the number of bytes loaded in memory */
406 ssize_t load_elf(const char *filename,
407                  uint64_t (*elf_note_fn)(void *, void *, bool),
408                  uint64_t (*translate_fn)(void *, uint64_t),
409                  void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
410                  uint64_t *highaddr, uint32_t *pflags, int big_endian,
411                  int elf_machine, int clear_lsb, int data_swab)
412 {
413     return load_elf_as(filename, elf_note_fn, translate_fn, translate_opaque,
414                        pentry, lowaddr, highaddr, pflags, big_endian,
415                        elf_machine, clear_lsb, data_swab, NULL);
416 }
417 
418 /* return < 0 if error, otherwise the number of bytes loaded in memory */
419 ssize_t load_elf_as(const char *filename,
420                     uint64_t (*elf_note_fn)(void *, void *, bool),
421                     uint64_t (*translate_fn)(void *, uint64_t),
422                     void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr,
423                     uint64_t *highaddr, uint32_t *pflags, int big_endian,
424                     int elf_machine, int clear_lsb, int data_swab,
425                     AddressSpace *as)
426 {
427     return load_elf_ram(filename, elf_note_fn, translate_fn, translate_opaque,
428                         pentry, lowaddr, highaddr, pflags, big_endian,
429                         elf_machine, clear_lsb, data_swab, as, true);
430 }
431 
432 /* return < 0 if error, otherwise the number of bytes loaded in memory */
433 ssize_t load_elf_ram(const char *filename,
434                      uint64_t (*elf_note_fn)(void *, void *, bool),
435                      uint64_t (*translate_fn)(void *, uint64_t),
436                      void *translate_opaque, uint64_t *pentry,
437                      uint64_t *lowaddr, uint64_t *highaddr, uint32_t *pflags,
438                      int big_endian, int elf_machine, int clear_lsb,
439                      int data_swab, AddressSpace *as, bool load_rom)
440 {
441     return load_elf_ram_sym(filename, elf_note_fn,
442                             translate_fn, translate_opaque,
443                             pentry, lowaddr, highaddr, pflags, big_endian,
444                             elf_machine, clear_lsb, data_swab, as,
445                             load_rom, NULL);
446 }
447 
448 /* return < 0 if error, otherwise the number of bytes loaded in memory */
449 ssize_t load_elf_ram_sym(const char *filename,
450                          uint64_t (*elf_note_fn)(void *, void *, bool),
451                          uint64_t (*translate_fn)(void *, uint64_t),
452                          void *translate_opaque, uint64_t *pentry,
453                          uint64_t *lowaddr, uint64_t *highaddr,
454                          uint32_t *pflags, int big_endian, int elf_machine,
455                          int clear_lsb, int data_swab,
456                          AddressSpace *as, bool load_rom, symbol_fn_t sym_cb)
457 {
458     int fd, data_order, target_data_order, must_swab;
459     ssize_t ret = ELF_LOAD_FAILED;
460     uint8_t e_ident[EI_NIDENT];
461 
462     fd = open(filename, O_RDONLY | O_BINARY);
463     if (fd < 0) {
464         perror(filename);
465         return -1;
466     }
467     if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident))
468         goto fail;
469     if (e_ident[0] != ELFMAG0 ||
470         e_ident[1] != ELFMAG1 ||
471         e_ident[2] != ELFMAG2 ||
472         e_ident[3] != ELFMAG3) {
473         ret = ELF_LOAD_NOT_ELF;
474         goto fail;
475     }
476 #if HOST_BIG_ENDIAN
477     data_order = ELFDATA2MSB;
478 #else
479     data_order = ELFDATA2LSB;
480 #endif
481     must_swab = data_order != e_ident[EI_DATA];
482     if (big_endian) {
483         target_data_order = ELFDATA2MSB;
484     } else {
485         target_data_order = ELFDATA2LSB;
486     }
487 
488     if (target_data_order != e_ident[EI_DATA]) {
489         ret = ELF_LOAD_WRONG_ENDIAN;
490         goto fail;
491     }
492 
493     lseek(fd, 0, SEEK_SET);
494     if (e_ident[EI_CLASS] == ELFCLASS64) {
495         ret = load_elf64(filename, fd, elf_note_fn,
496                          translate_fn, translate_opaque, must_swab,
497                          pentry, lowaddr, highaddr, pflags, elf_machine,
498                          clear_lsb, data_swab, as, load_rom, sym_cb);
499     } else {
500         ret = load_elf32(filename, fd, elf_note_fn,
501                          translate_fn, translate_opaque, must_swab,
502                          pentry, lowaddr, highaddr, pflags, elf_machine,
503                          clear_lsb, data_swab, as, load_rom, sym_cb);
504     }
505 
506  fail:
507     close(fd);
508     return ret;
509 }
510 
511 static void bswap_uboot_header(uboot_image_header_t *hdr)
512 {
513 #if !HOST_BIG_ENDIAN
514     bswap32s(&hdr->ih_magic);
515     bswap32s(&hdr->ih_hcrc);
516     bswap32s(&hdr->ih_time);
517     bswap32s(&hdr->ih_size);
518     bswap32s(&hdr->ih_load);
519     bswap32s(&hdr->ih_ep);
520     bswap32s(&hdr->ih_dcrc);
521 #endif
522 }
523 
524 
525 #define ZALLOC_ALIGNMENT	16
526 
527 static void *zalloc(void *x, unsigned items, unsigned size)
528 {
529     void *p;
530 
531     size *= items;
532     size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
533 
534     p = g_malloc(size);
535 
536     return (p);
537 }
538 
539 static void zfree(void *x, void *addr)
540 {
541     g_free(addr);
542 }
543 
544 
545 #define HEAD_CRC	2
546 #define EXTRA_FIELD	4
547 #define ORIG_NAME	8
548 #define COMMENT		0x10
549 #define RESERVED	0xe0
550 
551 #define DEFLATED	8
552 
553 ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src, size_t srclen)
554 {
555     z_stream s;
556     ssize_t dstbytes;
557     int r, i, flags;
558 
559     /* skip header */
560     i = 10;
561     if (srclen < 4) {
562         goto toosmall;
563     }
564     flags = src[3];
565     if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
566         puts ("Error: Bad gzipped data\n");
567         return -1;
568     }
569     if ((flags & EXTRA_FIELD) != 0) {
570         if (srclen < 12) {
571             goto toosmall;
572         }
573         i = 12 + src[10] + (src[11] << 8);
574     }
575     if ((flags & ORIG_NAME) != 0) {
576         while (i < srclen && src[i++] != 0) {
577             /* do nothing */
578         }
579     }
580     if ((flags & COMMENT) != 0) {
581         while (i < srclen && src[i++] != 0) {
582             /* do nothing */
583         }
584     }
585     if ((flags & HEAD_CRC) != 0) {
586         i += 2;
587     }
588     if (i >= srclen) {
589         goto toosmall;
590     }
591 
592     s.zalloc = zalloc;
593     s.zfree = zfree;
594 
595     r = inflateInit2(&s, -MAX_WBITS);
596     if (r != Z_OK) {
597         printf ("Error: inflateInit2() returned %d\n", r);
598         return (-1);
599     }
600     s.next_in = src + i;
601     s.avail_in = srclen - i;
602     s.next_out = dst;
603     s.avail_out = dstlen;
604     r = inflate(&s, Z_FINISH);
605     if (r != Z_OK && r != Z_STREAM_END) {
606         printf ("Error: inflate() returned %d\n", r);
607         return -1;
608     }
609     dstbytes = s.next_out - (unsigned char *) dst;
610     inflateEnd(&s);
611 
612     return dstbytes;
613 
614 toosmall:
615     puts("Error: gunzip out of data in header\n");
616     return -1;
617 }
618 
619 /* Load a U-Boot image.  */
620 static int load_uboot_image(const char *filename, hwaddr *ep, hwaddr *loadaddr,
621                             int *is_linux, uint8_t image_type,
622                             uint64_t (*translate_fn)(void *, uint64_t),
623                             void *translate_opaque, AddressSpace *as)
624 {
625     int fd;
626     int size;
627     hwaddr address;
628     uboot_image_header_t h;
629     uboot_image_header_t *hdr = &h;
630     uint8_t *data = NULL;
631     int ret = -1;
632     int do_uncompress = 0;
633 
634     fd = open(filename, O_RDONLY | O_BINARY);
635     if (fd < 0)
636         return -1;
637 
638     size = read(fd, hdr, sizeof(uboot_image_header_t));
639     if (size < sizeof(uboot_image_header_t)) {
640         goto out;
641     }
642 
643     bswap_uboot_header(hdr);
644 
645     if (hdr->ih_magic != IH_MAGIC)
646         goto out;
647 
648     if (hdr->ih_type != image_type) {
649         if (!(image_type == IH_TYPE_KERNEL &&
650             hdr->ih_type == IH_TYPE_KERNEL_NOLOAD)) {
651             fprintf(stderr, "Wrong image type %d, expected %d\n", hdr->ih_type,
652                     image_type);
653             goto out;
654         }
655     }
656 
657     /* TODO: Implement other image types.  */
658     switch (hdr->ih_type) {
659     case IH_TYPE_KERNEL_NOLOAD:
660         if (!loadaddr || *loadaddr == LOAD_UIMAGE_LOADADDR_INVALID) {
661             fprintf(stderr, "this image format (kernel_noload) cannot be "
662                     "loaded on this machine type");
663             goto out;
664         }
665 
666         hdr->ih_load = *loadaddr + sizeof(*hdr);
667         hdr->ih_ep += hdr->ih_load;
668         /* fall through */
669     case IH_TYPE_KERNEL:
670         address = hdr->ih_load;
671         if (translate_fn) {
672             address = translate_fn(translate_opaque, address);
673         }
674         if (loadaddr) {
675             *loadaddr = hdr->ih_load;
676         }
677 
678         switch (hdr->ih_comp) {
679         case IH_COMP_NONE:
680             break;
681         case IH_COMP_GZIP:
682             do_uncompress = 1;
683             break;
684         default:
685             fprintf(stderr,
686                     "Unable to load u-boot images with compression type %d\n",
687                     hdr->ih_comp);
688             goto out;
689         }
690 
691         if (ep) {
692             *ep = hdr->ih_ep;
693         }
694 
695         /* TODO: Check CPU type.  */
696         if (is_linux) {
697             if (hdr->ih_os == IH_OS_LINUX) {
698                 *is_linux = 1;
699             } else {
700                 *is_linux = 0;
701             }
702         }
703 
704         break;
705     case IH_TYPE_RAMDISK:
706         address = *loadaddr;
707         break;
708     default:
709         fprintf(stderr, "Unsupported u-boot image type %d\n", hdr->ih_type);
710         goto out;
711     }
712 
713     data = g_malloc(hdr->ih_size);
714 
715     if (read(fd, data, hdr->ih_size) != hdr->ih_size) {
716         fprintf(stderr, "Error reading file\n");
717         goto out;
718     }
719 
720     if (do_uncompress) {
721         uint8_t *compressed_data;
722         size_t max_bytes;
723         ssize_t bytes;
724 
725         compressed_data = data;
726         max_bytes = UBOOT_MAX_GUNZIP_BYTES;
727         data = g_malloc(max_bytes);
728 
729         bytes = gunzip(data, max_bytes, compressed_data, hdr->ih_size);
730         g_free(compressed_data);
731         if (bytes < 0) {
732             fprintf(stderr, "Unable to decompress gzipped image!\n");
733             goto out;
734         }
735         hdr->ih_size = bytes;
736     }
737 
738     rom_add_blob_fixed_as(filename, data, hdr->ih_size, address, as);
739 
740     ret = hdr->ih_size;
741 
742 out:
743     g_free(data);
744     close(fd);
745     return ret;
746 }
747 
748 int load_uimage(const char *filename, hwaddr *ep, hwaddr *loadaddr,
749                 int *is_linux,
750                 uint64_t (*translate_fn)(void *, uint64_t),
751                 void *translate_opaque)
752 {
753     return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
754                             translate_fn, translate_opaque, NULL);
755 }
756 
757 int load_uimage_as(const char *filename, hwaddr *ep, hwaddr *loadaddr,
758                    int *is_linux,
759                    uint64_t (*translate_fn)(void *, uint64_t),
760                    void *translate_opaque, AddressSpace *as)
761 {
762     return load_uboot_image(filename, ep, loadaddr, is_linux, IH_TYPE_KERNEL,
763                             translate_fn, translate_opaque, as);
764 }
765 
766 /* Load a ramdisk.  */
767 int load_ramdisk(const char *filename, hwaddr addr, uint64_t max_sz)
768 {
769     return load_ramdisk_as(filename, addr, max_sz, NULL);
770 }
771 
772 int load_ramdisk_as(const char *filename, hwaddr addr, uint64_t max_sz,
773                     AddressSpace *as)
774 {
775     return load_uboot_image(filename, NULL, &addr, NULL, IH_TYPE_RAMDISK,
776                             NULL, NULL, as);
777 }
778 
779 /* Load a gzip-compressed kernel to a dynamically allocated buffer. */
780 int load_image_gzipped_buffer(const char *filename, uint64_t max_sz,
781                               uint8_t **buffer)
782 {
783     uint8_t *compressed_data = NULL;
784     uint8_t *data = NULL;
785     gsize len;
786     ssize_t bytes;
787     int ret = -1;
788 
789     if (!g_file_get_contents(filename, (char **) &compressed_data, &len,
790                              NULL)) {
791         goto out;
792     }
793 
794     /* Is it a gzip-compressed file? */
795     if (len < 2 ||
796         compressed_data[0] != 0x1f ||
797         compressed_data[1] != 0x8b) {
798         goto out;
799     }
800 
801     if (max_sz > LOAD_IMAGE_MAX_GUNZIP_BYTES) {
802         max_sz = LOAD_IMAGE_MAX_GUNZIP_BYTES;
803     }
804 
805     data = g_malloc(max_sz);
806     bytes = gunzip(data, max_sz, compressed_data, len);
807     if (bytes < 0) {
808         fprintf(stderr, "%s: unable to decompress gzipped kernel file\n",
809                 filename);
810         goto out;
811     }
812 
813     /* trim to actual size and return to caller */
814     *buffer = g_realloc(data, bytes);
815     ret = bytes;
816     /* ownership has been transferred to caller */
817     data = NULL;
818 
819  out:
820     g_free(compressed_data);
821     g_free(data);
822     return ret;
823 }
824 
825 /* Load a gzip-compressed kernel. */
826 int load_image_gzipped(const char *filename, hwaddr addr, uint64_t max_sz)
827 {
828     int bytes;
829     uint8_t *data;
830 
831     bytes = load_image_gzipped_buffer(filename, max_sz, &data);
832     if (bytes != -1) {
833         rom_add_blob_fixed(filename, data, bytes, addr);
834         g_free(data);
835     }
836     return bytes;
837 }
838 
839 /*
840  * Functions for reboot-persistent memory regions.
841  *  - used for vga bios and option roms.
842  *  - also linux kernel (-kernel / -initrd).
843  */
844 
845 typedef struct Rom Rom;
846 
847 struct Rom {
848     char *name;
849     char *path;
850 
851     /* datasize is the amount of memory allocated in "data". If datasize is less
852      * than romsize, it means that the area from datasize to romsize is filled
853      * with zeros.
854      */
855     size_t romsize;
856     size_t datasize;
857 
858     uint8_t *data;
859     MemoryRegion *mr;
860     AddressSpace *as;
861     int isrom;
862     char *fw_dir;
863     char *fw_file;
864     GMappedFile *mapped_file;
865 
866     bool committed;
867 
868     hwaddr addr;
869     QTAILQ_ENTRY(Rom) next;
870 };
871 
872 static FWCfgState *fw_cfg;
873 static QTAILQ_HEAD(, Rom) roms = QTAILQ_HEAD_INITIALIZER(roms);
874 
875 /*
876  * rom->data can be heap-allocated or memory-mapped (e.g. when added with
877  * rom_add_elf_program())
878  */
879 static void rom_free_data(Rom *rom)
880 {
881     if (rom->mapped_file) {
882         g_mapped_file_unref(rom->mapped_file);
883         rom->mapped_file = NULL;
884     } else {
885         g_free(rom->data);
886     }
887 
888     rom->data = NULL;
889 }
890 
891 static void rom_free(Rom *rom)
892 {
893     rom_free_data(rom);
894     g_free(rom->path);
895     g_free(rom->name);
896     g_free(rom->fw_dir);
897     g_free(rom->fw_file);
898     g_free(rom);
899 }
900 
901 static inline bool rom_order_compare(Rom *rom, Rom *item)
902 {
903     return ((uintptr_t)(void *)rom->as > (uintptr_t)(void *)item->as) ||
904            (rom->as == item->as && rom->addr >= item->addr);
905 }
906 
907 static void rom_insert(Rom *rom)
908 {
909     Rom *item;
910 
911     if (roms_loaded) {
912         hw_error ("ROM images must be loaded at startup\n");
913     }
914 
915     /* The user didn't specify an address space, this is the default */
916     if (!rom->as) {
917         rom->as = &address_space_memory;
918     }
919 
920     rom->committed = false;
921 
922     /* List is ordered by load address in the same address space */
923     QTAILQ_FOREACH(item, &roms, next) {
924         if (rom_order_compare(rom, item)) {
925             continue;
926         }
927         QTAILQ_INSERT_BEFORE(item, rom, next);
928         return;
929     }
930     QTAILQ_INSERT_TAIL(&roms, rom, next);
931 }
932 
933 static void fw_cfg_resized(const char *id, uint64_t length, void *host)
934 {
935     if (fw_cfg) {
936         fw_cfg_modify_file(fw_cfg, id + strlen("/rom@"), host, length);
937     }
938 }
939 
940 static void *rom_set_mr(Rom *rom, Object *owner, const char *name, bool ro)
941 {
942     void *data;
943 
944     rom->mr = g_malloc(sizeof(*rom->mr));
945     memory_region_init_resizeable_ram(rom->mr, owner, name,
946                                       rom->datasize, rom->romsize,
947                                       fw_cfg_resized,
948                                       &error_fatal);
949     memory_region_set_readonly(rom->mr, ro);
950     vmstate_register_ram_global(rom->mr);
951 
952     data = memory_region_get_ram_ptr(rom->mr);
953     memcpy(data, rom->data, rom->datasize);
954 
955     return data;
956 }
957 
958 int rom_add_file(const char *file, const char *fw_dir,
959                  hwaddr addr, int32_t bootindex,
960                  bool option_rom, MemoryRegion *mr,
961                  AddressSpace *as)
962 {
963     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
964     Rom *rom;
965     int rc, fd = -1;
966     char devpath[100];
967 
968     if (as && mr) {
969         fprintf(stderr, "Specifying an Address Space and Memory Region is " \
970                 "not valid when loading a rom\n");
971         /* We haven't allocated anything so we don't need any cleanup */
972         return -1;
973     }
974 
975     rom = g_malloc0(sizeof(*rom));
976     rom->name = g_strdup(file);
977     rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
978     rom->as = as;
979     if (rom->path == NULL) {
980         rom->path = g_strdup(file);
981     }
982 
983     fd = open(rom->path, O_RDONLY | O_BINARY);
984     if (fd == -1) {
985         fprintf(stderr, "Could not open option rom '%s': %s\n",
986                 rom->path, strerror(errno));
987         goto err;
988     }
989 
990     if (fw_dir) {
991         rom->fw_dir  = g_strdup(fw_dir);
992         rom->fw_file = g_strdup(file);
993     }
994     rom->addr     = addr;
995     rom->romsize  = lseek(fd, 0, SEEK_END);
996     if (rom->romsize == -1) {
997         fprintf(stderr, "rom: file %-20s: get size error: %s\n",
998                 rom->name, strerror(errno));
999         goto err;
1000     }
1001 
1002     rom->datasize = rom->romsize;
1003     rom->data     = g_malloc0(rom->datasize);
1004     lseek(fd, 0, SEEK_SET);
1005     rc = read(fd, rom->data, rom->datasize);
1006     if (rc != rom->datasize) {
1007         fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
1008                 rom->name, rc, rom->datasize);
1009         goto err;
1010     }
1011     close(fd);
1012     rom_insert(rom);
1013     if (rom->fw_file && fw_cfg) {
1014         const char *basename;
1015         char fw_file_name[FW_CFG_MAX_FILE_PATH];
1016         void *data;
1017 
1018         basename = strrchr(rom->fw_file, '/');
1019         if (basename) {
1020             basename++;
1021         } else {
1022             basename = rom->fw_file;
1023         }
1024         snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
1025                  basename);
1026         snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
1027 
1028         if ((!option_rom || mc->option_rom_has_mr) && mc->rom_file_has_mr) {
1029             data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, true);
1030         } else {
1031             data = rom->data;
1032         }
1033 
1034         fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
1035     } else {
1036         if (mr) {
1037             rom->mr = mr;
1038             snprintf(devpath, sizeof(devpath), "/rom@%s", file);
1039         } else {
1040             snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);
1041         }
1042     }
1043 
1044     add_boot_device_path(bootindex, NULL, devpath);
1045     return 0;
1046 
1047 err:
1048     if (fd != -1)
1049         close(fd);
1050 
1051     rom_free(rom);
1052     return -1;
1053 }
1054 
1055 MemoryRegion *rom_add_blob(const char *name, const void *blob, size_t len,
1056                    size_t max_len, hwaddr addr, const char *fw_file_name,
1057                    FWCfgCallback fw_callback, void *callback_opaque,
1058                    AddressSpace *as, bool read_only)
1059 {
1060     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
1061     Rom *rom;
1062     MemoryRegion *mr = NULL;
1063 
1064     rom           = g_malloc0(sizeof(*rom));
1065     rom->name     = g_strdup(name);
1066     rom->as       = as;
1067     rom->addr     = addr;
1068     rom->romsize  = max_len ? max_len : len;
1069     rom->datasize = len;
1070     g_assert(rom->romsize >= rom->datasize);
1071     rom->data     = g_malloc0(rom->datasize);
1072     memcpy(rom->data, blob, len);
1073     rom_insert(rom);
1074     if (fw_file_name && fw_cfg) {
1075         char devpath[100];
1076         void *data;
1077 
1078         if (read_only) {
1079             snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
1080         } else {
1081             snprintf(devpath, sizeof(devpath), "/ram@%s", fw_file_name);
1082         }
1083 
1084         if (mc->rom_file_has_mr) {
1085             data = rom_set_mr(rom, OBJECT(fw_cfg), devpath, read_only);
1086             mr = rom->mr;
1087         } else {
1088             data = rom->data;
1089         }
1090 
1091         fw_cfg_add_file_callback(fw_cfg, fw_file_name,
1092                                  fw_callback, NULL, callback_opaque,
1093                                  data, rom->datasize, read_only);
1094     }
1095     return mr;
1096 }
1097 
1098 /* This function is specific for elf program because we don't need to allocate
1099  * all the rom. We just allocate the first part and the rest is just zeros. This
1100  * is why romsize and datasize are different. Also, this function takes its own
1101  * reference to "mapped_file", so we don't have to allocate and copy the buffer.
1102  */
1103 int rom_add_elf_program(const char *name, GMappedFile *mapped_file, void *data,
1104                         size_t datasize, size_t romsize, hwaddr addr,
1105                         AddressSpace *as)
1106 {
1107     Rom *rom;
1108 
1109     rom           = g_malloc0(sizeof(*rom));
1110     rom->name     = g_strdup(name);
1111     rom->addr     = addr;
1112     rom->datasize = datasize;
1113     rom->romsize  = romsize;
1114     rom->data     = data;
1115     rom->as       = as;
1116 
1117     if (mapped_file && data) {
1118         g_mapped_file_ref(mapped_file);
1119         rom->mapped_file = mapped_file;
1120     }
1121 
1122     rom_insert(rom);
1123     return 0;
1124 }
1125 
1126 int rom_add_vga(const char *file)
1127 {
1128     return rom_add_file(file, "vgaroms", 0, -1, true, NULL, NULL);
1129 }
1130 
1131 int rom_add_option(const char *file, int32_t bootindex)
1132 {
1133     return rom_add_file(file, "genroms", 0, bootindex, true, NULL, NULL);
1134 }
1135 
1136 static void rom_reset(void *unused)
1137 {
1138     Rom *rom;
1139 
1140     QTAILQ_FOREACH(rom, &roms, next) {
1141         if (rom->fw_file) {
1142             continue;
1143         }
1144         /*
1145          * We don't need to fill in the RAM with ROM data because we'll fill
1146          * the data in during the next incoming migration in all cases.  Note
1147          * that some of those RAMs can actually be modified by the guest.
1148          */
1149         if (runstate_check(RUN_STATE_INMIGRATE)) {
1150             if (rom->data && rom->isrom) {
1151                 /*
1152                  * Free it so that a rom_reset after migration doesn't
1153                  * overwrite a potentially modified 'rom'.
1154                  */
1155                 rom_free_data(rom);
1156             }
1157             continue;
1158         }
1159 
1160         if (rom->data == NULL) {
1161             continue;
1162         }
1163         if (rom->mr) {
1164             void *host = memory_region_get_ram_ptr(rom->mr);
1165             memcpy(host, rom->data, rom->datasize);
1166             memset(host + rom->datasize, 0, rom->romsize - rom->datasize);
1167         } else {
1168             address_space_write_rom(rom->as, rom->addr, MEMTXATTRS_UNSPECIFIED,
1169                                     rom->data, rom->datasize);
1170             address_space_set(rom->as, rom->addr + rom->datasize, 0,
1171                               rom->romsize - rom->datasize,
1172                               MEMTXATTRS_UNSPECIFIED);
1173         }
1174         if (rom->isrom) {
1175             /* rom needs to be written only once */
1176             rom_free_data(rom);
1177         }
1178         /*
1179          * The rom loader is really on the same level as firmware in the guest
1180          * shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
1181          * that the instruction cache for that new region is clear, so that the
1182          * CPU definitely fetches its instructions from the just written data.
1183          */
1184         cpu_flush_icache_range(rom->addr, rom->datasize);
1185 
1186         trace_loader_write_rom(rom->name, rom->addr, rom->datasize, rom->isrom);
1187     }
1188 }
1189 
1190 /* Return true if two consecutive ROMs in the ROM list overlap */
1191 static bool roms_overlap(Rom *last_rom, Rom *this_rom)
1192 {
1193     if (!last_rom) {
1194         return false;
1195     }
1196     return last_rom->as == this_rom->as &&
1197         last_rom->addr + last_rom->romsize > this_rom->addr;
1198 }
1199 
1200 static const char *rom_as_name(Rom *rom)
1201 {
1202     const char *name = rom->as ? rom->as->name : NULL;
1203     return name ?: "anonymous";
1204 }
1205 
1206 static void rom_print_overlap_error_header(void)
1207 {
1208     error_report("Some ROM regions are overlapping");
1209     error_printf(
1210         "These ROM regions might have been loaded by "
1211         "direct user request or by default.\n"
1212         "They could be BIOS/firmware images, a guest kernel, "
1213         "initrd or some other file loaded into guest memory.\n"
1214         "Check whether you intended to load all this guest code, and "
1215         "whether it has been built to load to the correct addresses.\n");
1216 }
1217 
1218 static void rom_print_one_overlap_error(Rom *last_rom, Rom *rom)
1219 {
1220     error_printf(
1221         "\nThe following two regions overlap (in the %s address space):\n",
1222         rom_as_name(rom));
1223     error_printf(
1224         "  %s (addresses 0x" TARGET_FMT_plx " - 0x" TARGET_FMT_plx ")\n",
1225         last_rom->name, last_rom->addr, last_rom->addr + last_rom->romsize);
1226     error_printf(
1227         "  %s (addresses 0x" TARGET_FMT_plx " - 0x" TARGET_FMT_plx ")\n",
1228         rom->name, rom->addr, rom->addr + rom->romsize);
1229 }
1230 
1231 int rom_check_and_register_reset(void)
1232 {
1233     MemoryRegionSection section;
1234     Rom *rom, *last_rom = NULL;
1235     bool found_overlap = false;
1236 
1237     QTAILQ_FOREACH(rom, &roms, next) {
1238         if (rom->fw_file) {
1239             continue;
1240         }
1241         if (!rom->mr) {
1242             if (roms_overlap(last_rom, rom)) {
1243                 if (!found_overlap) {
1244                     found_overlap = true;
1245                     rom_print_overlap_error_header();
1246                 }
1247                 rom_print_one_overlap_error(last_rom, rom);
1248                 /* Keep going through the list so we report all overlaps */
1249             }
1250             last_rom = rom;
1251         }
1252         section = memory_region_find(rom->mr ? rom->mr : get_system_memory(),
1253                                      rom->addr, 1);
1254         rom->isrom = int128_nz(section.size) && memory_region_is_rom(section.mr);
1255         memory_region_unref(section.mr);
1256     }
1257     if (found_overlap) {
1258         return -1;
1259     }
1260 
1261     qemu_register_reset(rom_reset, NULL);
1262     roms_loaded = 1;
1263     return 0;
1264 }
1265 
1266 void rom_set_fw(FWCfgState *f)
1267 {
1268     fw_cfg = f;
1269 }
1270 
1271 void rom_set_order_override(int order)
1272 {
1273     if (!fw_cfg)
1274         return;
1275     fw_cfg_set_order_override(fw_cfg, order);
1276 }
1277 
1278 void rom_reset_order_override(void)
1279 {
1280     if (!fw_cfg)
1281         return;
1282     fw_cfg_reset_order_override(fw_cfg);
1283 }
1284 
1285 void rom_transaction_begin(void)
1286 {
1287     Rom *rom;
1288 
1289     /* Ignore ROMs added without the transaction API */
1290     QTAILQ_FOREACH(rom, &roms, next) {
1291         rom->committed = true;
1292     }
1293 }
1294 
1295 void rom_transaction_end(bool commit)
1296 {
1297     Rom *rom;
1298     Rom *tmp;
1299 
1300     QTAILQ_FOREACH_SAFE(rom, &roms, next, tmp) {
1301         if (rom->committed) {
1302             continue;
1303         }
1304         if (commit) {
1305             rom->committed = true;
1306         } else {
1307             QTAILQ_REMOVE(&roms, rom, next);
1308             rom_free(rom);
1309         }
1310     }
1311 }
1312 
1313 static Rom *find_rom(hwaddr addr, size_t size)
1314 {
1315     Rom *rom;
1316 
1317     QTAILQ_FOREACH(rom, &roms, next) {
1318         if (rom->fw_file) {
1319             continue;
1320         }
1321         if (rom->mr) {
1322             continue;
1323         }
1324         if (rom->addr > addr) {
1325             continue;
1326         }
1327         if (rom->addr + rom->romsize < addr + size) {
1328             continue;
1329         }
1330         return rom;
1331     }
1332     return NULL;
1333 }
1334 
1335 typedef struct RomSec {
1336     hwaddr base;
1337     int se; /* start/end flag */
1338 } RomSec;
1339 
1340 
1341 /*
1342  * Sort into address order. We break ties between rom-startpoints
1343  * and rom-endpoints in favour of the startpoint, by sorting the 0->1
1344  * transition before the 1->0 transition. Either way round would
1345  * work, but this way saves a little work later by avoiding
1346  * dealing with "gaps" of 0 length.
1347  */
1348 static gint sort_secs(gconstpointer a, gconstpointer b)
1349 {
1350     RomSec *ra = (RomSec *) a;
1351     RomSec *rb = (RomSec *) b;
1352 
1353     if (ra->base == rb->base) {
1354         return ra->se - rb->se;
1355     }
1356     return ra->base > rb->base ? 1 : -1;
1357 }
1358 
1359 static GList *add_romsec_to_list(GList *secs, hwaddr base, int se)
1360 {
1361    RomSec *cand = g_new(RomSec, 1);
1362    cand->base = base;
1363    cand->se = se;
1364    return g_list_prepend(secs, cand);
1365 }
1366 
1367 RomGap rom_find_largest_gap_between(hwaddr base, size_t size)
1368 {
1369     Rom *rom;
1370     RomSec *cand;
1371     RomGap res = {0, 0};
1372     hwaddr gapstart = base;
1373     GList *it, *secs = NULL;
1374     int count = 0;
1375 
1376     QTAILQ_FOREACH(rom, &roms, next) {
1377         /* Ignore blobs being loaded to special places */
1378         if (rom->mr || rom->fw_file) {
1379             continue;
1380         }
1381         /* ignore anything finishing bellow base */
1382         if (rom->addr + rom->romsize <= base) {
1383             continue;
1384         }
1385         /* ignore anything starting above the region */
1386         if (rom->addr >= base + size) {
1387             continue;
1388         }
1389 
1390         /* Save the start and end of each relevant ROM */
1391         secs = add_romsec_to_list(secs, rom->addr, 1);
1392 
1393         if (rom->addr + rom->romsize < base + size) {
1394             secs = add_romsec_to_list(secs, rom->addr + rom->romsize, -1);
1395         }
1396     }
1397 
1398     /* sentinel */
1399     secs = add_romsec_to_list(secs, base + size, 1);
1400 
1401     secs = g_list_sort(secs, sort_secs);
1402 
1403     for (it = g_list_first(secs); it; it = g_list_next(it)) {
1404         cand = (RomSec *) it->data;
1405         if (count == 0 && count + cand->se == 1) {
1406             size_t gap = cand->base - gapstart;
1407             if (gap > res.size) {
1408                 res.base = gapstart;
1409                 res.size = gap;
1410             }
1411         } else if (count == 1 && count + cand->se == 0) {
1412             gapstart = cand->base;
1413         }
1414         count += cand->se;
1415     }
1416 
1417     g_list_free_full(secs, g_free);
1418     return res;
1419 }
1420 
1421 /*
1422  * Copies memory from registered ROMs to dest. Any memory that is contained in
1423  * a ROM between addr and addr + size is copied. Note that this can involve
1424  * multiple ROMs, which need not start at addr and need not end at addr + size.
1425  */
1426 int rom_copy(uint8_t *dest, hwaddr addr, size_t size)
1427 {
1428     hwaddr end = addr + size;
1429     uint8_t *s, *d = dest;
1430     size_t l = 0;
1431     Rom *rom;
1432 
1433     QTAILQ_FOREACH(rom, &roms, next) {
1434         if (rom->fw_file) {
1435             continue;
1436         }
1437         if (rom->mr) {
1438             continue;
1439         }
1440         if (rom->addr + rom->romsize < addr) {
1441             continue;
1442         }
1443         if (rom->addr > end || rom->addr < addr) {
1444             break;
1445         }
1446 
1447         d = dest + (rom->addr - addr);
1448         s = rom->data;
1449         l = rom->datasize;
1450 
1451         if ((d + l) > (dest + size)) {
1452             l = dest - d;
1453         }
1454 
1455         if (l > 0) {
1456             memcpy(d, s, l);
1457         }
1458 
1459         if (rom->romsize > rom->datasize) {
1460             /* If datasize is less than romsize, it means that we didn't
1461              * allocate all the ROM because the trailing data are only zeros.
1462              */
1463 
1464             d += l;
1465             l = rom->romsize - rom->datasize;
1466 
1467             if ((d + l) > (dest + size)) {
1468                 /* Rom size doesn't fit in the destination area. Adjust to avoid
1469                  * overflow.
1470                  */
1471                 l = dest - d;
1472             }
1473 
1474             if (l > 0) {
1475                 memset(d, 0x0, l);
1476             }
1477         }
1478     }
1479 
1480     return (d + l) - dest;
1481 }
1482 
1483 void *rom_ptr(hwaddr addr, size_t size)
1484 {
1485     Rom *rom;
1486 
1487     rom = find_rom(addr, size);
1488     if (!rom || !rom->data)
1489         return NULL;
1490     return rom->data + (addr - rom->addr);
1491 }
1492 
1493 typedef struct FindRomCBData {
1494     size_t size; /* Amount of data we want from ROM, in bytes */
1495     MemoryRegion *mr; /* MR at the unaliased guest addr */
1496     hwaddr xlat; /* Offset of addr within mr */
1497     void *rom; /* Output: rom data pointer, if found */
1498 } FindRomCBData;
1499 
1500 static bool find_rom_cb(Int128 start, Int128 len, const MemoryRegion *mr,
1501                         hwaddr offset_in_region, void *opaque)
1502 {
1503     FindRomCBData *cbdata = opaque;
1504     hwaddr alias_addr;
1505 
1506     if (mr != cbdata->mr) {
1507         return false;
1508     }
1509 
1510     alias_addr = int128_get64(start) + cbdata->xlat - offset_in_region;
1511     cbdata->rom = rom_ptr(alias_addr, cbdata->size);
1512     if (!cbdata->rom) {
1513         return false;
1514     }
1515     /* Found a match, stop iterating */
1516     return true;
1517 }
1518 
1519 void *rom_ptr_for_as(AddressSpace *as, hwaddr addr, size_t size)
1520 {
1521     /*
1522      * Find any ROM data for the given guest address range.  If there
1523      * is a ROM blob then return a pointer to the host memory
1524      * corresponding to 'addr'; otherwise return NULL.
1525      *
1526      * We look not only for ROM blobs that were loaded directly to
1527      * addr, but also for ROM blobs that were loaded to aliases of
1528      * that memory at other addresses within the AddressSpace.
1529      *
1530      * Note that we do not check @as against the 'as' member in the
1531      * 'struct Rom' returned by rom_ptr(). The Rom::as is the
1532      * AddressSpace which the rom blob should be written to, whereas
1533      * our @as argument is the AddressSpace which we are (effectively)
1534      * reading from, and the same underlying RAM will often be visible
1535      * in multiple AddressSpaces. (A common example is a ROM blob
1536      * written to the 'system' address space but then read back via a
1537      * CPU's cpu->as pointer.) This does mean we might potentially
1538      * return a false-positive match if a ROM blob was loaded into an
1539      * AS which is entirely separate and distinct from the one we're
1540      * querying, but this issue exists also for rom_ptr() and hasn't
1541      * caused any problems in practice.
1542      */
1543     FlatView *fv;
1544     void *rom;
1545     hwaddr len_unused;
1546     FindRomCBData cbdata = {};
1547 
1548     /* Easy case: there's data at the actual address */
1549     rom = rom_ptr(addr, size);
1550     if (rom) {
1551         return rom;
1552     }
1553 
1554     RCU_READ_LOCK_GUARD();
1555 
1556     fv = address_space_to_flatview(as);
1557     cbdata.mr = flatview_translate(fv, addr, &cbdata.xlat, &len_unused,
1558                                    false, MEMTXATTRS_UNSPECIFIED);
1559     if (!cbdata.mr) {
1560         /* Nothing at this address, so there can't be any aliasing */
1561         return NULL;
1562     }
1563     cbdata.size = size;
1564     flatview_for_each_range(fv, find_rom_cb, &cbdata);
1565     return cbdata.rom;
1566 }
1567 
1568 HumanReadableText *qmp_x_query_roms(Error **errp)
1569 {
1570     Rom *rom;
1571     g_autoptr(GString) buf = g_string_new("");
1572 
1573     QTAILQ_FOREACH(rom, &roms, next) {
1574         if (rom->mr) {
1575             g_string_append_printf(buf, "%s"
1576                                    " size=0x%06zx name=\"%s\"\n",
1577                                    memory_region_name(rom->mr),
1578                                    rom->romsize,
1579                                    rom->name);
1580         } else if (!rom->fw_file) {
1581             g_string_append_printf(buf, "addr=" TARGET_FMT_plx
1582                                    " size=0x%06zx mem=%s name=\"%s\"\n",
1583                                    rom->addr, rom->romsize,
1584                                    rom->isrom ? "rom" : "ram",
1585                                    rom->name);
1586         } else {
1587             g_string_append_printf(buf, "fw=%s/%s"
1588                                    " size=0x%06zx name=\"%s\"\n",
1589                                    rom->fw_dir,
1590                                    rom->fw_file,
1591                                    rom->romsize,
1592                                    rom->name);
1593         }
1594     }
1595 
1596     return human_readable_text_from_str(buf);
1597 }
1598 
1599 typedef enum HexRecord HexRecord;
1600 enum HexRecord {
1601     DATA_RECORD = 0,
1602     EOF_RECORD,
1603     EXT_SEG_ADDR_RECORD,
1604     START_SEG_ADDR_RECORD,
1605     EXT_LINEAR_ADDR_RECORD,
1606     START_LINEAR_ADDR_RECORD,
1607 };
1608 
1609 /* Each record contains a 16-bit address which is combined with the upper 16
1610  * bits of the implicit "next address" to form a 32-bit address.
1611  */
1612 #define NEXT_ADDR_MASK 0xffff0000
1613 
1614 #define DATA_FIELD_MAX_LEN 0xff
1615 #define LEN_EXCEPT_DATA 0x5
1616 /* 0x5 = sizeof(byte_count) + sizeof(address) + sizeof(record_type) +
1617  *       sizeof(checksum) */
1618 typedef struct {
1619     uint8_t byte_count;
1620     uint16_t address;
1621     uint8_t record_type;
1622     uint8_t data[DATA_FIELD_MAX_LEN];
1623     uint8_t checksum;
1624 } HexLine;
1625 
1626 /* return 0 or -1 if error */
1627 static bool parse_record(HexLine *line, uint8_t *our_checksum, const uint8_t c,
1628                          uint32_t *index, const bool in_process)
1629 {
1630     /* +-------+---------------+-------+---------------------+--------+
1631      * | byte  |               |record |                     |        |
1632      * | count |    address    | type  |        data         |checksum|
1633      * +-------+---------------+-------+---------------------+--------+
1634      * ^       ^               ^       ^                     ^        ^
1635      * |1 byte |    2 bytes    |1 byte |     0-255 bytes     | 1 byte |
1636      */
1637     uint8_t value = 0;
1638     uint32_t idx = *index;
1639     /* ignore space */
1640     if (g_ascii_isspace(c)) {
1641         return true;
1642     }
1643     if (!g_ascii_isxdigit(c) || !in_process) {
1644         return false;
1645     }
1646     value = g_ascii_xdigit_value(c);
1647     value = (idx & 0x1) ? (value & 0xf) : (value << 4);
1648     if (idx < 2) {
1649         line->byte_count |= value;
1650     } else if (2 <= idx && idx < 6) {
1651         line->address <<= 4;
1652         line->address += g_ascii_xdigit_value(c);
1653     } else if (6 <= idx && idx < 8) {
1654         line->record_type |= value;
1655     } else if (8 <= idx && idx < 8 + 2 * line->byte_count) {
1656         line->data[(idx - 8) >> 1] |= value;
1657     } else if (8 + 2 * line->byte_count <= idx &&
1658                idx < 10 + 2 * line->byte_count) {
1659         line->checksum |= value;
1660     } else {
1661         return false;
1662     }
1663     *our_checksum += value;
1664     ++(*index);
1665     return true;
1666 }
1667 
1668 typedef struct {
1669     const char *filename;
1670     HexLine line;
1671     uint8_t *bin_buf;
1672     hwaddr *start_addr;
1673     int total_size;
1674     uint32_t next_address_to_write;
1675     uint32_t current_address;
1676     uint32_t current_rom_index;
1677     uint32_t rom_start_address;
1678     AddressSpace *as;
1679     bool complete;
1680 } HexParser;
1681 
1682 /* return size or -1 if error */
1683 static int handle_record_type(HexParser *parser)
1684 {
1685     HexLine *line = &(parser->line);
1686     switch (line->record_type) {
1687     case DATA_RECORD:
1688         parser->current_address =
1689             (parser->next_address_to_write & NEXT_ADDR_MASK) | line->address;
1690         /* verify this is a contiguous block of memory */
1691         if (parser->current_address != parser->next_address_to_write) {
1692             if (parser->current_rom_index != 0) {
1693                 rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
1694                                       parser->current_rom_index,
1695                                       parser->rom_start_address, parser->as);
1696             }
1697             parser->rom_start_address = parser->current_address;
1698             parser->current_rom_index = 0;
1699         }
1700 
1701         /* copy from line buffer to output bin_buf */
1702         memcpy(parser->bin_buf + parser->current_rom_index, line->data,
1703                line->byte_count);
1704         parser->current_rom_index += line->byte_count;
1705         parser->total_size += line->byte_count;
1706         /* save next address to write */
1707         parser->next_address_to_write =
1708             parser->current_address + line->byte_count;
1709         break;
1710 
1711     case EOF_RECORD:
1712         if (parser->current_rom_index != 0) {
1713             rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
1714                                   parser->current_rom_index,
1715                                   parser->rom_start_address, parser->as);
1716         }
1717         parser->complete = true;
1718         return parser->total_size;
1719     case EXT_SEG_ADDR_RECORD:
1720     case EXT_LINEAR_ADDR_RECORD:
1721         if (line->byte_count != 2 && line->address != 0) {
1722             return -1;
1723         }
1724 
1725         if (parser->current_rom_index != 0) {
1726             rom_add_blob_fixed_as(parser->filename, parser->bin_buf,
1727                                   parser->current_rom_index,
1728                                   parser->rom_start_address, parser->as);
1729         }
1730 
1731         /* save next address to write,
1732          * in case of non-contiguous block of memory */
1733         parser->next_address_to_write = (line->data[0] << 12) |
1734                                         (line->data[1] << 4);
1735         if (line->record_type == EXT_LINEAR_ADDR_RECORD) {
1736             parser->next_address_to_write <<= 12;
1737         }
1738 
1739         parser->rom_start_address = parser->next_address_to_write;
1740         parser->current_rom_index = 0;
1741         break;
1742 
1743     case START_SEG_ADDR_RECORD:
1744         if (line->byte_count != 4 && line->address != 0) {
1745             return -1;
1746         }
1747 
1748         /* x86 16-bit CS:IP segmented addressing */
1749         *(parser->start_addr) = (((line->data[0] << 8) | line->data[1]) << 4) +
1750                                 ((line->data[2] << 8) | line->data[3]);
1751         break;
1752 
1753     case START_LINEAR_ADDR_RECORD:
1754         if (line->byte_count != 4 && line->address != 0) {
1755             return -1;
1756         }
1757 
1758         *(parser->start_addr) = ldl_be_p(line->data);
1759         break;
1760 
1761     default:
1762         return -1;
1763     }
1764 
1765     return parser->total_size;
1766 }
1767 
1768 /* return size or -1 if error */
1769 static int parse_hex_blob(const char *filename, hwaddr *addr, uint8_t *hex_blob,
1770                           size_t hex_blob_size, AddressSpace *as)
1771 {
1772     bool in_process = false; /* avoid re-enter and
1773                               * check whether record begin with ':' */
1774     uint8_t *end = hex_blob + hex_blob_size;
1775     uint8_t our_checksum = 0;
1776     uint32_t record_index = 0;
1777     HexParser parser = {
1778         .filename = filename,
1779         .bin_buf = g_malloc(hex_blob_size),
1780         .start_addr = addr,
1781         .as = as,
1782         .complete = false
1783     };
1784 
1785     rom_transaction_begin();
1786 
1787     for (; hex_blob < end && !parser.complete; ++hex_blob) {
1788         switch (*hex_blob) {
1789         case '\r':
1790         case '\n':
1791             if (!in_process) {
1792                 break;
1793             }
1794 
1795             in_process = false;
1796             if ((LEN_EXCEPT_DATA + parser.line.byte_count) * 2 !=
1797                     record_index ||
1798                 our_checksum != 0) {
1799                 parser.total_size = -1;
1800                 goto out;
1801             }
1802 
1803             if (handle_record_type(&parser) == -1) {
1804                 parser.total_size = -1;
1805                 goto out;
1806             }
1807             break;
1808 
1809         /* start of a new record. */
1810         case ':':
1811             memset(&parser.line, 0, sizeof(HexLine));
1812             in_process = true;
1813             record_index = 0;
1814             break;
1815 
1816         /* decoding lines */
1817         default:
1818             if (!parse_record(&parser.line, &our_checksum, *hex_blob,
1819                               &record_index, in_process)) {
1820                 parser.total_size = -1;
1821                 goto out;
1822             }
1823             break;
1824         }
1825     }
1826 
1827 out:
1828     g_free(parser.bin_buf);
1829     rom_transaction_end(parser.total_size != -1);
1830     return parser.total_size;
1831 }
1832 
1833 /* return size or -1 if error */
1834 int load_targphys_hex_as(const char *filename, hwaddr *entry, AddressSpace *as)
1835 {
1836     gsize hex_blob_size;
1837     gchar *hex_blob;
1838     int total_size = 0;
1839 
1840     if (!g_file_get_contents(filename, &hex_blob, &hex_blob_size, NULL)) {
1841         return -1;
1842     }
1843 
1844     total_size = parse_hex_blob(filename, entry, (uint8_t *)hex_blob,
1845                                 hex_blob_size, as);
1846 
1847     g_free(hex_blob);
1848     return total_size;
1849 }
1850