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