xref: /freebsd/contrib/elftoolchain/elfcopy/main.c (revision 545ddfbe7d4fe8adfb862903b24eac1d5896c1ef)
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 3111 2014-12-20 08:33:01Z kaiwang27 $");
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);
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 static int
527 copy_from_tempfile(const char *src, const char *dst, int infd, int *outfd)
528 {
529 	int tmpfd;
530 
531 	/*
532 	 * First, check if we can use rename().
533 	 */
534 	if (rename(src, dst) >= 0) {
535 		*outfd = infd;
536 		return (0);
537 	} else if (errno != EXDEV)
538 		return (-1);
539 
540 	/*
541 	 * If the rename() failed due to 'src' and 'dst' residing in
542 	 * two different file systems, invoke a helper function in
543 	 * libelftc to do the copy.
544 	 */
545 
546 	if (unlink(dst) < 0)
547 		return (-1);
548 
549 	if ((tmpfd = open(dst, O_CREAT | O_WRONLY, 0755)) < 0)
550 		return (-1);
551 
552 	if (lseek(infd, 0, SEEK_SET) < 0)
553 		return (-1);
554 
555 	if (elftc_copyfile(infd, tmpfd) < 0)
556 		return (-1);
557 
558 	/*
559 	 * Remove the temporary file from the file system
560 	 * namespace, and close its file descriptor.
561 	 */
562 	if (unlink(src) < 0)
563 		return (-1);
564 
565 	(void) close(infd);
566 
567 	/*
568 	 * Return the file descriptor for the destination.
569 	 */
570 	*outfd = tmpfd;
571 
572 	return (0);
573 }
574 
575 static void
576 create_file(struct elfcopy *ecp, const char *src, const char *dst)
577 {
578 	struct stat	 sb;
579 	char		*tempfile, *elftemp;
580 	int		 efd, ifd, ofd, ofd0, tfd;
581 
582 	tempfile = NULL;
583 
584 	if (src == NULL)
585 		errx(EXIT_FAILURE, "internal: src == NULL");
586 	if ((ifd = open(src, O_RDONLY)) == -1)
587 		err(EXIT_FAILURE, "open %s failed", src);
588 
589 	if (fstat(ifd, &sb) == -1)
590 		err(EXIT_FAILURE, "fstat %s failed", src);
591 
592 	if (dst == NULL)
593 		create_tempfile(&tempfile, &ofd);
594 	else
595 		if ((ofd = open(dst, O_RDWR|O_CREAT, 0755)) == -1)
596 			err(EXIT_FAILURE, "open %s failed", dst);
597 
598 #ifndef LIBELF_AR
599 	/* Detect and process ar(1) archive using libarchive. */
600 	if (ac_detect_ar(ifd)) {
601 		ac_create_ar(ecp, ifd, ofd);
602 		goto copy_done;
603 	}
604 #endif
605 
606 	if (lseek(ifd, 0, SEEK_SET) < 0)
607 		err(EXIT_FAILURE, "lseek failed");
608 
609 	/*
610 	 * If input object is not ELF file, convert it to an intermediate
611 	 * ELF object before processing.
612 	 */
613 	if (ecp->itf != ETF_ELF) {
614 		create_tempfile(&elftemp, &efd);
615 		if ((ecp->eout = elf_begin(efd, ELF_C_WRITE, NULL)) == NULL)
616 			errx(EXIT_FAILURE, "elf_begin() failed: %s",
617 			    elf_errmsg(-1));
618 		elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);
619 		if (ecp->itf == ETF_BINARY)
620 			create_elf_from_binary(ecp, ifd, src);
621 		else if (ecp->itf == ETF_IHEX)
622 			create_elf_from_ihex(ecp, ifd);
623 		else if (ecp->itf == ETF_SREC)
624 			create_elf_from_srec(ecp, ifd);
625 		else
626 			errx(EXIT_FAILURE, "Internal: invalid target flavour");
627 		elf_end(ecp->eout);
628 
629 		/* Open intermediate ELF object as new input object. */
630 		close(ifd);
631 		if ((ifd = open(elftemp, O_RDONLY)) == -1)
632 			err(EXIT_FAILURE, "open %s failed", src);
633 		close(efd);
634 		free(elftemp);
635 	}
636 
637 	if ((ecp->ein = elf_begin(ifd, ELF_C_READ, NULL)) == NULL)
638 		errx(EXIT_FAILURE, "elf_begin() failed: %s",
639 		    elf_errmsg(-1));
640 
641 	switch (elf_kind(ecp->ein)) {
642 	case ELF_K_NONE:
643 		errx(EXIT_FAILURE, "file format not recognized");
644 	case ELF_K_ELF:
645 		if ((ecp->eout = elf_begin(ofd, ELF_C_WRITE, NULL)) == NULL)
646 			errx(EXIT_FAILURE, "elf_begin() failed: %s",
647 			    elf_errmsg(-1));
648 
649 		/* elfcopy(1) manage ELF layout by itself. */
650 		elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);
651 
652 		/*
653 		 * Create output ELF object.
654 		 */
655 		create_elf(ecp);
656 		elf_end(ecp->eout);
657 
658 		/*
659 		 * Convert the output ELF object to binary/srec/ihex if need.
660 		 */
661 		if (ecp->otf != ETF_ELF) {
662 			/*
663 			 * Create (another) tempfile for binary/srec/ihex
664 			 * output object.
665 			 */
666 			if (tempfile != NULL) {
667 				if (unlink(tempfile) < 0)
668 					err(EXIT_FAILURE, "unlink %s failed",
669 					    tempfile);
670 				free(tempfile);
671 			}
672 			create_tempfile(&tempfile, &ofd0);
673 
674 
675 			/*
676 			 * Rewind the file descriptor being processed.
677 			 */
678 			if (lseek(ofd, 0, SEEK_SET) < 0)
679 				err(EXIT_FAILURE,
680 				    "lseek failed for the output object");
681 
682 			/*
683 			 * Call flavour-specific conversion routine.
684 			 */
685 			switch (ecp->otf) {
686 			case ETF_BINARY:
687 				create_binary(ofd, ofd0);
688 				break;
689 			case ETF_IHEX:
690 				create_ihex(ofd, ofd0);
691 				break;
692 			case ETF_SREC:
693 				create_srec(ecp, ofd, ofd0,
694 				    dst != NULL ? dst : src);
695 				break;
696 			default:
697 				errx(EXIT_FAILURE, "Internal: unsupported"
698 				    " output flavour %d", ecp->oec);
699 			}
700 
701 			close(ofd);
702 			ofd = ofd0;
703 		}
704 
705 		break;
706 
707 	case ELF_K_AR:
708 		/* XXX: Not yet supported. */
709 		break;
710 	default:
711 		errx(EXIT_FAILURE, "file format not supported");
712 	}
713 
714 	elf_end(ecp->ein);
715 
716 #ifndef LIBELF_AR
717 copy_done:
718 #endif
719 
720 	if (tempfile != NULL) {
721 		if (dst == NULL)
722 			dst = src;
723 
724 		if (copy_from_tempfile(tempfile, dst, ofd, &tfd) < 0)
725 			err(EXIT_FAILURE, "creation of %s failed", dst);
726 
727 		free(tempfile);
728 		tempfile = NULL;
729 
730 		ofd = tfd;
731 	}
732 
733 	if (strcmp(dst, "/dev/null") && fchmod(ofd, sb.st_mode) == -1)
734 		err(EXIT_FAILURE, "fchmod %s failed", dst);
735 
736 	if ((ecp->flags & PRESERVE_DATE) &&
737 	    elftc_set_timestamps(dst, &sb) < 0)
738 		err(EXIT_FAILURE, "setting timestamps failed");
739 
740 	close(ifd);
741 	close(ofd);
742 }
743 
744 static void
745 elfcopy_main(struct elfcopy *ecp, int argc, char **argv)
746 {
747 	struct sec_action	*sac;
748 	const char		*infile, *outfile;
749 	char			*fn, *s;
750 	int			 opt;
751 
752 	while ((opt = getopt_long(argc, argv, "dB:gG:I:j:K:L:N:O:pR:s:SwW:xXV",
753 	    elfcopy_longopts, NULL)) != -1) {
754 		switch(opt) {
755 		case 'B':
756 			/* ignored */
757 			break;
758 		case 'R':
759 			sac = lookup_sec_act(ecp, optarg, 1);
760 			if (sac->copy != 0)
761 				errx(EXIT_FAILURE,
762 				    "both copy and remove specified");
763 			sac->remove = 1;
764 			ecp->flags |= SEC_REMOVE;
765 			break;
766 		case 'S':
767 			ecp->strip = STRIP_ALL;
768 			break;
769 		case 'g':
770 			ecp->strip = STRIP_DEBUG;
771 			break;
772 		case 'G':
773 			ecp->flags |= KEEP_GLOBAL;
774 			add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEPG);
775 			break;
776 		case 'I':
777 		case 's':
778 			set_input_target(ecp, optarg);
779 			break;
780 		case 'j':
781 			sac = lookup_sec_act(ecp, optarg, 1);
782 			if (sac->remove != 0)
783 				errx(EXIT_FAILURE,
784 				    "both copy and remove specified");
785 			sac->copy = 1;
786 			ecp->flags |= SEC_COPY;
787 			break;
788 		case 'K':
789 			add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);
790 			break;
791 		case 'L':
792 			add_to_symop_list(ecp, optarg, NULL, SYMOP_LOCALIZE);
793 			break;
794 		case 'N':
795 			add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);
796 			break;
797 		case 'O':
798 			set_output_target(ecp, optarg);
799 			break;
800 		case 'p':
801 			ecp->flags |= PRESERVE_DATE;
802 			break;
803 		case 'V':
804 			print_version();
805 			break;
806 		case 'w':
807 			ecp->flags |= WILDCARD;
808 			break;
809 		case 'W':
810 			add_to_symop_list(ecp, optarg, NULL, SYMOP_WEAKEN);
811 			break;
812 		case 'x':
813 			ecp->flags |= DISCARD_LOCAL;
814 			break;
815 		case 'X':
816 			ecp->flags |= DISCARD_LLABEL;
817 			break;
818 		case ECP_ADD_GNU_DEBUGLINK:
819 			ecp->debuglink = optarg;
820 			break;
821 		case ECP_ADD_SECTION:
822 			add_section(ecp, optarg);
823 			break;
824 		case ECP_CHANGE_ADDR:
825 			ecp->change_addr = (int64_t) strtoll(optarg, NULL, 0);
826 			break;
827 		case ECP_CHANGE_SEC_ADDR:
828 			parse_sec_address_op(ecp, opt, "--change-section-addr",
829 			    optarg);
830 			break;
831 		case ECP_CHANGE_SEC_LMA:
832 			parse_sec_address_op(ecp, opt, "--change-section-lma",
833 			    optarg);
834 			break;
835 		case ECP_CHANGE_SEC_VMA:
836 			parse_sec_address_op(ecp, opt, "--change-section-vma",
837 			    optarg);
838 			break;
839 		case ECP_CHANGE_START:
840 			ecp->change_start = (int64_t) strtoll(optarg, NULL, 0);
841 			break;
842 		case ECP_CHANGE_WARN:
843 			/* default */
844 			break;
845 		case ECP_GAP_FILL:
846 			ecp->fill = (uint8_t) strtoul(optarg, NULL, 0);
847 			ecp->flags |= GAP_FILL;
848 			break;
849 		case ECP_GLOBALIZE_SYMBOL:
850 			add_to_symop_list(ecp, optarg, NULL, SYMOP_GLOBALIZE);
851 			break;
852 		case ECP_GLOBALIZE_SYMBOLS:
853 			parse_symlist_file(ecp, optarg, SYMOP_GLOBALIZE);
854 			break;
855 		case ECP_KEEP_SYMBOLS:
856 			parse_symlist_file(ecp, optarg, SYMOP_KEEP);
857 			break;
858 		case ECP_KEEP_GLOBAL_SYMBOLS:
859 			parse_symlist_file(ecp, optarg, SYMOP_KEEPG);
860 			break;
861 		case ECP_LOCALIZE_SYMBOLS:
862 			parse_symlist_file(ecp, optarg, SYMOP_LOCALIZE);
863 			break;
864 		case ECP_NO_CHANGE_WARN:
865 			ecp->flags |= NO_CHANGE_WARN;
866 			break;
867 		case ECP_ONLY_DEBUG:
868 			ecp->strip = STRIP_NONDEBUG;
869 			break;
870 		case ECP_PAD_TO:
871 			ecp->pad_to = (uint64_t) strtoull(optarg, NULL, 0);
872 			break;
873 		case ECP_PREFIX_ALLOC:
874 			ecp->prefix_alloc = optarg;
875 			break;
876 		case ECP_PREFIX_SEC:
877 			ecp->prefix_sec = optarg;
878 			break;
879 		case ECP_PREFIX_SYM:
880 			ecp->prefix_sym = optarg;
881 			break;
882 		case ECP_REDEF_SYMBOL:
883 			if ((s = strchr(optarg, '=')) == NULL)
884 				errx(EXIT_FAILURE,
885 				    "illegal format for --redefine-sym");
886 			*s++ = '\0';
887 			add_to_symop_list(ecp, optarg, s, SYMOP_REDEF);
888 			break;
889 		case ECP_REDEF_SYMBOLS:
890 			parse_symlist_file(ecp, optarg, SYMOP_REDEF);
891 			break;
892 		case ECP_RENAME_SECTION:
893 			if ((fn = strchr(optarg, '=')) == NULL)
894 				errx(EXIT_FAILURE,
895 				    "illegal format for --rename-section");
896 			*fn++ = '\0';
897 
898 			/* Check for optional flags. */
899 			if ((s = strchr(fn, ',')) != NULL)
900 				*s++ = '\0';
901 
902 			sac = lookup_sec_act(ecp, optarg, 1);
903 			sac->rename = 1;
904 			sac->newname = fn;
905 			if (s != NULL)
906 				parse_sec_flags(sac, s);
907 			break;
908 		case ECP_SET_OSABI:
909 			set_osabi(ecp, optarg);
910 			break;
911 		case ECP_SET_SEC_FLAGS:
912 			if ((s = strchr(optarg, '=')) == NULL)
913 				errx(EXIT_FAILURE,
914 				    "illegal format for --set-section-flags");
915 			*s++ = '\0';
916 			sac = lookup_sec_act(ecp, optarg, 1);
917 			parse_sec_flags(sac, s);
918 			break;
919 		case ECP_SET_START:
920 			ecp->flags |= SET_START;
921 			ecp->set_start = (uint64_t) strtoull(optarg, NULL, 0);
922 			break;
923 		case ECP_SREC_FORCE_S3:
924 			ecp->flags |= SREC_FORCE_S3;
925 			break;
926 		case ECP_SREC_LEN:
927 			ecp->flags |= SREC_FORCE_LEN;
928 			ecp->srec_len = strtoul(optarg, NULL, 0);
929 			break;
930 		case ECP_STRIP_SYMBOLS:
931 			parse_symlist_file(ecp, optarg, SYMOP_STRIP);
932 			break;
933 		case ECP_STRIP_UNNEEDED:
934 			ecp->strip = STRIP_UNNEEDED;
935 			break;
936 		case ECP_WEAKEN_ALL:
937 			ecp->flags |= WEAKEN_ALL;
938 			break;
939 		case ECP_WEAKEN_SYMBOLS:
940 			parse_symlist_file(ecp, optarg, SYMOP_WEAKEN);
941 			break;
942 		default:
943 			elfcopy_usage();
944 		}
945 	}
946 
947 	if (optind == argc || optind + 2 < argc)
948 		elfcopy_usage();
949 
950 	infile = argv[optind];
951 	outfile = NULL;
952 	if (optind + 1 < argc)
953 		outfile = argv[optind + 1];
954 
955 	create_file(ecp, infile, outfile);
956 }
957 
958 static void
959 mcs_main(struct elfcopy *ecp, int argc, char **argv)
960 {
961 	struct sec_action	*sac;
962 	const char		*string;
963 	int			 append, delete, compress, name, print;
964 	int			 opt, i;
965 
966 	append = delete = compress = name = print = 0;
967 	string = NULL;
968 	while ((opt = getopt_long(argc, argv, "a:cdhn:pV", mcs_longopts,
969 		NULL)) != -1) {
970 		switch(opt) {
971 		case 'a':
972 			append = 1;
973 			string = optarg; /* XXX multiple -a not supported */
974 			break;
975 		case 'c':
976 			compress = 1;
977 			break;
978 		case 'd':
979 			delete = 1;
980 			break;
981 		case 'n':
982 			name = 1;
983 			(void)lookup_sec_act(ecp, optarg, 1);
984 			break;
985 		case 'p':
986 			print = 1;
987 			break;
988 		case 'V':
989 			print_version();
990 			break;
991 		case 'h':
992 		default:
993 			mcs_usage();
994 		}
995 	}
996 
997 	if (optind == argc)
998 		mcs_usage();
999 
1000 	/* Must specify one operation at least. */
1001 	if (!append && !compress && !delete && !print)
1002 		mcs_usage();
1003 
1004 	/*
1005 	 * If we are going to delete, ignore other operations. This is
1006 	 * different from the Solaris implementation, which can print
1007 	 * and delete a section at the same time, for example. Also, this
1008 	 * implementation do not respect the order between operations that
1009 	 * user specified, i.e., "mcs -pc a.out" equals to "mcs -cp a.out".
1010 	 */
1011 	if (delete) {
1012 		append = compress = print = 0;
1013 		ecp->flags |= SEC_REMOVE;
1014 	}
1015 	if (append)
1016 		ecp->flags |= SEC_APPEND;
1017 	if (compress)
1018 		ecp->flags |= SEC_COMPRESS;
1019 	if (print)
1020 		ecp->flags |= SEC_PRINT;
1021 
1022 	/* .comment is the default section to operate on. */
1023 	if (!name)
1024 		(void)lookup_sec_act(ecp, ".comment", 1);
1025 
1026 	STAILQ_FOREACH(sac, &ecp->v_sac, sac_list) {
1027 		sac->append = append;
1028 		sac->compress = compress;
1029 		sac->print = print;
1030 		sac->remove = delete;
1031 		sac->string = string;
1032 	}
1033 
1034 	for (i = optind; i < argc; i++) {
1035 		/* If only -p is specified, output to /dev/null */
1036 		if (print && !append && !compress && !delete)
1037 			create_file(ecp, argv[i], "/dev/null");
1038 		else
1039 			create_file(ecp, argv[i], NULL);
1040 	}
1041 }
1042 
1043 static void
1044 strip_main(struct elfcopy *ecp, int argc, char **argv)
1045 {
1046 	struct sec_action	*sac;
1047 	const char		*outfile;
1048 	int			 opt;
1049 	int			 i;
1050 
1051 	outfile = NULL;
1052 	while ((opt = getopt_long(argc, argv, "hI:K:N:o:O:pR:sSdgVxXw",
1053 	    strip_longopts, NULL)) != -1) {
1054 		switch(opt) {
1055 		case 'R':
1056 			sac = lookup_sec_act(ecp, optarg, 1);
1057 			sac->remove = 1;
1058 			ecp->flags |= SEC_REMOVE;
1059 			break;
1060 		case 's':
1061 			ecp->strip = STRIP_ALL;
1062 			break;
1063 		case 'S':
1064 		case 'g':
1065 		case 'd':
1066 			ecp->strip = STRIP_DEBUG;
1067 			break;
1068 		case 'I':
1069 			/* ignored */
1070 			break;
1071 		case 'K':
1072 			add_to_symop_list(ecp, optarg, NULL, SYMOP_KEEP);
1073 			break;
1074 		case 'N':
1075 			add_to_symop_list(ecp, optarg, NULL, SYMOP_STRIP);
1076 			break;
1077 		case 'o':
1078 			outfile = optarg;
1079 			break;
1080 		case 'O':
1081 			set_output_target(ecp, optarg);
1082 			break;
1083 		case 'p':
1084 			ecp->flags |= PRESERVE_DATE;
1085 			break;
1086 		case 'V':
1087 			print_version();
1088 			break;
1089 		case 'w':
1090 			ecp->flags |= WILDCARD;
1091 			break;
1092 		case 'x':
1093 			ecp->flags |= DISCARD_LOCAL;
1094 			break;
1095 		case 'X':
1096 			ecp->flags |= DISCARD_LLABEL;
1097 			break;
1098 		case ECP_ONLY_DEBUG:
1099 			ecp->strip = STRIP_NONDEBUG;
1100 			break;
1101 		case ECP_STRIP_UNNEEDED:
1102 			ecp->strip = STRIP_UNNEEDED;
1103 			break;
1104 		case 'h':
1105 		default:
1106 			strip_usage();
1107 		}
1108 	}
1109 
1110 	if (ecp->strip == 0 &&
1111 	    ((ecp->flags & DISCARD_LOCAL) == 0) &&
1112 	    ((ecp->flags & DISCARD_LLABEL) == 0) &&
1113 	    lookup_symop_list(ecp, NULL, SYMOP_STRIP) == NULL)
1114 		ecp->strip = STRIP_ALL;
1115 	if (optind == argc)
1116 		strip_usage();
1117 
1118 	for (i = optind; i < argc; i++)
1119 		create_file(ecp, argv[i], outfile);
1120 }
1121 
1122 static void
1123 parse_sec_flags(struct sec_action *sac, char *s)
1124 {
1125 	const char	*flag;
1126 	int		 found, i;
1127 
1128 	for (flag = strtok(s, ","); flag; flag = strtok(NULL, ",")) {
1129 		found = 0;
1130 		for (i = 0; sec_flags[i].name != NULL; i++)
1131 			if (strcasecmp(sec_flags[i].name, flag) == 0) {
1132 				sac->flags |= sec_flags[i].value;
1133 				found = 1;
1134 				break;
1135 			}
1136 		if (!found)
1137 			errx(EXIT_FAILURE, "unrecognized section flag %s",
1138 			    flag);
1139 	}
1140 }
1141 
1142 static void
1143 parse_sec_address_op(struct elfcopy *ecp, int optnum, const char *optname,
1144     char *s)
1145 {
1146 	struct sec_action	*sac;
1147 	const char		*name;
1148 	char			*v;
1149 	char			 op;
1150 
1151 	name = v = s;
1152 	do {
1153 		v++;
1154 	} while (*v != '\0' && *v != '=' && *v != '+' && *v != '-');
1155 	if (*v == '\0' || *(v + 1) == '\0')
1156 		errx(EXIT_FAILURE, "invalid format for %s", optname);
1157 	op = *v;
1158 	*v++ = '\0';
1159 	sac = lookup_sec_act(ecp, name, 1);
1160 	switch (op) {
1161 	case '=':
1162 		if (optnum == ECP_CHANGE_SEC_LMA ||
1163 		    optnum == ECP_CHANGE_SEC_ADDR) {
1164 			sac->setlma = 1;
1165 			sac->lma = (uint64_t) strtoull(v, NULL, 0);
1166 		}
1167 		if (optnum == ECP_CHANGE_SEC_VMA ||
1168 		    optnum == ECP_CHANGE_SEC_ADDR) {
1169 			sac->setvma = 1;
1170 			sac->vma = (uint64_t) strtoull(v, NULL, 0);
1171 		}
1172 		break;
1173 	case '+':
1174 		if (optnum == ECP_CHANGE_SEC_LMA ||
1175 		    optnum == ECP_CHANGE_SEC_ADDR)
1176 			sac->lma_adjust = (int64_t) strtoll(v, NULL, 0);
1177 		if (optnum == ECP_CHANGE_SEC_VMA ||
1178 		    optnum == ECP_CHANGE_SEC_ADDR)
1179 			sac->vma_adjust = (int64_t) strtoll(v, NULL, 0);
1180 		break;
1181 	case '-':
1182 		if (optnum == ECP_CHANGE_SEC_LMA ||
1183 		    optnum == ECP_CHANGE_SEC_ADDR)
1184 			sac->lma_adjust = (int64_t) -strtoll(v, NULL, 0);
1185 		if (optnum == ECP_CHANGE_SEC_VMA ||
1186 		    optnum == ECP_CHANGE_SEC_ADDR)
1187 			sac->vma_adjust = (int64_t) -strtoll(v, NULL, 0);
1188 		break;
1189 	default:
1190 		break;
1191 	}
1192 }
1193 
1194 static void
1195 parse_symlist_file(struct elfcopy *ecp, const char *fn, unsigned int op)
1196 {
1197 	struct symfile	*sf;
1198 	struct stat	 sb;
1199 	FILE		*fp;
1200 	char		*data, *p, *line, *end, *e, *n;
1201 
1202 	if (stat(fn, &sb) == -1)
1203 		err(EXIT_FAILURE, "stat %s failed", fn);
1204 
1205 	/* Check if we already read and processed this file. */
1206 	STAILQ_FOREACH(sf, &ecp->v_symfile, symfile_list) {
1207 		if (sf->dev == sb.st_dev && sf->ino == sb.st_ino)
1208 			goto process_symfile;
1209 	}
1210 
1211 	if ((fp = fopen(fn, "r")) == NULL)
1212 		err(EXIT_FAILURE, "can not open %s", fn);
1213 	if ((data = malloc(sb.st_size + 1)) == NULL)
1214 		err(EXIT_FAILURE, "malloc failed");
1215 	if (fread(data, 1, sb.st_size, fp) == 0 || ferror(fp))
1216 		err(EXIT_FAILURE, "fread failed");
1217 	fclose(fp);
1218 	data[sb.st_size] = '\0';
1219 
1220 	if ((sf = calloc(1, sizeof(*sf))) == NULL)
1221 		err(EXIT_FAILURE, "malloc failed");
1222 	sf->dev = sb.st_dev;
1223 	sf->ino = sb.st_ino;
1224 	sf->size = sb.st_size + 1;
1225 	sf->data = data;
1226 
1227 process_symfile:
1228 
1229 	/*
1230 	 * Basically what we do here is to convert EOL to '\0', and remove
1231 	 * leading and trailing whitespaces for each line.
1232 	 */
1233 
1234 	end = sf->data + sf->size;
1235 	line = NULL;
1236 	for(p = sf->data; p < end; p++) {
1237 		if ((*p == '\t' || *p == ' ') && line == NULL)
1238 			continue;
1239 		if (*p == '\r' || *p == '\n' || *p == '\0') {
1240 			*p = '\0';
1241 			if (line == NULL)
1242 				continue;
1243 
1244 			/* Skip comment. */
1245 			if (*line == '#') {
1246 				line = NULL;
1247 				continue;
1248 			}
1249 
1250 			e = p - 1;
1251 			while(e != line && (*e == '\t' || *e == ' '))
1252 				*e-- = '\0';
1253 			if (op != SYMOP_REDEF)
1254 				add_to_symop_list(ecp, line, NULL, op);
1255 			else {
1256 				if (strlen(line) < 3)
1257 					errx(EXIT_FAILURE,
1258 					    "illegal format for"
1259 					    " --redefine-sym");
1260 				for(n = line + 1; n < e; n++) {
1261 					if (*n == ' ' || *n == '\t') {
1262 						while(*n == ' ' || *n == '\t')
1263 							*n++ = '\0';
1264 						break;
1265 					}
1266 				}
1267 				if (n >= e)
1268 					errx(EXIT_FAILURE,
1269 					    "illegal format for"
1270 					    " --redefine-sym");
1271 				add_to_symop_list(ecp, line, n, op);
1272 			}
1273 			line = NULL;
1274 			continue;
1275 		}
1276 
1277 		if (line == NULL)
1278 			line = p;
1279 	}
1280 }
1281 
1282 static void
1283 set_input_target(struct elfcopy *ecp, const char *target_name)
1284 {
1285 	Elftc_Bfd_Target *tgt;
1286 
1287 	if ((tgt = elftc_bfd_find_target(target_name)) == NULL)
1288 		errx(EXIT_FAILURE, "%s: invalid target name", target_name);
1289 	ecp->itf = elftc_bfd_target_flavor(tgt);
1290 }
1291 
1292 static void
1293 set_output_target(struct elfcopy *ecp, const char *target_name)
1294 {
1295 	Elftc_Bfd_Target *tgt;
1296 
1297 	if ((tgt = elftc_bfd_find_target(target_name)) == NULL)
1298 		errx(EXIT_FAILURE, "%s: invalid target name", target_name);
1299 	ecp->otf = elftc_bfd_target_flavor(tgt);
1300 	if (ecp->otf == ETF_ELF) {
1301 		ecp->oec = elftc_bfd_target_class(tgt);
1302 		ecp->oed = elftc_bfd_target_byteorder(tgt);
1303 		ecp->oem = elftc_bfd_target_machine(tgt);
1304 	}
1305 	ecp->otgt = target_name;
1306 }
1307 
1308 static void
1309 set_osabi(struct elfcopy *ecp, const char *abi)
1310 {
1311 	int i, found;
1312 
1313 	found = 0;
1314 	for (i = 0; osabis[i].name != NULL; i++)
1315 		if (strcasecmp(osabis[i].name, abi) == 0) {
1316 			ecp->abi = osabis[i].abi;
1317 			found = 1;
1318 			break;
1319 		}
1320 	if (!found)
1321 		errx(EXIT_FAILURE, "unrecognized OSABI %s", abi);
1322 }
1323 
1324 #define	ELFCOPY_USAGE_MESSAGE	"\
1325 Usage: %s [options] infile [outfile]\n\
1326   Transform an ELF object.\n\n\
1327   Options:\n\
1328   -d | -g | --strip-debug      Remove debugging information from the output.\n\
1329   -j SECTION | --only-section=SECTION\n\
1330                                Copy only the named section to the output.\n\
1331   -p | --preserve-dates        Preserve access and modification times.\n\
1332   -w | --wildcard              Use shell-style patterns to name symbols.\n\
1333   -x | --discard-all           Do not copy non-globals to the output.\n\
1334   -I FORMAT | --input-target=FORMAT\n\
1335                                (Accepted but ignored).\n\
1336   -K SYM | --keep-symbol=SYM   Copy symbol SYM to the output.\n\
1337   -L SYM | --localize-symbol=SYM\n\
1338                                Make symbol SYM local to the output file.\n\
1339   -N SYM | --strip-symbol=SYM  Do not copy symbol SYM to the output.\n\
1340   -R NAME | --remove-section=NAME\n\
1341                                Remove the named section.\n\
1342   -S | --strip-all             Remove all symbol and relocation information\n\
1343                                from the output.\n\
1344   -V | --version               Print a version identifier and exit.\n\
1345   -W SYM | --weaken-symbol=SYM Mark symbol SYM as weak in the output.\n\
1346   -X | --discard-locals        Do not copy compiler generated symbols to\n\
1347                                the output.\n\
1348   --add-section NAME=FILE      Add the contents of FILE to the ELF object as\n\
1349                                a new section named NAME.\n\
1350   --adjust-section-vma SECTION{=,+,-}VAL | \\\n\
1351     --change-section-address SECTION{=,+,-}VAL\n\
1352                                Set or adjust the VMA and the LMA of the\n\
1353                                named section by VAL.\n\
1354   --adjust-start=INCR | --change-start=INCR\n\
1355                                Add INCR to the start address for the ELF\n\
1356                                object.\n\
1357   --adjust-vma=INCR | --change-addresses=INCR\n\
1358                                Increase the VMA and LMA of all sections by\n\
1359                                INCR.\n\
1360   --adjust-warning | --change-warnings\n\
1361                                Issue warnings for non-existent sections.\n\
1362   --change-section-lma SECTION{=,+,-}VAL\n\
1363                                Set or adjust the LMA address of the named\n\
1364                                section by VAL.\n\
1365   --change-section-vma SECTION{=,+,-}VAL\n\
1366                                Set or adjust the VMA address of the named\n\
1367                                section by VAL.\n\
1368   --gap-fill=VAL               Fill the gaps between sections with bytes\n\
1369                                of value VAL.\n\
1370   --no-adjust-warning| --no-change-warnings\n\
1371                                Do not issue warnings for non-existent\n\
1372                                sections.\n\
1373   --only-keep-debug            Copy only debugging information.\n\
1374   --output-target=FORMAT       Use the specified format for the output.\n\
1375   --pad-to=ADDRESS             Pad the output object upto the given address.\n\
1376   --prefix-alloc-sections=STRING\n\
1377                                Prefix the section names of all the allocated\n\
1378                                sections with STRING.\n\
1379   --prefix-sections=STRING     Prefix the section names of all the sections\n\
1380                                with STRING.\n\
1381   --prefix-symbols=STRING      Prefix the symbol names of all the symbols\n\
1382                                with STRING.\n\
1383   --rename-section OLDNAME=NEWNAME[,FLAGS]\n\
1384                                Rename and optionally change section flags.\n\
1385   --set-section-flags SECTION=FLAGS\n\
1386                                Set section flags for the named section.\n\
1387                                Supported flags are: 'alloc', 'code',\n\
1388                                'contents', 'data', 'debug', 'load',\n\
1389                                'noload', 'readonly', 'rom', and 'shared'.\n\
1390   --set-start=ADDRESS          Set the start address of the ELF object.\n\
1391   --srec-forceS3               Only generate S3 S-Records.\n\
1392   --srec-len=LEN               Set the maximum length of a S-Record line.\n\
1393   --strip-unneeded             Do not copy relocation information.\n"
1394 
1395 static void
1396 elfcopy_usage(void)
1397 {
1398 	(void) fprintf(stderr, ELFCOPY_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1399 	exit(EXIT_FAILURE);
1400 }
1401 
1402 #define	MCS_USAGE_MESSAGE	"\
1403 Usage: %s [options] file...\n\
1404   Manipulate the comment section in an ELF object.\n\n\
1405   Options:\n\
1406   -a STRING        Append 'STRING' to the comment section.\n\
1407   -c               Remove duplicate entries from the comment section.\n\
1408   -d               Delete the comment section.\n\
1409   -h | --help      Print a help message and exit.\n\
1410   -n NAME          Operate on the ELF section with name 'NAME'.\n\
1411   -p               Print the contents of the comment section.\n\
1412   -V | --version   Print a version identifier and exit.\n"
1413 
1414 static void
1415 mcs_usage(void)
1416 {
1417 	(void) fprintf(stderr, MCS_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1418 	exit(EXIT_FAILURE);
1419 }
1420 
1421 #define	STRIP_USAGE_MESSAGE	"\
1422 Usage: %s [options] file...\n\
1423   Discard information from ELF objects.\n\n\
1424   Options:\n\
1425   -d | -g | -S | --strip-debug    Remove debugging symbols.\n\
1426   -h | --help                     Print a help message.\n\
1427   --only-keep-debug               Keep debugging information only.\n\
1428   -p | --preserve-dates           Preserve access and modification times.\n\
1429   -s | --strip-all                Remove all symbols.\n\
1430   --strip-unneeded                Remove symbols not needed for relocation\n\
1431                                   processing.\n\
1432   -w | --wildcard                 Use shell-style patterns to name symbols.\n\
1433   -x | --discard-all              Discard all non-global symbols.\n\
1434   -I TGT| --input-target=TGT      (Accepted, but ignored).\n\
1435   -K SYM | --keep-symbol=SYM      Keep symbol 'SYM' in the output.\n\
1436   -N SYM | --strip-symbol=SYM     Remove symbol 'SYM' from the output.\n\
1437   -O TGT | --output-target=TGT    Set the output file format to 'TGT'.\n\
1438   -R SEC | --remove-section=SEC   Remove the section named 'SEC'.\n\
1439   -V | --version                  Print a version identifier and exit.\n\
1440   -X | --discard-locals           Remove compiler-generated local symbols.\n"
1441 
1442 static void
1443 strip_usage(void)
1444 {
1445 	(void) fprintf(stderr, STRIP_USAGE_MESSAGE, ELFTC_GETPROGNAME());
1446 	exit(EXIT_FAILURE);
1447 }
1448 
1449 static void
1450 print_version(void)
1451 {
1452 	(void) printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
1453 	exit(EXIT_SUCCESS);
1454 }
1455 
1456 int
1457 main(int argc, char **argv)
1458 {
1459 	struct elfcopy *ecp;
1460 
1461 	if (elf_version(EV_CURRENT) == EV_NONE)
1462 		errx(EXIT_FAILURE, "ELF library initialization failed: %s",
1463 		    elf_errmsg(-1));
1464 
1465 	ecp = calloc(1, sizeof(*ecp));
1466 	if (ecp == NULL)
1467 		err(EXIT_FAILURE, "calloc failed");
1468 	memset(ecp, 0, sizeof(*ecp));
1469 
1470 	ecp->itf = ecp->otf = ETF_ELF;
1471 	ecp->iec = ecp->oec = ELFCLASSNONE;
1472 	ecp->oed = ELFDATANONE;
1473 	ecp->abi = -1;
1474 	/* There is always an empty section. */
1475 	ecp->nos = 1;
1476 	ecp->fill = 0;
1477 
1478 	STAILQ_INIT(&ecp->v_seg);
1479 	STAILQ_INIT(&ecp->v_sac);
1480 	STAILQ_INIT(&ecp->v_sadd);
1481 	STAILQ_INIT(&ecp->v_symop);
1482 	STAILQ_INIT(&ecp->v_symfile);
1483 	STAILQ_INIT(&ecp->v_arobj);
1484 	TAILQ_INIT(&ecp->v_sec);
1485 
1486 	if ((ecp->progname = ELFTC_GETPROGNAME()) == NULL)
1487 		ecp->progname = "elfcopy";
1488 
1489 	if (strcmp(ecp->progname, "strip") == 0)
1490 		strip_main(ecp, argc, argv);
1491 	else if (strcmp(ecp->progname, "mcs") == 0)
1492 		mcs_main(ecp, argc, argv);
1493 	else
1494 		elfcopy_main(ecp, argc, argv);
1495 
1496 	free_sec_add(ecp);
1497 	free_sec_act(ecp);
1498 	free(ecp);
1499 
1500 	exit(EXIT_SUCCESS);
1501 }
1502