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