2 * Copyright (c) 2007-2013 Kai Wang
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/param.h>
42 ELFTC_VCSID("$Id: main.c 3757 2019-06-28 01:15:28Z emaste $");
46 ECP_ADD_GNU_DEBUGLINK,
56 ECP_GLOBALIZE_SYMBOLS,
58 ECP_KEEP_GLOBAL_SYMBOLS,
83 static struct option mcs_longopts[] =
85 { "help", no_argument, NULL, 'h' },
86 { "version", no_argument, NULL, 'V' },
90 static struct option strip_longopts[] =
92 {"discard-all", no_argument, NULL, 'x'},
93 {"discard-locals", no_argument, NULL, 'X'},
94 {"help", no_argument, NULL, 'h'},
95 {"input-target", required_argument, NULL, 'I'},
96 {"keep-symbol", required_argument, NULL, 'K'},
97 {"only-keep-debug", no_argument, NULL, ECP_ONLY_DEBUG},
98 {"output-file", required_argument, NULL, 'o'},
99 {"output-target", required_argument, NULL, 'O'},
100 {"preserve-dates", no_argument, NULL, 'p'},
101 {"remove-section", required_argument, NULL, 'R'},
102 {"strip-all", no_argument, NULL, 's'},
103 {"strip-debug", no_argument, NULL, 'S'},
104 {"strip-symbol", required_argument, NULL, 'N'},
105 {"strip-unneeded", no_argument, NULL, ECP_STRIP_UNNEEDED},
106 {"version", no_argument, NULL, 'V'},
107 {"wildcard", no_argument, NULL, 'w'},
111 static struct option elfcopy_longopts[] =
113 {"add-gnu-debuglink", required_argument, NULL, ECP_ADD_GNU_DEBUGLINK},
114 {"add-section", required_argument, NULL, ECP_ADD_SECTION},
115 {"adjust-section-vma", required_argument, NULL, ECP_CHANGE_SEC_ADDR},
116 {"adjust-vma", required_argument, NULL, ECP_CHANGE_ADDR},
117 {"adjust-start", required_argument, NULL, ECP_CHANGE_START},
118 {"adjust-warnings", no_argument, NULL, ECP_CHANGE_WARN},
119 {"binary-architecture", required_argument, NULL, 'B'},
120 {"change-addresses", required_argument, NULL, ECP_CHANGE_ADDR},
121 {"change-section-address", required_argument, NULL,
122 ECP_CHANGE_SEC_ADDR},
123 {"change-section-lma", required_argument, NULL, ECP_CHANGE_SEC_LMA},
124 {"change-section-vma", required_argument, NULL, ECP_CHANGE_SEC_VMA},
125 {"change-start", required_argument, NULL, ECP_CHANGE_START},
126 {"change-warnings", no_argument, NULL, ECP_CHANGE_WARN},
127 {"discard-all", no_argument, NULL, 'x'},
128 {"discard-locals", no_argument, NULL, 'X'},
129 {"extract-dwo", no_argument, NULL, ECP_ONLY_DWO},
130 {"gap-fill", required_argument, NULL, ECP_GAP_FILL},
131 {"globalize-symbol", required_argument, NULL, ECP_GLOBALIZE_SYMBOL},
132 {"globalize-symbols", required_argument, NULL, ECP_GLOBALIZE_SYMBOLS},
133 {"help", no_argument, NULL, 'h'},
134 {"input-target", required_argument, NULL, 'I'},
135 {"keep-symbol", required_argument, NULL, 'K'},
136 {"keep-symbols", required_argument, NULL, ECP_KEEP_SYMBOLS},
137 {"keep-global-symbol", required_argument, NULL, 'G'},
138 {"keep-global-symbols", required_argument, NULL,
139 ECP_KEEP_GLOBAL_SYMBOLS},
140 {"localize-hidden", no_argument, NULL, ECP_LOCALIZE_HIDDEN},
141 {"localize-symbol", required_argument, NULL, 'L'},
142 {"localize-symbols", required_argument, NULL, ECP_LOCALIZE_SYMBOLS},
143 {"no-adjust-warnings", no_argument, NULL, ECP_NO_CHANGE_WARN},
144 {"no-change-warnings", no_argument, NULL, ECP_NO_CHANGE_WARN},
145 {"only-keep-debug", no_argument, NULL, ECP_ONLY_DEBUG},
146 {"only-section", required_argument, NULL, 'j'},
147 {"osabi", required_argument, NULL, ECP_SET_OSABI},
148 {"output-target", required_argument, NULL, 'O'},
149 {"pad-to", required_argument, NULL, ECP_PAD_TO},
150 {"preserve-dates", no_argument, NULL, 'p'},
151 {"prefix-alloc-sections", required_argument, NULL, ECP_PREFIX_ALLOC},
152 {"prefix-sections", required_argument, NULL, ECP_PREFIX_SEC},
153 {"prefix-symbols", required_argument, NULL, ECP_PREFIX_SYM},
154 {"redefine-sym", required_argument, NULL, ECP_REDEF_SYMBOL},
155 {"redefine-syms", required_argument, NULL, ECP_REDEF_SYMBOLS},
156 {"remove-section", required_argument, NULL, 'R'},
157 {"rename-section", required_argument, NULL, ECP_RENAME_SECTION},
158 {"set-section-flags", required_argument, NULL, ECP_SET_SEC_FLAGS},
159 {"set-start", required_argument, NULL, ECP_SET_START},
160 {"srec-forceS3", no_argument, NULL, ECP_SREC_FORCE_S3},
161 {"srec-len", required_argument, NULL, ECP_SREC_LEN},
162 {"strip-all", no_argument, NULL, 'S'},
163 {"strip-debug", no_argument, 0, 'g'},
164 {"strip-dwo", no_argument, NULL, ECP_STRIP_DWO},
165 {"strip-symbol", required_argument, NULL, 'N'},
166 {"strip-symbols", required_argument, NULL, ECP_STRIP_SYMBOLS},
167 {"strip-unneeded", no_argument, NULL, ECP_STRIP_UNNEEDED},
168 {"version", no_argument, NULL, 'V'},
169 {"weaken", no_argument, NULL, ECP_WEAKEN_ALL},
170 {"weaken-symbol", required_argument, NULL, 'W'},
171 {"weaken-symbols", required_argument, NULL, ECP_WEAKEN_SYMBOLS},
172 {"wildcard", no_argument, NULL, 'w'},
182 {"noload", SF_NOLOAD},
183 {"readonly", SF_READONLY},
188 {"share", SF_SHARED},
189 {"contents", SF_CONTENTS},
197 {"sysv", ELFOSABI_SYSV},
198 {"hpus", ELFOSABI_HPUX},
199 {"netbsd", ELFOSABI_NETBSD},
200 {"linux", ELFOSABI_LINUX},
201 {"hurd", ELFOSABI_HURD},
202 {"86open", ELFOSABI_86OPEN},
203 {"solaris", ELFOSABI_SOLARIS},
204 {"aix", ELFOSABI_AIX},
205 {"irix", ELFOSABI_IRIX},
206 {"freebsd", ELFOSABI_FREEBSD},
207 {"tru64", ELFOSABI_TRU64},
208 {"modesto", ELFOSABI_MODESTO},
209 {"openbsd", ELFOSABI_OPENBSD},
210 {"openvms", ELFOSABI_OPENVMS},
211 {"nsk", ELFOSABI_NSK},
212 {"cloudabi", ELFOSABI_CLOUDABI},
213 {"arm", ELFOSABI_ARM},
214 {"standalone", ELFOSABI_STANDALONE},
218 static int copy_from_tempfile(const char *src, const char *dst,
219 int infd, int *outfd, int in_place);
220 static void create_file(struct elfcopy *ecp, const char *src,
222 static void elfcopy_main(struct elfcopy *ecp, int argc, char **argv);
223 static void elfcopy_usage(void);
224 static void mcs_main(struct elfcopy *ecp, int argc, char **argv);
225 static void mcs_usage(void);
226 static void parse_sec_address_op(struct elfcopy *ecp, int optnum,
227 const char *optname, char *s);
228 static void parse_sec_flags(struct sec_action *sac, char *s);
229 static void parse_symlist_file(struct elfcopy *ecp, const char *fn,
231 static void print_version(void);
232 static void set_input_target(struct elfcopy *ecp, const char *target_name);
233 static void set_osabi(struct elfcopy *ecp, const char *abi);
234 static void set_output_target(struct elfcopy *ecp, const char *target_name);
235 static void strip_main(struct elfcopy *ecp, int argc, char **argv);
236 static void strip_usage(void);
239 * An ELF object usually has a structure described by the
243 * | NULL | <- always a SHT_NULL section
258 * | .comment | <- above(include) this: normal sections
261 * | add sections| <- unloadable sections added by --add-section
264 * | .shstrtab | <- section name string table
267 * | shdrs | <- section header table
270 * | .symtab | <- symbol table, if any
273 * | .strtab | <- symbol name string table, if any
276 * | .rel.text | <- relocation info for .o files.
280 create_elf(struct elfcopy *ecp)
282 struct section *shtab;
287 ecp->flags |= SYMTAB_INTACT;
288 ecp->flags &= ~SYMTAB_EXIST;
291 if (gelf_getehdr(ecp->ein, &ieh) == NULL)
292 errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
294 if ((ecp->iec = gelf_getclass(ecp->ein)) == ELFCLASSNONE)
295 errx(EXIT_FAILURE, "getclass() failed: %s",
298 if (ecp->oec == ELFCLASSNONE)
300 if (ecp->oed == ELFDATANONE)
301 ecp->oed = ieh.e_ident[EI_DATA];
303 if (gelf_newehdr(ecp->eout, ecp->oec) == NULL)
304 errx(EXIT_FAILURE, "gelf_newehdr failed: %s",
306 if (gelf_getehdr(ecp->eout, &oeh) == NULL)
307 errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
310 memcpy(oeh.e_ident, ieh.e_ident, sizeof(ieh.e_ident));
311 oeh.e_ident[EI_CLASS] = ecp->oec;
312 oeh.e_ident[EI_DATA] = ecp->oed;
314 oeh.e_ident[EI_OSABI] = ecp->abi;
315 oeh.e_flags = ieh.e_flags;
316 oeh.e_machine = ieh.e_machine;
317 oeh.e_type = ieh.e_type;
318 oeh.e_entry = ieh.e_entry;
319 oeh.e_version = ieh.e_version;
321 ecp->flags &= ~(EXECUTABLE | DYNAMIC | RELOCATABLE);
322 if (ieh.e_type == ET_EXEC)
323 ecp->flags |= EXECUTABLE;
324 else if (ieh.e_type == ET_DYN)
325 ecp->flags |= DYNAMIC;
326 else if (ieh.e_type == ET_REL)
327 ecp->flags |= RELOCATABLE;
329 errx(EXIT_FAILURE, "unsupported e_type");
331 if (!elf_getshnum(ecp->ein, &ishnum))
332 errx(EXIT_FAILURE, "elf_getshnum failed: %s",
334 if (ishnum > 0 && (ecp->secndx = calloc(ishnum,
335 sizeof(*ecp->secndx))) == NULL)
336 err(EXIT_FAILURE, "calloc failed");
338 /* Read input object program header. */
342 * Scan of input sections: we iterate through sections from input
343 * object, skip sections need to be stripped, allot Elf_Scn and
344 * create internal section structure for sections we want.
345 * (i.e., determine output sections)
349 /* Apply section address changes, if any. */
353 * Determine if the symbol table needs to be changed based on
354 * command line options.
356 if (ecp->strip == STRIP_DEBUG ||
357 ecp->strip == STRIP_UNNEEDED ||
358 ecp->flags & WEAKEN_ALL ||
359 ecp->flags & LOCALIZE_HIDDEN ||
360 ecp->flags & DISCARD_LOCAL ||
361 ecp->flags & DISCARD_LLABEL ||
362 ecp->prefix_sym != NULL ||
363 !STAILQ_EMPTY(&ecp->v_symop))
364 ecp->flags &= ~SYMTAB_INTACT;
367 * Create symbol table. Symbols are filtered or stripped according to
368 * command line args specified by user, and later updated for the new
369 * layout of sections in the output object.
371 if ((ecp->flags & SYMTAB_EXIST) != 0)
375 * Write the underlying ehdr. Note that it should be called
376 * before elf_setshstrndx() since it will overwrite e->e_shstrndx.
378 if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
379 errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
383 * First processing of output sections: at this stage we copy the
384 * content of each section from input to output object. Section
385 * content will be modified and printed (mcs) if need. Also content of
386 * relocation section probably will be filtered and updated according
387 * to symbol table changes.
392 * Second processing of output sections: Update section headers.
393 * At this stage we set name string index, update st_link and st_info
394 * for output sections.
398 /* Renew oeh to get the updated e_shstrndx. */
399 if (gelf_getehdr(ecp->eout, &oeh) == NULL)
400 errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
404 * Insert SHDR table into the internal section list as a "pseudo"
405 * section, so later it will get sorted and resynced just as "normal"
408 * Under FreeBSD, Binutils objcopy always put the section header
409 * at the end of all the sections. We want to do the same here.
411 * However, note that the behaviour is still different with Binutils:
412 * elfcopy checks the FreeBSD OSABI tag to tell whether it needs to
413 * move the section headers, while Binutils is probably configured
414 * this way when it's compiled on FreeBSD.
416 if (oeh.e_ident[EI_OSABI] == ELFOSABI_FREEBSD)
417 shtab = insert_shtab(ecp, 1);
419 shtab = insert_shtab(ecp, 0);
422 * Resync section offsets in the output object. This is needed
423 * because probably sections are modified or new sections are added,
424 * as a result overlap/gap might appears.
426 resync_sections(ecp);
428 /* Store SHDR offset in EHDR. */
429 oeh.e_shoff = shtab->off;
431 /* Put program header table immediately after the Elf header. */
432 if (ecp->ophnum > 0) {
433 oeh.e_phoff = gelf_fsize(ecp->eout, ELF_T_EHDR, 1, EV_CURRENT);
434 if (oeh.e_phoff == 0)
435 errx(EXIT_FAILURE, "gelf_fsize() failed: %s",
440 * Update ELF object entry point if requested.
442 if (ecp->change_addr != 0)
443 oeh.e_entry += ecp->change_addr;
444 if (ecp->flags & SET_START)
445 oeh.e_entry = ecp->set_start;
446 if (ecp->change_start != 0)
447 oeh.e_entry += ecp->change_start;
450 * Update ehdr again before we call elf_update(), since we
451 * modified e_shoff and e_phoff.
453 if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
454 errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
460 /* Write out the output elf object. */
461 if (elf_update(ecp->eout, ELF_C_WRITE) < 0)
462 errx(EXIT_FAILURE, "elf_update() failed: %s",
465 /* Release allocated resource. */
470 free_elf(struct elfcopy *ecp)
472 struct segment *seg, *seg_temp;
473 struct section *sec, *sec_temp;
475 /* Free internal segment list. */
476 if (!STAILQ_EMPTY(&ecp->v_seg)) {
477 STAILQ_FOREACH_SAFE(seg, &ecp->v_seg, seg_list, seg_temp) {
478 STAILQ_REMOVE(&ecp->v_seg, seg, segment, seg_list);
483 /* Free symbol table buffers. */
486 /* Free section name string table. */
487 elftc_string_table_destroy(ecp->shstrtab->strtab);
489 /* Free internal section list. */
490 if (!TAILQ_EMPTY(&ecp->v_sec)) {
491 TAILQ_FOREACH_SAFE(sec, &ecp->v_sec, sec_list, sec_temp) {
492 TAILQ_REMOVE(&ecp->v_sec, sec, sec_list);
493 if (sec->buf != NULL)
495 if (sec->newname != NULL)
497 if (sec->pad != NULL)
505 ecp->shstrtab = NULL;
507 if (ecp->secndx != NULL) {
513 /* Create a temporary file. */
515 create_tempfile(char **fn, int *fd)
521 #define _TEMPFILE "ecp.XXXXXXXX"
522 #define _TEMPFILEPATH "/tmp/ecp.XXXXXXXX"
524 if (fn == NULL || fd == NULL)
526 /* Repect TMPDIR environment variable. */
527 tmpdir = getenv("TMPDIR");
528 if (tmpdir != NULL && *tmpdir != '\0') {
529 tlen = strlen(tmpdir);
530 plen = strlen(_TEMPFILE);
531 tmpf = malloc(tlen + plen + 2);
533 err(EXIT_FAILURE, "malloc failed");
534 strncpy(tmpf, tmpdir, tlen);
535 cp = &tmpf[tlen - 1];
538 strncpy(cp, _TEMPFILE, plen);
541 tmpf = strdup(_TEMPFILEPATH);
543 err(EXIT_FAILURE, "strdup failed");
545 if ((*fd = mkstemp(tmpf)) == -1)
546 err(EXIT_FAILURE, "mkstemp %s failed", tmpf);
547 if (fchmod(*fd, 0644) == -1)
548 err(EXIT_FAILURE, "fchmod %s failed", tmpf);
556 * Copy temporary file with path src and file descriptor infd to path dst.
557 * If in_place is set act as if editing the file in place, avoiding rename()
558 * to preserve hard and symbolic links. Output file remains open, with file
559 * descriptor returned in outfd.
562 copy_from_tempfile(const char *src, const char *dst, int infd, int *outfd,
568 * First, check if we can use rename().
571 if (rename(src, dst) >= 0) {
574 } else if (errno != EXDEV)
578 * If the rename() failed due to 'src' and 'dst' residing in
579 * two different file systems, invoke a helper function in
580 * libelftc to do the copy.
587 if ((tmpfd = open(dst, O_CREAT | O_TRUNC | O_WRONLY, 0755)) < 0)
590 if (elftc_copyfile(infd, tmpfd) < 0) {
596 * Remove the temporary file from the file system
597 * namespace, and close its file descriptor.
599 if (unlink(src) < 0) {
607 * Return the file descriptor for the destination.
615 create_file(struct elfcopy *ecp, const char *src, const char *dst)
618 char *tempfile, *elftemp;
619 int efd, ifd, ofd, ofd0, tfd;
625 errx(EXIT_FAILURE, "internal: src == NULL");
626 if ((ifd = open(src, O_RDONLY)) == -1)
627 err(EXIT_FAILURE, "open %s failed", src);
629 if (fstat(ifd, &sb) == -1)
630 err(EXIT_FAILURE, "fstat %s failed", src);
633 create_tempfile(&tempfile, &ofd);
635 if ((ofd = open(dst, O_RDWR|O_CREAT, 0755)) == -1)
636 err(EXIT_FAILURE, "open %s failed", dst);
639 /* Detect and process ar(1) archive using libarchive. */
640 if (ac_detect_ar(ifd)) {
641 ac_create_ar(ecp, ifd, ofd);
646 if (lseek(ifd, 0, SEEK_SET) < 0)
647 err(EXIT_FAILURE, "lseek failed");
650 * If input object is not ELF file, convert it to an intermediate
651 * ELF object before processing.
653 if (ecp->itf != ETF_ELF) {
655 * If the output object is not an ELF file, choose an arbitrary
656 * ELF format for the intermediate file. srec, ihex and binary
657 * formats are independent of class, endianness and machine
658 * type so these choices do not affect the output.
660 if (ecp->otf != ETF_ELF) {
661 if (ecp->oec == ELFCLASSNONE)
662 ecp->oec = ELFCLASS64;
663 if (ecp->oed == ELFDATANONE)
664 ecp->oed = ELFDATA2LSB;
666 create_tempfile(&elftemp, &efd);
667 if ((ecp->eout = elf_begin(efd, ELF_C_WRITE, NULL)) == NULL)
668 errx(EXIT_FAILURE, "elf_begin() failed: %s",
670 elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);
671 if (ecp->itf == ETF_BINARY)
672 create_elf_from_binary(ecp, ifd, src);
673 else if (ecp->itf == ETF_IHEX)
674 create_elf_from_ihex(ecp, ifd);
675 else if (ecp->itf == ETF_SREC)
676 create_elf_from_srec(ecp, ifd);
678 errx(EXIT_FAILURE, "Internal: invalid target flavour");
681 /* Open intermediate ELF object as new input object. */
683 if ((ifd = open(elftemp, O_RDONLY)) == -1)
684 err(EXIT_FAILURE, "open %s failed", src);
686 if (unlink(elftemp) < 0)
687 err(EXIT_FAILURE, "unlink %s failed", elftemp);
691 if ((ecp->ein = elf_begin(ifd, ELF_C_READ, NULL)) == NULL)
692 errx(EXIT_FAILURE, "elf_begin() failed: %s",
695 switch (elf_kind(ecp->ein)) {
697 errx(EXIT_FAILURE, "file format not recognized");
699 if ((ecp->eout = elf_begin(ofd, ELF_C_WRITE, NULL)) == NULL)
700 errx(EXIT_FAILURE, "elf_begin() failed: %s",
703 /* elfcopy(1) manage ELF layout by itself. */
704 elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);
707 * Create output ELF object.
713 * Convert the output ELF object to binary/srec/ihex if need.
715 if (ecp->otf != ETF_ELF) {
717 * Create (another) tempfile for binary/srec/ihex
720 if (tempfile != NULL) {
721 if (unlink(tempfile) < 0)
722 err(EXIT_FAILURE, "unlink %s failed",
726 create_tempfile(&tempfile, &ofd0);
730 * Rewind the file descriptor being processed.
732 if (lseek(ofd, 0, SEEK_SET) < 0)
734 "lseek failed for the output object");
737 * Call flavour-specific conversion routine.
741 create_binary(ofd, ofd0);
744 create_ihex(ofd, ofd0);
747 create_srec(ecp, ofd, ofd0,
748 dst != NULL ? dst : src);
753 create_pe(ecp, ofd, ofd0);
755 errx(EXIT_FAILURE, "PE/EFI support not enabled"
760 errx(EXIT_FAILURE, "Internal: unsupported"
761 " output flavour %d", ecp->oec);
771 /* XXX: Not yet supported. */
774 errx(EXIT_FAILURE, "file format not supported");
783 if (tempfile != NULL) {
787 if (lstat(dst, &sb) != -1 &&
788 (sb.st_nlink > 1 || S_ISLNK(sb.st_mode)))
792 if (copy_from_tempfile(tempfile, dst, ofd, &tfd, in_place) < 0)
793 err(EXIT_FAILURE, "creation of %s failed", dst);
801 if (strcmp(dst, "/dev/null") && fchmod(ofd, sb.st_mode) == -1)
802 err(EXIT_FAILURE, "fchmod %s failed", dst);
804 if ((ecp->flags & PRESERVE_DATE) &&
805 elftc_set_timestamps(dst, &sb) < 0)
806 err(EXIT_FAILURE, "setting timestamps failed");
813 elfcopy_main(struct elfcopy *ecp, int argc, char **argv)
815 struct sec_action *sac;
816 const char *infile, *outfile;
820 while ((opt = getopt_long(argc, argv, "dB:gG:I:j:K:L:N:O:pR:s:SwW:xXV",
821 elfcopy_longopts, NULL)) != -1) {
827 sac = lookup_sec_act(ecp, optarg, 1);
830 "both copy and remove specified");
832 ecp->flags |= SEC_REMOVE;
835 ecp->strip = STRIP_ALL;
838 ecp->strip = STRIP_DEBUG;
841 ecp->flags |= KEEP_GLOBAL;
842 add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEPG);
846 set_input_target(ecp, optarg);
849 sac = lookup_sec_act(ecp, optarg, 1);
850 if (sac->remove != 0)
852 "both copy and remove specified");
854 ecp->flags |= SEC_COPY;
857 add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);
860 add_to_symop_list(ecp, optarg, NULL, SYMOP_LOCALIZE);
863 add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);
866 set_output_target(ecp, optarg);
869 ecp->flags |= PRESERVE_DATE;
875 ecp->flags |= WILDCARD;
878 add_to_symop_list(ecp, optarg, NULL, SYMOP_WEAKEN);
881 ecp->flags |= DISCARD_LOCAL;
884 ecp->flags |= DISCARD_LLABEL;
886 case ECP_ADD_GNU_DEBUGLINK:
887 ecp->debuglink = optarg;
889 case ECP_ADD_SECTION:
890 add_section(ecp, optarg);
892 case ECP_CHANGE_ADDR:
893 ecp->change_addr = (int64_t) strtoll(optarg, NULL, 0);
895 case ECP_CHANGE_SEC_ADDR:
896 parse_sec_address_op(ecp, opt, "--change-section-addr",
899 case ECP_CHANGE_SEC_LMA:
900 parse_sec_address_op(ecp, opt, "--change-section-lma",
903 case ECP_CHANGE_SEC_VMA:
904 parse_sec_address_op(ecp, opt, "--change-section-vma",
907 case ECP_CHANGE_START:
908 ecp->change_start = (int64_t) strtoll(optarg, NULL, 0);
910 case ECP_CHANGE_WARN:
914 ecp->fill = (uint8_t) strtoul(optarg, NULL, 0);
915 ecp->flags |= GAP_FILL;
917 case ECP_GLOBALIZE_SYMBOL:
918 add_to_symop_list(ecp, optarg, NULL, SYMOP_GLOBALIZE);
920 case ECP_GLOBALIZE_SYMBOLS:
921 parse_symlist_file(ecp, optarg, SYMOP_GLOBALIZE);
923 case ECP_KEEP_SYMBOLS:
924 parse_symlist_file(ecp, optarg, SYMOP_KEEP);
926 case ECP_KEEP_GLOBAL_SYMBOLS:
927 parse_symlist_file(ecp, optarg, SYMOP_KEEPG);
929 case ECP_LOCALIZE_HIDDEN:
930 ecp->flags |= LOCALIZE_HIDDEN;
932 case ECP_LOCALIZE_SYMBOLS:
933 parse_symlist_file(ecp, optarg, SYMOP_LOCALIZE);
935 case ECP_NO_CHANGE_WARN:
936 ecp->flags |= NO_CHANGE_WARN;
939 ecp->strip = STRIP_NONDEBUG;
942 ecp->strip = STRIP_NONDWO;
945 ecp->pad_to = (uint64_t) strtoull(optarg, NULL, 0);
947 case ECP_PREFIX_ALLOC:
948 ecp->prefix_alloc = optarg;
951 ecp->prefix_sec = optarg;
954 ecp->prefix_sym = optarg;
956 case ECP_REDEF_SYMBOL:
957 if ((s = strchr(optarg, '=')) == NULL)
959 "illegal format for --redefine-sym");
961 add_to_symop_list(ecp, optarg, s, SYMOP_REDEF);
963 case ECP_REDEF_SYMBOLS:
964 parse_symlist_file(ecp, optarg, SYMOP_REDEF);
966 case ECP_RENAME_SECTION:
967 if ((fn = strchr(optarg, '=')) == NULL)
969 "illegal format for --rename-section");
972 /* Check for optional flags. */
973 if ((s = strchr(fn, ',')) != NULL)
976 sac = lookup_sec_act(ecp, optarg, 1);
980 parse_sec_flags(sac, s);
983 set_osabi(ecp, optarg);
985 case ECP_SET_SEC_FLAGS:
986 if ((s = strchr(optarg, '=')) == NULL)
988 "illegal format for --set-section-flags");
990 sac = lookup_sec_act(ecp, optarg, 1);
991 parse_sec_flags(sac, s);
994 ecp->flags |= SET_START;
995 ecp->set_start = (uint64_t) strtoull(optarg, NULL, 0);
997 case ECP_SREC_FORCE_S3:
998 ecp->flags |= SREC_FORCE_S3;
1001 ecp->flags |= SREC_FORCE_LEN;
1002 ecp->srec_len = strtoul(optarg, NULL, 0);
1005 ecp->strip = STRIP_DWO;
1007 case ECP_STRIP_SYMBOLS:
1008 parse_symlist_file(ecp, optarg, SYMOP_STRIP);
1010 case ECP_STRIP_UNNEEDED:
1011 ecp->strip = STRIP_UNNEEDED;
1013 case ECP_WEAKEN_ALL:
1014 ecp->flags |= WEAKEN_ALL;
1016 case ECP_WEAKEN_SYMBOLS:
1017 parse_symlist_file(ecp, optarg, SYMOP_WEAKEN);
1027 if (argc == 0 || argc > 2)
1035 create_file(ecp, infile, outfile);
1039 mcs_main(struct elfcopy *ecp, int argc, char **argv)
1041 struct sec_action *sac;
1043 int append, delete, compress, name, print;
1046 append = delete = compress = name = print = 0;
1048 while ((opt = getopt_long(argc, argv, "a:cdhn:pV", mcs_longopts,
1053 string = optarg; /* XXX multiple -a not supported */
1063 (void)lookup_sec_act(ecp, optarg, 1);
1083 /* Must specify one operation at least. */
1084 if (!append && !compress && !delete && !print)
1088 * If we are going to delete, ignore other operations. This is
1089 * different from the Solaris implementation, which can print
1090 * and delete a section at the same time, for example. Also, this
1091 * implementation do not respect the order between operations that
1092 * user specified, i.e., "mcs -pc a.out" equals to "mcs -cp a.out".
1095 append = compress = print = 0;
1096 ecp->flags |= SEC_REMOVE;
1099 ecp->flags |= SEC_APPEND;
1101 ecp->flags |= SEC_COMPRESS;
1103 ecp->flags |= SEC_PRINT;
1105 /* .comment is the default section to operate on. */
1107 (void)lookup_sec_act(ecp, ".comment", 1);
1109 STAILQ_FOREACH(sac, &ecp->v_sac, sac_list) {
1110 sac->append = append;
1111 sac->compress = compress;
1113 sac->remove = delete;
1114 sac->string = string;
1117 for (i = 0; i < argc; i++) {
1118 /* If only -p is specified, output to /dev/null */
1119 if (print && !append && !compress && !delete)
1120 create_file(ecp, argv[i], "/dev/null");
1122 create_file(ecp, argv[i], NULL);
1127 strip_main(struct elfcopy *ecp, int argc, char **argv)
1129 struct sec_action *sac;
1130 const char *outfile;
1135 while ((opt = getopt_long(argc, argv, "hI:K:N:o:O:pR:sSdgVxXw",
1136 strip_longopts, NULL)) != -1) {
1139 sac = lookup_sec_act(ecp, optarg, 1);
1141 ecp->flags |= SEC_REMOVE;
1144 ecp->strip = STRIP_ALL;
1149 ecp->strip = STRIP_DEBUG;
1155 add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);
1158 add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);
1164 set_output_target(ecp, optarg);
1167 ecp->flags |= PRESERVE_DATE;
1173 ecp->flags |= WILDCARD;
1176 ecp->flags |= DISCARD_LOCAL;
1179 ecp->flags |= DISCARD_LLABEL;
1181 case ECP_ONLY_DEBUG:
1182 ecp->strip = STRIP_NONDEBUG;
1184 case ECP_STRIP_UNNEEDED:
1185 ecp->strip = STRIP_UNNEEDED;
1196 if (ecp->strip == 0 &&
1197 ((ecp->flags & DISCARD_LOCAL) == 0) &&
1198 ((ecp->flags & DISCARD_LLABEL) == 0) &&
1199 lookup_symop_list(ecp, NULL, SYMOP_STRIP) == NULL)
1200 ecp->strip = STRIP_ALL;
1204 * Only accept a single input file if an output file had been
1207 if (outfile != NULL && argc != 1)
1210 for (i = 0; i < argc; i++)
1211 create_file(ecp, argv[i], outfile);
1215 parse_sec_flags(struct sec_action *sac, char *s)
1220 for (flag = strtok(s, ","); flag; flag = strtok(NULL, ",")) {
1222 for (i = 0; sec_flags[i].name != NULL; i++)
1223 if (strcasecmp(sec_flags[i].name, flag) == 0) {
1224 sac->flags |= sec_flags[i].value;
1229 errx(EXIT_FAILURE, "unrecognized section flag %s",
1235 parse_sec_address_op(struct elfcopy *ecp, int optnum, const char *optname,
1238 struct sec_action *sac;
1246 } while (*v != '\0' && *v != '=' && *v != '+' && *v != '-');
1247 if (*v == '\0' || *(v + 1) == '\0')
1248 errx(EXIT_FAILURE, "invalid format for %s", optname);
1251 sac = lookup_sec_act(ecp, name, 1);
1254 if (optnum == ECP_CHANGE_SEC_LMA ||
1255 optnum == ECP_CHANGE_SEC_ADDR) {
1257 sac->lma = (uint64_t) strtoull(v, NULL, 0);
1259 if (optnum == ECP_CHANGE_SEC_VMA ||
1260 optnum == ECP_CHANGE_SEC_ADDR) {
1262 sac->vma = (uint64_t) strtoull(v, NULL, 0);
1266 if (optnum == ECP_CHANGE_SEC_LMA ||
1267 optnum == ECP_CHANGE_SEC_ADDR)
1268 sac->lma_adjust = (int64_t) strtoll(v, NULL, 0);
1269 if (optnum == ECP_CHANGE_SEC_VMA ||
1270 optnum == ECP_CHANGE_SEC_ADDR)
1271 sac->vma_adjust = (int64_t) strtoll(v, NULL, 0);
1274 if (optnum == ECP_CHANGE_SEC_LMA ||
1275 optnum == ECP_CHANGE_SEC_ADDR)
1276 sac->lma_adjust = (int64_t) -strtoll(v, NULL, 0);
1277 if (optnum == ECP_CHANGE_SEC_VMA ||
1278 optnum == ECP_CHANGE_SEC_ADDR)
1279 sac->vma_adjust = (int64_t) -strtoll(v, NULL, 0);
1287 parse_symlist_file(struct elfcopy *ecp, const char *fn, unsigned int op)
1292 char *data, *p, *line, *end, *e, *n;
1294 if (stat(fn, &sb) == -1)
1295 err(EXIT_FAILURE, "stat %s failed", fn);
1297 /* Check if we already read and processed this file. */
1298 STAILQ_FOREACH(sf, &ecp->v_symfile, symfile_list) {
1299 if (sf->dev == sb.st_dev && sf->ino == sb.st_ino)
1300 goto process_symfile;
1303 if ((fp = fopen(fn, "r")) == NULL)
1304 err(EXIT_FAILURE, "can not open %s", fn);
1305 if ((data = malloc(sb.st_size + 1)) == NULL)
1306 err(EXIT_FAILURE, "malloc failed");
1308 if (fread(data, sb.st_size, 1, fp) != 1)
1309 err(EXIT_FAILURE, "fread failed");
1311 data[sb.st_size] = '\0';
1313 if ((sf = calloc(1, sizeof(*sf))) == NULL)
1314 err(EXIT_FAILURE, "malloc failed");
1315 sf->dev = sb.st_dev;
1316 sf->ino = sb.st_ino;
1317 sf->size = sb.st_size + 1;
1323 * Basically what we do here is to convert EOL to '\0', and remove
1324 * leading and trailing whitespaces for each line.
1327 end = sf->data + sf->size;
1329 for(p = sf->data; p < end; p++) {
1330 if ((*p == '\t' || *p == ' ') && line == NULL)
1332 if (*p == '\r' || *p == '\n' || *p == '\0') {
1344 while(e != line && (*e == '\t' || *e == ' '))
1346 if (op != SYMOP_REDEF)
1347 add_to_symop_list(ecp, line, NULL, op);
1349 if (strlen(line) < 3)
1351 "illegal format for"
1353 for(n = line + 1; n < e; n++) {
1354 if (*n == ' ' || *n == '\t') {
1355 while(*n == ' ' || *n == '\t')
1362 "illegal format for"
1364 add_to_symop_list(ecp, line, n, op);
1376 set_input_target(struct elfcopy *ecp, const char *target_name)
1378 Elftc_Bfd_Target *tgt;
1380 if ((tgt = elftc_bfd_find_target(target_name)) == NULL)
1381 errx(EXIT_FAILURE, "%s: invalid target name", target_name);
1382 ecp->itf = elftc_bfd_target_flavor(tgt);
1386 set_output_target(struct elfcopy *ecp, const char *target_name)
1388 Elftc_Bfd_Target *tgt;
1390 if ((tgt = elftc_bfd_find_target(target_name)) == NULL)
1391 errx(EXIT_FAILURE, "%s: invalid target name", target_name);
1392 ecp->otf = elftc_bfd_target_flavor(tgt);
1393 if (ecp->otf == ETF_ELF) {
1394 ecp->oec = elftc_bfd_target_class(tgt);
1395 ecp->oed = elftc_bfd_target_byteorder(tgt);
1396 ecp->oem = elftc_bfd_target_machine(tgt);
1398 if (ecp->otf == ETF_EFI || ecp->otf == ETF_PE)
1399 ecp->oem = elftc_bfd_target_machine(tgt);
1401 ecp->otgt = target_name;
1405 set_osabi(struct elfcopy *ecp, const char *abi)
1410 for (i = 0; osabis[i].name != NULL; i++)
1411 if (strcasecmp(osabis[i].name, abi) == 0) {
1412 ecp->abi = osabis[i].abi;
1417 errx(EXIT_FAILURE, "unrecognized OSABI %s", abi);
1420 #define ELFCOPY_USAGE_MESSAGE "\
1421 Usage: %s [options] infile [outfile]\n\
1422 Transform object files.\n\n\
1424 -d | -g | --strip-debug Remove debugging information from the output.\n\
1425 -j SECTION | --only-section=SECTION\n\
1426 Copy only the named section to the output.\n\
1427 -p | --preserve-dates Preserve access and modification times.\n\
1428 -w | --wildcard Use shell-style patterns to name symbols.\n\
1429 -x | --discard-all Do not copy non-globals to the output.\n\
1430 -I FORMAT | --input-target=FORMAT\n\
1431 Specify object format for the input file.\n\
1432 -K SYM | --keep-symbol=SYM Copy symbol SYM to the output.\n\
1433 -L SYM | --localize-symbol=SYM\n\
1434 Make symbol SYM local to the output file.\n\
1435 -N SYM | --strip-symbol=SYM Do not copy symbol SYM to the output.\n\
1436 -O FORMAT | --output-target=FORMAT\n\
1437 Specify object format for the output file.\n\
1438 FORMAT should be a target name understood by\n\
1439 elftc_bfd_find_target(3).\n\
1440 -R NAME | --remove-section=NAME\n\
1441 Remove the named section.\n\
1442 -S | --strip-all Remove all symbol and relocation information\n\
1444 -V | --version Print a version identifier and exit.\n\
1445 -W SYM | --weaken-symbol=SYM Mark symbol SYM as weak in the output.\n\
1446 -X | --discard-locals Do not copy compiler generated symbols to\n\
1448 --add-section NAME=FILE Add the contents of FILE to the ELF object as\n\
1449 a new section named NAME.\n\
1450 --adjust-section-vma SECTION{=,+,-}VAL | \\\n\
1451 --change-section-address SECTION{=,+,-}VAL\n\
1452 Set or adjust the VMA and the LMA of the\n\
1453 named section by VAL.\n\
1454 --adjust-start=INCR | --change-start=INCR\n\
1455 Add INCR to the start address for the ELF\n\
1457 --adjust-vma=INCR | --change-addresses=INCR\n\
1458 Increase the VMA and LMA of all sections by\n\
1460 --adjust-warning | --change-warnings\n\
1461 Issue warnings for non-existent sections.\n\
1462 --change-section-lma SECTION{=,+,-}VAL\n\
1463 Set or adjust the LMA address of the named\n\
1465 --change-section-vma SECTION{=,+,-}VAL\n\
1466 Set or adjust the VMA address of the named\n\
1468 --gap-fill=VAL Fill the gaps between sections with bytes\n\
1470 --localize-hidden Make all hidden symbols local to the output\n\
1472 --no-adjust-warning| --no-change-warnings\n\
1473 Do not issue warnings for non-existent\n\
1475 --only-keep-debug Copy only debugging information.\n\
1476 --output-target=FORMAT Use the specified format for the output.\n\
1477 --pad-to=ADDRESS Pad the output object up to the given address.\n\
1478 --prefix-alloc-sections=STRING\n\
1479 Prefix the section names of all the allocated\n\
1480 sections with STRING.\n\
1481 --prefix-sections=STRING Prefix the section names of all the sections\n\
1483 --prefix-symbols=STRING Prefix the symbol names of all the symbols\n\
1485 --rename-section OLDNAME=NEWNAME[,FLAGS]\n\
1486 Rename and optionally change section flags.\n\
1487 --set-section-flags SECTION=FLAGS\n\
1488 Set section flags for the named section.\n\
1489 Supported flags are: 'alloc', 'code',\n\
1490 'contents', 'data', 'debug', 'load',\n\
1491 'noload', 'readonly', 'rom', and 'shared'.\n\
1492 --set-start=ADDRESS Set the start address of the ELF object.\n\
1493 --srec-forceS3 Only generate S3 S-Records.\n\
1494 --srec-len=LEN Set the maximum length of a S-Record line.\n\
1495 --strip-unneeded Do not copy relocation information.\n"
1500 (void) fprintf(stderr, ELFCOPY_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1504 #define MCS_USAGE_MESSAGE "\
1505 Usage: %s [options] file...\n\
1506 Manipulate the comment section in an ELF object.\n\n\
1508 -a STRING Append 'STRING' to the comment section.\n\
1509 -c Remove duplicate entries from the comment section.\n\
1510 -d Delete the comment section.\n\
1511 -h | --help Print a help message and exit.\n\
1512 -n NAME Operate on the ELF section with name 'NAME'.\n\
1513 -p Print the contents of the comment section.\n\
1514 -V | --version Print a version identifier and exit.\n"
1519 (void) fprintf(stderr, MCS_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1523 #define STRIP_USAGE_MESSAGE "\
1524 Usage: %s [options] file...\n\
1525 Discard information from ELF objects.\n\n\
1527 -d | -g | -S | --strip-debug Remove debugging symbols.\n\
1528 -h | --help Print a help message.\n\
1529 -o FILE | --output-file FILE Write output to FILE.\n\
1530 --only-keep-debug Keep debugging information only.\n\
1531 -p | --preserve-dates Preserve access and modification times.\n\
1532 -s | --strip-all Remove all symbols.\n\
1533 --strip-unneeded Remove symbols not needed for relocation\n\
1535 -w | --wildcard Use shell-style patterns to name symbols.\n\
1536 -x | --discard-all Discard all non-global symbols.\n\
1537 -I TGT| --input-target=TGT (Accepted, but ignored).\n\
1538 -K SYM | --keep-symbol=SYM Keep symbol 'SYM' in the output.\n\
1539 -N SYM | --strip-symbol=SYM Remove symbol 'SYM' from the output.\n\
1540 -O TGT | --output-target=TGT Set the output file format to 'TGT'.\n\
1541 -R SEC | --remove-section=SEC Remove the section named 'SEC'.\n\
1542 -V | --version Print a version identifier and exit.\n\
1543 -X | --discard-locals Remove compiler-generated local symbols.\n"
1548 (void) fprintf(stderr, STRIP_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1555 (void) printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
1560 * Compare the ending of s with end.
1563 strrcmp(const char *s, const char *end)
1565 size_t endlen, slen;
1568 endlen = strlen(end);
1572 return (strcmp(s, end));
1576 main(int argc, char **argv)
1578 struct elfcopy *ecp;
1580 if (elf_version(EV_CURRENT) == EV_NONE)
1581 errx(EXIT_FAILURE, "ELF library initialization failed: %s",
1584 ecp = calloc(1, sizeof(*ecp));
1586 err(EXIT_FAILURE, "calloc failed");
1588 ecp->itf = ecp->otf = ETF_ELF;
1589 ecp->iec = ecp->oec = ELFCLASSNONE;
1590 ecp->oed = ELFDATANONE;
1592 /* There is always an empty section. */
1596 STAILQ_INIT(&ecp->v_seg);
1597 STAILQ_INIT(&ecp->v_sac);
1598 STAILQ_INIT(&ecp->v_sadd);
1599 STAILQ_INIT(&ecp->v_symop);
1600 STAILQ_INIT(&ecp->v_symfile);
1601 STAILQ_INIT(&ecp->v_arobj);
1602 TAILQ_INIT(&ecp->v_sec);
1604 if ((ecp->progname = ELFTC_GETPROGNAME()) == NULL)
1605 ecp->progname = "elfcopy";
1607 if (strrcmp(ecp->progname, "strip") == 0)
1608 strip_main(ecp, argc, argv);
1609 else if (strrcmp(ecp->progname, "mcs") == 0)
1610 mcs_main(ecp, argc, argv);
1612 if (strrcmp(ecp->progname, "elfcopy") != 0 &&
1613 strrcmp(ecp->progname, "objcopy") != 0)
1614 warnx("program mode not known, defaulting to elfcopy");
1615 elfcopy_main(ecp, argc, argv);