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