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