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