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