Path: blob/main/contrib/elftoolchain/elfcopy/main.c
39536 views
/*-1* Copyright (c) 2007-2013 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>2829#include <err.h>30#include <errno.h>31#include <fcntl.h>32#include <getopt.h>33#include <libelftc.h>34#include <stdio.h>35#include <stdlib.h>36#include <string.h>37#include <unistd.h>3839#include "elfcopy.h"4041ELFTC_VCSID("$Id: main.c 3757 2019-06-28 01:15:28Z emaste $");4243enum options44{45ECP_ADD_GNU_DEBUGLINK,46ECP_ADD_SECTION,47ECP_CHANGE_ADDR,48ECP_CHANGE_SEC_ADDR,49ECP_CHANGE_SEC_LMA,50ECP_CHANGE_SEC_VMA,51ECP_CHANGE_START,52ECP_CHANGE_WARN,53ECP_GAP_FILL,54ECP_GLOBALIZE_SYMBOL,55ECP_GLOBALIZE_SYMBOLS,56ECP_KEEP_SYMBOLS,57ECP_KEEP_GLOBAL_SYMBOLS,58ECP_LOCALIZE_HIDDEN,59ECP_LOCALIZE_SYMBOLS,60ECP_NO_CHANGE_WARN,61ECP_ONLY_DEBUG,62ECP_ONLY_DWO,63ECP_PAD_TO,64ECP_PREFIX_ALLOC,65ECP_PREFIX_SEC,66ECP_PREFIX_SYM,67ECP_REDEF_SYMBOL,68ECP_REDEF_SYMBOLS,69ECP_RENAME_SECTION,70ECP_SET_OSABI,71ECP_SET_SEC_FLAGS,72ECP_SET_START,73ECP_SREC_FORCE_S3,74ECP_SREC_LEN,75ECP_STRIP_DWO,76ECP_STRIP_SYMBOLS,77ECP_STRIP_UNNEEDED,78ECP_WEAKEN_ALL,79ECP_WEAKEN_SYMBOLS80};8182static struct option mcs_longopts[] =83{84{ "help", no_argument, NULL, 'h' },85{ "version", no_argument, NULL, 'V' },86{ NULL, 0, NULL, 0 }87};8889static struct option strip_longopts[] =90{91{"discard-all", no_argument, NULL, 'x'},92{"discard-locals", no_argument, NULL, 'X'},93{"help", no_argument, NULL, 'h'},94{"input-target", required_argument, NULL, 'I'},95{"keep-symbol", required_argument, NULL, 'K'},96{"only-keep-debug", no_argument, NULL, ECP_ONLY_DEBUG},97{"output-file", required_argument, NULL, 'o'},98{"output-target", required_argument, NULL, 'O'},99{"preserve-dates", no_argument, NULL, 'p'},100{"remove-section", required_argument, NULL, 'R'},101{"strip-all", no_argument, NULL, 's'},102{"strip-debug", no_argument, NULL, 'S'},103{"strip-symbol", required_argument, NULL, 'N'},104{"strip-unneeded", no_argument, NULL, ECP_STRIP_UNNEEDED},105{"version", no_argument, NULL, 'V'},106{"wildcard", no_argument, NULL, 'w'},107{NULL, 0, NULL, 0}108};109110static struct option elfcopy_longopts[] =111{112{"add-gnu-debuglink", required_argument, NULL, ECP_ADD_GNU_DEBUGLINK},113{"add-section", required_argument, NULL, ECP_ADD_SECTION},114{"adjust-section-vma", required_argument, NULL, ECP_CHANGE_SEC_ADDR},115{"adjust-vma", required_argument, NULL, ECP_CHANGE_ADDR},116{"adjust-start", required_argument, NULL, ECP_CHANGE_START},117{"adjust-warnings", no_argument, NULL, ECP_CHANGE_WARN},118{"binary-architecture", required_argument, NULL, 'B'},119{"change-addresses", required_argument, NULL, ECP_CHANGE_ADDR},120{"change-section-address", required_argument, NULL,121ECP_CHANGE_SEC_ADDR},122{"change-section-lma", required_argument, NULL, ECP_CHANGE_SEC_LMA},123{"change-section-vma", required_argument, NULL, ECP_CHANGE_SEC_VMA},124{"change-start", required_argument, NULL, ECP_CHANGE_START},125{"change-warnings", no_argument, NULL, ECP_CHANGE_WARN},126{"discard-all", no_argument, NULL, 'x'},127{"discard-locals", no_argument, NULL, 'X'},128{"extract-dwo", no_argument, NULL, ECP_ONLY_DWO},129{"gap-fill", required_argument, NULL, ECP_GAP_FILL},130{"globalize-symbol", required_argument, NULL, ECP_GLOBALIZE_SYMBOL},131{"globalize-symbols", required_argument, NULL, ECP_GLOBALIZE_SYMBOLS},132{"help", no_argument, NULL, 'h'},133{"input-target", required_argument, NULL, 'I'},134{"keep-symbol", required_argument, NULL, 'K'},135{"keep-symbols", required_argument, NULL, ECP_KEEP_SYMBOLS},136{"keep-global-symbol", required_argument, NULL, 'G'},137{"keep-global-symbols", required_argument, NULL,138ECP_KEEP_GLOBAL_SYMBOLS},139{"localize-hidden", no_argument, NULL, ECP_LOCALIZE_HIDDEN},140{"localize-symbol", required_argument, NULL, 'L'},141{"localize-symbols", required_argument, NULL, ECP_LOCALIZE_SYMBOLS},142{"no-adjust-warnings", no_argument, NULL, ECP_NO_CHANGE_WARN},143{"no-change-warnings", no_argument, NULL, ECP_NO_CHANGE_WARN},144{"only-keep-debug", no_argument, NULL, ECP_ONLY_DEBUG},145{"only-section", required_argument, NULL, 'j'},146{"osabi", required_argument, NULL, ECP_SET_OSABI},147{"output-target", required_argument, NULL, 'O'},148{"pad-to", required_argument, NULL, ECP_PAD_TO},149{"preserve-dates", no_argument, NULL, 'p'},150{"prefix-alloc-sections", required_argument, NULL, ECP_PREFIX_ALLOC},151{"prefix-sections", required_argument, NULL, ECP_PREFIX_SEC},152{"prefix-symbols", required_argument, NULL, ECP_PREFIX_SYM},153{"redefine-sym", required_argument, NULL, ECP_REDEF_SYMBOL},154{"redefine-syms", required_argument, NULL, ECP_REDEF_SYMBOLS},155{"remove-section", required_argument, NULL, 'R'},156{"rename-section", required_argument, NULL, ECP_RENAME_SECTION},157{"set-section-flags", required_argument, NULL, ECP_SET_SEC_FLAGS},158{"set-start", required_argument, NULL, ECP_SET_START},159{"srec-forceS3", no_argument, NULL, ECP_SREC_FORCE_S3},160{"srec-len", required_argument, NULL, ECP_SREC_LEN},161{"strip-all", no_argument, NULL, 'S'},162{"strip-debug", no_argument, 0, 'g'},163{"strip-dwo", no_argument, NULL, ECP_STRIP_DWO},164{"strip-symbol", required_argument, NULL, 'N'},165{"strip-symbols", required_argument, NULL, ECP_STRIP_SYMBOLS},166{"strip-unneeded", no_argument, NULL, ECP_STRIP_UNNEEDED},167{"version", no_argument, NULL, 'V'},168{"weaken", no_argument, NULL, ECP_WEAKEN_ALL},169{"weaken-symbol", required_argument, NULL, 'W'},170{"weaken-symbols", required_argument, NULL, ECP_WEAKEN_SYMBOLS},171{"wildcard", no_argument, NULL, 'w'},172{NULL, 0, NULL, 0}173};174175static struct {176const char *name;177int value;178} sec_flags[] = {179{"alloc", SF_ALLOC},180{"load", SF_LOAD},181{"noload", SF_NOLOAD},182{"readonly", SF_READONLY},183{"debug", SF_DEBUG},184{"code", SF_CODE},185{"data", SF_DATA},186{"rom", SF_ROM},187{"share", SF_SHARED},188{"contents", SF_CONTENTS},189{NULL, 0}190};191192static struct {193const char *name;194int abi;195} osabis[] = {196{"sysv", ELFOSABI_SYSV},197{"hpus", ELFOSABI_HPUX},198{"netbsd", ELFOSABI_NETBSD},199{"linux", ELFOSABI_LINUX},200{"hurd", ELFOSABI_HURD},201{"86open", ELFOSABI_86OPEN},202{"solaris", ELFOSABI_SOLARIS},203{"aix", ELFOSABI_AIX},204{"irix", ELFOSABI_IRIX},205{"freebsd", ELFOSABI_FREEBSD},206{"tru64", ELFOSABI_TRU64},207{"modesto", ELFOSABI_MODESTO},208{"openbsd", ELFOSABI_OPENBSD},209{"openvms", ELFOSABI_OPENVMS},210{"nsk", ELFOSABI_NSK},211{"cloudabi", ELFOSABI_CLOUDABI},212{"arm", ELFOSABI_ARM},213{"standalone", ELFOSABI_STANDALONE},214{NULL, 0}215};216217static int copy_from_tempfile(const char *src, const char *dst,218int infd, int *outfd, int in_place);219static void create_file(struct elfcopy *ecp, const char *src,220const char *dst);221static void elfcopy_main(struct elfcopy *ecp, int argc, char **argv);222static void elfcopy_usage(void);223static void mcs_main(struct elfcopy *ecp, int argc, char **argv);224static void mcs_usage(void);225static void parse_sec_address_op(struct elfcopy *ecp, int optnum,226const char *optname, char *s);227static void parse_sec_flags(struct sec_action *sac, char *s);228static void parse_symlist_file(struct elfcopy *ecp, const char *fn,229unsigned int op);230static void print_version(void);231static void set_input_target(struct elfcopy *ecp, const char *target_name);232static void set_osabi(struct elfcopy *ecp, const char *abi);233static void set_output_target(struct elfcopy *ecp, const char *target_name);234static void strip_main(struct elfcopy *ecp, int argc, char **argv);235static void strip_usage(void);236237/*238* An ELF object usually has a structure described by the239* diagram below.240* _____________241* | |242* | NULL | <- always a SHT_NULL section243* |_____________|244* | |245* | .interp |246* |_____________|247* | |248* | ... |249* |_____________|250* | |251* | .text |252* |_____________|253* | |254* | ... |255* |_____________|256* | |257* | .comment | <- above(include) this: normal sections258* |_____________|259* | |260* | add sections| <- unloadable sections added by --add-section261* |_____________|262* | |263* | .shstrtab | <- section name string table264* |_____________|265* | |266* | shdrs | <- section header table267* |_____________|268* | |269* | .symtab | <- symbol table, if any270* |_____________|271* | |272* | .strtab | <- symbol name string table, if any273* |_____________|274* | |275* | .rel.text | <- relocation info for .o files.276* |_____________|277*/278void279create_elf(struct elfcopy *ecp)280{281struct section *shtab;282GElf_Ehdr ieh;283GElf_Ehdr oeh;284size_t ishnum;285286ecp->flags |= SYMTAB_INTACT;287ecp->flags &= ~SYMTAB_EXIST;288289/* Create EHDR. */290if (gelf_getehdr(ecp->ein, &ieh) == NULL)291errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",292elf_errmsg(-1));293if ((ecp->iec = gelf_getclass(ecp->ein)) == ELFCLASSNONE)294errx(EXIT_FAILURE, "getclass() failed: %s",295elf_errmsg(-1));296297if (ecp->oec == ELFCLASSNONE)298ecp->oec = ecp->iec;299if (ecp->oed == ELFDATANONE)300ecp->oed = ieh.e_ident[EI_DATA];301302if (gelf_newehdr(ecp->eout, ecp->oec) == NULL)303errx(EXIT_FAILURE, "gelf_newehdr failed: %s",304elf_errmsg(-1));305if (gelf_getehdr(ecp->eout, &oeh) == NULL)306errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",307elf_errmsg(-1));308309memcpy(oeh.e_ident, ieh.e_ident, sizeof(ieh.e_ident));310oeh.e_ident[EI_CLASS] = ecp->oec;311oeh.e_ident[EI_DATA] = ecp->oed;312if (ecp->abi != -1)313oeh.e_ident[EI_OSABI] = ecp->abi;314oeh.e_flags = ieh.e_flags;315oeh.e_machine = ieh.e_machine;316oeh.e_type = ieh.e_type;317oeh.e_entry = ieh.e_entry;318oeh.e_version = ieh.e_version;319320ecp->flags &= ~(EXECUTABLE | DYNAMIC | RELOCATABLE);321if (ieh.e_type == ET_EXEC)322ecp->flags |= EXECUTABLE;323else if (ieh.e_type == ET_DYN)324ecp->flags |= DYNAMIC;325else if (ieh.e_type == ET_REL)326ecp->flags |= RELOCATABLE;327else328errx(EXIT_FAILURE, "unsupported e_type");329330if (!elf_getshnum(ecp->ein, &ishnum))331errx(EXIT_FAILURE, "elf_getshnum failed: %s",332elf_errmsg(-1));333if (ishnum > 0 && (ecp->secndx = calloc(ishnum,334sizeof(*ecp->secndx))) == NULL)335err(EXIT_FAILURE, "calloc failed");336337/* Read input object program header. */338setup_phdr(ecp);339340/*341* Scan of input sections: we iterate through sections from input342* object, skip sections need to be stripped, allot Elf_Scn and343* create internal section structure for sections we want.344* (i.e., determine output sections)345*/346create_scn(ecp);347348/* Apply section address changes, if any. */349adjust_addr(ecp);350351/*352* Determine if the symbol table needs to be changed based on353* command line options.354*/355if (ecp->strip == STRIP_DEBUG ||356ecp->strip == STRIP_UNNEEDED ||357ecp->flags & WEAKEN_ALL ||358ecp->flags & LOCALIZE_HIDDEN ||359ecp->flags & DISCARD_LOCAL ||360ecp->flags & DISCARD_LLABEL ||361ecp->prefix_sym != NULL ||362!STAILQ_EMPTY(&ecp->v_symop))363ecp->flags &= ~SYMTAB_INTACT;364365/*366* Create symbol table. Symbols are filtered or stripped according to367* command line args specified by user, and later updated for the new368* layout of sections in the output object.369*/370if ((ecp->flags & SYMTAB_EXIST) != 0)371create_symtab(ecp);372373/*374* Write the underlying ehdr. Note that it should be called375* before elf_setshstrndx() since it will overwrite e->e_shstrndx.376*/377if (gelf_update_ehdr(ecp->eout, &oeh) == 0)378errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",379elf_errmsg(-1));380381/*382* First processing of output sections: at this stage we copy the383* content of each section from input to output object. Section384* content will be modified and printed (mcs) if need. Also content of385* relocation section probably will be filtered and updated according386* to symbol table changes.387*/388copy_content(ecp);389390/*391* Second processing of output sections: Update section headers.392* At this stage we set name string index, update st_link and st_info393* for output sections.394*/395update_shdr(ecp, 1);396397/* Renew oeh to get the updated e_shstrndx. */398if (gelf_getehdr(ecp->eout, &oeh) == NULL)399errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",400elf_errmsg(-1));401402/*403* Insert SHDR table into the internal section list as a "pseudo"404* section, so later it will get sorted and resynced just as "normal"405* sections.406*407* Under FreeBSD, Binutils objcopy always put the section header408* at the end of all the sections. We want to do the same here.409*410* However, note that the behaviour is still different with Binutils:411* elfcopy checks the FreeBSD OSABI tag to tell whether it needs to412* move the section headers, while Binutils is probably configured413* this way when it's compiled on FreeBSD.414*/415if (oeh.e_ident[EI_OSABI] == ELFOSABI_FREEBSD)416shtab = insert_shtab(ecp, 1);417else418shtab = insert_shtab(ecp, 0);419420/*421* Resync section offsets in the output object. This is needed422* because probably sections are modified or new sections are added,423* as a result overlap/gap might appears.424*/425resync_sections(ecp);426427/* Store SHDR offset in EHDR. */428oeh.e_shoff = shtab->off;429430/* Put program header table immediately after the Elf header. */431if (ecp->ophnum > 0) {432oeh.e_phoff = gelf_fsize(ecp->eout, ELF_T_EHDR, 1, EV_CURRENT);433if (oeh.e_phoff == 0)434errx(EXIT_FAILURE, "gelf_fsize() failed: %s",435elf_errmsg(-1));436}437438/*439* Update ELF object entry point if requested.440*/441if (ecp->change_addr != 0)442oeh.e_entry += ecp->change_addr;443if (ecp->flags & SET_START)444oeh.e_entry = ecp->set_start;445if (ecp->change_start != 0)446oeh.e_entry += ecp->change_start;447448/*449* Update ehdr again before we call elf_update(), since we450* modified e_shoff and e_phoff.451*/452if (gelf_update_ehdr(ecp->eout, &oeh) == 0)453errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",454elf_errmsg(-1));455456if (ecp->ophnum > 0)457copy_phdr(ecp);458459/* Write out the output elf object. */460if (elf_update(ecp->eout, ELF_C_WRITE) < 0)461errx(EXIT_FAILURE, "elf_update() failed: %s",462elf_errmsg(-1));463464/* Release allocated resource. */465free_elf(ecp);466}467468void469free_elf(struct elfcopy *ecp)470{471struct segment *seg, *seg_temp;472struct section *sec, *sec_temp;473474/* Free internal segment list. */475if (!STAILQ_EMPTY(&ecp->v_seg)) {476STAILQ_FOREACH_SAFE(seg, &ecp->v_seg, seg_list, seg_temp) {477STAILQ_REMOVE(&ecp->v_seg, seg, segment, seg_list);478free(seg);479}480}481482/* Free symbol table buffers. */483free_symtab(ecp);484485/* Free section name string table. */486elftc_string_table_destroy(ecp->shstrtab->strtab);487488/* Free internal section list. */489if (!TAILQ_EMPTY(&ecp->v_sec)) {490TAILQ_FOREACH_SAFE(sec, &ecp->v_sec, sec_list, sec_temp) {491TAILQ_REMOVE(&ecp->v_sec, sec, sec_list);492if (sec->buf != NULL)493free(sec->buf);494if (sec->newname != NULL)495free(sec->newname);496if (sec->pad != NULL)497free(sec->pad);498free(sec);499}500}501502ecp->symtab = NULL;503ecp->strtab = NULL;504ecp->shstrtab = NULL;505506if (ecp->secndx != NULL) {507free(ecp->secndx);508ecp->secndx = NULL;509}510}511512/*513* Remove a temporary file, without freeing its filename.514*515* Safe to pass NULL, will just ignore it.516*/517int518cleanup_tempfile(char *fn)519{520int errno_save, retval;521522if (fn == NULL)523return 0;524errno_save = errno;525if ((retval = unlink(fn)) < 0) {526warn("unlink tempfile %s failed", fn);527errno = errno_save;528return retval;529}530return 0;531}532533/* Create a temporary file. */534void535create_tempfile(const char *src, char **fn, int *fd)536{537static const char _TEMPDIR[] = "/tmp/";538static const char _TEMPFILE[] = "ecp.XXXXXXXX";539const char *tmpdir;540char *tmpf;541size_t tlen, slen, plen;542543if (fn == NULL || fd == NULL)544return;545for (;;) {546if (src == NULL) {547/* Respect TMPDIR environment variable. */548tmpdir = getenv("TMPDIR");549if (tmpdir == NULL || *tmpdir == '\0')550tmpdir = _TEMPDIR;551tlen = strlen(tmpdir);552slen = tmpdir[tlen - 1] == '/' ? 0 : 1;553} else {554/* Create temporary file relative to source file. */555if ((tmpdir = strrchr(src, '/')) == NULL) {556/* No path, only use a template filename. */557tlen = 0;558} else {559/* Append the template after the slash. */560tlen = ++tmpdir - src;561tmpdir = src;562}563slen = 0;564}565plen = strlen(_TEMPFILE) + 1;566tmpf = malloc(tlen + slen + plen);567if (tmpf == NULL)568err(EXIT_FAILURE, "malloc failed");569if (tlen > 0)570memcpy(tmpf, tmpdir, tlen);571if (slen > 0)572tmpf[tlen] = '/';573/* Copy template filename including NUL terminator. */574memcpy(tmpf + tlen + slen, _TEMPFILE, plen);575if ((*fd = mkstemp(tmpf)) != -1)576break;577if (errno != EACCES || src == NULL)578err(EXIT_FAILURE, "mkstemp %s failed", tmpf);579/* Permission denied, try again using TMPDIR or /tmp. */580free(tmpf);581src = NULL;582}583if (fchmod(*fd, 0644) == -1)584err(EXIT_FAILURE, "fchmod %s failed", tmpf);585*fn = tmpf;586}587588/*589* Copy temporary file with path src and file descriptor infd to path dst.590* If in_place is set act as if editing the file in place, avoiding rename()591* to preserve hard and symbolic links. Output file remains open, with file592* descriptor returned in outfd.593*/594static int595copy_from_tempfile(const char *src, const char *dst, int infd, int *outfd,596int in_place)597{598int tmpfd;599600/*601* First, check if we can use rename().602*/603if (in_place == 0) {604if (rename(src, dst) >= 0) {605*outfd = infd;606return (0);607} else if (errno != EXDEV && errno != EACCES)608return (-1);609610/*611* If the rename() failed due to 'src' and 'dst' residing in612* two different file systems, invoke a helper function in613* libelftc to do the copy.614*/615616if (errno != EACCES && unlink(dst) < 0)617return (-1);618}619620if ((tmpfd = open(dst, O_CREAT | O_TRUNC | O_WRONLY, 0755)) < 0)621return (-1);622623if (elftc_copyfile(infd, tmpfd) < 0) {624(void) close(tmpfd);625return (-1);626}627628/*629* Remove the temporary file from the file system630* namespace, and close its file descriptor.631*/632if (unlink(src) < 0) {633(void) close(tmpfd);634return (-1);635}636637(void) close(infd);638639/*640* Return the file descriptor for the destination.641*/642*outfd = tmpfd;643644return (0);645}646647static void648create_file(struct elfcopy *ecp, const char *src, const char *dst)649{650struct stat sb;651char *tempfile, *elftemp;652int efd, ifd, ofd, ofd0, tfd;653int in_place;654655tempfile = NULL;656657if (src == NULL)658errx(EXIT_FAILURE, "internal: src == NULL");659if ((ifd = open(src, O_RDONLY)) == -1)660err(EXIT_FAILURE, "open %s failed", src);661662if (fstat(ifd, &sb) == -1)663err(EXIT_FAILURE, "fstat %s failed", src);664665if (dst == NULL)666create_tempfile(src, &tempfile, &ofd);667else668if ((ofd = open(dst, O_RDWR|O_CREAT, 0755)) == -1)669err(EXIT_FAILURE, "open %s failed", dst);670671#ifndef LIBELF_AR672/* Detect and process ar(1) archive using libarchive. */673if (ac_detect_ar(ifd)) {674ac_create_ar(ecp, ifd, ofd);675goto copy_done;676}677#endif678679if (lseek(ifd, 0, SEEK_SET) < 0) {680cleanup_tempfile(tempfile);681err(EXIT_FAILURE, "lseek failed");682}683684/*685* If input object is not ELF file, convert it to an intermediate686* ELF object before processing.687*/688if (ecp->itf != ETF_ELF) {689/*690* If the output object is not an ELF file, choose an arbitrary691* ELF format for the intermediate file. srec, ihex and binary692* formats are independent of class, endianness and machine693* type so these choices do not affect the output.694*/695if (ecp->otf != ETF_ELF) {696if (ecp->oec == ELFCLASSNONE)697ecp->oec = ELFCLASS64;698if (ecp->oed == ELFDATANONE)699ecp->oed = ELFDATA2LSB;700}701create_tempfile(src, &elftemp, &efd);702if ((ecp->eout = elf_begin(efd, ELF_C_WRITE, NULL)) == NULL) {703cleanup_tempfile(elftemp);704cleanup_tempfile(tempfile);705errx(EXIT_FAILURE, "elf_begin() failed: %s",706elf_errmsg(-1));707}708elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);709if (ecp->itf == ETF_BINARY)710create_elf_from_binary(ecp, ifd, src);711else if (ecp->itf == ETF_IHEX)712create_elf_from_ihex(ecp, ifd);713else if (ecp->itf == ETF_SREC)714create_elf_from_srec(ecp, ifd);715else {716cleanup_tempfile(elftemp);717cleanup_tempfile(tempfile);718errx(EXIT_FAILURE, "Internal: invalid target flavour");719}720elf_end(ecp->eout);721722/* Open intermediate ELF object as new input object. */723close(ifd);724if ((ifd = open(elftemp, O_RDONLY)) == -1) {725cleanup_tempfile(elftemp);726cleanup_tempfile(tempfile);727err(EXIT_FAILURE, "open %s failed", src);728}729close(efd);730if (cleanup_tempfile(elftemp) < 0) {731cleanup_tempfile(tempfile);732err(EXIT_FAILURE, "unlink %s failed", elftemp);733}734free(elftemp);735elftemp = NULL;736}737738if ((ecp->ein = elf_begin(ifd, ELF_C_READ, NULL)) == NULL) {739cleanup_tempfile(tempfile);740if (fstat(ifd, &sb) == 0 && sb.st_size == 0)741errx(EXIT_FAILURE, "file format not recognized");742errx(EXIT_FAILURE, "elf_begin() failed: %s",743elf_errmsg(-1));744}745746switch (elf_kind(ecp->ein)) {747case ELF_K_NONE:748cleanup_tempfile(tempfile);749errx(EXIT_FAILURE, "file format not recognized");750case ELF_K_ELF:751if ((ecp->eout = elf_begin(ofd, ELF_C_WRITE, NULL)) == NULL) {752cleanup_tempfile(tempfile);753errx(EXIT_FAILURE, "elf_begin() failed: %s",754elf_errmsg(-1));755}756757/* elfcopy(1) manage ELF layout by itself. */758elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);759760/*761* Create output ELF object.762*/763create_elf(ecp);764elf_end(ecp->eout);765766/*767* Convert the output ELF object to binary/srec/ihex if need.768*/769if (ecp->otf != ETF_ELF) {770/*771* Create (another) tempfile for binary/srec/ihex772* output object.773*/774if (cleanup_tempfile(tempfile) < 0)775errx(EXIT_FAILURE, "unlink %s failed",776tempfile);777free(tempfile);778create_tempfile(src, &tempfile, &ofd0);779780781/*782* Rewind the file descriptor being processed.783*/784if (lseek(ofd, 0, SEEK_SET) < 0) {785cleanup_tempfile(tempfile);786err(EXIT_FAILURE,787"lseek failed for the output object");788}789790/*791* Call flavour-specific conversion routine.792*/793switch (ecp->otf) {794case ETF_BINARY:795create_binary(ofd, ofd0);796break;797case ETF_IHEX:798create_ihex(ofd, ofd0);799break;800case ETF_SREC:801create_srec(ecp, ofd, ofd0,802dst != NULL ? dst : src);803break;804case ETF_PE:805case ETF_EFI:806#if WITH_PE807create_pe(ecp, ofd, ofd0);808#else809cleanup_tempfile(tempfile);810errx(EXIT_FAILURE, "PE/EFI support not enabled"811" at compile time");812#endif813break;814default:815cleanup_tempfile(tempfile);816errx(EXIT_FAILURE, "Internal: unsupported"817" output flavour %d", ecp->oec);818}819820close(ofd);821ofd = ofd0;822}823824break;825826case ELF_K_AR:827/* XXX: Not yet supported. */828break;829default:830cleanup_tempfile(tempfile);831errx(EXIT_FAILURE, "file format not supported");832}833834elf_end(ecp->ein);835836#ifndef LIBELF_AR837copy_done:838#endif839840if (tempfile != NULL) {841in_place = 0;842if (dst == NULL) {843dst = src;844if (lstat(dst, &sb) != -1 &&845(sb.st_nlink > 1 || S_ISLNK(sb.st_mode)))846in_place = 1;847}848849if (copy_from_tempfile(tempfile, dst, ofd,850&tfd, in_place) < 0) {851cleanup_tempfile(tempfile);852err(EXIT_FAILURE, "creation of %s failed", dst);853}854855/* 'tempfile' has been removed by copy_from_tempfile(). */856free(tempfile);857tempfile = NULL;858859ofd = tfd;860}861862if (strcmp(dst, "/dev/null") && fchmod(ofd, sb.st_mode) == -1)863err(EXIT_FAILURE, "fchmod %s failed", dst);864865if ((ecp->flags & PRESERVE_DATE) &&866elftc_set_timestamps(dst, &sb) < 0)867err(EXIT_FAILURE, "setting timestamps failed");868869close(ifd);870close(ofd);871}872873static void874elfcopy_main(struct elfcopy *ecp, int argc, char **argv)875{876struct sec_action *sac;877const char *infile, *outfile;878char *fn, *s;879int opt;880881while ((opt = getopt_long(argc, argv, "dB:gG:I:j:K:L:N:O:pR:s:SwW:xXV",882elfcopy_longopts, NULL)) != -1) {883switch(opt) {884case 'B':885/* ignored */886break;887case 'R':888sac = lookup_sec_act(ecp, optarg, 1);889if (sac->copy != 0)890errx(EXIT_FAILURE,891"both copy and remove specified");892sac->remove = 1;893ecp->flags |= SEC_REMOVE;894break;895case 'S':896ecp->strip = STRIP_ALL;897break;898case 'g':899ecp->strip = STRIP_DEBUG;900break;901case 'G':902ecp->flags |= KEEP_GLOBAL;903add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEPG);904break;905case 'I':906case 's':907set_input_target(ecp, optarg);908break;909case 'j':910sac = lookup_sec_act(ecp, optarg, 1);911if (sac->remove != 0)912errx(EXIT_FAILURE,913"both copy and remove specified");914sac->copy = 1;915ecp->flags |= SEC_COPY;916break;917case 'K':918add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);919break;920case 'L':921add_to_symop_list(ecp, optarg, NULL, SYMOP_LOCALIZE);922break;923case 'N':924add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);925break;926case 'O':927set_output_target(ecp, optarg);928break;929case 'p':930ecp->flags |= PRESERVE_DATE;931break;932case 'V':933print_version();934break;935case 'w':936ecp->flags |= WILDCARD;937break;938case 'W':939add_to_symop_list(ecp, optarg, NULL, SYMOP_WEAKEN);940break;941case 'x':942ecp->flags |= DISCARD_LOCAL;943break;944case 'X':945ecp->flags |= DISCARD_LLABEL;946break;947case ECP_ADD_GNU_DEBUGLINK:948ecp->debuglink = optarg;949break;950case ECP_ADD_SECTION:951add_section(ecp, optarg);952break;953case ECP_CHANGE_ADDR:954ecp->change_addr = (int64_t) strtoll(optarg, NULL, 0);955break;956case ECP_CHANGE_SEC_ADDR:957parse_sec_address_op(ecp, opt, "--change-section-addr",958optarg);959break;960case ECP_CHANGE_SEC_LMA:961parse_sec_address_op(ecp, opt, "--change-section-lma",962optarg);963break;964case ECP_CHANGE_SEC_VMA:965parse_sec_address_op(ecp, opt, "--change-section-vma",966optarg);967break;968case ECP_CHANGE_START:969ecp->change_start = (int64_t) strtoll(optarg, NULL, 0);970break;971case ECP_CHANGE_WARN:972/* default */973break;974case ECP_GAP_FILL:975ecp->fill = (uint8_t) strtoul(optarg, NULL, 0);976ecp->flags |= GAP_FILL;977break;978case ECP_GLOBALIZE_SYMBOL:979add_to_symop_list(ecp, optarg, NULL, SYMOP_GLOBALIZE);980break;981case ECP_GLOBALIZE_SYMBOLS:982parse_symlist_file(ecp, optarg, SYMOP_GLOBALIZE);983break;984case ECP_KEEP_SYMBOLS:985parse_symlist_file(ecp, optarg, SYMOP_KEEP);986break;987case ECP_KEEP_GLOBAL_SYMBOLS:988parse_symlist_file(ecp, optarg, SYMOP_KEEPG);989break;990case ECP_LOCALIZE_HIDDEN:991ecp->flags |= LOCALIZE_HIDDEN;992break;993case ECP_LOCALIZE_SYMBOLS:994parse_symlist_file(ecp, optarg, SYMOP_LOCALIZE);995break;996case ECP_NO_CHANGE_WARN:997ecp->flags |= NO_CHANGE_WARN;998break;999case ECP_ONLY_DEBUG:1000ecp->strip = STRIP_NONDEBUG;1001break;1002case ECP_ONLY_DWO:1003ecp->strip = STRIP_NONDWO;1004break;1005case ECP_PAD_TO:1006ecp->pad_to = (uint64_t) strtoull(optarg, NULL, 0);1007break;1008case ECP_PREFIX_ALLOC:1009ecp->prefix_alloc = optarg;1010break;1011case ECP_PREFIX_SEC:1012ecp->prefix_sec = optarg;1013break;1014case ECP_PREFIX_SYM:1015ecp->prefix_sym = optarg;1016break;1017case ECP_REDEF_SYMBOL:1018if ((s = strchr(optarg, '=')) == NULL)1019errx(EXIT_FAILURE,1020"illegal format for --redefine-sym");1021*s++ = '\0';1022add_to_symop_list(ecp, optarg, s, SYMOP_REDEF);1023break;1024case ECP_REDEF_SYMBOLS:1025parse_symlist_file(ecp, optarg, SYMOP_REDEF);1026break;1027case ECP_RENAME_SECTION:1028if ((fn = strchr(optarg, '=')) == NULL)1029errx(EXIT_FAILURE,1030"illegal format for --rename-section");1031*fn++ = '\0';10321033/* Check for optional flags. */1034if ((s = strchr(fn, ',')) != NULL)1035*s++ = '\0';10361037sac = lookup_sec_act(ecp, optarg, 1);1038sac->rename = 1;1039sac->newname = fn;1040if (s != NULL)1041parse_sec_flags(sac, s);1042break;1043case ECP_SET_OSABI:1044set_osabi(ecp, optarg);1045break;1046case ECP_SET_SEC_FLAGS:1047if ((s = strchr(optarg, '=')) == NULL)1048errx(EXIT_FAILURE,1049"illegal format for --set-section-flags");1050*s++ = '\0';1051sac = lookup_sec_act(ecp, optarg, 1);1052parse_sec_flags(sac, s);1053break;1054case ECP_SET_START:1055ecp->flags |= SET_START;1056ecp->set_start = (uint64_t) strtoull(optarg, NULL, 0);1057break;1058case ECP_SREC_FORCE_S3:1059ecp->flags |= SREC_FORCE_S3;1060break;1061case ECP_SREC_LEN:1062ecp->flags |= SREC_FORCE_LEN;1063ecp->srec_len = strtoul(optarg, NULL, 0);1064break;1065case ECP_STRIP_DWO:1066ecp->strip = STRIP_DWO;1067break;1068case ECP_STRIP_SYMBOLS:1069parse_symlist_file(ecp, optarg, SYMOP_STRIP);1070break;1071case ECP_STRIP_UNNEEDED:1072ecp->strip = STRIP_UNNEEDED;1073break;1074case ECP_WEAKEN_ALL:1075ecp->flags |= WEAKEN_ALL;1076break;1077case ECP_WEAKEN_SYMBOLS:1078parse_symlist_file(ecp, optarg, SYMOP_WEAKEN);1079break;1080default:1081elfcopy_usage();1082}1083}10841085argc -= optind;1086argv += optind;10871088if (argc == 0 || argc > 2)1089elfcopy_usage();10901091infile = argv[0];1092outfile = NULL;1093if (argc > 1)1094outfile = argv[1];10951096create_file(ecp, infile, outfile);1097}10981099static void1100mcs_main(struct elfcopy *ecp, int argc, char **argv)1101{1102struct sec_action *sac;1103const char *string;1104int append, delete, compress, name, print;1105int opt, i;11061107append = delete = compress = name = print = 0;1108string = NULL;1109while ((opt = getopt_long(argc, argv, "a:cdhn:pV", mcs_longopts,1110NULL)) != -1) {1111switch(opt) {1112case 'a':1113append = 1;1114string = optarg; /* XXX multiple -a not supported */1115break;1116case 'c':1117compress = 1;1118break;1119case 'd':1120delete = 1;1121break;1122case 'n':1123name = 1;1124(void)lookup_sec_act(ecp, optarg, 1);1125break;1126case 'p':1127print = 1;1128break;1129case 'V':1130print_version();1131break;1132case 'h':1133default:1134mcs_usage();1135}1136}11371138argc -= optind;1139argv += optind;11401141if (argc == 0)1142mcs_usage();11431144/* Must specify one operation at least. */1145if (!append && !compress && !delete && !print)1146mcs_usage();11471148/*1149* If we are going to delete, ignore other operations. This is1150* different from the Solaris implementation, which can print1151* and delete a section at the same time, for example. Also, this1152* implementation do not respect the order between operations that1153* user specified, i.e., "mcs -pc a.out" equals to "mcs -cp a.out".1154*/1155if (delete) {1156append = compress = print = 0;1157ecp->flags |= SEC_REMOVE;1158}1159if (append)1160ecp->flags |= SEC_APPEND;1161if (compress)1162ecp->flags |= SEC_COMPRESS;1163if (print)1164ecp->flags |= SEC_PRINT;11651166/* .comment is the default section to operate on. */1167if (!name)1168(void)lookup_sec_act(ecp, ".comment", 1);11691170STAILQ_FOREACH(sac, &ecp->v_sac, sac_list) {1171sac->append = append;1172sac->compress = compress;1173sac->print = print;1174sac->remove = delete;1175sac->string = string;1176}11771178for (i = 0; i < argc; i++) {1179/* If only -p is specified, output to /dev/null */1180if (print && !append && !compress && !delete)1181create_file(ecp, argv[i], "/dev/null");1182else1183create_file(ecp, argv[i], NULL);1184}1185}11861187static void1188strip_main(struct elfcopy *ecp, int argc, char **argv)1189{1190struct sec_action *sac;1191const char *outfile;1192int opt;1193int i;11941195outfile = NULL;1196while ((opt = getopt_long(argc, argv, "hI:K:N:o:O:pR:sSdgVxXw",1197strip_longopts, NULL)) != -1) {1198switch(opt) {1199case 'R':1200sac = lookup_sec_act(ecp, optarg, 1);1201sac->remove = 1;1202ecp->flags |= SEC_REMOVE;1203break;1204case 's':1205ecp->strip = STRIP_ALL;1206break;1207case 'S':1208case 'g':1209case 'd':1210ecp->strip = STRIP_DEBUG;1211break;1212case 'I':1213/* ignored */1214break;1215case 'K':1216add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);1217break;1218case 'N':1219add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);1220break;1221case 'o':1222outfile = optarg;1223break;1224case 'O':1225set_output_target(ecp, optarg);1226break;1227case 'p':1228ecp->flags |= PRESERVE_DATE;1229break;1230case 'V':1231print_version();1232break;1233case 'w':1234ecp->flags |= WILDCARD;1235break;1236case 'x':1237ecp->flags |= DISCARD_LOCAL;1238break;1239case 'X':1240ecp->flags |= DISCARD_LLABEL;1241break;1242case ECP_ONLY_DEBUG:1243ecp->strip = STRIP_NONDEBUG;1244break;1245case ECP_STRIP_UNNEEDED:1246ecp->strip = STRIP_UNNEEDED;1247break;1248case 'h':1249default:1250strip_usage();1251}1252}12531254argc -= optind;1255argv += optind;12561257if (ecp->strip == 0 &&1258((ecp->flags & DISCARD_LOCAL) == 0) &&1259((ecp->flags & DISCARD_LLABEL) == 0) &&1260lookup_symop_list(ecp, NULL, SYMOP_STRIP) == NULL)1261ecp->strip = STRIP_ALL;1262if (argc == 0)1263strip_usage();1264/*1265* Only accept a single input file if an output file had been1266* specified.1267*/1268if (outfile != NULL && argc != 1)1269strip_usage();12701271for (i = 0; i < argc; i++)1272create_file(ecp, argv[i], outfile);1273}12741275static void1276parse_sec_flags(struct sec_action *sac, char *s)1277{1278const char *flag;1279int found, i;12801281for (flag = strtok(s, ","); flag; flag = strtok(NULL, ",")) {1282found = 0;1283for (i = 0; sec_flags[i].name != NULL; i++)1284if (strcasecmp(sec_flags[i].name, flag) == 0) {1285sac->flags |= sec_flags[i].value;1286found = 1;1287break;1288}1289if (!found)1290errx(EXIT_FAILURE, "unrecognized section flag %s",1291flag);1292}1293}12941295static void1296parse_sec_address_op(struct elfcopy *ecp, int optnum, const char *optname,1297char *s)1298{1299struct sec_action *sac;1300const char *name;1301char *v;1302char op;13031304name = v = s;1305do {1306v++;1307} while (*v != '\0' && *v != '=' && *v != '+' && *v != '-');1308if (*v == '\0' || *(v + 1) == '\0')1309errx(EXIT_FAILURE, "invalid format for %s", optname);1310op = *v;1311*v++ = '\0';1312sac = lookup_sec_act(ecp, name, 1);1313switch (op) {1314case '=':1315if (optnum == ECP_CHANGE_SEC_LMA ||1316optnum == ECP_CHANGE_SEC_ADDR) {1317sac->setlma = 1;1318sac->lma = (uint64_t) strtoull(v, NULL, 0);1319}1320if (optnum == ECP_CHANGE_SEC_VMA ||1321optnum == ECP_CHANGE_SEC_ADDR) {1322sac->setvma = 1;1323sac->vma = (uint64_t) strtoull(v, NULL, 0);1324}1325break;1326case '+':1327if (optnum == ECP_CHANGE_SEC_LMA ||1328optnum == ECP_CHANGE_SEC_ADDR)1329sac->lma_adjust = (int64_t) strtoll(v, NULL, 0);1330if (optnum == ECP_CHANGE_SEC_VMA ||1331optnum == ECP_CHANGE_SEC_ADDR)1332sac->vma_adjust = (int64_t) strtoll(v, NULL, 0);1333break;1334case '-':1335if (optnum == ECP_CHANGE_SEC_LMA ||1336optnum == ECP_CHANGE_SEC_ADDR)1337sac->lma_adjust = (int64_t) -strtoll(v, NULL, 0);1338if (optnum == ECP_CHANGE_SEC_VMA ||1339optnum == ECP_CHANGE_SEC_ADDR)1340sac->vma_adjust = (int64_t) -strtoll(v, NULL, 0);1341break;1342default:1343break;1344}1345}13461347static void1348parse_symlist_file(struct elfcopy *ecp, const char *fn, unsigned int op)1349{1350struct symfile *sf;1351struct stat sb;1352FILE *fp;1353char *data, *p, *line, *end, *e, *n;13541355if (stat(fn, &sb) == -1)1356err(EXIT_FAILURE, "stat %s failed", fn);13571358/* Check if we already read and processed this file. */1359STAILQ_FOREACH(sf, &ecp->v_symfile, symfile_list) {1360if (sf->dev == sb.st_dev && sf->ino == sb.st_ino)1361goto process_symfile;1362}13631364if ((fp = fopen(fn, "r")) == NULL)1365err(EXIT_FAILURE, "can not open %s", fn);1366if ((data = malloc(sb.st_size + 1)) == NULL)1367err(EXIT_FAILURE, "malloc failed");1368if (sb.st_size > 0)1369if (fread(data, sb.st_size, 1, fp) != 1)1370err(EXIT_FAILURE, "fread failed");1371fclose(fp);1372data[sb.st_size] = '\0';13731374if ((sf = calloc(1, sizeof(*sf))) == NULL)1375err(EXIT_FAILURE, "malloc failed");1376sf->dev = sb.st_dev;1377sf->ino = sb.st_ino;1378sf->size = sb.st_size + 1;1379sf->data = data;13801381process_symfile:13821383/*1384* Basically what we do here is to convert EOL to '\0', and remove1385* leading and trailing whitespaces for each line.1386*/13871388end = sf->data + sf->size;1389line = NULL;1390for(p = sf->data; p < end; p++) {1391if ((*p == '\t' || *p == ' ') && line == NULL)1392continue;1393if (*p == '\r' || *p == '\n' || *p == '\0') {1394*p = '\0';1395if (line == NULL)1396continue;13971398/* Skip comment. */1399if (*line == '#') {1400line = NULL;1401continue;1402}14031404e = p - 1;1405while(e != line && (*e == '\t' || *e == ' '))1406*e-- = '\0';1407if (op != SYMOP_REDEF)1408add_to_symop_list(ecp, line, NULL, op);1409else {1410if (strlen(line) < 3)1411errx(EXIT_FAILURE,1412"illegal format for"1413" --redefine-sym");1414for(n = line + 1; n < e; n++) {1415if (*n == ' ' || *n == '\t') {1416while(*n == ' ' || *n == '\t')1417*n++ = '\0';1418break;1419}1420}1421if (n >= e)1422errx(EXIT_FAILURE,1423"illegal format for"1424" --redefine-sym");1425add_to_symop_list(ecp, line, n, op);1426}1427line = NULL;1428continue;1429}14301431if (line == NULL)1432line = p;1433}1434}14351436static void1437set_input_target(struct elfcopy *ecp, const char *target_name)1438{1439Elftc_Bfd_Target *tgt;14401441if ((tgt = elftc_bfd_find_target(target_name)) == NULL)1442errx(EXIT_FAILURE, "%s: invalid target name", target_name);1443ecp->itf = elftc_bfd_target_flavor(tgt);1444}14451446static void1447set_output_target(struct elfcopy *ecp, const char *target_name)1448{1449Elftc_Bfd_Target *tgt;14501451if ((tgt = elftc_bfd_find_target(target_name)) == NULL)1452errx(EXIT_FAILURE, "%s: invalid target name", target_name);1453ecp->otf = elftc_bfd_target_flavor(tgt);1454if (ecp->otf == ETF_ELF) {1455ecp->oec = elftc_bfd_target_class(tgt);1456ecp->oed = elftc_bfd_target_byteorder(tgt);1457ecp->oem = elftc_bfd_target_machine(tgt);1458ecp->abi = elftc_bfd_target_osabi(tgt);1459}1460if (ecp->otf == ETF_EFI || ecp->otf == ETF_PE)1461ecp->oem = elftc_bfd_target_machine(tgt);14621463ecp->otgt = target_name;1464}14651466static void1467set_osabi(struct elfcopy *ecp, const char *abi)1468{1469int i, found;14701471found = 0;1472for (i = 0; osabis[i].name != NULL; i++)1473if (strcasecmp(osabis[i].name, abi) == 0) {1474ecp->abi = osabis[i].abi;1475found = 1;1476break;1477}1478if (!found)1479errx(EXIT_FAILURE, "unrecognized OSABI %s", abi);1480}14811482#define ELFCOPY_USAGE_MESSAGE "\1483Usage: %s [options] infile [outfile]\n\1484Transform object files.\n\n\1485Options:\n\1486-d | -g | --strip-debug Remove debugging information from the output.\n\1487-j SECTION | --only-section=SECTION\n\1488Copy only the named section to the output.\n\1489-p | --preserve-dates Preserve access and modification times.\n\1490-w | --wildcard Use shell-style patterns to name symbols.\n\1491-x | --discard-all Do not copy non-globals to the output.\n\1492-I FORMAT | --input-target=FORMAT\n\1493Specify object format for the input file.\n\1494-K SYM | --keep-symbol=SYM Copy symbol SYM to the output.\n\1495-L SYM | --localize-symbol=SYM\n\1496Make symbol SYM local to the output file.\n\1497-N SYM | --strip-symbol=SYM Do not copy symbol SYM to the output.\n\1498-O FORMAT | --output-target=FORMAT\n\1499Specify object format for the output file.\n\1500FORMAT should be a target name understood by\n\1501elftc_bfd_find_target(3).\n\1502-R NAME | --remove-section=NAME\n\1503Remove the named section.\n\1504-S | --strip-all Remove all symbol and relocation information\n\1505from the output.\n\1506-V | --version Print a version identifier and exit.\n\1507-W SYM | --weaken-symbol=SYM Mark symbol SYM as weak in the output.\n\1508-X | --discard-locals Do not copy compiler generated symbols to\n\1509the output.\n\1510--add-section NAME=FILE Add the contents of FILE to the ELF object as\n\1511a new section named NAME.\n\1512--adjust-section-vma SECTION{=,+,-}VAL | \\\n\1513--change-section-address SECTION{=,+,-}VAL\n\1514Set or adjust the VMA and the LMA of the\n\1515named section by VAL.\n\1516--adjust-start=INCR | --change-start=INCR\n\1517Add INCR to the start address for the ELF\n\1518object.\n\1519--adjust-vma=INCR | --change-addresses=INCR\n\1520Increase the VMA and LMA of all sections by\n\1521INCR.\n\1522--adjust-warning | --change-warnings\n\1523Issue warnings for non-existent sections.\n\1524--change-section-lma SECTION{=,+,-}VAL\n\1525Set or adjust the LMA address of the named\n\1526section by VAL.\n\1527--change-section-vma SECTION{=,+,-}VAL\n\1528Set or adjust the VMA address of the named\n\1529section by VAL.\n\1530--gap-fill=VAL Fill the gaps between sections with bytes\n\1531of value VAL.\n\1532--localize-hidden Make all hidden symbols local to the output\n\1533file.\n\1534--no-adjust-warning| --no-change-warnings\n\1535Do not issue warnings for non-existent\n\1536sections.\n\1537--only-keep-debug Copy only debugging information.\n\1538--output-target=FORMAT Use the specified format for the output.\n\1539--pad-to=ADDRESS Pad the output object up to the given address.\n\1540--prefix-alloc-sections=STRING\n\1541Prefix the section names of all the allocated\n\1542sections with STRING.\n\1543--prefix-sections=STRING Prefix the section names of all the sections\n\1544with STRING.\n\1545--prefix-symbols=STRING Prefix the symbol names of all the symbols\n\1546with STRING.\n\1547--rename-section OLDNAME=NEWNAME[,FLAGS]\n\1548Rename and optionally change section flags.\n\1549--set-section-flags SECTION=FLAGS\n\1550Set section flags for the named section.\n\1551Supported flags are: 'alloc', 'code',\n\1552'contents', 'data', 'debug', 'load',\n\1553'noload', 'readonly', 'rom', and 'shared'.\n\1554--set-start=ADDRESS Set the start address of the ELF object.\n\1555--srec-forceS3 Only generate S3 S-Records.\n\1556--srec-len=LEN Set the maximum length of a S-Record line.\n\1557--strip-unneeded Do not copy relocation information.\n"15581559static void1560elfcopy_usage(void)1561{1562(void) fprintf(stderr, ELFCOPY_USAGE_MESSAGE, ELFTC_GETPROGNAME());1563exit(EXIT_FAILURE);1564}15651566#define MCS_USAGE_MESSAGE "\1567Usage: %s [options] file...\n\1568Manipulate the comment section in an ELF object.\n\n\1569Options:\n\1570-a STRING Append 'STRING' to the comment section.\n\1571-c Remove duplicate entries from the comment section.\n\1572-d Delete the comment section.\n\1573-h | --help Print a help message and exit.\n\1574-n NAME Operate on the ELF section with name 'NAME'.\n\1575-p Print the contents of the comment section.\n\1576-V | --version Print a version identifier and exit.\n"15771578static void1579mcs_usage(void)1580{1581(void) fprintf(stderr, MCS_USAGE_MESSAGE, ELFTC_GETPROGNAME());1582exit(EXIT_FAILURE);1583}15841585#define STRIP_USAGE_MESSAGE "\1586Usage: %s [options] file...\n\1587Discard information from ELF objects.\n\n\1588Options:\n\1589-d | -g | -S | --strip-debug Remove debugging symbols.\n\1590-h | --help Print a help message.\n\1591-o FILE | --output-file FILE Write output to FILE.\n\1592--only-keep-debug Keep debugging information only.\n\1593-p | --preserve-dates Preserve access and modification times.\n\1594-s | --strip-all Remove all symbols.\n\1595--strip-unneeded Remove symbols not needed for relocation\n\1596processing.\n\1597-w | --wildcard Use shell-style patterns to name symbols.\n\1598-x | --discard-all Discard all non-global symbols.\n\1599-I TGT| --input-target=TGT (Accepted, but ignored).\n\1600-K SYM | --keep-symbol=SYM Keep symbol 'SYM' in the output.\n\1601-N SYM | --strip-symbol=SYM Remove symbol 'SYM' from the output.\n\1602-O TGT | --output-target=TGT Set the output file format to 'TGT'.\n\1603-R SEC | --remove-section=SEC Remove the section named 'SEC'.\n\1604-V | --version Print a version identifier and exit.\n\1605-X | --discard-locals Remove compiler-generated local symbols.\n"16061607static void1608strip_usage(void)1609{1610(void) fprintf(stderr, STRIP_USAGE_MESSAGE, ELFTC_GETPROGNAME());1611exit(EXIT_FAILURE);1612}16131614static void1615print_version(void)1616{1617(void) printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());1618exit(EXIT_SUCCESS);1619}16201621/*1622* Compare the ending of s with end.1623*/1624static int1625strrcmp(const char *s, const char *end)1626{1627size_t endlen, slen;16281629slen = strlen(s);1630endlen = strlen(end);16311632if (slen >= endlen)1633s += slen - endlen;1634return (strcmp(s, end));1635}16361637int1638main(int argc, char **argv)1639{1640struct elfcopy *ecp;16411642if (elf_version(EV_CURRENT) == EV_NONE)1643errx(EXIT_FAILURE, "ELF library initialization failed: %s",1644elf_errmsg(-1));16451646ecp = calloc(1, sizeof(*ecp));1647if (ecp == NULL)1648err(EXIT_FAILURE, "calloc failed");16491650ecp->itf = ecp->otf = ETF_ELF;1651ecp->iec = ecp->oec = ELFCLASSNONE;1652ecp->oed = ELFDATANONE;1653ecp->abi = -1;1654/* There is always an empty section. */1655ecp->nos = 1;1656ecp->fill = 0;16571658STAILQ_INIT(&ecp->v_seg);1659STAILQ_INIT(&ecp->v_sac);1660STAILQ_INIT(&ecp->v_sadd);1661STAILQ_INIT(&ecp->v_symop);1662STAILQ_INIT(&ecp->v_symfile);1663STAILQ_INIT(&ecp->v_arobj);1664TAILQ_INIT(&ecp->v_sec);16651666if ((ecp->progname = ELFTC_GETPROGNAME()) == NULL)1667ecp->progname = "elfcopy";16681669if (strrcmp(ecp->progname, "strip") == 0)1670strip_main(ecp, argc, argv);1671else if (strrcmp(ecp->progname, "mcs") == 0)1672mcs_main(ecp, argc, argv);1673else {1674if (strrcmp(ecp->progname, "elfcopy") != 0 &&1675strrcmp(ecp->progname, "objcopy") != 0)1676warnx("program mode not known, defaulting to elfcopy");1677elfcopy_main(ecp, argc, argv);1678}16791680free_sec_add(ecp);1681free_sec_act(ecp);1682free(ecp);16831684exit(EXIT_SUCCESS);1685}168616871688