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