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