Path: blob/main/contrib/elftoolchain/elfcopy/binary.c
39534 views
/*-1* Copyright (c) 2010,2011 Kai Wang2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12*13* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND14* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE17* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL18* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)20* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT21* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY22* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF23* SUCH DAMAGE.24*/2526#include <sys/param.h>27#include <sys/stat.h>28#include <ctype.h>29#include <err.h>30#include <gelf.h>31#include <stdio.h>32#include <stdlib.h>33#include <string.h>34#include <unistd.h>3536#include "elfcopy.h"3738ELFTC_VCSID("$Id: binary.c 3757 2019-06-28 01:15:28Z emaste $");3940/*41* Convert ELF object to `binary'. Sections with SHF_ALLOC flag set42* are copied to the result binary. The relative offsets for each section43* are retained, so the result binary file might contain "holes".44*/45void46create_binary(int ifd, int ofd)47{48Elf *e;49Elf_Scn *scn;50Elf_Data *d;51Elf64_Addr baseaddr;52GElf_Shdr sh;53off_t baseoff, off;54int elferr;5556if ((e = elf_begin(ifd, ELF_C_READ, NULL)) == NULL)57errx(EXIT_FAILURE, "elf_begin() failed: %s",58elf_errmsg(-1));5960baseaddr = 0;61baseoff = 0;62if (lseek(ofd, baseoff, SEEK_SET) < 0)63err(EXIT_FAILURE, "lseek failed");6465/*66* Find base offset in the first iteration.67*/68baseoff = -1;69scn = NULL;70while ((scn = elf_nextscn(e, scn)) != NULL) {71if (gelf_getshdr(scn, &sh) == NULL) {72warnx("gelf_getshdr failed: %s", elf_errmsg(-1));73(void) elf_errno();74continue;75}76if ((sh.sh_flags & SHF_ALLOC) == 0 ||77sh.sh_type == SHT_NOBITS ||78sh.sh_size == 0)79continue;80if (baseoff == -1 || (off_t) sh.sh_offset < baseoff) {81baseoff = sh.sh_offset;82baseaddr = sh.sh_addr;83}84}85elferr = elf_errno();86if (elferr != 0)87warnx("elf_nextscn failed: %s", elf_errmsg(elferr));8889if (baseoff == -1)90return;9192/*93* Write out sections in the second iteration.94*/95scn = NULL;96while ((scn = elf_nextscn(e, scn)) != NULL) {97if (gelf_getshdr(scn, &sh) == NULL) {98warnx("gelf_getshdr failed: %s", elf_errmsg(-1));99(void) elf_errno();100continue;101}102if ((sh.sh_flags & SHF_ALLOC) == 0 ||103sh.sh_type == SHT_NOBITS ||104sh.sh_size == 0)105continue;106(void) elf_errno();107if ((d = elf_rawdata(scn, NULL)) == NULL) {108elferr = elf_errno();109if (elferr != 0)110warnx("elf_rawdata failed: %s", elf_errmsg(-1));111continue;112}113if (d->d_buf == NULL || d->d_size == 0)114continue;115116/* lseek to section offset relative to `baseaddr'. */117off = sh.sh_addr - baseaddr;118if (lseek(ofd, off, SEEK_SET) < 0)119err(EXIT_FAILURE, "lseek failed");120121/* Write out section contents. */122if (write(ofd, d->d_buf, d->d_size) != (ssize_t) d->d_size)123err(EXIT_FAILURE, "write failed");124}125elferr = elf_errno();126if (elferr != 0)127warnx("elf_nextscn failed: %s", elf_errmsg(elferr));128}129130#define _SYMBOL_NAMSZ 1024131132/*133* Convert `binary' to ELF object. The input `binary' is converted to134* a relocatable (.o) file, a few symbols will also be created to make135* it easier to access the binary data in other compilation units.136*/137void138create_elf_from_binary(struct elfcopy *ecp, int ifd, const char *ifn)139{140char name[_SYMBOL_NAMSZ];141struct section *sec, *sec_temp, *shtab;142struct stat sb;143GElf_Ehdr oeh;144GElf_Shdr sh;145void *content;146uint64_t off, data_start, data_end, data_size;147char *sym_basename, *p;148149/* Reset internal section list. */150if (!TAILQ_EMPTY(&ecp->v_sec))151TAILQ_FOREACH_SAFE(sec, &ecp->v_sec, sec_list, sec_temp) {152TAILQ_REMOVE(&ecp->v_sec, sec, sec_list);153free(sec);154}155156if (fstat(ifd, &sb) == -1)157err(EXIT_FAILURE, "fstat failed");158159/* Read the input binary file to a internal buffer. */160if ((content = malloc(sb.st_size)) == NULL)161err(EXIT_FAILURE, "malloc failed");162if (read(ifd, content, sb.st_size) != sb.st_size)163err(EXIT_FAILURE, "read failed");164165/*166* TODO: copy the input binary to output binary verbatim if -O is not167* specified.168*/169170/* Create EHDR for output .o file. */171if (gelf_newehdr(ecp->eout, ecp->oec) == NULL)172errx(EXIT_FAILURE, "gelf_newehdr failed: %s",173elf_errmsg(-1));174if (gelf_getehdr(ecp->eout, &oeh) == NULL)175errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",176elf_errmsg(-1));177178/* Initialise e_ident fields. */179oeh.e_ident[EI_CLASS] = ecp->oec;180oeh.e_ident[EI_DATA] = ecp->oed;181/*182* TODO: Set OSABI according to the OS platform where elfcopy(1)183* was build. (probably)184*/185oeh.e_ident[EI_OSABI] = ELFOSABI_NONE;186oeh.e_machine = ecp->oem;187oeh.e_type = ET_REL;188oeh.e_entry = 0;189190ecp->flags |= RELOCATABLE;191192/* Create .shstrtab section */193init_shstrtab(ecp);194ecp->shstrtab->off = 0;195196/*197* Create `.data' section which contains the binary data. The198* section is inserted immediately after EHDR.199*/200off = gelf_fsize(ecp->eout, ELF_T_EHDR, 1, EV_CURRENT);201if (off == 0)202errx(EXIT_FAILURE, "gelf_fsize() failed: %s", elf_errmsg(-1));203(void) create_external_section(ecp, ".data", NULL, content, sb.st_size,204off, SHT_PROGBITS, ELF_T_BYTE, SHF_ALLOC | SHF_WRITE, 1, 0, 1);205206/* Insert .shstrtab after .data section. */207if ((ecp->shstrtab->os = elf_newscn(ecp->eout)) == NULL)208errx(EXIT_FAILURE, "elf_newscn failed: %s",209elf_errmsg(-1));210insert_to_sec_list(ecp, ecp->shstrtab, 1);211212/* Insert section header table here. */213shtab = insert_shtab(ecp, 1);214215/* Count in .symtab and .strtab section headers. */216shtab->sz += gelf_fsize(ecp->eout, ELF_T_SHDR, 2, EV_CURRENT);217218if ((sym_basename = strdup(ifn)) == NULL)219err(1, "strdup");220for (p = sym_basename; *p != '\0'; p++)221if (!isalnum(*p & 0xFF))222*p = '_';223#define _GEN_SYMNAME(S) do { \224snprintf(name, sizeof(name), "%s%s%s", "_binary_", sym_basename, S); \225} while (0)226227/*228* Create symbol table.229*/230create_external_symtab(ecp);231data_start = 0;232data_end = data_start + sb.st_size;233data_size = sb.st_size;234_GEN_SYMNAME("_start");235add_to_symtab(ecp, name, data_start, 0, 1,236ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);237_GEN_SYMNAME("_end");238add_to_symtab(ecp, name, data_end, 0, 1,239ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);240_GEN_SYMNAME("_size");241add_to_symtab(ecp, name, data_size, 0, SHN_ABS,242ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);243finalize_external_symtab(ecp);244create_symtab_data(ecp);245#undef _GEN_SYMNAME246free(sym_basename);247248/*249* Write the underlying ehdr. Note that it should be called250* before elf_setshstrndx() since it will overwrite e->e_shstrndx.251*/252if (gelf_update_ehdr(ecp->eout, &oeh) == 0)253errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",254elf_errmsg(-1));255256/* Update sh_name pointer for each section header entry. */257ecp->flags |= SYMTAB_EXIST;258update_shdr(ecp, 0);259260/* Properly set sh_link field of .symtab section. */261if (gelf_getshdr(ecp->symtab->os, &sh) == NULL)262errx(EXIT_FAILURE, "692 gelf_getshdr() failed: %s",263elf_errmsg(-1));264sh.sh_link = elf_ndxscn(ecp->strtab->os);265if (!gelf_update_shdr(ecp->symtab->os, &sh))266errx(EXIT_FAILURE, "gelf_update_shdr() failed: %s",267elf_errmsg(-1));268269/* Renew oeh to get the updated e_shstrndx. */270if (gelf_getehdr(ecp->eout, &oeh) == NULL)271errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",272elf_errmsg(-1));273274/* Resync section offsets. */275resync_sections(ecp);276277/* Store SHDR offset in EHDR. */278oeh.e_shoff = shtab->off;279280/* Update ehdr since we modified e_shoff. */281if (gelf_update_ehdr(ecp->eout, &oeh) == 0)282errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",283elf_errmsg(-1));284285/* Write out the output elf object. */286if (elf_update(ecp->eout, ELF_C_WRITE) < 0)287errx(EXIT_FAILURE, "elf_update() failed: %s",288elf_errmsg(-1));289290/* Release allocated resource. */291free(content);292free_elf(ecp);293}294295296