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