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