2 * QEMU Executable loader
4 * Copyright (c) 2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
24 * Gunzip functionality in this file is derived from u-boot:
26 * (C) Copyright 2008 Semihalf
28 * (C) Copyright 2000-2005
29 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
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.
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.
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/>.
45 #include "qemu/osdep.h"
46 #include "qemu-common.h"
47 #include "qemu/datadir.h"
48 #include "qapi/error.h"
51 #include "disas/disas.h"
52 #include "migration/vmstate.h"
53 #include "monitor/monitor.h"
54 #include "sysemu/reset.h"
55 #include "sysemu/sysemu.h"
56 #include "uboot_image.h"
57 #include "hw/loader.h"
58 #include "hw/nvram/fw_cfg.h"
59 #include "exec/memory.h"
60 #include "hw/boards.h"
61 #include "qemu/cutils.h"
62 #include "sysemu/runstate.h"
66 static int roms_loaded
;
68 /* return the size or -1 if error */
69 int64_t get_image_size(const char *filename
)
73 fd
= open(filename
, O_RDONLY
| O_BINARY
);
76 size
= lseek(fd
, 0, SEEK_END
);
81 /* return the size or -1 if error */
82 ssize_t
load_image_size(const char *filename
, void *addr
, size_t size
)
85 ssize_t actsize
, l
= 0;
87 fd
= open(filename
, O_RDONLY
| O_BINARY
);
92 while ((actsize
= read(fd
, addr
+ l
, size
- l
)) > 0) {
98 return actsize
< 0 ? -1 : l
;
101 /* read()-like version */
102 ssize_t
read_targphys(const char *name
,
103 int fd
, hwaddr dst_addr
, size_t nbytes
)
108 buf
= g_malloc(nbytes
);
109 did
= read(fd
, buf
, nbytes
);
111 rom_add_blob_fixed("read", buf
, did
, dst_addr
);
116 int load_image_targphys(const char *filename
,
117 hwaddr addr
, uint64_t max_sz
)
119 return load_image_targphys_as(filename
, addr
, max_sz
, NULL
);
122 /* return the size or -1 if error */
123 int load_image_targphys_as(const char *filename
,
124 hwaddr addr
, uint64_t max_sz
, AddressSpace
*as
)
128 size
= get_image_size(filename
);
129 if (size
< 0 || size
> max_sz
) {
133 if (rom_add_file_fixed_as(filename
, addr
, -1, as
) < 0) {
140 int load_image_mr(const char *filename
, MemoryRegion
*mr
)
144 if (!memory_access_is_direct(mr
, false)) {
145 /* Can only load an image into RAM or ROM */
149 size
= get_image_size(filename
);
151 if (size
< 0 || size
> memory_region_size(mr
)) {
155 if (rom_add_file_mr(filename
, mr
, -1) < 0) {
162 void pstrcpy_targphys(const char *name
, hwaddr dest
, int buf_size
,
168 if (buf_size
<= 0) return;
169 nulp
= memchr(source
, 0, buf_size
);
171 rom_add_blob_fixed(name
, source
, (nulp
- source
) + 1, dest
);
173 rom_add_blob_fixed(name
, source
, buf_size
, dest
);
174 ptr
= rom_ptr(dest
+ buf_size
- 1, sizeof(*ptr
));
183 uint32_t a_info
; /* Use macros N_MAGIC, etc for access */
184 uint32_t a_text
; /* length of text, in bytes */
185 uint32_t a_data
; /* length of data, in bytes */
186 uint32_t a_bss
; /* length of uninitialized data area, in bytes */
187 uint32_t a_syms
; /* length of symbol table data in file, in bytes */
188 uint32_t a_entry
; /* start address */
189 uint32_t a_trsize
; /* length of relocation info for text, in bytes */
190 uint32_t a_drsize
; /* length of relocation info for data, in bytes */
193 static void bswap_ahdr(struct exec
*e
)
195 bswap32s(&e
->a_info
);
196 bswap32s(&e
->a_text
);
197 bswap32s(&e
->a_data
);
199 bswap32s(&e
->a_syms
);
200 bswap32s(&e
->a_entry
);
201 bswap32s(&e
->a_trsize
);
202 bswap32s(&e
->a_drsize
);
205 #define N_MAGIC(exec) ((exec).a_info & 0xffff)
210 #define _N_HDROFF(x) (1024 - sizeof (struct exec))
211 #define N_TXTOFF(x) \
212 (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : \
213 (N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec)))
214 #define N_TXTADDR(x, target_page_size) (N_MAGIC(x) == QMAGIC ? target_page_size : 0)
215 #define _N_SEGMENT_ROUND(x, target_page_size) (((x) + target_page_size - 1) & ~(target_page_size - 1))
217 #define _N_TXTENDADDR(x, target_page_size) (N_TXTADDR(x, target_page_size)+(x).a_text)
219 #define N_DATADDR(x, target_page_size) \
220 (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x, target_page_size)) \
221 : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x, target_page_size), target_page_size)))
224 int load_aout(const char *filename
, hwaddr addr
, int max_sz
,
225 int bswap_needed
, hwaddr target_page_size
)
232 fd
= open(filename
, O_RDONLY
| O_BINARY
);
236 size
= read(fd
, &e
, sizeof(e
));
249 if (e
.a_text
+ e
.a_data
> max_sz
)
251 lseek(fd
, N_TXTOFF(e
), SEEK_SET
);
252 size
= read_targphys(filename
, fd
, addr
, e
.a_text
+ e
.a_data
);
257 if (N_DATADDR(e
, target_page_size
) + e
.a_data
> max_sz
)
259 lseek(fd
, N_TXTOFF(e
), SEEK_SET
);
260 size
= read_targphys(filename
, fd
, addr
, e
.a_text
);
263 ret
= read_targphys(filename
, fd
, addr
+ N_DATADDR(e
, target_page_size
),
281 static void *load_at(int fd
, off_t offset
, size_t size
)
284 if (lseek(fd
, offset
, SEEK_SET
) < 0)
286 ptr
= g_malloc(size
);
287 if (read(fd
, ptr
, size
) != size
) {
298 #define ELF_CLASS ELFCLASS32
302 #define elf_word uint32_t
303 #define elf_sword int32_t
304 #define bswapSZs bswap32s
305 #include "hw/elf_ops.h"
317 #define elfhdr elf64_hdr
318 #define elf_phdr elf64_phdr
319 #define elf_note elf64_note
320 #define elf_shdr elf64_shdr
321 #define elf_sym elf64_sym
322 #define elf_rela elf64_rela
323 #define elf_word uint64_t
324 #define elf_sword int64_t
325 #define bswapSZs bswap64s
327 #include "hw/elf_ops.h"
329 const char *load_elf_strerror(ssize_t error
)
334 case ELF_LOAD_FAILED
:
335 return "Failed to load ELF";
336 case ELF_LOAD_NOT_ELF
:
337 return "The image is not ELF";
338 case ELF_LOAD_WRONG_ARCH
:
339 return "The image is from incompatible architecture";
340 case ELF_LOAD_WRONG_ENDIAN
:
341 return "The image has incorrect endianness";
342 case ELF_LOAD_TOO_BIG
:
343 return "The image segments are too big to load";
345 return "Unknown error";
349 void load_elf_hdr(const char *filename
, void *hdr
, bool *is64
, Error
**errp
)
352 uint8_t e_ident_local
[EI_NIDENT
];
354 size_t hdr_size
, off
;
362 fd
= open(filename
, O_RDONLY
| O_BINARY
);
364 error_setg_errno(errp
, errno
, "Failed to open file: %s", filename
);
367 if (read(fd
, hdr
, EI_NIDENT
) != EI_NIDENT
) {
368 error_setg_errno(errp
, errno
, "Failed to read file: %s", filename
);
371 if (e_ident
[0] != ELFMAG0
||
372 e_ident
[1] != ELFMAG1
||
373 e_ident
[2] != ELFMAG2
||
374 e_ident
[3] != ELFMAG3
) {
375 error_setg(errp
, "Bad ELF magic");
379 is64l
= e_ident
[EI_CLASS
] == ELFCLASS64
;
380 hdr_size
= is64l
? sizeof(Elf64_Ehdr
) : sizeof(Elf32_Ehdr
);
386 while (hdr
!= e_ident_local
&& off
< hdr_size
) {
387 size_t br
= read(fd
, hdr
+ off
, hdr_size
- off
);
390 error_setg(errp
, "File too short: %s", filename
);
393 error_setg_errno(errp
, errno
, "Failed to read file: %s",
404 /* return < 0 if error, otherwise the number of bytes loaded in memory */
405 ssize_t
load_elf(const char *filename
,
406 uint64_t (*elf_note_fn
)(void *, void *, bool),
407 uint64_t (*translate_fn
)(void *, uint64_t),
408 void *translate_opaque
, uint64_t *pentry
, uint64_t *lowaddr
,
409 uint64_t *highaddr
, uint32_t *pflags
, int big_endian
,
410 int elf_machine
, int clear_lsb
, int data_swab
)
412 return load_elf_as(filename
, elf_note_fn
, translate_fn
, translate_opaque
,
413 pentry
, lowaddr
, highaddr
, pflags
, big_endian
,
414 elf_machine
, clear_lsb
, data_swab
, NULL
);
417 /* return < 0 if error, otherwise the number of bytes loaded in memory */
418 ssize_t
load_elf_as(const char *filename
,
419 uint64_t (*elf_note_fn
)(void *, void *, bool),
420 uint64_t (*translate_fn
)(void *, uint64_t),
421 void *translate_opaque
, uint64_t *pentry
, uint64_t *lowaddr
,
422 uint64_t *highaddr
, uint32_t *pflags
, int big_endian
,
423 int elf_machine
, int clear_lsb
, int data_swab
,
426 return load_elf_ram(filename
, elf_note_fn
, translate_fn
, translate_opaque
,
427 pentry
, lowaddr
, highaddr
, pflags
, big_endian
,
428 elf_machine
, clear_lsb
, data_swab
, as
, true);
431 /* return < 0 if error, otherwise the number of bytes loaded in memory */
432 ssize_t
load_elf_ram(const char *filename
,
433 uint64_t (*elf_note_fn
)(void *, void *, bool),
434 uint64_t (*translate_fn
)(void *, uint64_t),
435 void *translate_opaque
, uint64_t *pentry
,
436 uint64_t *lowaddr
, uint64_t *highaddr
, uint32_t *pflags
,
437 int big_endian
, int elf_machine
, int clear_lsb
,
438 int data_swab
, AddressSpace
*as
, bool load_rom
)
440 return load_elf_ram_sym(filename
, elf_note_fn
,
441 translate_fn
, translate_opaque
,
442 pentry
, lowaddr
, highaddr
, pflags
, big_endian
,
443 elf_machine
, clear_lsb
, data_swab
, as
,
447 /* return < 0 if error, otherwise the number of bytes loaded in memory */
448 ssize_t
load_elf_ram_sym(const char *filename
,
449 uint64_t (*elf_note_fn
)(void *, void *, bool),
450 uint64_t (*translate_fn
)(void *, uint64_t),
451 void *translate_opaque
, uint64_t *pentry
,
452 uint64_t *lowaddr
, uint64_t *highaddr
,
453 uint32_t *pflags
, int big_endian
, int elf_machine
,
454 int clear_lsb
, int data_swab
,
455 AddressSpace
*as
, bool load_rom
, symbol_fn_t sym_cb
)
457 int fd
, data_order
, target_data_order
, must_swab
;
458 ssize_t ret
= ELF_LOAD_FAILED
;
459 uint8_t e_ident
[EI_NIDENT
];
461 fd
= open(filename
, O_RDONLY
| O_BINARY
);
466 if (read(fd
, e_ident
, sizeof(e_ident
)) != sizeof(e_ident
))
468 if (e_ident
[0] != ELFMAG0
||
469 e_ident
[1] != ELFMAG1
||
470 e_ident
[2] != ELFMAG2
||
471 e_ident
[3] != ELFMAG3
) {
472 ret
= ELF_LOAD_NOT_ELF
;
475 #ifdef HOST_WORDS_BIGENDIAN
476 data_order
= ELFDATA2MSB
;
478 data_order
= ELFDATA2LSB
;
480 must_swab
= data_order
!= e_ident
[EI_DATA
];
482 target_data_order
= ELFDATA2MSB
;
484 target_data_order
= ELFDATA2LSB
;
487 if (target_data_order
!= e_ident
[EI_DATA
]) {
488 ret
= ELF_LOAD_WRONG_ENDIAN
;
492 lseek(fd
, 0, SEEK_SET
);
493 if (e_ident
[EI_CLASS
] == ELFCLASS64
) {
494 ret
= load_elf64(filename
, fd
, elf_note_fn
,
495 translate_fn
, translate_opaque
, must_swab
,
496 pentry
, lowaddr
, highaddr
, pflags
, elf_machine
,
497 clear_lsb
, data_swab
, as
, load_rom
, sym_cb
);
499 ret
= load_elf32(filename
, fd
, elf_note_fn
,
500 translate_fn
, translate_opaque
, must_swab
,
501 pentry
, lowaddr
, highaddr
, pflags
, elf_machine
,
502 clear_lsb
, data_swab
, as
, load_rom
, sym_cb
);
510 static void bswap_uboot_header(uboot_image_header_t
*hdr
)
512 #ifndef HOST_WORDS_BIGENDIAN
513 bswap32s(&hdr
->ih_magic
);
514 bswap32s(&hdr
->ih_hcrc
);
515 bswap32s(&hdr
->ih_time
);
516 bswap32s(&hdr
->ih_size
);
517 bswap32s(&hdr
->ih_load
);
518 bswap32s(&hdr
->ih_ep
);
519 bswap32s(&hdr
->ih_dcrc
);
524 #define ZALLOC_ALIGNMENT 16
526 static void *zalloc(void *x
, unsigned items
, unsigned size
)
531 size
= (size
+ ZALLOC_ALIGNMENT
- 1) & ~(ZALLOC_ALIGNMENT
- 1);
538 static void zfree(void *x
, void *addr
)
545 #define EXTRA_FIELD 4
548 #define RESERVED 0xe0
552 ssize_t
gunzip(void *dst
, size_t dstlen
, uint8_t *src
, size_t srclen
)
564 if (src
[2] != DEFLATED
|| (flags
& RESERVED
) != 0) {
565 puts ("Error: Bad gzipped data\n");
568 if ((flags
& EXTRA_FIELD
) != 0) {
572 i
= 12 + src
[10] + (src
[11] << 8);
574 if ((flags
& ORIG_NAME
) != 0) {
575 while (i
< srclen
&& src
[i
++] != 0) {
579 if ((flags
& COMMENT
) != 0) {
580 while (i
< srclen
&& src
[i
++] != 0) {
584 if ((flags
& HEAD_CRC
) != 0) {
594 r
= inflateInit2(&s
, -MAX_WBITS
);
596 printf ("Error: inflateInit2() returned %d\n", r
);
600 s
.avail_in
= srclen
- i
;
602 s
.avail_out
= dstlen
;
603 r
= inflate(&s
, Z_FINISH
);
604 if (r
!= Z_OK
&& r
!= Z_STREAM_END
) {
605 printf ("Error: inflate() returned %d\n", r
);
608 dstbytes
= s
.next_out
- (unsigned char *) dst
;
614 puts("Error: gunzip out of data in header\n");
618 /* Load a U-Boot image. */
619 static int load_uboot_image(const char *filename
, hwaddr
*ep
, hwaddr
*loadaddr
,
620 int *is_linux
, uint8_t image_type
,
621 uint64_t (*translate_fn
)(void *, uint64_t),
622 void *translate_opaque
, AddressSpace
*as
)
627 uboot_image_header_t h
;
628 uboot_image_header_t
*hdr
= &h
;
629 uint8_t *data
= NULL
;
631 int do_uncompress
= 0;
633 fd
= open(filename
, O_RDONLY
| O_BINARY
);
637 size
= read(fd
, hdr
, sizeof(uboot_image_header_t
));
638 if (size
< sizeof(uboot_image_header_t
)) {
642 bswap_uboot_header(hdr
);
644 if (hdr
->ih_magic
!= IH_MAGIC
)
647 if (hdr
->ih_type
!= image_type
) {
648 if (!(image_type
== IH_TYPE_KERNEL
&&
649 hdr
->ih_type
== IH_TYPE_KERNEL_NOLOAD
)) {
650 fprintf(stderr
, "Wrong image type %d, expected %d\n", hdr
->ih_type
,
656 /* TODO: Implement other image types. */
657 switch (hdr
->ih_type
) {
658 case IH_TYPE_KERNEL_NOLOAD
:
659 if (!loadaddr
|| *loadaddr
== LOAD_UIMAGE_LOADADDR_INVALID
) {
660 fprintf(stderr
, "this image format (kernel_noload) cannot be "
661 "loaded on this machine type");
665 hdr
->ih_load
= *loadaddr
+ sizeof(*hdr
);
666 hdr
->ih_ep
+= hdr
->ih_load
;
669 address
= hdr
->ih_load
;
671 address
= translate_fn(translate_opaque
, address
);
674 *loadaddr
= hdr
->ih_load
;
677 switch (hdr
->ih_comp
) {
685 "Unable to load u-boot images with compression type %d\n",
694 /* TODO: Check CPU type. */
696 if (hdr
->ih_os
== IH_OS_LINUX
) {
704 case IH_TYPE_RAMDISK
:
708 fprintf(stderr
, "Unsupported u-boot image type %d\n", hdr
->ih_type
);
712 data
= g_malloc(hdr
->ih_size
);
714 if (read(fd
, data
, hdr
->ih_size
) != hdr
->ih_size
) {
715 fprintf(stderr
, "Error reading file\n");
720 uint8_t *compressed_data
;
724 compressed_data
= data
;
725 max_bytes
= UBOOT_MAX_GUNZIP_BYTES
;
726 data
= g_malloc(max_bytes
);
728 bytes
= gunzip(data
, max_bytes
, compressed_data
, hdr
->ih_size
);
729 g_free(compressed_data
);
731 fprintf(stderr
, "Unable to decompress gzipped image!\n");
734 hdr
->ih_size
= bytes
;
737 rom_add_blob_fixed_as(filename
, data
, hdr
->ih_size
, address
, as
);
747 int load_uimage(const char *filename
, hwaddr
*ep
, hwaddr
*loadaddr
,
749 uint64_t (*translate_fn
)(void *, uint64_t),
750 void *translate_opaque
)
752 return load_uboot_image(filename
, ep
, loadaddr
, is_linux
, IH_TYPE_KERNEL
,
753 translate_fn
, translate_opaque
, NULL
);
756 int load_uimage_as(const char *filename
, hwaddr
*ep
, hwaddr
*loadaddr
,
758 uint64_t (*translate_fn
)(void *, uint64_t),
759 void *translate_opaque
, AddressSpace
*as
)
761 return load_uboot_image(filename
, ep
, loadaddr
, is_linux
, IH_TYPE_KERNEL
,
762 translate_fn
, translate_opaque
, as
);
765 /* Load a ramdisk. */
766 int load_ramdisk(const char *filename
, hwaddr addr
, uint64_t max_sz
)
768 return load_ramdisk_as(filename
, addr
, max_sz
, NULL
);
771 int load_ramdisk_as(const char *filename
, hwaddr addr
, uint64_t max_sz
,
774 return load_uboot_image(filename
, NULL
, &addr
, NULL
, IH_TYPE_RAMDISK
,
778 /* Load a gzip-compressed kernel to a dynamically allocated buffer. */
779 int load_image_gzipped_buffer(const char *filename
, uint64_t max_sz
,
782 uint8_t *compressed_data
= NULL
;
783 uint8_t *data
= NULL
;
788 if (!g_file_get_contents(filename
, (char **) &compressed_data
, &len
,
793 /* Is it a gzip-compressed file? */
795 compressed_data
[0] != 0x1f ||
796 compressed_data
[1] != 0x8b) {
800 if (max_sz
> LOAD_IMAGE_MAX_GUNZIP_BYTES
) {
801 max_sz
= LOAD_IMAGE_MAX_GUNZIP_BYTES
;
804 data
= g_malloc(max_sz
);
805 bytes
= gunzip(data
, max_sz
, compressed_data
, len
);
807 fprintf(stderr
, "%s: unable to decompress gzipped kernel file\n",
812 /* trim to actual size and return to caller */
813 *buffer
= g_realloc(data
, bytes
);
815 /* ownership has been transferred to caller */
819 g_free(compressed_data
);
824 /* Load a gzip-compressed kernel. */
825 int load_image_gzipped(const char *filename
, hwaddr addr
, uint64_t max_sz
)
830 bytes
= load_image_gzipped_buffer(filename
, max_sz
, &data
);
832 rom_add_blob_fixed(filename
, data
, bytes
, addr
);
839 * Functions for reboot-persistent memory regions.
840 * - used for vga bios and option roms.
841 * - also linux kernel (-kernel / -initrd).
844 typedef struct Rom Rom
;
850 /* datasize is the amount of memory allocated in "data". If datasize is less
851 * than romsize, it means that the area from datasize to romsize is filled
863 GMappedFile
*mapped_file
;
868 QTAILQ_ENTRY(Rom
) next
;
871 static FWCfgState
*fw_cfg
;
872 static QTAILQ_HEAD(, Rom
) roms
= QTAILQ_HEAD_INITIALIZER(roms
);
875 * rom->data can be heap-allocated or memory-mapped (e.g. when added with
876 * rom_add_elf_program())
878 static void rom_free_data(Rom
*rom
)
880 if (rom
->mapped_file
) {
881 g_mapped_file_unref(rom
->mapped_file
);
882 rom
->mapped_file
= NULL
;
890 static void rom_free(Rom
*rom
)
896 g_free(rom
->fw_file
);
900 static inline bool rom_order_compare(Rom
*rom
, Rom
*item
)
902 return ((uintptr_t)(void *)rom
->as
> (uintptr_t)(void *)item
->as
) ||
903 (rom
->as
== item
->as
&& rom
->addr
>= item
->addr
);
906 static void rom_insert(Rom
*rom
)
911 hw_error ("ROM images must be loaded at startup\n");
914 /* The user didn't specify an address space, this is the default */
916 rom
->as
= &address_space_memory
;
919 rom
->committed
= false;
921 /* List is ordered by load address in the same address space */
922 QTAILQ_FOREACH(item
, &roms
, next
) {
923 if (rom_order_compare(rom
, item
)) {
926 QTAILQ_INSERT_BEFORE(item
, rom
, next
);
929 QTAILQ_INSERT_TAIL(&roms
, rom
, next
);
932 static void fw_cfg_resized(const char *id
, uint64_t length
, void *host
)
935 fw_cfg_modify_file(fw_cfg
, id
+ strlen("/rom@"), host
, length
);
939 static void *rom_set_mr(Rom
*rom
, Object
*owner
, const char *name
, bool ro
)
943 rom
->mr
= g_malloc(sizeof(*rom
->mr
));
944 memory_region_init_resizeable_ram(rom
->mr
, owner
, name
,
945 rom
->datasize
, rom
->romsize
,
948 memory_region_set_readonly(rom
->mr
, ro
);
949 vmstate_register_ram_global(rom
->mr
);
951 data
= memory_region_get_ram_ptr(rom
->mr
);
952 memcpy(data
, rom
->data
, rom
->datasize
);
957 int rom_add_file(const char *file
, const char *fw_dir
,
958 hwaddr addr
, int32_t bootindex
,
959 bool option_rom
, MemoryRegion
*mr
,
962 MachineClass
*mc
= MACHINE_GET_CLASS(qdev_get_machine());
968 fprintf(stderr
, "Specifying an Address Space and Memory Region is " \
969 "not valid when loading a rom\n");
970 /* We haven't allocated anything so we don't need any cleanup */
974 rom
= g_malloc0(sizeof(*rom
));
975 rom
->name
= g_strdup(file
);
976 rom
->path
= qemu_find_file(QEMU_FILE_TYPE_BIOS
, rom
->name
);
978 if (rom
->path
== NULL
) {
979 rom
->path
= g_strdup(file
);
982 fd
= open(rom
->path
, O_RDONLY
| O_BINARY
);
984 fprintf(stderr
, "Could not open option rom '%s': %s\n",
985 rom
->path
, strerror(errno
));
990 rom
->fw_dir
= g_strdup(fw_dir
);
991 rom
->fw_file
= g_strdup(file
);
994 rom
->romsize
= lseek(fd
, 0, SEEK_END
);
995 if (rom
->romsize
== -1) {
996 fprintf(stderr
, "rom: file %-20s: get size error: %s\n",
997 rom
->name
, strerror(errno
));
1001 rom
->datasize
= rom
->romsize
;
1002 rom
->data
= g_malloc0(rom
->datasize
);
1003 lseek(fd
, 0, SEEK_SET
);
1004 rc
= read(fd
, rom
->data
, rom
->datasize
);
1005 if (rc
!= rom
->datasize
) {
1006 fprintf(stderr
, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
1007 rom
->name
, rc
, rom
->datasize
);
1012 if (rom
->fw_file
&& fw_cfg
) {
1013 const char *basename
;
1014 char fw_file_name
[FW_CFG_MAX_FILE_PATH
];
1017 basename
= strrchr(rom
->fw_file
, '/');
1021 basename
= rom
->fw_file
;
1023 snprintf(fw_file_name
, sizeof(fw_file_name
), "%s/%s", rom
->fw_dir
,
1025 snprintf(devpath
, sizeof(devpath
), "/rom@%s", fw_file_name
);
1027 if ((!option_rom
|| mc
->option_rom_has_mr
) && mc
->rom_file_has_mr
) {
1028 data
= rom_set_mr(rom
, OBJECT(fw_cfg
), devpath
, true);
1033 fw_cfg_add_file(fw_cfg
, fw_file_name
, data
, rom
->romsize
);
1037 snprintf(devpath
, sizeof(devpath
), "/rom@%s", file
);
1039 snprintf(devpath
, sizeof(devpath
), "/rom@" TARGET_FMT_plx
, addr
);
1043 add_boot_device_path(bootindex
, NULL
, devpath
);
1054 MemoryRegion
*rom_add_blob(const char *name
, const void *blob
, size_t len
,
1055 size_t max_len
, hwaddr addr
, const char *fw_file_name
,
1056 FWCfgCallback fw_callback
, void *callback_opaque
,
1057 AddressSpace
*as
, bool read_only
)
1059 MachineClass
*mc
= MACHINE_GET_CLASS(qdev_get_machine());
1061 MemoryRegion
*mr
= NULL
;
1063 rom
= g_malloc0(sizeof(*rom
));
1064 rom
->name
= g_strdup(name
);
1067 rom
->romsize
= max_len
? max_len
: len
;
1068 rom
->datasize
= len
;
1069 g_assert(rom
->romsize
>= rom
->datasize
);
1070 rom
->data
= g_malloc0(rom
->datasize
);
1071 memcpy(rom
->data
, blob
, len
);
1073 if (fw_file_name
&& fw_cfg
) {
1078 snprintf(devpath
, sizeof(devpath
), "/rom@%s", fw_file_name
);
1080 snprintf(devpath
, sizeof(devpath
), "/ram@%s", fw_file_name
);
1083 if (mc
->rom_file_has_mr
) {
1084 data
= rom_set_mr(rom
, OBJECT(fw_cfg
), devpath
, read_only
);
1090 fw_cfg_add_file_callback(fw_cfg
, fw_file_name
,
1091 fw_callback
, NULL
, callback_opaque
,
1092 data
, rom
->datasize
, read_only
);
1097 /* This function is specific for elf program because we don't need to allocate
1098 * all the rom. We just allocate the first part and the rest is just zeros. This
1099 * is why romsize and datasize are different. Also, this function takes its own
1100 * reference to "mapped_file", so we don't have to allocate and copy the buffer.
1102 int rom_add_elf_program(const char *name
, GMappedFile
*mapped_file
, void *data
,
1103 size_t datasize
, size_t romsize
, hwaddr addr
,
1108 rom
= g_malloc0(sizeof(*rom
));
1109 rom
->name
= g_strdup(name
);
1111 rom
->datasize
= datasize
;
1112 rom
->romsize
= romsize
;
1116 if (mapped_file
&& data
) {
1117 g_mapped_file_ref(mapped_file
);
1118 rom
->mapped_file
= mapped_file
;
1125 int rom_add_vga(const char *file
)
1127 return rom_add_file(file
, "vgaroms", 0, -1, true, NULL
, NULL
);
1130 int rom_add_option(const char *file
, int32_t bootindex
)
1132 return rom_add_file(file
, "genroms", 0, bootindex
, true, NULL
, NULL
);
1135 static void rom_reset(void *unused
)
1139 QTAILQ_FOREACH(rom
, &roms
, next
) {
1144 * We don't need to fill in the RAM with ROM data because we'll fill
1145 * the data in during the next incoming migration in all cases. Note
1146 * that some of those RAMs can actually be modified by the guest.
1148 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1149 if (rom
->data
&& rom
->isrom
) {
1151 * Free it so that a rom_reset after migration doesn't
1152 * overwrite a potentially modified 'rom'.
1159 if (rom
->data
== NULL
) {
1163 void *host
= memory_region_get_ram_ptr(rom
->mr
);
1164 memcpy(host
, rom
->data
, rom
->datasize
);
1166 address_space_write_rom(rom
->as
, rom
->addr
, MEMTXATTRS_UNSPECIFIED
,
1167 rom
->data
, rom
->datasize
);
1170 /* rom needs to be written only once */
1174 * The rom loader is really on the same level as firmware in the guest
1175 * shadowing a ROM into RAM. Such a shadowing mechanism needs to ensure
1176 * that the instruction cache for that new region is clear, so that the
1177 * CPU definitely fetches its instructions from the just written data.
1179 cpu_flush_icache_range(rom
->addr
, rom
->datasize
);
1181 trace_loader_write_rom(rom
->name
, rom
->addr
, rom
->datasize
, rom
->isrom
);
1185 /* Return true if two consecutive ROMs in the ROM list overlap */
1186 static bool roms_overlap(Rom
*last_rom
, Rom
*this_rom
)
1191 return last_rom
->as
== this_rom
->as
&&
1192 last_rom
->addr
+ last_rom
->romsize
> this_rom
->addr
;
1195 static const char *rom_as_name(Rom
*rom
)
1197 const char *name
= rom
->as
? rom
->as
->name
: NULL
;
1198 return name
?: "anonymous";
1201 static void rom_print_overlap_error_header(void)
1203 error_report("Some ROM regions are overlapping");
1205 "These ROM regions might have been loaded by "
1206 "direct user request or by default.\n"
1207 "They could be BIOS/firmware images, a guest kernel, "
1208 "initrd or some other file loaded into guest memory.\n"
1209 "Check whether you intended to load all this guest code, and "
1210 "whether it has been built to load to the correct addresses.\n");
1213 static void rom_print_one_overlap_error(Rom
*last_rom
, Rom
*rom
)
1216 "\nThe following two regions overlap (in the %s address space):\n",
1219 " %s (addresses 0x" TARGET_FMT_plx
" - 0x" TARGET_FMT_plx
")\n",
1220 last_rom
->name
, last_rom
->addr
, last_rom
->addr
+ last_rom
->romsize
);
1222 " %s (addresses 0x" TARGET_FMT_plx
" - 0x" TARGET_FMT_plx
")\n",
1223 rom
->name
, rom
->addr
, rom
->addr
+ rom
->romsize
);
1226 int rom_check_and_register_reset(void)
1228 MemoryRegionSection section
;
1229 Rom
*rom
, *last_rom
= NULL
;
1230 bool found_overlap
= false;
1232 QTAILQ_FOREACH(rom
, &roms
, next
) {
1237 if (roms_overlap(last_rom
, rom
)) {
1238 if (!found_overlap
) {
1239 found_overlap
= true;
1240 rom_print_overlap_error_header();
1242 rom_print_one_overlap_error(last_rom
, rom
);
1243 /* Keep going through the list so we report all overlaps */
1247 section
= memory_region_find(rom
->mr
? rom
->mr
: get_system_memory(),
1249 rom
->isrom
= int128_nz(section
.size
) && memory_region_is_rom(section
.mr
);
1250 memory_region_unref(section
.mr
);
1252 if (found_overlap
) {
1256 qemu_register_reset(rom_reset
, NULL
);
1261 void rom_set_fw(FWCfgState
*f
)
1266 void rom_set_order_override(int order
)
1270 fw_cfg_set_order_override(fw_cfg
, order
);
1273 void rom_reset_order_override(void)
1277 fw_cfg_reset_order_override(fw_cfg
);
1280 void rom_transaction_begin(void)
1284 /* Ignore ROMs added without the transaction API */
1285 QTAILQ_FOREACH(rom
, &roms
, next
) {
1286 rom
->committed
= true;
1290 void rom_transaction_end(bool commit
)
1295 QTAILQ_FOREACH_SAFE(rom
, &roms
, next
, tmp
) {
1296 if (rom
->committed
) {
1300 rom
->committed
= true;
1302 QTAILQ_REMOVE(&roms
, rom
, next
);
1308 static Rom
*find_rom(hwaddr addr
, size_t size
)
1312 QTAILQ_FOREACH(rom
, &roms
, next
) {
1319 if (rom
->addr
> addr
) {
1322 if (rom
->addr
+ rom
->romsize
< addr
+ size
) {
1331 * Copies memory from registered ROMs to dest. Any memory that is contained in
1332 * a ROM between addr and addr + size is copied. Note that this can involve
1333 * multiple ROMs, which need not start at addr and need not end at addr + size.
1335 int rom_copy(uint8_t *dest
, hwaddr addr
, size_t size
)
1337 hwaddr end
= addr
+ size
;
1338 uint8_t *s
, *d
= dest
;
1342 QTAILQ_FOREACH(rom
, &roms
, next
) {
1349 if (rom
->addr
+ rom
->romsize
< addr
) {
1352 if (rom
->addr
> end
|| rom
->addr
< addr
) {
1356 d
= dest
+ (rom
->addr
- addr
);
1360 if ((d
+ l
) > (dest
+ size
)) {
1368 if (rom
->romsize
> rom
->datasize
) {
1369 /* If datasize is less than romsize, it means that we didn't
1370 * allocate all the ROM because the trailing data are only zeros.
1374 l
= rom
->romsize
- rom
->datasize
;
1376 if ((d
+ l
) > (dest
+ size
)) {
1377 /* Rom size doesn't fit in the destination area. Adjust to avoid
1389 return (d
+ l
) - dest
;
1392 void *rom_ptr(hwaddr addr
, size_t size
)
1396 rom
= find_rom(addr
, size
);
1397 if (!rom
|| !rom
->data
)
1399 return rom
->data
+ (addr
- rom
->addr
);
1402 typedef struct FindRomCBData
{
1403 size_t size
; /* Amount of data we want from ROM, in bytes */
1404 MemoryRegion
*mr
; /* MR at the unaliased guest addr */
1405 hwaddr xlat
; /* Offset of addr within mr */
1406 void *rom
; /* Output: rom data pointer, if found */
1409 static bool find_rom_cb(Int128 start
, Int128 len
, const MemoryRegion
*mr
,
1410 hwaddr offset_in_region
, void *opaque
)
1412 FindRomCBData
*cbdata
= opaque
;
1415 if (mr
!= cbdata
->mr
) {
1419 alias_addr
= int128_get64(start
) + cbdata
->xlat
- offset_in_region
;
1420 cbdata
->rom
= rom_ptr(alias_addr
, cbdata
->size
);
1424 /* Found a match, stop iterating */
1428 void *rom_ptr_for_as(AddressSpace
*as
, hwaddr addr
, size_t size
)
1431 * Find any ROM data for the given guest address range. If there
1432 * is a ROM blob then return a pointer to the host memory
1433 * corresponding to 'addr'; otherwise return NULL.
1435 * We look not only for ROM blobs that were loaded directly to
1436 * addr, but also for ROM blobs that were loaded to aliases of
1437 * that memory at other addresses within the AddressSpace.
1439 * Note that we do not check @as against the 'as' member in the
1440 * 'struct Rom' returned by rom_ptr(). The Rom::as is the
1441 * AddressSpace which the rom blob should be written to, whereas
1442 * our @as argument is the AddressSpace which we are (effectively)
1443 * reading from, and the same underlying RAM will often be visible
1444 * in multiple AddressSpaces. (A common example is a ROM blob
1445 * written to the 'system' address space but then read back via a
1446 * CPU's cpu->as pointer.) This does mean we might potentially
1447 * return a false-positive match if a ROM blob was loaded into an
1448 * AS which is entirely separate and distinct from the one we're
1449 * querying, but this issue exists also for rom_ptr() and hasn't
1450 * caused any problems in practice.
1455 FindRomCBData cbdata
= {};
1457 /* Easy case: there's data at the actual address */
1458 rom
= rom_ptr(addr
, size
);
1463 RCU_READ_LOCK_GUARD();
1465 fv
= address_space_to_flatview(as
);
1466 cbdata
.mr
= flatview_translate(fv
, addr
, &cbdata
.xlat
, &len_unused
,
1467 false, MEMTXATTRS_UNSPECIFIED
);
1469 /* Nothing at this address, so there can't be any aliasing */
1473 flatview_for_each_range(fv
, find_rom_cb
, &cbdata
);
1477 void hmp_info_roms(Monitor
*mon
, const QDict
*qdict
)
1481 QTAILQ_FOREACH(rom
, &roms
, next
) {
1483 monitor_printf(mon
, "%s"
1484 " size=0x%06zx name=\"%s\"\n",
1485 memory_region_name(rom
->mr
),
1488 } else if (!rom
->fw_file
) {
1489 monitor_printf(mon
, "addr=" TARGET_FMT_plx
1490 " size=0x%06zx mem=%s name=\"%s\"\n",
1491 rom
->addr
, rom
->romsize
,
1492 rom
->isrom
? "rom" : "ram",
1495 monitor_printf(mon
, "fw=%s/%s"
1496 " size=0x%06zx name=\"%s\"\n",
1505 typedef enum HexRecord HexRecord
;
1509 EXT_SEG_ADDR_RECORD
,
1510 START_SEG_ADDR_RECORD
,
1511 EXT_LINEAR_ADDR_RECORD
,
1512 START_LINEAR_ADDR_RECORD
,
1515 /* Each record contains a 16-bit address which is combined with the upper 16
1516 * bits of the implicit "next address" to form a 32-bit address.
1518 #define NEXT_ADDR_MASK 0xffff0000
1520 #define DATA_FIELD_MAX_LEN 0xff
1521 #define LEN_EXCEPT_DATA 0x5
1522 /* 0x5 = sizeof(byte_count) + sizeof(address) + sizeof(record_type) +
1523 * sizeof(checksum) */
1527 uint8_t record_type
;
1528 uint8_t data
[DATA_FIELD_MAX_LEN
];
1532 /* return 0 or -1 if error */
1533 static bool parse_record(HexLine
*line
, uint8_t *our_checksum
, const uint8_t c
,
1534 uint32_t *index
, const bool in_process
)
1536 /* +-------+---------------+-------+---------------------+--------+
1537 * | byte | |record | | |
1538 * | count | address | type | data |checksum|
1539 * +-------+---------------+-------+---------------------+--------+
1541 * |1 byte | 2 bytes |1 byte | 0-255 bytes | 1 byte |
1544 uint32_t idx
= *index
;
1546 if (g_ascii_isspace(c
)) {
1549 if (!g_ascii_isxdigit(c
) || !in_process
) {
1552 value
= g_ascii_xdigit_value(c
);
1553 value
= (idx
& 0x1) ? (value
& 0xf) : (value
<< 4);
1555 line
->byte_count
|= value
;
1556 } else if (2 <= idx
&& idx
< 6) {
1557 line
->address
<<= 4;
1558 line
->address
+= g_ascii_xdigit_value(c
);
1559 } else if (6 <= idx
&& idx
< 8) {
1560 line
->record_type
|= value
;
1561 } else if (8 <= idx
&& idx
< 8 + 2 * line
->byte_count
) {
1562 line
->data
[(idx
- 8) >> 1] |= value
;
1563 } else if (8 + 2 * line
->byte_count
<= idx
&&
1564 idx
< 10 + 2 * line
->byte_count
) {
1565 line
->checksum
|= value
;
1569 *our_checksum
+= value
;
1575 const char *filename
;
1580 uint32_t next_address_to_write
;
1581 uint32_t current_address
;
1582 uint32_t current_rom_index
;
1583 uint32_t rom_start_address
;
1588 /* return size or -1 if error */
1589 static int handle_record_type(HexParser
*parser
)
1591 HexLine
*line
= &(parser
->line
);
1592 switch (line
->record_type
) {
1594 parser
->current_address
=
1595 (parser
->next_address_to_write
& NEXT_ADDR_MASK
) | line
->address
;
1596 /* verify this is a contiguous block of memory */
1597 if (parser
->current_address
!= parser
->next_address_to_write
) {
1598 if (parser
->current_rom_index
!= 0) {
1599 rom_add_blob_fixed_as(parser
->filename
, parser
->bin_buf
,
1600 parser
->current_rom_index
,
1601 parser
->rom_start_address
, parser
->as
);
1603 parser
->rom_start_address
= parser
->current_address
;
1604 parser
->current_rom_index
= 0;
1607 /* copy from line buffer to output bin_buf */
1608 memcpy(parser
->bin_buf
+ parser
->current_rom_index
, line
->data
,
1610 parser
->current_rom_index
+= line
->byte_count
;
1611 parser
->total_size
+= line
->byte_count
;
1612 /* save next address to write */
1613 parser
->next_address_to_write
=
1614 parser
->current_address
+ line
->byte_count
;
1618 if (parser
->current_rom_index
!= 0) {
1619 rom_add_blob_fixed_as(parser
->filename
, parser
->bin_buf
,
1620 parser
->current_rom_index
,
1621 parser
->rom_start_address
, parser
->as
);
1623 parser
->complete
= true;
1624 return parser
->total_size
;
1625 case EXT_SEG_ADDR_RECORD
:
1626 case EXT_LINEAR_ADDR_RECORD
:
1627 if (line
->byte_count
!= 2 && line
->address
!= 0) {
1631 if (parser
->current_rom_index
!= 0) {
1632 rom_add_blob_fixed_as(parser
->filename
, parser
->bin_buf
,
1633 parser
->current_rom_index
,
1634 parser
->rom_start_address
, parser
->as
);
1637 /* save next address to write,
1638 * in case of non-contiguous block of memory */
1639 parser
->next_address_to_write
= (line
->data
[0] << 12) |
1640 (line
->data
[1] << 4);
1641 if (line
->record_type
== EXT_LINEAR_ADDR_RECORD
) {
1642 parser
->next_address_to_write
<<= 12;
1645 parser
->rom_start_address
= parser
->next_address_to_write
;
1646 parser
->current_rom_index
= 0;
1649 case START_SEG_ADDR_RECORD
:
1650 if (line
->byte_count
!= 4 && line
->address
!= 0) {
1654 /* x86 16-bit CS:IP segmented addressing */
1655 *(parser
->start_addr
) = (((line
->data
[0] << 8) | line
->data
[1]) << 4) +
1656 ((line
->data
[2] << 8) | line
->data
[3]);
1659 case START_LINEAR_ADDR_RECORD
:
1660 if (line
->byte_count
!= 4 && line
->address
!= 0) {
1664 *(parser
->start_addr
) = ldl_be_p(line
->data
);
1671 return parser
->total_size
;
1674 /* return size or -1 if error */
1675 static int parse_hex_blob(const char *filename
, hwaddr
*addr
, uint8_t *hex_blob
,
1676 size_t hex_blob_size
, AddressSpace
*as
)
1678 bool in_process
= false; /* avoid re-enter and
1679 * check whether record begin with ':' */
1680 uint8_t *end
= hex_blob
+ hex_blob_size
;
1681 uint8_t our_checksum
= 0;
1682 uint32_t record_index
= 0;
1683 HexParser parser
= {
1684 .filename
= filename
,
1685 .bin_buf
= g_malloc(hex_blob_size
),
1691 rom_transaction_begin();
1693 for (; hex_blob
< end
&& !parser
.complete
; ++hex_blob
) {
1694 switch (*hex_blob
) {
1702 if ((LEN_EXCEPT_DATA
+ parser
.line
.byte_count
) * 2 !=
1704 our_checksum
!= 0) {
1705 parser
.total_size
= -1;
1709 if (handle_record_type(&parser
) == -1) {
1710 parser
.total_size
= -1;
1715 /* start of a new record. */
1717 memset(&parser
.line
, 0, sizeof(HexLine
));
1722 /* decoding lines */
1724 if (!parse_record(&parser
.line
, &our_checksum
, *hex_blob
,
1725 &record_index
, in_process
)) {
1726 parser
.total_size
= -1;
1734 g_free(parser
.bin_buf
);
1735 rom_transaction_end(parser
.total_size
!= -1);
1736 return parser
.total_size
;
1739 /* return size or -1 if error */
1740 int load_targphys_hex_as(const char *filename
, hwaddr
*entry
, AddressSpace
*as
)
1742 gsize hex_blob_size
;
1746 if (!g_file_get_contents(filename
, &hex_blob
, &hex_blob_size
, NULL
)) {
1750 total_size
= parse_hex_blob(filename
, entry
, (uint8_t *)hex_blob
,