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