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