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