objcopy.c revision 1.1.1.2 1 /* objcopy.c -- copy object file from input to output, optionally massaging it.
2 Copyright (C) 1991-2015 Free Software Foundation, Inc.
3
4 This file is part of GNU Binutils.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
19 02110-1301, USA. */
20
21 #include "sysdep.h"
23 #include "bfd.h"
24 #include "progress.h"
25 #include "getopt.h"
26 #include "libiberty.h"
27 #include "bucomm.h"
28 #include "budbg.h"
29 #include "filenames.h"
30 #include "fnmatch.h"
31 #include "elf-bfd.h"
32 #include <sys/stat.h>
33 #include <ctype.h>
34 #include "libbfd.h"
35 #include "coff/internal.h"
36 #include "libcoff.h"
37
38 /* FIXME: See bfd/peXXigen.c for why we include an architecture specific
39 header in generic PE code. */
40 #include "coff/i386.h"
41 #include "coff/pe.h"
42
43 static bfd_vma pe_file_alignment = (bfd_vma) -1;
44 static bfd_vma pe_heap_commit = (bfd_vma) -1;
45 static bfd_vma pe_heap_reserve = (bfd_vma) -1;
46 static bfd_vma pe_image_base = (bfd_vma) -1;
47 static bfd_vma pe_section_alignment = (bfd_vma) -1;
48 static bfd_vma pe_stack_commit = (bfd_vma) -1;
49 static bfd_vma pe_stack_reserve = (bfd_vma) -1;
50 static short pe_subsystem = -1;
51 static short pe_major_subsystem_version = -1;
52 static short pe_minor_subsystem_version = -1;
53
54 struct is_specified_symbol_predicate_data
55 {
56 const char * name;
57 bfd_boolean found;
58 };
59
60 /* A list to support redefine_sym. */
61 struct redefine_node
62 {
63 char *source;
64 char *target;
65 struct redefine_node *next;
66 };
67
68 struct addsym_node
69 {
70 struct addsym_node *next;
71 char * symdef;
72 long symval;
73 flagword flags;
74 char * section;
75 char * othersym;
76 };
77
78 typedef struct section_rename
79 {
80 const char * old_name;
81 const char * new_name;
82 flagword flags;
83 struct section_rename * next;
84 }
85 section_rename;
86
87 /* List of sections to be renamed. */
88 static section_rename *section_rename_list;
89
90 static asymbol **isympp = NULL; /* Input symbols. */
91 static asymbol **osympp = NULL; /* Output symbols that survive stripping. */
92
93 /* If `copy_byte' >= 0, copy 'copy_width' byte(s) of every `interleave' bytes. */
94 static int copy_byte = -1;
95 static int interleave = 0; /* Initialised to 4 in copy_main(). */
96 static int copy_width = 1;
97
98 static bfd_boolean verbose; /* Print file and target names. */
99 static bfd_boolean preserve_dates; /* Preserve input file timestamp. */
100 static int deterministic = -1; /* Enable deterministic archives. */
101 static int status = 0; /* Exit status. */
102
103 enum strip_action
104 {
105 STRIP_UNDEF,
106 STRIP_NONE, /* Don't strip. */
107 STRIP_DEBUG, /* Strip all debugger symbols. */
108 STRIP_UNNEEDED, /* Strip unnecessary symbols. */
109 STRIP_NONDEBUG, /* Strip everything but debug info. */
110 STRIP_DWO, /* Strip all DWO info. */
111 STRIP_NONDWO, /* Strip everything but DWO info. */
112 STRIP_ALL /* Strip all symbols. */
113 };
114
115 /* Which symbols to remove. */
116 static enum strip_action strip_symbols = STRIP_UNDEF;
117
118 enum locals_action
119 {
120 LOCALS_UNDEF,
121 LOCALS_START_L, /* Discard locals starting with L. */
122 LOCALS_ALL /* Discard all locals. */
123 };
124
125 /* Which local symbols to remove. Overrides STRIP_ALL. */
126 static enum locals_action discard_locals;
127
128 /* Structure used to hold lists of sections and actions to take. */
129 struct section_list
130 {
131 struct section_list * next; /* Next section to change. */
132 const char * pattern; /* Section name pattern. */
133 bfd_boolean used; /* Whether this entry was used. */
134
135 unsigned int context; /* What to do with matching sections. */
136 /* Flag bits used in the context field.
137 COPY and REMOVE are mutually exlusive. SET and ALTER are mutually exclusive. */
138 #define SECTION_CONTEXT_REMOVE (1 << 0) /* Remove this section. */
139 #define SECTION_CONTEXT_COPY (1 << 1) /* Copy this section, delete all non-copied section. */
140 #define SECTION_CONTEXT_SET_VMA (1 << 2) /* Set the sections' VMA address. */
141 #define SECTION_CONTEXT_ALTER_VMA (1 << 3) /* Increment or decrement the section's VMA address. */
142 #define SECTION_CONTEXT_SET_LMA (1 << 4) /* Set the sections' LMA address. */
143 #define SECTION_CONTEXT_ALTER_LMA (1 << 5) /* Increment or decrement the section's LMA address. */
144 #define SECTION_CONTEXT_SET_FLAGS (1 << 6) /* Set the section's flags. */
145
146 bfd_vma vma_val; /* Amount to change by or set to. */
147 bfd_vma lma_val; /* Amount to change by or set to. */
148 flagword flags; /* What to set the section flags to. */
149 };
150
151 static struct section_list *change_sections;
152
153 /* TRUE if some sections are to be removed. */
154 static bfd_boolean sections_removed;
155
156 /* TRUE if only some sections are to be copied. */
157 static bfd_boolean sections_copied;
158
159 /* Changes to the start address. */
160 static bfd_vma change_start = 0;
161 static bfd_boolean set_start_set = FALSE;
162 static bfd_vma set_start;
163
164 /* Changes to section addresses. */
165 static bfd_vma change_section_address = 0;
166
167 /* Filling gaps between sections. */
168 static bfd_boolean gap_fill_set = FALSE;
169 static bfd_byte gap_fill = 0;
170
171 /* Pad to a given address. */
172 static bfd_boolean pad_to_set = FALSE;
173 static bfd_vma pad_to;
174
175 /* Use alternative machine code? */
176 static unsigned long use_alt_mach_code = 0;
177
178 /* Output BFD flags user wants to set or clear */
179 static flagword bfd_flags_to_set;
180 static flagword bfd_flags_to_clear;
181
182 /* List of sections to add. */
183 struct section_add
184 {
185 /* Next section to add. */
186 struct section_add *next;
187 /* Name of section to add. */
188 const char *name;
189 /* Name of file holding section contents. */
190 const char *filename;
191 /* Size of file. */
192 size_t size;
193 /* Contents of file. */
194 bfd_byte *contents;
195 /* BFD section, after it has been added. */
196 asection *section;
197 };
198
199 /* List of sections to add to the output BFD. */
200 static struct section_add *add_sections;
201
202 /* List of sections to update in the output BFD. */
203 static struct section_add *update_sections;
204
205 /* List of sections to dump from the output BFD. */
206 static struct section_add *dump_sections;
207
208 /* If non-NULL the argument to --add-gnu-debuglink.
209 This should be the filename to store in the .gnu_debuglink section. */
210 static const char * gnu_debuglink_filename = NULL;
211
212 /* Whether to convert debugging information. */
213 static bfd_boolean convert_debugging = FALSE;
214
215 /* Whether to compress/decompress DWARF debug sections. */
216 static enum
217 {
218 nothing = 0,
219 compress = 1 << 0,
220 compress_zlib = compress | 1 << 1,
221 compress_gnu_zlib = compress | 1 << 2,
222 compress_gabi_zlib = compress | 1 << 3,
223 decompress = 1 << 4
224 } do_debug_sections = nothing;
225
226 /* Whether to change the leading character in symbol names. */
227 static bfd_boolean change_leading_char = FALSE;
228
229 /* Whether to remove the leading character from global symbol names. */
230 static bfd_boolean remove_leading_char = FALSE;
231
232 /* Whether to permit wildcard in symbol comparison. */
233 static bfd_boolean wildcard = FALSE;
234
235 /* True if --localize-hidden is in effect. */
236 static bfd_boolean localize_hidden = FALSE;
237
238 /* List of symbols to strip, keep, localize, keep-global, weaken,
239 or redefine. */
240 static htab_t strip_specific_htab = NULL;
241 static htab_t strip_unneeded_htab = NULL;
242 static htab_t keep_specific_htab = NULL;
243 static htab_t localize_specific_htab = NULL;
244 static htab_t globalize_specific_htab = NULL;
245 static htab_t keepglobal_specific_htab = NULL;
246 static htab_t weaken_specific_htab = NULL;
247 static struct redefine_node *redefine_sym_list = NULL;
248 static struct addsym_node *add_sym_list = NULL, **add_sym_tail = &add_sym_list;
249 static int add_symbols = 0;
250
251 /* If this is TRUE, we weaken global symbols (set BSF_WEAK). */
252 static bfd_boolean weaken = FALSE;
253
254 /* If this is TRUE, we retain BSF_FILE symbols. */
255 static bfd_boolean keep_file_symbols = FALSE;
256
257 /* Prefix symbols/sections. */
258 static char *prefix_symbols_string = 0;
259 static char *prefix_sections_string = 0;
260 static char *prefix_alloc_sections_string = 0;
261
262 /* True if --extract-symbol was passed on the command line. */
263 static bfd_boolean extract_symbol = FALSE;
264
265 /* If `reverse_bytes' is nonzero, then reverse the order of every chunk
266 of <reverse_bytes> bytes within each output section. */
267 static int reverse_bytes = 0;
268
269 /* For Coff objects, we may want to allow or disallow long section names,
270 or preserve them where found in the inputs. Debug info relies on them. */
271 enum long_section_name_handling
272 {
273 DISABLE,
274 ENABLE,
275 KEEP
276 };
277
278 /* The default long section handling mode is to preserve them.
279 This is also the only behaviour for 'strip'. */
280 static enum long_section_name_handling long_section_names = KEEP;
281
282 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
283 enum command_line_switch
284 {
285 OPTION_ADD_SECTION=150,
286 OPTION_ADD_GNU_DEBUGLINK,
287 OPTION_ADD_SYMBOL,
288 OPTION_ALT_MACH_CODE,
289 OPTION_CHANGE_ADDRESSES,
290 OPTION_CHANGE_LEADING_CHAR,
291 OPTION_CHANGE_SECTION_ADDRESS,
292 OPTION_CHANGE_SECTION_LMA,
293 OPTION_CHANGE_SECTION_VMA,
294 OPTION_CHANGE_START,
295 OPTION_CHANGE_WARNINGS,
296 OPTION_COMPRESS_DEBUG_SECTIONS,
297 OPTION_DEBUGGING,
298 OPTION_DECOMPRESS_DEBUG_SECTIONS,
299 OPTION_DUMP_SECTION,
300 OPTION_EXTRACT_DWO,
301 OPTION_EXTRACT_SYMBOL,
302 OPTION_FILE_ALIGNMENT,
303 OPTION_FORMATS_INFO,
304 OPTION_GAP_FILL,
305 OPTION_GLOBALIZE_SYMBOL,
306 OPTION_GLOBALIZE_SYMBOLS,
307 OPTION_HEAP,
308 OPTION_IMAGE_BASE,
309 OPTION_IMPURE,
310 OPTION_INTERLEAVE_WIDTH,
311 OPTION_KEEPGLOBAL_SYMBOLS,
312 OPTION_KEEP_FILE_SYMBOLS,
313 OPTION_KEEP_SYMBOLS,
314 OPTION_LOCALIZE_HIDDEN,
315 OPTION_LOCALIZE_SYMBOLS,
316 OPTION_LONG_SECTION_NAMES,
317 OPTION_NO_CHANGE_WARNINGS,
318 OPTION_ONLY_KEEP_DEBUG,
319 OPTION_PAD_TO,
320 OPTION_PREFIX_ALLOC_SECTIONS,
321 OPTION_PREFIX_SECTIONS,
322 OPTION_PREFIX_SYMBOLS,
323 OPTION_PURE,
324 OPTION_READONLY_TEXT,
325 OPTION_REDEFINE_SYM,
326 OPTION_REDEFINE_SYMS,
327 OPTION_REMOVE_LEADING_CHAR,
328 OPTION_RENAME_SECTION,
329 OPTION_REVERSE_BYTES,
330 OPTION_SECTION_ALIGNMENT,
331 OPTION_SET_SECTION_FLAGS,
332 OPTION_SET_START,
333 OPTION_SREC_FORCES3,
334 OPTION_SREC_LEN,
335 OPTION_STACK,
336 OPTION_STRIP_DWO,
337 OPTION_STRIP_SYMBOLS,
338 OPTION_STRIP_UNNEEDED,
339 OPTION_STRIP_UNNEEDED_SYMBOL,
340 OPTION_STRIP_UNNEEDED_SYMBOLS,
341 OPTION_SUBSYSTEM,
342 OPTION_UPDATE_SECTION,
343 OPTION_WEAKEN,
344 OPTION_WEAKEN_SYMBOLS,
345 OPTION_WRITABLE_TEXT
346 };
347
348 /* Options to handle if running as "strip". */
349
350 static struct option strip_options[] =
351 {
352 {"disable-deterministic-archives", no_argument, 0, 'U'},
353 {"discard-all", no_argument, 0, 'x'},
354 {"discard-locals", no_argument, 0, 'X'},
355 {"enable-deterministic-archives", no_argument, 0, 'D'},
356 {"format", required_argument, 0, 'F'}, /* Obsolete */
357 {"help", no_argument, 0, 'h'},
358 {"info", no_argument, 0, OPTION_FORMATS_INFO},
359 {"input-format", required_argument, 0, 'I'}, /* Obsolete */
360 {"input-target", required_argument, 0, 'I'},
361 {"keep-file-symbols", no_argument, 0, OPTION_KEEP_FILE_SYMBOLS},
362 {"keep-symbol", required_argument, 0, 'K'},
363 {"only-keep-debug", no_argument, 0, OPTION_ONLY_KEEP_DEBUG},
364 {"output-file", required_argument, 0, 'o'},
365 {"output-format", required_argument, 0, 'O'}, /* Obsolete */
366 {"output-target", required_argument, 0, 'O'},
367 {"preserve-dates", no_argument, 0, 'p'},
368 {"remove-section", required_argument, 0, 'R'},
369 {"strip-all", no_argument, 0, 's'},
370 {"strip-debug", no_argument, 0, 'S'},
371 {"strip-dwo", no_argument, 0, OPTION_STRIP_DWO},
372 {"strip-symbol", required_argument, 0, 'N'},
373 {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
374 {"target", required_argument, 0, 'F'},
375 {"verbose", no_argument, 0, 'v'},
376 {"version", no_argument, 0, 'V'},
377 {"wildcard", no_argument, 0, 'w'},
378 {0, no_argument, 0, 0}
379 };
380
381 /* Options to handle if running as "objcopy". */
382
383 static struct option copy_options[] =
384 {
385 {"add-gnu-debuglink", required_argument, 0, OPTION_ADD_GNU_DEBUGLINK},
386 {"add-section", required_argument, 0, OPTION_ADD_SECTION},
387 {"add-symbol", required_argument, 0, OPTION_ADD_SYMBOL},
388 {"adjust-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
389 {"adjust-start", required_argument, 0, OPTION_CHANGE_START},
390 {"adjust-vma", required_argument, 0, OPTION_CHANGE_ADDRESSES},
391 {"adjust-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
392 {"alt-machine-code", required_argument, 0, OPTION_ALT_MACH_CODE},
393 {"binary-architecture", required_argument, 0, 'B'},
394 {"byte", required_argument, 0, 'b'},
395 {"change-addresses", required_argument, 0, OPTION_CHANGE_ADDRESSES},
396 {"change-leading-char", no_argument, 0, OPTION_CHANGE_LEADING_CHAR},
397 {"change-section-address", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
398 {"change-section-lma", required_argument, 0, OPTION_CHANGE_SECTION_LMA},
399 {"change-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_VMA},
400 {"change-start", required_argument, 0, OPTION_CHANGE_START},
401 {"change-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
402 {"compress-debug-sections", optional_argument, 0, OPTION_COMPRESS_DEBUG_SECTIONS},
403 {"debugging", no_argument, 0, OPTION_DEBUGGING},
404 {"decompress-debug-sections", no_argument, 0, OPTION_DECOMPRESS_DEBUG_SECTIONS},
405 {"disable-deterministic-archives", no_argument, 0, 'U'},
406 {"discard-all", no_argument, 0, 'x'},
407 {"discard-locals", no_argument, 0, 'X'},
408 {"dump-section", required_argument, 0, OPTION_DUMP_SECTION},
409 {"enable-deterministic-archives", no_argument, 0, 'D'},
410 {"extract-dwo", no_argument, 0, OPTION_EXTRACT_DWO},
411 {"extract-symbol", no_argument, 0, OPTION_EXTRACT_SYMBOL},
412 {"file-alignment", required_argument, 0, OPTION_FILE_ALIGNMENT},
413 {"format", required_argument, 0, 'F'}, /* Obsolete */
414 {"gap-fill", required_argument, 0, OPTION_GAP_FILL},
415 {"globalize-symbol", required_argument, 0, OPTION_GLOBALIZE_SYMBOL},
416 {"globalize-symbols", required_argument, 0, OPTION_GLOBALIZE_SYMBOLS},
417 {"heap", required_argument, 0, OPTION_HEAP},
418 {"help", no_argument, 0, 'h'},
419 {"image-base", required_argument, 0 , OPTION_IMAGE_BASE},
420 {"impure", no_argument, 0, OPTION_IMPURE},
421 {"info", no_argument, 0, OPTION_FORMATS_INFO},
422 {"input-format", required_argument, 0, 'I'}, /* Obsolete */
423 {"input-target", required_argument, 0, 'I'},
424 {"interleave", optional_argument, 0, 'i'},
425 {"interleave-width", required_argument, 0, OPTION_INTERLEAVE_WIDTH},
426 {"keep-file-symbols", no_argument, 0, OPTION_KEEP_FILE_SYMBOLS},
427 {"keep-global-symbol", required_argument, 0, 'G'},
428 {"keep-global-symbols", required_argument, 0, OPTION_KEEPGLOBAL_SYMBOLS},
429 {"keep-symbol", required_argument, 0, 'K'},
430 {"keep-symbols", required_argument, 0, OPTION_KEEP_SYMBOLS},
431 {"localize-hidden", no_argument, 0, OPTION_LOCALIZE_HIDDEN},
432 {"localize-symbol", required_argument, 0, 'L'},
433 {"localize-symbols", required_argument, 0, OPTION_LOCALIZE_SYMBOLS},
434 {"long-section-names", required_argument, 0, OPTION_LONG_SECTION_NAMES},
435 {"no-adjust-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
436 {"no-change-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
437 {"only-keep-debug", no_argument, 0, OPTION_ONLY_KEEP_DEBUG},
438 {"only-section", required_argument, 0, 'j'},
439 {"output-format", required_argument, 0, 'O'}, /* Obsolete */
440 {"output-target", required_argument, 0, 'O'},
441 {"pad-to", required_argument, 0, OPTION_PAD_TO},
442 {"prefix-alloc-sections", required_argument, 0, OPTION_PREFIX_ALLOC_SECTIONS},
443 {"prefix-sections", required_argument, 0, OPTION_PREFIX_SECTIONS},
444 {"prefix-symbols", required_argument, 0, OPTION_PREFIX_SYMBOLS},
445 {"preserve-dates", no_argument, 0, 'p'},
446 {"pure", no_argument, 0, OPTION_PURE},
447 {"readonly-text", no_argument, 0, OPTION_READONLY_TEXT},
448 {"redefine-sym", required_argument, 0, OPTION_REDEFINE_SYM},
449 {"redefine-syms", required_argument, 0, OPTION_REDEFINE_SYMS},
450 {"remove-leading-char", no_argument, 0, OPTION_REMOVE_LEADING_CHAR},
451 {"remove-section", required_argument, 0, 'R'},
452 {"rename-section", required_argument, 0, OPTION_RENAME_SECTION},
453 {"reverse-bytes", required_argument, 0, OPTION_REVERSE_BYTES},
454 {"section-alignment", required_argument, 0, OPTION_SECTION_ALIGNMENT},
455 {"set-section-flags", required_argument, 0, OPTION_SET_SECTION_FLAGS},
456 {"set-start", required_argument, 0, OPTION_SET_START},
457 {"srec-forceS3", no_argument, 0, OPTION_SREC_FORCES3},
458 {"srec-len", required_argument, 0, OPTION_SREC_LEN},
459 {"stack", required_argument, 0, OPTION_STACK},
460 {"strip-all", no_argument, 0, 'S'},
461 {"strip-debug", no_argument, 0, 'g'},
462 {"strip-dwo", no_argument, 0, OPTION_STRIP_DWO},
463 {"strip-symbol", required_argument, 0, 'N'},
464 {"strip-symbols", required_argument, 0, OPTION_STRIP_SYMBOLS},
465 {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
466 {"strip-unneeded-symbol", required_argument, 0, OPTION_STRIP_UNNEEDED_SYMBOL},
467 {"strip-unneeded-symbols", required_argument, 0, OPTION_STRIP_UNNEEDED_SYMBOLS},
468 {"subsystem", required_argument, 0, OPTION_SUBSYSTEM},
469 {"target", required_argument, 0, 'F'},
470 {"update-section", required_argument, 0, OPTION_UPDATE_SECTION},
471 {"verbose", no_argument, 0, 'v'},
472 {"version", no_argument, 0, 'V'},
473 {"weaken", no_argument, 0, OPTION_WEAKEN},
474 {"weaken-symbol", required_argument, 0, 'W'},
475 {"weaken-symbols", required_argument, 0, OPTION_WEAKEN_SYMBOLS},
476 {"wildcard", no_argument, 0, 'w'},
477 {"writable-text", no_argument, 0, OPTION_WRITABLE_TEXT},
478 {0, no_argument, 0, 0}
479 };
480
481 /* IMPORTS */
482 extern char *program_name;
483
484 /* This flag distinguishes between strip and objcopy:
485 1 means this is 'strip'; 0 means this is 'objcopy'.
486 -1 means if we should use argv[0] to decide. */
487 extern int is_strip;
488
489 /* The maximum length of an S record. This variable is declared in srec.c
490 and can be modified by the --srec-len parameter. */
491 extern unsigned int Chunk;
492
493 /* Restrict the generation of Srecords to type S3 only.
494 This variable is declare in bfd/srec.c and can be toggled
495 on by the --srec-forceS3 command line switch. */
496 extern bfd_boolean S3Forced;
497
498 /* Forward declarations. */
499 static void setup_section (bfd *, asection *, void *);
500 static void setup_bfd_headers (bfd *, bfd *);
501 static void copy_relocations_in_section (bfd *, asection *, void *);
502 static void copy_section (bfd *, asection *, void *);
503 static void get_sections (bfd *, asection *, void *);
504 static int compare_section_lma (const void *, const void *);
505 static void mark_symbols_used_in_relocations (bfd *, asection *, void *);
506 static bfd_boolean write_debugging_info (bfd *, void *, long *, asymbol ***);
507 static const char *lookup_sym_redefinition (const char *);
508
509 static void
511 copy_usage (FILE *stream, int exit_status)
512 {
513 fprintf (stream, _("Usage: %s [option(s)] in-file [out-file]\n"), program_name);
514 fprintf (stream, _(" Copies a binary file, possibly transforming it in the process\n"));
515 fprintf (stream, _(" The options are:\n"));
516 fprintf (stream, _("\
517 -I --input-target <bfdname> Assume input file is in format <bfdname>\n\
518 -O --output-target <bfdname> Create an output file in format <bfdname>\n\
519 -B --binary-architecture <arch> Set output arch, when input is arch-less\n\
520 -F --target <bfdname> Set both input and output format to <bfdname>\n\
521 --debugging Convert debugging information, if possible\n\
522 -p --preserve-dates Copy modified/access timestamps to the output\n"));
523 if (DEFAULT_AR_DETERMINISTIC)
524 fprintf (stream, _("\
525 -D --enable-deterministic-archives\n\
526 Produce deterministic output when stripping archives (default)\n\
527 -U --disable-deterministic-archives\n\
528 Disable -D behavior\n"));
529 else
530 fprintf (stream, _("\
531 -D --enable-deterministic-archives\n\
532 Produce deterministic output when stripping archives\n\
533 -U --disable-deterministic-archives\n\
534 Disable -D behavior (default)\n"));
535 fprintf (stream, _("\
536 -j --only-section <name> Only copy section <name> into the output\n\
537 --add-gnu-debuglink=<file> Add section .gnu_debuglink linking to <file>\n\
538 -R --remove-section <name> Remove section <name> from the output\n\
539 -S --strip-all Remove all symbol and relocation information\n\
540 -g --strip-debug Remove all debugging symbols & sections\n\
541 --strip-dwo Remove all DWO sections\n\
542 --strip-unneeded Remove all symbols not needed by relocations\n\
543 -N --strip-symbol <name> Do not copy symbol <name>\n\
544 --strip-unneeded-symbol <name>\n\
545 Do not copy symbol <name> unless needed by\n\
546 relocations\n\
547 --only-keep-debug Strip everything but the debug information\n\
548 --extract-dwo Copy only DWO sections\n\
549 --extract-symbol Remove section contents but keep symbols\n\
550 -K --keep-symbol <name> Do not strip symbol <name>\n\
551 --keep-file-symbols Do not strip file symbol(s)\n\
552 --localize-hidden Turn all ELF hidden symbols into locals\n\
553 -L --localize-symbol <name> Force symbol <name> to be marked as a local\n\
554 --globalize-symbol <name> Force symbol <name> to be marked as a global\n\
555 -G --keep-global-symbol <name> Localize all symbols except <name>\n\
556 -W --weaken-symbol <name> Force symbol <name> to be marked as a weak\n\
557 --weaken Force all global symbols to be marked as weak\n\
558 -w --wildcard Permit wildcard in symbol comparison\n\
559 -x --discard-all Remove all non-global symbols\n\
560 -X --discard-locals Remove any compiler-generated symbols\n\
561 -i --interleave[=<number>] Only copy N out of every <number> bytes\n\
562 --interleave-width <number> Set N for --interleave\n\
563 -b --byte <num> Select byte <num> in every interleaved block\n\
564 --gap-fill <val> Fill gaps between sections with <val>\n\
565 --pad-to <addr> Pad the last section up to address <addr>\n\
566 --set-start <addr> Set the start address to <addr>\n\
567 {--change-start|--adjust-start} <incr>\n\
568 Add <incr> to the start address\n\
569 {--change-addresses|--adjust-vma} <incr>\n\
570 Add <incr> to LMA, VMA and start addresses\n\
571 {--change-section-address|--adjust-section-vma} <name>{=|+|-}<val>\n\
572 Change LMA and VMA of section <name> by <val>\n\
573 --change-section-lma <name>{=|+|-}<val>\n\
574 Change the LMA of section <name> by <val>\n\
575 --change-section-vma <name>{=|+|-}<val>\n\
576 Change the VMA of section <name> by <val>\n\
577 {--[no-]change-warnings|--[no-]adjust-warnings}\n\
578 Warn if a named section does not exist\n\
579 --set-section-flags <name>=<flags>\n\
580 Set section <name>'s properties to <flags>\n\
581 --add-section <name>=<file> Add section <name> found in <file> to output\n\
582 --update-section <name>=<file>\n\
583 Update contents of section <name> with\n\
584 contents found in <file>\n\
585 --dump-section <name>=<file> Dump the contents of section <name> into <file>\n\
586 --rename-section <old>=<new>[,<flags>] Rename section <old> to <new>\n\
587 --long-section-names {enable|disable|keep}\n\
588 Handle long section names in Coff objects.\n\
589 --change-leading-char Force output format's leading character style\n\
590 --remove-leading-char Remove leading character from global symbols\n\
591 --reverse-bytes=<num> Reverse <num> bytes at a time, in output sections with content\n\
592 --redefine-sym <old>=<new> Redefine symbol name <old> to <new>\n\
593 --redefine-syms <file> --redefine-sym for all symbol pairs \n\
594 listed in <file>\n\
595 --srec-len <number> Restrict the length of generated Srecords\n\
596 --srec-forceS3 Restrict the type of generated Srecords to S3\n\
597 --strip-symbols <file> -N for all symbols listed in <file>\n\
598 --strip-unneeded-symbols <file>\n\
599 --strip-unneeded-symbol for all symbols listed\n\
600 in <file>\n\
601 --keep-symbols <file> -K for all symbols listed in <file>\n\
602 --localize-symbols <file> -L for all symbols listed in <file>\n\
603 --globalize-symbols <file> --globalize-symbol for all in <file>\n\
604 --keep-global-symbols <file> -G for all symbols listed in <file>\n\
605 --weaken-symbols <file> -W for all symbols listed in <file>\n\
606 --add-symbol <name>=[<section>:]<value>[,<flags>] Add a symbol\n\
607 --alt-machine-code <index> Use the target's <index>'th alternative machine\n\
608 --writable-text Mark the output text as writable\n\
609 --readonly-text Make the output text write protected\n\
610 --pure Mark the output file as demand paged\n\
611 --impure Mark the output file as impure\n\
612 --prefix-symbols <prefix> Add <prefix> to start of every symbol name\n\
613 --prefix-sections <prefix> Add <prefix> to start of every section name\n\
614 --prefix-alloc-sections <prefix>\n\
615 Add <prefix> to start of every allocatable\n\
616 section name\n\
617 --file-alignment <num> Set PE file alignment to <num>\n\
618 --heap <reserve>[,<commit>] Set PE reserve/commit heap to <reserve>/\n\
619 <commit>\n\
620 --image-base <address> Set PE image base to <address>\n\
621 --section-alignment <num> Set PE section alignment to <num>\n\
622 --stack <reserve>[,<commit>] Set PE reserve/commit stack to <reserve>/\n\
623 <commit>\n\
624 --subsystem <name>[:<version>]\n\
625 Set PE subsystem to <name> [& <version>]\n\
626 --compress-debug-sections[={none|zlib|zlib-gnu|zlib-gabi}]\n\
627 Compress DWARF debug sections using zlib\n\
628 --decompress-debug-sections Decompress DWARF debug sections using zlib\n\
629 -v --verbose List all object files modified\n\
630 @<file> Read options from <file>\n\
631 -V --version Display this program's version number\n\
632 -h --help Display this output\n\
633 --info List object formats & architectures supported\n\
634 "));
635 list_supported_targets (program_name, stream);
636 if (REPORT_BUGS_TO[0] && exit_status == 0)
637 fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
638 exit (exit_status);
639 }
640
641 static void
642 strip_usage (FILE *stream, int exit_status)
643 {
644 fprintf (stream, _("Usage: %s <option(s)> in-file(s)\n"), program_name);
645 fprintf (stream, _(" Removes symbols and sections from files\n"));
646 fprintf (stream, _(" The options are:\n"));
647 fprintf (stream, _("\
648 -I --input-target=<bfdname> Assume input file is in format <bfdname>\n\
649 -O --output-target=<bfdname> Create an output file in format <bfdname>\n\
650 -F --target=<bfdname> Set both input and output format to <bfdname>\n\
651 -p --preserve-dates Copy modified/access timestamps to the output\n\
652 "));
653 if (DEFAULT_AR_DETERMINISTIC)
654 fprintf (stream, _("\
655 -D --enable-deterministic-archives\n\
656 Produce deterministic output when stripping archives (default)\n\
657 -U --disable-deterministic-archives\n\
658 Disable -D behavior\n"));
659 else
660 fprintf (stream, _("\
661 -D --enable-deterministic-archives\n\
662 Produce deterministic output when stripping archives\n\
663 -U --disable-deterministic-archives\n\
664 Disable -D behavior (default)\n"));
665 fprintf (stream, _("\
666 -R --remove-section=<name> Also remove section <name> from the output\n\
667 -s --strip-all Remove all symbol and relocation information\n\
668 -g -S -d --strip-debug Remove all debugging symbols & sections\n\
669 --strip-dwo Remove all DWO sections\n\
670 --strip-unneeded Remove all symbols not needed by relocations\n\
671 --only-keep-debug Strip everything but the debug information\n\
672 -N --strip-symbol=<name> Do not copy symbol <name>\n\
673 -K --keep-symbol=<name> Do not strip symbol <name>\n\
674 --keep-file-symbols Do not strip file symbol(s)\n\
675 -w --wildcard Permit wildcard in symbol comparison\n\
676 -x --discard-all Remove all non-global symbols\n\
677 -X --discard-locals Remove any compiler-generated symbols\n\
678 -v --verbose List all object files modified\n\
679 -V --version Display this program's version number\n\
680 -h --help Display this output\n\
681 --info List object formats & architectures supported\n\
682 -o <file> Place stripped output into <file>\n\
683 "));
684
685 list_supported_targets (program_name, stream);
686 if (REPORT_BUGS_TO[0] && exit_status == 0)
687 fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
688 exit (exit_status);
689 }
690
691 /* Parse section flags into a flagword, with a fatal error if the
692 string can't be parsed. */
693
694 static flagword
695 parse_flags (const char *s)
696 {
697 flagword ret;
698 const char *snext;
699 int len;
700
701 ret = SEC_NO_FLAGS;
702
703 do
704 {
705 snext = strchr (s, ',');
706 if (snext == NULL)
707 len = strlen (s);
708 else
709 {
710 len = snext - s;
711 ++snext;
712 }
713
714 if (0) ;
715 #define PARSE_FLAG(fname,fval) \
716 else if (strncasecmp (fname, s, len) == 0) ret |= fval
717 PARSE_FLAG ("alloc", SEC_ALLOC);
718 PARSE_FLAG ("load", SEC_LOAD);
719 PARSE_FLAG ("noload", SEC_NEVER_LOAD);
720 PARSE_FLAG ("readonly", SEC_READONLY);
721 PARSE_FLAG ("debug", SEC_DEBUGGING);
722 PARSE_FLAG ("code", SEC_CODE);
723 PARSE_FLAG ("data", SEC_DATA);
724 PARSE_FLAG ("rom", SEC_ROM);
725 PARSE_FLAG ("share", SEC_COFF_SHARED);
726 PARSE_FLAG ("contents", SEC_HAS_CONTENTS);
727 PARSE_FLAG ("merge", SEC_MERGE);
728 PARSE_FLAG ("strings", SEC_STRINGS);
729 #undef PARSE_FLAG
730 else
731 {
732 char *copy;
733
734 copy = (char *) xmalloc (len + 1);
735 strncpy (copy, s, len);
736 copy[len] = '\0';
737 non_fatal (_("unrecognized section flag `%s'"), copy);
738 fatal (_("supported flags: %s"),
739 "alloc, load, noload, readonly, debug, code, data, rom, share, contents, merge, strings");
740 }
741
742 s = snext;
743 }
744 while (s != NULL);
745
746 return ret;
747 }
748
749 /* Parse symbol flags into a flagword, with a fatal error if the
750 string can't be parsed. */
751
752 static flagword
753 parse_symflags (const char *s, char **other)
754 {
755 flagword ret;
756 const char *snext;
757 int len;
758
759 ret = BSF_NO_FLAGS;
760
761 do
762 {
763 snext = strchr (s, ',');
764 if (snext == NULL)
765 len = strlen (s);
766 else
767 {
768 len = snext - s;
769 ++snext;
770 }
771
772 #define PARSE_FLAG(fname,fval) \
773 else if (len == (int) sizeof fname - 1 && strncasecmp (fname, s, len) == 0) \
774 ret |= fval
775
776 #define PARSE_OTHER(fname,fval) \
777 else if (len >= (int) sizeof fname && strncasecmp (fname, s, sizeof fname - 1) == 0) \
778 fval = xstrndup (s + sizeof fname - 1, len - sizeof fname + 1)
779
780 if (0) ;
781 PARSE_FLAG ("local", BSF_LOCAL);
782 PARSE_FLAG ("global", BSF_GLOBAL);
783 PARSE_FLAG ("export", BSF_EXPORT);
784 PARSE_FLAG ("debug", BSF_DEBUGGING);
785 PARSE_FLAG ("function", BSF_FUNCTION);
786 PARSE_FLAG ("weak", BSF_WEAK);
787 PARSE_FLAG ("section", BSF_SECTION_SYM);
788 PARSE_FLAG ("constructor", BSF_CONSTRUCTOR);
789 PARSE_FLAG ("warning", BSF_WARNING);
790 PARSE_FLAG ("indirect", BSF_INDIRECT);
791 PARSE_FLAG ("file", BSF_FILE);
792 PARSE_FLAG ("object", BSF_OBJECT);
793 PARSE_FLAG ("synthetic", BSF_SYNTHETIC);
794 PARSE_FLAG ("indirect-function", BSF_GNU_INDIRECT_FUNCTION | BSF_FUNCTION);
795 PARSE_FLAG ("unique-object", BSF_GNU_UNIQUE | BSF_OBJECT);
796 PARSE_OTHER ("before=", *other);
797
798 #undef PARSE_FLAG
799 #undef PARSE_OTHER
800 else
801 {
802 char *copy;
803
804 copy = (char *) xmalloc (len + 1);
805 strncpy (copy, s, len);
806 copy[len] = '\0';
807 non_fatal (_("unrecognized symbol flag `%s'"), copy);
808 fatal (_("supported flags: %s"),
809 "local, global, export, debug, function, weak, section, "
810 "constructor, warning, indirect, file, object, synthetic, "
811 "indirect-function, unique-object, before=<othersym>");
812 }
813
814 s = snext;
815 }
816 while (s != NULL);
817
818 return ret;
819 }
820
821 /* Find and optionally add an entry in the change_sections list.
822
823 We need to be careful in how we match section names because of the support
824 for wildcard characters. For example suppose that the user has invoked
825 objcopy like this:
826
827 --set-section-flags .debug_*=debug
828 --set-section-flags .debug_str=readonly,debug
829 --change-section-address .debug_*ranges=0x1000
830
831 With the idea that all debug sections will receive the DEBUG flag, the
832 .debug_str section will also receive the READONLY flag and the
833 .debug_ranges and .debug_aranges sections will have their address set to
834 0x1000. (This may not make much sense, but it is just an example).
835
836 When adding the section name patterns to the section list we need to make
837 sure that previous entries do not match with the new entry, unless the
838 match is exact. (In which case we assume that the user is overriding
839 the previous entry with the new context).
840
841 When matching real section names to the section list we make use of the
842 wildcard characters, but we must do so in context. Eg if we are setting
843 section addresses then we match for .debug_ranges but not for .debug_info.
844
845 Finally, if ADD is false and we do find a match, we mark the section list
846 entry as used. */
847
848 static struct section_list *
849 find_section_list (const char *name, bfd_boolean add, unsigned int context)
850 {
851 struct section_list *p;
852
853 /* assert ((context & ((1 << 7) - 1)) != 0); */
854
855 for (p = change_sections; p != NULL; p = p->next)
856 {
857 if (add)
858 {
859 if (strcmp (p->pattern, name) == 0)
860 {
861 /* Check for context conflicts. */
862 if (((p->context & SECTION_CONTEXT_REMOVE)
863 && (context & SECTION_CONTEXT_COPY))
864 || ((context & SECTION_CONTEXT_REMOVE)
865 && (p->context & SECTION_CONTEXT_COPY)))
866 fatal (_("error: %s both copied and removed"), name);
867
868 if (((p->context & SECTION_CONTEXT_SET_VMA)
869 && (context & SECTION_CONTEXT_ALTER_VMA))
870 || ((context & SECTION_CONTEXT_SET_VMA)
871 && (context & SECTION_CONTEXT_ALTER_VMA)))
872 fatal (_("error: %s both sets and alters VMA"), name);
873
874 if (((p->context & SECTION_CONTEXT_SET_LMA)
875 && (context & SECTION_CONTEXT_ALTER_LMA))
876 || ((context & SECTION_CONTEXT_SET_LMA)
877 && (context & SECTION_CONTEXT_ALTER_LMA)))
878 fatal (_("error: %s both sets and alters LMA"), name);
879
880 /* Extend the context. */
881 p->context |= context;
882 return p;
883 }
884 }
885 /* If we are not adding a new name/pattern then
886 only check for a match if the context applies. */
887 else if ((p->context & context)
888 /* We could check for the presence of wildchar characters
889 first and choose between calling strcmp and fnmatch,
890 but is that really worth it ? */
891 && fnmatch (p->pattern, name, 0) == 0)
892 {
893 p->used = TRUE;
894 return p;
895 }
896 }
897
898 if (! add)
899 return NULL;
900
901 p = (struct section_list *) xmalloc (sizeof (struct section_list));
902 p->pattern = name;
903 p->used = FALSE;
904 p->context = context;
905 p->vma_val = 0;
906 p->lma_val = 0;
907 p->flags = 0;
908 p->next = change_sections;
909 change_sections = p;
910
911 return p;
912 }
913
914 /* There is htab_hash_string but no htab_eq_string. Makes sense. */
915
916 static int
917 eq_string (const void *s1, const void *s2)
918 {
919 return strcmp ((const char *) s1, (const char *) s2) == 0;
920 }
921
922 static htab_t
923 create_symbol_htab (void)
924 {
925 return htab_create_alloc (16, htab_hash_string, eq_string, NULL, xcalloc, free);
926 }
927
928 static void
929 create_symbol_htabs (void)
930 {
931 strip_specific_htab = create_symbol_htab ();
932 strip_unneeded_htab = create_symbol_htab ();
933 keep_specific_htab = create_symbol_htab ();
934 localize_specific_htab = create_symbol_htab ();
935 globalize_specific_htab = create_symbol_htab ();
936 keepglobal_specific_htab = create_symbol_htab ();
937 weaken_specific_htab = create_symbol_htab ();
938 }
939
940 /* Add a symbol to strip_specific_list. */
941
942 static void
943 add_specific_symbol (const char *name, htab_t htab)
944 {
945 *htab_find_slot (htab, name, INSERT) = (char *) name;
946 }
947
948 /* Add symbols listed in `filename' to strip_specific_list. */
949
950 #define IS_WHITESPACE(c) ((c) == ' ' || (c) == '\t')
951 #define IS_LINE_TERMINATOR(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
952
953 static void
954 add_specific_symbols (const char *filename, htab_t htab)
955 {
956 off_t size;
957 FILE * f;
958 char * line;
959 char * buffer;
960 unsigned int line_count;
961
962 size = get_file_size (filename);
963 if (size == 0)
964 {
965 status = 1;
966 return;
967 }
968
969 buffer = (char *) xmalloc (size + 2);
970 f = fopen (filename, FOPEN_RT);
971 if (f == NULL)
972 fatal (_("cannot open '%s': %s"), filename, strerror (errno));
973
974 if (fread (buffer, 1, size, f) == 0 || ferror (f))
975 fatal (_("%s: fread failed"), filename);
976
977 fclose (f);
978 buffer [size] = '\n';
979 buffer [size + 1] = '\0';
980
981 line_count = 1;
982
983 for (line = buffer; * line != '\0'; line ++)
984 {
985 char * eol;
986 char * name;
987 char * name_end;
988 int finished = FALSE;
989
990 for (eol = line;; eol ++)
991 {
992 switch (* eol)
993 {
994 case '\n':
995 * eol = '\0';
996 /* Cope with \n\r. */
997 if (eol[1] == '\r')
998 ++ eol;
999 finished = TRUE;
1000 break;
1001
1002 case '\r':
1003 * eol = '\0';
1004 /* Cope with \r\n. */
1005 if (eol[1] == '\n')
1006 ++ eol;
1007 finished = TRUE;
1008 break;
1009
1010 case 0:
1011 finished = TRUE;
1012 break;
1013
1014 case '#':
1015 /* Line comment, Terminate the line here, in case a
1016 name is present and then allow the rest of the
1017 loop to find the real end of the line. */
1018 * eol = '\0';
1019 break;
1020
1021 default:
1022 break;
1023 }
1024
1025 if (finished)
1026 break;
1027 }
1028
1029 /* A name may now exist somewhere between 'line' and 'eol'.
1030 Strip off leading whitespace and trailing whitespace,
1031 then add it to the list. */
1032 for (name = line; IS_WHITESPACE (* name); name ++)
1033 ;
1034 for (name_end = name;
1035 (! IS_WHITESPACE (* name_end))
1036 && (! IS_LINE_TERMINATOR (* name_end));
1037 name_end ++)
1038 ;
1039
1040 if (! IS_LINE_TERMINATOR (* name_end))
1041 {
1042 char * extra;
1043
1044 for (extra = name_end + 1; IS_WHITESPACE (* extra); extra ++)
1045 ;
1046
1047 if (! IS_LINE_TERMINATOR (* extra))
1048 non_fatal (_("%s:%d: Ignoring rubbish found on this line"),
1049 filename, line_count);
1050 }
1051
1052 * name_end = '\0';
1053
1054 if (name_end > name)
1055 add_specific_symbol (name, htab);
1056
1057 /* Advance line pointer to end of line. The 'eol ++' in the for
1058 loop above will then advance us to the start of the next line. */
1059 line = eol;
1060 line_count ++;
1061 }
1062 }
1063
1064 /* See whether a symbol should be stripped or kept
1065 based on strip_specific_list and keep_symbols. */
1066
1067 static int
1068 is_specified_symbol_predicate (void **slot, void *data)
1069 {
1070 struct is_specified_symbol_predicate_data *d =
1071 (struct is_specified_symbol_predicate_data *) data;
1072 const char *slot_name = (char *) *slot;
1073
1074 if (*slot_name != '!')
1075 {
1076 if (! fnmatch (slot_name, d->name, 0))
1077 {
1078 d->found = TRUE;
1079 /* Continue traversal, there might be a non-match rule. */
1080 return 1;
1081 }
1082 }
1083 else
1084 {
1085 if (! fnmatch (slot_name + 1, d->name, 0))
1086 {
1087 d->found = FALSE;
1088 /* Stop traversal. */
1089 return 0;
1090 }
1091 }
1092
1093 /* Continue traversal. */
1094 return 1;
1095 }
1096
1097 static bfd_boolean
1098 is_specified_symbol (const char *name, htab_t htab)
1099 {
1100 if (wildcard)
1101 {
1102 struct is_specified_symbol_predicate_data data;
1103
1104 data.name = name;
1105 data.found = FALSE;
1106
1107 htab_traverse (htab, is_specified_symbol_predicate, &data);
1108
1109 return data.found;
1110 }
1111
1112 return htab_find (htab, name) != NULL;
1113 }
1114
1115 /* Return a pointer to the symbol used as a signature for GROUP. */
1116
1117 static asymbol *
1118 group_signature (asection *group)
1119 {
1120 bfd *abfd = group->owner;
1121 Elf_Internal_Shdr *ghdr;
1122
1123 if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
1124 return NULL;
1125
1126 ghdr = &elf_section_data (group)->this_hdr;
1127 if (ghdr->sh_link < elf_numsections (abfd))
1128 {
1129 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1130 Elf_Internal_Shdr *symhdr = elf_elfsections (abfd) [ghdr->sh_link];
1131
1132 if (symhdr->sh_type == SHT_SYMTAB
1133 && ghdr->sh_info < symhdr->sh_size / bed->s->sizeof_sym)
1134 return isympp[ghdr->sh_info - 1];
1135 }
1136 return NULL;
1137 }
1138
1139 /* Return TRUE if the section is a DWO section. */
1140
1141 static bfd_boolean
1142 is_dwo_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1143 {
1144 const char *name = bfd_get_section_name (abfd, sec);
1145 int len = strlen (name);
1146
1147 return strncmp (name + len - 4, ".dwo", 4) == 0;
1148 }
1149
1150 /* Return TRUE if section SEC is in the update list. */
1151
1152 static bfd_boolean
1153 is_update_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1154 {
1155 if (update_sections != NULL)
1156 {
1157 struct section_add *pupdate;
1158
1159 for (pupdate = update_sections;
1160 pupdate != NULL;
1161 pupdate = pupdate->next)
1162 {
1163 if (strcmp (sec->name, pupdate->name) == 0)
1164 return TRUE;
1165 }
1166 }
1167
1168 return FALSE;
1169 }
1170
1171 /* See if a non-group section is being removed. */
1172
1173 static bfd_boolean
1174 is_strip_section_1 (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1175 {
1176 if (sections_removed || sections_copied)
1177 {
1178 struct section_list *p;
1179 struct section_list *q;
1180
1181 p = find_section_list (bfd_get_section_name (abfd, sec), FALSE,
1182 SECTION_CONTEXT_REMOVE);
1183 q = find_section_list (bfd_get_section_name (abfd, sec), FALSE,
1184 SECTION_CONTEXT_COPY);
1185
1186 if (p && q)
1187 fatal (_("error: section %s matches both remove and copy options"),
1188 bfd_get_section_name (abfd, sec));
1189 if (p && is_update_section (abfd, sec))
1190 fatal (_("error: section %s matches both update and remove options"),
1191 bfd_get_section_name (abfd, sec));
1192
1193 if (p != NULL)
1194 return TRUE;
1195 if (sections_copied && q == NULL)
1196 return TRUE;
1197 }
1198
1199 if ((bfd_get_section_flags (abfd, sec) & SEC_DEBUGGING) != 0)
1200 {
1201 if (strip_symbols == STRIP_DEBUG
1202 || strip_symbols == STRIP_UNNEEDED
1203 || strip_symbols == STRIP_ALL
1204 || discard_locals == LOCALS_ALL
1205 || convert_debugging)
1206 {
1207 /* By default we don't want to strip .reloc section.
1208 This section has for pe-coff special meaning. See
1209 pe-dll.c file in ld, and peXXigen.c in bfd for details. */
1210 if (strcmp (bfd_get_section_name (abfd, sec), ".reloc") != 0)
1211 return TRUE;
1212 }
1213
1214 if (strip_symbols == STRIP_DWO)
1215 return is_dwo_section (abfd, sec);
1216
1217 if (strip_symbols == STRIP_NONDEBUG)
1218 return FALSE;
1219 }
1220
1221 if (strip_symbols == STRIP_NONDWO)
1222 return !is_dwo_section (abfd, sec);
1223
1224 return FALSE;
1225 }
1226
1227 /* See if a section is being removed. */
1228
1229 static bfd_boolean
1230 is_strip_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1231 {
1232 if (is_strip_section_1 (abfd, sec))
1233 return TRUE;
1234
1235 if ((bfd_get_section_flags (abfd, sec) & SEC_GROUP) != 0)
1236 {
1237 asymbol *gsym;
1238 const char *gname;
1239 asection *elt, *first;
1240
1241 /* PR binutils/3181
1242 If we are going to strip the group signature symbol, then
1243 strip the group section too. */
1244 gsym = group_signature (sec);
1245 if (gsym != NULL)
1246 gname = gsym->name;
1247 else
1248 gname = sec->name;
1249 if ((strip_symbols == STRIP_ALL
1250 && !is_specified_symbol (gname, keep_specific_htab))
1251 || is_specified_symbol (gname, strip_specific_htab))
1252 return TRUE;
1253
1254 /* Remove the group section if all members are removed. */
1255 first = elt = elf_next_in_group (sec);
1256 while (elt != NULL)
1257 {
1258 if (!is_strip_section_1 (abfd, elt))
1259 return FALSE;
1260 elt = elf_next_in_group (elt);
1261 if (elt == first)
1262 break;
1263 }
1264
1265 return TRUE;
1266 }
1267
1268 return FALSE;
1269 }
1270
1271 static bfd_boolean
1272 is_nondebug_keep_contents_section (bfd *ibfd, asection *isection)
1273 {
1274 /* Always keep ELF note sections. */
1275 if (ibfd->xvec->flavour == bfd_target_elf_flavour)
1276 return (elf_section_type (isection) == SHT_NOTE);
1277
1278 /* Always keep the .buildid section for PE/COFF.
1279
1280 Strictly, this should be written "always keep the section storing the debug
1281 directory", but that may be the .text section for objects produced by some
1282 tools, which it is not sensible to keep. */
1283 if (ibfd->xvec->flavour == bfd_target_coff_flavour)
1284 return (strcmp (bfd_get_section_name (ibfd, isection), ".buildid") == 0);
1285
1286 return FALSE;
1287 }
1288
1289 /* Return true if SYM is a hidden symbol. */
1290
1291 static bfd_boolean
1292 is_hidden_symbol (asymbol *sym)
1293 {
1294 elf_symbol_type *elf_sym;
1295
1296 elf_sym = elf_symbol_from (sym->the_bfd, sym);
1297 if (elf_sym != NULL)
1298 switch (ELF_ST_VISIBILITY (elf_sym->internal_elf_sym.st_other))
1299 {
1300 case STV_HIDDEN:
1301 case STV_INTERNAL:
1302 return TRUE;
1303 }
1304 return FALSE;
1305 }
1306
1307 static bfd_boolean
1308 need_sym_before (struct addsym_node **node, const char *sym)
1309 {
1310 int count;
1311 struct addsym_node *ptr = add_sym_list;
1312
1313 /* 'othersym' symbols are at the front of the list. */
1314 for (count = 0; count < add_symbols; count++)
1315 {
1316 if (!ptr->othersym)
1317 break;
1318 else if (strcmp (ptr->othersym, sym) == 0)
1319 {
1320 free (ptr->othersym);
1321 ptr->othersym = ""; /* Empty name is hopefully never a valid symbol name. */
1322 *node = ptr;
1323 return TRUE;
1324 }
1325 ptr = ptr->next;
1326 }
1327 return FALSE;
1328 }
1329
1330 static asymbol *
1331 create_new_symbol (struct addsym_node *ptr, bfd *obfd)
1332 {
1333 asymbol *sym = bfd_make_empty_symbol(obfd);
1334
1335 bfd_asymbol_name(sym) = ptr->symdef;
1336 sym->value = ptr->symval;
1337 sym->flags = ptr->flags;
1338 if (ptr->section)
1339 {
1340 asection *sec = bfd_get_section_by_name (obfd, ptr->section);
1341 if (!sec)
1342 fatal (_("Section %s not found"), ptr->section);
1343 sym->section = sec;
1344 }
1345 else
1346 sym->section = bfd_abs_section_ptr;
1347 return sym;
1348 }
1349
1350 /* Choose which symbol entries to copy; put the result in OSYMS.
1351 We don't copy in place, because that confuses the relocs.
1352 Return the number of symbols to print. */
1353
1354 static unsigned int
1355 filter_symbols (bfd *abfd, bfd *obfd, asymbol **osyms,
1356 asymbol **isyms, long symcount)
1357 {
1358 asymbol **from = isyms, **to = osyms;
1359 long src_count = 0, dst_count = 0;
1360 int relocatable = (abfd->flags & (EXEC_P | DYNAMIC)) == 0;
1361
1362 for (; src_count < symcount; src_count++)
1363 {
1364 asymbol *sym = from[src_count];
1365 flagword flags = sym->flags;
1366 char *name = (char *) bfd_asymbol_name (sym);
1367 bfd_boolean keep;
1368 bfd_boolean used_in_reloc = FALSE;
1369 bfd_boolean undefined;
1370 bfd_boolean rem_leading_char;
1371 bfd_boolean add_leading_char;
1372
1373 undefined = bfd_is_und_section (bfd_get_section (sym));
1374
1375 if (add_sym_list)
1376 {
1377 struct addsym_node *ptr;
1378
1379 if (need_sym_before (&ptr, name))
1380 to[dst_count++] = create_new_symbol (ptr, obfd);
1381 }
1382
1383 if (redefine_sym_list)
1384 {
1385 char *old_name, *new_name;
1386
1387 old_name = (char *) bfd_asymbol_name (sym);
1388 new_name = (char *) lookup_sym_redefinition (old_name);
1389 bfd_asymbol_name (sym) = new_name;
1390 name = new_name;
1391 }
1392
1393 /* Check if we will remove the current leading character. */
1394 rem_leading_char =
1395 (name[0] == bfd_get_symbol_leading_char (abfd))
1396 && (change_leading_char
1397 || (remove_leading_char
1398 && ((flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1399 || undefined
1400 || bfd_is_com_section (bfd_get_section (sym)))));
1401
1402 /* Check if we will add a new leading character. */
1403 add_leading_char =
1404 change_leading_char
1405 && (bfd_get_symbol_leading_char (obfd) != '\0')
1406 && (bfd_get_symbol_leading_char (abfd) == '\0'
1407 || (name[0] == bfd_get_symbol_leading_char (abfd)));
1408
1409 /* Short circuit for change_leading_char if we can do it in-place. */
1410 if (rem_leading_char && add_leading_char && !prefix_symbols_string)
1411 {
1412 name[0] = bfd_get_symbol_leading_char (obfd);
1413 bfd_asymbol_name (sym) = name;
1414 rem_leading_char = FALSE;
1415 add_leading_char = FALSE;
1416 }
1417
1418 /* Remove leading char. */
1419 if (rem_leading_char)
1420 bfd_asymbol_name (sym) = ++name;
1421
1422 /* Add new leading char and/or prefix. */
1423 if (add_leading_char || prefix_symbols_string)
1424 {
1425 char *n, *ptr;
1426
1427 ptr = n = (char *) xmalloc (1 + strlen (prefix_symbols_string)
1428 + strlen (name) + 1);
1429 if (add_leading_char)
1430 *ptr++ = bfd_get_symbol_leading_char (obfd);
1431
1432 if (prefix_symbols_string)
1433 {
1434 strcpy (ptr, prefix_symbols_string);
1435 ptr += strlen (prefix_symbols_string);
1436 }
1437
1438 strcpy (ptr, name);
1439 bfd_asymbol_name (sym) = n;
1440 name = n;
1441 }
1442
1443 if (strip_symbols == STRIP_ALL)
1444 keep = FALSE;
1445 else if ((flags & BSF_KEEP) != 0 /* Used in relocation. */
1446 || ((flags & BSF_SECTION_SYM) != 0
1447 && ((*bfd_get_section (sym)->symbol_ptr_ptr)->flags
1448 & BSF_KEEP) != 0))
1449 {
1450 keep = TRUE;
1451 used_in_reloc = TRUE;
1452 }
1453 else if (relocatable /* Relocatable file. */
1454 && ((flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1455 || bfd_is_com_section (bfd_get_section (sym))))
1456 keep = TRUE;
1457 else if (bfd_decode_symclass (sym) == 'I')
1458 /* Global symbols in $idata sections need to be retained
1459 even if relocatable is FALSE. External users of the
1460 library containing the $idata section may reference these
1461 symbols. */
1462 keep = TRUE;
1463 else if ((flags & BSF_GLOBAL) != 0 /* Global symbol. */
1464 || (flags & BSF_WEAK) != 0
1465 || undefined
1466 || bfd_is_com_section (bfd_get_section (sym)))
1467 keep = strip_symbols != STRIP_UNNEEDED;
1468 else if ((flags & BSF_DEBUGGING) != 0) /* Debugging symbol. */
1469 keep = (strip_symbols != STRIP_DEBUG
1470 && strip_symbols != STRIP_UNNEEDED
1471 && ! convert_debugging);
1472 else if (bfd_coff_get_comdat_section (abfd, bfd_get_section (sym)))
1473 /* COMDAT sections store special information in local
1474 symbols, so we cannot risk stripping any of them. */
1475 keep = TRUE;
1476 else /* Local symbol. */
1477 keep = (strip_symbols != STRIP_UNNEEDED
1478 && (discard_locals != LOCALS_ALL
1479 && (discard_locals != LOCALS_START_L
1480 || ! bfd_is_local_label (abfd, sym))));
1481
1482 if (keep && is_specified_symbol (name, strip_specific_htab))
1483 {
1484 /* There are multiple ways to set 'keep' above, but if it
1485 was the relocatable symbol case, then that's an error. */
1486 if (used_in_reloc)
1487 {
1488 non_fatal (_("not stripping symbol `%s' because it is named in a relocation"), name);
1489 status = 1;
1490 }
1491 else
1492 keep = FALSE;
1493 }
1494
1495 if (keep
1496 && !(flags & BSF_KEEP)
1497 && is_specified_symbol (name, strip_unneeded_htab))
1498 keep = FALSE;
1499
1500 if (!keep
1501 && ((keep_file_symbols && (flags & BSF_FILE))
1502 || is_specified_symbol (name, keep_specific_htab)))
1503 keep = TRUE;
1504
1505 if (keep && is_strip_section (abfd, bfd_get_section (sym)))
1506 keep = FALSE;
1507
1508 if (keep)
1509 {
1510 if ((flags & BSF_GLOBAL) != 0
1511 && (weaken || is_specified_symbol (name, weaken_specific_htab)))
1512 {
1513 sym->flags &= ~ BSF_GLOBAL;
1514 sym->flags |= BSF_WEAK;
1515 }
1516
1517 if (!undefined
1518 && (flags & (BSF_GLOBAL | BSF_WEAK))
1519 && (is_specified_symbol (name, localize_specific_htab)
1520 || (htab_elements (keepglobal_specific_htab) != 0
1521 && ! is_specified_symbol (name, keepglobal_specific_htab))
1522 || (localize_hidden && is_hidden_symbol (sym))))
1523 {
1524 sym->flags &= ~ (BSF_GLOBAL | BSF_WEAK);
1525 sym->flags |= BSF_LOCAL;
1526 }
1527
1528 if (!undefined
1529 && (flags & BSF_LOCAL)
1530 && is_specified_symbol (name, globalize_specific_htab))
1531 {
1532 sym->flags &= ~ BSF_LOCAL;
1533 sym->flags |= BSF_GLOBAL;
1534 }
1535
1536 to[dst_count++] = sym;
1537 }
1538 }
1539 if (add_sym_list)
1540 {
1541 struct addsym_node *ptr = add_sym_list;
1542
1543 for (src_count = 0; src_count < add_symbols; src_count++)
1544 {
1545 if (ptr->othersym)
1546 {
1547 if (strcmp (ptr->othersym, ""))
1548 fatal (_("'before=%s' not found"), ptr->othersym);
1549 }
1550 else
1551 to[dst_count++] = create_new_symbol (ptr, obfd);
1552
1553 ptr = ptr->next;
1554 }
1555 }
1556
1557 to[dst_count] = NULL;
1558
1559 return dst_count;
1560 }
1561
1562 /* Find the redefined name of symbol SOURCE. */
1563
1564 static const char *
1565 lookup_sym_redefinition (const char *source)
1566 {
1567 struct redefine_node *list;
1568
1569 for (list = redefine_sym_list; list != NULL; list = list->next)
1570 if (strcmp (source, list->source) == 0)
1571 return list->target;
1572
1573 return source;
1574 }
1575
1576 /* Add a node to a symbol redefine list. */
1577
1578 static void
1579 redefine_list_append (const char *cause, const char *source, const char *target)
1580 {
1581 struct redefine_node **p;
1582 struct redefine_node *list;
1583 struct redefine_node *new_node;
1584
1585 for (p = &redefine_sym_list; (list = *p) != NULL; p = &list->next)
1586 {
1587 if (strcmp (source, list->source) == 0)
1588 fatal (_("%s: Multiple redefinition of symbol \"%s\""),
1589 cause, source);
1590
1591 if (strcmp (target, list->target) == 0)
1592 fatal (_("%s: Symbol \"%s\" is target of more than one redefinition"),
1593 cause, target);
1594 }
1595
1596 new_node = (struct redefine_node *) xmalloc (sizeof (struct redefine_node));
1597
1598 new_node->source = strdup (source);
1599 new_node->target = strdup (target);
1600 new_node->next = NULL;
1601
1602 *p = new_node;
1603 }
1604
1605 /* Handle the --redefine-syms option. Read lines containing "old new"
1606 from the file, and add them to the symbol redefine list. */
1607
1608 static void
1609 add_redefine_syms_file (const char *filename)
1610 {
1611 FILE *file;
1612 char *buf;
1613 size_t bufsize;
1614 size_t len;
1615 size_t outsym_off;
1616 int c, lineno;
1617
1618 file = fopen (filename, "r");
1619 if (file == NULL)
1620 fatal (_("couldn't open symbol redefinition file %s (error: %s)"),
1621 filename, strerror (errno));
1622
1623 bufsize = 100;
1624 buf = (char *) xmalloc (bufsize + 1 /* For the terminating NUL. */);
1625
1626 lineno = 1;
1627 c = getc (file);
1628 len = 0;
1629 outsym_off = 0;
1630 while (c != EOF)
1631 {
1632 /* Collect the input symbol name. */
1633 while (! IS_WHITESPACE (c) && ! IS_LINE_TERMINATOR (c) && c != EOF)
1634 {
1635 if (c == '#')
1636 goto comment;
1637 buf[len++] = c;
1638 if (len >= bufsize)
1639 {
1640 bufsize *= 2;
1641 buf = (char *) xrealloc (buf, bufsize + 1);
1642 }
1643 c = getc (file);
1644 }
1645 buf[len++] = '\0';
1646 if (c == EOF)
1647 break;
1648
1649 /* Eat white space between the symbol names. */
1650 while (IS_WHITESPACE (c))
1651 c = getc (file);
1652 if (c == '#' || IS_LINE_TERMINATOR (c))
1653 goto comment;
1654 if (c == EOF)
1655 break;
1656
1657 /* Collect the output symbol name. */
1658 outsym_off = len;
1659 while (! IS_WHITESPACE (c) && ! IS_LINE_TERMINATOR (c) && c != EOF)
1660 {
1661 if (c == '#')
1662 goto comment;
1663 buf[len++] = c;
1664 if (len >= bufsize)
1665 {
1666 bufsize *= 2;
1667 buf = (char *) xrealloc (buf, bufsize + 1);
1668 }
1669 c = getc (file);
1670 }
1671 buf[len++] = '\0';
1672 if (c == EOF)
1673 break;
1674
1675 /* Eat white space at end of line. */
1676 while (! IS_LINE_TERMINATOR(c) && c != EOF && IS_WHITESPACE (c))
1677 c = getc (file);
1678 if (c == '#')
1679 goto comment;
1680 /* Handle \r\n. */
1681 if ((c == '\r' && (c = getc (file)) == '\n')
1682 || c == '\n' || c == EOF)
1683 {
1684 end_of_line:
1685 /* Append the redefinition to the list. */
1686 if (buf[0] != '\0')
1687 redefine_list_append (filename, &buf[0], &buf[outsym_off]);
1688
1689 lineno++;
1690 len = 0;
1691 outsym_off = 0;
1692 if (c == EOF)
1693 break;
1694 c = getc (file);
1695 continue;
1696 }
1697 else
1698 fatal (_("%s:%d: garbage found at end of line"), filename, lineno);
1699 comment:
1700 if (len != 0 && (outsym_off == 0 || outsym_off == len))
1701 fatal (_("%s:%d: missing new symbol name"), filename, lineno);
1702 buf[len++] = '\0';
1703
1704 /* Eat the rest of the line and finish it. */
1705 while (c != '\n' && c != EOF)
1706 c = getc (file);
1707 goto end_of_line;
1708 }
1709
1710 if (len != 0)
1711 fatal (_("%s:%d: premature end of file"), filename, lineno);
1712
1713 free (buf);
1714 }
1715
1716 /* Copy unkown object file IBFD onto OBFD.
1717 Returns TRUE upon success, FALSE otherwise. */
1718
1719 static bfd_boolean
1720 copy_unknown_object (bfd *ibfd, bfd *obfd)
1721 {
1722 char *cbuf;
1723 int tocopy;
1724 long ncopied;
1725 long size;
1726 struct stat buf;
1727
1728 if (bfd_stat_arch_elt (ibfd, &buf) != 0)
1729 {
1730 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1731 return FALSE;
1732 }
1733
1734 size = buf.st_size;
1735 if (size < 0)
1736 {
1737 non_fatal (_("stat returns negative size for `%s'"),
1738 bfd_get_archive_filename (ibfd));
1739 return FALSE;
1740 }
1741
1742 if (bfd_seek (ibfd, (file_ptr) 0, SEEK_SET) != 0)
1743 {
1744 bfd_nonfatal (bfd_get_archive_filename (ibfd));
1745 return FALSE;
1746 }
1747
1748 if (verbose)
1749 printf (_("copy from `%s' [unknown] to `%s' [unknown]\n"),
1750 bfd_get_archive_filename (ibfd), bfd_get_filename (obfd));
1751
1752 cbuf = (char *) xmalloc (BUFSIZE);
1753 ncopied = 0;
1754 while (ncopied < size)
1755 {
1756 tocopy = size - ncopied;
1757 if (tocopy > BUFSIZE)
1758 tocopy = BUFSIZE;
1759
1760 if (bfd_bread (cbuf, (bfd_size_type) tocopy, ibfd)
1761 != (bfd_size_type) tocopy)
1762 {
1763 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1764 free (cbuf);
1765 return FALSE;
1766 }
1767
1768 if (bfd_bwrite (cbuf, (bfd_size_type) tocopy, obfd)
1769 != (bfd_size_type) tocopy)
1770 {
1771 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
1772 free (cbuf);
1773 return FALSE;
1774 }
1775
1776 ncopied += tocopy;
1777 }
1778
1779 /* We should at least to be able to read it back when copying an
1780 unknown object in an archive. */
1781 chmod (bfd_get_filename (obfd), buf.st_mode | S_IRUSR);
1782 free (cbuf);
1783 return TRUE;
1784 }
1785
1786 /* Copy object file IBFD onto OBFD.
1787 Returns TRUE upon success, FALSE otherwise. */
1788
1789 static bfd_boolean
1790 copy_object (bfd *ibfd, bfd *obfd, const bfd_arch_info_type *input_arch)
1791 {
1792 bfd_vma start;
1793 long symcount;
1794 asection **osections = NULL;
1795 asection *gnu_debuglink_section = NULL;
1796 bfd_size_type *gaps = NULL;
1797 bfd_size_type max_gap = 0;
1798 long symsize;
1799 void *dhandle;
1800 enum bfd_architecture iarch;
1801 unsigned int imach;
1802 unsigned int c, i;
1803
1804 if (ibfd->xvec->byteorder != obfd->xvec->byteorder
1805 && ibfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN
1806 && obfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN)
1807 {
1808 /* PR 17636: Call non-fatal so that we return to our parent who
1809 may need to tidy temporary files. */
1810 non_fatal (_("Unable to change endianness of input file(s)"));
1811 return FALSE;
1812 }
1813
1814 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
1815 {
1816 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
1817 return FALSE;
1818 }
1819
1820 if (ibfd->sections == NULL)
1821 {
1822 non_fatal (_("error: the input file '%s' has no sections"),
1823 bfd_get_archive_filename (ibfd));
1824 return FALSE;
1825 }
1826
1827 if ((do_debug_sections & compress) != 0
1828 && do_debug_sections != compress
1829 && ibfd->xvec->flavour != bfd_target_elf_flavour)
1830 {
1831 non_fatal (_("--compress-debug-sections=[zlib|zlib-gnu|zlib-gabi] is unsupported on `%s'"),
1832 bfd_get_archive_filename (ibfd));
1833 return FALSE;
1834 }
1835
1836 if (verbose)
1837 printf (_("copy from `%s' [%s] to `%s' [%s]\n"),
1838 bfd_get_archive_filename (ibfd), bfd_get_target (ibfd),
1839 bfd_get_filename (obfd), bfd_get_target (obfd));
1840
1841 if (extract_symbol)
1842 start = 0;
1843 else
1844 {
1845 if (set_start_set)
1846 start = set_start;
1847 else
1848 start = bfd_get_start_address (ibfd);
1849 start += change_start;
1850 }
1851
1852 /* Neither the start address nor the flags
1853 need to be set for a core file. */
1854 if (bfd_get_format (obfd) != bfd_core)
1855 {
1856 flagword flags;
1857
1858 flags = bfd_get_file_flags (ibfd);
1859 flags |= bfd_flags_to_set;
1860 flags &= ~bfd_flags_to_clear;
1861 flags &= bfd_applicable_file_flags (obfd);
1862
1863 if (strip_symbols == STRIP_ALL)
1864 flags &= ~HAS_RELOC;
1865
1866 if (!bfd_set_start_address (obfd, start)
1867 || !bfd_set_file_flags (obfd, flags))
1868 {
1869 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1870 return FALSE;
1871 }
1872 }
1873
1874 /* Copy architecture of input file to output file. */
1875 iarch = bfd_get_arch (ibfd);
1876 imach = bfd_get_mach (ibfd);
1877 if (input_arch)
1878 {
1879 if (bfd_get_arch_info (ibfd) == NULL
1880 || bfd_get_arch_info (ibfd)->arch == bfd_arch_unknown)
1881 {
1882 iarch = input_arch->arch;
1883 imach = input_arch->mach;
1884 }
1885 else
1886 non_fatal (_("Input file `%s' ignores binary architecture parameter."),
1887 bfd_get_archive_filename (ibfd));
1888 }
1889 if (!bfd_set_arch_mach (obfd, iarch, imach)
1890 && (ibfd->target_defaulted
1891 || bfd_get_arch (ibfd) != bfd_get_arch (obfd)))
1892 {
1893 if (bfd_get_arch (ibfd) == bfd_arch_unknown)
1894 non_fatal (_("Unable to recognise the format of the input file `%s'"),
1895 bfd_get_archive_filename (ibfd));
1896 else
1897 non_fatal (_("Output file cannot represent architecture `%s'"),
1898 bfd_printable_arch_mach (bfd_get_arch (ibfd),
1899 bfd_get_mach (ibfd)));
1900 return FALSE;
1901 }
1902
1903 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
1904 {
1905 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1906 return FALSE;
1907 }
1908
1909 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
1910 && bfd_pei_p (obfd))
1911 {
1912 /* Set up PE parameters. */
1913 pe_data_type *pe = pe_data (obfd);
1914
1915 /* Copy PE parameters before changing them. */
1916 if (ibfd->xvec->flavour == bfd_target_coff_flavour
1917 && bfd_pei_p (ibfd))
1918 pe->pe_opthdr = pe_data (ibfd)->pe_opthdr;
1919
1920 if (pe_file_alignment != (bfd_vma) -1)
1921 pe->pe_opthdr.FileAlignment = pe_file_alignment;
1922 else
1923 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
1924
1925 if (pe_heap_commit != (bfd_vma) -1)
1926 pe->pe_opthdr.SizeOfHeapCommit = pe_heap_commit;
1927
1928 if (pe_heap_reserve != (bfd_vma) -1)
1929 pe->pe_opthdr.SizeOfHeapCommit = pe_heap_reserve;
1930
1931 if (pe_image_base != (bfd_vma) -1)
1932 pe->pe_opthdr.ImageBase = pe_image_base;
1933
1934 if (pe_section_alignment != (bfd_vma) -1)
1935 pe->pe_opthdr.SectionAlignment = pe_section_alignment;
1936 else
1937 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
1938
1939 if (pe_stack_commit != (bfd_vma) -1)
1940 pe->pe_opthdr.SizeOfStackCommit = pe_stack_commit;
1941
1942 if (pe_stack_reserve != (bfd_vma) -1)
1943 pe->pe_opthdr.SizeOfStackCommit = pe_stack_reserve;
1944
1945 if (pe_subsystem != -1)
1946 pe->pe_opthdr.Subsystem = pe_subsystem;
1947
1948 if (pe_major_subsystem_version != -1)
1949 pe->pe_opthdr.MajorSubsystemVersion = pe_major_subsystem_version;
1950
1951 if (pe_minor_subsystem_version != -1)
1952 pe->pe_opthdr.MinorSubsystemVersion = pe_minor_subsystem_version;
1953
1954 if (pe_file_alignment > pe_section_alignment)
1955 {
1956 char file_alignment[20], section_alignment[20];
1957
1958 sprintf_vma (file_alignment, pe_file_alignment);
1959 sprintf_vma (section_alignment, pe_section_alignment);
1960 non_fatal (_("warning: file alignment (0x%s) > section alignment (0x%s)"),
1961
1962 file_alignment, section_alignment);
1963 }
1964 }
1965
1966 if (isympp)
1967 free (isympp);
1968
1969 if (osympp != isympp)
1970 free (osympp);
1971
1972 isympp = NULL;
1973 osympp = NULL;
1974
1975 symsize = bfd_get_symtab_upper_bound (ibfd);
1976 if (symsize < 0)
1977 {
1978 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1979 return FALSE;
1980 }
1981
1982 osympp = isympp = (asymbol **) xmalloc (symsize);
1983 symcount = bfd_canonicalize_symtab (ibfd, isympp);
1984 if (symcount < 0)
1985 {
1986 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1987 return FALSE;
1988 }
1989 /* PR 17512: file: d6323821
1990 If the symbol table could not be loaded do not pretend that we have
1991 any symbols. This trips us up later on when we load the relocs. */
1992 if (symcount == 0)
1993 {
1994 free (isympp);
1995 osympp = isympp = NULL;
1996 }
1997
1998 /* BFD mandates that all output sections be created and sizes set before
1999 any output is done. Thus, we traverse all sections multiple times. */
2000 bfd_map_over_sections (ibfd, setup_section, obfd);
2001
2002 if (!extract_symbol)
2003 setup_bfd_headers (ibfd, obfd);
2004
2005 if (add_sections != NULL)
2006 {
2007 struct section_add *padd;
2008 struct section_list *pset;
2009
2010 for (padd = add_sections; padd != NULL; padd = padd->next)
2011 {
2012 flagword flags;
2013
2014 pset = find_section_list (padd->name, FALSE,
2015 SECTION_CONTEXT_SET_FLAGS);
2016 if (pset != NULL)
2017 flags = pset->flags | SEC_HAS_CONTENTS;
2018 else
2019 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DATA;
2020
2021 /* bfd_make_section_with_flags() does not return very helpful
2022 error codes, so check for the most likely user error first. */
2023 if (bfd_get_section_by_name (obfd, padd->name))
2024 {
2025 bfd_nonfatal_message (NULL, obfd, NULL,
2026 _("can't add section '%s'"), padd->name);
2027 return FALSE;
2028 }
2029 else
2030 {
2031 /* We use LINKER_CREATED here so that the backend hooks
2032 will create any special section type information,
2033 instead of presuming we know what we're doing merely
2034 because we set the flags. */
2035 padd->section = bfd_make_section_with_flags
2036 (obfd, padd->name, flags | SEC_LINKER_CREATED);
2037 if (padd->section == NULL)
2038 {
2039 bfd_nonfatal_message (NULL, obfd, NULL,
2040 _("can't create section `%s'"),
2041 padd->name);
2042 return FALSE;
2043 }
2044 }
2045
2046 if (! bfd_set_section_size (obfd, padd->section, padd->size))
2047 {
2048 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2049 return FALSE;
2050 }
2051
2052 pset = find_section_list (padd->name, FALSE,
2053 SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA);
2054 if (pset != NULL
2055 && ! bfd_set_section_vma (obfd, padd->section, pset->vma_val))
2056 {
2057 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2058 return FALSE;
2059 }
2060
2061 pset = find_section_list (padd->name, FALSE,
2062 SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA);
2063 if (pset != NULL)
2064 {
2065 padd->section->lma = pset->lma_val;
2066
2067 if (! bfd_set_section_alignment
2068 (obfd, padd->section,
2069 bfd_section_alignment (obfd, padd->section)))
2070 {
2071 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2072 return FALSE;
2073 }
2074 }
2075 }
2076 }
2077
2078 if (update_sections != NULL)
2079 {
2080 struct section_add *pupdate;
2081
2082 for (pupdate = update_sections;
2083 pupdate != NULL;
2084 pupdate = pupdate->next)
2085 {
2086 asection *osec;
2087
2088 pupdate->section = bfd_get_section_by_name (ibfd, pupdate->name);
2089 if (pupdate->section == NULL)
2090 {
2091 non_fatal (_("error: %s not found, can't be updated"), pupdate->name);
2092 return FALSE;
2093 }
2094
2095 osec = pupdate->section->output_section;
2096 if (! bfd_set_section_size (obfd, osec, pupdate->size))
2097 {
2098 bfd_nonfatal_message (NULL, obfd, osec, NULL);
2099 return FALSE;
2100 }
2101 }
2102 }
2103
2104 if (dump_sections != NULL)
2105 {
2106 struct section_add * pdump;
2107
2108 for (pdump = dump_sections; pdump != NULL; pdump = pdump->next)
2109 {
2110 asection * sec;
2111
2112 sec = bfd_get_section_by_name (ibfd, pdump->name);
2113 if (sec == NULL)
2114 {
2115 bfd_nonfatal_message (NULL, ibfd, NULL,
2116 _("can't dump section '%s' - it does not exist"),
2117 pdump->name);
2118 continue;
2119 }
2120
2121 if ((bfd_get_section_flags (ibfd, sec) & SEC_HAS_CONTENTS) == 0)
2122 {
2123 bfd_nonfatal_message (NULL, ibfd, sec,
2124 _("can't dump section - it has no contents"));
2125 continue;
2126 }
2127
2128 bfd_size_type size = bfd_get_section_size (sec);
2129 if (size == 0)
2130 {
2131 bfd_nonfatal_message (NULL, ibfd, sec,
2132 _("can't dump section - it is empty"));
2133 continue;
2134 }
2135
2136 FILE * f;
2137 f = fopen (pdump->filename, FOPEN_WB);
2138 if (f == NULL)
2139 {
2140 bfd_nonfatal_message (pdump->filename, NULL, NULL,
2141 _("could not open section dump file"));
2142 continue;
2143 }
2144
2145 bfd_byte * contents = xmalloc (size);
2146 if (bfd_get_section_contents (ibfd, sec, contents, 0, size))
2147 {
2148 if (fwrite (contents, 1, size, f) != size)
2149 {
2150 non_fatal (_("error writing section contents to %s (error: %s)"),
2151 pdump->filename,
2152 strerror (errno));
2153 return FALSE;
2154 }
2155 }
2156 else
2157 bfd_nonfatal_message (NULL, ibfd, sec,
2158 _("could not retrieve section contents"));
2159
2160 fclose (f);
2161 free (contents);
2162 }
2163 }
2164
2165 if (gnu_debuglink_filename != NULL)
2166 {
2167 /* PR 15125: Give a helpful warning message if
2168 the debuglink section already exists, and
2169 allow the rest of the copy to complete. */
2170 if (bfd_get_section_by_name (obfd, ".gnu_debuglink"))
2171 {
2172 non_fatal (_("%s: debuglink section already exists"),
2173 bfd_get_filename (obfd));
2174 gnu_debuglink_filename = NULL;
2175 }
2176 else
2177 {
2178 gnu_debuglink_section = bfd_create_gnu_debuglink_section
2179 (obfd, gnu_debuglink_filename);
2180
2181 if (gnu_debuglink_section == NULL)
2182 {
2183 bfd_nonfatal_message (NULL, obfd, NULL,
2184 _("cannot create debug link section `%s'"),
2185 gnu_debuglink_filename);
2186 return FALSE;
2187 }
2188
2189 /* Special processing for PE format files. We
2190 have no way to distinguish PE from COFF here. */
2191 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour)
2192 {
2193 bfd_vma debuglink_vma;
2194 asection * highest_section;
2195 asection * sec;
2196
2197 /* The PE spec requires that all sections be adjacent and sorted
2198 in ascending order of VMA. It also specifies that debug
2199 sections should be last. This is despite the fact that debug
2200 sections are not loaded into memory and so in theory have no
2201 use for a VMA.
2202
2203 This means that the debuglink section must be given a non-zero
2204 VMA which makes it contiguous with other debug sections. So
2205 walk the current section list, find the section with the
2206 highest VMA and start the debuglink section after that one. */
2207 for (sec = obfd->sections, highest_section = NULL;
2208 sec != NULL;
2209 sec = sec->next)
2210 if (sec->vma > 0
2211 && (highest_section == NULL
2212 || sec->vma > highest_section->vma))
2213 highest_section = sec;
2214
2215 if (highest_section)
2216 debuglink_vma = BFD_ALIGN (highest_section->vma
2217 + highest_section->size,
2218 /* FIXME: We ought to be using
2219 COFF_PAGE_SIZE here or maybe
2220 bfd_get_section_alignment() (if it
2221 was set) but since this is for PE
2222 and we know the required alignment
2223 it is easier just to hard code it. */
2224 0x1000);
2225 else
2226 /* Umm, not sure what to do in this case. */
2227 debuglink_vma = 0x1000;
2228
2229 bfd_set_section_vma (obfd, gnu_debuglink_section, debuglink_vma);
2230 }
2231 }
2232 }
2233
2234 c = bfd_count_sections (obfd);
2235 if (c != 0
2236 && (gap_fill_set || pad_to_set))
2237 {
2238 asection **set;
2239
2240 /* We must fill in gaps between the sections and/or we must pad
2241 the last section to a specified address. We do this by
2242 grabbing a list of the sections, sorting them by VMA, and
2243 increasing the section sizes as required to fill the gaps.
2244 We write out the gap contents below. */
2245
2246 osections = (asection **) xmalloc (c * sizeof (asection *));
2247 set = osections;
2248 bfd_map_over_sections (obfd, get_sections, &set);
2249
2250 qsort (osections, c, sizeof (asection *), compare_section_lma);
2251
2252 gaps = (bfd_size_type *) xmalloc (c * sizeof (bfd_size_type));
2253 memset (gaps, 0, c * sizeof (bfd_size_type));
2254
2255 if (gap_fill_set)
2256 {
2257 for (i = 0; i < c - 1; i++)
2258 {
2259 flagword flags;
2260 bfd_size_type size;
2261 bfd_vma gap_start, gap_stop;
2262
2263 flags = bfd_get_section_flags (obfd, osections[i]);
2264 if ((flags & SEC_HAS_CONTENTS) == 0
2265 || (flags & SEC_LOAD) == 0)
2266 continue;
2267
2268 size = bfd_section_size (obfd, osections[i]);
2269 gap_start = bfd_section_lma (obfd, osections[i]) + size;
2270 gap_stop = bfd_section_lma (obfd, osections[i + 1]);
2271 if (gap_start < gap_stop)
2272 {
2273 if (! bfd_set_section_size (obfd, osections[i],
2274 size + (gap_stop - gap_start)))
2275 {
2276 bfd_nonfatal_message (NULL, obfd, osections[i],
2277 _("Can't fill gap after section"));
2278 status = 1;
2279 break;
2280 }
2281 gaps[i] = gap_stop - gap_start;
2282 if (max_gap < gap_stop - gap_start)
2283 max_gap = gap_stop - gap_start;
2284 }
2285 }
2286 }
2287
2288 if (pad_to_set)
2289 {
2290 bfd_vma lma;
2291 bfd_size_type size;
2292
2293 lma = bfd_section_lma (obfd, osections[c - 1]);
2294 size = bfd_section_size (obfd, osections[c - 1]);
2295 if (lma + size < pad_to)
2296 {
2297 if (! bfd_set_section_size (obfd, osections[c - 1],
2298 pad_to - lma))
2299 {
2300 bfd_nonfatal_message (NULL, obfd, osections[c - 1],
2301 _("can't add padding"));
2302 status = 1;
2303 }
2304 else
2305 {
2306 gaps[c - 1] = pad_to - (lma + size);
2307 if (max_gap < pad_to - (lma + size))
2308 max_gap = pad_to - (lma + size);
2309 }
2310 }
2311 }
2312 }
2313
2314 /* Symbol filtering must happen after the output sections
2315 have been created, but before their contents are set. */
2316 dhandle = NULL;
2317 if (convert_debugging)
2318 dhandle = read_debugging_info (ibfd, isympp, symcount, FALSE);
2319
2320 if (strip_symbols == STRIP_DEBUG
2321 || strip_symbols == STRIP_ALL
2322 || strip_symbols == STRIP_UNNEEDED
2323 || strip_symbols == STRIP_NONDEBUG
2324 || strip_symbols == STRIP_DWO
2325 || strip_symbols == STRIP_NONDWO
2326 || discard_locals != LOCALS_UNDEF
2327 || localize_hidden
2328 || htab_elements (strip_specific_htab) != 0
2329 || htab_elements (keep_specific_htab) != 0
2330 || htab_elements (localize_specific_htab) != 0
2331 || htab_elements (globalize_specific_htab) != 0
2332 || htab_elements (keepglobal_specific_htab) != 0
2333 || htab_elements (weaken_specific_htab) != 0
2334 || prefix_symbols_string
2335 || sections_removed
2336 || sections_copied
2337 || convert_debugging
2338 || change_leading_char
2339 || remove_leading_char
2340 || redefine_sym_list
2341 || weaken
2342 || add_symbols)
2343 {
2344 /* Mark symbols used in output relocations so that they
2345 are kept, even if they are local labels or static symbols.
2346
2347 Note we iterate over the input sections examining their
2348 relocations since the relocations for the output sections
2349 haven't been set yet. mark_symbols_used_in_relocations will
2350 ignore input sections which have no corresponding output
2351 section. */
2352 if (strip_symbols != STRIP_ALL)
2353 bfd_map_over_sections (ibfd,
2354 mark_symbols_used_in_relocations,
2355 isympp);
2356 osympp = (asymbol **) xmalloc ((symcount + add_symbols + 1) * sizeof (asymbol *));
2357 symcount = filter_symbols (ibfd, obfd, osympp, isympp, symcount);
2358 }
2359
2360 if (convert_debugging && dhandle != NULL)
2361 {
2362 if (! write_debugging_info (obfd, dhandle, &symcount, &osympp))
2363 {
2364 status = 1;
2365 return FALSE;
2366 }
2367 }
2368
2369 bfd_set_symtab (obfd, osympp, symcount);
2370
2371 /* This has to happen before section positions are set. */
2372 bfd_map_over_sections (ibfd, copy_relocations_in_section, obfd);
2373
2374 /* This has to happen after the symbol table has been set. */
2375 bfd_map_over_sections (ibfd, copy_section, obfd);
2376
2377 if (add_sections != NULL)
2378 {
2379 struct section_add *padd;
2380
2381 for (padd = add_sections; padd != NULL; padd = padd->next)
2382 {
2383 if (! bfd_set_section_contents (obfd, padd->section, padd->contents,
2384 0, padd->size))
2385 {
2386 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2387 return FALSE;
2388 }
2389 }
2390 }
2391
2392 if (update_sections != NULL)
2393 {
2394 struct section_add *pupdate;
2395
2396 for (pupdate = update_sections;
2397 pupdate != NULL;
2398 pupdate = pupdate->next)
2399 {
2400 asection *osec;
2401
2402 osec = pupdate->section->output_section;
2403 if (! bfd_set_section_contents (obfd, osec, pupdate->contents,
2404 0, pupdate->size))
2405 {
2406 bfd_nonfatal_message (NULL, obfd, osec, NULL);
2407 return FALSE;
2408 }
2409 }
2410 }
2411
2412 if (gnu_debuglink_filename != NULL)
2413 {
2414 if (! bfd_fill_in_gnu_debuglink_section
2415 (obfd, gnu_debuglink_section, gnu_debuglink_filename))
2416 {
2417 bfd_nonfatal_message (NULL, obfd, NULL,
2418 _("cannot fill debug link section `%s'"),
2419 gnu_debuglink_filename);
2420 return FALSE;
2421 }
2422 }
2423
2424 if (gap_fill_set || pad_to_set)
2425 {
2426 bfd_byte *buf;
2427
2428 /* Fill in the gaps. */
2429 if (max_gap > 8192)
2430 max_gap = 8192;
2431 buf = (bfd_byte *) xmalloc (max_gap);
2432 memset (buf, gap_fill, max_gap);
2433
2434 c = bfd_count_sections (obfd);
2435 for (i = 0; i < c; i++)
2436 {
2437 if (gaps[i] != 0)
2438 {
2439 bfd_size_type left;
2440 file_ptr off;
2441
2442 left = gaps[i];
2443 off = bfd_section_size (obfd, osections[i]) - left;
2444
2445 while (left > 0)
2446 {
2447 bfd_size_type now;
2448
2449 if (left > 8192)
2450 now = 8192;
2451 else
2452 now = left;
2453
2454 if (! bfd_set_section_contents (obfd, osections[i], buf,
2455 off, now))
2456 {
2457 bfd_nonfatal_message (NULL, obfd, osections[i], NULL);
2458 free (buf);
2459 return FALSE;
2460 }
2461
2462 left -= now;
2463 off += now;
2464 }
2465 }
2466 }
2467 free (buf);
2468 }
2469
2470 /* Allow the BFD backend to copy any private data it understands
2471 from the input BFD to the output BFD. This is done last to
2472 permit the routine to look at the filtered symbol table, which is
2473 important for the ECOFF code at least. */
2474 if (! bfd_copy_private_bfd_data (ibfd, obfd))
2475 {
2476 bfd_nonfatal_message (NULL, obfd, NULL,
2477 _("error copying private BFD data"));
2478 return FALSE;
2479 }
2480
2481 /* Switch to the alternate machine code. We have to do this at the
2482 very end, because we only initialize the header when we create
2483 the first section. */
2484 if (use_alt_mach_code != 0)
2485 {
2486 if (! bfd_alt_mach_code (obfd, use_alt_mach_code))
2487 {
2488 non_fatal (_("this target does not support %lu alternative machine codes"),
2489 use_alt_mach_code);
2490 if (bfd_get_flavour (obfd) == bfd_target_elf_flavour)
2491 {
2492 non_fatal (_("treating that number as an absolute e_machine value instead"));
2493 elf_elfheader (obfd)->e_machine = use_alt_mach_code;
2494 }
2495 else
2496 non_fatal (_("ignoring the alternative value"));
2497 }
2498 }
2499
2500 return TRUE;
2501 }
2502
2503 /* Read each archive element in turn from IBFD, copy the
2504 contents to temp file, and keep the temp file handle.
2505 If 'force_output_target' is TRUE then make sure that
2506 all elements in the new archive are of the type
2507 'output_target'. */
2508
2509 static void
2510 copy_archive (bfd *ibfd, bfd *obfd, const char *output_target,
2511 bfd_boolean force_output_target,
2512 const bfd_arch_info_type *input_arch)
2513 {
2514 struct name_list
2515 {
2516 struct name_list *next;
2517 const char *name;
2518 bfd *obfd;
2519 } *list, *l;
2520 bfd **ptr = &obfd->archive_head;
2521 bfd *this_element;
2522 char *dir;
2523 const char *filename;
2524
2525 /* Make a temp directory to hold the contents. */
2526 dir = make_tempdir (bfd_get_filename (obfd));
2527 if (dir == NULL)
2528 fatal (_("cannot create tempdir for archive copying (error: %s)"),
2529 strerror (errno));
2530
2531 if (strip_symbols == STRIP_ALL)
2532 obfd->has_armap = FALSE;
2533 else
2534 obfd->has_armap = ibfd->has_armap;
2535 obfd->is_thin_archive = ibfd->is_thin_archive;
2536
2537 if (deterministic)
2538 obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
2539
2540 list = NULL;
2541
2542 this_element = bfd_openr_next_archived_file (ibfd, NULL);
2543
2544 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
2545 {
2546 status = 1;
2547 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
2548 goto cleanup_and_exit;
2549 }
2550
2551 while (!status && this_element != NULL)
2552 {
2553 char *output_name;
2554 bfd *output_bfd;
2555 bfd *last_element;
2556 struct stat buf;
2557 int stat_status = 0;
2558 bfd_boolean del = TRUE;
2559 bfd_boolean ok_object;
2560
2561 /* PR binutils/17533: Do not allow directory traversal
2562 outside of the current directory tree by archive members. */
2563 if (! is_valid_archive_path (bfd_get_filename (this_element)))
2564 {
2565 non_fatal (_("illegal pathname found in archive member: %s"),
2566 bfd_get_filename (this_element));
2567 status = 1;
2568 goto cleanup_and_exit;
2569 }
2570
2571 /* Create an output file for this member. */
2572 output_name = concat (dir, "/",
2573 bfd_get_filename (this_element), (char *) 0);
2574
2575 /* If the file already exists, make another temp dir. */
2576 if (stat (output_name, &buf) >= 0)
2577 {
2578 output_name = make_tempdir (output_name);
2579 if (output_name == NULL)
2580 {
2581 non_fatal (_("cannot create tempdir for archive copying (error: %s)"),
2582 strerror (errno));
2583 status = 1;
2584 goto cleanup_and_exit;
2585 }
2586
2587 l = (struct name_list *) xmalloc (sizeof (struct name_list));
2588 l->name = output_name;
2589 l->next = list;
2590 l->obfd = NULL;
2591 list = l;
2592 output_name = concat (output_name, "/",
2593 bfd_get_filename (this_element), (char *) 0);
2594 }
2595
2596 if (preserve_dates)
2597 {
2598 stat_status = bfd_stat_arch_elt (this_element, &buf);
2599
2600 if (stat_status != 0)
2601 non_fatal (_("internal stat error on %s"),
2602 bfd_get_filename (this_element));
2603 }
2604
2605 l = (struct name_list *) xmalloc (sizeof (struct name_list));
2606 l->name = output_name;
2607 l->next = list;
2608 l->obfd = NULL;
2609 list = l;
2610
2611 ok_object = bfd_check_format (this_element, bfd_object);
2612 if (!ok_object)
2613 bfd_nonfatal_message (NULL, this_element, NULL,
2614 _("Unable to recognise the format of file"));
2615
2616 /* PR binutils/3110: Cope with archives
2617 containing multiple target types. */
2618 if (force_output_target || !ok_object)
2619 output_bfd = bfd_openw (output_name, output_target);
2620 else
2621 output_bfd = bfd_openw (output_name, bfd_get_target (this_element));
2622
2623 if (output_bfd == NULL)
2624 {
2625 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
2626 status = 1;
2627 goto cleanup_and_exit;
2628 }
2629
2630 if (ok_object)
2631 {
2632 del = !copy_object (this_element, output_bfd, input_arch);
2633
2634 if (del && bfd_get_arch (this_element) == bfd_arch_unknown)
2635 /* Try again as an unknown object file. */
2636 ok_object = FALSE;
2637 else if (!bfd_close (output_bfd))
2638 {
2639 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
2640 /* Error in new object file. Don't change archive. */
2641 status = 1;
2642 }
2643 }
2644
2645 if (!ok_object)
2646 {
2647 del = !copy_unknown_object (this_element, output_bfd);
2648 if (!bfd_close_all_done (output_bfd))
2649 {
2650 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
2651 /* Error in new object file. Don't change archive. */
2652 status = 1;
2653 }
2654 }
2655
2656 if (del)
2657 {
2658 unlink (output_name);
2659 status = 1;
2660 }
2661 else
2662 {
2663 if (preserve_dates && stat_status == 0)
2664 set_times (output_name, &buf);
2665
2666 /* Open the newly output file and attach to our list. */
2667 output_bfd = bfd_openr (output_name, output_target);
2668
2669 l->obfd = output_bfd;
2670
2671 *ptr = output_bfd;
2672 ptr = &output_bfd->archive_next;
2673
2674 last_element = this_element;
2675
2676 this_element = bfd_openr_next_archived_file (ibfd, last_element);
2677
2678 bfd_close (last_element);
2679 }
2680 }
2681 *ptr = NULL;
2682
2683 filename = bfd_get_filename (obfd);
2684 if (!bfd_close (obfd))
2685 {
2686 status = 1;
2687 bfd_nonfatal_message (filename, NULL, NULL, NULL);
2688 }
2689
2690 filename = bfd_get_filename (ibfd);
2691 if (!bfd_close (ibfd))
2692 {
2693 status = 1;
2694 bfd_nonfatal_message (filename, NULL, NULL, NULL);
2695 }
2696
2697 cleanup_and_exit:
2698 /* Delete all the files that we opened. */
2699 for (l = list; l != NULL; l = l->next)
2700 {
2701 if (l->obfd == NULL)
2702 rmdir (l->name);
2703 else
2704 {
2705 bfd_close (l->obfd);
2706 unlink (l->name);
2707 }
2708 }
2709
2710 rmdir (dir);
2711 }
2712
2713 static void
2714 set_long_section_mode (bfd *output_bfd, bfd *input_bfd, enum long_section_name_handling style)
2715 {
2716 /* This is only relevant to Coff targets. */
2717 if (bfd_get_flavour (output_bfd) == bfd_target_coff_flavour)
2718 {
2719 if (style == KEEP
2720 && bfd_get_flavour (input_bfd) == bfd_target_coff_flavour)
2721 style = bfd_coff_long_section_names (input_bfd) ? ENABLE : DISABLE;
2722 bfd_coff_set_long_section_names (output_bfd, style != DISABLE);
2723 }
2724 }
2725
2726 /* The top-level control. */
2727
2728 static void
2729 copy_file (const char *input_filename, const char *output_filename,
2730 const char *input_target, const char *output_target,
2731 const bfd_arch_info_type *input_arch)
2732 {
2733 bfd *ibfd;
2734 char **obj_matching;
2735 char **core_matching;
2736 off_t size = get_file_size (input_filename);
2737
2738 if (size < 1)
2739 {
2740 if (size == 0)
2741 non_fatal (_("error: the input file '%s' is empty"),
2742 input_filename);
2743 status = 1;
2744 return;
2745 }
2746
2747 /* To allow us to do "strip *" without dying on the first
2748 non-object file, failures are nonfatal. */
2749 ibfd = bfd_openr (input_filename, input_target);
2750 if (ibfd == NULL)
2751 {
2752 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
2753 status = 1;
2754 return;
2755 }
2756
2757 switch (do_debug_sections)
2758 {
2759 case compress:
2760 case compress_zlib:
2761 case compress_gnu_zlib:
2762 case compress_gabi_zlib:
2763 ibfd->flags |= BFD_COMPRESS;
2764 /* Don't check if input is ELF here since this information is
2765 only available after bfd_check_format_matches is called. */
2766 if (do_debug_sections != compress_gnu_zlib)
2767 ibfd->flags |= BFD_COMPRESS_GABI;
2768 break;
2769 case decompress:
2770 ibfd->flags |= BFD_DECOMPRESS;
2771 break;
2772 default:
2773 break;
2774 }
2775
2776 if (bfd_check_format (ibfd, bfd_archive))
2777 {
2778 bfd_boolean force_output_target;
2779 bfd *obfd;
2780
2781 /* bfd_get_target does not return the correct value until
2782 bfd_check_format succeeds. */
2783 if (output_target == NULL)
2784 {
2785 output_target = bfd_get_target (ibfd);
2786 force_output_target = FALSE;
2787 }
2788 else
2789 force_output_target = TRUE;
2790
2791 obfd = bfd_openw (output_filename, output_target);
2792 if (obfd == NULL)
2793 {
2794 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
2795 status = 1;
2796 return;
2797 }
2798 /* This is a no-op on non-Coff targets. */
2799 set_long_section_mode (obfd, ibfd, long_section_names);
2800
2801 copy_archive (ibfd, obfd, output_target, force_output_target, input_arch);
2802 }
2803 else if (bfd_check_format_matches (ibfd, bfd_object, &obj_matching))
2804 {
2805 bfd *obfd;
2806 do_copy:
2807
2808 /* bfd_get_target does not return the correct value until
2809 bfd_check_format succeeds. */
2810 if (output_target == NULL)
2811 output_target = bfd_get_target (ibfd);
2812
2813 obfd = bfd_openw (output_filename, output_target);
2814 if (obfd == NULL)
2815 {
2816 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
2817 status = 1;
2818 return;
2819 }
2820 /* This is a no-op on non-Coff targets. */
2821 set_long_section_mode (obfd, ibfd, long_section_names);
2822
2823 if (! copy_object (ibfd, obfd, input_arch))
2824 status = 1;
2825
2826 /* PR 17512: file: 0f15796a.
2827 If the file could not be copied it may not be in a writeable
2828 state. So use bfd_close_all_done to avoid the possibility of
2829 writing uninitialised data into the file. */
2830 if (! (status ? bfd_close_all_done (obfd) : bfd_close (obfd)))
2831 {
2832 status = 1;
2833 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
2834 return;
2835 }
2836
2837 if (!bfd_close (ibfd))
2838 {
2839 status = 1;
2840 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
2841 return;
2842 }
2843 }
2844 else
2845 {
2846 bfd_error_type obj_error = bfd_get_error ();
2847 bfd_error_type core_error;
2848
2849 if (bfd_check_format_matches (ibfd, bfd_core, &core_matching))
2850 {
2851 /* This probably can't happen.. */
2852 if (obj_error == bfd_error_file_ambiguously_recognized)
2853 free (obj_matching);
2854 goto do_copy;
2855 }
2856
2857 core_error = bfd_get_error ();
2858 /* Report the object error in preference to the core error. */
2859 if (obj_error != core_error)
2860 bfd_set_error (obj_error);
2861
2862 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
2863
2864 if (obj_error == bfd_error_file_ambiguously_recognized)
2865 {
2866 list_matching_formats (obj_matching);
2867 free (obj_matching);
2868 }
2869 if (core_error == bfd_error_file_ambiguously_recognized)
2870 {
2871 list_matching_formats (core_matching);
2872 free (core_matching);
2873 }
2874
2875 status = 1;
2876 }
2877 }
2878
2879 /* Add a name to the section renaming list. */
2880
2881 static void
2882 add_section_rename (const char * old_name, const char * new_name,
2883 flagword flags)
2884 {
2885 section_rename * srename;
2886
2887 /* Check for conflicts first. */
2888 for (srename = section_rename_list; srename != NULL; srename = srename->next)
2889 if (strcmp (srename->old_name, old_name) == 0)
2890 {
2891 /* Silently ignore duplicate definitions. */
2892 if (strcmp (srename->new_name, new_name) == 0
2893 && srename->flags == flags)
2894 return;
2895
2896 fatal (_("Multiple renames of section %s"), old_name);
2897 }
2898
2899 srename = (section_rename *) xmalloc (sizeof (* srename));
2900
2901 srename->old_name = old_name;
2902 srename->new_name = new_name;
2903 srename->flags = flags;
2904 srename->next = section_rename_list;
2905
2906 section_rename_list = srename;
2907 }
2908
2909 /* Check the section rename list for a new name of the input section
2910 ISECTION. Return the new name if one is found.
2911 Also set RETURNED_FLAGS to the flags to be used for this section. */
2912
2913 static const char *
2914 find_section_rename (bfd * ibfd ATTRIBUTE_UNUSED, sec_ptr isection,
2915 flagword * returned_flags)
2916 {
2917 const char * old_name = bfd_section_name (ibfd, isection);
2918 section_rename * srename;
2919
2920 /* Default to using the flags of the input section. */
2921 * returned_flags = bfd_get_section_flags (ibfd, isection);
2922
2923 for (srename = section_rename_list; srename != NULL; srename = srename->next)
2924 if (strcmp (srename->old_name, old_name) == 0)
2925 {
2926 if (srename->flags != (flagword) -1)
2927 * returned_flags = srename->flags;
2928
2929 return srename->new_name;
2930 }
2931
2932 return old_name;
2933 }
2934
2935 /* Once each of the sections is copied, we may still need to do some
2936 finalization work for private section headers. Do that here. */
2937
2938 static void
2939 setup_bfd_headers (bfd *ibfd, bfd *obfd)
2940 {
2941 /* Allow the BFD backend to copy any private data it understands
2942 from the input section to the output section. */
2943 if (! bfd_copy_private_header_data (ibfd, obfd))
2944 {
2945 status = 1;
2946 bfd_nonfatal_message (NULL, ibfd, NULL,
2947 _("error in private header data"));
2948 return;
2949 }
2950
2951 /* All went well. */
2952 return;
2953 }
2954
2955 /* Create a section in OBFD with the same
2956 name and attributes as ISECTION in IBFD. */
2957
2958 static void
2959 setup_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
2960 {
2961 bfd *obfd = (bfd *) obfdarg;
2962 struct section_list *p;
2963 sec_ptr osection;
2964 bfd_size_type size;
2965 bfd_vma vma;
2966 bfd_vma lma;
2967 flagword flags;
2968 const char *err;
2969 const char * name;
2970 char *prefix = NULL;
2971 bfd_boolean make_nobits;
2972
2973 if (is_strip_section (ibfd, isection))
2974 return;
2975
2976 /* Get the, possibly new, name of the output section. */
2977 name = find_section_rename (ibfd, isection, & flags);
2978
2979 /* Prefix sections. */
2980 if ((prefix_alloc_sections_string)
2981 && (bfd_get_section_flags (ibfd, isection) & SEC_ALLOC))
2982 prefix = prefix_alloc_sections_string;
2983 else if (prefix_sections_string)
2984 prefix = prefix_sections_string;
2985
2986 if (prefix)
2987 {
2988 char *n;
2989
2990 n = (char *) xmalloc (strlen (prefix) + strlen (name) + 1);
2991 strcpy (n, prefix);
2992 strcat (n, name);
2993 name = n;
2994 }
2995
2996 make_nobits = FALSE;
2997
2998 p = find_section_list (bfd_section_name (ibfd, isection), FALSE,
2999 SECTION_CONTEXT_SET_FLAGS);
3000 if (p != NULL)
3001 flags = p->flags | (flags & (SEC_HAS_CONTENTS | SEC_RELOC));
3002 else if (strip_symbols == STRIP_NONDEBUG
3003 && (flags & (SEC_ALLOC | SEC_GROUP)) != 0
3004 && !is_nondebug_keep_contents_section (ibfd, isection))
3005 {
3006 flags &= ~(SEC_HAS_CONTENTS | SEC_LOAD | SEC_GROUP);
3007 if (obfd->xvec->flavour == bfd_target_elf_flavour)
3008 {
3009 make_nobits = TRUE;
3010
3011 /* Twiddle the input section flags so that it seems to
3012 elf.c:copy_private_bfd_data that section flags have not
3013 changed between input and output sections. This hack
3014 prevents wholesale rewriting of the program headers. */
3015 isection->flags &= ~(SEC_HAS_CONTENTS | SEC_LOAD | SEC_GROUP);
3016 }
3017 }
3018
3019 osection = bfd_make_section_anyway_with_flags (obfd, name, flags);
3020
3021 if (osection == NULL)
3022 {
3023 err = _("failed to create output section");
3024 goto loser;
3025 }
3026
3027 if (make_nobits)
3028 elf_section_type (osection) = SHT_NOBITS;
3029
3030 size = bfd_section_size (ibfd, isection);
3031 size = bfd_convert_section_size (ibfd, isection, obfd, size);
3032 if (copy_byte >= 0)
3033 size = (size + interleave - 1) / interleave * copy_width;
3034 else if (extract_symbol)
3035 size = 0;
3036 if (! bfd_set_section_size (obfd, osection, size))
3037 {
3038 err = _("failed to set size");
3039 goto loser;
3040 }
3041
3042 vma = bfd_section_vma (ibfd, isection);
3043 p = find_section_list (bfd_section_name (ibfd, isection), FALSE,
3044 SECTION_CONTEXT_ALTER_VMA | SECTION_CONTEXT_SET_VMA);
3045 if (p != NULL)
3046 {
3047 if (p->context & SECTION_CONTEXT_SET_VMA)
3048 vma = p->vma_val;
3049 else
3050 vma += p->vma_val;
3051 }
3052 else
3053 vma += change_section_address;
3054
3055 if (! bfd_set_section_vma (obfd, osection, vma))
3056 {
3057 err = _("failed to set vma");
3058 goto loser;
3059 }
3060
3061 lma = isection->lma;
3062 p = find_section_list (bfd_section_name (ibfd, isection), FALSE,
3063 SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_SET_LMA);
3064 if (p != NULL)
3065 {
3066 if (p->context & SECTION_CONTEXT_ALTER_LMA)
3067 lma += p->lma_val;
3068 else
3069 lma = p->lma_val;
3070 }
3071 else
3072 lma += change_section_address;
3073
3074 osection->lma = lma;
3075
3076 /* FIXME: This is probably not enough. If we change the LMA we
3077 may have to recompute the header for the file as well. */
3078 if (!bfd_set_section_alignment (obfd,
3079 osection,
3080 bfd_section_alignment (ibfd, isection)))
3081 {
3082 err = _("failed to set alignment");
3083 goto loser;
3084 }
3085
3086 /* Copy merge entity size. */
3087 osection->entsize = isection->entsize;
3088
3089 /* Copy compress status. */
3090 osection->compress_status = isection->compress_status;
3091
3092 /* This used to be mangle_section; we do here to avoid using
3093 bfd_get_section_by_name since some formats allow multiple
3094 sections with the same name. */
3095 isection->output_section = osection;
3096 isection->output_offset = 0;
3097
3098 if ((isection->flags & SEC_GROUP) != 0)
3099 {
3100 asymbol *gsym = group_signature (isection);
3101
3102 if (gsym != NULL)
3103 {
3104 gsym->flags |= BSF_KEEP;
3105 if (ibfd->xvec->flavour == bfd_target_elf_flavour)
3106 elf_group_id (isection) = gsym;
3107 }
3108 }
3109
3110 /* Allow the BFD backend to copy any private data it understands
3111 from the input section to the output section. */
3112 if (!bfd_copy_private_section_data (ibfd, isection, obfd, osection))
3113 {
3114 err = _("failed to copy private data");
3115 goto loser;
3116 }
3117
3118 /* All went well. */
3119 return;
3120
3121 loser:
3122 status = 1;
3123 bfd_nonfatal_message (NULL, obfd, osection, err);
3124 }
3125
3126 /* Return TRUE if input section ISECTION should be skipped. */
3127
3128 static bfd_boolean
3129 skip_section (bfd *ibfd, sec_ptr isection)
3130 {
3131 sec_ptr osection;
3132 bfd_size_type size;
3133 flagword flags;
3134
3135 /* If we have already failed earlier on,
3136 do not keep on generating complaints now. */
3137 if (status != 0)
3138 return TRUE;
3139
3140 if (extract_symbol)
3141 return TRUE;
3142
3143 if (is_strip_section (ibfd, isection))
3144 return TRUE;
3145
3146 if (is_update_section (ibfd, isection))
3147 return TRUE;
3148
3149 flags = bfd_get_section_flags (ibfd, isection);
3150 if ((flags & SEC_GROUP) != 0)
3151 return TRUE;
3152
3153 osection = isection->output_section;
3154 size = bfd_get_section_size (isection);
3155
3156 if (size == 0 || osection == 0)
3157 return TRUE;
3158
3159 return FALSE;
3160 }
3161
3162 /* Copy relocations in input section ISECTION of IBFD to an output
3163 section with the same name in OBFDARG. If stripping then don't
3164 copy any relocation info. */
3165
3166 static void
3167 copy_relocations_in_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
3168 {
3169 bfd *obfd = (bfd *) obfdarg;
3170 long relsize;
3171 arelent **relpp;
3172 long relcount;
3173 sec_ptr osection;
3174
3175 if (skip_section (ibfd, isection))
3176 return;
3177
3178 osection = isection->output_section;
3179
3180 /* Core files and DWO files do not need to be relocated. */
3181 if (bfd_get_format (obfd) == bfd_core || strip_symbols == STRIP_NONDWO)
3182 relsize = 0;
3183 else
3184 {
3185 relsize = bfd_get_reloc_upper_bound (ibfd, isection);
3186
3187 if (relsize < 0)
3188 {
3189 /* Do not complain if the target does not support relocations. */
3190 if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
3191 relsize = 0;
3192 else
3193 {
3194 status = 1;
3195 bfd_nonfatal_message (NULL, ibfd, isection, NULL);
3196 return;
3197 }
3198 }
3199 }
3200
3201 if (relsize == 0)
3202 {
3203 bfd_set_reloc (obfd, osection, NULL, 0);
3204 osection->flags &= ~SEC_RELOC;
3205 }
3206 else
3207 {
3208 relpp = (arelent **) xmalloc (relsize);
3209 relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, isympp);
3210 if (relcount < 0)
3211 {
3212 status = 1;
3213 bfd_nonfatal_message (NULL, ibfd, isection,
3214 _("relocation count is negative"));
3215 return;
3216 }
3217
3218 if (strip_symbols == STRIP_ALL)
3219 {
3220 /* Remove relocations which are not in
3221 keep_strip_specific_list. */
3222 arelent **temp_relpp;
3223 long temp_relcount = 0;
3224 long i;
3225
3226 temp_relpp = (arelent **) xmalloc (relsize);
3227 for (i = 0; i < relcount; i++)
3228 {
3229 /* PR 17512: file: 9e907e0c. */
3230 if (relpp[i]->sym_ptr_ptr)
3231 if (is_specified_symbol (bfd_asymbol_name (*relpp[i]->sym_ptr_ptr),
3232 keep_specific_htab))
3233 temp_relpp [temp_relcount++] = relpp [i];
3234 }
3235 relcount = temp_relcount;
3236 free (relpp);
3237 relpp = temp_relpp;
3238 }
3239
3240 bfd_set_reloc (obfd, osection, relcount == 0 ? NULL : relpp, relcount);
3241 if (relcount == 0)
3242 {
3243 osection->flags &= ~SEC_RELOC;
3244 free (relpp);
3245 }
3246 }
3247 }
3248
3249 /* Copy the data of input section ISECTION of IBFD
3250 to an output section with the same name in OBFD. */
3251
3252 static void
3253 copy_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
3254 {
3255 bfd *obfd = (bfd *) obfdarg;
3256 struct section_list *p;
3257 sec_ptr osection;
3258 bfd_size_type size;
3259
3260 if (skip_section (ibfd, isection))
3261 return;
3262
3263 osection = isection->output_section;
3264 /* The output SHF_COMPRESSED section size is different from input if
3265 ELF classes of input and output aren't the same. We can't use
3266 the output section size since --interleave will shrink the output
3267 section. Size will be updated if the section is converted. */
3268 size = bfd_get_section_size (isection);
3269
3270 if (bfd_get_section_flags (ibfd, isection) & SEC_HAS_CONTENTS
3271 && bfd_get_section_flags (obfd, osection) & SEC_HAS_CONTENTS)
3272 {
3273 bfd_byte *memhunk = NULL;
3274
3275 if (!bfd_get_full_section_contents (ibfd, isection, &memhunk)
3276 || !bfd_convert_section_contents (ibfd, isection, obfd,
3277 &memhunk, &size))
3278 {
3279 status = 1;
3280 bfd_nonfatal_message (NULL, ibfd, isection, NULL);
3281 return;
3282 }
3283
3284 if (reverse_bytes)
3285 {
3286 /* We don't handle leftover bytes (too many possible behaviors,
3287 and we don't know what the user wants). The section length
3288 must be a multiple of the number of bytes to swap. */
3289 if ((size % reverse_bytes) == 0)
3290 {
3291 unsigned long i, j;
3292 bfd_byte b;
3293
3294 for (i = 0; i < size; i += reverse_bytes)
3295 for (j = 0; j < (unsigned long)(reverse_bytes / 2); j++)
3296 {
3297 bfd_byte *m = (bfd_byte *) memhunk;
3298
3299 b = m[i + j];
3300 m[i + j] = m[(i + reverse_bytes) - (j + 1)];
3301 m[(i + reverse_bytes) - (j + 1)] = b;
3302 }
3303 }
3304 else
3305 /* User must pad the section up in order to do this. */
3306 fatal (_("cannot reverse bytes: length of section %s must be evenly divisible by %d"),
3307 bfd_section_name (ibfd, isection), reverse_bytes);
3308 }
3309
3310 if (copy_byte >= 0)
3311 {
3312 /* Keep only every `copy_byte'th byte in MEMHUNK. */
3313 char *from = (char *) memhunk + copy_byte;
3314 char *to = (char *) memhunk;
3315 char *end = (char *) memhunk + size;
3316 int i;
3317
3318 for (; from < end; from += interleave)
3319 for (i = 0; i < copy_width; i++)
3320 {
3321 if (&from[i] >= end)
3322 break;
3323 *to++ = from[i];
3324 }
3325
3326 size = (size + interleave - 1 - copy_byte) / interleave * copy_width;
3327 osection->lma /= interleave;
3328 }
3329
3330 if (!bfd_set_section_contents (obfd, osection, memhunk, 0, size))
3331 {
3332 status = 1;
3333 bfd_nonfatal_message (NULL, obfd, osection, NULL);
3334 return;
3335 }
3336 free (memhunk);
3337 }
3338 else if ((p = find_section_list (bfd_get_section_name (ibfd, isection),
3339 FALSE, SECTION_CONTEXT_SET_FLAGS)) != NULL
3340 && (p->flags & SEC_HAS_CONTENTS) != 0)
3341 {
3342 void *memhunk = xmalloc (size);
3343
3344 /* We don't permit the user to turn off the SEC_HAS_CONTENTS
3345 flag--they can just remove the section entirely and add it
3346 back again. However, we do permit them to turn on the
3347 SEC_HAS_CONTENTS flag, and take it to mean that the section
3348 contents should be zeroed out. */
3349
3350 memset (memhunk, 0, size);
3351 if (! bfd_set_section_contents (obfd, osection, memhunk, 0, size))
3352 {
3353 status = 1;
3354 bfd_nonfatal_message (NULL, obfd, osection, NULL);
3355 return;
3356 }
3357 free (memhunk);
3358 }
3359 }
3360
3361 /* Get all the sections. This is used when --gap-fill or --pad-to is
3362 used. */
3363
3364 static void
3365 get_sections (bfd *obfd ATTRIBUTE_UNUSED, asection *osection, void *secppparg)
3366 {
3367 asection ***secppp = (asection ***) secppparg;
3368
3369 **secppp = osection;
3370 ++(*secppp);
3371 }
3372
3373 /* Sort sections by VMA. This is called via qsort, and is used when
3374 --gap-fill or --pad-to is used. We force non loadable or empty
3375 sections to the front, where they are easier to ignore. */
3376
3377 static int
3378 compare_section_lma (const void *arg1, const void *arg2)
3379 {
3380 const asection *const *sec1 = (const asection * const *) arg1;
3381 const asection *const *sec2 = (const asection * const *) arg2;
3382 flagword flags1, flags2;
3383
3384 /* Sort non loadable sections to the front. */
3385 flags1 = (*sec1)->flags;
3386 flags2 = (*sec2)->flags;
3387 if ((flags1 & SEC_HAS_CONTENTS) == 0
3388 || (flags1 & SEC_LOAD) == 0)
3389 {
3390 if ((flags2 & SEC_HAS_CONTENTS) != 0
3391 && (flags2 & SEC_LOAD) != 0)
3392 return -1;
3393 }
3394 else
3395 {
3396 if ((flags2 & SEC_HAS_CONTENTS) == 0
3397 || (flags2 & SEC_LOAD) == 0)
3398 return 1;
3399 }
3400
3401 /* Sort sections by LMA. */
3402 if ((*sec1)->lma > (*sec2)->lma)
3403 return 1;
3404 else if ((*sec1)->lma < (*sec2)->lma)
3405 return -1;
3406
3407 /* Sort sections with the same LMA by size. */
3408 if (bfd_get_section_size (*sec1) > bfd_get_section_size (*sec2))
3409 return 1;
3410 else if (bfd_get_section_size (*sec1) < bfd_get_section_size (*sec2))
3411 return -1;
3412
3413 return 0;
3414 }
3415
3416 /* Mark all the symbols which will be used in output relocations with
3417 the BSF_KEEP flag so that those symbols will not be stripped.
3418
3419 Ignore relocations which will not appear in the output file. */
3420
3421 static void
3422 mark_symbols_used_in_relocations (bfd *ibfd, sec_ptr isection, void *symbolsarg)
3423 {
3424 asymbol **symbols = (asymbol **) symbolsarg;
3425 long relsize;
3426 arelent **relpp;
3427 long relcount, i;
3428
3429 /* Ignore an input section with no corresponding output section. */
3430 if (isection->output_section == NULL)
3431 return;
3432
3433 relsize = bfd_get_reloc_upper_bound (ibfd, isection);
3434 if (relsize < 0)
3435 {
3436 /* Do not complain if the target does not support relocations. */
3437 if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
3438 return;
3439 bfd_fatal (bfd_get_filename (ibfd));
3440 }
3441
3442 if (relsize == 0)
3443 return;
3444
3445 relpp = (arelent **) xmalloc (relsize);
3446 relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, symbols);
3447 if (relcount < 0)
3448 bfd_fatal (bfd_get_filename (ibfd));
3449
3450 /* Examine each symbol used in a relocation. If it's not one of the
3451 special bfd section symbols, then mark it with BSF_KEEP. */
3452 for (i = 0; i < relcount; i++)
3453 {
3454 if (*relpp[i]->sym_ptr_ptr != bfd_com_section_ptr->symbol
3455 && *relpp[i]->sym_ptr_ptr != bfd_abs_section_ptr->symbol
3456 && *relpp[i]->sym_ptr_ptr != bfd_und_section_ptr->symbol)
3457 (*relpp[i]->sym_ptr_ptr)->flags |= BSF_KEEP;
3458 }
3459
3460 if (relpp != NULL)
3461 free (relpp);
3462 }
3463
3464 /* Write out debugging information. */
3465
3466 static bfd_boolean
3467 write_debugging_info (bfd *obfd, void *dhandle,
3468 long *symcountp ATTRIBUTE_UNUSED,
3469 asymbol ***symppp ATTRIBUTE_UNUSED)
3470 {
3471 if (bfd_get_flavour (obfd) == bfd_target_ieee_flavour)
3472 return write_ieee_debugging_info (obfd, dhandle);
3473
3474 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
3475 || bfd_get_flavour (obfd) == bfd_target_elf_flavour)
3476 {
3477 bfd_byte *syms, *strings;
3478 bfd_size_type symsize, stringsize;
3479 asection *stabsec, *stabstrsec;
3480 flagword flags;
3481
3482 if (! write_stabs_in_sections_debugging_info (obfd, dhandle, &syms,
3483 &symsize, &strings,
3484 &stringsize))
3485 return FALSE;
3486
3487 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DEBUGGING;
3488 stabsec = bfd_make_section_with_flags (obfd, ".stab", flags);
3489 stabstrsec = bfd_make_section_with_flags (obfd, ".stabstr", flags);
3490 if (stabsec == NULL
3491 || stabstrsec == NULL
3492 || ! bfd_set_section_size (obfd, stabsec, symsize)
3493 || ! bfd_set_section_size (obfd, stabstrsec, stringsize)
3494 || ! bfd_set_section_alignment (obfd, stabsec, 2)
3495 || ! bfd_set_section_alignment (obfd, stabstrsec, 0))
3496 {
3497 bfd_nonfatal_message (NULL, obfd, NULL,
3498 _("can't create debugging section"));
3499 return FALSE;
3500 }
3501
3502 /* We can get away with setting the section contents now because
3503 the next thing the caller is going to do is copy over the
3504 real sections. We may someday have to split the contents
3505 setting out of this function. */
3506 if (! bfd_set_section_contents (obfd, stabsec, syms, 0, symsize)
3507 || ! bfd_set_section_contents (obfd, stabstrsec, strings, 0,
3508 stringsize))
3509 {
3510 bfd_nonfatal_message (NULL, obfd, NULL,
3511 _("can't set debugging section contents"));
3512 return FALSE;
3513 }
3514
3515 return TRUE;
3516 }
3517
3518 bfd_nonfatal_message (NULL, obfd, NULL,
3519 _("don't know how to write debugging information for %s"),
3520 bfd_get_target (obfd));
3521 return FALSE;
3522 }
3523
3524 /* If neither -D nor -U was specified explicitly,
3525 then use the configured default. */
3526 static void
3527 default_deterministic (void)
3528 {
3529 if (deterministic < 0)
3530 deterministic = DEFAULT_AR_DETERMINISTIC;
3531 }
3532
3533 static int
3534 strip_main (int argc, char *argv[])
3535 {
3536 char *input_target = NULL;
3537 char *output_target = NULL;
3538 bfd_boolean show_version = FALSE;
3539 bfd_boolean formats_info = FALSE;
3540 int c;
3541 int i;
3542 char *output_file = NULL;
3543
3544 while ((c = getopt_long (argc, argv, "I:O:F:K:N:R:o:sSpdgxXHhVvwDU",
3545 strip_options, (int *) 0)) != EOF)
3546 {
3547 switch (c)
3548 {
3549 case 'I':
3550 input_target = optarg;
3551 break;
3552 case 'O':
3553 output_target = optarg;
3554 break;
3555 case 'F':
3556 input_target = output_target = optarg;
3557 break;
3558 case 'R':
3559 find_section_list (optarg, TRUE, SECTION_CONTEXT_REMOVE);
3560 sections_removed = TRUE;
3561 break;
3562 case 's':
3563 strip_symbols = STRIP_ALL;
3564 break;
3565 case 'S':
3566 case 'g':
3567 case 'd': /* Historic BSD alias for -g. Used by early NetBSD. */
3568 strip_symbols = STRIP_DEBUG;
3569 break;
3570 case OPTION_STRIP_DWO:
3571 strip_symbols = STRIP_DWO;
3572 break;
3573 case OPTION_STRIP_UNNEEDED:
3574 strip_symbols = STRIP_UNNEEDED;
3575 break;
3576 case 'K':
3577 add_specific_symbol (optarg, keep_specific_htab);
3578 break;
3579 case 'N':
3580 add_specific_symbol (optarg, strip_specific_htab);
3581 break;
3582 case 'o':
3583 output_file = optarg;
3584 break;
3585 case 'p':
3586 preserve_dates = TRUE;
3587 break;
3588 case 'D':
3589 deterministic = TRUE;
3590 break;
3591 case 'U':
3592 deterministic = FALSE;
3593 break;
3594 case 'x':
3595 discard_locals = LOCALS_ALL;
3596 break;
3597 case 'X':
3598 discard_locals = LOCALS_START_L;
3599 break;
3600 case 'v':
3601 verbose = TRUE;
3602 break;
3603 case 'V':
3604 show_version = TRUE;
3605 break;
3606 case OPTION_FORMATS_INFO:
3607 formats_info = TRUE;
3608 break;
3609 case OPTION_ONLY_KEEP_DEBUG:
3610 strip_symbols = STRIP_NONDEBUG;
3611 break;
3612 case OPTION_KEEP_FILE_SYMBOLS:
3613 keep_file_symbols = 1;
3614 break;
3615 case 0:
3616 /* We've been given a long option. */
3617 break;
3618 case 'w':
3619 wildcard = TRUE;
3620 break;
3621 case 'H':
3622 case 'h':
3623 strip_usage (stdout, 0);
3624 default:
3625 strip_usage (stderr, 1);
3626 }
3627 }
3628
3629 if (formats_info)
3630 {
3631 display_info ();
3632 return 0;
3633 }
3634
3635 if (show_version)
3636 print_version ("strip");
3637
3638 default_deterministic ();
3639
3640 /* Default is to strip all symbols. */
3641 if (strip_symbols == STRIP_UNDEF
3642 && discard_locals == LOCALS_UNDEF
3643 && htab_elements (strip_specific_htab) == 0)
3644 strip_symbols = STRIP_ALL;
3645
3646 if (output_target == NULL)
3647 output_target = input_target;
3648
3649 i = optind;
3650 if (i == argc
3651 || (output_file != NULL && (i + 1) < argc))
3652 strip_usage (stderr, 1);
3653
3654 for (; i < argc; i++)
3655 {
3656 int hold_status = status;
3657 struct stat statbuf;
3658 char *tmpname;
3659
3660 if (get_file_size (argv[i]) < 1)
3661 {
3662 status = 1;
3663 continue;
3664 }
3665
3666 if (preserve_dates)
3667 /* No need to check the return value of stat().
3668 It has already been checked in get_file_size(). */
3669 stat (argv[i], &statbuf);
3670
3671 if (output_file == NULL
3672 || filename_cmp (argv[i], output_file) == 0)
3673 tmpname = make_tempname (argv[i]);
3674 else
3675 tmpname = output_file;
3676
3677 if (tmpname == NULL)
3678 {
3679 bfd_nonfatal_message (argv[i], NULL, NULL,
3680 _("could not create temporary file to hold stripped copy"));
3681 status = 1;
3682 continue;
3683 }
3684
3685 status = 0;
3686 copy_file (argv[i], tmpname, input_target, output_target, NULL);
3687 if (status == 0)
3688 {
3689 if (preserve_dates)
3690 set_times (tmpname, &statbuf);
3691 if (output_file != tmpname)
3692 status = (smart_rename (tmpname,
3693 output_file ? output_file : argv[i],
3694 preserve_dates) != 0);
3695 if (status == 0)
3696 status = hold_status;
3697 }
3698 else
3699 unlink_if_ordinary (tmpname);
3700 if (output_file != tmpname)
3701 free (tmpname);
3702 }
3703
3704 return status;
3705 }
3706
3707 /* Set up PE subsystem. */
3708
3709 static void
3710 set_pe_subsystem (const char *s)
3711 {
3712 const char *version, *subsystem;
3713 size_t i;
3714 static const struct
3715 {
3716 const char *name;
3717 const char set_def;
3718 const short value;
3719 }
3720 v[] =
3721 {
3722 { "native", 0, IMAGE_SUBSYSTEM_NATIVE },
3723 { "windows", 0, IMAGE_SUBSYSTEM_WINDOWS_GUI },
3724 { "console", 0, IMAGE_SUBSYSTEM_WINDOWS_CUI },
3725 { "posix", 0, IMAGE_SUBSYSTEM_POSIX_CUI },
3726 { "wince", 0, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI },
3727 { "efi-app", 1, IMAGE_SUBSYSTEM_EFI_APPLICATION },
3728 { "efi-bsd", 1, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER },
3729 { "efi-rtd", 1, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER },
3730 { "sal-rtd", 1, IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER },
3731 { "xbox", 0, IMAGE_SUBSYSTEM_XBOX }
3732 };
3733 short value;
3734 char *copy;
3735 int set_def = -1;
3736
3737 /* Check for the presence of a version number. */
3738 version = strchr (s, ':');
3739 if (version == NULL)
3740 subsystem = s;
3741 else
3742 {
3743 int len = version - s;
3744 copy = xstrdup (s);
3745 subsystem = copy;
3746 copy[len] = '\0';
3747 version = copy + 1 + len;
3748 pe_major_subsystem_version = strtoul (version, ©, 0);
3749 if (*copy == '.')
3750 pe_minor_subsystem_version = strtoul (copy + 1, ©, 0);
3751 if (*copy != '\0')
3752 non_fatal (_("%s: bad version in PE subsystem"), s);
3753 }
3754
3755 /* Check for numeric subsystem. */
3756 value = (short) strtol (subsystem, ©, 0);
3757 if (*copy == '\0')
3758 {
3759 for (i = 0; i < ARRAY_SIZE (v); i++)
3760 if (v[i].value == value)
3761 {
3762 pe_subsystem = value;
3763 set_def = v[i].set_def;
3764 break;
3765 }
3766 }
3767 else
3768 {
3769 /* Search for subsystem by name. */
3770 for (i = 0; i < ARRAY_SIZE (v); i++)
3771 if (strcmp (subsystem, v[i].name) == 0)
3772 {
3773 pe_subsystem = v[i].value;
3774 set_def = v[i].set_def;
3775 break;
3776 }
3777 }
3778
3779 switch (set_def)
3780 {
3781 case -1:
3782 fatal (_("unknown PE subsystem: %s"), s);
3783 break;
3784 case 0:
3785 break;
3786 default:
3787 if (pe_file_alignment == (bfd_vma) -1)
3788 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
3789 if (pe_section_alignment == (bfd_vma) -1)
3790 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
3791 break;
3792 }
3793 if (s != subsystem)
3794 free ((char *) subsystem);
3795 }
3796
3797 /* Convert EFI target to PEI target. */
3798
3799 static void
3800 convert_efi_target (char *efi)
3801 {
3802 efi[0] = 'p';
3803 efi[1] = 'e';
3804 efi[2] = 'i';
3805
3806 if (strcmp (efi + 4, "ia32") == 0)
3807 {
3808 /* Change ia32 to i386. */
3809 efi[5]= '3';
3810 efi[6]= '8';
3811 efi[7]= '6';
3812 }
3813 else if (strcmp (efi + 4, "x86_64") == 0)
3814 {
3815 /* Change x86_64 to x86-64. */
3816 efi[7] = '-';
3817 }
3818 }
3819
3820 /* Allocate and return a pointer to a struct section_add, initializing the
3821 structure using ARG, a string in the format "sectionname=filename".
3822 The returned structure will have its next pointer set to NEXT. The
3823 OPTION field is the name of the command line option currently being
3824 parsed, and is only used if an error needs to be reported. */
3825
3826 static struct section_add *
3827 init_section_add (const char *arg,
3828 struct section_add *next,
3829 const char *option)
3830 {
3831 struct section_add *pa;
3832 const char *s;
3833
3834 s = strchr (arg, '=');
3835 if (s == NULL)
3836 fatal (_("bad format for %s"), option);
3837
3838 pa = (struct section_add *) xmalloc (sizeof (struct section_add));
3839 pa->name = xstrndup (arg, s - arg);
3840 pa->filename = s + 1;
3841 pa->next = next;
3842 pa->contents = NULL;
3843 pa->size = 0;
3844
3845 return pa;
3846 }
3847
3848 /* Load the file specified in PA, allocating memory to hold the file
3849 contents, and store a pointer to the allocated memory in the contents
3850 field of PA. The size field of PA is also updated. All errors call
3851 FATAL. */
3852
3853 static void
3854 section_add_load_file (struct section_add *pa)
3855 {
3856 size_t off, alloc;
3857 FILE *f;
3858
3859 /* We don't use get_file_size so that we can do
3860 --add-section .note.GNU_stack=/dev/null
3861 get_file_size doesn't work on /dev/null. */
3862
3863 f = fopen (pa->filename, FOPEN_RB);
3864 if (f == NULL)
3865 fatal (_("cannot open: %s: %s"),
3866 pa->filename, strerror (errno));
3867
3868 off = 0;
3869 alloc = 4096;
3870 pa->contents = (bfd_byte *) xmalloc (alloc);
3871 while (!feof (f))
3872 {
3873 off_t got;
3874
3875 if (off == alloc)
3876 {
3877 alloc <<= 1;
3878 pa->contents = (bfd_byte *) xrealloc (pa->contents, alloc);
3879 }
3880
3881 got = fread (pa->contents + off, 1, alloc - off, f);
3882 if (ferror (f))
3883 fatal (_("%s: fread failed"), pa->filename);
3884
3885 off += got;
3886 }
3887
3888 pa->size = off;
3889
3890 fclose (f);
3891 }
3892
3893 static int
3894 copy_main (int argc, char *argv[])
3895 {
3896 char *input_filename = NULL;
3897 char *output_filename = NULL;
3898 char *tmpname;
3899 char *input_target = NULL;
3900 char *output_target = NULL;
3901 bfd_boolean show_version = FALSE;
3902 bfd_boolean change_warn = TRUE;
3903 bfd_boolean formats_info = FALSE;
3904 int c;
3905 struct stat statbuf;
3906 const bfd_arch_info_type *input_arch = NULL;
3907
3908 while ((c = getopt_long (argc, argv, "b:B:i:I:j:K:N:s:O:d:F:L:G:R:SpgxXHhVvW:wDU",
3909 copy_options, (int *) 0)) != EOF)
3910 {
3911 switch (c)
3912 {
3913 case 'b':
3914 copy_byte = atoi (optarg);
3915 if (copy_byte < 0)
3916 fatal (_("byte number must be non-negative"));
3917 break;
3918
3919 case 'B':
3920 input_arch = bfd_scan_arch (optarg);
3921 if (input_arch == NULL)
3922 fatal (_("architecture %s unknown"), optarg);
3923 break;
3924
3925 case 'i':
3926 if (optarg)
3927 {
3928 interleave = atoi (optarg);
3929 if (interleave < 1)
3930 fatal (_("interleave must be positive"));
3931 }
3932 else
3933 interleave = 4;
3934 break;
3935
3936 case OPTION_INTERLEAVE_WIDTH:
3937 copy_width = atoi (optarg);
3938 if (copy_width < 1)
3939 fatal(_("interleave width must be positive"));
3940 break;
3941
3942 case 'I':
3943 case 's': /* "source" - 'I' is preferred */
3944 input_target = optarg;
3945 break;
3946
3947 case 'O':
3948 case 'd': /* "destination" - 'O' is preferred */
3949 output_target = optarg;
3950 break;
3951
3952 case 'F':
3953 input_target = output_target = optarg;
3954 break;
3955
3956 case 'j':
3957 find_section_list (optarg, TRUE, SECTION_CONTEXT_COPY);
3958 sections_copied = TRUE;
3959 break;
3960
3961 case 'R':
3962 find_section_list (optarg, TRUE, SECTION_CONTEXT_REMOVE);
3963 sections_removed = TRUE;
3964 break;
3965
3966 case 'S':
3967 strip_symbols = STRIP_ALL;
3968 break;
3969
3970 case 'g':
3971 strip_symbols = STRIP_DEBUG;
3972 break;
3973
3974 case OPTION_STRIP_DWO:
3975 strip_symbols = STRIP_DWO;
3976 break;
3977
3978 case OPTION_STRIP_UNNEEDED:
3979 strip_symbols = STRIP_UNNEEDED;
3980 break;
3981
3982 case OPTION_ONLY_KEEP_DEBUG:
3983 strip_symbols = STRIP_NONDEBUG;
3984 break;
3985
3986 case OPTION_KEEP_FILE_SYMBOLS:
3987 keep_file_symbols = 1;
3988 break;
3989
3990 case OPTION_ADD_GNU_DEBUGLINK:
3991 long_section_names = ENABLE ;
3992 gnu_debuglink_filename = optarg;
3993 break;
3994
3995 case 'K':
3996 add_specific_symbol (optarg, keep_specific_htab);
3997 break;
3998
3999 case 'N':
4000 add_specific_symbol (optarg, strip_specific_htab);
4001 break;
4002
4003 case OPTION_STRIP_UNNEEDED_SYMBOL:
4004 add_specific_symbol (optarg, strip_unneeded_htab);
4005 break;
4006
4007 case 'L':
4008 add_specific_symbol (optarg, localize_specific_htab);
4009 break;
4010
4011 case OPTION_GLOBALIZE_SYMBOL:
4012 add_specific_symbol (optarg, globalize_specific_htab);
4013 break;
4014
4015 case 'G':
4016 add_specific_symbol (optarg, keepglobal_specific_htab);
4017 break;
4018
4019 case 'W':
4020 add_specific_symbol (optarg, weaken_specific_htab);
4021 break;
4022
4023 case 'p':
4024 preserve_dates = TRUE;
4025 break;
4026
4027 case 'D':
4028 deterministic = TRUE;
4029 break;
4030
4031 case 'U':
4032 deterministic = FALSE;
4033 break;
4034
4035 case 'w':
4036 wildcard = TRUE;
4037 break;
4038
4039 case 'x':
4040 discard_locals = LOCALS_ALL;
4041 break;
4042
4043 case 'X':
4044 discard_locals = LOCALS_START_L;
4045 break;
4046
4047 case 'v':
4048 verbose = TRUE;
4049 break;
4050
4051 case 'V':
4052 show_version = TRUE;
4053 break;
4054
4055 case OPTION_FORMATS_INFO:
4056 formats_info = TRUE;
4057 break;
4058
4059 case OPTION_WEAKEN:
4060 weaken = TRUE;
4061 break;
4062
4063 case OPTION_ADD_SECTION:
4064 add_sections = init_section_add (optarg, add_sections,
4065 "--add-section");
4066 section_add_load_file (add_sections);
4067 break;
4068
4069 case OPTION_UPDATE_SECTION:
4070 update_sections = init_section_add (optarg, update_sections,
4071 "--update-section");
4072 section_add_load_file (update_sections);
4073 break;
4074
4075 case OPTION_DUMP_SECTION:
4076 dump_sections = init_section_add (optarg, dump_sections,
4077 "--dump-section");
4078 break;
4079
4080 case OPTION_ADD_SYMBOL:
4081 {
4082 char *s, *t;
4083 struct addsym_node *newsym = xmalloc (sizeof *newsym);
4084
4085 newsym->next = NULL;
4086 s = strchr (optarg, '=');
4087 if (s == NULL)
4088 fatal (_("bad format for %s"), "--add-symbol");
4089 t = strchr (s + 1, ':');
4090
4091 newsym->symdef = xstrndup (optarg, s - optarg);
4092 if (t)
4093 {
4094 newsym->section = xstrndup (s + 1, t - (s + 1));
4095 newsym->symval = strtol (t + 1, NULL, 0);
4096 }
4097 else
4098 {
4099 newsym->section = NULL;
4100 newsym->symval = strtol (s + 1, NULL, 0);
4101 t = s;
4102 }
4103
4104 t = strchr (t + 1, ',');
4105 newsym->othersym = NULL;
4106 if (t)
4107 newsym->flags = parse_symflags (t+1, &newsym->othersym);
4108 else
4109 newsym->flags = BSF_GLOBAL;
4110
4111 /* Keep 'othersym' symbols at the front of the list. */
4112 if (newsym->othersym)
4113 {
4114 newsym->next = add_sym_list;
4115 if (!add_sym_list)
4116 add_sym_tail = &newsym->next;
4117 add_sym_list = newsym;
4118 }
4119 else
4120 {
4121 *add_sym_tail = newsym;
4122 add_sym_tail = &newsym->next;
4123 }
4124 add_symbols++;
4125 }
4126 break;
4127
4128 case OPTION_CHANGE_START:
4129 change_start = parse_vma (optarg, "--change-start");
4130 break;
4131
4132 case OPTION_CHANGE_SECTION_ADDRESS:
4133 case OPTION_CHANGE_SECTION_LMA:
4134 case OPTION_CHANGE_SECTION_VMA:
4135 {
4136 struct section_list * p;
4137 unsigned int context = 0;
4138 const char *s;
4139 int len;
4140 char *name;
4141 char *option = NULL;
4142 bfd_vma val;
4143
4144 switch (c)
4145 {
4146 case OPTION_CHANGE_SECTION_ADDRESS:
4147 option = "--change-section-address";
4148 context = SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_ALTER_VMA;
4149 break;
4150 case OPTION_CHANGE_SECTION_LMA:
4151 option = "--change-section-lma";
4152 context = SECTION_CONTEXT_ALTER_LMA;
4153 break;
4154 case OPTION_CHANGE_SECTION_VMA:
4155 option = "--change-section-vma";
4156 context = SECTION_CONTEXT_ALTER_VMA;
4157 break;
4158 }
4159
4160 s = strchr (optarg, '=');
4161 if (s == NULL)
4162 {
4163 s = strchr (optarg, '+');
4164 if (s == NULL)
4165 {
4166 s = strchr (optarg, '-');
4167 if (s == NULL)
4168 fatal (_("bad format for %s"), option);
4169 }
4170 }
4171 else
4172 {
4173 /* Correct the context. */
4174 switch (c)
4175 {
4176 case OPTION_CHANGE_SECTION_ADDRESS:
4177 context = SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_SET_VMA;
4178 break;
4179 case OPTION_CHANGE_SECTION_LMA:
4180 context = SECTION_CONTEXT_SET_LMA;
4181 break;
4182 case OPTION_CHANGE_SECTION_VMA:
4183 context = SECTION_CONTEXT_SET_VMA;
4184 break;
4185 }
4186 }
4187
4188 len = s - optarg;
4189 name = (char *) xmalloc (len + 1);
4190 strncpy (name, optarg, len);
4191 name[len] = '\0';
4192
4193 p = find_section_list (name, TRUE, context);
4194
4195 val = parse_vma (s + 1, option);
4196 if (*s == '-')
4197 val = - val;
4198
4199 switch (c)
4200 {
4201 case OPTION_CHANGE_SECTION_ADDRESS:
4202 p->vma_val = val;
4203 /* Drop through. */
4204
4205 case OPTION_CHANGE_SECTION_LMA:
4206 p->lma_val = val;
4207 break;
4208
4209 case OPTION_CHANGE_SECTION_VMA:
4210 p->vma_val = val;
4211 break;
4212 }
4213 }
4214 break;
4215
4216 case OPTION_CHANGE_ADDRESSES:
4217 change_section_address = parse_vma (optarg, "--change-addresses");
4218 change_start = change_section_address;
4219 break;
4220
4221 case OPTION_CHANGE_WARNINGS:
4222 change_warn = TRUE;
4223 break;
4224
4225 case OPTION_CHANGE_LEADING_CHAR:
4226 change_leading_char = TRUE;
4227 break;
4228
4229 case OPTION_COMPRESS_DEBUG_SECTIONS:
4230 if (optarg)
4231 {
4232 if (strcasecmp (optarg, "none") == 0)
4233 do_debug_sections = decompress;
4234 else if (strcasecmp (optarg, "zlib") == 0)
4235 do_debug_sections = compress_zlib;
4236 else if (strcasecmp (optarg, "zlib-gnu") == 0)
4237 do_debug_sections = compress_gnu_zlib;
4238 else if (strcasecmp (optarg, "zlib-gabi") == 0)
4239 do_debug_sections = compress_gabi_zlib;
4240 else
4241 fatal (_("unrecognized --compress-debug-sections type `%s'"),
4242 optarg);
4243 }
4244 else
4245 do_debug_sections = compress;
4246 break;
4247
4248 case OPTION_DEBUGGING:
4249 convert_debugging = TRUE;
4250 break;
4251
4252 case OPTION_DECOMPRESS_DEBUG_SECTIONS:
4253 do_debug_sections = decompress;
4254 break;
4255
4256 case OPTION_GAP_FILL:
4257 {
4258 bfd_vma gap_fill_vma;
4259
4260 gap_fill_vma = parse_vma (optarg, "--gap-fill");
4261 gap_fill = (bfd_byte) gap_fill_vma;
4262 if ((bfd_vma) gap_fill != gap_fill_vma)
4263 {
4264 char buff[20];
4265
4266 sprintf_vma (buff, gap_fill_vma);
4267
4268 non_fatal (_("Warning: truncating gap-fill from 0x%s to 0x%x"),
4269 buff, gap_fill);
4270 }
4271 gap_fill_set = TRUE;
4272 }
4273 break;
4274
4275 case OPTION_NO_CHANGE_WARNINGS:
4276 change_warn = FALSE;
4277 break;
4278
4279 case OPTION_PAD_TO:
4280 pad_to = parse_vma (optarg, "--pad-to");
4281 pad_to_set = TRUE;
4282 break;
4283
4284 case OPTION_REMOVE_LEADING_CHAR:
4285 remove_leading_char = TRUE;
4286 break;
4287
4288 case OPTION_REDEFINE_SYM:
4289 {
4290 /* Push this redefinition onto redefine_symbol_list. */
4291
4292 int len;
4293 const char *s;
4294 const char *nextarg;
4295 char *source, *target;
4296
4297 s = strchr (optarg, '=');
4298 if (s == NULL)
4299 fatal (_("bad format for %s"), "--redefine-sym");
4300
4301 len = s - optarg;
4302 source = (char *) xmalloc (len + 1);
4303 strncpy (source, optarg, len);
4304 source[len] = '\0';
4305
4306 nextarg = s + 1;
4307 len = strlen (nextarg);
4308 target = (char *) xmalloc (len + 1);
4309 strcpy (target, nextarg);
4310
4311 redefine_list_append ("--redefine-sym", source, target);
4312
4313 free (source);
4314 free (target);
4315 }
4316 break;
4317
4318 case OPTION_REDEFINE_SYMS:
4319 add_redefine_syms_file (optarg);
4320 break;
4321
4322 case OPTION_SET_SECTION_FLAGS:
4323 {
4324 struct section_list *p;
4325 const char *s;
4326 int len;
4327 char *name;
4328
4329 s = strchr (optarg, '=');
4330 if (s == NULL)
4331 fatal (_("bad format for %s"), "--set-section-flags");
4332
4333 len = s - optarg;
4334 name = (char *) xmalloc (len + 1);
4335 strncpy (name, optarg, len);
4336 name[len] = '\0';
4337
4338 p = find_section_list (name, TRUE, SECTION_CONTEXT_SET_FLAGS);
4339
4340 p->flags = parse_flags (s + 1);
4341 }
4342 break;
4343
4344 case OPTION_RENAME_SECTION:
4345 {
4346 flagword flags;
4347 const char *eq, *fl;
4348 char *old_name;
4349 char *new_name;
4350 unsigned int len;
4351
4352 eq = strchr (optarg, '=');
4353 if (eq == NULL)
4354 fatal (_("bad format for %s"), "--rename-section");
4355
4356 len = eq - optarg;
4357 if (len == 0)
4358 fatal (_("bad format for %s"), "--rename-section");
4359
4360 old_name = (char *) xmalloc (len + 1);
4361 strncpy (old_name, optarg, len);
4362 old_name[len] = 0;
4363
4364 eq++;
4365 fl = strchr (eq, ',');
4366 if (fl)
4367 {
4368 flags = parse_flags (fl + 1);
4369 len = fl - eq;
4370 }
4371 else
4372 {
4373 flags = -1;
4374 len = strlen (eq);
4375 }
4376
4377 if (len == 0)
4378 fatal (_("bad format for %s"), "--rename-section");
4379
4380 new_name = (char *) xmalloc (len + 1);
4381 strncpy (new_name, eq, len);
4382 new_name[len] = 0;
4383
4384 add_section_rename (old_name, new_name, flags);
4385 }
4386 break;
4387
4388 case OPTION_SET_START:
4389 set_start = parse_vma (optarg, "--set-start");
4390 set_start_set = TRUE;
4391 break;
4392
4393 case OPTION_SREC_LEN:
4394 Chunk = parse_vma (optarg, "--srec-len");
4395 break;
4396
4397 case OPTION_SREC_FORCES3:
4398 S3Forced = TRUE;
4399 break;
4400
4401 case OPTION_STRIP_SYMBOLS:
4402 add_specific_symbols (optarg, strip_specific_htab);
4403 break;
4404
4405 case OPTION_STRIP_UNNEEDED_SYMBOLS:
4406 add_specific_symbols (optarg, strip_unneeded_htab);
4407 break;
4408
4409 case OPTION_KEEP_SYMBOLS:
4410 add_specific_symbols (optarg, keep_specific_htab);
4411 break;
4412
4413 case OPTION_LOCALIZE_HIDDEN:
4414 localize_hidden = TRUE;
4415 break;
4416
4417 case OPTION_LOCALIZE_SYMBOLS:
4418 add_specific_symbols (optarg, localize_specific_htab);
4419 break;
4420
4421 case OPTION_LONG_SECTION_NAMES:
4422 if (!strcmp ("enable", optarg))
4423 long_section_names = ENABLE;
4424 else if (!strcmp ("disable", optarg))
4425 long_section_names = DISABLE;
4426 else if (!strcmp ("keep", optarg))
4427 long_section_names = KEEP;
4428 else
4429 fatal (_("unknown long section names option '%s'"), optarg);
4430 break;
4431
4432 case OPTION_GLOBALIZE_SYMBOLS:
4433 add_specific_symbols (optarg, globalize_specific_htab);
4434 break;
4435
4436 case OPTION_KEEPGLOBAL_SYMBOLS:
4437 add_specific_symbols (optarg, keepglobal_specific_htab);
4438 break;
4439
4440 case OPTION_WEAKEN_SYMBOLS:
4441 add_specific_symbols (optarg, weaken_specific_htab);
4442 break;
4443
4444 case OPTION_ALT_MACH_CODE:
4445 use_alt_mach_code = strtoul (optarg, NULL, 0);
4446 if (use_alt_mach_code == 0)
4447 fatal (_("unable to parse alternative machine code"));
4448 break;
4449
4450 case OPTION_PREFIX_SYMBOLS:
4451 prefix_symbols_string = optarg;
4452 break;
4453
4454 case OPTION_PREFIX_SECTIONS:
4455 prefix_sections_string = optarg;
4456 break;
4457
4458 case OPTION_PREFIX_ALLOC_SECTIONS:
4459 prefix_alloc_sections_string = optarg;
4460 break;
4461
4462 case OPTION_READONLY_TEXT:
4463 bfd_flags_to_set |= WP_TEXT;
4464 bfd_flags_to_clear &= ~WP_TEXT;
4465 break;
4466
4467 case OPTION_WRITABLE_TEXT:
4468 bfd_flags_to_clear |= WP_TEXT;
4469 bfd_flags_to_set &= ~WP_TEXT;
4470 break;
4471
4472 case OPTION_PURE:
4473 bfd_flags_to_set |= D_PAGED;
4474 bfd_flags_to_clear &= ~D_PAGED;
4475 break;
4476
4477 case OPTION_IMPURE:
4478 bfd_flags_to_clear |= D_PAGED;
4479 bfd_flags_to_set &= ~D_PAGED;
4480 break;
4481
4482 case OPTION_EXTRACT_DWO:
4483 strip_symbols = STRIP_NONDWO;
4484 break;
4485
4486 case OPTION_EXTRACT_SYMBOL:
4487 extract_symbol = TRUE;
4488 break;
4489
4490 case OPTION_REVERSE_BYTES:
4491 {
4492 int prev = reverse_bytes;
4493
4494 reverse_bytes = atoi (optarg);
4495 if ((reverse_bytes <= 0) || ((reverse_bytes % 2) != 0))
4496 fatal (_("number of bytes to reverse must be positive and even"));
4497
4498 if (prev && prev != reverse_bytes)
4499 non_fatal (_("Warning: ignoring previous --reverse-bytes value of %d"),
4500 prev);
4501 break;
4502 }
4503
4504 case OPTION_FILE_ALIGNMENT:
4505 pe_file_alignment = parse_vma (optarg, "--file-alignment");
4506 break;
4507
4508 case OPTION_HEAP:
4509 {
4510 char *end;
4511 pe_heap_reserve = strtoul (optarg, &end, 0);
4512 if (end == optarg
4513 || (*end != '.' && *end != '\0'))
4514 non_fatal (_("%s: invalid reserve value for --heap"),
4515 optarg);
4516 else if (*end != '\0')
4517 {
4518 pe_heap_commit = strtoul (end + 1, &end, 0);
4519 if (*end != '\0')
4520 non_fatal (_("%s: invalid commit value for --heap"),
4521 optarg);
4522 }
4523 }
4524 break;
4525
4526 case OPTION_IMAGE_BASE:
4527 pe_image_base = parse_vma (optarg, "--image-base");
4528 break;
4529
4530 case OPTION_SECTION_ALIGNMENT:
4531 pe_section_alignment = parse_vma (optarg,
4532 "--section-alignment");
4533 break;
4534
4535 case OPTION_SUBSYSTEM:
4536 set_pe_subsystem (optarg);
4537 break;
4538
4539 case OPTION_STACK:
4540 {
4541 char *end;
4542 pe_stack_reserve = strtoul (optarg, &end, 0);
4543 if (end == optarg
4544 || (*end != '.' && *end != '\0'))
4545 non_fatal (_("%s: invalid reserve value for --stack"),
4546 optarg);
4547 else if (*end != '\0')
4548 {
4549 pe_stack_commit = strtoul (end + 1, &end, 0);
4550 if (*end != '\0')
4551 non_fatal (_("%s: invalid commit value for --stack"),
4552 optarg);
4553 }
4554 }
4555 break;
4556
4557 case 0:
4558 /* We've been given a long option. */
4559 break;
4560
4561 case 'H':
4562 case 'h':
4563 copy_usage (stdout, 0);
4564
4565 default:
4566 copy_usage (stderr, 1);
4567 }
4568 }
4569
4570 if (formats_info)
4571 {
4572 display_info ();
4573 return 0;
4574 }
4575
4576 if (show_version)
4577 print_version ("objcopy");
4578
4579 if (interleave && copy_byte == -1)
4580 fatal (_("interleave start byte must be set with --byte"));
4581
4582 if (copy_byte >= interleave)
4583 fatal (_("byte number must be less than interleave"));
4584
4585 if (copy_width > interleave - copy_byte)
4586 fatal (_("interleave width must be less than or equal to interleave - byte`"));
4587
4588 if (optind == argc || optind + 2 < argc)
4589 copy_usage (stderr, 1);
4590
4591 input_filename = argv[optind];
4592 if (optind + 1 < argc)
4593 output_filename = argv[optind + 1];
4594
4595 default_deterministic ();
4596
4597 /* Default is to strip no symbols. */
4598 if (strip_symbols == STRIP_UNDEF && discard_locals == LOCALS_UNDEF)
4599 strip_symbols = STRIP_NONE;
4600
4601 if (output_target == NULL)
4602 output_target = input_target;
4603
4604 /* Convert input EFI target to PEI target. */
4605 if (input_target != NULL
4606 && strncmp (input_target, "efi-", 4) == 0)
4607 {
4608 char *efi;
4609
4610 efi = xstrdup (output_target + 4);
4611 if (strncmp (efi, "bsdrv-", 6) == 0
4612 || strncmp (efi, "rtdrv-", 6) == 0)
4613 efi += 2;
4614 else if (strncmp (efi, "app-", 4) != 0)
4615 fatal (_("unknown input EFI target: %s"), input_target);
4616
4617 input_target = efi;
4618 convert_efi_target (efi);
4619 }
4620
4621 /* Convert output EFI target to PEI target. */
4622 if (output_target != NULL
4623 && strncmp (output_target, "efi-", 4) == 0)
4624 {
4625 char *efi;
4626
4627 efi = xstrdup (output_target + 4);
4628 if (strncmp (efi, "app-", 4) == 0)
4629 {
4630 if (pe_subsystem == -1)
4631 pe_subsystem = IMAGE_SUBSYSTEM_EFI_APPLICATION;
4632 }
4633 else if (strncmp (efi, "bsdrv-", 6) == 0)
4634 {
4635 if (pe_subsystem == -1)
4636 pe_subsystem = IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
4637 efi += 2;
4638 }
4639 else if (strncmp (efi, "rtdrv-", 6) == 0)
4640 {
4641 if (pe_subsystem == -1)
4642 pe_subsystem = IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER;
4643 efi += 2;
4644 }
4645 else
4646 fatal (_("unknown output EFI target: %s"), output_target);
4647
4648 if (pe_file_alignment == (bfd_vma) -1)
4649 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
4650 if (pe_section_alignment == (bfd_vma) -1)
4651 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
4652
4653 output_target = efi;
4654 convert_efi_target (efi);
4655 }
4656
4657 if (preserve_dates)
4658 if (stat (input_filename, & statbuf) < 0)
4659 fatal (_("warning: could not locate '%s'. System error message: %s"),
4660 input_filename, strerror (errno));
4661
4662 /* If there is no destination file, or the source and destination files
4663 are the same, then create a temp and rename the result into the input. */
4664 if (output_filename == NULL
4665 || filename_cmp (input_filename, output_filename) == 0)
4666 tmpname = make_tempname (input_filename);
4667 else
4668 tmpname = output_filename;
4669
4670 if (tmpname == NULL)
4671 fatal (_("warning: could not create temporary file whilst copying '%s', (error: %s)"),
4672 input_filename, strerror (errno));
4673
4674 copy_file (input_filename, tmpname, input_target, output_target, input_arch);
4675 if (status == 0)
4676 {
4677 if (preserve_dates)
4678 set_times (tmpname, &statbuf);
4679 if (tmpname != output_filename)
4680 status = (smart_rename (tmpname, input_filename,
4681 preserve_dates) != 0);
4682 }
4683 else
4684 unlink_if_ordinary (tmpname);
4685
4686 if (change_warn)
4687 {
4688 struct section_list *p;
4689
4690 for (p = change_sections; p != NULL; p = p->next)
4691 {
4692 if (! p->used)
4693 {
4694 if (p->context & (SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA))
4695 {
4696 char buff [20];
4697
4698 sprintf_vma (buff, p->vma_val);
4699
4700 /* xgettext:c-format */
4701 non_fatal (_("%s %s%c0x%s never used"),
4702 "--change-section-vma",
4703 p->pattern,
4704 p->context & SECTION_CONTEXT_SET_VMA ? '=' : '+',
4705 buff);
4706 }
4707
4708 if (p->context & (SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA))
4709 {
4710 char buff [20];
4711
4712 sprintf_vma (buff, p->lma_val);
4713
4714 /* xgettext:c-format */
4715 non_fatal (_("%s %s%c0x%s never used"),
4716 "--change-section-lma",
4717 p->pattern,
4718 p->context & SECTION_CONTEXT_SET_LMA ? '=' : '+',
4719 buff);
4720 }
4721 }
4722 }
4723 }
4724
4725 return 0;
4726 }
4727
4728 int
4729 main (int argc, char *argv[])
4730 {
4731 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
4732 setlocale (LC_MESSAGES, "");
4733 #endif
4734 #if defined (HAVE_SETLOCALE)
4735 setlocale (LC_CTYPE, "");
4736 #endif
4737 bindtextdomain (PACKAGE, LOCALEDIR);
4738 textdomain (PACKAGE);
4739
4740 program_name = argv[0];
4741 xmalloc_set_program_name (program_name);
4742
4743 START_PROGRESS (program_name, 0);
4744
4745 expandargv (&argc, &argv);
4746
4747 strip_symbols = STRIP_UNDEF;
4748 discard_locals = LOCALS_UNDEF;
4749
4750 bfd_init ();
4751 set_default_bfd_target ();
4752
4753 if (is_strip < 0)
4754 {
4755 int i = strlen (program_name);
4756 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
4757 /* Drop the .exe suffix, if any. */
4758 if (i > 4 && FILENAME_CMP (program_name + i - 4, ".exe") == 0)
4759 {
4760 i -= 4;
4761 program_name[i] = '\0';
4762 }
4763 #endif
4764 is_strip = (i >= 5 && FILENAME_CMP (program_name + i - 5, "strip") == 0);
4765 }
4766
4767 create_symbol_htabs ();
4768
4769 if (argv != NULL)
4770 bfd_set_error_program_name (argv[0]);
4771
4772 if (is_strip)
4773 strip_main (argc, argv);
4774 else
4775 copy_main (argc, argv);
4776
4777 END_PROGRESS (program_name);
4778
4779 return status;
4780 }
4781