blob: acb25a7475ce7ff066088a40dbc05d52a5881e19 [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;
Damien Zammit00252472017-09-03 21:04:41 +1000438 Elf64_Half shnum;
439 Elf64_Xword i;
Aaron Durbinc0780942014-03-05 16:41:27 -0600440 Elf64_Xword nsyms;
441 Elf64_Sym *sym;
442 struct buffer b;
443
444 ehdr = &pelf->ehdr;
445
446 shdr = NULL;
Damien Zammit00252472017-09-03 21:04:41 +1000447 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
448 if (pelf->shdr[shnum].sh_type != SHT_SYMTAB)
Aaron Durbinc0780942014-03-05 16:41:27 -0600449 continue;
450
451 if (shdr != NULL) {
452 ERROR("Multiple symbol sections found. %u and %u\n",
Damien Zammit00252472017-09-03 21:04:41 +1000453 (unsigned int)(shdr - pelf->shdr), shnum);
Aaron Durbinc0780942014-03-05 16:41:27 -0600454 return -1;
455 }
456
Damien Zammit00252472017-09-03 21:04:41 +1000457 shdr = &pelf->shdr[shnum];
Aaron Durbinc0780942014-03-05 16:41:27 -0600458 }
459
460 if (shdr == NULL) {
461 ERROR("No symbol table found.\n");
462 return -1;
463 }
464
465 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
466 if (check_size(in, shdr->sh_offset, buffer_size(&b), "symtab"))
467 return -1;
468
469 nsyms = shdr->sh_size / shdr->sh_entsize;
470
471 pelf->syms = calloc(nsyms, sizeof(Elf64_Sym));
472
473 for (i = 0; i < nsyms; i++) {
474 sym = &pelf->syms[i];
475
476 if (bit64) {
477 sym->st_name = xdr->get32(&b);
478 sym->st_info = xdr->get8(&b);
479 sym->st_other = xdr->get8(&b);
480 sym->st_shndx = xdr->get16(&b);
481 sym->st_value = xdr->get64(&b);
482 sym->st_size = xdr->get64(&b);
483 } else {
484 sym->st_name = xdr->get32(&b);
485 sym->st_value = xdr->get32(&b);
486 sym->st_size = xdr->get32(&b);
487 sym->st_info = xdr->get8(&b);
488 sym->st_other = xdr->get8(&b);
489 sym->st_shndx = xdr->get16(&b);
490 }
491 }
492
493 return 0;
494}
495
Aaron Durbind0f61652014-03-05 13:09:55 -0600496int parse_elf(const struct buffer *pinput, struct parsed_elf *pelf, int flags)
497{
498 struct xdr *xdr = &xdr_le;
499 int bit64 = 0;
500 struct buffer input;
501 Elf64_Ehdr *ehdr;
502
503 /* Zero out the parsed elf structure. */
504 memset(pelf, 0, sizeof(*pelf));
505
506 if (!iself(buffer_get(pinput))) {
Patrick Georgi8320b9a2017-07-05 13:28:24 +0200507 DEBUG("The stage file is not in ELF format!\n");
Aaron Durbind0f61652014-03-05 13:09:55 -0600508 return -1;
509 }
510
511 buffer_clone(&input, pinput);
512 ehdr = &pelf->ehdr;
513 elf_eident(&input, ehdr);
514 bit64 = ehdr->e_ident[EI_CLASS] == ELFCLASS64;
515 /* Assume LE unless we are sure otherwise.
516 * We're not going to take on the task of
517 * fully validating the ELF file. That way
518 * lies madness.
519 */
520 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
521 xdr = &xdr_be;
522
523 elf_ehdr(&input, ehdr, xdr, bit64);
524
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600525 /* Relocation processing requires section header parsing. */
526 if (flags & ELF_PARSE_RELOC)
527 flags |= ELF_PARSE_SHDR;
528
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600529 /* String table processing requires section header parsing. */
530 if (flags & ELF_PARSE_STRTAB)
531 flags |= ELF_PARSE_SHDR;
532
Aaron Durbinc0780942014-03-05 16:41:27 -0600533 /* Symbole table processing requires section header parsing. */
534 if (flags & ELF_PARSE_SYMTAB)
535 flags |= ELF_PARSE_SHDR;
536
Aaron Durbind0f61652014-03-05 13:09:55 -0600537 if ((flags & ELF_PARSE_PHDR) && phdr_read(pinput, pelf, xdr, bit64))
538 goto fail;
539
540 if ((flags & ELF_PARSE_SHDR) && shdr_read(pinput, pelf, xdr, bit64))
541 goto fail;
542
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600543 if ((flags & ELF_PARSE_RELOC) && reloc_read(pinput, pelf, xdr, bit64))
544 goto fail;
545
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600546 if ((flags & ELF_PARSE_STRTAB) && strtab_read(pinput, pelf))
547 goto fail;
548
Aaron Durbinc0780942014-03-05 16:41:27 -0600549 if ((flags & ELF_PARSE_SYMTAB) && symtab_read(pinput, pelf, xdr, bit64))
550 goto fail;
551
Aaron Durbind0f61652014-03-05 13:09:55 -0600552 return 0;
553
554fail:
555 parsed_elf_destroy(pelf);
556 return -1;
557}
558
559void parsed_elf_destroy(struct parsed_elf *pelf)
560{
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600561 Elf64_Half i;
562
Aaron Durbind0f61652014-03-05 13:09:55 -0600563 free(pelf->phdr);
564 free(pelf->shdr);
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600565 if (pelf->relocs != NULL) {
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600566 for (i = 0; i < pelf->ehdr.e_shnum; i++)
567 free(pelf->relocs[i]);
568 }
569 free(pelf->relocs);
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600570
571 if (pelf->strtabs != NULL) {
572 for (i = 0; i < pelf->ehdr.e_shnum; i++)
573 free(pelf->strtabs[i]);
574 }
575 free(pelf->strtabs);
Aaron Durbinc0780942014-03-05 16:41:27 -0600576 free(pelf->syms);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800577}
578
579/* Get the headers from the buffer.
580 * Return -1 in the event of an error.
581 * The section headers are optional; if NULL
582 * is passed in for pshdr they won't be parsed.
583 * We don't (yet) make payload parsing optional
584 * because we've never seen a use case.
585 */
586int
587elf_headers(const struct buffer *pinput,
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800588 Elf64_Ehdr *ehdr,
589 Elf64_Phdr **pphdr,
590 Elf64_Shdr **pshdr)
591{
Aaron Durbind0f61652014-03-05 13:09:55 -0600592 struct parsed_elf pelf;
593 int flags;
Aaron Durbina983cea2014-03-04 22:08:05 -0600594
Aaron Durbind0f61652014-03-05 13:09:55 -0600595 flags = ELF_PARSE_PHDR;
596
597 if (pshdr != NULL)
598 flags |= ELF_PARSE_SHDR;
599
600 if (parse_elf(pinput, &pelf, flags))
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800601 return -1;
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800602
Aaron Durbind0f61652014-03-05 13:09:55 -0600603 /* Copy out the parsed elf header. */
604 memcpy(ehdr, &pelf.ehdr, sizeof(*ehdr));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800605
Aaron Durbind0f61652014-03-05 13:09:55 -0600606 *pphdr = calloc(ehdr->e_phnum, sizeof(Elf64_Phdr));
607 memcpy(*pphdr, pelf.phdr, ehdr->e_phnum * sizeof(Elf64_Phdr));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800608
Aaron Durbind0f61652014-03-05 13:09:55 -0600609 if (pshdr != NULL) {
610 *pshdr = calloc(ehdr->e_shnum, sizeof(Elf64_Shdr));
611 memcpy(*pshdr, pelf.shdr, ehdr->e_shnum * sizeof(Elf64_Shdr));
612 }
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800613
Aaron Durbind0f61652014-03-05 13:09:55 -0600614 parsed_elf_destroy(&pelf);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800615
616 return 0;
617}
Aaron Durbin36be8132014-03-11 11:48:56 -0500618
619/* ELF Writing Support
620 *
621 * The ELF file is written according to the following layout:
622 * +------------------+
623 * | ELF Header |
624 * +------------------+
625 * | Section Headers |
626 * +------------------+
627 * | Program Headers |
628 * +------------------+
629 * | String table |
630 * +------------------+ <- 4KiB Aligned
631 * | Code/Data |
632 * +------------------+
633 */
634
Aaron Durbin4f930c92015-10-27 16:21:55 -0500635void elf_init_eheader(Elf64_Ehdr *ehdr, int machine, int nbits, int endian)
636{
637 memset(ehdr, 0, sizeof(*ehdr));
638 ehdr->e_ident[EI_MAG0] = ELFMAG0;
639 ehdr->e_ident[EI_MAG1] = ELFMAG1;
640 ehdr->e_ident[EI_MAG2] = ELFMAG2;
641 ehdr->e_ident[EI_MAG3] = ELFMAG3;
642 ehdr->e_ident[EI_CLASS] = nbits;
643 ehdr->e_ident[EI_DATA] = endian;
644 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
645 ehdr->e_type = ET_EXEC;
646 ehdr->e_machine = machine;
647 ehdr->e_version = EV_CURRENT;
648 if (nbits == ELFCLASS64) {
649 ehdr->e_ehsize = sizeof(Elf64_Ehdr);
650 ehdr->e_phentsize = sizeof(Elf64_Phdr);
651 ehdr->e_shentsize = sizeof(Elf64_Shdr);
652 } else {
653 ehdr->e_ehsize = sizeof(Elf32_Ehdr);
654 ehdr->e_phentsize = sizeof(Elf32_Phdr);
655 ehdr->e_shentsize = sizeof(Elf32_Shdr);
656 }
657}
658
Aaron Durbin36be8132014-03-11 11:48:56 -0500659/* Arbitray maximum number of sections. */
660#define MAX_SECTIONS 16
661struct elf_writer_section {
662 Elf64_Shdr shdr;
663 struct buffer content;
664 const char *name;
665};
666
Aaron Durbincedcb882015-10-28 11:26:40 -0500667struct elf_writer_string_table {
668 size_t next_offset;
669 size_t max_size;
670 char *buffer;
671};
672
673struct elf_writer_sym_table {
674 size_t max_entries;
675 size_t num_entries;
676 Elf64_Sym *syms;
677};
678
679#define MAX_REL_NAME 32
680struct elf_writer_rel {
681 size_t num_entries;
682 size_t max_entries;
683 Elf64_Rel *rels;
684 struct elf_writer_section *sec;
685 char name[MAX_REL_NAME];
686};
687
Aaron Durbin36be8132014-03-11 11:48:56 -0500688struct elf_writer
689{
690 Elf64_Ehdr ehdr;
691 struct xdr *xdr;
692 size_t num_secs;
693 struct elf_writer_section sections[MAX_SECTIONS];
Aaron Durbincedcb882015-10-28 11:26:40 -0500694 struct elf_writer_rel rel_sections[MAX_SECTIONS];
Aaron Durbin36be8132014-03-11 11:48:56 -0500695 Elf64_Phdr *phdrs;
Aaron Durbincedcb882015-10-28 11:26:40 -0500696 struct elf_writer_section *shstrtab_sec;
697 struct elf_writer_section *strtab_sec;
698 struct elf_writer_section *symtab_sec;
699 struct elf_writer_string_table strtab;
700 struct elf_writer_sym_table symtab;
Aaron Durbin36be8132014-03-11 11:48:56 -0500701 int bit64;
702};
703
Aaron Durbincedcb882015-10-28 11:26:40 -0500704static size_t section_index(struct elf_writer *ew,
705 struct elf_writer_section *sec)
706{
707 return sec - &ew->sections[0];
708}
709
710static struct elf_writer_section *last_section(struct elf_writer *ew)
711{
712 return &ew->sections[ew->num_secs - 1];
713}
714
715static void strtab_init(struct elf_writer *ew, size_t size)
716{
717 struct buffer b;
718 Elf64_Shdr shdr;
719
720 /* Start adding strings after the initial NUL entry. */
721 ew->strtab.next_offset = 1;
722 ew->strtab.max_size = size;
723 ew->strtab.buffer = calloc(1, ew->strtab.max_size);
724
725 buffer_init(&b, NULL, ew->strtab.buffer, ew->strtab.max_size);
726 memset(&shdr, 0, sizeof(shdr));
727 shdr.sh_type = SHT_STRTAB;
728 shdr.sh_addralign = 1;
729 shdr.sh_size = ew->strtab.max_size;
730 elf_writer_add_section(ew, &shdr, &b, ".strtab");
731 ew->strtab_sec = last_section(ew);
732}
733
734static void symtab_init(struct elf_writer *ew, size_t max_entries)
735{
736 struct buffer b;
737 Elf64_Shdr shdr;
738
739 memset(&shdr, 0, sizeof(shdr));
740 shdr.sh_type = SHT_SYMTAB;
741
742 if (ew->bit64) {
743 shdr.sh_entsize = sizeof(Elf64_Sym);
744 shdr.sh_addralign = sizeof(Elf64_Addr);
745 } else {
746 shdr.sh_entsize = sizeof(Elf32_Sym);
747 shdr.sh_addralign = sizeof(Elf32_Addr);
748 }
749
750 shdr.sh_size = shdr.sh_entsize * max_entries;
751
752 ew->symtab.syms = calloc(max_entries, sizeof(Elf64_Sym));
753 ew->symtab.num_entries = 1;
754 ew->symtab.max_entries = max_entries;
755
756 buffer_init(&b, NULL, ew->symtab.syms, shdr.sh_size);
757
758 elf_writer_add_section(ew, &shdr, &b, ".symtab");
759 ew->symtab_sec = last_section(ew);
760}
761
Aaron Durbin36be8132014-03-11 11:48:56 -0500762struct elf_writer *elf_writer_init(const Elf64_Ehdr *ehdr)
763{
764 struct elf_writer *ew;
765 Elf64_Shdr shdr;
766 struct buffer empty_buffer;
767
768 if (!iself(ehdr))
769 return NULL;
770
771 ew = calloc(1, sizeof(*ew));
772
773 memcpy(&ew->ehdr, ehdr, sizeof(ew->ehdr));
774
775 ew->bit64 = ew->ehdr.e_ident[EI_CLASS] == ELFCLASS64;
776
777 /* Set the endinan ops. */
778 if (ew->ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
779 ew->xdr = &xdr_be;
780 else
781 ew->xdr = &xdr_le;
782
783 /* Reset count and offsets */
784 ew->ehdr.e_phoff = 0;
785 ew->ehdr.e_shoff = 0;
786 ew->ehdr.e_shnum = 0;
787 ew->ehdr.e_phnum = 0;
788
789 memset(&empty_buffer, 0, sizeof(empty_buffer));
790 memset(&shdr, 0, sizeof(shdr));
791
792 /* Add SHT_NULL section header. */
793 shdr.sh_type = SHT_NULL;
794 elf_writer_add_section(ew, &shdr, &empty_buffer, NULL);
795
796 /* Add section header string table and maintain reference to it. */
797 shdr.sh_type = SHT_STRTAB;
798 elf_writer_add_section(ew, &shdr, &empty_buffer, ".shstrtab");
Aaron Durbincedcb882015-10-28 11:26:40 -0500799 ew->shstrtab_sec = last_section(ew);
800 ew->ehdr.e_shstrndx = section_index(ew, ew->shstrtab_sec);
801
802 /* Add a small string table and symbol table. */
803 strtab_init(ew, 4096);
804 symtab_init(ew, 100);
Aaron Durbin36be8132014-03-11 11:48:56 -0500805
806 return ew;
807}
808
809/*
810 * Clean up any internal state represented by ew. Aftewards the elf_writer
811 * is invalid.
Furquan Shaikhb927bec2016-08-05 12:04:55 -0700812 * It is safe to call elf_writer_destroy with ew as NULL. It returns without
813 * performing any action.
Aaron Durbin36be8132014-03-11 11:48:56 -0500814 */
815void elf_writer_destroy(struct elf_writer *ew)
816{
Aaron Durbincedcb882015-10-28 11:26:40 -0500817 int i;
Furquan Shaikhb927bec2016-08-05 12:04:55 -0700818 if (ew == NULL)
819 return;
Aaron Durbin36be8132014-03-11 11:48:56 -0500820 if (ew->phdrs != NULL)
821 free(ew->phdrs);
Aaron Durbincedcb882015-10-28 11:26:40 -0500822 free(ew->strtab.buffer);
823 free(ew->symtab.syms);
824 for (i = 0; i < MAX_SECTIONS; i++)
825 free(ew->rel_sections[i].rels);
Aaron Durbin36be8132014-03-11 11:48:56 -0500826 free(ew);
827}
828
829/*
830 * Add a section to the ELF file. Section type, flags, and memsize are
831 * maintained from the passed in Elf64_Shdr. The buffer represents the
832 * content of the section while the name is the name of section itself.
833 * Returns < 0 on error, 0 on success.
834 */
835int elf_writer_add_section(struct elf_writer *ew, const Elf64_Shdr *shdr,
836 struct buffer *contents, const char *name)
837{
838 struct elf_writer_section *newsh;
839
840 if (ew->num_secs == MAX_SECTIONS)
841 return -1;
842
843 newsh = &ew->sections[ew->num_secs];
844 ew->num_secs++;
845
846 memcpy(&newsh->shdr, shdr, sizeof(newsh->shdr));
847 newsh->shdr.sh_offset = 0;
848
849 newsh->name = name;
850 if (contents != NULL)
851 buffer_clone(&newsh->content, contents);
852
853 return 0;
854}
855
856static void ehdr_write(struct elf_writer *ew, struct buffer *m)
857{
858 int i;
859
860 for (i = 0; i < EI_NIDENT; i++)
861 ew->xdr->put8(m, ew->ehdr.e_ident[i]);
862 ew->xdr->put16(m, ew->ehdr.e_type);
863 ew->xdr->put16(m, ew->ehdr.e_machine);
864 ew->xdr->put32(m, ew->ehdr.e_version);
865 if (ew->bit64) {
866 ew->xdr->put64(m, ew->ehdr.e_entry);
867 ew->xdr->put64(m, ew->ehdr.e_phoff);
868 ew->xdr->put64(m, ew->ehdr.e_shoff);
869 } else {
870 ew->xdr->put32(m, ew->ehdr.e_entry);
871 ew->xdr->put32(m, ew->ehdr.e_phoff);
872 ew->xdr->put32(m, ew->ehdr.e_shoff);
873 }
874 ew->xdr->put32(m, ew->ehdr.e_flags);
875 ew->xdr->put16(m, ew->ehdr.e_ehsize);
876 ew->xdr->put16(m, ew->ehdr.e_phentsize);
877 ew->xdr->put16(m, ew->ehdr.e_phnum);
878 ew->xdr->put16(m, ew->ehdr.e_shentsize);
879 ew->xdr->put16(m, ew->ehdr.e_shnum);
880 ew->xdr->put16(m, ew->ehdr.e_shstrndx);
881}
882
883static void shdr_write(struct elf_writer *ew, size_t n, struct buffer *m)
884{
885 struct xdr *xdr = ew->xdr;
886 int bit64 = ew->bit64;
887 struct elf_writer_section *sec = &ew->sections[n];
888 Elf64_Shdr *shdr = &sec->shdr;
889
890 xdr->put32(m, shdr->sh_name);
891 xdr->put32(m, shdr->sh_type);
Aaron Durbin36be8132014-03-11 11:48:56 -0500892 if (bit64) {
Aaron Durbinbc349b82014-08-22 14:05:00 -0500893 xdr->put64(m, shdr->sh_flags);
Aaron Durbin36be8132014-03-11 11:48:56 -0500894 xdr->put64(m, shdr->sh_addr);
895 xdr->put64(m, shdr->sh_offset);
896 xdr->put64(m, shdr->sh_size);
897 xdr->put32(m, shdr->sh_link);
898 xdr->put32(m, shdr->sh_info);
899 xdr->put64(m, shdr->sh_addralign);
900 xdr->put64(m, shdr->sh_entsize);
901 } else {
Aaron Durbinbc349b82014-08-22 14:05:00 -0500902 xdr->put32(m, shdr->sh_flags);
Aaron Durbin36be8132014-03-11 11:48:56 -0500903 xdr->put32(m, shdr->sh_addr);
904 xdr->put32(m, shdr->sh_offset);
905 xdr->put32(m, shdr->sh_size);
906 xdr->put32(m, shdr->sh_link);
907 xdr->put32(m, shdr->sh_info);
908 xdr->put32(m, shdr->sh_addralign);
909 xdr->put32(m, shdr->sh_entsize);
910 }
911}
912
913static void
914phdr_write(struct elf_writer *ew, struct buffer *m, Elf64_Phdr *phdr)
915{
916 if (ew->bit64) {
917 ew->xdr->put32(m, phdr->p_type);
918 ew->xdr->put32(m, phdr->p_flags);
919 ew->xdr->put64(m, phdr->p_offset);
920 ew->xdr->put64(m, phdr->p_vaddr);
921 ew->xdr->put64(m, phdr->p_paddr);
922 ew->xdr->put64(m, phdr->p_filesz);
923 ew->xdr->put64(m, phdr->p_memsz);
924 ew->xdr->put64(m, phdr->p_align);
925 } else {
926 ew->xdr->put32(m, phdr->p_type);
927 ew->xdr->put32(m, phdr->p_offset);
928 ew->xdr->put32(m, phdr->p_vaddr);
929 ew->xdr->put32(m, phdr->p_paddr);
930 ew->xdr->put32(m, phdr->p_filesz);
931 ew->xdr->put32(m, phdr->p_memsz);
932 ew->xdr->put32(m, phdr->p_flags);
933 ew->xdr->put32(m, phdr->p_align);
934 }
935
936}
937
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500938static int section_consecutive(struct elf_writer *ew, Elf64_Half secidx)
939{
940 Elf64_Half i;
941 struct elf_writer_section *prev_alloc = NULL;
942
943 if (secidx == 0)
944 return 0;
945
946 for (i = 0; i < secidx; i++) {
947 if (ew->sections[i].shdr.sh_flags & SHF_ALLOC)
948 prev_alloc = &ew->sections[i];
949 }
950
951 if (prev_alloc == NULL)
952 return 0;
953
954 if (prev_alloc->shdr.sh_addr + prev_alloc->shdr.sh_size ==
955 ew->sections[secidx].shdr.sh_addr)
956 return 1;
957
958 return 0;
959}
960
961static void write_phdrs(struct elf_writer *ew, struct buffer *phdrs)
962{
963 Elf64_Half i;
964 Elf64_Phdr phdr;
965 size_t num_written = 0;
Antonello Dettori3bded7d2016-06-16 13:40:24 +0200966 size_t num_needs_write = 0;
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500967
968 for (i = 0; i < ew->num_secs; i++) {
969 struct elf_writer_section *sec = &ew->sections[i];
970
971 if (!(sec->shdr.sh_flags & SHF_ALLOC))
972 continue;
973
974 if (!section_consecutive(ew, i)) {
975 /* Write out previously set phdr. */
Antonello Dettori3bded7d2016-06-16 13:40:24 +0200976 if (num_needs_write != num_written) {
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500977 phdr_write(ew, phdrs, &phdr);
978 num_written++;
979 }
980 phdr.p_type = PT_LOAD;
981 phdr.p_offset = sec->shdr.sh_offset;
982 phdr.p_vaddr = sec->shdr.sh_addr;
983 phdr.p_paddr = sec->shdr.sh_addr;
984 phdr.p_filesz = buffer_size(&sec->content);
985 phdr.p_memsz = sec->shdr.sh_size;
986 phdr.p_flags = 0;
987 if (sec->shdr.sh_flags & SHF_EXECINSTR)
988 phdr.p_flags |= PF_X | PF_R;
989 if (sec->shdr.sh_flags & SHF_WRITE)
990 phdr.p_flags |= PF_W;
991 phdr.p_align = sec->shdr.sh_addralign;
Antonello Dettori3bded7d2016-06-16 13:40:24 +0200992 num_needs_write++;
993
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500994 } else {
995 /* Accumulate file size and memsize. The assumption
996 * is that each section is either NOBITS or full
997 * (sh_size == file size). This is standard in that
998 * an ELF section doesn't have a file size component. */
999 if (sec->shdr.sh_flags & SHF_EXECINSTR)
1000 phdr.p_flags |= PF_X | PF_R;
1001 if (sec->shdr.sh_flags & SHF_WRITE)
1002 phdr.p_flags |= PF_W;
1003 phdr.p_filesz += buffer_size(&sec->content);
1004 phdr.p_memsz += sec->shdr.sh_size;
1005 }
1006 }
1007
1008 /* Write out the last phdr. */
Antonello Dettori3bded7d2016-06-16 13:40:24 +02001009 if (num_needs_write != num_written) {
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001010 phdr_write(ew, phdrs, &phdr);
Antonello Dettori3bded7d2016-06-16 13:40:24 +02001011 num_written++;
1012 }
1013 assert(num_written == ew->ehdr.e_phnum);
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001014}
1015
Aaron Durbincedcb882015-10-28 11:26:40 -05001016static void fixup_symbol_table(struct elf_writer *ew)
1017{
1018 struct elf_writer_section *sec = ew->symtab_sec;
1019
1020 /* If there is only the NULL section, mark section as inactive. */
1021 if (ew->symtab.num_entries == 1) {
1022 sec->shdr.sh_type = SHT_NULL;
1023 sec->shdr.sh_size = 0;
1024 } else {
1025 size_t i;
1026 struct buffer wr;
1027
1028 buffer_clone(&wr, &sec->content);
1029 /* To appease xdr. */
1030 buffer_set_size(&wr, 0);
1031 for (i = 0; i < ew->symtab.num_entries; i++) {
1032 /* Create local copy as were over-writing backing
1033 * store of the symbol. */
1034 Elf64_Sym sym = ew->symtab.syms[i];
1035 if (ew->bit64) {
1036 ew->xdr->put32(&wr, sym.st_name);
1037 ew->xdr->put8(&wr, sym.st_info);
1038 ew->xdr->put8(&wr, sym.st_other);
1039 ew->xdr->put16(&wr, sym.st_shndx);
1040 ew->xdr->put64(&wr, sym.st_value);
1041 ew->xdr->put64(&wr, sym.st_size);
1042 } else {
1043 ew->xdr->put32(&wr, sym.st_name);
1044 ew->xdr->put32(&wr, sym.st_value);
1045 ew->xdr->put32(&wr, sym.st_size);
1046 ew->xdr->put8(&wr, sym.st_info);
1047 ew->xdr->put8(&wr, sym.st_other);
1048 ew->xdr->put16(&wr, sym.st_shndx);
1049 }
1050 }
1051
1052 /* Update section size. */
1053 sec->shdr.sh_size = sec->shdr.sh_entsize;
1054 sec->shdr.sh_size *= ew->symtab.num_entries;
1055
1056 /* Fix up sh_link to point to string table. */
1057 sec->shdr.sh_link = section_index(ew, ew->strtab_sec);
1058 /* sh_info is supposed to be 1 greater than symbol table
1059 * index of last local binding. Just use max symbols. */
1060 sec->shdr.sh_info = ew->symtab.num_entries;
1061 }
1062
1063 buffer_set_size(&sec->content, sec->shdr.sh_size);
1064}
1065
1066static void fixup_relocations(struct elf_writer *ew)
1067{
1068 int i;
1069 Elf64_Xword type;
1070
1071 switch (ew->ehdr.e_machine) {
1072 case EM_386:
1073 type = R_386_32;
1074 break;
1075 case EM_ARM:
1076 type = R_ARM_ABS32;
1077 break;
1078 case EM_AARCH64:
1079 type = R_AARCH64_ABS64;
1080 break;
1081 case EM_MIPS:
1082 type = R_MIPS_32;
1083 break;
1084 case EM_RISCV:
1085 type = R_RISCV_32;
1086 break;
Ronald G. Minniched4aa042015-12-11 18:19:52 +00001087 case EM_PPC64:
1088 type = R_PPC64_ADDR32;
1089 break;
Aaron Durbincedcb882015-10-28 11:26:40 -05001090 default:
1091 ERROR("Unable to handle relocations for e_machine %x\n",
1092 ew->ehdr.e_machine);
1093 return;
1094 }
1095
1096 for (i = 0; i < MAX_SECTIONS; i++) {
1097 struct elf_writer_rel *rel_sec = &ew->rel_sections[i];
1098 struct elf_writer_section *sec = rel_sec->sec;
1099 struct buffer writer;
1100 size_t j;
1101
1102 if (sec == NULL)
1103 continue;
1104
1105 /* Update section header size as well as content size. */
1106 buffer_init(&sec->content, sec->content.name, rel_sec->rels,
1107 rel_sec->num_entries * sec->shdr.sh_entsize);
1108 sec->shdr.sh_size = buffer_size(&sec->content);
1109 buffer_clone(&writer, &sec->content);
1110 /* To make xdr happy. */
1111 buffer_set_size(&writer, 0);
1112
1113 for (j = 0; j < ew->rel_sections[i].num_entries; j++) {
1114 /* Make copy as we're overwriting backing store. */
1115 Elf64_Rel rel = rel_sec->rels[j];
1116 rel.r_info = ELF64_R_INFO(ELF64_R_SYM(rel.r_info),
1117 ELF64_R_TYPE(type));
1118
1119 if (ew->bit64) {
1120 ew->xdr->put64(&writer, rel.r_offset);
1121 ew->xdr->put64(&writer, rel.r_info);
1122 } else {
1123 Elf32_Rel rel32;
1124 rel32.r_offset = rel.r_offset;
1125 rel32.r_info =
1126 ELF32_R_INFO(ELF64_R_SYM(rel.r_info),
1127 ELF64_R_TYPE(rel.r_info));
1128 ew->xdr->put32(&writer, rel32.r_offset);
1129 ew->xdr->put32(&writer, rel32.r_info);
1130 }
1131 }
1132 }
1133}
1134
Aaron Durbin36be8132014-03-11 11:48:56 -05001135/*
1136 * Serialize the ELF file to the output buffer. Return < 0 on error,
1137 * 0 on success.
1138 */
1139int elf_writer_serialize(struct elf_writer *ew, struct buffer *out)
1140{
1141 Elf64_Half i;
1142 Elf64_Xword metadata_size;
1143 Elf64_Xword program_size;
1144 Elf64_Off shstroffset;
1145 size_t shstrlen;
1146 struct buffer metadata;
1147 struct buffer phdrs;
1148 struct buffer data;
1149 struct buffer *strtab;
1150
1151 INFO("Writing %zu sections.\n", ew->num_secs);
1152
Aaron Durbincedcb882015-10-28 11:26:40 -05001153 /* Perform any necessary work for special sections. */
1154 fixup_symbol_table(ew);
1155 fixup_relocations(ew);
1156
Aaron Durbin36be8132014-03-11 11:48:56 -05001157 /* Determine size of sections to be written. */
1158 program_size = 0;
1159 /* Start with 1 byte for first byte of section header string table. */
1160 shstrlen = 1;
1161 for (i = 0; i < ew->num_secs; i++) {
1162 struct elf_writer_section *sec = &ew->sections[i];
1163
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001164 if (sec->shdr.sh_flags & SHF_ALLOC) {
1165 if (!section_consecutive(ew, i))
1166 ew->ehdr.e_phnum++;
1167 }
Aaron Durbin36be8132014-03-11 11:48:56 -05001168
1169 program_size += buffer_size(&sec->content);
1170
1171 /* Keep track of the length sections' names. */
1172 if (sec->name != NULL) {
1173 sec->shdr.sh_name = shstrlen;
1174 shstrlen += strlen(sec->name) + 1;
1175 }
1176 }
1177 ew->ehdr.e_shnum = ew->num_secs;
1178 metadata_size = 0;
1179 metadata_size += ew->ehdr.e_ehsize;
1180 metadata_size += ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1181 metadata_size += ew->ehdr.e_phnum * ew->ehdr.e_phentsize;
1182 shstroffset = metadata_size;
1183 /* Align up section header string size and metadata size to 4KiB */
1184 metadata_size = ALIGN(metadata_size + shstrlen, 4096);
1185
1186 if (buffer_create(out, metadata_size + program_size, "elfout")) {
1187 ERROR("Could not create output buffer for ELF.\n");
1188 return -1;
1189 }
1190
1191 INFO("Created %zu output buffer for ELF file.\n", buffer_size(out));
1192
1193 /*
1194 * Write out ELF header. Section headers come right after ELF header
1195 * followed by the program headers. Buffers need to be created first
1196 * to do the writing.
1197 */
1198 ew->ehdr.e_shoff = ew->ehdr.e_ehsize;
1199 ew->ehdr.e_phoff = ew->ehdr.e_shoff +
1200 ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1201
1202 buffer_splice(&metadata, out, 0, metadata_size);
1203 buffer_splice(&phdrs, out, ew->ehdr.e_phoff,
1204 ew->ehdr.e_phnum * ew->ehdr.e_phentsize);
1205 buffer_splice(&data, out, metadata_size, program_size);
1206 /* Set up the section header string table contents. */
Aaron Durbincedcb882015-10-28 11:26:40 -05001207 strtab = &ew->shstrtab_sec->content;
Aaron Durbin36be8132014-03-11 11:48:56 -05001208 buffer_splice(strtab, out, shstroffset, shstrlen);
Aaron Durbincedcb882015-10-28 11:26:40 -05001209 ew->shstrtab_sec->shdr.sh_size = shstrlen;
Aaron Durbin36be8132014-03-11 11:48:56 -05001210
1211 /* Reset current locations. */
1212 buffer_set_size(&metadata, 0);
1213 buffer_set_size(&data, 0);
1214 buffer_set_size(&phdrs, 0);
1215 buffer_set_size(strtab, 0);
1216
1217 /* ELF Header */
1218 ehdr_write(ew, &metadata);
1219
1220 /* Write out section headers, section strings, section content, and
1221 * program headers. */
1222 ew->xdr->put8(strtab, 0);
1223 for (i = 0; i < ew->num_secs; i++) {
Aaron Durbin36be8132014-03-11 11:48:56 -05001224 struct elf_writer_section *sec = &ew->sections[i];
1225
Aaron Durbincedcb882015-10-28 11:26:40 -05001226 /* Update section offsets. Be sure to not update SHN_UNDEF. */
1227 if (sec == ew->shstrtab_sec)
Aaron Durbin36be8132014-03-11 11:48:56 -05001228 sec->shdr.sh_offset = shstroffset;
Aaron Durbincedcb882015-10-28 11:26:40 -05001229 else if (i != SHN_UNDEF)
Aaron Durbin36be8132014-03-11 11:48:56 -05001230 sec->shdr.sh_offset = buffer_size(&data) +
1231 metadata_size;
Aaron Durbincedcb882015-10-28 11:26:40 -05001232
Aaron Durbin36be8132014-03-11 11:48:56 -05001233 shdr_write(ew, i, &metadata);
1234
1235 /* Add section name to string table. */
1236 if (sec->name != NULL)
1237 bputs(strtab, sec->name, strlen(sec->name) + 1);
1238
Aaron Durbincedcb882015-10-28 11:26:40 -05001239 /* Output section data for all sections but SHN_UNDEF and
1240 * section header string table. */
1241 if (i != SHN_UNDEF && sec != ew->shstrtab_sec)
1242 bputs(&data, buffer_get(&sec->content),
1243 buffer_size(&sec->content));
Aaron Durbin36be8132014-03-11 11:48:56 -05001244 }
1245
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001246 write_phdrs(ew, &phdrs);
1247
Aaron Durbin36be8132014-03-11 11:48:56 -05001248 return 0;
1249}
Aaron Durbincedcb882015-10-28 11:26:40 -05001250
1251/* Add a string to the string table returning index on success, < 0 on error. */
1252static int elf_writer_add_string(struct elf_writer *ew, const char *new)
1253{
1254 size_t current_offset;
1255 size_t new_len;
1256
1257 for (current_offset = 0; current_offset < ew->strtab.next_offset; ) {
1258 const char *str = ew->strtab.buffer + current_offset;
1259 size_t len = strlen(str) + 1;
1260
1261 if (!strcmp(str, new))
1262 return current_offset;
1263 current_offset += len;
1264 }
1265
1266 new_len = strlen(new) + 1;
1267
1268 if (current_offset + new_len > ew->strtab.max_size) {
1269 ERROR("No space for string in .strtab.\n");
1270 return -1;
1271 }
1272
1273 memcpy(ew->strtab.buffer + current_offset, new, new_len);
1274 ew->strtab.next_offset = current_offset + new_len;
1275
1276 return current_offset;
1277}
1278
1279static int elf_writer_section_index(struct elf_writer *ew, const char *name)
1280{
1281 size_t i;
1282
1283 for (i = 0; i < ew->num_secs; i++) {
1284 if (ew->sections[i].name == NULL)
1285 continue;
1286 if (!strcmp(ew->sections[i].name, name))
1287 return i;
1288 }
1289
1290 ERROR("ELF Section not found: %s\n", name);
1291
1292 return -1;
1293}
1294
1295int elf_writer_add_symbol(struct elf_writer *ew, const char *name,
1296 const char *section_name,
1297 Elf64_Addr value, Elf64_Word size,
1298 int binding, int type)
1299{
Patrick Georgi172a14d2015-10-31 01:35:20 +01001300 int i;
Aaron Durbincedcb882015-10-28 11:26:40 -05001301 Elf64_Sym sym = {
1302 .st_value = value,
1303 .st_size = size,
1304 .st_info = ELF64_ST_INFO(binding, type),
1305 };
1306
1307 if (ew->symtab.max_entries == ew->symtab.num_entries) {
1308 ERROR("No more symbol entries left.\n");
1309 return -1;
1310 }
1311
Patrick Georgi172a14d2015-10-31 01:35:20 +01001312 i = elf_writer_add_string(ew, name);
1313 if (i < 0)
Aaron Durbincedcb882015-10-28 11:26:40 -05001314 return -1;
Patrick Georgi172a14d2015-10-31 01:35:20 +01001315 sym.st_name = i;
Aaron Durbincedcb882015-10-28 11:26:40 -05001316
Patrick Georgi172a14d2015-10-31 01:35:20 +01001317 i = elf_writer_section_index(ew, section_name);
1318 if (i < 0)
Aaron Durbincedcb882015-10-28 11:26:40 -05001319 return -1;
Patrick Georgi172a14d2015-10-31 01:35:20 +01001320 sym.st_shndx = i;
Aaron Durbincedcb882015-10-28 11:26:40 -05001321
1322 ew->symtab.syms[ew->symtab.num_entries++] = sym;
1323
1324 return 0;
1325}
1326
1327static int elf_sym_index(struct elf_writer *ew, const char *sym)
1328{
Patrick Georgi172a14d2015-10-31 01:35:20 +01001329 int j;
Aaron Durbincedcb882015-10-28 11:26:40 -05001330 size_t i;
1331 Elf64_Word st_name;
1332
1333 /* Determine index of symbol in the string table. */
Patrick Georgi172a14d2015-10-31 01:35:20 +01001334 j = elf_writer_add_string(ew, sym);
1335 if (j < 0)
Aaron Durbincedcb882015-10-28 11:26:40 -05001336 return -1;
1337
Patrick Georgi172a14d2015-10-31 01:35:20 +01001338 st_name = j;
Aaron Durbincedcb882015-10-28 11:26:40 -05001339
1340 for (i = 0; i < ew->symtab.num_entries; i++)
1341 if (ew->symtab.syms[i].st_name == st_name)
1342 return i;
1343
1344 return -1;
1345}
1346
1347static struct elf_writer_rel *rel_section(struct elf_writer *ew,
1348 const Elf64_Rel *r)
1349{
1350 Elf64_Sym *sym;
1351 struct elf_writer_rel *rel;
1352 Elf64_Shdr shdr;
1353 struct buffer b;
1354
1355 sym = &ew->symtab.syms[ELF64_R_SYM(r->r_info)];
1356
1357 /* Determine if section has been initialized yet. */
1358 rel = &ew->rel_sections[sym->st_shndx];
1359 if (rel->sec != NULL)
1360 return rel;
1361
1362 memset(&shdr, 0, sizeof(shdr));
1363 shdr.sh_type = SHT_REL;
1364 shdr.sh_link = section_index(ew, ew->symtab_sec);
1365 shdr.sh_info = sym->st_shndx;
1366
1367 if (ew->bit64) {
1368 shdr.sh_addralign = sizeof(Elf64_Addr);
1369 shdr.sh_entsize = sizeof(Elf64_Rel);
1370 } else {
1371 shdr.sh_addralign = sizeof(Elf32_Addr);
1372 shdr.sh_entsize = sizeof(Elf32_Rel);
1373 }
1374
1375 if ((strlen(".rel") + strlen(ew->sections[sym->st_shndx].name) + 1) >
1376 MAX_REL_NAME) {
1377 ERROR("Rel Section name won't fit\n");
1378 return NULL;
1379 }
1380
1381 strcat(rel->name, ".rel");
1382 strcat(rel->name, ew->sections[sym->st_shndx].name);
1383 buffer_init(&b, rel->name, NULL, 0);
1384
1385 elf_writer_add_section(ew, &shdr, &b, rel->name);
1386 rel->sec = last_section(ew);
1387
1388 return rel;
1389}
1390
1391static int add_rel(struct elf_writer_rel *rel_sec, const Elf64_Rel *rel)
1392{
1393 if (rel_sec->num_entries == rel_sec->max_entries) {
1394 size_t num = rel_sec->max_entries * 2;
1395 Elf64_Rel *old_rels;
1396
1397 if (num == 0)
1398 num = 128;
1399
1400 old_rels = rel_sec->rels;
1401 rel_sec->rels = calloc(num, sizeof(Elf64_Rel));
1402
1403 memcpy(rel_sec->rels, old_rels,
1404 rel_sec->num_entries * sizeof(Elf64_Rel));
1405 free(old_rels);
1406
1407 rel_sec->max_entries = num;
1408 }
1409
1410 rel_sec->rels[rel_sec->num_entries] = *rel;
1411 rel_sec->num_entries++;
1412
1413 return 0;
1414}
1415
1416int elf_writer_add_rel(struct elf_writer *ew, const char *sym, Elf64_Addr addr)
1417{
1418 Elf64_Rel rel;
1419 Elf64_Xword sym_info;
1420 int sym_index;
1421 struct elf_writer_rel *rel_sec;
1422
1423 sym_index = elf_sym_index(ew, sym);
1424
1425 if (sym_index < 0) {
1426 ERROR("Unable to locate symbol: %s\n", sym);
1427 return -1;
1428 }
1429
1430 sym_info = sym_index;
1431
1432 /* The relocation type will get fixed prior to serialization. */
1433 rel.r_offset = addr;
1434 rel.r_info = ELF64_R_INFO(sym_info, 0);
1435
1436 rel_sec = rel_section(ew, &rel);
1437
1438 if (rel_sec == NULL)
1439 return -1;
1440
1441 return add_rel(rel_sec, &rel);
1442}