]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/elftoolchain/elfcopy/main.c
Merge ^/head r295544 through r295600.
[FreeBSD/FreeBSD.git] / contrib / elftoolchain / elfcopy / main.c
1 /*-
2  * Copyright (c) 2007-2013 Kai Wang
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/param.h>
28 #include <sys/stat.h>
29
30 #include <err.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <getopt.h>
34 #include <libelftc.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39
40 #include "elfcopy.h"
41
42 ELFTC_VCSID("$Id: main.c 3399 2016-02-12 18:07:56Z emaste $");
43
44 enum options
45 {
46         ECP_ADD_GNU_DEBUGLINK,
47         ECP_ADD_SECTION,
48         ECP_CHANGE_ADDR,
49         ECP_CHANGE_SEC_ADDR,
50         ECP_CHANGE_SEC_LMA,
51         ECP_CHANGE_SEC_VMA,
52         ECP_CHANGE_START,
53         ECP_CHANGE_WARN,
54         ECP_GAP_FILL,
55         ECP_GLOBALIZE_SYMBOL,
56         ECP_GLOBALIZE_SYMBOLS,
57         ECP_KEEP_SYMBOLS,
58         ECP_KEEP_GLOBAL_SYMBOLS,
59         ECP_LOCALIZE_HIDDEN,
60         ECP_LOCALIZE_SYMBOLS,
61         ECP_NO_CHANGE_WARN,
62         ECP_ONLY_DEBUG,
63         ECP_ONLY_DWO,
64         ECP_PAD_TO,
65         ECP_PREFIX_ALLOC,
66         ECP_PREFIX_SEC,
67         ECP_PREFIX_SYM,
68         ECP_REDEF_SYMBOL,
69         ECP_REDEF_SYMBOLS,
70         ECP_RENAME_SECTION,
71         ECP_SET_OSABI,
72         ECP_SET_SEC_FLAGS,
73         ECP_SET_START,
74         ECP_SREC_FORCE_S3,
75         ECP_SREC_LEN,
76         ECP_STRIP_DWO,
77         ECP_STRIP_SYMBOLS,
78         ECP_STRIP_UNNEEDED,
79         ECP_WEAKEN_ALL,
80         ECP_WEAKEN_SYMBOLS
81 };
82
83 static struct option mcs_longopts[] =
84 {
85         { "help", no_argument, NULL, 'h' },
86         { "version", no_argument, NULL, 'V' },
87         { NULL, 0, NULL, 0 }
88 };
89
90 static struct option strip_longopts[] =
91 {
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'},
108         {NULL, 0, NULL, 0}
109 };
110
111 static struct option elfcopy_longopts[] =
112 {
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'},
173         {NULL, 0, NULL, 0}
174 };
175
176 static struct {
177         const char *name;
178         int value;
179 } sec_flags[] = {
180         {"alloc", SF_ALLOC},
181         {"load", SF_LOAD},
182         {"noload", SF_NOLOAD},
183         {"readonly", SF_READONLY},
184         {"debug", SF_DEBUG},
185         {"code", SF_CODE},
186         {"data", SF_DATA},
187         {"rom", SF_ROM},
188         {"share", SF_SHARED},
189         {"contents", SF_CONTENTS},
190         {NULL, 0}
191 };
192
193 static struct {
194         const char *name;
195         int abi;
196 } osabis[] = {
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         {"arm", ELFOSABI_ARM},
213         {"standalone", ELFOSABI_STANDALONE},
214         {NULL, 0}
215 };
216
217 static int      copy_from_tempfile(const char *src, const char *dst,
218     int infd, int *outfd, int in_place);
219 static void     create_file(struct elfcopy *ecp, const char *src,
220     const char *dst);
221 static void     elfcopy_main(struct elfcopy *ecp, int argc, char **argv);
222 static void     elfcopy_usage(void);
223 static void     mcs_main(struct elfcopy *ecp, int argc, char **argv);
224 static void     mcs_usage(void);
225 static void     parse_sec_address_op(struct elfcopy *ecp, int optnum,
226     const char *optname, char *s);
227 static void     parse_sec_flags(struct sec_action *sac, char *s);
228 static void     parse_symlist_file(struct elfcopy *ecp, const char *fn,
229     unsigned int op);
230 static void     print_version(void);
231 static void     set_input_target(struct elfcopy *ecp, const char *target_name);
232 static void     set_osabi(struct elfcopy *ecp, const char *abi);
233 static void     set_output_target(struct elfcopy *ecp, const char *target_name);
234 static void     strip_main(struct elfcopy *ecp, int argc, char **argv);
235 static void     strip_usage(void);
236
237 /*
238  * An ELF object usually has a sturcture described by the
239  * diagram below.
240  *  _____________
241  * |             |
242  * |     NULL    | <- always a SHT_NULL section
243  * |_____________|
244  * |             |
245  * |   .interp   |
246  * |_____________|
247  * |             |
248  * |     ...     |
249  * |_____________|
250  * |             |
251  * |    .text    |
252  * |_____________|
253  * |             |
254  * |     ...     |
255  * |_____________|
256  * |             |
257  * |  .comment   | <- above(include) this: normal sections
258  * |_____________|
259  * |             |
260  * | add sections| <- unloadable sections added by --add-section
261  * |_____________|
262  * |             |
263  * |  .shstrtab  | <- section name string table
264  * |_____________|
265  * |             |
266  * |    shdrs    | <- section header table
267  * |_____________|
268  * |             |
269  * |   .symtab   | <- symbol table, if any
270  * |_____________|
271  * |             |
272  * |   .strtab   | <- symbol name string table, if any
273  * |_____________|
274  * |             |
275  * |  .rel.text  | <- relocation info for .o files.
276  * |_____________|
277  */
278 void
279 create_elf(struct elfcopy *ecp)
280 {
281         struct section  *shtab;
282         GElf_Ehdr        ieh;
283         GElf_Ehdr        oeh;
284         size_t           ishnum;
285
286         ecp->flags |= SYMTAB_INTACT;
287
288         /* Create EHDR. */
289         if (gelf_getehdr(ecp->ein, &ieh) == NULL)
290                 errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
291                     elf_errmsg(-1));
292         if ((ecp->iec = gelf_getclass(ecp->ein)) == ELFCLASSNONE)
293                 errx(EXIT_FAILURE, "getclass() failed: %s",
294                     elf_errmsg(-1));
295
296         if (ecp->oec == ELFCLASSNONE)
297                 ecp->oec = ecp->iec;
298         if (ecp->oed == ELFDATANONE)
299                 ecp->oed = ieh.e_ident[EI_DATA];
300
301         if (gelf_newehdr(ecp->eout, ecp->oec) == NULL)
302                 errx(EXIT_FAILURE, "gelf_newehdr failed: %s",
303                     elf_errmsg(-1));
304         if (gelf_getehdr(ecp->eout, &oeh) == NULL)
305                 errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
306                     elf_errmsg(-1));
307
308         memcpy(oeh.e_ident, ieh.e_ident, sizeof(ieh.e_ident));
309         oeh.e_ident[EI_CLASS] = ecp->oec;
310         oeh.e_ident[EI_DATA]  = ecp->oed;
311         if (ecp->abi != -1)
312                 oeh.e_ident[EI_OSABI] = ecp->abi;
313         oeh.e_flags           = ieh.e_flags;
314         oeh.e_machine         = ieh.e_machine;
315         oeh.e_type            = ieh.e_type;
316         oeh.e_entry           = ieh.e_entry;
317         oeh.e_version         = ieh.e_version;
318
319         ecp->flags &= ~(EXECUTABLE | DYNAMIC | RELOCATABLE);
320         if (ieh.e_type == ET_EXEC)
321                 ecp->flags |= EXECUTABLE;
322         else if (ieh.e_type == ET_DYN)
323                 ecp->flags |= DYNAMIC;
324         else if (ieh.e_type == ET_REL)
325                 ecp->flags |= RELOCATABLE;
326         else
327                 errx(EXIT_FAILURE, "unsupported e_type");
328
329         if (!elf_getshnum(ecp->ein, &ishnum))
330                 errx(EXIT_FAILURE, "elf_getshnum failed: %s",
331                     elf_errmsg(-1));
332         if (ishnum > 0 && (ecp->secndx = calloc(ishnum,
333             sizeof(*ecp->secndx))) == NULL)
334                 err(EXIT_FAILURE, "calloc failed");
335
336         /* Read input object program header. */
337         setup_phdr(ecp);
338
339         /*
340          * Scan of input sections: we iterate through sections from input
341          * object, skip sections need to be stripped, allot Elf_Scn and
342          * create internal section structure for sections we want.
343          * (i.e., determine output sections)
344          */
345         create_scn(ecp);
346
347         /* Apply section address changes, if any. */
348         adjust_addr(ecp);
349
350         /*
351          * Determine if the symbol table needs to be changed based on
352          * command line options.
353          */
354         if (ecp->strip == STRIP_DEBUG ||
355             ecp->strip == STRIP_UNNEEDED ||
356             ecp->flags & WEAKEN_ALL ||
357             ecp->flags & LOCALIZE_HIDDEN ||
358             ecp->flags & DISCARD_LOCAL ||
359             ecp->flags & DISCARD_LLABEL ||
360             ecp->prefix_sym != NULL ||
361             !STAILQ_EMPTY(&ecp->v_symop))
362                 ecp->flags &= ~SYMTAB_INTACT;
363
364         /*
365          * Create symbol table. Symbols are filtered or stripped according to
366          * command line args specified by user, and later updated for the new
367          * layout of sections in the output object.
368          */
369         if ((ecp->flags & SYMTAB_EXIST) != 0)
370                 create_symtab(ecp);
371
372         /*
373          * First processing of output sections: at this stage we copy the
374          * content of each section from input to output object.  Section
375          * content will be modified and printed (mcs) if need. Also content of
376          * relocation section probably will be filtered and updated according
377          * to symbol table changes.
378          */
379         copy_content(ecp);
380
381         /*
382          * Write the underlying ehdr. Note that it should be called
383          * before elf_setshstrndx() since it will overwrite e->e_shstrndx.
384          */
385         if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
386                 errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
387                     elf_errmsg(-1));
388
389         /* Generate section name string table (.shstrtab). */
390         set_shstrtab(ecp);
391
392         /*
393          * Second processing of output sections: Update section headers.
394          * At this stage we set name string index, update st_link and st_info
395          * for output sections.
396          */
397         update_shdr(ecp, 1);
398
399         /* Renew oeh to get the updated e_shstrndx. */
400         if (gelf_getehdr(ecp->eout, &oeh) == NULL)
401                 errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
402                     elf_errmsg(-1));
403
404         /*
405          * Insert SHDR table into the internal section list as a "pseudo"
406          * section, so later it will get sorted and resynced just as "normal"
407          * sections.
408          *
409          * Under FreeBSD, Binutils objcopy always put the section header
410          * at the end of all the sections. We want to do the same here.
411          *
412          * However, note that the behaviour is still different with Binutils:
413          * elfcopy checks the FreeBSD OSABI tag to tell whether it needs to
414          * move the section headers, while Binutils is probably configured
415          * this way when it's compiled on FreeBSD.
416          */
417         if (oeh.e_ident[EI_OSABI] == ELFOSABI_FREEBSD)
418                 shtab = insert_shtab(ecp, 1);
419         else
420                 shtab = insert_shtab(ecp, 0);
421
422         /*
423          * Resync section offsets in the output object. This is needed
424          * because probably sections are modified or new sections are added,
425          * as a result overlap/gap might appears.
426          */
427         resync_sections(ecp);
428
429         /* Store SHDR offset in EHDR. */
430         oeh.e_shoff = shtab->off;
431
432         /* Put program header table immediately after the Elf header. */
433         if (ecp->ophnum > 0) {
434                 oeh.e_phoff = gelf_fsize(ecp->eout, ELF_T_EHDR, 1, EV_CURRENT);
435                 if (oeh.e_phoff == 0)
436                         errx(EXIT_FAILURE, "gelf_fsize() failed: %s",
437                             elf_errmsg(-1));
438         }
439
440         /*
441          * Update ELF object entry point if requested.
442          */
443         if (ecp->change_addr != 0)
444                 oeh.e_entry += ecp->change_addr;
445         if (ecp->flags & SET_START)
446                 oeh.e_entry = ecp->set_start;
447         if (ecp->change_start != 0)
448                 oeh.e_entry += ecp->change_start;
449
450         /*
451          * Update ehdr again before we call elf_update(), since we
452          * modified e_shoff and e_phoff.
453          */
454         if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
455                 errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
456                     elf_errmsg(-1));
457
458         if (ecp->ophnum > 0)
459                 copy_phdr(ecp);
460
461         /* Write out the output elf object. */
462         if (elf_update(ecp->eout, ELF_C_WRITE) < 0)
463                 errx(EXIT_FAILURE, "elf_update() failed: %s",
464                     elf_errmsg(-1));
465
466         /* Release allocated resource. */
467         free_elf(ecp);
468 }
469
470 void
471 free_elf(struct elfcopy *ecp)
472 {
473         struct segment  *seg, *seg_temp;
474         struct section  *sec, *sec_temp;
475
476         /* Free internal segment list. */
477         if (!STAILQ_EMPTY(&ecp->v_seg)) {
478                 STAILQ_FOREACH_SAFE(seg, &ecp->v_seg, seg_list, seg_temp) {
479                         STAILQ_REMOVE(&ecp->v_seg, seg, segment, seg_list);
480                         free(seg);
481                 }
482         }
483
484         /* Free symbol table buffers. */
485         free_symtab(ecp);
486
487         /* Free internal section list. */
488         if (!TAILQ_EMPTY(&ecp->v_sec)) {
489                 TAILQ_FOREACH_SAFE(sec, &ecp->v_sec, sec_list, sec_temp) {
490                         TAILQ_REMOVE(&ecp->v_sec, sec, sec_list);
491                         if (sec->buf != NULL)
492                                 free(sec->buf);
493                         if (sec->newname != NULL)
494                                 free(sec->newname);
495                         if (sec->pad != NULL)
496                                 free(sec->pad);
497                         free(sec);
498                 }
499         }
500
501         if (ecp->secndx != NULL) {
502                 free(ecp->secndx);
503                 ecp->secndx = NULL;
504         }
505 }
506
507 /* Create a temporary file. */
508 void
509 create_tempfile(char **fn, int *fd)
510 {
511         const char      *tmpdir;
512         char            *cp, *tmpf;
513         size_t           tlen, plen;
514
515 #define _TEMPFILE "ecp.XXXXXXXX"
516 #define _TEMPFILEPATH "/tmp/ecp.XXXXXXXX"
517
518         if (fn == NULL || fd == NULL)
519                 return;
520         /* Repect TMPDIR environment variable. */
521         tmpdir = getenv("TMPDIR");
522         if (tmpdir != NULL && *tmpdir != '\0') {
523                 tlen = strlen(tmpdir);
524                 plen = strlen(_TEMPFILE);
525                 tmpf = malloc(tlen + plen + 2);
526                 if (tmpf == NULL)
527                         err(EXIT_FAILURE, "malloc failed");
528                 strncpy(tmpf, tmpdir, tlen);
529                 cp = &tmpf[tlen - 1];
530                 if (*cp++ != '/')
531                         *cp++ = '/';
532                 strncpy(cp, _TEMPFILE, plen);
533                 cp[plen] = '\0';
534         } else {
535                 tmpf = strdup(_TEMPFILEPATH);
536                 if (tmpf == NULL)
537                         err(EXIT_FAILURE, "strdup failed");
538         }
539         if ((*fd = mkstemp(tmpf)) == -1)
540                 err(EXIT_FAILURE, "mkstemp %s failed", tmpf);
541         if (fchmod(*fd, 0644) == -1)
542                 err(EXIT_FAILURE, "fchmod %s failed", tmpf);
543         *fn = tmpf;
544
545 #undef _TEMPFILE
546 #undef _TEMPFILEPATH
547 }
548
549 /*
550  * Copy temporary file with path src and file descriptor infd to path dst.
551  * If in_place is set act as if editing the file in place, avoiding rename()
552  * to preserve hard and symbolic links. Output file remains open, with file
553  * descriptor returned in outfd.
554  */
555 static int
556 copy_from_tempfile(const char *src, const char *dst, int infd, int *outfd,
557     int in_place)
558 {
559         int tmpfd;
560
561         /*
562          * First, check if we can use rename().
563          */
564         if (in_place == 0) {
565                 if (rename(src, dst) >= 0) {
566                         *outfd = infd;
567                         return (0);
568                 } else if (errno != EXDEV)
569                         return (-1);
570         
571                 /*
572                  * If the rename() failed due to 'src' and 'dst' residing in
573                  * two different file systems, invoke a helper function in
574                  * libelftc to do the copy.
575                  */
576
577                 if (unlink(dst) < 0)
578                         return (-1);
579         }
580
581         if ((tmpfd = open(dst, O_CREAT | O_TRUNC | O_WRONLY, 0755)) < 0)
582                 return (-1);
583
584         if (elftc_copyfile(infd, tmpfd) < 0)
585                 return (-1);
586
587         /*
588          * Remove the temporary file from the file system
589          * namespace, and close its file descriptor.
590          */
591         if (unlink(src) < 0)
592                 return (-1);
593
594         (void) close(infd);
595
596         /*
597          * Return the file descriptor for the destination.
598          */
599         *outfd = tmpfd;
600
601         return (0);
602 }
603
604 static void
605 create_file(struct elfcopy *ecp, const char *src, const char *dst)
606 {
607         struct stat      sb;
608         char            *tempfile, *elftemp;
609         int              efd, ifd, ofd, ofd0, tfd;
610         int              in_place;
611
612         tempfile = NULL;
613
614         if (src == NULL)
615                 errx(EXIT_FAILURE, "internal: src == NULL");
616         if ((ifd = open(src, O_RDONLY)) == -1)
617                 err(EXIT_FAILURE, "open %s failed", src);
618
619         if (fstat(ifd, &sb) == -1)
620                 err(EXIT_FAILURE, "fstat %s failed", src);
621
622         if (dst == NULL)
623                 create_tempfile(&tempfile, &ofd);
624         else
625                 if ((ofd = open(dst, O_RDWR|O_CREAT, 0755)) == -1)
626                         err(EXIT_FAILURE, "open %s failed", dst);
627
628 #ifndef LIBELF_AR
629         /* Detect and process ar(1) archive using libarchive. */
630         if (ac_detect_ar(ifd)) {
631                 ac_create_ar(ecp, ifd, ofd);
632                 goto copy_done;
633         }
634 #endif
635
636         if (lseek(ifd, 0, SEEK_SET) < 0)
637                 err(EXIT_FAILURE, "lseek failed");
638
639         /*
640          * If input object is not ELF file, convert it to an intermediate
641          * ELF object before processing.
642          */
643         if (ecp->itf != ETF_ELF) {
644                 create_tempfile(&elftemp, &efd);
645                 if ((ecp->eout = elf_begin(efd, ELF_C_WRITE, NULL)) == NULL)
646                         errx(EXIT_FAILURE, "elf_begin() failed: %s",
647                             elf_errmsg(-1));
648                 elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);
649                 if (ecp->itf == ETF_BINARY)
650                         create_elf_from_binary(ecp, ifd, src);
651                 else if (ecp->itf == ETF_IHEX)
652                         create_elf_from_ihex(ecp, ifd);
653                 else if (ecp->itf == ETF_SREC)
654                         create_elf_from_srec(ecp, ifd);
655                 else
656                         errx(EXIT_FAILURE, "Internal: invalid target flavour");
657                 elf_end(ecp->eout);
658
659                 /* Open intermediate ELF object as new input object. */
660                 close(ifd);
661                 if ((ifd = open(elftemp, O_RDONLY)) == -1)
662                         err(EXIT_FAILURE, "open %s failed", src);
663                 close(efd);
664                 free(elftemp);
665         }
666
667         if ((ecp->ein = elf_begin(ifd, ELF_C_READ, NULL)) == NULL)
668                 errx(EXIT_FAILURE, "elf_begin() failed: %s",
669                     elf_errmsg(-1));
670
671         switch (elf_kind(ecp->ein)) {
672         case ELF_K_NONE:
673                 errx(EXIT_FAILURE, "file format not recognized");
674         case ELF_K_ELF:
675                 if ((ecp->eout = elf_begin(ofd, ELF_C_WRITE, NULL)) == NULL)
676                         errx(EXIT_FAILURE, "elf_begin() failed: %s",
677                             elf_errmsg(-1));
678
679                 /* elfcopy(1) manage ELF layout by itself. */
680                 elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);
681
682                 /*
683                  * Create output ELF object.
684                  */
685                 create_elf(ecp);
686                 elf_end(ecp->eout);
687
688                 /*
689                  * Convert the output ELF object to binary/srec/ihex if need.
690                  */
691                 if (ecp->otf != ETF_ELF) {
692                         /*
693                          * Create (another) tempfile for binary/srec/ihex
694                          * output object.
695                          */
696                         if (tempfile != NULL) {
697                                 if (unlink(tempfile) < 0)
698                                         err(EXIT_FAILURE, "unlink %s failed",
699                                             tempfile);
700                                 free(tempfile);
701                         }
702                         create_tempfile(&tempfile, &ofd0);
703
704
705                         /*
706                          * Rewind the file descriptor being processed.
707                          */
708                         if (lseek(ofd, 0, SEEK_SET) < 0)
709                                 err(EXIT_FAILURE,
710                                     "lseek failed for the output object");
711
712                         /*
713                          * Call flavour-specific conversion routine.
714                          */
715                         switch (ecp->otf) {
716                         case ETF_BINARY:
717                                 create_binary(ofd, ofd0);
718                                 break;
719                         case ETF_IHEX:
720                                 create_ihex(ofd, ofd0);
721                                 break;
722                         case ETF_SREC:
723                                 create_srec(ecp, ofd, ofd0,
724                                     dst != NULL ? dst : src);
725                                 break;
726                         case ETF_PE:
727                         case ETF_EFI:
728 #if     WITH_PE
729                                 create_pe(ecp, ofd, ofd0);
730 #else
731                                 errx(EXIT_FAILURE, "PE/EFI support not enabled"
732                                     " at compile time");
733 #endif
734                                 break;
735                         default:
736                                 errx(EXIT_FAILURE, "Internal: unsupported"
737                                     " output flavour %d", ecp->oec);
738                         }
739
740                         close(ofd);
741                         ofd = ofd0;
742                 }
743
744                 break;
745
746         case ELF_K_AR:
747                 /* XXX: Not yet supported. */
748                 break;
749         default:
750                 errx(EXIT_FAILURE, "file format not supported");
751         }
752
753         elf_end(ecp->ein);
754
755 #ifndef LIBELF_AR
756 copy_done:
757 #endif
758
759         if (tempfile != NULL) {
760                 in_place = 0;
761                 if (dst == NULL) {
762                         dst = src;
763                         if (lstat(dst, &sb) != -1 &&
764                             (sb.st_nlink > 1 || S_ISLNK(sb.st_mode)))
765                                 in_place = 1;
766                 }
767
768                 if (copy_from_tempfile(tempfile, dst, ofd, &tfd, in_place) < 0)
769                         err(EXIT_FAILURE, "creation of %s failed", dst);
770
771                 free(tempfile);
772                 tempfile = NULL;
773
774                 ofd = tfd;
775         }
776
777         if (strcmp(dst, "/dev/null") && fchmod(ofd, sb.st_mode) == -1)
778                 err(EXIT_FAILURE, "fchmod %s failed", dst);
779
780         if ((ecp->flags & PRESERVE_DATE) &&
781             elftc_set_timestamps(dst, &sb) < 0)
782                 err(EXIT_FAILURE, "setting timestamps failed");
783
784         close(ifd);
785         close(ofd);
786 }
787
788 static void
789 elfcopy_main(struct elfcopy *ecp, int argc, char **argv)
790 {
791         struct sec_action       *sac;
792         const char              *infile, *outfile;
793         char                    *fn, *s;
794         int                      opt;
795
796         while ((opt = getopt_long(argc, argv, "dB:gG:I:j:K:L:N:O:pR:s:SwW:xXV",
797             elfcopy_longopts, NULL)) != -1) {
798                 switch(opt) {
799                 case 'B':
800                         /* ignored */
801                         break;
802                 case 'R':
803                         sac = lookup_sec_act(ecp, optarg, 1);
804                         if (sac->copy != 0)
805                                 errx(EXIT_FAILURE,
806                                     "both copy and remove specified");
807                         sac->remove = 1;
808                         ecp->flags |= SEC_REMOVE;
809                         break;
810                 case 'S':
811                         ecp->strip = STRIP_ALL;
812                         break;
813                 case 'g':
814                         ecp->strip = STRIP_DEBUG;
815                         break;
816                 case 'G':
817                         ecp->flags |= KEEP_GLOBAL;
818                         add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEPG);
819                         break;
820                 case 'I':
821                 case 's':
822                         set_input_target(ecp, optarg);
823                         break;
824                 case 'j':
825                         sac = lookup_sec_act(ecp, optarg, 1);
826                         if (sac->remove != 0)
827                                 errx(EXIT_FAILURE,
828                                     "both copy and remove specified");
829                         sac->copy = 1;
830                         ecp->flags |= SEC_COPY;
831                         break;
832                 case 'K':
833                         add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);
834                         break;
835                 case 'L':
836                         add_to_symop_list(ecp, optarg, NULL, SYMOP_LOCALIZE);
837                         break;
838                 case 'N':
839                         add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);
840                         break;
841                 case 'O':
842                         set_output_target(ecp, optarg);
843                         break;
844                 case 'p':
845                         ecp->flags |= PRESERVE_DATE;
846                         break;
847                 case 'V':
848                         print_version();
849                         break;
850                 case 'w':
851                         ecp->flags |= WILDCARD;
852                         break;
853                 case 'W':
854                         add_to_symop_list(ecp, optarg, NULL, SYMOP_WEAKEN);
855                         break;
856                 case 'x':
857                         ecp->flags |= DISCARD_LOCAL;
858                         break;
859                 case 'X':
860                         ecp->flags |= DISCARD_LLABEL;
861                         break;
862                 case ECP_ADD_GNU_DEBUGLINK:
863                         ecp->debuglink = optarg;
864                         break;
865                 case ECP_ADD_SECTION:
866                         add_section(ecp, optarg);
867                         break;
868                 case ECP_CHANGE_ADDR:
869                         ecp->change_addr = (int64_t) strtoll(optarg, NULL, 0);
870                         break;
871                 case ECP_CHANGE_SEC_ADDR:
872                         parse_sec_address_op(ecp, opt, "--change-section-addr",
873                             optarg);
874                         break;
875                 case ECP_CHANGE_SEC_LMA:
876                         parse_sec_address_op(ecp, opt, "--change-section-lma",
877                             optarg);
878                         break;
879                 case ECP_CHANGE_SEC_VMA:
880                         parse_sec_address_op(ecp, opt, "--change-section-vma",
881                             optarg);
882                         break;
883                 case ECP_CHANGE_START:
884                         ecp->change_start = (int64_t) strtoll(optarg, NULL, 0);
885                         break;
886                 case ECP_CHANGE_WARN:
887                         /* default */
888                         break;
889                 case ECP_GAP_FILL:
890                         ecp->fill = (uint8_t) strtoul(optarg, NULL, 0);
891                         ecp->flags |= GAP_FILL;
892                         break;
893                 case ECP_GLOBALIZE_SYMBOL:
894                         add_to_symop_list(ecp, optarg, NULL, SYMOP_GLOBALIZE);
895                         break;
896                 case ECP_GLOBALIZE_SYMBOLS:
897                         parse_symlist_file(ecp, optarg, SYMOP_GLOBALIZE);
898                         break;
899                 case ECP_KEEP_SYMBOLS:
900                         parse_symlist_file(ecp, optarg, SYMOP_KEEP);
901                         break;
902                 case ECP_KEEP_GLOBAL_SYMBOLS:
903                         parse_symlist_file(ecp, optarg, SYMOP_KEEPG);
904                         break;
905                 case ECP_LOCALIZE_HIDDEN:
906                         ecp->flags |= LOCALIZE_HIDDEN;
907                         break;
908                 case ECP_LOCALIZE_SYMBOLS:
909                         parse_symlist_file(ecp, optarg, SYMOP_LOCALIZE);
910                         break;
911                 case ECP_NO_CHANGE_WARN:
912                         ecp->flags |= NO_CHANGE_WARN;
913                         break;
914                 case ECP_ONLY_DEBUG:
915                         ecp->strip = STRIP_NONDEBUG;
916                         break;
917                 case ECP_ONLY_DWO:
918                         ecp->strip = STRIP_NONDWO;
919                         break;
920                 case ECP_PAD_TO:
921                         ecp->pad_to = (uint64_t) strtoull(optarg, NULL, 0);
922                         break;
923                 case ECP_PREFIX_ALLOC:
924                         ecp->prefix_alloc = optarg;
925                         break;
926                 case ECP_PREFIX_SEC:
927                         ecp->prefix_sec = optarg;
928                         break;
929                 case ECP_PREFIX_SYM:
930                         ecp->prefix_sym = optarg;
931                         break;
932                 case ECP_REDEF_SYMBOL:
933                         if ((s = strchr(optarg, '=')) == NULL)
934                                 errx(EXIT_FAILURE,
935                                     "illegal format for --redefine-sym");
936                         *s++ = '\0';
937                         add_to_symop_list(ecp, optarg, s, SYMOP_REDEF);
938                         break;
939                 case ECP_REDEF_SYMBOLS:
940                         parse_symlist_file(ecp, optarg, SYMOP_REDEF);
941                         break;
942                 case ECP_RENAME_SECTION:
943                         if ((fn = strchr(optarg, '=')) == NULL)
944                                 errx(EXIT_FAILURE,
945                                     "illegal format for --rename-section");
946                         *fn++ = '\0';
947
948                         /* Check for optional flags. */
949                         if ((s = strchr(fn, ',')) != NULL)
950                                 *s++ = '\0';
951
952                         sac = lookup_sec_act(ecp, optarg, 1);
953                         sac->rename = 1;
954                         sac->newname = fn;
955                         if (s != NULL)
956                                 parse_sec_flags(sac, s);
957                         break;
958                 case ECP_SET_OSABI:
959                         set_osabi(ecp, optarg);
960                         break;
961                 case ECP_SET_SEC_FLAGS:
962                         if ((s = strchr(optarg, '=')) == NULL)
963                                 errx(EXIT_FAILURE,
964                                     "illegal format for --set-section-flags");
965                         *s++ = '\0';
966                         sac = lookup_sec_act(ecp, optarg, 1);
967                         parse_sec_flags(sac, s);
968                         break;
969                 case ECP_SET_START:
970                         ecp->flags |= SET_START;
971                         ecp->set_start = (uint64_t) strtoull(optarg, NULL, 0);
972                         break;
973                 case ECP_SREC_FORCE_S3:
974                         ecp->flags |= SREC_FORCE_S3;
975                         break;
976                 case ECP_SREC_LEN:
977                         ecp->flags |= SREC_FORCE_LEN;
978                         ecp->srec_len = strtoul(optarg, NULL, 0);
979                         break;
980                 case ECP_STRIP_DWO:
981                         ecp->strip = STRIP_DWO;
982                         break;
983                 case ECP_STRIP_SYMBOLS:
984                         parse_symlist_file(ecp, optarg, SYMOP_STRIP);
985                         break;
986                 case ECP_STRIP_UNNEEDED:
987                         ecp->strip = STRIP_UNNEEDED;
988                         break;
989                 case ECP_WEAKEN_ALL:
990                         ecp->flags |= WEAKEN_ALL;
991                         break;
992                 case ECP_WEAKEN_SYMBOLS:
993                         parse_symlist_file(ecp, optarg, SYMOP_WEAKEN);
994                         break;
995                 default:
996                         elfcopy_usage();
997                 }
998         }
999
1000         if (optind == argc || optind + 2 < argc)
1001                 elfcopy_usage();
1002
1003         infile = argv[optind];
1004         outfile = NULL;
1005         if (optind + 1 < argc)
1006                 outfile = argv[optind + 1];
1007
1008         create_file(ecp, infile, outfile);
1009 }
1010
1011 static void
1012 mcs_main(struct elfcopy *ecp, int argc, char **argv)
1013 {
1014         struct sec_action       *sac;
1015         const char              *string;
1016         int                      append, delete, compress, name, print;
1017         int                      opt, i;
1018
1019         append = delete = compress = name = print = 0;
1020         string = NULL;
1021         while ((opt = getopt_long(argc, argv, "a:cdhn:pV", mcs_longopts,
1022                 NULL)) != -1) {
1023                 switch(opt) {
1024                 case 'a':
1025                         append = 1;
1026                         string = optarg; /* XXX multiple -a not supported */
1027                         break;
1028                 case 'c':
1029                         compress = 1;
1030                         break;
1031                 case 'd':
1032                         delete = 1;
1033                         break;
1034                 case 'n':
1035                         name = 1;
1036                         (void)lookup_sec_act(ecp, optarg, 1);
1037                         break;
1038                 case 'p':
1039                         print = 1;
1040                         break;
1041                 case 'V':
1042                         print_version();
1043                         break;
1044                 case 'h':
1045                 default:
1046                         mcs_usage();
1047                 }
1048         }
1049
1050         if (optind == argc)
1051                 mcs_usage();
1052
1053         /* Must specify one operation at least. */
1054         if (!append && !compress && !delete && !print)
1055                 mcs_usage();
1056
1057         /*
1058          * If we are going to delete, ignore other operations. This is
1059          * different from the Solaris implementation, which can print
1060          * and delete a section at the same time, for example. Also, this
1061          * implementation do not respect the order between operations that
1062          * user specified, i.e., "mcs -pc a.out" equals to "mcs -cp a.out".
1063          */
1064         if (delete) {
1065                 append = compress = print = 0;
1066                 ecp->flags |= SEC_REMOVE;
1067         }
1068         if (append)
1069                 ecp->flags |= SEC_APPEND;
1070         if (compress)
1071                 ecp->flags |= SEC_COMPRESS;
1072         if (print)
1073                 ecp->flags |= SEC_PRINT;
1074
1075         /* .comment is the default section to operate on. */
1076         if (!name)
1077                 (void)lookup_sec_act(ecp, ".comment", 1);
1078
1079         STAILQ_FOREACH(sac, &ecp->v_sac, sac_list) {
1080                 sac->append = append;
1081                 sac->compress = compress;
1082                 sac->print = print;
1083                 sac->remove = delete;
1084                 sac->string = string;
1085         }
1086
1087         for (i = optind; i < argc; i++) {
1088                 /* If only -p is specified, output to /dev/null */
1089                 if (print && !append && !compress && !delete)
1090                         create_file(ecp, argv[i], "/dev/null");
1091                 else
1092                         create_file(ecp, argv[i], NULL);
1093         }
1094 }
1095
1096 static void
1097 strip_main(struct elfcopy *ecp, int argc, char **argv)
1098 {
1099         struct sec_action       *sac;
1100         const char              *outfile;
1101         int                      opt;
1102         int                      i;
1103
1104         outfile = NULL;
1105         while ((opt = getopt_long(argc, argv, "hI:K:N:o:O:pR:sSdgVxXw",
1106             strip_longopts, NULL)) != -1) {
1107                 switch(opt) {
1108                 case 'R':
1109                         sac = lookup_sec_act(ecp, optarg, 1);
1110                         sac->remove = 1;
1111                         ecp->flags |= SEC_REMOVE;
1112                         break;
1113                 case 's':
1114                         ecp->strip = STRIP_ALL;
1115                         break;
1116                 case 'S':
1117                 case 'g':
1118                 case 'd':
1119                         ecp->strip = STRIP_DEBUG;
1120                         break;
1121                 case 'I':
1122                         /* ignored */
1123                         break;
1124                 case 'K':
1125                         add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);
1126                         break;
1127                 case 'N':
1128                         add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);
1129                         break;
1130                 case 'o':
1131                         outfile = optarg;
1132                         break;
1133                 case 'O':
1134                         set_output_target(ecp, optarg);
1135                         break;
1136                 case 'p':
1137                         ecp->flags |= PRESERVE_DATE;
1138                         break;
1139                 case 'V':
1140                         print_version();
1141                         break;
1142                 case 'w':
1143                         ecp->flags |= WILDCARD;
1144                         break;
1145                 case 'x':
1146                         ecp->flags |= DISCARD_LOCAL;
1147                         break;
1148                 case 'X':
1149                         ecp->flags |= DISCARD_LLABEL;
1150                         break;
1151                 case ECP_ONLY_DEBUG:
1152                         ecp->strip = STRIP_NONDEBUG;
1153                         break;
1154                 case ECP_STRIP_UNNEEDED:
1155                         ecp->strip = STRIP_UNNEEDED;
1156                         break;
1157                 case 'h':
1158                 default:
1159                         strip_usage();
1160                 }
1161         }
1162
1163         if (ecp->strip == 0 &&
1164             ((ecp->flags & DISCARD_LOCAL) == 0) &&
1165             ((ecp->flags & DISCARD_LLABEL) == 0) &&
1166             lookup_symop_list(ecp, NULL, SYMOP_STRIP) == NULL)
1167                 ecp->strip = STRIP_ALL;
1168         if (optind == argc)
1169                 strip_usage();
1170
1171         for (i = optind; i < argc; i++)
1172                 create_file(ecp, argv[i], outfile);
1173 }
1174
1175 static void
1176 parse_sec_flags(struct sec_action *sac, char *s)
1177 {
1178         const char      *flag;
1179         int              found, i;
1180
1181         for (flag = strtok(s, ","); flag; flag = strtok(NULL, ",")) {
1182                 found = 0;
1183                 for (i = 0; sec_flags[i].name != NULL; i++)
1184                         if (strcasecmp(sec_flags[i].name, flag) == 0) {
1185                                 sac->flags |= sec_flags[i].value;
1186                                 found = 1;
1187                                 break;
1188                         }
1189                 if (!found)
1190                         errx(EXIT_FAILURE, "unrecognized section flag %s",
1191                             flag);
1192         }
1193 }
1194
1195 static void
1196 parse_sec_address_op(struct elfcopy *ecp, int optnum, const char *optname,
1197     char *s)
1198 {
1199         struct sec_action       *sac;
1200         const char              *name;
1201         char                    *v;
1202         char                     op;
1203
1204         name = v = s;
1205         do {
1206                 v++;
1207         } while (*v != '\0' && *v != '=' && *v != '+' && *v != '-');
1208         if (*v == '\0' || *(v + 1) == '\0')
1209                 errx(EXIT_FAILURE, "invalid format for %s", optname);
1210         op = *v;
1211         *v++ = '\0';
1212         sac = lookup_sec_act(ecp, name, 1);
1213         switch (op) {
1214         case '=':
1215                 if (optnum == ECP_CHANGE_SEC_LMA ||
1216                     optnum == ECP_CHANGE_SEC_ADDR) {
1217                         sac->setlma = 1;
1218                         sac->lma = (uint64_t) strtoull(v, NULL, 0);
1219                 }
1220                 if (optnum == ECP_CHANGE_SEC_VMA ||
1221                     optnum == ECP_CHANGE_SEC_ADDR) {
1222                         sac->setvma = 1;
1223                         sac->vma = (uint64_t) strtoull(v, NULL, 0);
1224                 }
1225                 break;
1226         case '+':
1227                 if (optnum == ECP_CHANGE_SEC_LMA ||
1228                     optnum == ECP_CHANGE_SEC_ADDR)
1229                         sac->lma_adjust = (int64_t) strtoll(v, NULL, 0);
1230                 if (optnum == ECP_CHANGE_SEC_VMA ||
1231                     optnum == ECP_CHANGE_SEC_ADDR)
1232                         sac->vma_adjust = (int64_t) strtoll(v, NULL, 0);
1233                 break;
1234         case '-':
1235                 if (optnum == ECP_CHANGE_SEC_LMA ||
1236                     optnum == ECP_CHANGE_SEC_ADDR)
1237                         sac->lma_adjust = (int64_t) -strtoll(v, NULL, 0);
1238                 if (optnum == ECP_CHANGE_SEC_VMA ||
1239                     optnum == ECP_CHANGE_SEC_ADDR)
1240                         sac->vma_adjust = (int64_t) -strtoll(v, NULL, 0);
1241                 break;
1242         default:
1243                 break;
1244         }
1245 }
1246
1247 static void
1248 parse_symlist_file(struct elfcopy *ecp, const char *fn, unsigned int op)
1249 {
1250         struct symfile  *sf;
1251         struct stat      sb;
1252         FILE            *fp;
1253         char            *data, *p, *line, *end, *e, *n;
1254
1255         if (stat(fn, &sb) == -1)
1256                 err(EXIT_FAILURE, "stat %s failed", fn);
1257
1258         /* Check if we already read and processed this file. */
1259         STAILQ_FOREACH(sf, &ecp->v_symfile, symfile_list) {
1260                 if (sf->dev == sb.st_dev && sf->ino == sb.st_ino)
1261                         goto process_symfile;
1262         }
1263
1264         if ((fp = fopen(fn, "r")) == NULL)
1265                 err(EXIT_FAILURE, "can not open %s", fn);
1266         if ((data = malloc(sb.st_size + 1)) == NULL)
1267                 err(EXIT_FAILURE, "malloc failed");
1268         if (fread(data, 1, sb.st_size, fp) == 0 || ferror(fp))
1269                 err(EXIT_FAILURE, "fread failed");
1270         fclose(fp);
1271         data[sb.st_size] = '\0';
1272
1273         if ((sf = calloc(1, sizeof(*sf))) == NULL)
1274                 err(EXIT_FAILURE, "malloc failed");
1275         sf->dev = sb.st_dev;
1276         sf->ino = sb.st_ino;
1277         sf->size = sb.st_size + 1;
1278         sf->data = data;
1279
1280 process_symfile:
1281
1282         /*
1283          * Basically what we do here is to convert EOL to '\0', and remove
1284          * leading and trailing whitespaces for each line.
1285          */
1286
1287         end = sf->data + sf->size;
1288         line = NULL;
1289         for(p = sf->data; p < end; p++) {
1290                 if ((*p == '\t' || *p == ' ') && line == NULL)
1291                         continue;
1292                 if (*p == '\r' || *p == '\n' || *p == '\0') {
1293                         *p = '\0';
1294                         if (line == NULL)
1295                                 continue;
1296
1297                         /* Skip comment. */
1298                         if (*line == '#') {
1299                                 line = NULL;
1300                                 continue;
1301                         }
1302
1303                         e = p - 1;
1304                         while(e != line && (*e == '\t' || *e == ' '))
1305                                 *e-- = '\0';
1306                         if (op != SYMOP_REDEF)
1307                                 add_to_symop_list(ecp, line, NULL, op);
1308                         else {
1309                                 if (strlen(line) < 3)
1310                                         errx(EXIT_FAILURE,
1311                                             "illegal format for"
1312                                             " --redefine-sym");
1313                                 for(n = line + 1; n < e; n++) {
1314                                         if (*n == ' ' || *n == '\t') {
1315                                                 while(*n == ' ' || *n == '\t')
1316                                                         *n++ = '\0';
1317                                                 break;
1318                                         }
1319                                 }
1320                                 if (n >= e)
1321                                         errx(EXIT_FAILURE,
1322                                             "illegal format for"
1323                                             " --redefine-sym");
1324                                 add_to_symop_list(ecp, line, n, op);
1325                         }
1326                         line = NULL;
1327                         continue;
1328                 }
1329
1330                 if (line == NULL)
1331                         line = p;
1332         }
1333 }
1334
1335 static void
1336 set_input_target(struct elfcopy *ecp, const char *target_name)
1337 {
1338         Elftc_Bfd_Target *tgt;
1339
1340         if ((tgt = elftc_bfd_find_target(target_name)) == NULL)
1341                 errx(EXIT_FAILURE, "%s: invalid target name", target_name);
1342         ecp->itf = elftc_bfd_target_flavor(tgt);
1343 }
1344
1345 static void
1346 set_output_target(struct elfcopy *ecp, const char *target_name)
1347 {
1348         Elftc_Bfd_Target *tgt;
1349
1350         if ((tgt = elftc_bfd_find_target(target_name)) == NULL)
1351                 errx(EXIT_FAILURE, "%s: invalid target name", target_name);
1352         ecp->otf = elftc_bfd_target_flavor(tgt);
1353         if (ecp->otf == ETF_ELF) {
1354                 ecp->oec = elftc_bfd_target_class(tgt);
1355                 ecp->oed = elftc_bfd_target_byteorder(tgt);
1356                 ecp->oem = elftc_bfd_target_machine(tgt);
1357         }
1358         if (ecp->otf == ETF_EFI || ecp->otf == ETF_PE)
1359                 ecp->oem = elftc_bfd_target_machine(tgt);
1360
1361         ecp->otgt = target_name;
1362 }
1363
1364 static void
1365 set_osabi(struct elfcopy *ecp, const char *abi)
1366 {
1367         int i, found;
1368
1369         found = 0;
1370         for (i = 0; osabis[i].name != NULL; i++)
1371                 if (strcasecmp(osabis[i].name, abi) == 0) {
1372                         ecp->abi = osabis[i].abi;
1373                         found = 1;
1374                         break;
1375                 }
1376         if (!found)
1377                 errx(EXIT_FAILURE, "unrecognized OSABI %s", abi);
1378 }
1379
1380 #define ELFCOPY_USAGE_MESSAGE   "\
1381 Usage: %s [options] infile [outfile]\n\
1382   Transform object files.\n\n\
1383   Options:\n\
1384   -d | -g | --strip-debug      Remove debugging information from the output.\n\
1385   -j SECTION | --only-section=SECTION\n\
1386                                Copy only the named section to the output.\n\
1387   -p | --preserve-dates        Preserve access and modification times.\n\
1388   -w | --wildcard              Use shell-style patterns to name symbols.\n\
1389   -x | --discard-all           Do not copy non-globals to the output.\n\
1390   -I FORMAT | --input-target=FORMAT\n\
1391                                Specify object format for the input file.\n\
1392   -K SYM | --keep-symbol=SYM   Copy symbol SYM to the output.\n\
1393   -L SYM | --localize-symbol=SYM\n\
1394                                Make symbol SYM local to the output file.\n\
1395   -N SYM | --strip-symbol=SYM  Do not copy symbol SYM to the output.\n\
1396   -O FORMAT | --output-target=FORMAT\n\
1397                                Specify object format for the output file.\n\
1398                                FORMAT should be a target name understood by\n\
1399                                elftc_bfd_find_target(3).\n\
1400   -R NAME | --remove-section=NAME\n\
1401                                Remove the named section.\n\
1402   -S | --strip-all             Remove all symbol and relocation information\n\
1403                                from the output.\n\
1404   -V | --version               Print a version identifier and exit.\n\
1405   -W SYM | --weaken-symbol=SYM Mark symbol SYM as weak in the output.\n\
1406   -X | --discard-locals        Do not copy compiler generated symbols to\n\
1407                                the output.\n\
1408   --add-section NAME=FILE      Add the contents of FILE to the ELF object as\n\
1409                                a new section named NAME.\n\
1410   --adjust-section-vma SECTION{=,+,-}VAL | \\\n\
1411     --change-section-address SECTION{=,+,-}VAL\n\
1412                                Set or adjust the VMA and the LMA of the\n\
1413                                named section by VAL.\n\
1414   --adjust-start=INCR | --change-start=INCR\n\
1415                                Add INCR to the start address for the ELF\n\
1416                                object.\n\
1417   --adjust-vma=INCR | --change-addresses=INCR\n\
1418                                Increase the VMA and LMA of all sections by\n\
1419                                INCR.\n\
1420   --adjust-warning | --change-warnings\n\
1421                                Issue warnings for non-existent sections.\n\
1422   --change-section-lma SECTION{=,+,-}VAL\n\
1423                                Set or adjust the LMA address of the named\n\
1424                                section by VAL.\n\
1425   --change-section-vma SECTION{=,+,-}VAL\n\
1426                                Set or adjust the VMA address of the named\n\
1427                                section by VAL.\n\
1428   --gap-fill=VAL               Fill the gaps between sections with bytes\n\
1429                                of value VAL.\n\
1430   --localize-hidden            Make all hidden symbols local to the output\n\
1431                                file.\n\
1432   --no-adjust-warning| --no-change-warnings\n\
1433                                Do not issue warnings for non-existent\n\
1434                                sections.\n\
1435   --only-keep-debug            Copy only debugging information.\n\
1436   --output-target=FORMAT       Use the specified format for the output.\n\
1437   --pad-to=ADDRESS             Pad the output object upto the given address.\n\
1438   --prefix-alloc-sections=STRING\n\
1439                                Prefix the section names of all the allocated\n\
1440                                sections with STRING.\n\
1441   --prefix-sections=STRING     Prefix the section names of all the sections\n\
1442                                with STRING.\n\
1443   --prefix-symbols=STRING      Prefix the symbol names of all the symbols\n\
1444                                with STRING.\n\
1445   --rename-section OLDNAME=NEWNAME[,FLAGS]\n\
1446                                Rename and optionally change section flags.\n\
1447   --set-section-flags SECTION=FLAGS\n\
1448                                Set section flags for the named section.\n\
1449                                Supported flags are: 'alloc', 'code',\n\
1450                                'contents', 'data', 'debug', 'load',\n\
1451                                'noload', 'readonly', 'rom', and 'shared'.\n\
1452   --set-start=ADDRESS          Set the start address of the ELF object.\n\
1453   --srec-forceS3               Only generate S3 S-Records.\n\
1454   --srec-len=LEN               Set the maximum length of a S-Record line.\n\
1455   --strip-unneeded             Do not copy relocation information.\n"
1456
1457 static void
1458 elfcopy_usage(void)
1459 {
1460         (void) fprintf(stderr, ELFCOPY_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1461         exit(EXIT_FAILURE);
1462 }
1463
1464 #define MCS_USAGE_MESSAGE       "\
1465 Usage: %s [options] file...\n\
1466   Manipulate the comment section in an ELF object.\n\n\
1467   Options:\n\
1468   -a STRING        Append 'STRING' to the comment section.\n\
1469   -c               Remove duplicate entries from the comment section.\n\
1470   -d               Delete the comment section.\n\
1471   -h | --help      Print a help message and exit.\n\
1472   -n NAME          Operate on the ELF section with name 'NAME'.\n\
1473   -p               Print the contents of the comment section.\n\
1474   -V | --version   Print a version identifier and exit.\n"
1475
1476 static void
1477 mcs_usage(void)
1478 {
1479         (void) fprintf(stderr, MCS_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1480         exit(EXIT_FAILURE);
1481 }
1482
1483 #define STRIP_USAGE_MESSAGE     "\
1484 Usage: %s [options] file...\n\
1485   Discard information from ELF objects.\n\n\
1486   Options:\n\
1487   -d | -g | -S | --strip-debug    Remove debugging symbols.\n\
1488   -h | --help                     Print a help message.\n\
1489   -o FILE | --output-file FILE    Write output to FILE.\n\
1490   --only-keep-debug               Keep debugging information only.\n\
1491   -p | --preserve-dates           Preserve access and modification times.\n\
1492   -s | --strip-all                Remove all symbols.\n\
1493   --strip-unneeded                Remove symbols not needed for relocation\n\
1494                                   processing.\n\
1495   -w | --wildcard                 Use shell-style patterns to name symbols.\n\
1496   -x | --discard-all              Discard all non-global symbols.\n\
1497   -I TGT| --input-target=TGT      (Accepted, but ignored).\n\
1498   -K SYM | --keep-symbol=SYM      Keep symbol 'SYM' in the output.\n\
1499   -N SYM | --strip-symbol=SYM     Remove symbol 'SYM' from the output.\n\
1500   -O TGT | --output-target=TGT    Set the output file format to 'TGT'.\n\
1501   -R SEC | --remove-section=SEC   Remove the section named 'SEC'.\n\
1502   -V | --version                  Print a version identifier and exit.\n\
1503   -X | --discard-locals           Remove compiler-generated local symbols.\n"
1504
1505 static void
1506 strip_usage(void)
1507 {
1508         (void) fprintf(stderr, STRIP_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1509         exit(EXIT_FAILURE);
1510 }
1511
1512 static void
1513 print_version(void)
1514 {
1515         (void) printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
1516         exit(EXIT_SUCCESS);
1517 }
1518
1519 int
1520 main(int argc, char **argv)
1521 {
1522         struct elfcopy *ecp;
1523
1524         if (elf_version(EV_CURRENT) == EV_NONE)
1525                 errx(EXIT_FAILURE, "ELF library initialization failed: %s",
1526                     elf_errmsg(-1));
1527
1528         ecp = calloc(1, sizeof(*ecp));
1529         if (ecp == NULL)
1530                 err(EXIT_FAILURE, "calloc failed");
1531         memset(ecp, 0, sizeof(*ecp));
1532
1533         ecp->itf = ecp->otf = ETF_ELF;
1534         ecp->iec = ecp->oec = ELFCLASSNONE;
1535         ecp->oed = ELFDATANONE;
1536         ecp->abi = -1;
1537         /* There is always an empty section. */
1538         ecp->nos = 1;
1539         ecp->fill = 0;
1540
1541         STAILQ_INIT(&ecp->v_seg);
1542         STAILQ_INIT(&ecp->v_sac);
1543         STAILQ_INIT(&ecp->v_sadd);
1544         STAILQ_INIT(&ecp->v_symop);
1545         STAILQ_INIT(&ecp->v_symfile);
1546         STAILQ_INIT(&ecp->v_arobj);
1547         TAILQ_INIT(&ecp->v_sec);
1548
1549         if ((ecp->progname = ELFTC_GETPROGNAME()) == NULL)
1550                 ecp->progname = "elfcopy";
1551
1552         if (strcmp(ecp->progname, "strip") == 0)
1553                 strip_main(ecp, argc, argv);
1554         else if (strcmp(ecp->progname, "mcs") == 0)
1555                 mcs_main(ecp, argc, argv);
1556         else
1557                 elfcopy_main(ecp, argc, argv);
1558
1559         free_sec_add(ecp);
1560         free_sec_act(ecp);
1561         free(ecp);
1562
1563         exit(EXIT_SUCCESS);
1564 }