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