AUTHORS, util/: Drop individual copyright notices
[coreboot.git] / util / cbfstool / elfheaders.c
blob216e2778eebb4d63f8aef17de71a52a44f35a9a0
1 /* elf header parsing */
2 /*
3 * 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.
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.
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include "elfparsing.h"
18 #include "common.h"
19 #include "cbfs.h"
22 * Short form: this is complicated, but we've tried making it simple
23 * and we keep hitting problems with our ELF parsing.
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.
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.
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.
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
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:
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.
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.
100 * We also must accommodate different ELF files, and hence formats,
101 * 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!
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.
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.
118 static int iself(const void *input)
120 const Elf32_Ehdr *ehdr = input;
121 return !memcmp(ehdr->e_ident, ELFMAG, 4);
124 /* Get the ident array, so we can figure out
125 * endian-ness, word size, and in future other useful
126 * parameters
128 static void
129 elf_eident(struct buffer *input, Elf64_Ehdr *ehdr)
131 bgets(input, ehdr->e_ident, sizeof(ehdr->e_ident));
135 static int
136 check_size(const struct buffer *b, size_t offset, size_t size, const char *desc)
138 if (size == 0)
139 return 0;
141 if (offset >= buffer_size(b) || (offset + size) > buffer_size(b)) {
142 ERROR("The file is not large enough for the '%s'. "
143 "%zu bytes @ offset %zu, input %zu bytes.\n",
144 desc, size, offset, buffer_size(b));
145 return -1;
147 return 0;
150 static void
151 elf_ehdr(struct buffer *input, Elf64_Ehdr *ehdr, struct xdr *xdr, int bit64)
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);
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);
174 static void
175 elf_phdr(struct buffer *pinput, Elf64_Phdr *phdr,
176 int entsize, struct xdr *xdr, int bit64)
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.
185 struct buffer input;
186 buffer_clone(&input, pinput);
187 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);
206 buffer_seek(pinput, entsize);
209 static void
210 elf_shdr(struct buffer *pinput, Elf64_Shdr *shdr,
211 int entsize, struct xdr *xdr, int bit64)
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.
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);
244 buffer_seek(pinput, entsize);
247 static int
248 phdr_read(const struct buffer *in, struct parsed_elf *pelf,
249 struct xdr *xdr, int bit64)
251 struct buffer b;
252 Elf64_Phdr *phdr;
253 Elf64_Ehdr *ehdr;
254 int i;
256 ehdr = &pelf->ehdr;
257 /* 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.
262 buffer_splice(&b, in, ehdr->e_phoff,
263 (uint32_t)ehdr->e_phentsize * ehdr->e_phnum);
264 if (check_size(in, ehdr->e_phoff, buffer_size(&b), "program headers"))
265 return -1;
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.
271 phdr = calloc(ehdr->e_phnum, sizeof(*phdr));
272 for (i = 0; i < ehdr->e_phnum; i++) {
273 DEBUG("Parsing segment %d\n", i);
274 elf_phdr(&b, &phdr[i], ehdr->e_phentsize, xdr, bit64);
276 /* Ensure the contents are valid within the elf file. */
277 if (check_size(in, phdr[i].p_offset, phdr[i].p_filesz,
278 "segment contents")) {
279 free(phdr);
280 return -1;
284 pelf->phdr = phdr;
286 return 0;
289 static int
290 shdr_read(const struct buffer *in, struct parsed_elf *pelf,
291 struct xdr *xdr, int bit64)
293 struct buffer b;
294 Elf64_Shdr *shdr;
295 Elf64_Ehdr *ehdr;
296 int i;
298 ehdr = &pelf->ehdr;
300 /* 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.
305 buffer_splice(&b, in, ehdr->e_shoff,
306 (uint32_t)ehdr->e_shentsize * ehdr->e_shnum);
307 if (check_size(in, ehdr->e_shoff, buffer_size(&b), "section headers"))
308 return -1;
310 /* gather up all the shdrs. */
311 shdr = calloc(ehdr->e_shnum, sizeof(*shdr));
312 for (i = 0; i < ehdr->e_shnum; i++) {
313 DEBUG("Parsing section %d\n", i);
314 elf_shdr(&b, &shdr[i], ehdr->e_shentsize, xdr, bit64);
317 pelf->shdr = shdr;
319 return 0;
322 static int
323 reloc_read(const struct buffer *in, struct parsed_elf *pelf,
324 struct xdr *xdr, int bit64)
326 struct buffer b;
327 Elf64_Word i;
328 Elf64_Ehdr *ehdr;
330 ehdr = &pelf->ehdr;
331 pelf->relocs = calloc(ehdr->e_shnum, sizeof(Elf64_Rela *));
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;
341 shdr = &pelf->shdr[i];
343 /* Only process REL and RELA sections. */
344 if (shdr->sh_type != SHT_REL && shdr->sh_type != SHT_RELA)
345 continue;
347 DEBUG("Checking relocation section %u\n", i);
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;
357 is_rela = shdr->sh_type == SHT_RELA;
359 /* Determine the number relocations in this section. */
360 nrelocs = shdr->sh_size / shdr->sh_entsize;
362 pelf->relocs[i] = calloc(nrelocs, sizeof(Elf64_Rela));
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;
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;
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);
388 rela++;
392 return 0;
395 static int strtab_read(const struct buffer *in, struct parsed_elf *pelf)
397 Elf64_Ehdr *ehdr;
398 Elf64_Word i;
400 ehdr = &pelf->ehdr;
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;
408 /* For each section of type SHT_STRTAB create a symtab buffer. */
409 pelf->strtabs = calloc(ehdr->e_shnum, sizeof(struct buffer *));
411 for (i = 0; i < ehdr->e_shnum; i++) {
412 struct buffer *b;
413 Elf64_Shdr *shdr = &pelf->shdr[i];
415 if (shdr->sh_type != SHT_STRTAB)
416 continue;
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);
422 free(b);
423 return -1;
425 pelf->strtabs[i] = b;
428 return 0;
431 static int
432 symtab_read(const struct buffer *in, struct parsed_elf *pelf,
433 struct xdr *xdr, int bit64)
435 Elf64_Ehdr *ehdr;
436 Elf64_Shdr *shdr;
437 Elf64_Half shnum;
438 Elf64_Xword i;
439 Elf64_Xword nsyms;
440 Elf64_Sym *sym;
441 struct buffer b;
443 ehdr = &pelf->ehdr;
445 shdr = NULL;
446 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
447 if (pelf->shdr[shnum].sh_type != SHT_SYMTAB)
448 continue;
450 if (shdr != NULL) {
451 ERROR("Multiple symbol sections found. %u and %u\n",
452 (unsigned int)(shdr - pelf->shdr), shnum);
453 return -1;
456 shdr = &pelf->shdr[shnum];
459 if (shdr == NULL) {
460 ERROR("No symbol table found.\n");
461 return -1;
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;
468 nsyms = shdr->sh_size / shdr->sh_entsize;
470 pelf->syms = calloc(nsyms, sizeof(Elf64_Sym));
472 for (i = 0; i < nsyms; i++) {
473 sym = &pelf->syms[i];
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);
492 return 0;
495 int parse_elf(const struct buffer *pinput, struct parsed_elf *pelf, int flags)
497 struct xdr *xdr = &xdr_le;
498 int bit64 = 0;
499 struct buffer input;
500 Elf64_Ehdr *ehdr;
502 /* Zero out the parsed elf structure. */
503 memset(pelf, 0, sizeof(*pelf));
505 if (!iself(buffer_get(pinput))) {
506 DEBUG("The stage file is not in ELF format!\n");
507 return -1;
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.
519 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
520 xdr = &xdr_be;
522 elf_ehdr(&input, ehdr, xdr, bit64);
524 /* Relocation processing requires section header parsing. */
525 if (flags & ELF_PARSE_RELOC)
526 flags |= ELF_PARSE_SHDR;
528 /* String table processing requires section header parsing. */
529 if (flags & ELF_PARSE_STRTAB)
530 flags |= ELF_PARSE_SHDR;
532 /* Symbole table processing requires section header parsing. */
533 if (flags & ELF_PARSE_SYMTAB)
534 flags |= ELF_PARSE_SHDR;
536 if ((flags & ELF_PARSE_PHDR) && phdr_read(pinput, pelf, xdr, bit64))
537 goto fail;
539 if ((flags & ELF_PARSE_SHDR) && shdr_read(pinput, pelf, xdr, bit64))
540 goto fail;
542 if ((flags & ELF_PARSE_RELOC) && reloc_read(pinput, pelf, xdr, bit64))
543 goto fail;
545 if ((flags & ELF_PARSE_STRTAB) && strtab_read(pinput, pelf))
546 goto fail;
548 if ((flags & ELF_PARSE_SYMTAB) && symtab_read(pinput, pelf, xdr, bit64))
549 goto fail;
551 return 0;
553 fail:
554 parsed_elf_destroy(pelf);
555 return -1;
558 void parsed_elf_destroy(struct parsed_elf *pelf)
560 Elf64_Half i;
562 free(pelf->phdr);
563 free(pelf->shdr);
564 if (pelf->relocs != NULL) {
565 for (i = 0; i < pelf->ehdr.e_shnum; i++)
566 free(pelf->relocs[i]);
568 free(pelf->relocs);
570 if (pelf->strtabs != NULL) {
571 for (i = 0; i < pelf->ehdr.e_shnum; i++)
572 free(pelf->strtabs[i]);
574 free(pelf->strtabs);
575 free(pelf->syms);
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.
586 elf_headers(const struct buffer *pinput,
587 Elf64_Ehdr *ehdr,
588 Elf64_Phdr **pphdr,
589 Elf64_Shdr **pshdr)
591 struct parsed_elf pelf;
592 int flags;
594 flags = ELF_PARSE_PHDR;
596 if (pshdr != NULL)
597 flags |= ELF_PARSE_SHDR;
599 if (parse_elf(pinput, &pelf, flags))
600 return -1;
602 /* Copy out the parsed elf header. */
603 memcpy(ehdr, &pelf.ehdr, sizeof(*ehdr));
605 *pphdr = calloc(ehdr->e_phnum, sizeof(Elf64_Phdr));
606 memcpy(*pphdr, pelf.phdr, ehdr->e_phnum * sizeof(Elf64_Phdr));
608 if (pshdr != NULL) {
609 *pshdr = calloc(ehdr->e_shnum, sizeof(Elf64_Shdr));
610 memcpy(*pshdr, pelf.shdr, ehdr->e_shnum * sizeof(Elf64_Shdr));
613 parsed_elf_destroy(&pelf);
615 return 0;
618 /* ELF Writing Support
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 * +------------------+
634 void elf_init_eheader(Elf64_Ehdr *ehdr, int machine, int nbits, int endian)
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);
658 /* Arbitrary maximum number of sections. */
659 #define MAX_SECTIONS 16
660 struct elf_writer_section {
661 Elf64_Shdr shdr;
662 struct buffer content;
663 const char *name;
666 struct elf_writer_string_table {
667 size_t next_offset;
668 size_t max_size;
669 char *buffer;
672 struct elf_writer_sym_table {
673 size_t max_entries;
674 size_t num_entries;
675 Elf64_Sym *syms;
678 #define MAX_REL_NAME 32
679 struct 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];
687 struct elf_writer
689 Elf64_Ehdr ehdr;
690 struct xdr *xdr;
691 size_t num_secs;
692 struct elf_writer_section sections[MAX_SECTIONS];
693 struct elf_writer_rel rel_sections[MAX_SECTIONS];
694 Elf64_Phdr *phdrs;
695 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;
700 int bit64;
703 static size_t section_index(struct elf_writer *ew,
704 struct elf_writer_section *sec)
706 return sec - &ew->sections[0];
709 static struct elf_writer_section *last_section(struct elf_writer *ew)
711 return &ew->sections[ew->num_secs - 1];
714 static void strtab_init(struct elf_writer *ew, size_t size)
716 struct buffer b;
717 Elf64_Shdr shdr;
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);
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);
733 static void symtab_init(struct elf_writer *ew, size_t max_entries)
735 struct buffer b;
736 Elf64_Shdr shdr;
738 memset(&shdr, 0, sizeof(shdr));
739 shdr.sh_type = SHT_SYMTAB;
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);
749 shdr.sh_size = shdr.sh_entsize * max_entries;
751 ew->symtab.syms = calloc(max_entries, sizeof(Elf64_Sym));
752 ew->symtab.num_entries = 1;
753 ew->symtab.max_entries = max_entries;
755 buffer_init(&b, NULL, ew->symtab.syms, shdr.sh_size);
757 elf_writer_add_section(ew, &shdr, &b, ".symtab");
758 ew->symtab_sec = last_section(ew);
761 struct elf_writer *elf_writer_init(const Elf64_Ehdr *ehdr)
763 struct elf_writer *ew;
764 Elf64_Shdr shdr;
765 struct buffer empty_buffer;
767 if (!iself(ehdr))
768 return NULL;
770 ew = calloc(1, sizeof(*ew));
772 memcpy(&ew->ehdr, ehdr, sizeof(ew->ehdr));
774 ew->bit64 = ew->ehdr.e_ident[EI_CLASS] == ELFCLASS64;
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;
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;
788 memset(&empty_buffer, 0, sizeof(empty_buffer));
789 memset(&shdr, 0, sizeof(shdr));
791 /* Add SHT_NULL section header. */
792 shdr.sh_type = SHT_NULL;
793 elf_writer_add_section(ew, &shdr, &empty_buffer, NULL);
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");
798 ew->shstrtab_sec = last_section(ew);
799 ew->ehdr.e_shstrndx = section_index(ew, ew->shstrtab_sec);
801 /* Add a small string table and symbol table. */
802 strtab_init(ew, 4096);
803 symtab_init(ew, 100);
805 return ew;
809 * Clean up any internal state represented by ew. Aftewards the elf_writer
810 * is invalid.
811 * It is safe to call elf_writer_destroy with ew as NULL. It returns without
812 * performing any action.
814 void elf_writer_destroy(struct elf_writer *ew)
816 int i;
817 if (ew == NULL)
818 return;
819 if (ew->phdrs != NULL)
820 free(ew->phdrs);
821 free(ew->strtab.buffer);
822 free(ew->symtab.syms);
823 for (i = 0; i < MAX_SECTIONS; i++)
824 free(ew->rel_sections[i].rels);
825 free(ew);
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.
834 int elf_writer_add_section(struct elf_writer *ew, const Elf64_Shdr *shdr,
835 struct buffer *contents, const char *name)
837 struct elf_writer_section *newsh;
839 if (ew->num_secs == MAX_SECTIONS)
840 return -1;
842 newsh = &ew->sections[ew->num_secs];
843 ew->num_secs++;
845 memcpy(&newsh->shdr, shdr, sizeof(newsh->shdr));
846 newsh->shdr.sh_offset = 0;
848 newsh->name = name;
849 if (contents != NULL)
850 buffer_clone(&newsh->content, contents);
852 return 0;
855 static void ehdr_write(struct elf_writer *ew, struct buffer *m)
857 int i;
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);
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);
882 static void shdr_write(struct elf_writer *ew, size_t n, struct buffer *m)
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;
889 xdr->put32(m, shdr->sh_name);
890 xdr->put32(m, shdr->sh_type);
891 if (bit64) {
892 xdr->put64(m, shdr->sh_flags);
893 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 {
901 xdr->put32(m, shdr->sh_flags);
902 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);
912 static void
913 phdr_write(struct elf_writer *ew, struct buffer *m, Elf64_Phdr *phdr)
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);
937 static int section_consecutive(struct elf_writer *ew, Elf64_Half secidx)
939 Elf64_Half i;
940 struct elf_writer_section *prev_alloc = NULL;
942 if (secidx == 0)
943 return 0;
945 for (i = 0; i < secidx; i++) {
946 if (ew->sections[i].shdr.sh_flags & SHF_ALLOC)
947 prev_alloc = &ew->sections[i];
950 if (prev_alloc == NULL)
951 return 0;
953 if (prev_alloc->shdr.sh_addr + prev_alloc->shdr.sh_size ==
954 ew->sections[secidx].shdr.sh_addr)
955 return 1;
957 return 0;
960 static void write_phdrs(struct elf_writer *ew, struct buffer *phdrs)
962 Elf64_Half i;
963 Elf64_Phdr phdr;
964 size_t num_written = 0;
965 size_t num_needs_write = 0;
967 for (i = 0; i < ew->num_secs; i++) {
968 struct elf_writer_section *sec = &ew->sections[i];
970 if (!(sec->shdr.sh_flags & SHF_ALLOC))
971 continue;
973 if (!section_consecutive(ew, i)) {
974 /* Write out previously set phdr. */
975 if (num_needs_write != num_written) {
976 phdr_write(ew, phdrs, &phdr);
977 num_written++;
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;
991 num_needs_write++;
993 } 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;
1007 /* Write out the last phdr. */
1008 if (num_needs_write != num_written) {
1009 phdr_write(ew, phdrs, &phdr);
1010 num_written++;
1012 assert(num_written == ew->ehdr.e_phnum);
1015 static void fixup_symbol_table(struct elf_writer *ew)
1017 struct elf_writer_section *sec = ew->symtab_sec;
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;
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);
1051 /* Update section size. */
1052 sec->shdr.sh_size = sec->shdr.sh_entsize;
1053 sec->shdr.sh_size *= ew->symtab.num_entries;
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;
1062 buffer_set_size(&sec->content, sec->shdr.sh_size);
1065 static void fixup_relocations(struct elf_writer *ew)
1067 int i;
1068 Elf64_Xword type;
1070 switch (ew->ehdr.e_machine) {
1071 case EM_386:
1072 type = R_386_32;
1073 break;
1074 case EM_X86_64:
1075 type = R_AMD64_64;
1076 break;
1077 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;
1089 case EM_PPC64:
1090 type = R_PPC64_ADDR32;
1091 break;
1092 default:
1093 ERROR("Unable to handle relocations for e_machine %x\n",
1094 ew->ehdr.e_machine);
1095 return;
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;
1104 if (sec == NULL)
1105 continue;
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);
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));
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);
1138 * Serialize the ELF file to the output buffer. Return < 0 on error,
1139 * 0 on success.
1141 int elf_writer_serialize(struct elf_writer *ew, struct buffer *out)
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;
1153 INFO("Writing %zu sections.\n", ew->num_secs);
1155 /* Perform any necessary work for special sections. */
1156 fixup_symbol_table(ew);
1157 fixup_relocations(ew);
1159 /* 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];
1166 if (sec->shdr.sh_flags & SHF_ALLOC) {
1167 if (!section_consecutive(ew, i))
1168 ew->ehdr.e_phnum++;
1171 program_size += buffer_size(&sec->content);
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;
1179 ew->ehdr.e_shnum = ew->num_secs;
1180 metadata_size = 0;
1181 metadata_size += ew->ehdr.e_ehsize;
1182 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;
1184 shstroffset = metadata_size;
1185 /* Align up section header string size and metadata size to 4KiB */
1186 metadata_size = ALIGN(metadata_size + shstrlen, 4096);
1188 if (buffer_create(out, metadata_size + program_size, "elfout")) {
1189 ERROR("Could not create output buffer for ELF.\n");
1190 return -1;
1193 INFO("Created %zu output buffer for ELF file.\n", buffer_size(out));
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.
1200 ew->ehdr.e_shoff = ew->ehdr.e_ehsize;
1201 ew->ehdr.e_phoff = ew->ehdr.e_shoff +
1202 (Elf64_Off)ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1204 buffer_splice(&metadata, out, 0, metadata_size);
1205 buffer_splice(&phdrs, out, ew->ehdr.e_phoff,
1206 (uint32_t)ew->ehdr.e_phnum * ew->ehdr.e_phentsize);
1207 buffer_splice(&data, out, metadata_size, program_size);
1208 /* Set up the section header string table contents. */
1209 strtab = &ew->shstrtab_sec->content;
1210 buffer_splice(strtab, out, shstroffset, shstrlen);
1211 ew->shstrtab_sec->shdr.sh_size = shstrlen;
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);
1219 /* ELF Header */
1220 ehdr_write(ew, &metadata);
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++) {
1226 struct elf_writer_section *sec = &ew->sections[i];
1228 /* Update section offsets. Be sure to not update SHN_UNDEF. */
1229 if (sec == ew->shstrtab_sec)
1230 sec->shdr.sh_offset = shstroffset;
1231 else if (i != SHN_UNDEF)
1232 sec->shdr.sh_offset = buffer_size(&data) +
1233 metadata_size;
1235 shdr_write(ew, i, &metadata);
1237 /* Add section name to string table. */
1238 if (sec->name != NULL)
1239 bputs(strtab, sec->name, strlen(sec->name) + 1);
1241 /* 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));
1248 write_phdrs(ew, &phdrs);
1250 return 0;
1253 /* Add a string to the string table returning index on success, < 0 on error. */
1254 static int elf_writer_add_string(struct elf_writer *ew, const char *new)
1256 size_t current_offset;
1257 size_t new_len;
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;
1263 if (!strcmp(str, new))
1264 return current_offset;
1265 current_offset += len;
1268 new_len = strlen(new) + 1;
1270 if (current_offset + new_len > ew->strtab.max_size) {
1271 ERROR("No space for string in .strtab.\n");
1272 return -1;
1275 memcpy(ew->strtab.buffer + current_offset, new, new_len);
1276 ew->strtab.next_offset = current_offset + new_len;
1278 return current_offset;
1281 static int elf_writer_section_index(struct elf_writer *ew, const char *name)
1283 size_t i;
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;
1292 ERROR("ELF Section not found: %s\n", name);
1294 return -1;
1297 int 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)
1302 int i;
1303 Elf64_Sym sym = {
1304 .st_value = value,
1305 .st_size = size,
1306 .st_info = ELF64_ST_INFO(binding, type),
1309 if (ew->symtab.max_entries == ew->symtab.num_entries) {
1310 ERROR("No more symbol entries left.\n");
1311 return -1;
1314 i = elf_writer_add_string(ew, name);
1315 if (i < 0)
1316 return -1;
1317 sym.st_name = i;
1319 i = elf_writer_section_index(ew, section_name);
1320 if (i < 0)
1321 return -1;
1322 sym.st_shndx = i;
1324 ew->symtab.syms[ew->symtab.num_entries++] = sym;
1326 return 0;
1329 static int elf_sym_index(struct elf_writer *ew, const char *sym)
1331 int j;
1332 size_t i;
1333 Elf64_Word st_name;
1335 /* Determine index of symbol in the string table. */
1336 j = elf_writer_add_string(ew, sym);
1337 if (j < 0)
1338 return -1;
1340 st_name = j;
1342 for (i = 0; i < ew->symtab.num_entries; i++)
1343 if (ew->symtab.syms[i].st_name == st_name)
1344 return i;
1346 return -1;
1349 static struct elf_writer_rel *rel_section(struct elf_writer *ew,
1350 const Elf64_Rel *r)
1352 Elf64_Sym *sym;
1353 struct elf_writer_rel *rel;
1354 Elf64_Shdr shdr;
1355 struct buffer b;
1357 sym = &ew->symtab.syms[ELF64_R_SYM(r->r_info)];
1359 /* Determine if section has been initialized yet. */
1360 rel = &ew->rel_sections[sym->st_shndx];
1361 if (rel->sec != NULL)
1362 return rel;
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;
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);
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;
1383 strcat(rel->name, ".rel");
1384 strcat(rel->name, ew->sections[sym->st_shndx].name);
1385 buffer_init(&b, rel->name, NULL, 0);
1387 elf_writer_add_section(ew, &shdr, &b, rel->name);
1388 rel->sec = last_section(ew);
1390 return rel;
1393 static int add_rel(struct elf_writer_rel *rel_sec, const Elf64_Rel *rel)
1395 if (rel_sec->num_entries == rel_sec->max_entries) {
1396 size_t num = rel_sec->max_entries * 2;
1397 Elf64_Rel *old_rels;
1399 if (num == 0)
1400 num = 128;
1402 old_rels = rel_sec->rels;
1403 rel_sec->rels = calloc(num, sizeof(Elf64_Rel));
1405 memcpy(rel_sec->rels, old_rels,
1406 rel_sec->num_entries * sizeof(Elf64_Rel));
1407 free(old_rels);
1409 rel_sec->max_entries = num;
1412 rel_sec->rels[rel_sec->num_entries] = *rel;
1413 rel_sec->num_entries++;
1415 return 0;
1418 int elf_writer_add_rel(struct elf_writer *ew, const char *sym, Elf64_Addr addr)
1420 Elf64_Rel rel;
1421 Elf64_Xword sym_info;
1422 int sym_index;
1423 struct elf_writer_rel *rel_sec;
1425 sym_index = elf_sym_index(ew, sym);
1427 if (sym_index < 0) {
1428 ERROR("Unable to locate symbol: %s\n", sym);
1429 return -1;
1432 sym_info = sym_index;
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);
1438 rel_sec = rel_section(ew, &rel);
1440 if (rel_sec == NULL)
1441 return -1;
1443 return add_rel(rel_sec, &rel);
1446 int elf_program_file_size(const struct buffer *input, size_t *file_size)
1448 Elf64_Ehdr ehdr;
1449 Elf64_Phdr *phdr;
1450 int i;
1451 size_t loadable_file_size = 0;
1453 if (elf_headers(input, &ehdr, &phdr, NULL))
1454 return -1;
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;
1462 *file_size = loadable_file_size;
1464 free(phdr);
1466 return 0;