glue(bswap_ehdr,SZ)1 static void glue(bswap_ehdr, SZ)(struct elfhdr *ehdr)
2 {
3     bswap16s(&ehdr->e_type);			/* Object file type */
4     bswap16s(&ehdr->e_machine);		/* Architecture */
5     bswap32s(&ehdr->e_version);		/* Object file version */
6     bswapSZs(&ehdr->e_entry);		/* Entry point virtual address */
7     bswapSZs(&ehdr->e_phoff);		/* Program header table file offset */
8     bswapSZs(&ehdr->e_shoff);		/* Section header table file offset */
9     bswap32s(&ehdr->e_flags);		/* Processor-specific flags */
10     bswap16s(&ehdr->e_ehsize);		/* ELF header size in bytes */
11     bswap16s(&ehdr->e_phentsize);		/* Program header table entry size */
12     bswap16s(&ehdr->e_phnum);		/* Program header table entry count */
13     bswap16s(&ehdr->e_shentsize);		/* Section header table entry size */
14     bswap16s(&ehdr->e_shnum);		/* Section header table entry count */
15     bswap16s(&ehdr->e_shstrndx);		/* Section header string table index */
16 }
17 
glue(bswap_phdr,SZ)18 static void glue(bswap_phdr, SZ)(struct elf_phdr *phdr)
19 {
20     bswap32s(&phdr->p_type);			/* Segment type */
21     bswapSZs(&phdr->p_offset);		/* Segment file offset */
22     bswapSZs(&phdr->p_vaddr);		/* Segment virtual address */
23     bswapSZs(&phdr->p_paddr);		/* Segment physical address */
24     bswapSZs(&phdr->p_filesz);		/* Segment size in file */
25     bswapSZs(&phdr->p_memsz);		/* Segment size in memory */
26     bswap32s(&phdr->p_flags);		/* Segment flags */
27     bswapSZs(&phdr->p_align);		/* Segment alignment */
28 }
29 
glue(bswap_shdr,SZ)30 static void glue(bswap_shdr, SZ)(struct elf_shdr *shdr)
31 {
32     bswap32s(&shdr->sh_name);
33     bswap32s(&shdr->sh_type);
34     bswapSZs(&shdr->sh_flags);
35     bswapSZs(&shdr->sh_addr);
36     bswapSZs(&shdr->sh_offset);
37     bswapSZs(&shdr->sh_size);
38     bswap32s(&shdr->sh_link);
39     bswap32s(&shdr->sh_info);
40     bswapSZs(&shdr->sh_addralign);
41     bswapSZs(&shdr->sh_entsize);
42 }
43 
glue(bswap_sym,SZ)44 static void glue(bswap_sym, SZ)(struct elf_sym *sym)
45 {
46     bswap32s(&sym->st_name);
47     bswapSZs(&sym->st_value);
48     bswapSZs(&sym->st_size);
49     bswap16s(&sym->st_shndx);
50 }
51 
glue(bswap_rela,SZ)52 static void glue(bswap_rela, SZ)(struct elf_rela *rela)
53 {
54     bswapSZs(&rela->r_offset);
55     bswapSZs(&rela->r_info);
56     bswapSZs((elf_word *)&rela->r_addend);
57 }
58 
glue(find_section,SZ)59 static struct elf_shdr *glue(find_section, SZ)(struct elf_shdr *shdr_table,
60                                                int n, int type)
61 {
62     int i;
63     for(i=0;i<n;i++) {
64         if (shdr_table[i].sh_type == type)
65             return shdr_table + i;
66     }
67     return NULL;
68 }
69 
glue(symfind,SZ)70 static int glue(symfind, SZ)(const void *s0, const void *s1)
71 {
72     hwaddr addr = *(hwaddr *)s0;
73     struct elf_sym *sym = (struct elf_sym *)s1;
74     int result = 0;
75     if (addr < sym->st_value) {
76         result = -1;
77     } else if (addr >= sym->st_value + sym->st_size) {
78         result = 1;
79     }
80     return result;
81 }
82 
glue(lookup_symbol,SZ)83 static const char *glue(lookup_symbol, SZ)(struct syminfo *s,
84                                            hwaddr orig_addr)
85 {
86     struct elf_sym *syms = glue(s->disas_symtab.elf, SZ);
87     struct elf_sym *sym;
88 
89     sym = bsearch(&orig_addr, syms, s->disas_num_syms, sizeof(*syms),
90                   glue(symfind, SZ));
91     if (sym != NULL) {
92         return s->disas_strtab + sym->st_name;
93     }
94 
95     return "";
96 }
97 
glue(symcmp,SZ)98 static int glue(symcmp, SZ)(const void *s0, const void *s1)
99 {
100     struct elf_sym *sym0 = (struct elf_sym *)s0;
101     struct elf_sym *sym1 = (struct elf_sym *)s1;
102     return (sym0->st_value < sym1->st_value)
103         ? -1
104         : ((sym0->st_value > sym1->st_value) ? 1 : 0);
105 }
106 
glue(load_symbols,SZ)107 static int glue(load_symbols, SZ)(struct elfhdr *ehdr, int fd, int must_swab,
108                                   int clear_lsb, symbol_fn_t sym_cb)
109 {
110     struct elf_shdr *symtab, *strtab, *shdr_table = NULL;
111     struct elf_sym *syms = NULL;
112     struct syminfo *s;
113     int nsyms, i;
114     char *str = NULL;
115 
116     shdr_table = load_at(fd, ehdr->e_shoff,
117                          sizeof(struct elf_shdr) * ehdr->e_shnum);
118     if (!shdr_table)
119         return -1;
120 
121     if (must_swab) {
122         for (i = 0; i < ehdr->e_shnum; i++) {
123             glue(bswap_shdr, SZ)(shdr_table + i);
124         }
125     }
126 
127     symtab = glue(find_section, SZ)(shdr_table, ehdr->e_shnum, SHT_SYMTAB);
128     if (!symtab)
129         goto fail;
130     syms = load_at(fd, symtab->sh_offset, symtab->sh_size);
131     if (!syms)
132         goto fail;
133 
134     nsyms = symtab->sh_size / sizeof(struct elf_sym);
135 
136     /* String table */
137     if (symtab->sh_link >= ehdr->e_shnum) {
138         goto fail;
139     }
140     strtab = &shdr_table[symtab->sh_link];
141 
142     str = load_at(fd, strtab->sh_offset, strtab->sh_size);
143     if (!str) {
144         goto fail;
145     }
146 
147     i = 0;
148     while (i < nsyms) {
149         if (must_swab) {
150             glue(bswap_sym, SZ)(&syms[i]);
151         }
152         if (sym_cb) {
153             sym_cb(str + syms[i].st_name, syms[i].st_info,
154                    syms[i].st_value, syms[i].st_size);
155         }
156         /* We are only interested in function symbols.
157            Throw everything else away.  */
158         if (syms[i].st_shndx == SHN_UNDEF ||
159                 syms[i].st_shndx >= SHN_LORESERVE ||
160                 ELF_ST_TYPE(syms[i].st_info) != STT_FUNC) {
161             nsyms--;
162             if (i < nsyms) {
163                 syms[i] = syms[nsyms];
164             }
165             continue;
166         }
167         if (clear_lsb) {
168             /* The bottom address bit marks a Thumb or MIPS16 symbol.  */
169             syms[i].st_value &= ~(glue(glue(Elf, SZ), _Addr))1;
170         }
171         i++;
172     }
173     syms = g_realloc(syms, nsyms * sizeof(*syms));
174 
175     qsort(syms, nsyms, sizeof(*syms), glue(symcmp, SZ));
176     for (i = 0; i < nsyms - 1; i++) {
177         if (syms[i].st_size == 0) {
178             syms[i].st_size = syms[i + 1].st_value - syms[i].st_value;
179         }
180     }
181 
182     /* Commit */
183     s = g_malloc0(sizeof(*s));
184     s->lookup_symbol = glue(lookup_symbol, SZ);
185     glue(s->disas_symtab.elf, SZ) = syms;
186     s->disas_num_syms = nsyms;
187     s->disas_strtab = str;
188     s->next = syminfos;
189     syminfos = s;
190     g_free(shdr_table);
191     return 0;
192  fail:
193     g_free(syms);
194     g_free(str);
195     g_free(shdr_table);
196     return -1;
197 }
198 
glue(elf_reloc,SZ)199 static int glue(elf_reloc, SZ)(struct elfhdr *ehdr, int fd, int must_swab,
200                                uint64_t (*translate_fn)(void *, uint64_t),
201                                void *translate_opaque, uint8_t *data,
202                                struct elf_phdr *ph, int elf_machine)
203 {
204     struct elf_shdr *reltab, *shdr_table = NULL;
205     struct elf_rela *rels = NULL;
206     int nrels, i, ret = -1;
207     elf_word wordval;
208     void *addr;
209 
210     shdr_table = load_at(fd, ehdr->e_shoff,
211                          sizeof(struct elf_shdr) * ehdr->e_shnum);
212     if (!shdr_table) {
213         return -1;
214     }
215     if (must_swab) {
216         for (i = 0; i < ehdr->e_shnum; i++) {
217             glue(bswap_shdr, SZ)(&shdr_table[i]);
218         }
219     }
220 
221     reltab = glue(find_section, SZ)(shdr_table, ehdr->e_shnum, SHT_RELA);
222     if (!reltab) {
223         goto fail;
224     }
225     rels = load_at(fd, reltab->sh_offset, reltab->sh_size);
226     if (!rels) {
227         goto fail;
228     }
229     nrels = reltab->sh_size / sizeof(struct elf_rela);
230 
231     for (i = 0; i < nrels; i++) {
232         if (must_swab) {
233             glue(bswap_rela, SZ)(&rels[i]);
234         }
235         if (rels[i].r_offset < ph->p_vaddr ||
236             rels[i].r_offset >= ph->p_vaddr + ph->p_filesz) {
237             continue;
238         }
239         addr = &data[rels[i].r_offset - ph->p_vaddr];
240         switch (elf_machine) {
241         case EM_S390:
242             switch (rels[i].r_info) {
243             case R_390_RELATIVE:
244                 wordval = *(elf_word *)addr;
245                 if (must_swab) {
246                     bswapSZs(&wordval);
247                 }
248                 wordval = translate_fn(translate_opaque, wordval);
249                 if (must_swab) {
250                     bswapSZs(&wordval);
251                 }
252                 *(elf_word *)addr = wordval;
253                 break;
254             default:
255                 fprintf(stderr, "Unsupported relocation type %i!\n",
256                         (int)rels[i].r_info);
257             }
258         }
259     }
260 
261     ret = 0;
262 fail:
263     g_free(rels);
264     g_free(shdr_table);
265     return ret;
266 }
267 
268 /*
269  * Given 'nhdr', a pointer to a range of ELF Notes, search through them
270  * for a note matching type 'elf_note_type' and return a pointer to
271  * the matching ELF note.
272  */
glue(get_elf_note_type,SZ)273 static struct elf_note *glue(get_elf_note_type, SZ)(struct elf_note *nhdr,
274                                                     elf_word note_size,
275                                                     elf_word phdr_align,
276                                                     elf_word elf_note_type)
277 {
278     elf_word nhdr_size = sizeof(struct elf_note);
279     elf_word elf_note_entry_offset = 0;
280     elf_word note_type;
281     elf_word nhdr_namesz;
282     elf_word nhdr_descsz;
283 
284     if (nhdr == NULL) {
285         return NULL;
286     }
287 
288     note_type = nhdr->n_type;
289     while (note_type != elf_note_type) {
290         nhdr_namesz = nhdr->n_namesz;
291         nhdr_descsz = nhdr->n_descsz;
292 
293         elf_note_entry_offset = nhdr_size +
294             QEMU_ALIGN_UP(nhdr_namesz, phdr_align) +
295             QEMU_ALIGN_UP(nhdr_descsz, phdr_align);
296 
297         /*
298          * If the offset calculated in this iteration exceeds the
299          * supplied size, we are done and no matching note was found.
300          */
301         if (elf_note_entry_offset > note_size) {
302             return NULL;
303         }
304 
305         /* skip to the next ELF Note entry */
306         nhdr = (void *)nhdr + elf_note_entry_offset;
307         note_type = nhdr->n_type;
308     }
309 
310     return nhdr;
311 }
312 
glue(load_elf,SZ)313 static int glue(load_elf, SZ)(const char *name, int fd,
314                               uint64_t (*elf_note_fn)(void *, void *, bool),
315                               uint64_t (*translate_fn)(void *, uint64_t),
316                               void *translate_opaque,
317                               int must_swab, uint64_t *pentry,
318                               uint64_t *lowaddr, uint64_t *highaddr,
319                               int elf_machine, int clear_lsb, int data_swab,
320                               AddressSpace *as, bool load_rom,
321                               symbol_fn_t sym_cb)
322 {
323     struct elfhdr ehdr;
324     struct elf_phdr *phdr = NULL, *ph;
325     int size, i, total_size;
326     elf_word mem_size, file_size, data_offset;
327     uint64_t addr, low = (uint64_t)-1, high = 0;
328     GMappedFile *mapped_file = NULL;
329     uint8_t *data = NULL;
330     char label[128];
331     int ret = ELF_LOAD_FAILED;
332 
333     if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr))
334         goto fail;
335     if (must_swab) {
336         glue(bswap_ehdr, SZ)(&ehdr);
337     }
338 
339     if (elf_machine <= EM_NONE) {
340         /* The caller didn't specify an ARCH, we can figure it out */
341         elf_machine = ehdr.e_machine;
342     }
343 
344     switch (elf_machine) {
345         case EM_PPC64:
346             if (ehdr.e_machine != EM_PPC64) {
347                 if (ehdr.e_machine != EM_PPC) {
348                     ret = ELF_LOAD_WRONG_ARCH;
349                     goto fail;
350                 }
351             }
352             break;
353         case EM_X86_64:
354             if (ehdr.e_machine != EM_X86_64) {
355                 if (ehdr.e_machine != EM_386) {
356                     ret = ELF_LOAD_WRONG_ARCH;
357                     goto fail;
358                 }
359             }
360             break;
361         case EM_MICROBLAZE:
362             if (ehdr.e_machine != EM_MICROBLAZE) {
363                 if (ehdr.e_machine != EM_MICROBLAZE_OLD) {
364                     ret = ELF_LOAD_WRONG_ARCH;
365                     goto fail;
366                 }
367             }
368             break;
369         case EM_MOXIE:
370             if (ehdr.e_machine != EM_MOXIE) {
371                 if (ehdr.e_machine != EM_MOXIE_OLD) {
372                     ret = ELF_LOAD_WRONG_ARCH;
373                     goto fail;
374                 }
375             }
376             break;
377         case EM_MIPS:
378         case EM_NANOMIPS:
379             if ((ehdr.e_machine != EM_MIPS) &&
380                 (ehdr.e_machine != EM_NANOMIPS)) {
381                 ret = ELF_LOAD_WRONG_ARCH;
382                 goto fail;
383             }
384             break;
385         default:
386             if (elf_machine != ehdr.e_machine) {
387                 ret = ELF_LOAD_WRONG_ARCH;
388                 goto fail;
389             }
390     }
391 
392     if (pentry)
393         *pentry = (uint64_t)(elf_sword)ehdr.e_entry;
394 
395     glue(load_symbols, SZ)(&ehdr, fd, must_swab, clear_lsb, sym_cb);
396 
397     size = ehdr.e_phnum * sizeof(phdr[0]);
398     if (lseek(fd, ehdr.e_phoff, SEEK_SET) != ehdr.e_phoff) {
399         goto fail;
400     }
401     phdr = g_malloc0(size);
402     if (!phdr)
403         goto fail;
404     if (read(fd, phdr, size) != size)
405         goto fail;
406     if (must_swab) {
407         for(i = 0; i < ehdr.e_phnum; i++) {
408             ph = &phdr[i];
409             glue(bswap_phdr, SZ)(ph);
410         }
411     }
412 
413     /*
414      * Since we want to be able to modify the mapped buffer, we set the
415      * 'writeble' parameter to 'true'. Modifications to the buffer are not
416      * written back to the file.
417      */
418     mapped_file = g_mapped_file_new_from_fd(fd, true, NULL);
419     if (!mapped_file) {
420         goto fail;
421     }
422 
423     total_size = 0;
424     for(i = 0; i < ehdr.e_phnum; i++) {
425         ph = &phdr[i];
426         if (ph->p_type == PT_LOAD) {
427             mem_size = ph->p_memsz; /* Size of the ROM */
428             file_size = ph->p_filesz; /* Size of the allocated data */
429             data_offset = ph->p_offset; /* Offset where the data is located */
430 
431             if (file_size > 0) {
432                 if (g_mapped_file_get_length(mapped_file) <
433                     file_size + data_offset) {
434                     goto fail;
435                 }
436 
437                 data = (uint8_t *)g_mapped_file_get_contents(mapped_file);
438                 data += data_offset;
439             }
440 
441             /* The ELF spec is somewhat vague about the purpose of the
442              * physical address field. One common use in the embedded world
443              * is that physical address field specifies the load address
444              * and the virtual address field specifies the execution address.
445              * Segments are packed into ROM or flash, and the relocation
446              * and zero-initialization of data is done at runtime. This
447              * means that the memsz header represents the runtime size of the
448              * segment, but the filesz represents the loadtime size. If
449              * we try to honour the memsz value for an ELF file like this
450              * we will end up with overlapping segments (which the
451              * loader.c code will later reject).
452              * We support ELF files using this scheme by by checking whether
453              * paddr + memsz for this segment would overlap with any other
454              * segment. If so, then we assume it's using this scheme and
455              * truncate the loaded segment to the filesz size.
456              * If the segment considered as being memsz size doesn't overlap
457              * then we use memsz for the segment length, to handle ELF files
458              * which assume that the loader will do the zero-initialization.
459              */
460             if (mem_size > file_size) {
461                 /* If this segment's zero-init portion overlaps another
462                  * segment's data or zero-init portion, then truncate this one.
463                  * Invalid ELF files where the segments overlap even when
464                  * only file_size bytes are loaded will be rejected by
465                  * the ROM overlap check in loader.c, so we don't try to
466                  * explicitly detect those here.
467                  */
468                 int j;
469                 elf_word zero_start = ph->p_paddr + file_size;
470                 elf_word zero_end = ph->p_paddr + mem_size;
471 
472                 for (j = 0; j < ehdr.e_phnum; j++) {
473                     struct elf_phdr *jph = &phdr[j];
474 
475                     if (i != j && jph->p_type == PT_LOAD) {
476                         elf_word other_start = jph->p_paddr;
477                         elf_word other_end = jph->p_paddr + jph->p_memsz;
478 
479                         if (!(other_start >= zero_end ||
480                               zero_start >= other_end)) {
481                             mem_size = file_size;
482                             break;
483                         }
484                     }
485                 }
486             }
487 
488             if (mem_size > INT_MAX - total_size) {
489                 ret = ELF_LOAD_TOO_BIG;
490                 goto fail;
491             }
492 
493             /* address_offset is hack for kernel images that are
494                linked at the wrong physical address.  */
495             if (translate_fn) {
496                 addr = translate_fn(translate_opaque, ph->p_paddr);
497                 glue(elf_reloc, SZ)(&ehdr, fd, must_swab,  translate_fn,
498                                     translate_opaque, data, ph, elf_machine);
499             } else {
500                 addr = ph->p_paddr;
501             }
502 
503             if (data_swab) {
504                 int j;
505                 for (j = 0; j < file_size; j += (1 << data_swab)) {
506                     uint8_t *dp = data + j;
507                     switch (data_swab) {
508                     case (1):
509                         *(uint16_t *)dp = bswap16(*(uint16_t *)dp);
510                         break;
511                     case (2):
512                         *(uint32_t *)dp = bswap32(*(uint32_t *)dp);
513                         break;
514                     case (3):
515                         *(uint64_t *)dp = bswap64(*(uint64_t *)dp);
516                         break;
517                     default:
518                         g_assert_not_reached();
519                     }
520                 }
521             }
522 
523             /* the entry pointer in the ELF header is a virtual
524              * address, if the text segments paddr and vaddr differ
525              * we need to adjust the entry */
526             if (pentry && !translate_fn &&
527                     ph->p_vaddr != ph->p_paddr &&
528                     ehdr.e_entry >= ph->p_vaddr &&
529                     ehdr.e_entry < ph->p_vaddr + ph->p_filesz &&
530                     ph->p_flags & PF_X) {
531                 *pentry = ehdr.e_entry - ph->p_vaddr + ph->p_paddr;
532             }
533 
534             /* Some ELF files really do have segments of zero size;
535              * just ignore them rather than trying to create empty
536              * ROM blobs, because the zero-length blob can falsely
537              * trigger the overlapping-ROM-blobs check.
538              */
539             if (mem_size != 0) {
540                 if (load_rom) {
541                     snprintf(label, sizeof(label), "phdr #%d: %s", i, name);
542 
543                     /*
544                      * rom_add_elf_program() takes its own reference to
545                      * 'mapped_file'.
546                      */
547                     rom_add_elf_program(label, mapped_file, data, file_size,
548                                         mem_size, addr, as);
549                 } else {
550                     address_space_write(as ? as : &address_space_memory,
551                                         addr, MEMTXATTRS_UNSPECIFIED,
552                                         data, file_size);
553                 }
554             }
555 
556             total_size += mem_size;
557             if (addr < low)
558                 low = addr;
559             if ((addr + mem_size) > high)
560                 high = addr + mem_size;
561 
562             data = NULL;
563 
564         } else if (ph->p_type == PT_NOTE && elf_note_fn) {
565             struct elf_note *nhdr = NULL;
566 
567             file_size = ph->p_filesz; /* Size of the range of ELF notes */
568             data_offset = ph->p_offset; /* Offset where the notes are located */
569 
570             if (file_size > 0) {
571                 if (g_mapped_file_get_length(mapped_file) <
572                     file_size + data_offset) {
573                     goto fail;
574                 }
575 
576                 data = (uint8_t *)g_mapped_file_get_contents(mapped_file);
577                 data += data_offset;
578             }
579 
580             /*
581              * Search the ELF notes to find one with a type matching the
582              * value passed in via 'translate_opaque'
583              */
584             nhdr = (struct elf_note *)data;
585             assert(translate_opaque != NULL);
586             nhdr = glue(get_elf_note_type, SZ)(nhdr, file_size, ph->p_align,
587                                                *(uint64_t *)translate_opaque);
588             if (nhdr != NULL) {
589                 bool is64 =
590                     sizeof(struct elf_note) == sizeof(struct elf64_note);
591                 elf_note_fn((void *)nhdr, (void *)&ph->p_align, is64);
592             }
593             data = NULL;
594         }
595     }
596 
597     if (lowaddr)
598         *lowaddr = (uint64_t)(elf_sword)low;
599     if (highaddr)
600         *highaddr = (uint64_t)(elf_sword)high;
601     ret = total_size;
602  fail:
603     g_mapped_file_unref(mapped_file);
604     g_free(phdr);
605     return ret;
606 }
607