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