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