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