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