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