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