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