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