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