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