cachepc-qemu

Fork of AMDESE/qemu with changes for cachepc side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-qemu
Log | Files | Refs | Submodules | LICENSE | sfeed.txt

loader.c (50110B)


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