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