blob: 45e96fd850d3d5b41ba3255e3e2f80e674b9935c [file] [log] [blame]
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -08001/*
2 * elf header parsing.
3 *
4 * Copyright (C) 2013 Google, Inc.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
Patrick Georgib890a122015-03-26 15:17:45 +010017 * Foundation, Inc.
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -080018 */
19
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23
Aaron Durbin54ef3062014-03-05 12:12:09 -060024#include "elfparsing.h"
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -080025#include "common.h"
26#include "cbfs.h"
27
28/*
29 * Short form: this is complicated, but we've tried making it simple
30 * and we keep hitting problems with our ELF parsing.
31 *
32 * The ELF parsing situation has always been a bit tricky. In fact,
33 * we (and most others) have been getting it wrong in small ways for
34 * years. Recently this has caused real trouble for the ARM V8 build.
35 * In this file we attempt to finally get it right for all variations
36 * of endian-ness and word size and target architectures and
37 * architectures we might get run on. Phew!. To do this we borrow a
38 * page from the FreeBSD NFS xdr model (see elf_ehdr and elf_phdr),
39 * the Plan 9 endianness functions (see xdr.c), and Go interfaces (see
40 * how we use buffer structs in this file). This ends up being a bit
41 * wordy at the lowest level, but greatly simplifies the elf parsing
42 * code and removes a common source of bugs, namely, forgetting to
43 * flip type endianness when referencing a struct member.
44 *
45 * ELF files can have four combinations of data layout: 32/64, and
46 * big/little endian. Further, to add to the fun, depending on the
47 * word size, the size of the ELF structs varies. The coreboot SELF
48 * format is simpler in theory: it's supposed to be always BE, and the
49 * various struct members allow room for growth: the entry point is
50 * always 64 bits, for example, so the size of a SELF struct is
51 * constant, regardless of target architecture word size. Hence, we
52 * need to do some transformation of the ELF files.
53 *
54 * A given architecture, realistically, only supports one of the four
55 * combinations at a time as the 'native' format. Hence, our code has
56 * been sprinkled with every variation of [nh]to[hn][sll] over the
57 * years. We've never quite gotten it all right, however, and a quick
58 * pass over this code revealed another bug. It's all worked because,
59 * until now, all the working platforms that had CBFS were 32 LE. Even then,
60 * however, bugs crept in: we recently realized that we're not
61 * transforming the entry point to big format when we store into the
62 * SELF image.
63 *
64 * The problem is essentially an XDR operation:
65 * we have something in a foreign format and need to transform it.
66 * It's most like XDR because:
67 * 1) the byte order can be wrong
68 * 2) the word size can be wrong
69 * 3) the size of elements in the stream depends on the value
70 * of other elements in the stream
71 * it's not like XDR because:
72 * 1) the byte order can be right
73 * 2) the word size can be right
74 * 3) the struct members are all on a natural alignment
75 *
76 * Hence, this new approach. To cover word size issues, we *always*
77 * transform the two structs we care about, the file header and
78 * program header, into a native struct in the 64 bit format:
79 *
80 * [32,little] -> [Elf64_Ehdr, Elf64_Phdr]
81 * [64,little] -> [Elf64_Ehdr, Elf64_Phdr]
82 * [32,big] -> [Elf64_Ehdr, Elf64_Phdr]
83 * [64,big] -> [Elf64_Ehdr, Elf64_Phdr]
84 * Then we just use those structs, and all the need for inline ntoh* goes away,
85 * as well as all the chances for error.
86 * This works because all the SELF structs have fields large enough for
87 * the largest ELF 64 struct members, and all the Elf64 struct members
88 * are at least large enough for all ELF 32 struct members.
89 * We end up with one function to do all our ELF parsing, and two functions
90 * to transform the headers. For the put case, we also have
91 * XDR functions, and hopefully we'll never again spend 5 years with the
92 * wrong endian-ness on an output value :-)
93 * This should work for all word sizes and endianness we hope to target.
94 * I *really* don't want to be here for 128 bit addresses.
95 *
96 * The parse functions are called with a pointer to an input buffer
97 * struct. One might ask: are there enough bytes in the input buffer?
98 * We know there need to be at *least* sizeof(Elf32_Ehdr) +
99 * sizeof(Elf32_Phdr) bytes. Realistically, there has to be some data
100 * too. If we start to worry, though we have not in the past, we
101 * might apply the simple test: the input buffer needs to be at least
102 * sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr) bytes because, even if it's
103 * ELF 32, there's got to be *some* data! This is not theoretically
104 * accurate but it is actually good enough in practice. It allows the
105 * header transformation code to ignore the possibility of underrun.
106 *
107 * We also must accomodate different ELF files, and hence formats,
108 * in the same cbfs invocation. We might load a 64-bit payload
109 * on a 32-bit machine; we might even have a mixed armv7/armv8
110 * SOC or even a system with an x86/ARM!
111 *
112 * A possibly problematic (though unlikely to be so) assumption
113 * is that we expect the BIOS to remain in the lowest 32 bits
114 * of the physical address space. Since ARMV8 has standardized
115 * on that, and x86_64 also has, this seems a safe assumption.
116 *
117 * To repeat, ELF structs are different sizes because ELF struct
118 * members are different sizes, depending on values in the ELF file
119 * header. For this we use the functions defined in xdr.c, which
120 * consume bytes, convert the endianness, and advance the data pointer
121 * in the buffer struct.
122 */
123
Aaron Durbinaa8784c2014-03-05 12:01:36 -0600124
125static int iself(const void *input)
126{
127 const Elf32_Ehdr *ehdr = input;
128 return !memcmp(ehdr->e_ident, ELFMAG, 4);
129}
130
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800131/* Get the ident array, so we can figure out
132 * endian-ness, word size, and in future other useful
133 * parameters
134 */
135static void
136elf_eident(struct buffer *input, Elf64_Ehdr *ehdr)
137{
Aaron Durbina983cea2014-03-04 22:08:05 -0600138 bgets(input, ehdr->e_ident, sizeof(ehdr->e_ident));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800139}
140
141
Aaron Durbina983cea2014-03-04 22:08:05 -0600142static int
143check_size(const struct buffer *b, size_t offset, size_t size, const char *desc)
144{
145 if (size == 0)
146 return 0;
147
148 if (offset >= buffer_size(b) || (offset + size) > buffer_size(b)) {
149 ERROR("The file is not large enough for the '%s'. "
Paul Menzel470c37c2014-03-16 00:15:57 +0100150 "%zu bytes @ offset %zu, input %zu bytes.\n",
Aaron Durbina983cea2014-03-04 22:08:05 -0600151 desc, size, offset, buffer_size(b));
152 return -1;
153 }
154 return 0;
155}
156
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800157static void
158elf_ehdr(struct buffer *input, Elf64_Ehdr *ehdr, struct xdr *xdr, int bit64)
159{
160 ehdr->e_type = xdr->get16(input);
161 ehdr->e_machine = xdr->get16(input);
162 ehdr->e_version = xdr->get32(input);
163 if (bit64){
164 ehdr->e_entry = xdr->get64(input);
165 ehdr->e_phoff = xdr->get64(input);
166 ehdr->e_shoff = xdr->get64(input);
167 } else {
168 ehdr->e_entry = xdr->get32(input);
169 ehdr->e_phoff = xdr->get32(input);
170 ehdr->e_shoff = xdr->get32(input);
171 }
172 ehdr->e_flags = xdr->get32(input);
173 ehdr->e_ehsize = xdr->get16(input);
174 ehdr->e_phentsize = xdr->get16(input);
175 ehdr->e_phnum = xdr->get16(input);
176 ehdr->e_shentsize = xdr->get16(input);
177 ehdr->e_shnum = xdr->get16(input);
178 ehdr->e_shstrndx = xdr->get16(input);
179}
180
181static void
182elf_phdr(struct buffer *pinput, Elf64_Phdr *phdr,
183 int entsize, struct xdr *xdr, int bit64)
184{
185 /*
186 * The entsize need not be sizeof(*phdr).
187 * Hence, it is easier to keep a copy of the input,
188 * as the xdr functions may not advance the input
189 * pointer the full entsize; rather than get tricky
190 * we just advance it below.
191 */
Aaron Durbina983cea2014-03-04 22:08:05 -0600192 struct buffer input;
193 buffer_clone(&input, pinput);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800194 if (bit64){
195 phdr->p_type = xdr->get32(&input);
196 phdr->p_flags = xdr->get32(&input);
197 phdr->p_offset = xdr->get64(&input);
198 phdr->p_vaddr = xdr->get64(&input);
199 phdr->p_paddr = xdr->get64(&input);
200 phdr->p_filesz = xdr->get64(&input);
201 phdr->p_memsz = xdr->get64(&input);
202 phdr->p_align = xdr->get64(&input);
203 } else {
204 phdr->p_type = xdr->get32(&input);
205 phdr->p_offset = xdr->get32(&input);
206 phdr->p_vaddr = xdr->get32(&input);
207 phdr->p_paddr = xdr->get32(&input);
208 phdr->p_filesz = xdr->get32(&input);
209 phdr->p_memsz = xdr->get32(&input);
210 phdr->p_flags = xdr->get32(&input);
211 phdr->p_align = xdr->get32(&input);
212 }
Aaron Durbina983cea2014-03-04 22:08:05 -0600213 buffer_seek(pinput, entsize);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800214}
215
216static void
217elf_shdr(struct buffer *pinput, Elf64_Shdr *shdr,
218 int entsize, struct xdr *xdr, int bit64)
219{
220 /*
221 * The entsize need not be sizeof(*shdr).
222 * Hence, it is easier to keep a copy of the input,
223 * as the xdr functions may not advance the input
224 * pointer the full entsize; rather than get tricky
225 * we just advance it below.
226 */
227 struct buffer input = *pinput;
228 if (bit64){
229 shdr->sh_name = xdr->get32(&input);
230 shdr->sh_type = xdr->get32(&input);
231 shdr->sh_flags = xdr->get64(&input);
232 shdr->sh_addr = xdr->get64(&input);
233 shdr->sh_offset = xdr->get64(&input);
234 shdr->sh_size= xdr->get64(&input);
235 shdr->sh_link = xdr->get32(&input);
236 shdr->sh_info = xdr->get32(&input);
237 shdr->sh_addralign = xdr->get64(&input);
238 shdr->sh_entsize = xdr->get64(&input);
239 } else {
240 shdr->sh_name = xdr->get32(&input);
241 shdr->sh_type = xdr->get32(&input);
242 shdr->sh_flags = xdr->get32(&input);
243 shdr->sh_addr = xdr->get32(&input);
244 shdr->sh_offset = xdr->get32(&input);
245 shdr->sh_size = xdr->get32(&input);
246 shdr->sh_link = xdr->get32(&input);
247 shdr->sh_info = xdr->get32(&input);
248 shdr->sh_addralign = xdr->get32(&input);
249 shdr->sh_entsize = xdr->get32(&input);
250 }
Aaron Durbina983cea2014-03-04 22:08:05 -0600251 buffer_seek(pinput, entsize);
252}
253
Aaron Durbind0f61652014-03-05 13:09:55 -0600254static int
255phdr_read(const struct buffer *in, struct parsed_elf *pelf,
256 struct xdr *xdr, int bit64)
Aaron Durbina983cea2014-03-04 22:08:05 -0600257{
258 struct buffer b;
259 Elf64_Phdr *phdr;
Aaron Durbind0f61652014-03-05 13:09:55 -0600260 Elf64_Ehdr *ehdr;
Aaron Durbina983cea2014-03-04 22:08:05 -0600261 int i;
262
Aaron Durbind0f61652014-03-05 13:09:55 -0600263 ehdr = &pelf->ehdr;
Aaron Durbina983cea2014-03-04 22:08:05 -0600264 /* cons up an input buffer for the headers.
265 * Note that the program headers can be anywhere,
266 * per the ELF spec, You'd be surprised how many ELF
267 * readers miss this little detail.
268 */
269 buffer_splice(&b, in, ehdr->e_phoff, ehdr->e_phentsize * ehdr->e_phnum);
270 if (check_size(in, ehdr->e_phoff, buffer_size(&b), "program headers"))
Aaron Durbind0f61652014-03-05 13:09:55 -0600271 return -1;
Aaron Durbina983cea2014-03-04 22:08:05 -0600272
273 /* gather up all the phdrs.
274 * We do them all at once because there is more
275 * than one loop over all the phdrs.
276 */
Aaron Durbinb1b51182014-03-05 14:54:13 -0600277 phdr = calloc(ehdr->e_phnum, sizeof(*phdr));
Aaron Durbina31ff732014-03-07 15:23:05 -0600278 for (i = 0; i < ehdr->e_phnum; i++) {
279 DEBUG("Parsing segment %d\n", i);
Aaron Durbina983cea2014-03-04 22:08:05 -0600280 elf_phdr(&b, &phdr[i], ehdr->e_phentsize, xdr, bit64);
281
Aaron Durbina31ff732014-03-07 15:23:05 -0600282 /* Ensure the contents are valid within the elf file. */
283 if (check_size(in, phdr[i].p_offset, phdr[i].p_filesz,
Patrick Georgia65c21e2014-08-09 16:58:00 +0200284 "segment contents")) {
285 free(phdr);
Aaron Durbind0f61652014-03-05 13:09:55 -0600286 return -1;
Patrick Georgia65c21e2014-08-09 16:58:00 +0200287 }
Aaron Durbina31ff732014-03-07 15:23:05 -0600288 }
289
Aaron Durbind0f61652014-03-05 13:09:55 -0600290 pelf->phdr = phdr;
291
292 return 0;
Aaron Durbina983cea2014-03-04 22:08:05 -0600293}
294
Aaron Durbind0f61652014-03-05 13:09:55 -0600295static int
296shdr_read(const struct buffer *in, struct parsed_elf *pelf,
297 struct xdr *xdr, int bit64)
Aaron Durbina983cea2014-03-04 22:08:05 -0600298{
299 struct buffer b;
300 Elf64_Shdr *shdr;
Aaron Durbind0f61652014-03-05 13:09:55 -0600301 Elf64_Ehdr *ehdr;
Aaron Durbina983cea2014-03-04 22:08:05 -0600302 int i;
303
Aaron Durbind0f61652014-03-05 13:09:55 -0600304 ehdr = &pelf->ehdr;
305
Aaron Durbina983cea2014-03-04 22:08:05 -0600306 /* cons up an input buffer for the section headers.
307 * Note that the section headers can be anywhere,
308 * per the ELF spec, You'd be surprised how many ELF
309 * readers miss this little detail.
310 */
311 buffer_splice(&b, in, ehdr->e_shoff, ehdr->e_shentsize * ehdr->e_shnum);
312 if (check_size(in, ehdr->e_shoff, buffer_size(&b), "section headers"))
Aaron Durbind0f61652014-03-05 13:09:55 -0600313 return -1;
Aaron Durbina983cea2014-03-04 22:08:05 -0600314
315 /* gather up all the shdrs. */
Aaron Durbinb1b51182014-03-05 14:54:13 -0600316 shdr = calloc(ehdr->e_shnum, sizeof(*shdr));
Aaron Durbina31ff732014-03-07 15:23:05 -0600317 for (i = 0; i < ehdr->e_shnum; i++) {
318 DEBUG("Parsing section %d\n", i);
Aaron Durbina983cea2014-03-04 22:08:05 -0600319 elf_shdr(&b, &shdr[i], ehdr->e_shentsize, xdr, bit64);
Aaron Durbina31ff732014-03-07 15:23:05 -0600320 }
321
Aaron Durbind0f61652014-03-05 13:09:55 -0600322 pelf->shdr = shdr;
323
324 return 0;
325}
326
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600327static int
328reloc_read(const struct buffer *in, struct parsed_elf *pelf,
329 struct xdr *xdr, int bit64)
330{
331 struct buffer b;
332 Elf64_Word i;
333 Elf64_Ehdr *ehdr;
334
335 ehdr = &pelf->ehdr;
336 pelf->relocs = calloc(ehdr->e_shnum, sizeof(Elf64_Rela *));
337
338 /* Allocate array for each section that contains relocation entries. */
339 for (i = 0; i < ehdr->e_shnum; i++) {
340 Elf64_Shdr *shdr;
341 Elf64_Rela *rela;
342 Elf64_Xword j;
343 Elf64_Xword nrelocs;
344 int is_rela;
345
346 shdr = &pelf->shdr[i];
347
348 /* Only process REL and RELA sections. */
349 if (shdr->sh_type != SHT_REL && shdr->sh_type != SHT_RELA)
350 continue;
351
352 DEBUG("Checking relocation section %u\n", i);
353
354 /* Ensure the section that relocations apply is a valid. */
355 if (shdr->sh_info >= ehdr->e_shnum ||
356 shdr->sh_info == SHN_UNDEF) {
357 ERROR("Relocations apply to an invalid section: %u\n",
358 shdr[i].sh_info);
359 return -1;
360 }
361
362 is_rela = shdr->sh_type == SHT_RELA;
363
364 /* Determine the number relocations in this section. */
365 nrelocs = shdr->sh_size / shdr->sh_entsize;
366
367 pelf->relocs[i] = calloc(nrelocs, sizeof(Elf64_Rela));
368
369 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
370 if (check_size(in, shdr->sh_offset, buffer_size(&b),
371 "relocation section")) {
372 ERROR("Relocation section %u failed.\n", i);
373 return -1;
374 }
375
376 rela = pelf->relocs[i];
377 for (j = 0; j < nrelocs; j++) {
378 if (bit64) {
379 rela->r_offset = xdr->get64(&b);
380 rela->r_info = xdr->get64(&b);
381 if (is_rela)
382 rela->r_addend = xdr->get64(&b);
383 } else {
384 uint32_t r_info;
385
386 rela->r_offset = xdr->get32(&b);
387 r_info = xdr->get32(&b);
388 rela->r_info = ELF64_R_INFO(ELF32_R_SYM(r_info),
389 ELF32_R_TYPE(r_info));
390 if (is_rela)
391 rela->r_addend = xdr->get32(&b);
392 }
393 rela++;
394 }
395 }
396
397 return 0;
398}
399
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600400static int strtab_read(const struct buffer *in, struct parsed_elf *pelf)
401{
402 Elf64_Ehdr *ehdr;
403 Elf64_Word i;
404
405 ehdr = &pelf->ehdr;
406
407 if (ehdr->e_shstrndx >= ehdr->e_shnum) {
408 ERROR("Section header string table index out of range: %d\n",
409 ehdr->e_shstrndx);
410 return -1;
411 }
412
413 /* For each section of type SHT_STRTAB create a symtab buffer. */
414 pelf->strtabs = calloc(ehdr->e_shnum, sizeof(struct buffer *));
415
416 for (i = 0; i < ehdr->e_shnum; i++) {
417 struct buffer *b;
418 Elf64_Shdr *shdr = &pelf->shdr[i];
419
420 if (shdr->sh_type != SHT_STRTAB)
421 continue;
422
423 b = calloc(1, sizeof(*b));
424 buffer_splice(b, in, shdr->sh_offset, shdr->sh_size);
425 if (check_size(in, shdr->sh_offset, buffer_size(b), "strtab")) {
426 ERROR("STRTAB section not within bounds: %d\n", i);
Patrick Georgia65c21e2014-08-09 16:58:00 +0200427 free(b);
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600428 return -1;
429 }
430 pelf->strtabs[i] = b;
431 }
432
433 return 0;
434}
435
Aaron Durbinc0780942014-03-05 16:41:27 -0600436static int
437symtab_read(const struct buffer *in, struct parsed_elf *pelf,
438 struct xdr *xdr, int bit64)
439{
440 Elf64_Ehdr *ehdr;
441 Elf64_Shdr *shdr;
442 Elf64_Half i;
443 Elf64_Xword nsyms;
444 Elf64_Sym *sym;
445 struct buffer b;
446
447 ehdr = &pelf->ehdr;
448
449 shdr = NULL;
450 for (i = 0; i < ehdr->e_shnum; i++) {
451 if (pelf->shdr[i].sh_type != SHT_SYMTAB)
452 continue;
453
454 if (shdr != NULL) {
455 ERROR("Multiple symbol sections found. %u and %u\n",
456 (unsigned int)(shdr - pelf->shdr), i);
457 return -1;
458 }
459
460 shdr = &pelf->shdr[i];
461 }
462
463 if (shdr == NULL) {
464 ERROR("No symbol table found.\n");
465 return -1;
466 }
467
468 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
469 if (check_size(in, shdr->sh_offset, buffer_size(&b), "symtab"))
470 return -1;
471
472 nsyms = shdr->sh_size / shdr->sh_entsize;
473
474 pelf->syms = calloc(nsyms, sizeof(Elf64_Sym));
475
476 for (i = 0; i < nsyms; i++) {
477 sym = &pelf->syms[i];
478
479 if (bit64) {
480 sym->st_name = xdr->get32(&b);
481 sym->st_info = xdr->get8(&b);
482 sym->st_other = xdr->get8(&b);
483 sym->st_shndx = xdr->get16(&b);
484 sym->st_value = xdr->get64(&b);
485 sym->st_size = xdr->get64(&b);
486 } else {
487 sym->st_name = xdr->get32(&b);
488 sym->st_value = xdr->get32(&b);
489 sym->st_size = xdr->get32(&b);
490 sym->st_info = xdr->get8(&b);
491 sym->st_other = xdr->get8(&b);
492 sym->st_shndx = xdr->get16(&b);
493 }
494 }
495
496 return 0;
497}
498
Aaron Durbind0f61652014-03-05 13:09:55 -0600499int parse_elf(const struct buffer *pinput, struct parsed_elf *pelf, int flags)
500{
501 struct xdr *xdr = &xdr_le;
502 int bit64 = 0;
503 struct buffer input;
504 Elf64_Ehdr *ehdr;
505
506 /* Zero out the parsed elf structure. */
507 memset(pelf, 0, sizeof(*pelf));
508
509 if (!iself(buffer_get(pinput))) {
510 ERROR("The stage file is not in ELF format!\n");
511 return -1;
512 }
513
514 buffer_clone(&input, pinput);
515 ehdr = &pelf->ehdr;
516 elf_eident(&input, ehdr);
517 bit64 = ehdr->e_ident[EI_CLASS] == ELFCLASS64;
518 /* Assume LE unless we are sure otherwise.
519 * We're not going to take on the task of
520 * fully validating the ELF file. That way
521 * lies madness.
522 */
523 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
524 xdr = &xdr_be;
525
526 elf_ehdr(&input, ehdr, xdr, bit64);
527
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600528 /* Relocation processing requires section header parsing. */
529 if (flags & ELF_PARSE_RELOC)
530 flags |= ELF_PARSE_SHDR;
531
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600532 /* String table processing requires section header parsing. */
533 if (flags & ELF_PARSE_STRTAB)
534 flags |= ELF_PARSE_SHDR;
535
Aaron Durbinc0780942014-03-05 16:41:27 -0600536 /* Symbole table processing requires section header parsing. */
537 if (flags & ELF_PARSE_SYMTAB)
538 flags |= ELF_PARSE_SHDR;
539
Aaron Durbind0f61652014-03-05 13:09:55 -0600540 if ((flags & ELF_PARSE_PHDR) && phdr_read(pinput, pelf, xdr, bit64))
541 goto fail;
542
543 if ((flags & ELF_PARSE_SHDR) && shdr_read(pinput, pelf, xdr, bit64))
544 goto fail;
545
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600546 if ((flags & ELF_PARSE_RELOC) && reloc_read(pinput, pelf, xdr, bit64))
547 goto fail;
548
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600549 if ((flags & ELF_PARSE_STRTAB) && strtab_read(pinput, pelf))
550 goto fail;
551
Aaron Durbinc0780942014-03-05 16:41:27 -0600552 if ((flags & ELF_PARSE_SYMTAB) && symtab_read(pinput, pelf, xdr, bit64))
553 goto fail;
554
Aaron Durbind0f61652014-03-05 13:09:55 -0600555 return 0;
556
557fail:
558 parsed_elf_destroy(pelf);
559 return -1;
560}
561
562void parsed_elf_destroy(struct parsed_elf *pelf)
563{
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600564 Elf64_Half i;
565
Aaron Durbind0f61652014-03-05 13:09:55 -0600566 free(pelf->phdr);
567 free(pelf->shdr);
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600568 if (pelf->relocs != NULL) {
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600569 for (i = 0; i < pelf->ehdr.e_shnum; i++)
570 free(pelf->relocs[i]);
571 }
572 free(pelf->relocs);
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600573
574 if (pelf->strtabs != NULL) {
575 for (i = 0; i < pelf->ehdr.e_shnum; i++)
576 free(pelf->strtabs[i]);
577 }
578 free(pelf->strtabs);
Aaron Durbinc0780942014-03-05 16:41:27 -0600579 free(pelf->syms);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800580}
581
582/* Get the headers from the buffer.
583 * Return -1 in the event of an error.
584 * The section headers are optional; if NULL
585 * is passed in for pshdr they won't be parsed.
586 * We don't (yet) make payload parsing optional
587 * because we've never seen a use case.
588 */
589int
590elf_headers(const struct buffer *pinput,
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800591 Elf64_Ehdr *ehdr,
592 Elf64_Phdr **pphdr,
593 Elf64_Shdr **pshdr)
594{
Aaron Durbind0f61652014-03-05 13:09:55 -0600595 struct parsed_elf pelf;
596 int flags;
Aaron Durbina983cea2014-03-04 22:08:05 -0600597
Aaron Durbind0f61652014-03-05 13:09:55 -0600598 flags = ELF_PARSE_PHDR;
599
600 if (pshdr != NULL)
601 flags |= ELF_PARSE_SHDR;
602
603 if (parse_elf(pinput, &pelf, flags))
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800604 return -1;
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800605
Aaron Durbind0f61652014-03-05 13:09:55 -0600606 /* Copy out the parsed elf header. */
607 memcpy(ehdr, &pelf.ehdr, sizeof(*ehdr));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800608
Aaron Durbind0f61652014-03-05 13:09:55 -0600609 *pphdr = calloc(ehdr->e_phnum, sizeof(Elf64_Phdr));
610 memcpy(*pphdr, pelf.phdr, ehdr->e_phnum * sizeof(Elf64_Phdr));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800611
Aaron Durbind0f61652014-03-05 13:09:55 -0600612 if (pshdr != NULL) {
613 *pshdr = calloc(ehdr->e_shnum, sizeof(Elf64_Shdr));
614 memcpy(*pshdr, pelf.shdr, ehdr->e_shnum * sizeof(Elf64_Shdr));
615 }
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800616
Aaron Durbind0f61652014-03-05 13:09:55 -0600617 parsed_elf_destroy(&pelf);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800618
619 return 0;
620}
Aaron Durbin36be8132014-03-11 11:48:56 -0500621
622/* ELF Writing Support
623 *
624 * The ELF file is written according to the following layout:
625 * +------------------+
626 * | ELF Header |
627 * +------------------+
628 * | Section Headers |
629 * +------------------+
630 * | Program Headers |
631 * +------------------+
632 * | String table |
633 * +------------------+ <- 4KiB Aligned
634 * | Code/Data |
635 * +------------------+
636 */
637
Aaron Durbin4f930c92015-10-27 16:21:55 -0500638void elf_init_eheader(Elf64_Ehdr *ehdr, int machine, int nbits, int endian)
639{
640 memset(ehdr, 0, sizeof(*ehdr));
641 ehdr->e_ident[EI_MAG0] = ELFMAG0;
642 ehdr->e_ident[EI_MAG1] = ELFMAG1;
643 ehdr->e_ident[EI_MAG2] = ELFMAG2;
644 ehdr->e_ident[EI_MAG3] = ELFMAG3;
645 ehdr->e_ident[EI_CLASS] = nbits;
646 ehdr->e_ident[EI_DATA] = endian;
647 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
648 ehdr->e_type = ET_EXEC;
649 ehdr->e_machine = machine;
650 ehdr->e_version = EV_CURRENT;
651 if (nbits == ELFCLASS64) {
652 ehdr->e_ehsize = sizeof(Elf64_Ehdr);
653 ehdr->e_phentsize = sizeof(Elf64_Phdr);
654 ehdr->e_shentsize = sizeof(Elf64_Shdr);
655 } else {
656 ehdr->e_ehsize = sizeof(Elf32_Ehdr);
657 ehdr->e_phentsize = sizeof(Elf32_Phdr);
658 ehdr->e_shentsize = sizeof(Elf32_Shdr);
659 }
660}
661
Aaron Durbin36be8132014-03-11 11:48:56 -0500662/* Arbitray maximum number of sections. */
663#define MAX_SECTIONS 16
664struct elf_writer_section {
665 Elf64_Shdr shdr;
666 struct buffer content;
667 const char *name;
668};
669
Aaron Durbincedcb882015-10-28 11:26:40 -0500670struct elf_writer_string_table {
671 size_t next_offset;
672 size_t max_size;
673 char *buffer;
674};
675
676struct elf_writer_sym_table {
677 size_t max_entries;
678 size_t num_entries;
679 Elf64_Sym *syms;
680};
681
682#define MAX_REL_NAME 32
683struct elf_writer_rel {
684 size_t num_entries;
685 size_t max_entries;
686 Elf64_Rel *rels;
687 struct elf_writer_section *sec;
688 char name[MAX_REL_NAME];
689};
690
Aaron Durbin36be8132014-03-11 11:48:56 -0500691struct elf_writer
692{
693 Elf64_Ehdr ehdr;
694 struct xdr *xdr;
695 size_t num_secs;
696 struct elf_writer_section sections[MAX_SECTIONS];
Aaron Durbincedcb882015-10-28 11:26:40 -0500697 struct elf_writer_rel rel_sections[MAX_SECTIONS];
Aaron Durbin36be8132014-03-11 11:48:56 -0500698 Elf64_Phdr *phdrs;
Aaron Durbincedcb882015-10-28 11:26:40 -0500699 struct elf_writer_section *shstrtab_sec;
700 struct elf_writer_section *strtab_sec;
701 struct elf_writer_section *symtab_sec;
702 struct elf_writer_string_table strtab;
703 struct elf_writer_sym_table symtab;
Aaron Durbin36be8132014-03-11 11:48:56 -0500704 int bit64;
705};
706
Aaron Durbincedcb882015-10-28 11:26:40 -0500707static size_t section_index(struct elf_writer *ew,
708 struct elf_writer_section *sec)
709{
710 return sec - &ew->sections[0];
711}
712
713static struct elf_writer_section *last_section(struct elf_writer *ew)
714{
715 return &ew->sections[ew->num_secs - 1];
716}
717
718static void strtab_init(struct elf_writer *ew, size_t size)
719{
720 struct buffer b;
721 Elf64_Shdr shdr;
722
723 /* Start adding strings after the initial NUL entry. */
724 ew->strtab.next_offset = 1;
725 ew->strtab.max_size = size;
726 ew->strtab.buffer = calloc(1, ew->strtab.max_size);
727
728 buffer_init(&b, NULL, ew->strtab.buffer, ew->strtab.max_size);
729 memset(&shdr, 0, sizeof(shdr));
730 shdr.sh_type = SHT_STRTAB;
731 shdr.sh_addralign = 1;
732 shdr.sh_size = ew->strtab.max_size;
733 elf_writer_add_section(ew, &shdr, &b, ".strtab");
734 ew->strtab_sec = last_section(ew);
735}
736
737static void symtab_init(struct elf_writer *ew, size_t max_entries)
738{
739 struct buffer b;
740 Elf64_Shdr shdr;
741
742 memset(&shdr, 0, sizeof(shdr));
743 shdr.sh_type = SHT_SYMTAB;
744
745 if (ew->bit64) {
746 shdr.sh_entsize = sizeof(Elf64_Sym);
747 shdr.sh_addralign = sizeof(Elf64_Addr);
748 } else {
749 shdr.sh_entsize = sizeof(Elf32_Sym);
750 shdr.sh_addralign = sizeof(Elf32_Addr);
751 }
752
753 shdr.sh_size = shdr.sh_entsize * max_entries;
754
755 ew->symtab.syms = calloc(max_entries, sizeof(Elf64_Sym));
756 ew->symtab.num_entries = 1;
757 ew->symtab.max_entries = max_entries;
758
759 buffer_init(&b, NULL, ew->symtab.syms, shdr.sh_size);
760
761 elf_writer_add_section(ew, &shdr, &b, ".symtab");
762 ew->symtab_sec = last_section(ew);
763}
764
Aaron Durbin36be8132014-03-11 11:48:56 -0500765struct elf_writer *elf_writer_init(const Elf64_Ehdr *ehdr)
766{
767 struct elf_writer *ew;
768 Elf64_Shdr shdr;
769 struct buffer empty_buffer;
770
771 if (!iself(ehdr))
772 return NULL;
773
774 ew = calloc(1, sizeof(*ew));
775
776 memcpy(&ew->ehdr, ehdr, sizeof(ew->ehdr));
777
778 ew->bit64 = ew->ehdr.e_ident[EI_CLASS] == ELFCLASS64;
779
780 /* Set the endinan ops. */
781 if (ew->ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
782 ew->xdr = &xdr_be;
783 else
784 ew->xdr = &xdr_le;
785
786 /* Reset count and offsets */
787 ew->ehdr.e_phoff = 0;
788 ew->ehdr.e_shoff = 0;
789 ew->ehdr.e_shnum = 0;
790 ew->ehdr.e_phnum = 0;
791
792 memset(&empty_buffer, 0, sizeof(empty_buffer));
793 memset(&shdr, 0, sizeof(shdr));
794
795 /* Add SHT_NULL section header. */
796 shdr.sh_type = SHT_NULL;
797 elf_writer_add_section(ew, &shdr, &empty_buffer, NULL);
798
799 /* Add section header string table and maintain reference to it. */
800 shdr.sh_type = SHT_STRTAB;
801 elf_writer_add_section(ew, &shdr, &empty_buffer, ".shstrtab");
Aaron Durbincedcb882015-10-28 11:26:40 -0500802 ew->shstrtab_sec = last_section(ew);
803 ew->ehdr.e_shstrndx = section_index(ew, ew->shstrtab_sec);
804
805 /* Add a small string table and symbol table. */
806 strtab_init(ew, 4096);
807 symtab_init(ew, 100);
Aaron Durbin36be8132014-03-11 11:48:56 -0500808
809 return ew;
810}
811
812/*
813 * Clean up any internal state represented by ew. Aftewards the elf_writer
814 * is invalid.
815 */
816void elf_writer_destroy(struct elf_writer *ew)
817{
Aaron Durbincedcb882015-10-28 11:26:40 -0500818 int i;
Aaron Durbin36be8132014-03-11 11:48:56 -0500819 if (ew->phdrs != NULL)
820 free(ew->phdrs);
Aaron Durbincedcb882015-10-28 11:26:40 -0500821 free(ew->strtab.buffer);
822 free(ew->symtab.syms);
823 for (i = 0; i < MAX_SECTIONS; i++)
824 free(ew->rel_sections[i].rels);
Aaron Durbin36be8132014-03-11 11:48:56 -0500825 free(ew);
826}
827
828/*
829 * Add a section to the ELF file. Section type, flags, and memsize are
830 * maintained from the passed in Elf64_Shdr. The buffer represents the
831 * content of the section while the name is the name of section itself.
832 * Returns < 0 on error, 0 on success.
833 */
834int elf_writer_add_section(struct elf_writer *ew, const Elf64_Shdr *shdr,
835 struct buffer *contents, const char *name)
836{
837 struct elf_writer_section *newsh;
838
839 if (ew->num_secs == MAX_SECTIONS)
840 return -1;
841
842 newsh = &ew->sections[ew->num_secs];
843 ew->num_secs++;
844
845 memcpy(&newsh->shdr, shdr, sizeof(newsh->shdr));
846 newsh->shdr.sh_offset = 0;
847
848 newsh->name = name;
849 if (contents != NULL)
850 buffer_clone(&newsh->content, contents);
851
852 return 0;
853}
854
855static void ehdr_write(struct elf_writer *ew, struct buffer *m)
856{
857 int i;
858
859 for (i = 0; i < EI_NIDENT; i++)
860 ew->xdr->put8(m, ew->ehdr.e_ident[i]);
861 ew->xdr->put16(m, ew->ehdr.e_type);
862 ew->xdr->put16(m, ew->ehdr.e_machine);
863 ew->xdr->put32(m, ew->ehdr.e_version);
864 if (ew->bit64) {
865 ew->xdr->put64(m, ew->ehdr.e_entry);
866 ew->xdr->put64(m, ew->ehdr.e_phoff);
867 ew->xdr->put64(m, ew->ehdr.e_shoff);
868 } else {
869 ew->xdr->put32(m, ew->ehdr.e_entry);
870 ew->xdr->put32(m, ew->ehdr.e_phoff);
871 ew->xdr->put32(m, ew->ehdr.e_shoff);
872 }
873 ew->xdr->put32(m, ew->ehdr.e_flags);
874 ew->xdr->put16(m, ew->ehdr.e_ehsize);
875 ew->xdr->put16(m, ew->ehdr.e_phentsize);
876 ew->xdr->put16(m, ew->ehdr.e_phnum);
877 ew->xdr->put16(m, ew->ehdr.e_shentsize);
878 ew->xdr->put16(m, ew->ehdr.e_shnum);
879 ew->xdr->put16(m, ew->ehdr.e_shstrndx);
880}
881
882static void shdr_write(struct elf_writer *ew, size_t n, struct buffer *m)
883{
884 struct xdr *xdr = ew->xdr;
885 int bit64 = ew->bit64;
886 struct elf_writer_section *sec = &ew->sections[n];
887 Elf64_Shdr *shdr = &sec->shdr;
888
889 xdr->put32(m, shdr->sh_name);
890 xdr->put32(m, shdr->sh_type);
Aaron Durbin36be8132014-03-11 11:48:56 -0500891 if (bit64) {
Aaron Durbinbc349b82014-08-22 14:05:00 -0500892 xdr->put64(m, shdr->sh_flags);
Aaron Durbin36be8132014-03-11 11:48:56 -0500893 xdr->put64(m, shdr->sh_addr);
894 xdr->put64(m, shdr->sh_offset);
895 xdr->put64(m, shdr->sh_size);
896 xdr->put32(m, shdr->sh_link);
897 xdr->put32(m, shdr->sh_info);
898 xdr->put64(m, shdr->sh_addralign);
899 xdr->put64(m, shdr->sh_entsize);
900 } else {
Aaron Durbinbc349b82014-08-22 14:05:00 -0500901 xdr->put32(m, shdr->sh_flags);
Aaron Durbin36be8132014-03-11 11:48:56 -0500902 xdr->put32(m, shdr->sh_addr);
903 xdr->put32(m, shdr->sh_offset);
904 xdr->put32(m, shdr->sh_size);
905 xdr->put32(m, shdr->sh_link);
906 xdr->put32(m, shdr->sh_info);
907 xdr->put32(m, shdr->sh_addralign);
908 xdr->put32(m, shdr->sh_entsize);
909 }
910}
911
912static void
913phdr_write(struct elf_writer *ew, struct buffer *m, Elf64_Phdr *phdr)
914{
915 if (ew->bit64) {
916 ew->xdr->put32(m, phdr->p_type);
917 ew->xdr->put32(m, phdr->p_flags);
918 ew->xdr->put64(m, phdr->p_offset);
919 ew->xdr->put64(m, phdr->p_vaddr);
920 ew->xdr->put64(m, phdr->p_paddr);
921 ew->xdr->put64(m, phdr->p_filesz);
922 ew->xdr->put64(m, phdr->p_memsz);
923 ew->xdr->put64(m, phdr->p_align);
924 } else {
925 ew->xdr->put32(m, phdr->p_type);
926 ew->xdr->put32(m, phdr->p_offset);
927 ew->xdr->put32(m, phdr->p_vaddr);
928 ew->xdr->put32(m, phdr->p_paddr);
929 ew->xdr->put32(m, phdr->p_filesz);
930 ew->xdr->put32(m, phdr->p_memsz);
931 ew->xdr->put32(m, phdr->p_flags);
932 ew->xdr->put32(m, phdr->p_align);
933 }
934
935}
936
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500937static int section_consecutive(struct elf_writer *ew, Elf64_Half secidx)
938{
939 Elf64_Half i;
940 struct elf_writer_section *prev_alloc = NULL;
941
942 if (secidx == 0)
943 return 0;
944
945 for (i = 0; i < secidx; i++) {
946 if (ew->sections[i].shdr.sh_flags & SHF_ALLOC)
947 prev_alloc = &ew->sections[i];
948 }
949
950 if (prev_alloc == NULL)
951 return 0;
952
953 if (prev_alloc->shdr.sh_addr + prev_alloc->shdr.sh_size ==
954 ew->sections[secidx].shdr.sh_addr)
955 return 1;
956
957 return 0;
958}
959
960static void write_phdrs(struct elf_writer *ew, struct buffer *phdrs)
961{
962 Elf64_Half i;
963 Elf64_Phdr phdr;
964 size_t num_written = 0;
965
966 for (i = 0; i < ew->num_secs; i++) {
967 struct elf_writer_section *sec = &ew->sections[i];
968
969 if (!(sec->shdr.sh_flags & SHF_ALLOC))
970 continue;
971
972 if (!section_consecutive(ew, i)) {
973 /* Write out previously set phdr. */
974 if (num_written != 0) {
975 phdr_write(ew, phdrs, &phdr);
976 num_written++;
977 }
978 phdr.p_type = PT_LOAD;
979 phdr.p_offset = sec->shdr.sh_offset;
980 phdr.p_vaddr = sec->shdr.sh_addr;
981 phdr.p_paddr = sec->shdr.sh_addr;
982 phdr.p_filesz = buffer_size(&sec->content);
983 phdr.p_memsz = sec->shdr.sh_size;
984 phdr.p_flags = 0;
985 if (sec->shdr.sh_flags & SHF_EXECINSTR)
986 phdr.p_flags |= PF_X | PF_R;
987 if (sec->shdr.sh_flags & SHF_WRITE)
988 phdr.p_flags |= PF_W;
989 phdr.p_align = sec->shdr.sh_addralign;
990 } else {
991 /* Accumulate file size and memsize. The assumption
992 * is that each section is either NOBITS or full
993 * (sh_size == file size). This is standard in that
994 * an ELF section doesn't have a file size component. */
995 if (sec->shdr.sh_flags & SHF_EXECINSTR)
996 phdr.p_flags |= PF_X | PF_R;
997 if (sec->shdr.sh_flags & SHF_WRITE)
998 phdr.p_flags |= PF_W;
999 phdr.p_filesz += buffer_size(&sec->content);
1000 phdr.p_memsz += sec->shdr.sh_size;
1001 }
1002 }
1003
1004 /* Write out the last phdr. */
1005 if (num_written != ew->ehdr.e_phnum)
1006 phdr_write(ew, phdrs, &phdr);
1007}
1008
Aaron Durbincedcb882015-10-28 11:26:40 -05001009static void fixup_symbol_table(struct elf_writer *ew)
1010{
1011 struct elf_writer_section *sec = ew->symtab_sec;
1012
1013 /* If there is only the NULL section, mark section as inactive. */
1014 if (ew->symtab.num_entries == 1) {
1015 sec->shdr.sh_type = SHT_NULL;
1016 sec->shdr.sh_size = 0;
1017 } else {
1018 size_t i;
1019 struct buffer wr;
1020
1021 buffer_clone(&wr, &sec->content);
1022 /* To appease xdr. */
1023 buffer_set_size(&wr, 0);
1024 for (i = 0; i < ew->symtab.num_entries; i++) {
1025 /* Create local copy as were over-writing backing
1026 * store of the symbol. */
1027 Elf64_Sym sym = ew->symtab.syms[i];
1028 if (ew->bit64) {
1029 ew->xdr->put32(&wr, sym.st_name);
1030 ew->xdr->put8(&wr, sym.st_info);
1031 ew->xdr->put8(&wr, sym.st_other);
1032 ew->xdr->put16(&wr, sym.st_shndx);
1033 ew->xdr->put64(&wr, sym.st_value);
1034 ew->xdr->put64(&wr, sym.st_size);
1035 } else {
1036 ew->xdr->put32(&wr, sym.st_name);
1037 ew->xdr->put32(&wr, sym.st_value);
1038 ew->xdr->put32(&wr, sym.st_size);
1039 ew->xdr->put8(&wr, sym.st_info);
1040 ew->xdr->put8(&wr, sym.st_other);
1041 ew->xdr->put16(&wr, sym.st_shndx);
1042 }
1043 }
1044
1045 /* Update section size. */
1046 sec->shdr.sh_size = sec->shdr.sh_entsize;
1047 sec->shdr.sh_size *= ew->symtab.num_entries;
1048
1049 /* Fix up sh_link to point to string table. */
1050 sec->shdr.sh_link = section_index(ew, ew->strtab_sec);
1051 /* sh_info is supposed to be 1 greater than symbol table
1052 * index of last local binding. Just use max symbols. */
1053 sec->shdr.sh_info = ew->symtab.num_entries;
1054 }
1055
1056 buffer_set_size(&sec->content, sec->shdr.sh_size);
1057}
1058
1059static void fixup_relocations(struct elf_writer *ew)
1060{
1061 int i;
1062 Elf64_Xword type;
1063
1064 switch (ew->ehdr.e_machine) {
1065 case EM_386:
1066 type = R_386_32;
1067 break;
1068 case EM_ARM:
1069 type = R_ARM_ABS32;
1070 break;
1071 case EM_AARCH64:
1072 type = R_AARCH64_ABS64;
1073 break;
1074 case EM_MIPS:
1075 type = R_MIPS_32;
1076 break;
1077 case EM_RISCV:
1078 type = R_RISCV_32;
1079 break;
1080 default:
1081 ERROR("Unable to handle relocations for e_machine %x\n",
1082 ew->ehdr.e_machine);
1083 return;
1084 }
1085
1086 for (i = 0; i < MAX_SECTIONS; i++) {
1087 struct elf_writer_rel *rel_sec = &ew->rel_sections[i];
1088 struct elf_writer_section *sec = rel_sec->sec;
1089 struct buffer writer;
1090 size_t j;
1091
1092 if (sec == NULL)
1093 continue;
1094
1095 /* Update section header size as well as content size. */
1096 buffer_init(&sec->content, sec->content.name, rel_sec->rels,
1097 rel_sec->num_entries * sec->shdr.sh_entsize);
1098 sec->shdr.sh_size = buffer_size(&sec->content);
1099 buffer_clone(&writer, &sec->content);
1100 /* To make xdr happy. */
1101 buffer_set_size(&writer, 0);
1102
1103 for (j = 0; j < ew->rel_sections[i].num_entries; j++) {
1104 /* Make copy as we're overwriting backing store. */
1105 Elf64_Rel rel = rel_sec->rels[j];
1106 rel.r_info = ELF64_R_INFO(ELF64_R_SYM(rel.r_info),
1107 ELF64_R_TYPE(type));
1108
1109 if (ew->bit64) {
1110 ew->xdr->put64(&writer, rel.r_offset);
1111 ew->xdr->put64(&writer, rel.r_info);
1112 } else {
1113 Elf32_Rel rel32;
1114 rel32.r_offset = rel.r_offset;
1115 rel32.r_info =
1116 ELF32_R_INFO(ELF64_R_SYM(rel.r_info),
1117 ELF64_R_TYPE(rel.r_info));
1118 ew->xdr->put32(&writer, rel32.r_offset);
1119 ew->xdr->put32(&writer, rel32.r_info);
1120 }
1121 }
1122 }
1123}
1124
Aaron Durbin36be8132014-03-11 11:48:56 -05001125/*
1126 * Serialize the ELF file to the output buffer. Return < 0 on error,
1127 * 0 on success.
1128 */
1129int elf_writer_serialize(struct elf_writer *ew, struct buffer *out)
1130{
1131 Elf64_Half i;
1132 Elf64_Xword metadata_size;
1133 Elf64_Xword program_size;
1134 Elf64_Off shstroffset;
1135 size_t shstrlen;
1136 struct buffer metadata;
1137 struct buffer phdrs;
1138 struct buffer data;
1139 struct buffer *strtab;
1140
1141 INFO("Writing %zu sections.\n", ew->num_secs);
1142
Aaron Durbincedcb882015-10-28 11:26:40 -05001143 /* Perform any necessary work for special sections. */
1144 fixup_symbol_table(ew);
1145 fixup_relocations(ew);
1146
Aaron Durbin36be8132014-03-11 11:48:56 -05001147 /* Determine size of sections to be written. */
1148 program_size = 0;
1149 /* Start with 1 byte for first byte of section header string table. */
1150 shstrlen = 1;
1151 for (i = 0; i < ew->num_secs; i++) {
1152 struct elf_writer_section *sec = &ew->sections[i];
1153
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001154 if (sec->shdr.sh_flags & SHF_ALLOC) {
1155 if (!section_consecutive(ew, i))
1156 ew->ehdr.e_phnum++;
1157 }
Aaron Durbin36be8132014-03-11 11:48:56 -05001158
1159 program_size += buffer_size(&sec->content);
1160
1161 /* Keep track of the length sections' names. */
1162 if (sec->name != NULL) {
1163 sec->shdr.sh_name = shstrlen;
1164 shstrlen += strlen(sec->name) + 1;
1165 }
1166 }
1167 ew->ehdr.e_shnum = ew->num_secs;
1168 metadata_size = 0;
1169 metadata_size += ew->ehdr.e_ehsize;
1170 metadata_size += ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1171 metadata_size += ew->ehdr.e_phnum * ew->ehdr.e_phentsize;
1172 shstroffset = metadata_size;
1173 /* Align up section header string size and metadata size to 4KiB */
1174 metadata_size = ALIGN(metadata_size + shstrlen, 4096);
1175
1176 if (buffer_create(out, metadata_size + program_size, "elfout")) {
1177 ERROR("Could not create output buffer for ELF.\n");
1178 return -1;
1179 }
1180
1181 INFO("Created %zu output buffer for ELF file.\n", buffer_size(out));
1182
1183 /*
1184 * Write out ELF header. Section headers come right after ELF header
1185 * followed by the program headers. Buffers need to be created first
1186 * to do the writing.
1187 */
1188 ew->ehdr.e_shoff = ew->ehdr.e_ehsize;
1189 ew->ehdr.e_phoff = ew->ehdr.e_shoff +
1190 ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1191
1192 buffer_splice(&metadata, out, 0, metadata_size);
1193 buffer_splice(&phdrs, out, ew->ehdr.e_phoff,
1194 ew->ehdr.e_phnum * ew->ehdr.e_phentsize);
1195 buffer_splice(&data, out, metadata_size, program_size);
1196 /* Set up the section header string table contents. */
Aaron Durbincedcb882015-10-28 11:26:40 -05001197 strtab = &ew->shstrtab_sec->content;
Aaron Durbin36be8132014-03-11 11:48:56 -05001198 buffer_splice(strtab, out, shstroffset, shstrlen);
Aaron Durbincedcb882015-10-28 11:26:40 -05001199 ew->shstrtab_sec->shdr.sh_size = shstrlen;
Aaron Durbin36be8132014-03-11 11:48:56 -05001200
1201 /* Reset current locations. */
1202 buffer_set_size(&metadata, 0);
1203 buffer_set_size(&data, 0);
1204 buffer_set_size(&phdrs, 0);
1205 buffer_set_size(strtab, 0);
1206
1207 /* ELF Header */
1208 ehdr_write(ew, &metadata);
1209
1210 /* Write out section headers, section strings, section content, and
1211 * program headers. */
1212 ew->xdr->put8(strtab, 0);
1213 for (i = 0; i < ew->num_secs; i++) {
Aaron Durbin36be8132014-03-11 11:48:56 -05001214 struct elf_writer_section *sec = &ew->sections[i];
1215
Aaron Durbincedcb882015-10-28 11:26:40 -05001216 /* Update section offsets. Be sure to not update SHN_UNDEF. */
1217 if (sec == ew->shstrtab_sec)
Aaron Durbin36be8132014-03-11 11:48:56 -05001218 sec->shdr.sh_offset = shstroffset;
Aaron Durbincedcb882015-10-28 11:26:40 -05001219 else if (i != SHN_UNDEF)
Aaron Durbin36be8132014-03-11 11:48:56 -05001220 sec->shdr.sh_offset = buffer_size(&data) +
1221 metadata_size;
Aaron Durbincedcb882015-10-28 11:26:40 -05001222
Aaron Durbin36be8132014-03-11 11:48:56 -05001223 shdr_write(ew, i, &metadata);
1224
1225 /* Add section name to string table. */
1226 if (sec->name != NULL)
1227 bputs(strtab, sec->name, strlen(sec->name) + 1);
1228
Aaron Durbincedcb882015-10-28 11:26:40 -05001229 /* Output section data for all sections but SHN_UNDEF and
1230 * section header string table. */
1231 if (i != SHN_UNDEF && sec != ew->shstrtab_sec)
1232 bputs(&data, buffer_get(&sec->content),
1233 buffer_size(&sec->content));
Aaron Durbin36be8132014-03-11 11:48:56 -05001234 }
1235
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001236 write_phdrs(ew, &phdrs);
1237
Aaron Durbin36be8132014-03-11 11:48:56 -05001238 return 0;
1239}
Aaron Durbincedcb882015-10-28 11:26:40 -05001240
1241/* Add a string to the string table returning index on success, < 0 on error. */
1242static int elf_writer_add_string(struct elf_writer *ew, const char *new)
1243{
1244 size_t current_offset;
1245 size_t new_len;
1246
1247 for (current_offset = 0; current_offset < ew->strtab.next_offset; ) {
1248 const char *str = ew->strtab.buffer + current_offset;
1249 size_t len = strlen(str) + 1;
1250
1251 if (!strcmp(str, new))
1252 return current_offset;
1253 current_offset += len;
1254 }
1255
1256 new_len = strlen(new) + 1;
1257
1258 if (current_offset + new_len > ew->strtab.max_size) {
1259 ERROR("No space for string in .strtab.\n");
1260 return -1;
1261 }
1262
1263 memcpy(ew->strtab.buffer + current_offset, new, new_len);
1264 ew->strtab.next_offset = current_offset + new_len;
1265
1266 return current_offset;
1267}
1268
1269static int elf_writer_section_index(struct elf_writer *ew, const char *name)
1270{
1271 size_t i;
1272
1273 for (i = 0; i < ew->num_secs; i++) {
1274 if (ew->sections[i].name == NULL)
1275 continue;
1276 if (!strcmp(ew->sections[i].name, name))
1277 return i;
1278 }
1279
1280 ERROR("ELF Section not found: %s\n", name);
1281
1282 return -1;
1283}
1284
1285int elf_writer_add_symbol(struct elf_writer *ew, const char *name,
1286 const char *section_name,
1287 Elf64_Addr value, Elf64_Word size,
1288 int binding, int type)
1289{
1290 int index;
1291 Elf64_Sym sym = {
1292 .st_value = value,
1293 .st_size = size,
1294 .st_info = ELF64_ST_INFO(binding, type),
1295 };
1296
1297 if (ew->symtab.max_entries == ew->symtab.num_entries) {
1298 ERROR("No more symbol entries left.\n");
1299 return -1;
1300 }
1301
1302 index = elf_writer_add_string(ew, name);
1303 if (index < 0)
1304 return -1;
1305 sym.st_name = index;
1306
1307 index = elf_writer_section_index(ew, section_name);
1308 if (index < 0)
1309 return -1;
1310 sym.st_shndx = index;
1311
1312 ew->symtab.syms[ew->symtab.num_entries++] = sym;
1313
1314 return 0;
1315}
1316
1317static int elf_sym_index(struct elf_writer *ew, const char *sym)
1318{
1319 int index;
1320 size_t i;
1321 Elf64_Word st_name;
1322
1323 /* Determine index of symbol in the string table. */
1324 index = elf_writer_add_string(ew, sym);
1325 if (index < 0)
1326 return -1;
1327
1328 st_name = index;
1329
1330 for (i = 0; i < ew->symtab.num_entries; i++)
1331 if (ew->symtab.syms[i].st_name == st_name)
1332 return i;
1333
1334 return -1;
1335}
1336
1337static struct elf_writer_rel *rel_section(struct elf_writer *ew,
1338 const Elf64_Rel *r)
1339{
1340 Elf64_Sym *sym;
1341 struct elf_writer_rel *rel;
1342 Elf64_Shdr shdr;
1343 struct buffer b;
1344
1345 sym = &ew->symtab.syms[ELF64_R_SYM(r->r_info)];
1346
1347 /* Determine if section has been initialized yet. */
1348 rel = &ew->rel_sections[sym->st_shndx];
1349 if (rel->sec != NULL)
1350 return rel;
1351
1352 memset(&shdr, 0, sizeof(shdr));
1353 shdr.sh_type = SHT_REL;
1354 shdr.sh_link = section_index(ew, ew->symtab_sec);
1355 shdr.sh_info = sym->st_shndx;
1356
1357 if (ew->bit64) {
1358 shdr.sh_addralign = sizeof(Elf64_Addr);
1359 shdr.sh_entsize = sizeof(Elf64_Rel);
1360 } else {
1361 shdr.sh_addralign = sizeof(Elf32_Addr);
1362 shdr.sh_entsize = sizeof(Elf32_Rel);
1363 }
1364
1365 if ((strlen(".rel") + strlen(ew->sections[sym->st_shndx].name) + 1) >
1366 MAX_REL_NAME) {
1367 ERROR("Rel Section name won't fit\n");
1368 return NULL;
1369 }
1370
1371 strcat(rel->name, ".rel");
1372 strcat(rel->name, ew->sections[sym->st_shndx].name);
1373 buffer_init(&b, rel->name, NULL, 0);
1374
1375 elf_writer_add_section(ew, &shdr, &b, rel->name);
1376 rel->sec = last_section(ew);
1377
1378 return rel;
1379}
1380
1381static int add_rel(struct elf_writer_rel *rel_sec, const Elf64_Rel *rel)
1382{
1383 if (rel_sec->num_entries == rel_sec->max_entries) {
1384 size_t num = rel_sec->max_entries * 2;
1385 Elf64_Rel *old_rels;
1386
1387 if (num == 0)
1388 num = 128;
1389
1390 old_rels = rel_sec->rels;
1391 rel_sec->rels = calloc(num, sizeof(Elf64_Rel));
1392
1393 memcpy(rel_sec->rels, old_rels,
1394 rel_sec->num_entries * sizeof(Elf64_Rel));
1395 free(old_rels);
1396
1397 rel_sec->max_entries = num;
1398 }
1399
1400 rel_sec->rels[rel_sec->num_entries] = *rel;
1401 rel_sec->num_entries++;
1402
1403 return 0;
1404}
1405
1406int elf_writer_add_rel(struct elf_writer *ew, const char *sym, Elf64_Addr addr)
1407{
1408 Elf64_Rel rel;
1409 Elf64_Xword sym_info;
1410 int sym_index;
1411 struct elf_writer_rel *rel_sec;
1412
1413 sym_index = elf_sym_index(ew, sym);
1414
1415 if (sym_index < 0) {
1416 ERROR("Unable to locate symbol: %s\n", sym);
1417 return -1;
1418 }
1419
1420 sym_info = sym_index;
1421
1422 /* The relocation type will get fixed prior to serialization. */
1423 rel.r_offset = addr;
1424 rel.r_info = ELF64_R_INFO(sym_info, 0);
1425
1426 rel_sec = rel_section(ew, &rel);
1427
1428 if (rel_sec == NULL)
1429 return -1;
1430
1431 return add_rel(rel_sec, &rel);
1432}