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