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