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