util/superiotool/smsc.c: Add some register dumps
[coreboot.git] / util / cbfstool / elfheaders.c
blob9d02c3057380b926e766e0c2a47149b763b97061
1 /*
2 * elf header parsing.
4 * Copyright (C) 2013 Google, Inc.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; version 2 of the License.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
20 #include "elfparsing.h"
21 #include "common.h"
22 #include "cbfs.h"
25 * Short form: this is complicated, but we've tried making it simple
26 * and we keep hitting problems with our ELF parsing.
28 * The ELF parsing situation has always been a bit tricky. In fact,
29 * we (and most others) have been getting it wrong in small ways for
30 * years. Recently this has caused real trouble for the ARM V8 build.
31 * In this file we attempt to finally get it right for all variations
32 * of endian-ness and word size and target architectures and
33 * architectures we might get run on. Phew!. To do this we borrow a
34 * page from the FreeBSD NFS xdr model (see elf_ehdr and elf_phdr),
35 * the Plan 9 endianness functions (see xdr.c), and Go interfaces (see
36 * how we use buffer structs in this file). This ends up being a bit
37 * wordy at the lowest level, but greatly simplifies the elf parsing
38 * code and removes a common source of bugs, namely, forgetting to
39 * flip type endianness when referencing a struct member.
41 * ELF files can have four combinations of data layout: 32/64, and
42 * big/little endian. Further, to add to the fun, depending on the
43 * word size, the size of the ELF structs varies. The coreboot SELF
44 * format is simpler in theory: it's supposed to be always BE, and the
45 * various struct members allow room for growth: the entry point is
46 * always 64 bits, for example, so the size of a SELF struct is
47 * constant, regardless of target architecture word size. Hence, we
48 * need to do some transformation of the ELF files.
50 * A given architecture, realistically, only supports one of the four
51 * combinations at a time as the 'native' format. Hence, our code has
52 * been sprinkled with every variation of [nh]to[hn][sll] over the
53 * years. We've never quite gotten it all right, however, and a quick
54 * pass over this code revealed another bug. It's all worked because,
55 * until now, all the working platforms that had CBFS were 32 LE. Even then,
56 * however, bugs crept in: we recently realized that we're not
57 * transforming the entry point to big format when we store into the
58 * SELF image.
60 * The problem is essentially an XDR operation:
61 * we have something in a foreign format and need to transform it.
62 * It's most like XDR because:
63 * 1) the byte order can be wrong
64 * 2) the word size can be wrong
65 * 3) the size of elements in the stream depends on the value
66 * of other elements in the stream
67 * it's not like XDR because:
68 * 1) the byte order can be right
69 * 2) the word size can be right
70 * 3) the struct members are all on a natural alignment
72 * Hence, this new approach. To cover word size issues, we *always*
73 * transform the two structs we care about, the file header and
74 * program header, into a native struct in the 64 bit format:
76 * [32,little] -> [Elf64_Ehdr, Elf64_Phdr]
77 * [64,little] -> [Elf64_Ehdr, Elf64_Phdr]
78 * [32,big] -> [Elf64_Ehdr, Elf64_Phdr]
79 * [64,big] -> [Elf64_Ehdr, Elf64_Phdr]
80 * Then we just use those structs, and all the need for inline ntoh* goes away,
81 * as well as all the chances for error.
82 * This works because all the SELF structs have fields large enough for
83 * the largest ELF 64 struct members, and all the Elf64 struct members
84 * are at least large enough for all ELF 32 struct members.
85 * We end up with one function to do all our ELF parsing, and two functions
86 * to transform the headers. For the put case, we also have
87 * XDR functions, and hopefully we'll never again spend 5 years with the
88 * wrong endian-ness on an output value :-)
89 * This should work for all word sizes and endianness we hope to target.
90 * I *really* don't want to be here for 128 bit addresses.
92 * The parse functions are called with a pointer to an input buffer
93 * struct. One might ask: are there enough bytes in the input buffer?
94 * We know there need to be at *least* sizeof(Elf32_Ehdr) +
95 * sizeof(Elf32_Phdr) bytes. Realistically, there has to be some data
96 * too. If we start to worry, though we have not in the past, we
97 * might apply the simple test: the input buffer needs to be at least
98 * sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr) bytes because, even if it's
99 * ELF 32, there's got to be *some* data! This is not theoretically
100 * accurate but it is actually good enough in practice. It allows the
101 * header transformation code to ignore the possibility of underrun.
103 * We also must accommodate different ELF files, and hence formats,
104 * in the same cbfs invocation. We might load a 64-bit payload
105 * on a 32-bit machine; we might even have a mixed armv7/armv8
106 * SOC or even a system with an x86/ARM!
108 * A possibly problematic (though unlikely to be so) assumption
109 * is that we expect the BIOS to remain in the lowest 32 bits
110 * of the physical address space. Since ARMV8 has standardized
111 * on that, and x86_64 also has, this seems a safe assumption.
113 * To repeat, ELF structs are different sizes because ELF struct
114 * members are different sizes, depending on values in the ELF file
115 * header. For this we use the functions defined in xdr.c, which
116 * consume bytes, convert the endianness, and advance the data pointer
117 * in the buffer struct.
121 static int iself(const void *input)
123 const Elf32_Ehdr *ehdr = input;
124 return !memcmp(ehdr->e_ident, ELFMAG, 4);
127 /* Get the ident array, so we can figure out
128 * endian-ness, word size, and in future other useful
129 * parameters
131 static void
132 elf_eident(struct buffer *input, Elf64_Ehdr *ehdr)
134 bgets(input, ehdr->e_ident, sizeof(ehdr->e_ident));
138 static int
139 check_size(const struct buffer *b, size_t offset, size_t size, const char *desc)
141 if (size == 0)
142 return 0;
144 if (offset >= buffer_size(b) || (offset + size) > buffer_size(b)) {
145 ERROR("The file is not large enough for the '%s'. "
146 "%zu bytes @ offset %zu, input %zu bytes.\n",
147 desc, size, offset, buffer_size(b));
148 return -1;
150 return 0;
153 static void
154 elf_ehdr(struct buffer *input, Elf64_Ehdr *ehdr, struct xdr *xdr, int bit64)
156 ehdr->e_type = xdr->get16(input);
157 ehdr->e_machine = xdr->get16(input);
158 ehdr->e_version = xdr->get32(input);
159 if (bit64){
160 ehdr->e_entry = xdr->get64(input);
161 ehdr->e_phoff = xdr->get64(input);
162 ehdr->e_shoff = xdr->get64(input);
163 } else {
164 ehdr->e_entry = xdr->get32(input);
165 ehdr->e_phoff = xdr->get32(input);
166 ehdr->e_shoff = xdr->get32(input);
168 ehdr->e_flags = xdr->get32(input);
169 ehdr->e_ehsize = xdr->get16(input);
170 ehdr->e_phentsize = xdr->get16(input);
171 ehdr->e_phnum = xdr->get16(input);
172 ehdr->e_shentsize = xdr->get16(input);
173 ehdr->e_shnum = xdr->get16(input);
174 ehdr->e_shstrndx = xdr->get16(input);
177 static void
178 elf_phdr(struct buffer *pinput, Elf64_Phdr *phdr,
179 int entsize, struct xdr *xdr, int bit64)
182 * The entsize need not be sizeof(*phdr).
183 * Hence, it is easier to keep a copy of the input,
184 * as the xdr functions may not advance the input
185 * pointer the full entsize; rather than get tricky
186 * we just advance it below.
188 struct buffer input;
189 buffer_clone(&input, pinput);
190 if (bit64){
191 phdr->p_type = xdr->get32(&input);
192 phdr->p_flags = xdr->get32(&input);
193 phdr->p_offset = xdr->get64(&input);
194 phdr->p_vaddr = xdr->get64(&input);
195 phdr->p_paddr = xdr->get64(&input);
196 phdr->p_filesz = xdr->get64(&input);
197 phdr->p_memsz = xdr->get64(&input);
198 phdr->p_align = xdr->get64(&input);
199 } else {
200 phdr->p_type = xdr->get32(&input);
201 phdr->p_offset = xdr->get32(&input);
202 phdr->p_vaddr = xdr->get32(&input);
203 phdr->p_paddr = xdr->get32(&input);
204 phdr->p_filesz = xdr->get32(&input);
205 phdr->p_memsz = xdr->get32(&input);
206 phdr->p_flags = xdr->get32(&input);
207 phdr->p_align = xdr->get32(&input);
209 buffer_seek(pinput, entsize);
212 static void
213 elf_shdr(struct buffer *pinput, Elf64_Shdr *shdr,
214 int entsize, struct xdr *xdr, int bit64)
217 * The entsize need not be sizeof(*shdr).
218 * Hence, it is easier to keep a copy of the input,
219 * as the xdr functions may not advance the input
220 * pointer the full entsize; rather than get tricky
221 * we just advance it below.
223 struct buffer input = *pinput;
224 if (bit64){
225 shdr->sh_name = xdr->get32(&input);
226 shdr->sh_type = xdr->get32(&input);
227 shdr->sh_flags = xdr->get64(&input);
228 shdr->sh_addr = xdr->get64(&input);
229 shdr->sh_offset = xdr->get64(&input);
230 shdr->sh_size= xdr->get64(&input);
231 shdr->sh_link = xdr->get32(&input);
232 shdr->sh_info = xdr->get32(&input);
233 shdr->sh_addralign = xdr->get64(&input);
234 shdr->sh_entsize = xdr->get64(&input);
235 } else {
236 shdr->sh_name = xdr->get32(&input);
237 shdr->sh_type = xdr->get32(&input);
238 shdr->sh_flags = xdr->get32(&input);
239 shdr->sh_addr = xdr->get32(&input);
240 shdr->sh_offset = xdr->get32(&input);
241 shdr->sh_size = xdr->get32(&input);
242 shdr->sh_link = xdr->get32(&input);
243 shdr->sh_info = xdr->get32(&input);
244 shdr->sh_addralign = xdr->get32(&input);
245 shdr->sh_entsize = xdr->get32(&input);
247 buffer_seek(pinput, entsize);
250 static int
251 phdr_read(const struct buffer *in, struct parsed_elf *pelf,
252 struct xdr *xdr, int bit64)
254 struct buffer b;
255 Elf64_Phdr *phdr;
256 Elf64_Ehdr *ehdr;
257 int i;
259 ehdr = &pelf->ehdr;
260 /* cons up an input buffer for the headers.
261 * Note that the program headers can be anywhere,
262 * per the ELF spec, You'd be surprised how many ELF
263 * readers miss this little detail.
265 buffer_splice(&b, in, ehdr->e_phoff, ehdr->e_phentsize * ehdr->e_phnum);
266 if (check_size(in, ehdr->e_phoff, buffer_size(&b), "program headers"))
267 return -1;
269 /* gather up all the phdrs.
270 * We do them all at once because there is more
271 * than one loop over all the phdrs.
273 phdr = calloc(ehdr->e_phnum, sizeof(*phdr));
274 for (i = 0; i < ehdr->e_phnum; i++) {
275 DEBUG("Parsing segment %d\n", i);
276 elf_phdr(&b, &phdr[i], ehdr->e_phentsize, xdr, bit64);
278 /* Ensure the contents are valid within the elf file. */
279 if (check_size(in, phdr[i].p_offset, phdr[i].p_filesz,
280 "segment contents")) {
281 free(phdr);
282 return -1;
286 pelf->phdr = phdr;
288 return 0;
291 static int
292 shdr_read(const struct buffer *in, struct parsed_elf *pelf,
293 struct xdr *xdr, int bit64)
295 struct buffer b;
296 Elf64_Shdr *shdr;
297 Elf64_Ehdr *ehdr;
298 int i;
300 ehdr = &pelf->ehdr;
302 /* cons up an input buffer for the section headers.
303 * Note that the section headers can be anywhere,
304 * per the ELF spec, You'd be surprised how many ELF
305 * readers miss this little detail.
307 buffer_splice(&b, in, ehdr->e_shoff, ehdr->e_shentsize * ehdr->e_shnum);
308 if (check_size(in, ehdr->e_shoff, buffer_size(&b), "section headers"))
309 return -1;
311 /* gather up all the shdrs. */
312 shdr = calloc(ehdr->e_shnum, sizeof(*shdr));
313 for (i = 0; i < ehdr->e_shnum; i++) {
314 DEBUG("Parsing section %d\n", i);
315 elf_shdr(&b, &shdr[i], ehdr->e_shentsize, xdr, bit64);
318 pelf->shdr = shdr;
320 return 0;
323 static int
324 reloc_read(const struct buffer *in, struct parsed_elf *pelf,
325 struct xdr *xdr, int bit64)
327 struct buffer b;
328 Elf64_Word i;
329 Elf64_Ehdr *ehdr;
331 ehdr = &pelf->ehdr;
332 pelf->relocs = calloc(ehdr->e_shnum, sizeof(Elf64_Rela *));
334 /* Allocate array for each section that contains relocation entries. */
335 for (i = 0; i < ehdr->e_shnum; i++) {
336 Elf64_Shdr *shdr;
337 Elf64_Rela *rela;
338 Elf64_Xword j;
339 Elf64_Xword nrelocs;
340 int is_rela;
342 shdr = &pelf->shdr[i];
344 /* Only process REL and RELA sections. */
345 if (shdr->sh_type != SHT_REL && shdr->sh_type != SHT_RELA)
346 continue;
348 DEBUG("Checking relocation section %u\n", i);
350 /* Ensure the section that relocations apply is a valid. */
351 if (shdr->sh_info >= ehdr->e_shnum ||
352 shdr->sh_info == SHN_UNDEF) {
353 ERROR("Relocations apply to an invalid section: %u\n",
354 shdr[i].sh_info);
355 return -1;
358 is_rela = shdr->sh_type == SHT_RELA;
360 /* Determine the number relocations in this section. */
361 nrelocs = shdr->sh_size / shdr->sh_entsize;
363 pelf->relocs[i] = calloc(nrelocs, sizeof(Elf64_Rela));
365 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
366 if (check_size(in, shdr->sh_offset, buffer_size(&b),
367 "relocation section")) {
368 ERROR("Relocation section %u failed.\n", i);
369 return -1;
372 rela = pelf->relocs[i];
373 for (j = 0; j < nrelocs; j++) {
374 if (bit64) {
375 rela->r_offset = xdr->get64(&b);
376 rela->r_info = xdr->get64(&b);
377 if (is_rela)
378 rela->r_addend = xdr->get64(&b);
379 } else {
380 uint32_t r_info;
382 rela->r_offset = xdr->get32(&b);
383 r_info = xdr->get32(&b);
384 rela->r_info = ELF64_R_INFO(ELF32_R_SYM(r_info),
385 ELF32_R_TYPE(r_info));
386 if (is_rela)
387 rela->r_addend = xdr->get32(&b);
389 rela++;
393 return 0;
396 static int strtab_read(const struct buffer *in, struct parsed_elf *pelf)
398 Elf64_Ehdr *ehdr;
399 Elf64_Word i;
401 ehdr = &pelf->ehdr;
403 if (ehdr->e_shstrndx >= ehdr->e_shnum) {
404 ERROR("Section header string table index out of range: %d\n",
405 ehdr->e_shstrndx);
406 return -1;
409 /* For each section of type SHT_STRTAB create a symtab buffer. */
410 pelf->strtabs = calloc(ehdr->e_shnum, sizeof(struct buffer *));
412 for (i = 0; i < ehdr->e_shnum; i++) {
413 struct buffer *b;
414 Elf64_Shdr *shdr = &pelf->shdr[i];
416 if (shdr->sh_type != SHT_STRTAB)
417 continue;
419 b = calloc(1, sizeof(*b));
420 buffer_splice(b, in, shdr->sh_offset, shdr->sh_size);
421 if (check_size(in, shdr->sh_offset, buffer_size(b), "strtab")) {
422 ERROR("STRTAB section not within bounds: %d\n", i);
423 free(b);
424 return -1;
426 pelf->strtabs[i] = b;
429 return 0;
432 static int
433 symtab_read(const struct buffer *in, struct parsed_elf *pelf,
434 struct xdr *xdr, int bit64)
436 Elf64_Ehdr *ehdr;
437 Elf64_Shdr *shdr;
438 Elf64_Half shnum;
439 Elf64_Xword i;
440 Elf64_Xword nsyms;
441 Elf64_Sym *sym;
442 struct buffer b;
444 ehdr = &pelf->ehdr;
446 shdr = NULL;
447 for (shnum = 0; shnum < ehdr->e_shnum; shnum++) {
448 if (pelf->shdr[shnum].sh_type != SHT_SYMTAB)
449 continue;
451 if (shdr != NULL) {
452 ERROR("Multiple symbol sections found. %u and %u\n",
453 (unsigned int)(shdr - pelf->shdr), shnum);
454 return -1;
457 shdr = &pelf->shdr[shnum];
460 if (shdr == NULL) {
461 ERROR("No symbol table found.\n");
462 return -1;
465 buffer_splice(&b, in, shdr->sh_offset, shdr->sh_size);
466 if (check_size(in, shdr->sh_offset, buffer_size(&b), "symtab"))
467 return -1;
469 nsyms = shdr->sh_size / shdr->sh_entsize;
471 pelf->syms = calloc(nsyms, sizeof(Elf64_Sym));
473 for (i = 0; i < nsyms; i++) {
474 sym = &pelf->syms[i];
476 if (bit64) {
477 sym->st_name = xdr->get32(&b);
478 sym->st_info = xdr->get8(&b);
479 sym->st_other = xdr->get8(&b);
480 sym->st_shndx = xdr->get16(&b);
481 sym->st_value = xdr->get64(&b);
482 sym->st_size = xdr->get64(&b);
483 } else {
484 sym->st_name = xdr->get32(&b);
485 sym->st_value = xdr->get32(&b);
486 sym->st_size = xdr->get32(&b);
487 sym->st_info = xdr->get8(&b);
488 sym->st_other = xdr->get8(&b);
489 sym->st_shndx = xdr->get16(&b);
493 return 0;
496 int parse_elf(const struct buffer *pinput, struct parsed_elf *pelf, int flags)
498 struct xdr *xdr = &xdr_le;
499 int bit64 = 0;
500 struct buffer input;
501 Elf64_Ehdr *ehdr;
503 /* Zero out the parsed elf structure. */
504 memset(pelf, 0, sizeof(*pelf));
506 if (!iself(buffer_get(pinput))) {
507 DEBUG("The stage file is not in ELF format!\n");
508 return -1;
511 buffer_clone(&input, pinput);
512 ehdr = &pelf->ehdr;
513 elf_eident(&input, ehdr);
514 bit64 = ehdr->e_ident[EI_CLASS] == ELFCLASS64;
515 /* Assume LE unless we are sure otherwise.
516 * We're not going to take on the task of
517 * fully validating the ELF file. That way
518 * lies madness.
520 if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
521 xdr = &xdr_be;
523 elf_ehdr(&input, ehdr, xdr, bit64);
525 /* Relocation processing requires section header parsing. */
526 if (flags & ELF_PARSE_RELOC)
527 flags |= ELF_PARSE_SHDR;
529 /* String table processing requires section header parsing. */
530 if (flags & ELF_PARSE_STRTAB)
531 flags |= ELF_PARSE_SHDR;
533 /* Symbole table processing requires section header parsing. */
534 if (flags & ELF_PARSE_SYMTAB)
535 flags |= ELF_PARSE_SHDR;
537 if ((flags & ELF_PARSE_PHDR) && phdr_read(pinput, pelf, xdr, bit64))
538 goto fail;
540 if ((flags & ELF_PARSE_SHDR) && shdr_read(pinput, pelf, xdr, bit64))
541 goto fail;
543 if ((flags & ELF_PARSE_RELOC) && reloc_read(pinput, pelf, xdr, bit64))
544 goto fail;
546 if ((flags & ELF_PARSE_STRTAB) && strtab_read(pinput, pelf))
547 goto fail;
549 if ((flags & ELF_PARSE_SYMTAB) && symtab_read(pinput, pelf, xdr, bit64))
550 goto fail;
552 return 0;
554 fail:
555 parsed_elf_destroy(pelf);
556 return -1;
559 void parsed_elf_destroy(struct parsed_elf *pelf)
561 Elf64_Half i;
563 free(pelf->phdr);
564 free(pelf->shdr);
565 if (pelf->relocs != NULL) {
566 for (i = 0; i < pelf->ehdr.e_shnum; i++)
567 free(pelf->relocs[i]);
569 free(pelf->relocs);
571 if (pelf->strtabs != NULL) {
572 for (i = 0; i < pelf->ehdr.e_shnum; i++)
573 free(pelf->strtabs[i]);
575 free(pelf->strtabs);
576 free(pelf->syms);
579 /* Get the headers from the buffer.
580 * Return -1 in the event of an error.
581 * The section headers are optional; if NULL
582 * is passed in for pshdr they won't be parsed.
583 * We don't (yet) make payload parsing optional
584 * because we've never seen a use case.
587 elf_headers(const struct buffer *pinput,
588 Elf64_Ehdr *ehdr,
589 Elf64_Phdr **pphdr,
590 Elf64_Shdr **pshdr)
592 struct parsed_elf pelf;
593 int flags;
595 flags = ELF_PARSE_PHDR;
597 if (pshdr != NULL)
598 flags |= ELF_PARSE_SHDR;
600 if (parse_elf(pinput, &pelf, flags))
601 return -1;
603 /* Copy out the parsed elf header. */
604 memcpy(ehdr, &pelf.ehdr, sizeof(*ehdr));
606 *pphdr = calloc(ehdr->e_phnum, sizeof(Elf64_Phdr));
607 memcpy(*pphdr, pelf.phdr, ehdr->e_phnum * sizeof(Elf64_Phdr));
609 if (pshdr != NULL) {
610 *pshdr = calloc(ehdr->e_shnum, sizeof(Elf64_Shdr));
611 memcpy(*pshdr, pelf.shdr, ehdr->e_shnum * sizeof(Elf64_Shdr));
614 parsed_elf_destroy(&pelf);
616 return 0;
619 /* ELF Writing Support
621 * The ELF file is written according to the following layout:
622 * +------------------+
623 * | ELF Header |
624 * +------------------+
625 * | Section Headers |
626 * +------------------+
627 * | Program Headers |
628 * +------------------+
629 * | String table |
630 * +------------------+ <- 4KiB Aligned
631 * | Code/Data |
632 * +------------------+
635 void elf_init_eheader(Elf64_Ehdr *ehdr, int machine, int nbits, int endian)
637 memset(ehdr, 0, sizeof(*ehdr));
638 ehdr->e_ident[EI_MAG0] = ELFMAG0;
639 ehdr->e_ident[EI_MAG1] = ELFMAG1;
640 ehdr->e_ident[EI_MAG2] = ELFMAG2;
641 ehdr->e_ident[EI_MAG3] = ELFMAG3;
642 ehdr->e_ident[EI_CLASS] = nbits;
643 ehdr->e_ident[EI_DATA] = endian;
644 ehdr->e_ident[EI_VERSION] = EV_CURRENT;
645 ehdr->e_type = ET_EXEC;
646 ehdr->e_machine = machine;
647 ehdr->e_version = EV_CURRENT;
648 if (nbits == ELFCLASS64) {
649 ehdr->e_ehsize = sizeof(Elf64_Ehdr);
650 ehdr->e_phentsize = sizeof(Elf64_Phdr);
651 ehdr->e_shentsize = sizeof(Elf64_Shdr);
652 } else {
653 ehdr->e_ehsize = sizeof(Elf32_Ehdr);
654 ehdr->e_phentsize = sizeof(Elf32_Phdr);
655 ehdr->e_shentsize = sizeof(Elf32_Shdr);
659 /* Arbitray maximum number of sections. */
660 #define MAX_SECTIONS 16
661 struct elf_writer_section {
662 Elf64_Shdr shdr;
663 struct buffer content;
664 const char *name;
667 struct elf_writer_string_table {
668 size_t next_offset;
669 size_t max_size;
670 char *buffer;
673 struct elf_writer_sym_table {
674 size_t max_entries;
675 size_t num_entries;
676 Elf64_Sym *syms;
679 #define MAX_REL_NAME 32
680 struct elf_writer_rel {
681 size_t num_entries;
682 size_t max_entries;
683 Elf64_Rel *rels;
684 struct elf_writer_section *sec;
685 char name[MAX_REL_NAME];
688 struct elf_writer
690 Elf64_Ehdr ehdr;
691 struct xdr *xdr;
692 size_t num_secs;
693 struct elf_writer_section sections[MAX_SECTIONS];
694 struct elf_writer_rel rel_sections[MAX_SECTIONS];
695 Elf64_Phdr *phdrs;
696 struct elf_writer_section *shstrtab_sec;
697 struct elf_writer_section *strtab_sec;
698 struct elf_writer_section *symtab_sec;
699 struct elf_writer_string_table strtab;
700 struct elf_writer_sym_table symtab;
701 int bit64;
704 static size_t section_index(struct elf_writer *ew,
705 struct elf_writer_section *sec)
707 return sec - &ew->sections[0];
710 static struct elf_writer_section *last_section(struct elf_writer *ew)
712 return &ew->sections[ew->num_secs - 1];
715 static void strtab_init(struct elf_writer *ew, size_t size)
717 struct buffer b;
718 Elf64_Shdr shdr;
720 /* Start adding strings after the initial NUL entry. */
721 ew->strtab.next_offset = 1;
722 ew->strtab.max_size = size;
723 ew->strtab.buffer = calloc(1, ew->strtab.max_size);
725 buffer_init(&b, NULL, ew->strtab.buffer, ew->strtab.max_size);
726 memset(&shdr, 0, sizeof(shdr));
727 shdr.sh_type = SHT_STRTAB;
728 shdr.sh_addralign = 1;
729 shdr.sh_size = ew->strtab.max_size;
730 elf_writer_add_section(ew, &shdr, &b, ".strtab");
731 ew->strtab_sec = last_section(ew);
734 static void symtab_init(struct elf_writer *ew, size_t max_entries)
736 struct buffer b;
737 Elf64_Shdr shdr;
739 memset(&shdr, 0, sizeof(shdr));
740 shdr.sh_type = SHT_SYMTAB;
742 if (ew->bit64) {
743 shdr.sh_entsize = sizeof(Elf64_Sym);
744 shdr.sh_addralign = sizeof(Elf64_Addr);
745 } else {
746 shdr.sh_entsize = sizeof(Elf32_Sym);
747 shdr.sh_addralign = sizeof(Elf32_Addr);
750 shdr.sh_size = shdr.sh_entsize * max_entries;
752 ew->symtab.syms = calloc(max_entries, sizeof(Elf64_Sym));
753 ew->symtab.num_entries = 1;
754 ew->symtab.max_entries = max_entries;
756 buffer_init(&b, NULL, ew->symtab.syms, shdr.sh_size);
758 elf_writer_add_section(ew, &shdr, &b, ".symtab");
759 ew->symtab_sec = last_section(ew);
762 struct elf_writer *elf_writer_init(const Elf64_Ehdr *ehdr)
764 struct elf_writer *ew;
765 Elf64_Shdr shdr;
766 struct buffer empty_buffer;
768 if (!iself(ehdr))
769 return NULL;
771 ew = calloc(1, sizeof(*ew));
773 memcpy(&ew->ehdr, ehdr, sizeof(ew->ehdr));
775 ew->bit64 = ew->ehdr.e_ident[EI_CLASS] == ELFCLASS64;
777 /* Set the endinan ops. */
778 if (ew->ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
779 ew->xdr = &xdr_be;
780 else
781 ew->xdr = &xdr_le;
783 /* Reset count and offsets */
784 ew->ehdr.e_phoff = 0;
785 ew->ehdr.e_shoff = 0;
786 ew->ehdr.e_shnum = 0;
787 ew->ehdr.e_phnum = 0;
789 memset(&empty_buffer, 0, sizeof(empty_buffer));
790 memset(&shdr, 0, sizeof(shdr));
792 /* Add SHT_NULL section header. */
793 shdr.sh_type = SHT_NULL;
794 elf_writer_add_section(ew, &shdr, &empty_buffer, NULL);
796 /* Add section header string table and maintain reference to it. */
797 shdr.sh_type = SHT_STRTAB;
798 elf_writer_add_section(ew, &shdr, &empty_buffer, ".shstrtab");
799 ew->shstrtab_sec = last_section(ew);
800 ew->ehdr.e_shstrndx = section_index(ew, ew->shstrtab_sec);
802 /* Add a small string table and symbol table. */
803 strtab_init(ew, 4096);
804 symtab_init(ew, 100);
806 return ew;
810 * Clean up any internal state represented by ew. Aftewards the elf_writer
811 * is invalid.
812 * It is safe to call elf_writer_destroy with ew as NULL. It returns without
813 * performing any action.
815 void elf_writer_destroy(struct elf_writer *ew)
817 int i;
818 if (ew == NULL)
819 return;
820 if (ew->phdrs != NULL)
821 free(ew->phdrs);
822 free(ew->strtab.buffer);
823 free(ew->symtab.syms);
824 for (i = 0; i < MAX_SECTIONS; i++)
825 free(ew->rel_sections[i].rels);
826 free(ew);
830 * Add a section to the ELF file. Section type, flags, and memsize are
831 * maintained from the passed in Elf64_Shdr. The buffer represents the
832 * content of the section while the name is the name of section itself.
833 * Returns < 0 on error, 0 on success.
835 int elf_writer_add_section(struct elf_writer *ew, const Elf64_Shdr *shdr,
836 struct buffer *contents, const char *name)
838 struct elf_writer_section *newsh;
840 if (ew->num_secs == MAX_SECTIONS)
841 return -1;
843 newsh = &ew->sections[ew->num_secs];
844 ew->num_secs++;
846 memcpy(&newsh->shdr, shdr, sizeof(newsh->shdr));
847 newsh->shdr.sh_offset = 0;
849 newsh->name = name;
850 if (contents != NULL)
851 buffer_clone(&newsh->content, contents);
853 return 0;
856 static void ehdr_write(struct elf_writer *ew, struct buffer *m)
858 int i;
860 for (i = 0; i < EI_NIDENT; i++)
861 ew->xdr->put8(m, ew->ehdr.e_ident[i]);
862 ew->xdr->put16(m, ew->ehdr.e_type);
863 ew->xdr->put16(m, ew->ehdr.e_machine);
864 ew->xdr->put32(m, ew->ehdr.e_version);
865 if (ew->bit64) {
866 ew->xdr->put64(m, ew->ehdr.e_entry);
867 ew->xdr->put64(m, ew->ehdr.e_phoff);
868 ew->xdr->put64(m, ew->ehdr.e_shoff);
869 } else {
870 ew->xdr->put32(m, ew->ehdr.e_entry);
871 ew->xdr->put32(m, ew->ehdr.e_phoff);
872 ew->xdr->put32(m, ew->ehdr.e_shoff);
874 ew->xdr->put32(m, ew->ehdr.e_flags);
875 ew->xdr->put16(m, ew->ehdr.e_ehsize);
876 ew->xdr->put16(m, ew->ehdr.e_phentsize);
877 ew->xdr->put16(m, ew->ehdr.e_phnum);
878 ew->xdr->put16(m, ew->ehdr.e_shentsize);
879 ew->xdr->put16(m, ew->ehdr.e_shnum);
880 ew->xdr->put16(m, ew->ehdr.e_shstrndx);
883 static void shdr_write(struct elf_writer *ew, size_t n, struct buffer *m)
885 struct xdr *xdr = ew->xdr;
886 int bit64 = ew->bit64;
887 struct elf_writer_section *sec = &ew->sections[n];
888 Elf64_Shdr *shdr = &sec->shdr;
890 xdr->put32(m, shdr->sh_name);
891 xdr->put32(m, shdr->sh_type);
892 if (bit64) {
893 xdr->put64(m, shdr->sh_flags);
894 xdr->put64(m, shdr->sh_addr);
895 xdr->put64(m, shdr->sh_offset);
896 xdr->put64(m, shdr->sh_size);
897 xdr->put32(m, shdr->sh_link);
898 xdr->put32(m, shdr->sh_info);
899 xdr->put64(m, shdr->sh_addralign);
900 xdr->put64(m, shdr->sh_entsize);
901 } else {
902 xdr->put32(m, shdr->sh_flags);
903 xdr->put32(m, shdr->sh_addr);
904 xdr->put32(m, shdr->sh_offset);
905 xdr->put32(m, shdr->sh_size);
906 xdr->put32(m, shdr->sh_link);
907 xdr->put32(m, shdr->sh_info);
908 xdr->put32(m, shdr->sh_addralign);
909 xdr->put32(m, shdr->sh_entsize);
913 static void
914 phdr_write(struct elf_writer *ew, struct buffer *m, Elf64_Phdr *phdr)
916 if (ew->bit64) {
917 ew->xdr->put32(m, phdr->p_type);
918 ew->xdr->put32(m, phdr->p_flags);
919 ew->xdr->put64(m, phdr->p_offset);
920 ew->xdr->put64(m, phdr->p_vaddr);
921 ew->xdr->put64(m, phdr->p_paddr);
922 ew->xdr->put64(m, phdr->p_filesz);
923 ew->xdr->put64(m, phdr->p_memsz);
924 ew->xdr->put64(m, phdr->p_align);
925 } else {
926 ew->xdr->put32(m, phdr->p_type);
927 ew->xdr->put32(m, phdr->p_offset);
928 ew->xdr->put32(m, phdr->p_vaddr);
929 ew->xdr->put32(m, phdr->p_paddr);
930 ew->xdr->put32(m, phdr->p_filesz);
931 ew->xdr->put32(m, phdr->p_memsz);
932 ew->xdr->put32(m, phdr->p_flags);
933 ew->xdr->put32(m, phdr->p_align);
938 static int section_consecutive(struct elf_writer *ew, Elf64_Half secidx)
940 Elf64_Half i;
941 struct elf_writer_section *prev_alloc = NULL;
943 if (secidx == 0)
944 return 0;
946 for (i = 0; i < secidx; i++) {
947 if (ew->sections[i].shdr.sh_flags & SHF_ALLOC)
948 prev_alloc = &ew->sections[i];
951 if (prev_alloc == NULL)
952 return 0;
954 if (prev_alloc->shdr.sh_addr + prev_alloc->shdr.sh_size ==
955 ew->sections[secidx].shdr.sh_addr)
956 return 1;
958 return 0;
961 static void write_phdrs(struct elf_writer *ew, struct buffer *phdrs)
963 Elf64_Half i;
964 Elf64_Phdr phdr;
965 size_t num_written = 0;
966 size_t num_needs_write = 0;
968 for (i = 0; i < ew->num_secs; i++) {
969 struct elf_writer_section *sec = &ew->sections[i];
971 if (!(sec->shdr.sh_flags & SHF_ALLOC))
972 continue;
974 if (!section_consecutive(ew, i)) {
975 /* Write out previously set phdr. */
976 if (num_needs_write != num_written) {
977 phdr_write(ew, phdrs, &phdr);
978 num_written++;
980 phdr.p_type = PT_LOAD;
981 phdr.p_offset = sec->shdr.sh_offset;
982 phdr.p_vaddr = sec->shdr.sh_addr;
983 phdr.p_paddr = sec->shdr.sh_addr;
984 phdr.p_filesz = buffer_size(&sec->content);
985 phdr.p_memsz = sec->shdr.sh_size;
986 phdr.p_flags = 0;
987 if (sec->shdr.sh_flags & SHF_EXECINSTR)
988 phdr.p_flags |= PF_X | PF_R;
989 if (sec->shdr.sh_flags & SHF_WRITE)
990 phdr.p_flags |= PF_W;
991 phdr.p_align = sec->shdr.sh_addralign;
992 num_needs_write++;
994 } else {
995 /* Accumulate file size and memsize. The assumption
996 * is that each section is either NOBITS or full
997 * (sh_size == file size). This is standard in that
998 * an ELF section doesn't have a file size component. */
999 if (sec->shdr.sh_flags & SHF_EXECINSTR)
1000 phdr.p_flags |= PF_X | PF_R;
1001 if (sec->shdr.sh_flags & SHF_WRITE)
1002 phdr.p_flags |= PF_W;
1003 phdr.p_filesz += buffer_size(&sec->content);
1004 phdr.p_memsz += sec->shdr.sh_size;
1008 /* Write out the last phdr. */
1009 if (num_needs_write != num_written) {
1010 phdr_write(ew, phdrs, &phdr);
1011 num_written++;
1013 assert(num_written == ew->ehdr.e_phnum);
1016 static void fixup_symbol_table(struct elf_writer *ew)
1018 struct elf_writer_section *sec = ew->symtab_sec;
1020 /* If there is only the NULL section, mark section as inactive. */
1021 if (ew->symtab.num_entries == 1) {
1022 sec->shdr.sh_type = SHT_NULL;
1023 sec->shdr.sh_size = 0;
1024 } else {
1025 size_t i;
1026 struct buffer wr;
1028 buffer_clone(&wr, &sec->content);
1029 /* To appease xdr. */
1030 buffer_set_size(&wr, 0);
1031 for (i = 0; i < ew->symtab.num_entries; i++) {
1032 /* Create local copy as were over-writing backing
1033 * store of the symbol. */
1034 Elf64_Sym sym = ew->symtab.syms[i];
1035 if (ew->bit64) {
1036 ew->xdr->put32(&wr, sym.st_name);
1037 ew->xdr->put8(&wr, sym.st_info);
1038 ew->xdr->put8(&wr, sym.st_other);
1039 ew->xdr->put16(&wr, sym.st_shndx);
1040 ew->xdr->put64(&wr, sym.st_value);
1041 ew->xdr->put64(&wr, sym.st_size);
1042 } else {
1043 ew->xdr->put32(&wr, sym.st_name);
1044 ew->xdr->put32(&wr, sym.st_value);
1045 ew->xdr->put32(&wr, sym.st_size);
1046 ew->xdr->put8(&wr, sym.st_info);
1047 ew->xdr->put8(&wr, sym.st_other);
1048 ew->xdr->put16(&wr, sym.st_shndx);
1052 /* Update section size. */
1053 sec->shdr.sh_size = sec->shdr.sh_entsize;
1054 sec->shdr.sh_size *= ew->symtab.num_entries;
1056 /* Fix up sh_link to point to string table. */
1057 sec->shdr.sh_link = section_index(ew, ew->strtab_sec);
1058 /* sh_info is supposed to be 1 greater than symbol table
1059 * index of last local binding. Just use max symbols. */
1060 sec->shdr.sh_info = ew->symtab.num_entries;
1063 buffer_set_size(&sec->content, sec->shdr.sh_size);
1066 static void fixup_relocations(struct elf_writer *ew)
1068 int i;
1069 Elf64_Xword type;
1071 switch (ew->ehdr.e_machine) {
1072 case EM_386:
1073 type = R_386_32;
1074 break;
1075 case EM_ARM:
1076 type = R_ARM_ABS32;
1077 break;
1078 case EM_AARCH64:
1079 type = R_AARCH64_ABS64;
1080 break;
1081 case EM_MIPS:
1082 type = R_MIPS_32;
1083 break;
1084 case EM_RISCV:
1085 type = R_RISCV_32;
1086 break;
1087 case EM_PPC64:
1088 type = R_PPC64_ADDR32;
1089 break;
1090 default:
1091 ERROR("Unable to handle relocations for e_machine %x\n",
1092 ew->ehdr.e_machine);
1093 return;
1096 for (i = 0; i < MAX_SECTIONS; i++) {
1097 struct elf_writer_rel *rel_sec = &ew->rel_sections[i];
1098 struct elf_writer_section *sec = rel_sec->sec;
1099 struct buffer writer;
1100 size_t j;
1102 if (sec == NULL)
1103 continue;
1105 /* Update section header size as well as content size. */
1106 buffer_init(&sec->content, sec->content.name, rel_sec->rels,
1107 rel_sec->num_entries * sec->shdr.sh_entsize);
1108 sec->shdr.sh_size = buffer_size(&sec->content);
1109 buffer_clone(&writer, &sec->content);
1110 /* To make xdr happy. */
1111 buffer_set_size(&writer, 0);
1113 for (j = 0; j < ew->rel_sections[i].num_entries; j++) {
1114 /* Make copy as we're overwriting backing store. */
1115 Elf64_Rel rel = rel_sec->rels[j];
1116 rel.r_info = ELF64_R_INFO(ELF64_R_SYM(rel.r_info),
1117 ELF64_R_TYPE(type));
1119 if (ew->bit64) {
1120 ew->xdr->put64(&writer, rel.r_offset);
1121 ew->xdr->put64(&writer, rel.r_info);
1122 } else {
1123 Elf32_Rel rel32;
1124 rel32.r_offset = rel.r_offset;
1125 rel32.r_info =
1126 ELF32_R_INFO(ELF64_R_SYM(rel.r_info),
1127 ELF64_R_TYPE(rel.r_info));
1128 ew->xdr->put32(&writer, rel32.r_offset);
1129 ew->xdr->put32(&writer, rel32.r_info);
1136 * Serialize the ELF file to the output buffer. Return < 0 on error,
1137 * 0 on success.
1139 int elf_writer_serialize(struct elf_writer *ew, struct buffer *out)
1141 Elf64_Half i;
1142 Elf64_Xword metadata_size;
1143 Elf64_Xword program_size;
1144 Elf64_Off shstroffset;
1145 size_t shstrlen;
1146 struct buffer metadata;
1147 struct buffer phdrs;
1148 struct buffer data;
1149 struct buffer *strtab;
1151 INFO("Writing %zu sections.\n", ew->num_secs);
1153 /* Perform any necessary work for special sections. */
1154 fixup_symbol_table(ew);
1155 fixup_relocations(ew);
1157 /* Determine size of sections to be written. */
1158 program_size = 0;
1159 /* Start with 1 byte for first byte of section header string table. */
1160 shstrlen = 1;
1161 for (i = 0; i < ew->num_secs; i++) {
1162 struct elf_writer_section *sec = &ew->sections[i];
1164 if (sec->shdr.sh_flags & SHF_ALLOC) {
1165 if (!section_consecutive(ew, i))
1166 ew->ehdr.e_phnum++;
1169 program_size += buffer_size(&sec->content);
1171 /* Keep track of the length sections' names. */
1172 if (sec->name != NULL) {
1173 sec->shdr.sh_name = shstrlen;
1174 shstrlen += strlen(sec->name) + 1;
1177 ew->ehdr.e_shnum = ew->num_secs;
1178 metadata_size = 0;
1179 metadata_size += ew->ehdr.e_ehsize;
1180 metadata_size += ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1181 metadata_size += ew->ehdr.e_phnum * ew->ehdr.e_phentsize;
1182 shstroffset = metadata_size;
1183 /* Align up section header string size and metadata size to 4KiB */
1184 metadata_size = ALIGN(metadata_size + shstrlen, 4096);
1186 if (buffer_create(out, metadata_size + program_size, "elfout")) {
1187 ERROR("Could not create output buffer for ELF.\n");
1188 return -1;
1191 INFO("Created %zu output buffer for ELF file.\n", buffer_size(out));
1194 * Write out ELF header. Section headers come right after ELF header
1195 * followed by the program headers. Buffers need to be created first
1196 * to do the writing.
1198 ew->ehdr.e_shoff = ew->ehdr.e_ehsize;
1199 ew->ehdr.e_phoff = ew->ehdr.e_shoff +
1200 ew->ehdr.e_shnum * ew->ehdr.e_shentsize;
1202 buffer_splice(&metadata, out, 0, metadata_size);
1203 buffer_splice(&phdrs, out, ew->ehdr.e_phoff,
1204 ew->ehdr.e_phnum * ew->ehdr.e_phentsize);
1205 buffer_splice(&data, out, metadata_size, program_size);
1206 /* Set up the section header string table contents. */
1207 strtab = &ew->shstrtab_sec->content;
1208 buffer_splice(strtab, out, shstroffset, shstrlen);
1209 ew->shstrtab_sec->shdr.sh_size = shstrlen;
1211 /* Reset current locations. */
1212 buffer_set_size(&metadata, 0);
1213 buffer_set_size(&data, 0);
1214 buffer_set_size(&phdrs, 0);
1215 buffer_set_size(strtab, 0);
1217 /* ELF Header */
1218 ehdr_write(ew, &metadata);
1220 /* Write out section headers, section strings, section content, and
1221 * program headers. */
1222 ew->xdr->put8(strtab, 0);
1223 for (i = 0; i < ew->num_secs; i++) {
1224 struct elf_writer_section *sec = &ew->sections[i];
1226 /* Update section offsets. Be sure to not update SHN_UNDEF. */
1227 if (sec == ew->shstrtab_sec)
1228 sec->shdr.sh_offset = shstroffset;
1229 else if (i != SHN_UNDEF)
1230 sec->shdr.sh_offset = buffer_size(&data) +
1231 metadata_size;
1233 shdr_write(ew, i, &metadata);
1235 /* Add section name to string table. */
1236 if (sec->name != NULL)
1237 bputs(strtab, sec->name, strlen(sec->name) + 1);
1239 /* Output section data for all sections but SHN_UNDEF and
1240 * section header string table. */
1241 if (i != SHN_UNDEF && sec != ew->shstrtab_sec)
1242 bputs(&data, buffer_get(&sec->content),
1243 buffer_size(&sec->content));
1246 write_phdrs(ew, &phdrs);
1248 return 0;
1251 /* Add a string to the string table returning index on success, < 0 on error. */
1252 static int elf_writer_add_string(struct elf_writer *ew, const char *new)
1254 size_t current_offset;
1255 size_t new_len;
1257 for (current_offset = 0; current_offset < ew->strtab.next_offset; ) {
1258 const char *str = ew->strtab.buffer + current_offset;
1259 size_t len = strlen(str) + 1;
1261 if (!strcmp(str, new))
1262 return current_offset;
1263 current_offset += len;
1266 new_len = strlen(new) + 1;
1268 if (current_offset + new_len > ew->strtab.max_size) {
1269 ERROR("No space for string in .strtab.\n");
1270 return -1;
1273 memcpy(ew->strtab.buffer + current_offset, new, new_len);
1274 ew->strtab.next_offset = current_offset + new_len;
1276 return current_offset;
1279 static int elf_writer_section_index(struct elf_writer *ew, const char *name)
1281 size_t i;
1283 for (i = 0; i < ew->num_secs; i++) {
1284 if (ew->sections[i].name == NULL)
1285 continue;
1286 if (!strcmp(ew->sections[i].name, name))
1287 return i;
1290 ERROR("ELF Section not found: %s\n", name);
1292 return -1;
1295 int elf_writer_add_symbol(struct elf_writer *ew, const char *name,
1296 const char *section_name,
1297 Elf64_Addr value, Elf64_Word size,
1298 int binding, int type)
1300 int i;
1301 Elf64_Sym sym = {
1302 .st_value = value,
1303 .st_size = size,
1304 .st_info = ELF64_ST_INFO(binding, type),
1307 if (ew->symtab.max_entries == ew->symtab.num_entries) {
1308 ERROR("No more symbol entries left.\n");
1309 return -1;
1312 i = elf_writer_add_string(ew, name);
1313 if (i < 0)
1314 return -1;
1315 sym.st_name = i;
1317 i = elf_writer_section_index(ew, section_name);
1318 if (i < 0)
1319 return -1;
1320 sym.st_shndx = i;
1322 ew->symtab.syms[ew->symtab.num_entries++] = sym;
1324 return 0;
1327 static int elf_sym_index(struct elf_writer *ew, const char *sym)
1329 int j;
1330 size_t i;
1331 Elf64_Word st_name;
1333 /* Determine index of symbol in the string table. */
1334 j = elf_writer_add_string(ew, sym);
1335 if (j < 0)
1336 return -1;
1338 st_name = j;
1340 for (i = 0; i < ew->symtab.num_entries; i++)
1341 if (ew->symtab.syms[i].st_name == st_name)
1342 return i;
1344 return -1;
1347 static struct elf_writer_rel *rel_section(struct elf_writer *ew,
1348 const Elf64_Rel *r)
1350 Elf64_Sym *sym;
1351 struct elf_writer_rel *rel;
1352 Elf64_Shdr shdr;
1353 struct buffer b;
1355 sym = &ew->symtab.syms[ELF64_R_SYM(r->r_info)];
1357 /* Determine if section has been initialized yet. */
1358 rel = &ew->rel_sections[sym->st_shndx];
1359 if (rel->sec != NULL)
1360 return rel;
1362 memset(&shdr, 0, sizeof(shdr));
1363 shdr.sh_type = SHT_REL;
1364 shdr.sh_link = section_index(ew, ew->symtab_sec);
1365 shdr.sh_info = sym->st_shndx;
1367 if (ew->bit64) {
1368 shdr.sh_addralign = sizeof(Elf64_Addr);
1369 shdr.sh_entsize = sizeof(Elf64_Rel);
1370 } else {
1371 shdr.sh_addralign = sizeof(Elf32_Addr);
1372 shdr.sh_entsize = sizeof(Elf32_Rel);
1375 if ((strlen(".rel") + strlen(ew->sections[sym->st_shndx].name) + 1) >
1376 MAX_REL_NAME) {
1377 ERROR("Rel Section name won't fit\n");
1378 return NULL;
1381 strcat(rel->name, ".rel");
1382 strcat(rel->name, ew->sections[sym->st_shndx].name);
1383 buffer_init(&b, rel->name, NULL, 0);
1385 elf_writer_add_section(ew, &shdr, &b, rel->name);
1386 rel->sec = last_section(ew);
1388 return rel;
1391 static int add_rel(struct elf_writer_rel *rel_sec, const Elf64_Rel *rel)
1393 if (rel_sec->num_entries == rel_sec->max_entries) {
1394 size_t num = rel_sec->max_entries * 2;
1395 Elf64_Rel *old_rels;
1397 if (num == 0)
1398 num = 128;
1400 old_rels = rel_sec->rels;
1401 rel_sec->rels = calloc(num, sizeof(Elf64_Rel));
1403 memcpy(rel_sec->rels, old_rels,
1404 rel_sec->num_entries * sizeof(Elf64_Rel));
1405 free(old_rels);
1407 rel_sec->max_entries = num;
1410 rel_sec->rels[rel_sec->num_entries] = *rel;
1411 rel_sec->num_entries++;
1413 return 0;
1416 int elf_writer_add_rel(struct elf_writer *ew, const char *sym, Elf64_Addr addr)
1418 Elf64_Rel rel;
1419 Elf64_Xword sym_info;
1420 int sym_index;
1421 struct elf_writer_rel *rel_sec;
1423 sym_index = elf_sym_index(ew, sym);
1425 if (sym_index < 0) {
1426 ERROR("Unable to locate symbol: %s\n", sym);
1427 return -1;
1430 sym_info = sym_index;
1432 /* The relocation type will get fixed prior to serialization. */
1433 rel.r_offset = addr;
1434 rel.r_info = ELF64_R_INFO(sym_info, 0);
1436 rel_sec = rel_section(ew, &rel);
1438 if (rel_sec == NULL)
1439 return -1;
1441 return add_rel(rel_sec, &rel);
1444 int elf_program_file_size(const struct buffer *input, size_t *file_size)
1446 Elf64_Ehdr ehdr;
1447 Elf64_Phdr *phdr;
1448 int i;
1449 size_t loadable_file_size = 0;
1451 if (elf_headers(input, &ehdr, &phdr, NULL))
1452 return -1;
1454 for (i = 0; i < ehdr.e_phnum; i++) {
1455 if (phdr[i].p_type != PT_LOAD)
1456 continue;
1457 loadable_file_size += phdr[i].p_filesz;
1460 *file_size = loadable_file_size;
1462 free(phdr);
1464 return 0;