blob: 53fe7a1fcaae2c05e90bb145a8deacd925c66052 [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 *
Elyes HAOUAS3db01982018-08-23 18:08:20 +0200103 * We also must accommodate different ELF files, and hence formats,
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800104 * 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 */
Jacob Garber2d58bf62019-07-02 14:38:38 -0600265 buffer_splice(&b, in, ehdr->e_phoff,
266 (uint32_t)ehdr->e_phentsize * ehdr->e_phnum);
Aaron Durbina983cea2014-03-04 22:08:05 -0600267 if (check_size(in, ehdr->e_phoff, buffer_size(&b), "program headers"))
Aaron Durbind0f61652014-03-05 13:09:55 -0600268 return -1;
Aaron Durbina983cea2014-03-04 22:08:05 -0600269
270 /* gather up all the phdrs.
271 * We do them all at once because there is more
272 * than one loop over all the phdrs.
273 */
Aaron Durbinb1b51182014-03-05 14:54:13 -0600274 phdr = calloc(ehdr->e_phnum, sizeof(*phdr));
Aaron Durbina31ff732014-03-07 15:23:05 -0600275 for (i = 0; i < ehdr->e_phnum; i++) {
276 DEBUG("Parsing segment %d\n", i);
Aaron Durbina983cea2014-03-04 22:08:05 -0600277 elf_phdr(&b, &phdr[i], ehdr->e_phentsize, xdr, bit64);
278
Aaron Durbina31ff732014-03-07 15:23:05 -0600279 /* Ensure the contents are valid within the elf file. */
280 if (check_size(in, phdr[i].p_offset, phdr[i].p_filesz,
Patrick Georgia65c21e2014-08-09 16:58:00 +0200281 "segment contents")) {
282 free(phdr);
Aaron Durbind0f61652014-03-05 13:09:55 -0600283 return -1;
Patrick Georgia65c21e2014-08-09 16:58:00 +0200284 }
Aaron Durbina31ff732014-03-07 15:23:05 -0600285 }
286
Aaron Durbind0f61652014-03-05 13:09:55 -0600287 pelf->phdr = phdr;
288
289 return 0;
Aaron Durbina983cea2014-03-04 22:08:05 -0600290}
291
Aaron Durbind0f61652014-03-05 13:09:55 -0600292static int
293shdr_read(const struct buffer *in, struct parsed_elf *pelf,
294 struct xdr *xdr, int bit64)
Aaron Durbina983cea2014-03-04 22:08:05 -0600295{
296 struct buffer b;
297 Elf64_Shdr *shdr;
Aaron Durbind0f61652014-03-05 13:09:55 -0600298 Elf64_Ehdr *ehdr;
Aaron Durbina983cea2014-03-04 22:08:05 -0600299 int i;
300
Aaron Durbind0f61652014-03-05 13:09:55 -0600301 ehdr = &pelf->ehdr;
302
Aaron Durbina983cea2014-03-04 22:08:05 -0600303 /* cons up an input buffer for the section headers.
304 * Note that the section headers can be anywhere,
305 * per the ELF spec, You'd be surprised how many ELF
306 * readers miss this little detail.
307 */
Jacob Garber2d58bf62019-07-02 14:38:38 -0600308 buffer_splice(&b, in, ehdr->e_shoff,
309 (uint32_t)ehdr->e_shentsize * ehdr->e_shnum);
Aaron Durbina983cea2014-03-04 22:08:05 -0600310 if (check_size(in, ehdr->e_shoff, buffer_size(&b), "section headers"))
Aaron Durbind0f61652014-03-05 13:09:55 -0600311 return -1;
Aaron Durbina983cea2014-03-04 22:08:05 -0600312
313 /* gather up all the shdrs. */
Aaron Durbinb1b51182014-03-05 14:54:13 -0600314 shdr = calloc(ehdr->e_shnum, sizeof(*shdr));
Aaron Durbina31ff732014-03-07 15:23:05 -0600315 for (i = 0; i < ehdr->e_shnum; i++) {
316 DEBUG("Parsing section %d\n", i);
Aaron Durbina983cea2014-03-04 22:08:05 -0600317 elf_shdr(&b, &shdr[i], ehdr->e_shentsize, xdr, bit64);
Aaron Durbina31ff732014-03-07 15:23:05 -0600318 }
319
Aaron Durbind0f61652014-03-05 13:09:55 -0600320 pelf->shdr = shdr;
321
322 return 0;
323}
324
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600325static int
326reloc_read(const struct buffer *in, struct parsed_elf *pelf,
327 struct xdr *xdr, int bit64)
328{
329 struct buffer b;
330 Elf64_Word i;
331 Elf64_Ehdr *ehdr;
332
333 ehdr = &pelf->ehdr;
334 pelf->relocs = calloc(ehdr->e_shnum, sizeof(Elf64_Rela *));
335
336 /* Allocate array for each section that contains relocation entries. */
337 for (i = 0; i < ehdr->e_shnum; i++) {
338 Elf64_Shdr *shdr;
339 Elf64_Rela *rela;
340 Elf64_Xword j;
341 Elf64_Xword nrelocs;
342 int is_rela;
343
344 shdr = &pelf->shdr[i];
345
346 /* Only process REL and RELA sections. */
347 if (shdr->sh_type != SHT_REL && shdr->sh_type != SHT_RELA)
348 continue;
349
350 DEBUG("Checking relocation section %u\n", i);
351
352 /* Ensure the section that relocations apply is a valid. */
353 if (shdr->sh_info >= ehdr->e_shnum ||
354 shdr->sh_info == SHN_UNDEF) {
355 ERROR("Relocations apply to an invalid section: %u\n",
356 shdr[i].sh_info);
357 return -1;
358 }
359
360 is_rela = shdr->sh_type == SHT_RELA;
361
362 /* Determine the number relocations in this section. */
363 nrelocs = shdr->sh_size / shdr->sh_entsize;
364
365 pelf->relocs[i] = calloc(nrelocs, sizeof(Elf64_Rela));
366
367 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
368 if (check_size(in, shdr->sh_offset, buffer_size(&b),
369 "relocation section")) {
370 ERROR("Relocation section %u failed.\n", i);
371 return -1;
372 }
373
374 rela = pelf->relocs[i];
375 for (j = 0; j < nrelocs; j++) {
376 if (bit64) {
377 rela->r_offset = xdr->get64(&b);
378 rela->r_info = xdr->get64(&b);
379 if (is_rela)
380 rela->r_addend = xdr->get64(&b);
381 } else {
382 uint32_t r_info;
383
384 rela->r_offset = xdr->get32(&b);
385 r_info = xdr->get32(&b);
386 rela->r_info = ELF64_R_INFO(ELF32_R_SYM(r_info),
387 ELF32_R_TYPE(r_info));
388 if (is_rela)
389 rela->r_addend = xdr->get32(&b);
390 }
391 rela++;
392 }
393 }
394
395 return 0;
396}
397
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600398static int strtab_read(const struct buffer *in, struct parsed_elf *pelf)
399{
400 Elf64_Ehdr *ehdr;
401 Elf64_Word i;
402
403 ehdr = &pelf->ehdr;
404
405 if (ehdr->e_shstrndx >= ehdr->e_shnum) {
406 ERROR("Section header string table index out of range: %d\n",
407 ehdr->e_shstrndx);
408 return -1;
409 }
410
411 /* For each section of type SHT_STRTAB create a symtab buffer. */
412 pelf->strtabs = calloc(ehdr->e_shnum, sizeof(struct buffer *));
413
414 for (i = 0; i < ehdr->e_shnum; i++) {
415 struct buffer *b;
416 Elf64_Shdr *shdr = &pelf->shdr[i];
417
418 if (shdr->sh_type != SHT_STRTAB)
419 continue;
420
421 b = calloc(1, sizeof(*b));
422 buffer_splice(b, in, shdr->sh_offset, shdr->sh_size);
423 if (check_size(in, shdr->sh_offset, buffer_size(b), "strtab")) {
424 ERROR("STRTAB section not within bounds: %d\n", i);
Patrick Georgia65c21e2014-08-09 16:58:00 +0200425 free(b);
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600426 return -1;
427 }
428 pelf->strtabs[i] = b;
429 }
430
431 return 0;
432}
433
Aaron Durbinc0780942014-03-05 16:41:27 -0600434static int
435symtab_read(const struct buffer *in, struct parsed_elf *pelf,
436 struct xdr *xdr, int bit64)
437{
438 Elf64_Ehdr *ehdr;
439 Elf64_Shdr *shdr;
Damien Zammit00252472017-09-03 21:04:41 +1000440 Elf64_Half shnum;
441 Elf64_Xword i;
Aaron Durbinc0780942014-03-05 16:41:27 -0600442 Elf64_Xword nsyms;
443 Elf64_Sym *sym;
444 struct buffer b;
445
446 ehdr = &pelf->ehdr;
447
448 shdr = NULL;
Damien Zammit00252472017-09-03 21:04:41 +1000449 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
450 if (pelf->shdr[shnum].sh_type != SHT_SYMTAB)
Aaron Durbinc0780942014-03-05 16:41:27 -0600451 continue;
452
453 if (shdr != NULL) {
454 ERROR("Multiple symbol sections found. %u and %u\n",
Damien Zammit00252472017-09-03 21:04:41 +1000455 (unsigned int)(shdr - pelf->shdr), shnum);
Aaron Durbinc0780942014-03-05 16:41:27 -0600456 return -1;
457 }
458
Damien Zammit00252472017-09-03 21:04:41 +1000459 shdr = &pelf->shdr[shnum];
Aaron Durbinc0780942014-03-05 16:41:27 -0600460 }
461
462 if (shdr == NULL) {
463 ERROR("No symbol table found.\n");
464 return -1;
465 }
466
467 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
468 if (check_size(in, shdr->sh_offset, buffer_size(&b), "symtab"))
469 return -1;
470
471 nsyms = shdr->sh_size / shdr->sh_entsize;
472
473 pelf->syms = calloc(nsyms, sizeof(Elf64_Sym));
474
475 for (i = 0; i < nsyms; i++) {
476 sym = &pelf->syms[i];
477
478 if (bit64) {
479 sym->st_name = xdr->get32(&b);
480 sym->st_info = xdr->get8(&b);
481 sym->st_other = xdr->get8(&b);
482 sym->st_shndx = xdr->get16(&b);
483 sym->st_value = xdr->get64(&b);
484 sym->st_size = xdr->get64(&b);
485 } else {
486 sym->st_name = xdr->get32(&b);
487 sym->st_value = xdr->get32(&b);
488 sym->st_size = xdr->get32(&b);
489 sym->st_info = xdr->get8(&b);
490 sym->st_other = xdr->get8(&b);
491 sym->st_shndx = xdr->get16(&b);
492 }
493 }
494
495 return 0;
496}
497
Aaron Durbind0f61652014-03-05 13:09:55 -0600498int parse_elf(const struct buffer *pinput, struct parsed_elf *pelf, int flags)
499{
500 struct xdr *xdr = &xdr_le;
501 int bit64 = 0;
502 struct buffer input;
503 Elf64_Ehdr *ehdr;
504
505 /* Zero out the parsed elf structure. */
506 memset(pelf, 0, sizeof(*pelf));
507
508 if (!iself(buffer_get(pinput))) {
Patrick Georgi8320b9a2017-07-05 13:28:24 +0200509 DEBUG("The stage file is not in ELF format!\n");
Aaron Durbind0f61652014-03-05 13:09:55 -0600510 return -1;
511 }
512
513 buffer_clone(&input, pinput);
514 ehdr = &pelf->ehdr;
515 elf_eident(&input, ehdr);
516 bit64 = ehdr->e_ident[EI_CLASS] == ELFCLASS64;
517 /* Assume LE unless we are sure otherwise.
518 * We're not going to take on the task of
519 * fully validating the ELF file. That way
520 * lies madness.
521 */
522 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
523 xdr = &xdr_be;
524
525 elf_ehdr(&input, ehdr, xdr, bit64);
526
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600527 /* Relocation processing requires section header parsing. */
528 if (flags & ELF_PARSE_RELOC)
529 flags |= ELF_PARSE_SHDR;
530
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600531 /* String table processing requires section header parsing. */
532 if (flags & ELF_PARSE_STRTAB)
533 flags |= ELF_PARSE_SHDR;
534
Aaron Durbinc0780942014-03-05 16:41:27 -0600535 /* Symbole table processing requires section header parsing. */
536 if (flags & ELF_PARSE_SYMTAB)
537 flags |= ELF_PARSE_SHDR;
538
Aaron Durbind0f61652014-03-05 13:09:55 -0600539 if ((flags & ELF_PARSE_PHDR) && phdr_read(pinput, pelf, xdr, bit64))
540 goto fail;
541
542 if ((flags & ELF_PARSE_SHDR) && shdr_read(pinput, pelf, xdr, bit64))
543 goto fail;
544
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600545 if ((flags & ELF_PARSE_RELOC) && reloc_read(pinput, pelf, xdr, bit64))
546 goto fail;
547
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600548 if ((flags & ELF_PARSE_STRTAB) && strtab_read(pinput, pelf))
549 goto fail;
550
Aaron Durbinc0780942014-03-05 16:41:27 -0600551 if ((flags & ELF_PARSE_SYMTAB) && symtab_read(pinput, pelf, xdr, bit64))
552 goto fail;
553
Aaron Durbind0f61652014-03-05 13:09:55 -0600554 return 0;
555
556fail:
557 parsed_elf_destroy(pelf);
558 return -1;
559}
560
561void parsed_elf_destroy(struct parsed_elf *pelf)
562{
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600563 Elf64_Half i;
564
Aaron Durbind0f61652014-03-05 13:09:55 -0600565 free(pelf->phdr);
566 free(pelf->shdr);
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600567 if (pelf->relocs != NULL) {
Aaron Durbinccb5ad82014-03-05 13:57:30 -0600568 for (i = 0; i < pelf->ehdr.e_shnum; i++)
569 free(pelf->relocs[i]);
570 }
571 free(pelf->relocs);
Aaron Durbinc3e6e142014-03-05 14:33:42 -0600572
573 if (pelf->strtabs != NULL) {
574 for (i = 0; i < pelf->ehdr.e_shnum; i++)
575 free(pelf->strtabs[i]);
576 }
577 free(pelf->strtabs);
Aaron Durbinc0780942014-03-05 16:41:27 -0600578 free(pelf->syms);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800579}
580
581/* Get the headers from the buffer.
582 * Return -1 in the event of an error.
583 * The section headers are optional; if NULL
584 * is passed in for pshdr they won't be parsed.
585 * We don't (yet) make payload parsing optional
586 * because we've never seen a use case.
587 */
588int
589elf_headers(const struct buffer *pinput,
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800590 Elf64_Ehdr *ehdr,
591 Elf64_Phdr **pphdr,
592 Elf64_Shdr **pshdr)
593{
Aaron Durbind0f61652014-03-05 13:09:55 -0600594 struct parsed_elf pelf;
595 int flags;
Aaron Durbina983cea2014-03-04 22:08:05 -0600596
Aaron Durbind0f61652014-03-05 13:09:55 -0600597 flags = ELF_PARSE_PHDR;
598
599 if (pshdr != NULL)
600 flags |= ELF_PARSE_SHDR;
601
602 if (parse_elf(pinput, &pelf, flags))
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800603 return -1;
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800604
Aaron Durbind0f61652014-03-05 13:09:55 -0600605 /* Copy out the parsed elf header. */
606 memcpy(ehdr, &pelf.ehdr, sizeof(*ehdr));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800607
Aaron Durbind0f61652014-03-05 13:09:55 -0600608 *pphdr = calloc(ehdr->e_phnum, sizeof(Elf64_Phdr));
609 memcpy(*pphdr, pelf.phdr, ehdr->e_phnum * sizeof(Elf64_Phdr));
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800610
Aaron Durbind0f61652014-03-05 13:09:55 -0600611 if (pshdr != NULL) {
612 *pshdr = calloc(ehdr->e_shnum, sizeof(Elf64_Shdr));
613 memcpy(*pshdr, pelf.shdr, ehdr->e_shnum * sizeof(Elf64_Shdr));
614 }
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800615
Aaron Durbind0f61652014-03-05 13:09:55 -0600616 parsed_elf_destroy(&pelf);
Ronald G. Minnicha8a133d2013-12-30 13:16:18 -0800617
618 return 0;
619}
Aaron Durbin36be8132014-03-11 11:48:56 -0500620
621/* ELF Writing Support
622 *
623 * The ELF file is written according to the following layout:
624 * +------------------+
625 * | ELF Header |
626 * +------------------+
627 * | Section Headers |
628 * +------------------+
629 * | Program Headers |
630 * +------------------+
631 * | String table |
632 * +------------------+ <- 4KiB Aligned
633 * | Code/Data |
634 * +------------------+
635 */
636
Aaron Durbin4f930c92015-10-27 16:21:55 -0500637void elf_init_eheader(Elf64_Ehdr *ehdr, int machine, int nbits, int endian)
638{
639 memset(ehdr, 0, sizeof(*ehdr));
640 ehdr->e_ident[EI_MAG0] = ELFMAG0;
641 ehdr->e_ident[EI_MAG1] = ELFMAG1;
642 ehdr->e_ident[EI_MAG2] = ELFMAG2;
643 ehdr->e_ident[EI_MAG3] = ELFMAG3;
644 ehdr->e_ident[EI_CLASS] = nbits;
645 ehdr->e_ident[EI_DATA] = endian;
646 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
647 ehdr->e_type = ET_EXEC;
648 ehdr->e_machine = machine;
649 ehdr->e_version = EV_CURRENT;
650 if (nbits == ELFCLASS64) {
651 ehdr->e_ehsize = sizeof(Elf64_Ehdr);
652 ehdr->e_phentsize = sizeof(Elf64_Phdr);
653 ehdr->e_shentsize = sizeof(Elf64_Shdr);
654 } else {
655 ehdr->e_ehsize = sizeof(Elf32_Ehdr);
656 ehdr->e_phentsize = sizeof(Elf32_Phdr);
657 ehdr->e_shentsize = sizeof(Elf32_Shdr);
658 }
659}
660
Patrick Georgi01cfecc2020-01-29 13:31:16 +0100661/* Arbitrary maximum number of sections. */
Aaron Durbin36be8132014-03-11 11:48:56 -0500662#define MAX_SECTIONS 16
663struct elf_writer_section {
664 Elf64_Shdr shdr;
665 struct buffer content;
666 const char *name;
667};
668
Aaron Durbincedcb882015-10-28 11:26:40 -0500669struct elf_writer_string_table {
670 size_t next_offset;
671 size_t max_size;
672 char *buffer;
673};
674
675struct elf_writer_sym_table {
676 size_t max_entries;
677 size_t num_entries;
678 Elf64_Sym *syms;
679};
680
681#define MAX_REL_NAME 32
682struct elf_writer_rel {
683 size_t num_entries;
684 size_t max_entries;
685 Elf64_Rel *rels;
686 struct elf_writer_section *sec;
687 char name[MAX_REL_NAME];
688};
689
Aaron Durbin36be8132014-03-11 11:48:56 -0500690struct elf_writer
691{
692 Elf64_Ehdr ehdr;
693 struct xdr *xdr;
694 size_t num_secs;
695 struct elf_writer_section sections[MAX_SECTIONS];
Aaron Durbincedcb882015-10-28 11:26:40 -0500696 struct elf_writer_rel rel_sections[MAX_SECTIONS];
Aaron Durbin36be8132014-03-11 11:48:56 -0500697 Elf64_Phdr *phdrs;
Aaron Durbincedcb882015-10-28 11:26:40 -0500698 struct elf_writer_section *shstrtab_sec;
699 struct elf_writer_section *strtab_sec;
700 struct elf_writer_section *symtab_sec;
701 struct elf_writer_string_table strtab;
702 struct elf_writer_sym_table symtab;
Aaron Durbin36be8132014-03-11 11:48:56 -0500703 int bit64;
704};
705
Aaron Durbincedcb882015-10-28 11:26:40 -0500706static size_t section_index(struct elf_writer *ew,
707 struct elf_writer_section *sec)
708{
709 return sec - &ew->sections[0];
710}
711
712static struct elf_writer_section *last_section(struct elf_writer *ew)
713{
714 return &ew->sections[ew->num_secs - 1];
715}
716
717static void strtab_init(struct elf_writer *ew, size_t size)
718{
719 struct buffer b;
720 Elf64_Shdr shdr;
721
722 /* Start adding strings after the initial NUL entry. */
723 ew->strtab.next_offset = 1;
724 ew->strtab.max_size = size;
725 ew->strtab.buffer = calloc(1, ew->strtab.max_size);
726
727 buffer_init(&b, NULL, ew->strtab.buffer, ew->strtab.max_size);
728 memset(&shdr, 0, sizeof(shdr));
729 shdr.sh_type = SHT_STRTAB;
730 shdr.sh_addralign = 1;
731 shdr.sh_size = ew->strtab.max_size;
732 elf_writer_add_section(ew, &shdr, &b, ".strtab");
733 ew->strtab_sec = last_section(ew);
734}
735
736static void symtab_init(struct elf_writer *ew, size_t max_entries)
737{
738 struct buffer b;
739 Elf64_Shdr shdr;
740
741 memset(&shdr, 0, sizeof(shdr));
742 shdr.sh_type = SHT_SYMTAB;
743
744 if (ew->bit64) {
745 shdr.sh_entsize = sizeof(Elf64_Sym);
746 shdr.sh_addralign = sizeof(Elf64_Addr);
747 } else {
748 shdr.sh_entsize = sizeof(Elf32_Sym);
749 shdr.sh_addralign = sizeof(Elf32_Addr);
750 }
751
752 shdr.sh_size = shdr.sh_entsize * max_entries;
753
754 ew->symtab.syms = calloc(max_entries, sizeof(Elf64_Sym));
755 ew->symtab.num_entries = 1;
756 ew->symtab.max_entries = max_entries;
757
758 buffer_init(&b, NULL, ew->symtab.syms, shdr.sh_size);
759
760 elf_writer_add_section(ew, &shdr, &b, ".symtab");
761 ew->symtab_sec = last_section(ew);
762}
763
Aaron Durbin36be8132014-03-11 11:48:56 -0500764struct elf_writer *elf_writer_init(const Elf64_Ehdr *ehdr)
765{
766 struct elf_writer *ew;
767 Elf64_Shdr shdr;
768 struct buffer empty_buffer;
769
770 if (!iself(ehdr))
771 return NULL;
772
773 ew = calloc(1, sizeof(*ew));
774
775 memcpy(&ew->ehdr, ehdr, sizeof(ew->ehdr));
776
777 ew->bit64 = ew->ehdr.e_ident[EI_CLASS] == ELFCLASS64;
778
779 /* Set the endinan ops. */
780 if (ew->ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
781 ew->xdr = &xdr_be;
782 else
783 ew->xdr = &xdr_le;
784
785 /* Reset count and offsets */
786 ew->ehdr.e_phoff = 0;
787 ew->ehdr.e_shoff = 0;
788 ew->ehdr.e_shnum = 0;
789 ew->ehdr.e_phnum = 0;
790
791 memset(&empty_buffer, 0, sizeof(empty_buffer));
792 memset(&shdr, 0, sizeof(shdr));
793
794 /* Add SHT_NULL section header. */
795 shdr.sh_type = SHT_NULL;
796 elf_writer_add_section(ew, &shdr, &empty_buffer, NULL);
797
798 /* Add section header string table and maintain reference to it. */
799 shdr.sh_type = SHT_STRTAB;
800 elf_writer_add_section(ew, &shdr, &empty_buffer, ".shstrtab");
Aaron Durbincedcb882015-10-28 11:26:40 -0500801 ew->shstrtab_sec = last_section(ew);
802 ew->ehdr.e_shstrndx = section_index(ew, ew->shstrtab_sec);
803
804 /* Add a small string table and symbol table. */
805 strtab_init(ew, 4096);
806 symtab_init(ew, 100);
Aaron Durbin36be8132014-03-11 11:48:56 -0500807
808 return ew;
809}
810
811/*
812 * Clean up any internal state represented by ew. Aftewards the elf_writer
813 * is invalid.
Furquan Shaikhb927bec2016-08-05 12:04:55 -0700814 * It is safe to call elf_writer_destroy with ew as NULL. It returns without
815 * performing any action.
Aaron Durbin36be8132014-03-11 11:48:56 -0500816 */
817void elf_writer_destroy(struct elf_writer *ew)
818{
Aaron Durbincedcb882015-10-28 11:26:40 -0500819 int i;
Furquan Shaikhb927bec2016-08-05 12:04:55 -0700820 if (ew == NULL)
821 return;
Aaron Durbin36be8132014-03-11 11:48:56 -0500822 if (ew->phdrs != NULL)
823 free(ew->phdrs);
Aaron Durbincedcb882015-10-28 11:26:40 -0500824 free(ew->strtab.buffer);
825 free(ew->symtab.syms);
826 for (i = 0; i < MAX_SECTIONS; i++)
827 free(ew->rel_sections[i].rels);
Aaron Durbin36be8132014-03-11 11:48:56 -0500828 free(ew);
829}
830
831/*
832 * Add a section to the ELF file. Section type, flags, and memsize are
833 * maintained from the passed in Elf64_Shdr. The buffer represents the
834 * content of the section while the name is the name of section itself.
835 * Returns < 0 on error, 0 on success.
836 */
837int elf_writer_add_section(struct elf_writer *ew, const Elf64_Shdr *shdr,
838 struct buffer *contents, const char *name)
839{
840 struct elf_writer_section *newsh;
841
842 if (ew->num_secs == MAX_SECTIONS)
843 return -1;
844
845 newsh = &ew->sections[ew->num_secs];
846 ew->num_secs++;
847
848 memcpy(&newsh->shdr, shdr, sizeof(newsh->shdr));
849 newsh->shdr.sh_offset = 0;
850
851 newsh->name = name;
852 if (contents != NULL)
853 buffer_clone(&newsh->content, contents);
854
855 return 0;
856}
857
858static void ehdr_write(struct elf_writer *ew, struct buffer *m)
859{
860 int i;
861
862 for (i = 0; i < EI_NIDENT; i++)
863 ew->xdr->put8(m, ew->ehdr.e_ident[i]);
864 ew->xdr->put16(m, ew->ehdr.e_type);
865 ew->xdr->put16(m, ew->ehdr.e_machine);
866 ew->xdr->put32(m, ew->ehdr.e_version);
867 if (ew->bit64) {
868 ew->xdr->put64(m, ew->ehdr.e_entry);
869 ew->xdr->put64(m, ew->ehdr.e_phoff);
870 ew->xdr->put64(m, ew->ehdr.e_shoff);
871 } else {
872 ew->xdr->put32(m, ew->ehdr.e_entry);
873 ew->xdr->put32(m, ew->ehdr.e_phoff);
874 ew->xdr->put32(m, ew->ehdr.e_shoff);
875 }
876 ew->xdr->put32(m, ew->ehdr.e_flags);
877 ew->xdr->put16(m, ew->ehdr.e_ehsize);
878 ew->xdr->put16(m, ew->ehdr.e_phentsize);
879 ew->xdr->put16(m, ew->ehdr.e_phnum);
880 ew->xdr->put16(m, ew->ehdr.e_shentsize);
881 ew->xdr->put16(m, ew->ehdr.e_shnum);
882 ew->xdr->put16(m, ew->ehdr.e_shstrndx);
883}
884
885static void shdr_write(struct elf_writer *ew, size_t n, struct buffer *m)
886{
887 struct xdr *xdr = ew->xdr;
888 int bit64 = ew->bit64;
889 struct elf_writer_section *sec = &ew->sections[n];
890 Elf64_Shdr *shdr = &sec->shdr;
891
892 xdr->put32(m, shdr->sh_name);
893 xdr->put32(m, shdr->sh_type);
Aaron Durbin36be8132014-03-11 11:48:56 -0500894 if (bit64) {
Aaron Durbinbc349b82014-08-22 14:05:00 -0500895 xdr->put64(m, shdr->sh_flags);
Aaron Durbin36be8132014-03-11 11:48:56 -0500896 xdr->put64(m, shdr->sh_addr);
897 xdr->put64(m, shdr->sh_offset);
898 xdr->put64(m, shdr->sh_size);
899 xdr->put32(m, shdr->sh_link);
900 xdr->put32(m, shdr->sh_info);
901 xdr->put64(m, shdr->sh_addralign);
902 xdr->put64(m, shdr->sh_entsize);
903 } else {
Aaron Durbinbc349b82014-08-22 14:05:00 -0500904 xdr->put32(m, shdr->sh_flags);
Aaron Durbin36be8132014-03-11 11:48:56 -0500905 xdr->put32(m, shdr->sh_addr);
906 xdr->put32(m, shdr->sh_offset);
907 xdr->put32(m, shdr->sh_size);
908 xdr->put32(m, shdr->sh_link);
909 xdr->put32(m, shdr->sh_info);
910 xdr->put32(m, shdr->sh_addralign);
911 xdr->put32(m, shdr->sh_entsize);
912 }
913}
914
915static void
916phdr_write(struct elf_writer *ew, struct buffer *m, Elf64_Phdr *phdr)
917{
918 if (ew->bit64) {
919 ew->xdr->put32(m, phdr->p_type);
920 ew->xdr->put32(m, phdr->p_flags);
921 ew->xdr->put64(m, phdr->p_offset);
922 ew->xdr->put64(m, phdr->p_vaddr);
923 ew->xdr->put64(m, phdr->p_paddr);
924 ew->xdr->put64(m, phdr->p_filesz);
925 ew->xdr->put64(m, phdr->p_memsz);
926 ew->xdr->put64(m, phdr->p_align);
927 } else {
928 ew->xdr->put32(m, phdr->p_type);
929 ew->xdr->put32(m, phdr->p_offset);
930 ew->xdr->put32(m, phdr->p_vaddr);
931 ew->xdr->put32(m, phdr->p_paddr);
932 ew->xdr->put32(m, phdr->p_filesz);
933 ew->xdr->put32(m, phdr->p_memsz);
934 ew->xdr->put32(m, phdr->p_flags);
935 ew->xdr->put32(m, phdr->p_align);
936 }
937
938}
939
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500940static int section_consecutive(struct elf_writer *ew, Elf64_Half secidx)
941{
942 Elf64_Half i;
943 struct elf_writer_section *prev_alloc = NULL;
944
945 if (secidx == 0)
946 return 0;
947
948 for (i = 0; i < secidx; i++) {
949 if (ew->sections[i].shdr.sh_flags & SHF_ALLOC)
950 prev_alloc = &ew->sections[i];
951 }
952
953 if (prev_alloc == NULL)
954 return 0;
955
956 if (prev_alloc->shdr.sh_addr + prev_alloc->shdr.sh_size ==
957 ew->sections[secidx].shdr.sh_addr)
958 return 1;
959
960 return 0;
961}
962
963static void write_phdrs(struct elf_writer *ew, struct buffer *phdrs)
964{
965 Elf64_Half i;
966 Elf64_Phdr phdr;
967 size_t num_written = 0;
Antonello Dettori3bded7d2016-06-16 13:40:24 +0200968 size_t num_needs_write = 0;
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500969
970 for (i = 0; i < ew->num_secs; i++) {
971 struct elf_writer_section *sec = &ew->sections[i];
972
973 if (!(sec->shdr.sh_flags & SHF_ALLOC))
974 continue;
975
976 if (!section_consecutive(ew, i)) {
977 /* Write out previously set phdr. */
Antonello Dettori3bded7d2016-06-16 13:40:24 +0200978 if (num_needs_write != num_written) {
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500979 phdr_write(ew, phdrs, &phdr);
980 num_written++;
981 }
982 phdr.p_type = PT_LOAD;
983 phdr.p_offset = sec->shdr.sh_offset;
984 phdr.p_vaddr = sec->shdr.sh_addr;
985 phdr.p_paddr = sec->shdr.sh_addr;
986 phdr.p_filesz = buffer_size(&sec->content);
987 phdr.p_memsz = sec->shdr.sh_size;
988 phdr.p_flags = 0;
989 if (sec->shdr.sh_flags & SHF_EXECINSTR)
990 phdr.p_flags |= PF_X | PF_R;
991 if (sec->shdr.sh_flags & SHF_WRITE)
992 phdr.p_flags |= PF_W;
993 phdr.p_align = sec->shdr.sh_addralign;
Antonello Dettori3bded7d2016-06-16 13:40:24 +0200994 num_needs_write++;
995
Aaron Durbin8e982ea2015-10-28 10:09:07 -0500996 } else {
997 /* Accumulate file size and memsize. The assumption
998 * is that each section is either NOBITS or full
999 * (sh_size == file size). This is standard in that
1000 * an ELF section doesn't have a file size component. */
1001 if (sec->shdr.sh_flags & SHF_EXECINSTR)
1002 phdr.p_flags |= PF_X | PF_R;
1003 if (sec->shdr.sh_flags & SHF_WRITE)
1004 phdr.p_flags |= PF_W;
1005 phdr.p_filesz += buffer_size(&sec->content);
1006 phdr.p_memsz += sec->shdr.sh_size;
1007 }
1008 }
1009
1010 /* Write out the last phdr. */
Antonello Dettori3bded7d2016-06-16 13:40:24 +02001011 if (num_needs_write != num_written) {
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001012 phdr_write(ew, phdrs, &phdr);
Antonello Dettori3bded7d2016-06-16 13:40:24 +02001013 num_written++;
1014 }
1015 assert(num_written == ew->ehdr.e_phnum);
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001016}
1017
Aaron Durbincedcb882015-10-28 11:26:40 -05001018static void fixup_symbol_table(struct elf_writer *ew)
1019{
1020 struct elf_writer_section *sec = ew->symtab_sec;
1021
1022 /* If there is only the NULL section, mark section as inactive. */
1023 if (ew->symtab.num_entries == 1) {
1024 sec->shdr.sh_type = SHT_NULL;
1025 sec->shdr.sh_size = 0;
1026 } else {
1027 size_t i;
1028 struct buffer wr;
1029
1030 buffer_clone(&wr, &sec->content);
1031 /* To appease xdr. */
1032 buffer_set_size(&wr, 0);
1033 for (i = 0; i < ew->symtab.num_entries; i++) {
1034 /* Create local copy as were over-writing backing
1035 * store of the symbol. */
1036 Elf64_Sym sym = ew->symtab.syms[i];
1037 if (ew->bit64) {
1038 ew->xdr->put32(&wr, sym.st_name);
1039 ew->xdr->put8(&wr, sym.st_info);
1040 ew->xdr->put8(&wr, sym.st_other);
1041 ew->xdr->put16(&wr, sym.st_shndx);
1042 ew->xdr->put64(&wr, sym.st_value);
1043 ew->xdr->put64(&wr, sym.st_size);
1044 } else {
1045 ew->xdr->put32(&wr, sym.st_name);
1046 ew->xdr->put32(&wr, sym.st_value);
1047 ew->xdr->put32(&wr, sym.st_size);
1048 ew->xdr->put8(&wr, sym.st_info);
1049 ew->xdr->put8(&wr, sym.st_other);
1050 ew->xdr->put16(&wr, sym.st_shndx);
1051 }
1052 }
1053
1054 /* Update section size. */
1055 sec->shdr.sh_size = sec->shdr.sh_entsize;
1056 sec->shdr.sh_size *= ew->symtab.num_entries;
1057
1058 /* Fix up sh_link to point to string table. */
1059 sec->shdr.sh_link = section_index(ew, ew->strtab_sec);
1060 /* sh_info is supposed to be 1 greater than symbol table
1061 * index of last local binding. Just use max symbols. */
1062 sec->shdr.sh_info = ew->symtab.num_entries;
1063 }
1064
1065 buffer_set_size(&sec->content, sec->shdr.sh_size);
1066}
1067
1068static void fixup_relocations(struct elf_writer *ew)
1069{
1070 int i;
1071 Elf64_Xword type;
1072
1073 switch (ew->ehdr.e_machine) {
1074 case EM_386:
1075 type = R_386_32;
1076 break;
Patrick Rudolph565bebe2018-11-26 15:54:21 +01001077 case EM_X86_64:
1078 type = R_AMD64_64;
1079 break;
Aaron Durbincedcb882015-10-28 11:26:40 -05001080 case EM_ARM:
1081 type = R_ARM_ABS32;
1082 break;
1083 case EM_AARCH64:
1084 type = R_AARCH64_ABS64;
1085 break;
1086 case EM_MIPS:
1087 type = R_MIPS_32;
1088 break;
1089 case EM_RISCV:
1090 type = R_RISCV_32;
1091 break;
Ronald G. Minniched4aa042015-12-11 18:19:52 +00001092 case EM_PPC64:
1093 type = R_PPC64_ADDR32;
1094 break;
Aaron Durbincedcb882015-10-28 11:26:40 -05001095 default:
1096 ERROR("Unable to handle relocations for e_machine %x\n",
1097 ew->ehdr.e_machine);
1098 return;
1099 }
1100
1101 for (i = 0; i < MAX_SECTIONS; i++) {
1102 struct elf_writer_rel *rel_sec = &ew->rel_sections[i];
1103 struct elf_writer_section *sec = rel_sec->sec;
1104 struct buffer writer;
1105 size_t j;
1106
1107 if (sec == NULL)
1108 continue;
1109
1110 /* Update section header size as well as content size. */
1111 buffer_init(&sec->content, sec->content.name, rel_sec->rels,
1112 rel_sec->num_entries * sec->shdr.sh_entsize);
1113 sec->shdr.sh_size = buffer_size(&sec->content);
1114 buffer_clone(&writer, &sec->content);
1115 /* To make xdr happy. */
1116 buffer_set_size(&writer, 0);
1117
1118 for (j = 0; j < ew->rel_sections[i].num_entries; j++) {
1119 /* Make copy as we're overwriting backing store. */
1120 Elf64_Rel rel = rel_sec->rels[j];
1121 rel.r_info = ELF64_R_INFO(ELF64_R_SYM(rel.r_info),
1122 ELF64_R_TYPE(type));
1123
1124 if (ew->bit64) {
1125 ew->xdr->put64(&writer, rel.r_offset);
1126 ew->xdr->put64(&writer, rel.r_info);
1127 } else {
1128 Elf32_Rel rel32;
1129 rel32.r_offset = rel.r_offset;
1130 rel32.r_info =
1131 ELF32_R_INFO(ELF64_R_SYM(rel.r_info),
1132 ELF64_R_TYPE(rel.r_info));
1133 ew->xdr->put32(&writer, rel32.r_offset);
1134 ew->xdr->put32(&writer, rel32.r_info);
1135 }
1136 }
1137 }
1138}
1139
Aaron Durbin36be8132014-03-11 11:48:56 -05001140/*
1141 * Serialize the ELF file to the output buffer. Return < 0 on error,
1142 * 0 on success.
1143 */
1144int elf_writer_serialize(struct elf_writer *ew, struct buffer *out)
1145{
1146 Elf64_Half i;
1147 Elf64_Xword metadata_size;
1148 Elf64_Xword program_size;
1149 Elf64_Off shstroffset;
1150 size_t shstrlen;
1151 struct buffer metadata;
1152 struct buffer phdrs;
1153 struct buffer data;
1154 struct buffer *strtab;
1155
1156 INFO("Writing %zu sections.\n", ew->num_secs);
1157
Aaron Durbincedcb882015-10-28 11:26:40 -05001158 /* Perform any necessary work for special sections. */
1159 fixup_symbol_table(ew);
1160 fixup_relocations(ew);
1161
Aaron Durbin36be8132014-03-11 11:48:56 -05001162 /* Determine size of sections to be written. */
1163 program_size = 0;
1164 /* Start with 1 byte for first byte of section header string table. */
1165 shstrlen = 1;
1166 for (i = 0; i < ew->num_secs; i++) {
1167 struct elf_writer_section *sec = &ew->sections[i];
1168
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001169 if (sec->shdr.sh_flags & SHF_ALLOC) {
1170 if (!section_consecutive(ew, i))
1171 ew->ehdr.e_phnum++;
1172 }
Aaron Durbin36be8132014-03-11 11:48:56 -05001173
1174 program_size += buffer_size(&sec->content);
1175
1176 /* Keep track of the length sections' names. */
1177 if (sec->name != NULL) {
1178 sec->shdr.sh_name = shstrlen;
1179 shstrlen += strlen(sec->name) + 1;
1180 }
1181 }
1182 ew->ehdr.e_shnum = ew->num_secs;
1183 metadata_size = 0;
1184 metadata_size += ew->ehdr.e_ehsize;
Jacob Garber2d58bf62019-07-02 14:38:38 -06001185 metadata_size += (Elf64_Xword)ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1186 metadata_size += (Elf64_Xword)ew->ehdr.e_phnum * ew->ehdr.e_phentsize;
Aaron Durbin36be8132014-03-11 11:48:56 -05001187 shstroffset = metadata_size;
1188 /* Align up section header string size and metadata size to 4KiB */
1189 metadata_size = ALIGN(metadata_size + shstrlen, 4096);
1190
1191 if (buffer_create(out, metadata_size + program_size, "elfout")) {
1192 ERROR("Could not create output buffer for ELF.\n");
1193 return -1;
1194 }
1195
1196 INFO("Created %zu output buffer for ELF file.\n", buffer_size(out));
1197
1198 /*
1199 * Write out ELF header. Section headers come right after ELF header
1200 * followed by the program headers. Buffers need to be created first
1201 * to do the writing.
1202 */
1203 ew->ehdr.e_shoff = ew->ehdr.e_ehsize;
1204 ew->ehdr.e_phoff = ew->ehdr.e_shoff +
Jacob Garber2d58bf62019-07-02 14:38:38 -06001205 (Elf64_Off)ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
Aaron Durbin36be8132014-03-11 11:48:56 -05001206
1207 buffer_splice(&metadata, out, 0, metadata_size);
1208 buffer_splice(&phdrs, out, ew->ehdr.e_phoff,
Jacob Garber2d58bf62019-07-02 14:38:38 -06001209 (uint32_t)ew->ehdr.e_phnum * ew->ehdr.e_phentsize);
Aaron Durbin36be8132014-03-11 11:48:56 -05001210 buffer_splice(&data, out, metadata_size, program_size);
1211 /* Set up the section header string table contents. */
Aaron Durbincedcb882015-10-28 11:26:40 -05001212 strtab = &ew->shstrtab_sec->content;
Aaron Durbin36be8132014-03-11 11:48:56 -05001213 buffer_splice(strtab, out, shstroffset, shstrlen);
Aaron Durbincedcb882015-10-28 11:26:40 -05001214 ew->shstrtab_sec->shdr.sh_size = shstrlen;
Aaron Durbin36be8132014-03-11 11:48:56 -05001215
1216 /* Reset current locations. */
1217 buffer_set_size(&metadata, 0);
1218 buffer_set_size(&data, 0);
1219 buffer_set_size(&phdrs, 0);
1220 buffer_set_size(strtab, 0);
1221
1222 /* ELF Header */
1223 ehdr_write(ew, &metadata);
1224
1225 /* Write out section headers, section strings, section content, and
1226 * program headers. */
1227 ew->xdr->put8(strtab, 0);
1228 for (i = 0; i < ew->num_secs; i++) {
Aaron Durbin36be8132014-03-11 11:48:56 -05001229 struct elf_writer_section *sec = &ew->sections[i];
1230
Aaron Durbincedcb882015-10-28 11:26:40 -05001231 /* Update section offsets. Be sure to not update SHN_UNDEF. */
1232 if (sec == ew->shstrtab_sec)
Aaron Durbin36be8132014-03-11 11:48:56 -05001233 sec->shdr.sh_offset = shstroffset;
Aaron Durbincedcb882015-10-28 11:26:40 -05001234 else if (i != SHN_UNDEF)
Aaron Durbin36be8132014-03-11 11:48:56 -05001235 sec->shdr.sh_offset = buffer_size(&data) +
1236 metadata_size;
Aaron Durbincedcb882015-10-28 11:26:40 -05001237
Aaron Durbin36be8132014-03-11 11:48:56 -05001238 shdr_write(ew, i, &metadata);
1239
1240 /* Add section name to string table. */
1241 if (sec->name != NULL)
1242 bputs(strtab, sec->name, strlen(sec->name) + 1);
1243
Aaron Durbincedcb882015-10-28 11:26:40 -05001244 /* Output section data for all sections but SHN_UNDEF and
1245 * section header string table. */
1246 if (i != SHN_UNDEF && sec != ew->shstrtab_sec)
1247 bputs(&data, buffer_get(&sec->content),
1248 buffer_size(&sec->content));
Aaron Durbin36be8132014-03-11 11:48:56 -05001249 }
1250
Aaron Durbin8e982ea2015-10-28 10:09:07 -05001251 write_phdrs(ew, &phdrs);
1252
Aaron Durbin36be8132014-03-11 11:48:56 -05001253 return 0;
1254}
Aaron Durbincedcb882015-10-28 11:26:40 -05001255
1256/* Add a string to the string table returning index on success, < 0 on error. */
1257static int elf_writer_add_string(struct elf_writer *ew, const char *new)
1258{
1259 size_t current_offset;
1260 size_t new_len;
1261
1262 for (current_offset = 0; current_offset < ew->strtab.next_offset; ) {
1263 const char *str = ew->strtab.buffer + current_offset;
1264 size_t len = strlen(str) + 1;
1265
1266 if (!strcmp(str, new))
1267 return current_offset;
1268 current_offset += len;
1269 }
1270
1271 new_len = strlen(new) + 1;
1272
1273 if (current_offset + new_len > ew->strtab.max_size) {
1274 ERROR("No space for string in .strtab.\n");
1275 return -1;
1276 }
1277
1278 memcpy(ew->strtab.buffer + current_offset, new, new_len);
1279 ew->strtab.next_offset = current_offset + new_len;
1280
1281 return current_offset;
1282}
1283
1284static int elf_writer_section_index(struct elf_writer *ew, const char *name)
1285{
1286 size_t i;
1287
1288 for (i = 0; i < ew->num_secs; i++) {
1289 if (ew->sections[i].name == NULL)
1290 continue;
1291 if (!strcmp(ew->sections[i].name, name))
1292 return i;
1293 }
1294
1295 ERROR("ELF Section not found: %s\n", name);
1296
1297 return -1;
1298}
1299
1300int elf_writer_add_symbol(struct elf_writer *ew, const char *name,
1301 const char *section_name,
1302 Elf64_Addr value, Elf64_Word size,
1303 int binding, int type)
1304{
Patrick Georgi172a14d2015-10-31 01:35:20 +01001305 int i;
Aaron Durbincedcb882015-10-28 11:26:40 -05001306 Elf64_Sym sym = {
1307 .st_value = value,
1308 .st_size = size,
1309 .st_info = ELF64_ST_INFO(binding, type),
1310 };
1311
1312 if (ew->symtab.max_entries == ew->symtab.num_entries) {
1313 ERROR("No more symbol entries left.\n");
1314 return -1;
1315 }
1316
Patrick Georgi172a14d2015-10-31 01:35:20 +01001317 i = elf_writer_add_string(ew, 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_name = i;
Aaron Durbincedcb882015-10-28 11:26:40 -05001321
Patrick Georgi172a14d2015-10-31 01:35:20 +01001322 i = elf_writer_section_index(ew, section_name);
1323 if (i < 0)
Aaron Durbincedcb882015-10-28 11:26:40 -05001324 return -1;
Patrick Georgi172a14d2015-10-31 01:35:20 +01001325 sym.st_shndx = i;
Aaron Durbincedcb882015-10-28 11:26:40 -05001326
1327 ew->symtab.syms[ew->symtab.num_entries++] = sym;
1328
1329 return 0;
1330}
1331
1332static int elf_sym_index(struct elf_writer *ew, const char *sym)
1333{
Patrick Georgi172a14d2015-10-31 01:35:20 +01001334 int j;
Aaron Durbincedcb882015-10-28 11:26:40 -05001335 size_t i;
1336 Elf64_Word st_name;
1337
1338 /* Determine index of symbol in the string table. */
Patrick Georgi172a14d2015-10-31 01:35:20 +01001339 j = elf_writer_add_string(ew, sym);
1340 if (j < 0)
Aaron Durbincedcb882015-10-28 11:26:40 -05001341 return -1;
1342
Patrick Georgi172a14d2015-10-31 01:35:20 +01001343 st_name = j;
Aaron Durbincedcb882015-10-28 11:26:40 -05001344
1345 for (i = 0; i < ew->symtab.num_entries; i++)
1346 if (ew->symtab.syms[i].st_name == st_name)
1347 return i;
1348
1349 return -1;
1350}
1351
1352static struct elf_writer_rel *rel_section(struct elf_writer *ew,
1353 const Elf64_Rel *r)
1354{
1355 Elf64_Sym *sym;
1356 struct elf_writer_rel *rel;
1357 Elf64_Shdr shdr;
1358 struct buffer b;
1359
1360 sym = &ew->symtab.syms[ELF64_R_SYM(r->r_info)];
1361
1362 /* Determine if section has been initialized yet. */
1363 rel = &ew->rel_sections[sym->st_shndx];
1364 if (rel->sec != NULL)
1365 return rel;
1366
1367 memset(&shdr, 0, sizeof(shdr));
1368 shdr.sh_type = SHT_REL;
1369 shdr.sh_link = section_index(ew, ew->symtab_sec);
1370 shdr.sh_info = sym->st_shndx;
1371
1372 if (ew->bit64) {
1373 shdr.sh_addralign = sizeof(Elf64_Addr);
1374 shdr.sh_entsize = sizeof(Elf64_Rel);
1375 } else {
1376 shdr.sh_addralign = sizeof(Elf32_Addr);
1377 shdr.sh_entsize = sizeof(Elf32_Rel);
1378 }
1379
1380 if ((strlen(".rel") + strlen(ew->sections[sym->st_shndx].name) + 1) >
1381 MAX_REL_NAME) {
1382 ERROR("Rel Section name won't fit\n");
1383 return NULL;
1384 }
1385
1386 strcat(rel->name, ".rel");
1387 strcat(rel->name, ew->sections[sym->st_shndx].name);
1388 buffer_init(&b, rel->name, NULL, 0);
1389
1390 elf_writer_add_section(ew, &shdr, &b, rel->name);
1391 rel->sec = last_section(ew);
1392
1393 return rel;
1394}
1395
1396static int add_rel(struct elf_writer_rel *rel_sec, const Elf64_Rel *rel)
1397{
1398 if (rel_sec->num_entries == rel_sec->max_entries) {
1399 size_t num = rel_sec->max_entries * 2;
1400 Elf64_Rel *old_rels;
1401
1402 if (num == 0)
1403 num = 128;
1404
1405 old_rels = rel_sec->rels;
1406 rel_sec->rels = calloc(num, sizeof(Elf64_Rel));
1407
1408 memcpy(rel_sec->rels, old_rels,
1409 rel_sec->num_entries * sizeof(Elf64_Rel));
1410 free(old_rels);
1411
1412 rel_sec->max_entries = num;
1413 }
1414
1415 rel_sec->rels[rel_sec->num_entries] = *rel;
1416 rel_sec->num_entries++;
1417
1418 return 0;
1419}
1420
1421int elf_writer_add_rel(struct elf_writer *ew, const char *sym, Elf64_Addr addr)
1422{
1423 Elf64_Rel rel;
1424 Elf64_Xword sym_info;
1425 int sym_index;
1426 struct elf_writer_rel *rel_sec;
1427
1428 sym_index = elf_sym_index(ew, sym);
1429
1430 if (sym_index < 0) {
1431 ERROR("Unable to locate symbol: %s\n", sym);
1432 return -1;
1433 }
1434
1435 sym_info = sym_index;
1436
1437 /* The relocation type will get fixed prior to serialization. */
1438 rel.r_offset = addr;
1439 rel.r_info = ELF64_R_INFO(sym_info, 0);
1440
1441 rel_sec = rel_section(ew, &rel);
1442
1443 if (rel_sec == NULL)
1444 return -1;
1445
1446 return add_rel(rel_sec, &rel);
1447}
Aaron Durbinfacf1492017-12-18 14:50:22 -07001448
1449int elf_program_file_size(const struct buffer *input, size_t *file_size)
1450{
1451 Elf64_Ehdr ehdr;
1452 Elf64_Phdr *phdr;
1453 int i;
1454 size_t loadable_file_size = 0;
1455
1456 if (elf_headers(input, &ehdr, &phdr, NULL))
1457 return -1;
1458
1459 for (i = 0; i < ehdr.e_phnum; i++) {
1460 if (phdr[i].p_type != PT_LOAD)
1461 continue;
1462 loadable_file_size += phdr[i].p_filesz;
1463 }
1464
1465 *file_size = loadable_file_size;
1466
1467 free(phdr);
1468
1469 return 0;
1470}