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