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