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