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