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