Updated Malay translation for the bfd sub-directory
[binutils-gdb.git] / binutils / objcopy.c
blobf64417697cb8c98a9e5d5e01d6b28957a4002f13
1 /* objcopy.c -- copy object file from input to output, optionally massaging it.
2 Copyright (C) 1991-2025 Free Software Foundation, Inc.
4 This file is part of GNU Binutils.
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.
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.
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. */
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "getopt.h"
24 #include "libiberty.h"
25 #include "bucomm.h"
26 #include "budbg.h"
27 #include "filenames.h"
28 #include "fnmatch.h"
29 #include "elf-bfd.h"
30 #include "coff/internal.h"
31 #include "libcoff.h"
32 #include "safe-ctype.h"
34 /* FIXME: See bfd/peXXigen.c for why we include an architecture specific
35 header in generic PE code. */
36 #include "coff/i386.h"
37 #include "coff/pe.h"
39 static bfd_vma pe_file_alignment = (bfd_vma) -1;
40 static bfd_vma pe_heap_commit = (bfd_vma) -1;
41 static bfd_vma pe_heap_reserve = (bfd_vma) -1;
42 static bfd_vma pe_image_base = (bfd_vma) -1;
43 static bfd_vma pe_section_alignment = (bfd_vma) -1;
44 static bfd_vma pe_stack_commit = (bfd_vma) -1;
45 static bfd_vma pe_stack_reserve = (bfd_vma) -1;
46 static short pe_subsystem = -1;
47 static short pe_major_subsystem_version = -1;
48 static short pe_minor_subsystem_version = -1;
50 struct is_specified_symbol_predicate_data
52 const char *name;
53 bool found;
56 /* A node includes symbol name mapping to support redefine_sym. */
57 struct redefine_node
59 char *source;
60 char *target;
63 struct addsym_node
65 struct addsym_node *next;
66 char * symdef;
67 long symval;
68 flagword flags;
69 char * section;
70 const char * othersym;
73 typedef struct section_rename
75 const char * old_name;
76 const char * new_name;
77 flagword flags;
78 struct section_rename * next;
80 section_rename;
82 /* List of sections to be renamed. */
83 static section_rename *section_rename_list;
85 static asymbol **isympp = NULL; /* Input symbols. */
86 static asymbol **osympp = NULL; /* Output symbols that survive stripping. */
88 /* If `copy_byte' >= 0, copy 'copy_width' byte(s) of every `interleave' bytes. */
89 static int copy_byte = -1;
90 static int interleave = 0; /* Initialised to 4 in copy_main(). */
91 static int copy_width = 1;
93 static bool keep_section_symbols = false ;/* True if section symbols should be retained. */
94 static bool verbose; /* Print file and target names. */
95 static bool preserve_dates; /* Preserve input file timestamp. */
96 static int deterministic = -1; /* Enable deterministic archives. */
97 static int status = 0; /* Exit status. */
99 static bool merge_notes = false; /* Merge note sections. */
100 static bool strip_section_headers = false;/* Strip section headers. */
102 typedef struct merged_note_section
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;
110 enum strip_action
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. */
122 /* Which symbols to remove. */
123 static enum strip_action strip_symbols = STRIP_UNDEF;
125 enum locals_action
127 LOCALS_UNDEF,
128 LOCALS_START_L, /* Discard locals starting with L. */
129 LOCALS_ALL /* Discard all locals. */
132 /* Which local symbols to remove. Overrides STRIP_ALL. */
133 static enum locals_action discard_locals;
135 /* Structure used to hold lists of sections and actions to take. */
136 struct section_list
138 struct section_list *next; /* Next section to change. */
139 const char *pattern; /* Section name pattern. */
140 bool used; /* Whether this entry was used. */
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.
145 SET and ALTER are mutually exclusive. */
146 #define SECTION_CONTEXT_REMOVE (1 << 0) /* Remove this section. */
147 #define SECTION_CONTEXT_COPY (1 << 1) /* Copy this section, delete all non-copied section. */
148 #define SECTION_CONTEXT_KEEP (1 << 2) /* Keep this section. */
149 #define SECTION_CONTEXT_SET_VMA (1 << 3) /* Set the sections' VMA address. */
150 #define SECTION_CONTEXT_ALTER_VMA (1 << 4) /* Increment or decrement the section's VMA address. */
151 #define SECTION_CONTEXT_SET_LMA (1 << 5) /* Set the sections' LMA address. */
152 #define SECTION_CONTEXT_ALTER_LMA (1 << 6) /* Increment or decrement the section's LMA address. */
153 #define SECTION_CONTEXT_SET_FLAGS (1 << 7) /* Set the section's flags. */
154 #define SECTION_CONTEXT_REMOVE_RELOCS (1 << 8) /* Remove relocations for this section. */
155 #define SECTION_CONTEXT_SET_ALIGNMENT (1 << 9) /* Set alignment for section. */
157 bfd_vma vma_val; /* Amount to change by or set to. */
158 bfd_vma lma_val; /* Amount to change by or set to. */
159 flagword flags; /* What to set the section flags to. */
160 unsigned int alignment; /* Alignment of output section. */
163 static struct section_list *change_sections;
165 /* TRUE if some sections are to be removed. */
166 static bool sections_removed;
168 /* TRUE if only some sections are to be copied. */
169 static bool sections_copied;
171 /* Changes to the start address. */
172 static bfd_vma change_start = 0;
173 static bool set_start_set = false;
174 static bfd_vma set_start;
176 /* Changes to section addresses. */
177 static bfd_vma change_section_address = 0;
179 /* Filling gaps between sections. */
180 static bool gap_fill_set = false;
181 static bfd_byte gap_fill = 0;
183 /* Pad to a given address. */
184 static bool pad_to_set = false;
185 static bfd_vma pad_to;
187 /* Use alternative machine code? */
188 static unsigned long use_alt_mach_code = 0;
190 /* Output BFD flags user wants to set or clear */
191 static flagword bfd_flags_to_set;
192 static flagword bfd_flags_to_clear;
194 /* List of sections to add. */
195 struct section_add
197 /* Next section to add. */
198 struct section_add *next;
199 /* Name of section to add. */
200 const char *name;
201 /* Name of file holding section contents. */
202 const char *filename;
203 /* Size of file. */
204 size_t size;
205 /* Contents of file. */
206 bfd_byte *contents;
207 /* BFD section, after it has been added. */
208 asection *section;
211 /* List of sections to add to the output BFD. */
212 static struct section_add *add_sections;
214 /* List of sections to update in the output BFD. */
215 static struct section_add *update_sections;
217 /* List of sections to dump from the output BFD. */
218 static struct section_add *dump_sections;
220 /* If non-NULL the argument to --add-gnu-debuglink.
221 This should be the filename to store in the .gnu_debuglink section. */
222 static const char * gnu_debuglink_filename = NULL;
224 /* Whether to convert debugging information. */
225 static bool convert_debugging = false;
227 /* Whether to compress/decompress DWARF debug sections. */
228 static enum
230 nothing = 0,
231 compress = 1 << 0,
232 compress_zlib = compress | 1 << 1,
233 compress_gnu_zlib = compress | 1 << 2,
234 compress_gabi_zlib = compress | 1 << 3,
235 compress_zstd = compress | 1 << 4,
236 decompress = 1 << 5
237 } do_debug_sections = nothing;
239 /* Whether to generate ELF common symbols with the STT_COMMON type. */
240 static enum bfd_link_elf_stt_common do_elf_stt_common = unchanged;
242 /* Whether to change the leading character in symbol names. */
243 static bool change_leading_char = false;
245 /* Whether to remove the leading character from global symbol names. */
246 static bool remove_leading_char = false;
248 /* Whether to permit wildcard in symbol comparison. */
249 static bool wildcard = false;
251 /* True if --localize-hidden is in effect. */
252 static bool localize_hidden = false;
254 /* List of symbols to strip, keep, localize, keep-global, weaken,
255 or redefine. */
256 static htab_t strip_specific_htab = NULL;
257 static htab_t strip_unneeded_htab = NULL;
258 static htab_t keep_specific_htab = NULL;
259 static htab_t localize_specific_htab = NULL;
260 static htab_t globalize_specific_htab = NULL;
261 static htab_t keepglobal_specific_htab = NULL;
262 static htab_t weaken_specific_htab = NULL;
263 static htab_t redefine_specific_htab = NULL;
264 static htab_t redefine_specific_reverse_htab = NULL;
265 static struct addsym_node *add_sym_list = NULL, **add_sym_tail = &add_sym_list;
266 static int add_symbols = 0;
268 static char *strip_specific_buffer = NULL;
269 static char *strip_unneeded_buffer = NULL;
270 static char *keep_specific_buffer = NULL;
271 static char *localize_specific_buffer = NULL;
272 static char *globalize_specific_buffer = NULL;
273 static char *keepglobal_specific_buffer = NULL;
274 static char *weaken_specific_buffer = NULL;
276 /* If this is TRUE, we weaken global symbols (set BSF_WEAK). */
277 static bool weaken = false;
279 /* If this is TRUE, we retain BSF_FILE symbols. */
280 static bool keep_file_symbols = false;
282 /* Prefix symbols/sections. */
283 static char *prefix_symbols_string = 0;
284 static char *prefix_sections_string = 0;
285 static char *prefix_alloc_sections_string = 0;
287 /* True if --extract-symbol was passed on the command line. */
288 static bool extract_symbol = false;
290 /* If `reverse_bytes' is nonzero, then reverse the order of every chunk
291 of <reverse_bytes> bytes within each output section. */
292 static int reverse_bytes = 0;
294 /* For Coff objects, we may want to allow or disallow long section names,
295 or preserve them where found in the inputs. Debug info relies on them. */
296 enum long_section_name_handling
298 DISABLE,
299 ENABLE,
300 KEEP
303 /* The default long section handling mode is to preserve them.
304 This is also the only behaviour for 'strip'. */
305 static enum long_section_name_handling long_section_names = KEEP;
307 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
308 enum command_line_switch
310 OPTION_ADD_SECTION=150,
311 OPTION_ADD_GNU_DEBUGLINK,
312 OPTION_ADD_SYMBOL,
313 OPTION_ALT_MACH_CODE,
314 OPTION_CHANGE_ADDRESSES,
315 OPTION_CHANGE_LEADING_CHAR,
316 OPTION_CHANGE_SECTION_ADDRESS,
317 OPTION_CHANGE_SECTION_LMA,
318 OPTION_CHANGE_SECTION_VMA,
319 OPTION_CHANGE_START,
320 OPTION_CHANGE_WARNINGS,
321 OPTION_COMPRESS_DEBUG_SECTIONS,
322 OPTION_DEBUGGING,
323 OPTION_DECOMPRESS_DEBUG_SECTIONS,
324 OPTION_DUMP_SECTION,
325 OPTION_ELF_STT_COMMON,
326 OPTION_EXTRACT_DWO,
327 OPTION_EXTRACT_SYMBOL,
328 OPTION_FILE_ALIGNMENT,
329 OPTION_FORMATS_INFO,
330 OPTION_GAP_FILL,
331 OPTION_GLOBALIZE_SYMBOL,
332 OPTION_GLOBALIZE_SYMBOLS,
333 OPTION_HEAP,
334 OPTION_IMAGE_BASE,
335 OPTION_IMPURE,
336 OPTION_INTERLEAVE_WIDTH,
337 OPTION_KEEPGLOBAL_SYMBOLS,
338 OPTION_KEEP_FILE_SYMBOLS,
339 OPTION_KEEP_SECTION,
340 OPTION_KEEP_SYMBOLS,
341 OPTION_KEEP_SECTION_SYMBOLS,
342 OPTION_LOCALIZE_HIDDEN,
343 OPTION_LOCALIZE_SYMBOLS,
344 OPTION_LONG_SECTION_NAMES,
345 OPTION_MERGE_NOTES,
346 OPTION_NO_MERGE_NOTES,
347 OPTION_NO_CHANGE_WARNINGS,
348 OPTION_ONLY_KEEP_DEBUG,
349 OPTION_PAD_TO,
350 OPTION_PREFIX_ALLOC_SECTIONS,
351 OPTION_PREFIX_SECTIONS,
352 OPTION_PREFIX_SYMBOLS,
353 OPTION_PURE,
354 OPTION_READONLY_TEXT,
355 OPTION_REDEFINE_SYM,
356 OPTION_REDEFINE_SYMS,
357 OPTION_REMOVE_LEADING_CHAR,
358 OPTION_REMOVE_RELOCS,
359 OPTION_RENAME_SECTION,
360 OPTION_REVERSE_BYTES,
361 OPTION_PE_SECTION_ALIGNMENT,
362 OPTION_SET_SECTION_FLAGS,
363 OPTION_SET_SECTION_ALIGNMENT,
364 OPTION_SET_START,
365 OPTION_SREC_FORCES3,
366 OPTION_SREC_LEN,
367 OPTION_STACK,
368 OPTION_STRIP_DWO,
369 OPTION_STRIP_SECTION_HEADERS,
370 OPTION_STRIP_SYMBOLS,
371 OPTION_STRIP_UNNEEDED,
372 OPTION_STRIP_UNNEEDED_SYMBOL,
373 OPTION_STRIP_UNNEEDED_SYMBOLS,
374 OPTION_SUBSYSTEM,
375 OPTION_UPDATE_SECTION,
376 OPTION_VERILOG_DATA_WIDTH,
377 OPTION_WEAKEN,
378 OPTION_WEAKEN_SYMBOLS,
379 OPTION_WRITABLE_TEXT
382 /* Options to handle if running as "strip". */
384 static struct option strip_options[] =
386 {"disable-deterministic-archives", no_argument, 0, 'U'},
387 {"discard-all", no_argument, 0, 'x'},
388 {"discard-locals", no_argument, 0, 'X'},
389 {"enable-deterministic-archives", no_argument, 0, 'D'},
390 {"format", required_argument, 0, 'F'}, /* Obsolete */
391 {"help", no_argument, 0, 'h'},
392 {"info", no_argument, 0, OPTION_FORMATS_INFO},
393 {"input-format", required_argument, 0, 'I'}, /* Obsolete */
394 {"input-target", required_argument, 0, 'I'},
395 {"keep-section-symbols", no_argument, 0, OPTION_KEEP_SECTION_SYMBOLS},
396 {"keep-file-symbols", no_argument, 0, OPTION_KEEP_FILE_SYMBOLS},
397 {"keep-section", required_argument, 0, OPTION_KEEP_SECTION},
398 {"keep-symbol", required_argument, 0, 'K'},
399 {"merge-notes", no_argument, 0, 'M'},
400 {"no-merge-notes", no_argument, 0, OPTION_NO_MERGE_NOTES},
401 {"only-keep-debug", no_argument, 0, OPTION_ONLY_KEEP_DEBUG},
402 {"output-file", required_argument, 0, 'o'},
403 {"output-format", required_argument, 0, 'O'}, /* Obsolete */
404 {"output-target", required_argument, 0, 'O'},
405 {"preserve-dates", no_argument, 0, 'p'},
406 {"remove-section", required_argument, 0, 'R'},
407 {"remove-relocations", required_argument, 0, OPTION_REMOVE_RELOCS},
408 {"strip-section-headers", no_argument, 0, OPTION_STRIP_SECTION_HEADERS},
409 {"strip-all", no_argument, 0, 's'},
410 {"strip-debug", no_argument, 0, 'S'},
411 {"strip-dwo", no_argument, 0, OPTION_STRIP_DWO},
412 {"strip-symbol", required_argument, 0, 'N'},
413 {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
414 {"target", required_argument, 0, 'F'},
415 {"verbose", no_argument, 0, 'v'},
416 {"version", no_argument, 0, 'V'},
417 {"wildcard", no_argument, 0, 'w'},
418 {0, no_argument, 0, 0}
421 /* Options to handle if running as "objcopy". */
423 static struct option copy_options[] =
425 {"add-gnu-debuglink", required_argument, 0, OPTION_ADD_GNU_DEBUGLINK},
426 {"add-section", required_argument, 0, OPTION_ADD_SECTION},
427 {"add-symbol", required_argument, 0, OPTION_ADD_SYMBOL},
428 {"adjust-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
429 {"adjust-start", required_argument, 0, OPTION_CHANGE_START},
430 {"adjust-vma", required_argument, 0, OPTION_CHANGE_ADDRESSES},
431 {"adjust-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
432 {"alt-machine-code", required_argument, 0, OPTION_ALT_MACH_CODE},
433 {"binary-architecture", required_argument, 0, 'B'},
434 {"byte", required_argument, 0, 'b'},
435 {"change-addresses", required_argument, 0, OPTION_CHANGE_ADDRESSES},
436 {"change-leading-char", no_argument, 0, OPTION_CHANGE_LEADING_CHAR},
437 {"change-section-address", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
438 {"change-section-lma", required_argument, 0, OPTION_CHANGE_SECTION_LMA},
439 {"change-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_VMA},
440 {"change-start", required_argument, 0, OPTION_CHANGE_START},
441 {"change-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
442 {"compress-debug-sections", optional_argument, 0, OPTION_COMPRESS_DEBUG_SECTIONS},
443 {"debugging", no_argument, 0, OPTION_DEBUGGING},
444 {"decompress-debug-sections", no_argument, 0, OPTION_DECOMPRESS_DEBUG_SECTIONS},
445 {"disable-deterministic-archives", no_argument, 0, 'U'},
446 {"discard-all", no_argument, 0, 'x'},
447 {"discard-locals", no_argument, 0, 'X'},
448 {"dump-section", required_argument, 0, OPTION_DUMP_SECTION},
449 {"elf-stt-common", required_argument, 0, OPTION_ELF_STT_COMMON},
450 {"enable-deterministic-archives", no_argument, 0, 'D'},
451 {"extract-dwo", no_argument, 0, OPTION_EXTRACT_DWO},
452 {"extract-symbol", no_argument, 0, OPTION_EXTRACT_SYMBOL},
453 {"file-alignment", required_argument, 0, OPTION_FILE_ALIGNMENT},
454 {"format", required_argument, 0, 'F'}, /* Obsolete */
455 {"gap-fill", required_argument, 0, OPTION_GAP_FILL},
456 {"globalize-symbol", required_argument, 0, OPTION_GLOBALIZE_SYMBOL},
457 {"globalize-symbols", required_argument, 0, OPTION_GLOBALIZE_SYMBOLS},
458 {"heap", required_argument, 0, OPTION_HEAP},
459 {"help", no_argument, 0, 'h'},
460 {"image-base", required_argument, 0 , OPTION_IMAGE_BASE},
461 {"impure", no_argument, 0, OPTION_IMPURE},
462 {"info", no_argument, 0, OPTION_FORMATS_INFO},
463 {"input-format", required_argument, 0, 'I'}, /* Obsolete */
464 {"input-target", required_argument, 0, 'I'},
465 {"interleave", optional_argument, 0, 'i'},
466 {"interleave-width", required_argument, 0, OPTION_INTERLEAVE_WIDTH},
467 {"keep-file-symbols", no_argument, 0, OPTION_KEEP_FILE_SYMBOLS},
468 {"keep-global-symbol", required_argument, 0, 'G'},
469 {"keep-global-symbols", required_argument, 0, OPTION_KEEPGLOBAL_SYMBOLS},
470 {"keep-section", required_argument, 0, OPTION_KEEP_SECTION},
471 {"keep-symbol", required_argument, 0, 'K'},
472 {"keep-symbols", required_argument, 0, OPTION_KEEP_SYMBOLS},
473 {"keep-section-symbols", required_argument, 0, OPTION_KEEP_SECTION_SYMBOLS},
474 {"localize-hidden", no_argument, 0, OPTION_LOCALIZE_HIDDEN},
475 {"localize-symbol", required_argument, 0, 'L'},
476 {"localize-symbols", required_argument, 0, OPTION_LOCALIZE_SYMBOLS},
477 {"long-section-names", required_argument, 0, OPTION_LONG_SECTION_NAMES},
478 {"merge-notes", no_argument, 0, 'M'},
479 {"no-merge-notes", no_argument, 0, OPTION_NO_MERGE_NOTES},
480 {"no-adjust-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
481 {"no-change-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
482 {"only-keep-debug", no_argument, 0, OPTION_ONLY_KEEP_DEBUG},
483 {"only-section", required_argument, 0, 'j'},
484 {"output-format", required_argument, 0, 'O'}, /* Obsolete */
485 {"output-target", required_argument, 0, 'O'},
486 {"pad-to", required_argument, 0, OPTION_PAD_TO},
487 {"prefix-alloc-sections", required_argument, 0, OPTION_PREFIX_ALLOC_SECTIONS},
488 {"prefix-sections", required_argument, 0, OPTION_PREFIX_SECTIONS},
489 {"prefix-symbols", required_argument, 0, OPTION_PREFIX_SYMBOLS},
490 {"preserve-dates", no_argument, 0, 'p'},
491 {"pure", no_argument, 0, OPTION_PURE},
492 {"readonly-text", no_argument, 0, OPTION_READONLY_TEXT},
493 {"redefine-sym", required_argument, 0, OPTION_REDEFINE_SYM},
494 {"redefine-syms", required_argument, 0, OPTION_REDEFINE_SYMS},
495 {"remove-leading-char", no_argument, 0, OPTION_REMOVE_LEADING_CHAR},
496 {"remove-section", required_argument, 0, 'R'},
497 {"remove-relocations", required_argument, 0, OPTION_REMOVE_RELOCS},
498 {"strip-section-headers", no_argument, 0, OPTION_STRIP_SECTION_HEADERS},
499 {"rename-section", required_argument, 0, OPTION_RENAME_SECTION},
500 {"reverse-bytes", required_argument, 0, OPTION_REVERSE_BYTES},
501 {"section-alignment", required_argument, 0, OPTION_PE_SECTION_ALIGNMENT},
502 {"set-section-flags", required_argument, 0, OPTION_SET_SECTION_FLAGS},
503 {"set-section-alignment", required_argument, 0, OPTION_SET_SECTION_ALIGNMENT},
504 {"set-start", required_argument, 0, OPTION_SET_START},
505 {"srec-forceS3", no_argument, 0, OPTION_SREC_FORCES3},
506 {"srec-len", required_argument, 0, OPTION_SREC_LEN},
507 {"stack", required_argument, 0, OPTION_STACK},
508 {"strip-all", no_argument, 0, 'S'},
509 {"strip-debug", no_argument, 0, 'g'},
510 {"strip-dwo", no_argument, 0, OPTION_STRIP_DWO},
511 {"strip-symbol", required_argument, 0, 'N'},
512 {"strip-symbols", required_argument, 0, OPTION_STRIP_SYMBOLS},
513 {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
514 {"strip-unneeded-symbol", required_argument, 0, OPTION_STRIP_UNNEEDED_SYMBOL},
515 {"strip-unneeded-symbols", required_argument, 0, OPTION_STRIP_UNNEEDED_SYMBOLS},
516 {"subsystem", required_argument, 0, OPTION_SUBSYSTEM},
517 {"target", required_argument, 0, 'F'},
518 {"update-section", required_argument, 0, OPTION_UPDATE_SECTION},
519 {"verbose", no_argument, 0, 'v'},
520 {"verilog-data-width", required_argument, 0, OPTION_VERILOG_DATA_WIDTH},
521 {"version", no_argument, 0, 'V'},
522 {"weaken", no_argument, 0, OPTION_WEAKEN},
523 {"weaken-symbol", required_argument, 0, 'W'},
524 {"weaken-symbols", required_argument, 0, OPTION_WEAKEN_SYMBOLS},
525 {"wildcard", no_argument, 0, 'w'},
526 {"writable-text", no_argument, 0, OPTION_WRITABLE_TEXT},
527 {0, no_argument, 0, 0}
530 /* IMPORTS */
531 extern char *program_name;
533 /* This flag distinguishes between strip and objcopy:
534 1 means this is 'strip'; 0 means this is 'objcopy'.
535 -1 means if we should use argv[0] to decide. */
536 extern int is_strip;
538 /* The maximum length of an S record. This variable is defined in srec.c
539 and can be modified by the --srec-len parameter. */
540 extern unsigned int _bfd_srec_len;
542 /* Restrict the generation of Srecords to type S3 only.
543 This variable is defined in bfd/srec.c and can be toggled
544 on by the --srec-forceS3 command line switch. */
545 extern bool _bfd_srec_forceS3;
547 /* Width of data in bytes for verilog output.
548 This variable is declared in bfd/verilog.c and can be modified by
549 the --verilog-data-width parameter. */
550 extern unsigned int VerilogDataWidth;
552 /* Endianness of data for verilog output.
553 This variable is declared in bfd/verilog.c and is set in the
554 copy_object() function. */
555 extern enum bfd_endian VerilogDataEndianness;
557 /* Forward declarations. */
558 static bool setup_section (bfd *, asection *, bfd *);
559 static bool setup_bfd_headers (bfd *, bfd *);
560 static bool copy_relocations_in_section (bfd *, asection *, bfd *);
561 static bool copy_section (bfd *, asection *, bfd *);
562 static int compare_section_lma (const void *, const void *);
563 static bool mark_symbols_used_in_relocations (bfd *, asection *, asymbol **);
564 static bool write_debugging_info (bfd *, void *, long *, asymbol ***);
565 static const char *lookup_sym_redefinition (const char *);
566 static const char *find_section_rename (const char *, flagword *);
568 ATTRIBUTE_NORETURN static void
569 copy_usage (FILE *stream, int exit_status)
571 fprintf (stream, _("Usage: %s [option(s)] in-file [out-file]\n"), program_name);
572 fprintf (stream, _(" Copies a binary file, possibly transforming it in the process\n"));
573 fprintf (stream, _(" The options are:\n"));
574 fprintf (stream, _("\
575 -I --input-target <bfdname> Assume input file is in format <bfdname>\n\
576 -O --output-target <bfdname> Create an output file in format <bfdname>\n\
577 -B --binary-architecture <arch> Set output arch, when input is arch-less\n\
578 -F --target <bfdname> Set both input and output format to <bfdname>\n\
579 --debugging Convert debugging information, if possible\n\
580 -p --preserve-dates Copy modified/access timestamps to the output\n"));
581 if (DEFAULT_AR_DETERMINISTIC)
582 fprintf (stream, _("\
583 -D --enable-deterministic-archives\n\
584 Produce deterministic output when stripping archives (default)\n\
585 -U --disable-deterministic-archives\n\
586 Disable -D behavior\n"));
587 else
588 fprintf (stream, _("\
589 -D --enable-deterministic-archives\n\
590 Produce deterministic output when stripping archives\n\
591 -U --disable-deterministic-archives\n\
592 Disable -D behavior (default)\n"));
593 fprintf (stream, _("\
594 -j --only-section <name> Only copy section <name> into the output\n\
595 --add-gnu-debuglink=<file> Add section .gnu_debuglink linking to <file>\n\
596 -R --remove-section <name> Remove section <name> from the output\n\
597 --remove-relocations <name> Remove relocations from section <name>\n\
598 --strip-section-headers Strip section header from the output\n\
599 -S --strip-all Remove all symbol and relocation information\n\
600 -g --strip-debug Remove all debugging symbols & sections\n\
601 --strip-dwo Remove all DWO sections\n\
602 --strip-unneeded Remove all symbols not needed by relocations\n\
603 -N --strip-symbol <name> Do not copy symbol <name>\n\
604 --strip-unneeded-symbol <name>\n\
605 Do not copy symbol <name> unless needed by\n\
606 relocations\n\
607 --only-keep-debug Strip everything but the debug information\n\
608 --extract-dwo Copy only DWO sections\n\
609 --extract-symbol Remove section contents but keep symbols\n\
610 --keep-section <name> Do not strip section <name>\n\
611 -K --keep-symbol <name> Do not strip symbol <name>\n\
612 --keep-section-symbols Do not strip section symbols\n\
613 --keep-file-symbols Do not strip file symbol(s)\n\
614 --localize-hidden Turn all ELF hidden symbols into locals\n\
615 -L --localize-symbol <name> Force symbol <name> to be marked as a local\n\
616 --globalize-symbol <name> Force symbol <name> to be marked as a global\n\
617 -G --keep-global-symbol <name> Localize all symbols except <name>\n\
618 -W --weaken-symbol <name> Force symbol <name> to be marked as a weak\n\
619 --weaken Force all global symbols to be marked as weak\n\
620 -w --wildcard Permit wildcard in symbol comparison\n\
621 -x --discard-all Remove all non-global symbols\n\
622 -X --discard-locals Remove any compiler-generated symbols\n\
623 -i --interleave[=<number>] Only copy N out of every <number> bytes\n\
624 --interleave-width <number> Set N for --interleave\n\
625 -b --byte <num> Select byte <num> in every interleaved block\n\
626 --gap-fill <val> Fill gaps between sections with <val>\n\
627 --pad-to <addr> Pad the last section up to address <addr>\n\
628 --set-start <addr> Set the start address to <addr>\n\
629 {--change-start|--adjust-start} <incr>\n\
630 Add <incr> to the start address\n\
631 {--change-addresses|--adjust-vma} <incr>\n\
632 Add <incr> to LMA, VMA and start addresses\n\
633 {--change-section-address|--adjust-section-vma} <name>{=|+|-}<val>\n\
634 Change LMA and VMA of section <name> by <val>\n\
635 --change-section-lma <name>{=|+|-}<val>\n\
636 Change the LMA of section <name> by <val>\n\
637 --change-section-vma <name>{=|+|-}<val>\n\
638 Change the VMA of section <name> by <val>\n\
639 {--[no-]change-warnings|--[no-]adjust-warnings}\n\
640 Warn if a named section does not exist\n\
641 --set-section-flags <name>=<flags>\n\
642 Set section <name>'s properties to <flags>\n\
643 --set-section-alignment <name>=<align>\n\
644 Set section <name>'s alignment to <align> bytes\n\
645 --add-section <name>=<file> Add section <name> found in <file> to output\n\
646 --update-section <name>=<file>\n\
647 Update contents of section <name> with\n\
648 contents found in <file>\n\
649 --dump-section <name>=<file> Dump the contents of section <name> into <file>\n\
650 --rename-section <old>=<new>[,<flags>] Rename section <old> to <new>\n\
651 --long-section-names {enable|disable|keep}\n\
652 Handle long section names in Coff objects.\n\
653 --change-leading-char Force output format's leading character style\n\
654 --remove-leading-char Remove leading character from global symbols\n\
655 --reverse-bytes=<num> Reverse <num> bytes at a time, in output sections with content\n\
656 --redefine-sym <old>=<new> Redefine symbol name <old> to <new>\n\
657 --redefine-syms <file> --redefine-sym for all symbol pairs \n\
658 listed in <file>\n\
659 --srec-len <number> Restrict the length of generated Srecords\n\
660 --srec-forceS3 Restrict the type of generated Srecords to S3\n\
661 --strip-symbols <file> -N for all symbols listed in <file>\n\
662 --strip-unneeded-symbols <file>\n\
663 --strip-unneeded-symbol for all symbols listed\n\
664 in <file>\n\
665 --keep-symbols <file> -K for all symbols listed in <file>\n\
666 --localize-symbols <file> -L for all symbols listed in <file>\n\
667 --globalize-symbols <file> --globalize-symbol for all in <file>\n\
668 --keep-global-symbols <file> -G for all symbols listed in <file>\n\
669 --weaken-symbols <file> -W for all symbols listed in <file>\n\
670 --add-symbol <name>=[<section>:]<value>[,<flags>] Add a symbol\n\
671 --alt-machine-code <index> Use the target's <index>'th alternative machine\n\
672 --writable-text Mark the output text as writable\n\
673 --readonly-text Make the output text write protected\n\
674 --pure Mark the output file as demand paged\n\
675 --impure Mark the output file as impure\n\
676 --prefix-symbols <prefix> Add <prefix> to start of every symbol name\n\
677 --prefix-sections <prefix> Add <prefix> to start of every section name\n\
678 --prefix-alloc-sections <prefix>\n\
679 Add <prefix> to start of every allocatable\n\
680 section name\n\
681 --file-alignment <num> Set PE file alignment to <num>\n\
682 --heap <reserve>[,<commit>] Set PE reserve/commit heap to <reserve>/\n\
683 <commit>\n\
684 --image-base <address> Set PE image base to <address>\n\
685 --section-alignment <num> Set PE section alignment to <num>\n\
686 --stack <reserve>[,<commit>] Set PE reserve/commit stack to <reserve>/\n\
687 <commit>\n\
688 --subsystem <name>[:<version>]\n\
689 Set PE subsystem to <name> [& <version>]\n\
690 --compress-debug-sections[={none|zlib|zlib-gnu|zlib-gabi|zstd}]\n\
691 Compress DWARF debug sections\n\
692 --decompress-debug-sections Decompress DWARF debug sections using zlib\n\
693 --elf-stt-common=[yes|no] Generate ELF common symbols with STT_COMMON\n\
694 type\n\
695 --verilog-data-width <number> Specifies data width, in bytes, for verilog output\n\
696 -M --merge-notes Remove redundant entries in note sections\n\
697 --no-merge-notes Do not attempt to remove redundant notes (default)\n\
698 -v --verbose List all object files modified\n\
699 @<file> Read options from <file>\n\
700 -V --version Display this program's version number\n\
701 -h --help Display this output\n\
702 --info List object formats & architectures supported\n\
703 "));
704 list_supported_targets (program_name, stream);
705 if (REPORT_BUGS_TO[0] && exit_status == 0)
706 fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
707 exit (exit_status);
710 ATTRIBUTE_NORETURN static void
711 strip_usage (FILE *stream, int exit_status)
713 fprintf (stream, _("Usage: %s <option(s)> in-file(s)\n"), program_name);
714 fprintf (stream, _(" Removes symbols and sections from files\n"));
715 fprintf (stream, _(" The options are:\n"));
716 fprintf (stream, _("\
717 -I --input-target=<bfdname> Assume input file is in format <bfdname>\n\
718 -O --output-target=<bfdname> Create an output file in format <bfdname>\n\
719 -F --target=<bfdname> Set both input and output format to <bfdname>\n\
720 -p --preserve-dates Copy modified/access timestamps to the output\n\
721 "));
722 if (DEFAULT_AR_DETERMINISTIC)
723 fprintf (stream, _("\
724 -D --enable-deterministic-archives\n\
725 Produce deterministic output when stripping archives (default)\n\
726 -U --disable-deterministic-archives\n\
727 Disable -D behavior\n"));
728 else
729 fprintf (stream, _("\
730 -D --enable-deterministic-archives\n\
731 Produce deterministic output when stripping archives\n\
732 -U --disable-deterministic-archives\n\
733 Disable -D behavior (default)\n"));
734 fprintf (stream, _("\
735 -R --remove-section=<name> Also remove section <name> from the output\n\
736 --remove-relocations <name> Remove relocations from section <name>\n\
737 --strip-section-headers Strip section headers from the output\n\
738 -s --strip-all Remove all symbol and relocation information\n\
739 -g -S -d --strip-debug Remove all debugging symbols & sections\n\
740 --strip-dwo Remove all DWO sections\n\
741 --strip-unneeded Remove all symbols not needed by relocations\n\
742 --only-keep-debug Strip everything but the debug information\n\
743 -M --merge-notes Remove redundant entries in note sections (default)\n\
744 --no-merge-notes Do not attempt to remove redundant notes\n\
745 -N --strip-symbol=<name> Do not copy symbol <name>\n\
746 --keep-section=<name> Do not strip section <name>\n\
747 -K --keep-symbol=<name> Do not strip symbol <name>\n\
748 --keep-section-symbols Do not strip section symbols\n\
749 --keep-file-symbols Do not strip file symbol(s)\n\
750 -w --wildcard Permit wildcard in symbol comparison\n\
751 -x --discard-all Remove all non-global symbols\n\
752 -X --discard-locals Remove any compiler-generated symbols\n\
753 -v --verbose List all object files modified\n\
754 -V --version Display this program's version number\n\
755 -h --help Display this output\n\
756 --info List object formats & architectures supported\n\
757 -o <file> Place stripped output into <file>\n\
758 "));
760 list_supported_targets (program_name, stream);
761 if (REPORT_BUGS_TO[0] && exit_status == 0)
762 fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
763 exit (exit_status);
766 /* Parse section flags into a flagword, with a fatal error if the
767 string can't be parsed. */
769 static flagword
770 parse_flags (const char *s)
772 flagword ret;
773 const char *snext;
774 int len;
776 ret = SEC_NO_FLAGS;
780 snext = strchr (s, ',');
781 if (snext == NULL)
782 len = strlen (s);
783 else
785 len = snext - s;
786 ++snext;
789 if (0) ;
790 #define PARSE_FLAG(fname,fval) \
791 else if (strncasecmp (fname, s, len) == 0) ret |= fval
792 PARSE_FLAG ("alloc", SEC_ALLOC);
793 PARSE_FLAG ("load", SEC_LOAD);
794 PARSE_FLAG ("noload", SEC_NEVER_LOAD);
795 PARSE_FLAG ("readonly", SEC_READONLY);
796 PARSE_FLAG ("debug", SEC_DEBUGGING);
797 PARSE_FLAG ("code", SEC_CODE);
798 PARSE_FLAG ("data", SEC_DATA);
799 PARSE_FLAG ("rom", SEC_ROM);
800 PARSE_FLAG ("exclude", SEC_EXCLUDE);
801 PARSE_FLAG ("share", SEC_COFF_SHARED);
802 PARSE_FLAG ("contents", SEC_HAS_CONTENTS);
803 PARSE_FLAG ("merge", SEC_MERGE);
804 PARSE_FLAG ("strings", SEC_STRINGS);
805 PARSE_FLAG ("large", SEC_ELF_LARGE);
806 #undef PARSE_FLAG
807 else
809 char *copy;
811 copy = (char *) xmalloc (len + 1);
812 strncpy (copy, s, len);
813 copy[len] = '\0';
814 non_fatal (_("unrecognized section flag `%s'"), copy);
815 fatal (_ ("supported flags: %s"),
816 "alloc, load, noload, readonly, debug, code, data, rom, "
817 "exclude, contents, merge, strings, (COFF specific) share, "
818 "(ELF x86-64 specific) large");
821 s = snext;
823 while (s != NULL);
825 return ret;
828 /* Parse symbol flags into a flagword, with a fatal error if the
829 string can't be parsed. */
831 static flagword
832 parse_symflags (const char *s, const char **other)
834 flagword ret;
835 const char *snext;
836 size_t len;
838 ret = BSF_NO_FLAGS;
842 snext = strchr (s, ',');
843 if (snext == NULL)
844 len = strlen (s);
845 else
847 len = snext - s;
848 ++snext;
851 #define PARSE_FLAG(fname, fval) \
852 else if (len == sizeof fname - 1 \
853 && strncasecmp (fname, s, len) == 0) \
854 ret |= fval
856 #define PARSE_OTHER(fname, fval) \
857 else if (len >= sizeof fname \
858 && strncasecmp (fname, s, sizeof fname - 1) == 0) \
859 fval = xstrndup (s + sizeof fname - 1, len - sizeof fname + 1)
861 if (0) ;
862 PARSE_FLAG ("local", BSF_LOCAL);
863 PARSE_FLAG ("global", BSF_GLOBAL);
864 PARSE_FLAG ("export", BSF_EXPORT);
865 PARSE_FLAG ("debug", BSF_DEBUGGING);
866 PARSE_FLAG ("function", BSF_FUNCTION);
867 PARSE_FLAG ("weak", BSF_WEAK);
868 PARSE_FLAG ("section", BSF_SECTION_SYM);
869 PARSE_FLAG ("constructor", BSF_CONSTRUCTOR);
870 PARSE_FLAG ("warning", BSF_WARNING);
871 PARSE_FLAG ("indirect", BSF_INDIRECT);
872 PARSE_FLAG ("file", BSF_FILE);
873 PARSE_FLAG ("object", BSF_OBJECT);
874 PARSE_FLAG ("synthetic", BSF_SYNTHETIC);
875 PARSE_FLAG ("indirect-function", BSF_GNU_INDIRECT_FUNCTION | BSF_FUNCTION);
876 PARSE_FLAG ("unique-object", BSF_GNU_UNIQUE | BSF_OBJECT);
877 PARSE_OTHER ("before=", *other);
879 #undef PARSE_FLAG
880 #undef PARSE_OTHER
881 else
883 char *copy;
885 copy = (char *) xmalloc (len + 1);
886 strncpy (copy, s, len);
887 copy[len] = '\0';
888 non_fatal (_("unrecognized symbol flag `%s'"), copy);
889 fatal (_("supported flags: %s"),
890 "local, global, export, debug, function, weak, section, "
891 "constructor, warning, indirect, file, object, synthetic, "
892 "indirect-function, unique-object, before=<othersym>");
895 s = snext;
897 while (s != NULL);
899 return ret;
902 /* Find and optionally add an entry in the change_sections list.
904 We need to be careful in how we match section names because of the support
905 for wildcard characters. For example suppose that the user has invoked
906 objcopy like this:
908 --set-section-flags .debug_*=debug
909 --set-section-flags .debug_str=readonly,debug
910 --change-section-address .debug_*ranges=0x1000
912 With the idea that all debug sections will receive the DEBUG flag, the
913 .debug_str section will also receive the READONLY flag and the
914 .debug_ranges and .debug_aranges sections will have their address set to
915 0x1000. (This may not make much sense, but it is just an example).
917 When adding the section name patterns to the section list we need to make
918 sure that previous entries do not match with the new entry, unless the
919 match is exact. (In which case we assume that the user is overriding
920 the previous entry with the new context).
922 When matching real section names to the section list we make use of the
923 wildcard characters, but we must do so in context. Eg if we are setting
924 section addresses then we match for .debug_ranges but not for .debug_info.
926 Finally, if ADD is false and we do find a match, we mark the section list
927 entry as used. */
929 static struct section_list *
930 find_section_list (const char *name, bool add, unsigned int context)
932 struct section_list *p, *match = NULL;
934 /* assert ((context & ((1 << 7) - 1)) != 0); */
936 for (p = change_sections; p != NULL; p = p->next)
938 if (add)
940 if (strcmp (p->pattern, name) == 0)
942 /* Check for context conflicts. */
943 if (((p->context & SECTION_CONTEXT_REMOVE)
944 && (context & SECTION_CONTEXT_COPY))
945 || ((context & SECTION_CONTEXT_REMOVE)
946 && (p->context & SECTION_CONTEXT_COPY)))
947 fatal (_("error: %s both copied and removed"), name);
949 if (((p->context & SECTION_CONTEXT_SET_VMA)
950 && (context & SECTION_CONTEXT_ALTER_VMA))
951 || ((context & SECTION_CONTEXT_SET_VMA)
952 && (context & SECTION_CONTEXT_ALTER_VMA)))
953 fatal (_("error: %s both sets and alters VMA"), name);
955 if (((p->context & SECTION_CONTEXT_SET_LMA)
956 && (context & SECTION_CONTEXT_ALTER_LMA))
957 || ((context & SECTION_CONTEXT_SET_LMA)
958 && (context & SECTION_CONTEXT_ALTER_LMA)))
959 fatal (_("error: %s both sets and alters LMA"), name);
961 /* Extend the context. */
962 p->context |= context;
963 return p;
966 /* If we are not adding a new name/pattern then
967 only check for a match if the context applies. */
968 else if (p->context & context)
970 /* We could check for the presence of wildchar characters
971 first and choose between calling strcmp and fnmatch,
972 but is that really worth it ? */
973 if (p->pattern [0] == '!')
975 if (fnmatch (p->pattern + 1, name, 0) == 0)
977 p->used = true;
978 return NULL;
981 else
983 if (fnmatch (p->pattern, name, 0) == 0)
985 if (match == NULL)
986 match = p;
992 if (! add)
994 if (match != NULL)
995 match->used = true;
996 return match;
999 p = (struct section_list *) xmalloc (sizeof (struct section_list));
1000 p->pattern = name;
1001 p->used = false;
1002 p->context = context;
1003 p->vma_val = 0;
1004 p->lma_val = 0;
1005 p->flags = 0;
1006 p->alignment = 0;
1007 p->next = change_sections;
1008 change_sections = p;
1010 return p;
1013 /* S1 is the entry node already in the table, S2 is the key node. */
1015 static int
1016 eq_string_redefnode (const void *s1, const void *s2)
1018 struct redefine_node *node1 = (struct redefine_node *) s1;
1019 struct redefine_node *node2 = (struct redefine_node *) s2;
1020 return !strcmp ((const char *) node1->source, (const char *) node2->source);
1023 /* P is redefine node. Hash value is generated from its "source" filed. */
1025 static hashval_t
1026 htab_hash_redefnode (const void *p)
1028 struct redefine_node *redefnode = (struct redefine_node *) p;
1029 return htab_hash_string (redefnode->source);
1032 /* Create hashtab used for redefine node. */
1034 static htab_t
1035 create_symbol2redef_htab (void)
1037 return htab_create_alloc (16, htab_hash_redefnode, eq_string_redefnode, NULL,
1038 xcalloc, free);
1041 static htab_t
1042 create_symbol_htab (void)
1044 return htab_create_alloc (16, htab_hash_string, htab_eq_string, NULL,
1045 xcalloc, free);
1048 static void
1049 create_symbol_htabs (void)
1051 strip_specific_htab = create_symbol_htab ();
1052 strip_unneeded_htab = create_symbol_htab ();
1053 keep_specific_htab = create_symbol_htab ();
1054 localize_specific_htab = create_symbol_htab ();
1055 globalize_specific_htab = create_symbol_htab ();
1056 keepglobal_specific_htab = create_symbol_htab ();
1057 weaken_specific_htab = create_symbol_htab ();
1058 redefine_specific_htab = create_symbol2redef_htab ();
1059 /* As there is no bidirectional hash table in libiberty, need a reverse table
1060 to check duplicated target string. */
1061 redefine_specific_reverse_htab = create_symbol_htab ();
1064 static void
1065 delete_symbol_htabs (void)
1067 htab_delete (strip_specific_htab);
1068 htab_delete (strip_unneeded_htab);
1069 htab_delete (keep_specific_htab);
1070 htab_delete (localize_specific_htab);
1071 htab_delete (globalize_specific_htab);
1072 htab_delete (keepglobal_specific_htab);
1073 htab_delete (weaken_specific_htab);
1074 htab_delete (redefine_specific_htab);
1075 htab_delete (redefine_specific_reverse_htab);
1077 free (isympp);
1078 if (osympp != isympp)
1079 free (osympp);
1082 /* Add a symbol to strip_specific_list. */
1084 static void
1085 add_specific_symbol (const char *name, htab_t htab)
1087 *htab_find_slot (htab, name, INSERT) = (char *) name;
1090 /* Like add_specific_symbol, but the element type is void *. */
1092 static void
1093 add_specific_symbol_node (const void *node, htab_t htab)
1095 *htab_find_slot (htab, node, INSERT) = (void *) node;
1098 /* Add symbols listed in `filename' to strip_specific_list. */
1100 #define IS_WHITESPACE(c) ((c) == ' ' || (c) == '\t')
1101 #define IS_LINE_TERMINATOR(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
1103 static void
1104 add_specific_symbols (const char *filename, htab_t htab, char **buffer_p)
1106 off_t size;
1107 FILE * f;
1108 char * line;
1109 char * buffer;
1110 unsigned int line_count;
1112 size = get_file_size (filename);
1113 if (size == 0)
1115 status = 1;
1116 return;
1119 buffer = (char *) xmalloc (size + 2);
1120 f = fopen (filename, FOPEN_RT);
1121 if (f == NULL)
1122 fatal (_("cannot open '%s': %s"), filename, strerror (errno));
1124 if (fread (buffer, 1, size, f) == 0 || ferror (f))
1125 fatal (_("%s: fread failed"), filename);
1127 fclose (f);
1128 buffer [size] = '\n';
1129 buffer [size + 1] = '\0';
1131 line_count = 1;
1133 for (line = buffer; * line != '\0'; line ++)
1135 char * eol;
1136 char * name;
1137 char * name_end;
1138 int finished = false;
1140 for (eol = line;; eol ++)
1142 switch (* eol)
1144 case '\n':
1145 * eol = '\0';
1146 /* Cope with \n\r. */
1147 if (eol[1] == '\r')
1148 ++ eol;
1149 finished = true;
1150 break;
1152 case '\r':
1153 * eol = '\0';
1154 /* Cope with \r\n. */
1155 if (eol[1] == '\n')
1156 ++ eol;
1157 finished = true;
1158 break;
1160 case 0:
1161 finished = true;
1162 break;
1164 case '#':
1165 /* Line comment, Terminate the line here, in case a
1166 name is present and then allow the rest of the
1167 loop to find the real end of the line. */
1168 * eol = '\0';
1169 break;
1171 default:
1172 break;
1175 if (finished)
1176 break;
1179 /* A name may now exist somewhere between 'line' and 'eol'.
1180 Strip off leading whitespace and trailing whitespace,
1181 then add it to the list. */
1182 for (name = line; IS_WHITESPACE (* name); name ++)
1184 for (name_end = name;
1185 (! IS_WHITESPACE (* name_end))
1186 && (! IS_LINE_TERMINATOR (* name_end));
1187 name_end ++)
1190 if (! IS_LINE_TERMINATOR (* name_end))
1192 char * extra;
1194 for (extra = name_end + 1; IS_WHITESPACE (* extra); extra ++)
1197 if (! IS_LINE_TERMINATOR (* extra))
1198 non_fatal (_("%s:%d: Ignoring rubbish found on this line"),
1199 filename, line_count);
1202 * name_end = '\0';
1204 if (name_end > name)
1205 add_specific_symbol (name, htab);
1207 /* Advance line pointer to end of line. The 'eol ++' in the for
1208 loop above will then advance us to the start of the next line. */
1209 line = eol;
1210 line_count ++;
1213 /* Do not free the buffer. Parts of it will have been referenced
1214 in the calls to add_specific_symbol. */
1215 *buffer_p = buffer;
1218 /* See whether a symbol should be stripped or kept
1219 based on strip_specific_list and keep_symbols. */
1221 static int
1222 is_specified_symbol_predicate (void **slot, void *data)
1224 struct is_specified_symbol_predicate_data *d =
1225 (struct is_specified_symbol_predicate_data *) data;
1226 const char *slot_name = (char *) *slot;
1228 if (*slot_name != '!')
1230 if (! fnmatch (slot_name, d->name, 0))
1232 d->found = true;
1233 /* Continue traversal, there might be a non-match rule. */
1234 return 1;
1237 else
1239 if (! fnmatch (slot_name + 1, d->name, 0))
1241 d->found = false;
1242 /* Stop traversal. */
1243 return 0;
1247 /* Continue traversal. */
1248 return 1;
1251 static bool
1252 is_specified_symbol (const char *name, htab_t htab)
1254 if (wildcard)
1256 struct is_specified_symbol_predicate_data data;
1258 data.name = name;
1259 data.found = false;
1261 htab_traverse (htab, is_specified_symbol_predicate, &data);
1263 return data.found;
1266 return htab_find (htab, name) != NULL;
1269 /* Return a pointer to the symbol used as a signature for GROUP. */
1271 static asymbol *
1272 group_signature (asection *group)
1274 bfd *abfd = group->owner;
1275 Elf_Internal_Shdr *ghdr;
1277 /* PR 20089: An earlier error may have prevented us from loading the symbol table. */
1278 if (isympp == NULL)
1279 return NULL;
1281 if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
1282 return NULL;
1284 ghdr = &elf_section_data (group)->this_hdr;
1285 if (ghdr->sh_link == elf_onesymtab (abfd))
1287 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1288 Elf_Internal_Shdr *symhdr = &elf_symtab_hdr (abfd);
1290 if (ghdr->sh_info > 0
1291 && ghdr->sh_info < symhdr->sh_size / bed->s->sizeof_sym)
1292 return isympp[ghdr->sh_info - 1];
1294 return NULL;
1297 /* Return TRUE if the section is a DWO section. */
1299 static bool
1300 is_dwo_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1302 const char *name;
1303 int len;
1305 if (sec == NULL || (name = bfd_section_name (sec)) == NULL)
1306 return false;
1308 len = strlen (name);
1309 if (len < 5)
1310 return false;
1312 return startswith (name + len - 4, ".dwo");
1315 /* Return TRUE if section SEC is in the update list. */
1317 static bool
1318 is_update_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1320 if (update_sections != NULL)
1322 struct section_add *pupdate;
1324 for (pupdate = update_sections;
1325 pupdate != NULL;
1326 pupdate = pupdate->next)
1328 if (strcmp (sec->name, pupdate->name) == 0)
1329 return true;
1333 return false;
1336 static bool
1337 is_mergeable_note_section (bfd * abfd, asection * sec)
1339 if (merge_notes
1340 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
1341 && elf_section_data (sec)->this_hdr.sh_type == SHT_NOTE
1342 /* FIXME: We currently only support merging GNU_BUILD_NOTEs.
1343 We should add support for more note types. */
1344 && (startswith (sec->name, GNU_BUILD_ATTRS_SECTION_NAME)))
1345 return true;
1347 return false;
1350 /* See if a non-group section is being removed. */
1352 static bool
1353 is_strip_section_1 (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1355 if (find_section_list (bfd_section_name (sec), false, SECTION_CONTEXT_KEEP)
1356 != NULL)
1357 return false;
1359 if (sections_removed || sections_copied)
1361 struct section_list *p;
1362 struct section_list *q;
1364 p = find_section_list (bfd_section_name (sec), false,
1365 SECTION_CONTEXT_REMOVE);
1366 q = find_section_list (bfd_section_name (sec), false,
1367 SECTION_CONTEXT_COPY);
1369 if (p && q)
1370 fatal (_("error: section %s matches both remove and copy options"),
1371 bfd_section_name (sec));
1372 if (p && is_update_section (abfd, sec))
1373 fatal (_("error: section %s matches both update and remove options"),
1374 bfd_section_name (sec));
1376 if (p != NULL)
1377 return true;
1378 if (sections_copied && q == NULL)
1379 return true;
1382 /* Remove non-alloc sections for --strip-section-headers. */
1383 if (strip_section_headers
1384 && (bfd_section_flags (sec) & SEC_ALLOC) == 0)
1385 return true;
1387 if ((bfd_section_flags (sec) & SEC_DEBUGGING) != 0)
1389 if (strip_symbols == STRIP_DEBUG
1390 || strip_symbols == STRIP_UNNEEDED
1391 || strip_symbols == STRIP_ALL
1392 || discard_locals == LOCALS_ALL
1393 || convert_debugging)
1395 /* By default we don't want to strip .reloc section.
1396 This section has for pe-coff special meaning. See
1397 pe-dll.c file in ld, and peXXigen.c in bfd for details.
1398 Similarly we do not want to strip debuglink sections. */
1399 const char * kept_sections[] =
1401 ".reloc",
1402 ".gnu_debuglink",
1403 ".gnu_debugaltlink"
1405 int i;
1407 for (i = ARRAY_SIZE (kept_sections);i--;)
1408 if (strcmp (bfd_section_name (sec), kept_sections[i]) == 0)
1409 break;
1410 if (i == -1)
1411 return true;
1414 if (strip_symbols == STRIP_DWO)
1415 return is_dwo_section (abfd, sec);
1417 if (strip_symbols == STRIP_NONDEBUG)
1418 return false;
1421 if (strip_symbols == STRIP_NONDWO)
1422 return !is_dwo_section (abfd, sec);
1424 return false;
1427 /* See if a section is being removed. */
1429 static bool
1430 is_strip_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1432 if (is_strip_section_1 (abfd, sec))
1433 return true;
1435 if ((bfd_section_flags (sec) & SEC_GROUP) != 0)
1437 asymbol *gsym;
1438 const char *gname;
1439 asection *elt, *first;
1441 gsym = group_signature (sec);
1442 /* Strip groups without a valid signature. */
1443 if (gsym == NULL)
1444 return true;
1446 /* PR binutils/3181
1447 If we are going to strip the group signature symbol, then
1448 strip the group section too. */
1449 gname = gsym->name;
1450 if ((strip_symbols == STRIP_ALL
1451 && !is_specified_symbol (gname, keep_specific_htab))
1452 || is_specified_symbol (gname, strip_specific_htab))
1453 return true;
1455 /* Remove the group section if all members are removed. */
1456 first = elt = elf_next_in_group (sec);
1457 while (elt != NULL)
1459 if (!is_strip_section_1 (abfd, elt))
1460 return false;
1461 elt = elf_next_in_group (elt);
1462 if (elt == first)
1463 break;
1466 return true;
1469 return false;
1472 static bool
1473 is_nondebug_keep_contents_section (bfd *ibfd, asection *isection)
1475 /* Always keep ELF note sections. */
1476 if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour)
1477 return elf_section_type (isection) == SHT_NOTE;
1479 /* Always keep the .buildid section for PE/COFF.
1481 Strictly, this should be written "always keep the section storing the debug
1482 directory", but that may be the .text section for objects produced by some
1483 tools, which it is not sensible to keep. */
1484 if (bfd_get_flavour (ibfd) == bfd_target_coff_flavour)
1485 return strcmp (bfd_section_name (isection), ".buildid") == 0;
1487 return false;
1490 /* Return true if SYM is a hidden symbol. */
1492 static bool
1493 is_hidden_symbol (asymbol *sym)
1495 elf_symbol_type *elf_sym;
1497 elf_sym = elf_symbol_from (sym);
1498 if (elf_sym != NULL)
1499 switch (ELF_ST_VISIBILITY (elf_sym->internal_elf_sym.st_other))
1501 case STV_HIDDEN:
1502 case STV_INTERNAL:
1503 return true;
1505 return false;
1508 /* Empty name is hopefully never a valid symbol name. */
1509 static const char * empty_name = "";
1511 static bool
1512 need_sym_before (struct addsym_node **node, const char *sym)
1514 int count;
1515 struct addsym_node *ptr = add_sym_list;
1517 /* 'othersym' symbols are at the front of the list. */
1518 for (count = 0; count < add_symbols; count++)
1520 if (!ptr->othersym)
1521 break;
1522 if (ptr->othersym == empty_name)
1523 continue;
1524 else if (strcmp (ptr->othersym, sym) == 0)
1526 free ((char *) ptr->othersym);
1527 ptr->othersym = empty_name;
1528 *node = ptr;
1529 return true;
1531 ptr = ptr->next;
1533 return false;
1536 static asymbol *
1537 create_new_symbol (struct addsym_node *ptr, bfd *obfd)
1539 asymbol *sym = bfd_make_empty_symbol (obfd);
1541 bfd_set_asymbol_name (sym, ptr->symdef);
1542 sym->value = ptr->symval;
1543 sym->flags = ptr->flags;
1544 if (ptr->section)
1546 asection *sec = bfd_get_section_by_name (obfd, ptr->section);
1547 if (!sec)
1548 fatal (_("Section %s not found"), ptr->section);
1549 sym->section = sec;
1551 else
1552 sym->section = bfd_abs_section_ptr;
1553 return sym;
1556 /* Choose which symbol entries to copy; put the result in OSYMS.
1557 We don't copy in place, because that confuses the relocs.
1558 Update the number of symbols to print. */
1560 static bool
1561 filter_symbols (bfd *abfd, bfd *obfd, asymbol **osyms,
1562 asymbol **isyms, long *symcount)
1564 asymbol **from = isyms, **to = osyms;
1565 long src_count = 0, dst_count = 0;
1566 int relocatable = (abfd->flags & (EXEC_P | DYNAMIC)) == 0;
1568 for (; src_count < *symcount; src_count++)
1570 asymbol *sym = from[src_count];
1571 flagword flags = sym->flags;
1572 char *name = (char *) bfd_asymbol_name (sym);
1573 bool keep;
1574 bool used_in_reloc = false;
1575 bool undefined;
1576 bool rem_leading_char;
1577 bool add_leading_char;
1579 undefined = bfd_is_und_section (bfd_asymbol_section (sym));
1581 if (add_sym_list)
1583 struct addsym_node *ptr;
1585 if (need_sym_before (&ptr, name))
1586 to[dst_count++] = create_new_symbol (ptr, obfd);
1589 if (htab_elements (redefine_specific_htab) || section_rename_list)
1591 char *new_name;
1593 if (name[0] == '_'
1594 && name[1] == '_'
1595 && strcmp (name + (name[2] == '_'), "__gnu_lto_slim") == 0)
1597 fatal (_("redefining symbols does not work"
1598 " on LTO-compiled object files"));
1601 new_name = (char *) lookup_sym_redefinition (name);
1602 if (new_name == name
1603 && (flags & BSF_SECTION_SYM) != 0)
1604 new_name = (char *) find_section_rename (name, NULL);
1605 bfd_set_asymbol_name (sym, new_name);
1606 name = new_name;
1609 /* Check if we will remove the current leading character. */
1610 rem_leading_char =
1611 (name[0] != '\0'
1612 && name[0] == bfd_get_symbol_leading_char (abfd)
1613 && (change_leading_char
1614 || (remove_leading_char
1615 && ((flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1616 || undefined
1617 || bfd_is_com_section (bfd_asymbol_section (sym))))));
1619 /* Check if we will add a new leading character. */
1620 add_leading_char =
1621 change_leading_char
1622 && (bfd_get_symbol_leading_char (obfd) != '\0')
1623 && (bfd_get_symbol_leading_char (abfd) == '\0'
1624 || (name[0] == bfd_get_symbol_leading_char (abfd)));
1626 /* Short circuit for change_leading_char if we can do it in-place. */
1627 if (rem_leading_char && add_leading_char && !prefix_symbols_string)
1629 name[0] = bfd_get_symbol_leading_char (obfd);
1630 bfd_set_asymbol_name (sym, name);
1631 rem_leading_char = false;
1632 add_leading_char = false;
1635 /* Remove leading char. */
1636 if (rem_leading_char)
1637 bfd_set_asymbol_name (sym, ++name);
1639 /* Add new leading char and/or prefix. */
1640 if (add_leading_char || prefix_symbols_string)
1642 char *n, *ptr;
1643 size_t len = strlen (name) + 1;
1645 if (add_leading_char)
1646 len++;
1647 if (prefix_symbols_string)
1648 len += strlen (prefix_symbols_string);
1650 ptr = n = (char *) xmalloc (len);
1651 if (add_leading_char)
1652 *ptr++ = bfd_get_symbol_leading_char (obfd);
1654 if (prefix_symbols_string)
1656 strcpy (ptr, prefix_symbols_string);
1657 ptr += strlen (prefix_symbols_string);
1660 strcpy (ptr, name);
1661 bfd_set_asymbol_name (sym, n);
1662 name = n;
1665 if (strip_symbols == STRIP_ALL)
1666 keep = false;
1667 else if ((flags & BSF_KEEP) != 0 /* Used in relocation. */
1668 || ((flags & BSF_SECTION_SYM) != 0
1669 && (bfd_asymbol_section (sym)->symbol->flags
1670 & BSF_KEEP) != 0))
1672 keep = true;
1673 used_in_reloc = true;
1675 else if (relocatable /* Relocatable file. */
1676 && ((flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1677 || bfd_is_com_section (bfd_asymbol_section (sym))))
1678 keep = true;
1679 else if (bfd_decode_symclass (sym) == 'I')
1680 /* Global symbols in $idata sections need to be retained
1681 even if relocatable is FALSE. External users of the
1682 library containing the $idata section may reference these
1683 symbols. */
1684 keep = true;
1685 else if ((flags & BSF_GLOBAL) != 0 /* Global symbol. */
1686 || (flags & BSF_WEAK) != 0
1687 || undefined
1688 || bfd_is_com_section (bfd_asymbol_section (sym)))
1689 keep = strip_symbols != STRIP_UNNEEDED;
1690 else if ((flags & BSF_DEBUGGING) != 0) /* Debugging symbol. */
1691 keep = (strip_symbols != STRIP_DEBUG
1692 && strip_symbols != STRIP_UNNEEDED
1693 && ! convert_debugging);
1694 else if (bfd_coff_get_comdat_section (abfd, bfd_asymbol_section (sym)))
1695 /* COMDAT sections store special information in local
1696 symbols, so we cannot risk stripping any of them. */
1697 keep = true;
1698 else /* Local symbol. */
1699 keep = (strip_symbols != STRIP_UNNEEDED
1700 && (discard_locals != LOCALS_ALL
1701 && (discard_locals != LOCALS_START_L
1702 || ! bfd_is_local_label (abfd, sym))));
1704 if (keep && is_specified_symbol (name, strip_specific_htab))
1706 /* There are multiple ways to set 'keep' above, but if it
1707 was the relocatable symbol case, then that's an error. */
1708 if (used_in_reloc)
1710 non_fatal (_("not stripping symbol `%s' because it is named in a relocation"), name);
1711 return false;
1713 else
1714 keep = false;
1717 if (keep
1718 && !(flags & BSF_KEEP)
1719 && is_specified_symbol (name, strip_unneeded_htab))
1720 keep = false;
1722 if (!keep
1723 && ((keep_file_symbols && (flags & BSF_FILE))
1724 || is_specified_symbol (name, keep_specific_htab)))
1725 keep = true;
1727 if (keep && is_strip_section (abfd, bfd_asymbol_section (sym)))
1728 keep = false;
1730 if (keep)
1732 if (!undefined
1733 && (flags & (BSF_GLOBAL | BSF_WEAK))
1734 && (is_specified_symbol (name, localize_specific_htab)
1735 || (htab_elements (keepglobal_specific_htab) != 0
1736 && ! is_specified_symbol (name, keepglobal_specific_htab))
1737 || (localize_hidden && is_hidden_symbol (sym))))
1739 flags &= ~(BSF_GLOBAL | BSF_WEAK);
1740 flags |= BSF_LOCAL;
1743 else if (!undefined
1744 && (flags & BSF_LOCAL)
1745 && !(flags & BSF_FILE)
1746 && is_specified_symbol (name, globalize_specific_htab))
1748 flags &= ~BSF_LOCAL;
1749 flags |= BSF_GLOBAL;
1752 if (((flags & (BSF_GLOBAL | BSF_GNU_UNIQUE))
1753 || undefined)
1754 && (weaken || is_specified_symbol (name, weaken_specific_htab)))
1756 flags &= ~(BSF_GLOBAL | BSF_GNU_UNIQUE);
1757 flags |= BSF_WEAK;
1760 sym->flags = flags;
1761 to[dst_count++] = sym;
1764 if (add_sym_list)
1766 struct addsym_node *ptr = add_sym_list;
1768 for (src_count = 0; src_count < add_symbols; src_count++)
1770 if (ptr->othersym)
1772 if (ptr->othersym != empty_name)
1773 fatal (_("'before=%s' not found"), ptr->othersym);
1775 else
1776 to[dst_count++] = create_new_symbol (ptr, obfd);
1778 ptr = ptr->next;
1782 to[dst_count] = NULL;
1783 *symcount = dst_count;
1785 return true;
1788 /* Find the redefined name of symbol SOURCE. */
1790 static const char *
1791 lookup_sym_redefinition (const char *source)
1793 struct redefine_node key_node = {(char *) source, NULL};
1794 struct redefine_node *redef_node
1795 = (struct redefine_node *) htab_find (redefine_specific_htab, &key_node);
1797 return redef_node == NULL ? source : redef_node->target;
1800 /* Insert a node into symbol redefine hash tabel. */
1802 static void
1803 add_redefine_and_check (const char *cause, const char *source,
1804 const char *target)
1806 struct redefine_node *new_node
1807 = (struct redefine_node *) xmalloc (sizeof (struct redefine_node));
1809 new_node->source = strdup (source);
1810 new_node->target = strdup (target);
1812 if (htab_find (redefine_specific_htab, new_node) != HTAB_EMPTY_ENTRY)
1813 fatal (_("%s: Multiple redefinition of symbol \"%s\""),
1814 cause, source);
1816 if (htab_find (redefine_specific_reverse_htab, target) != HTAB_EMPTY_ENTRY)
1817 fatal (_("%s: Symbol \"%s\" is target of more than one redefinition"),
1818 cause, target);
1820 /* Insert the NEW_NODE into hash table for quick search. */
1821 add_specific_symbol_node (new_node, redefine_specific_htab);
1823 /* Insert the target string into the reverse hash table, this is needed for
1824 duplicated target string check. */
1825 add_specific_symbol (new_node->target, redefine_specific_reverse_htab);
1829 /* Handle the --redefine-syms option. Read lines containing "old new"
1830 from the file, and add them to the symbol redefine list. */
1832 static void
1833 add_redefine_syms_file (const char *filename)
1835 FILE *file;
1836 char *buf;
1837 size_t bufsize;
1838 size_t len;
1839 size_t outsym_off;
1840 int c, lineno;
1842 file = fopen (filename, "r");
1843 if (file == NULL)
1844 fatal (_("couldn't open symbol redefinition file %s (error: %s)"),
1845 filename, strerror (errno));
1847 bufsize = 100;
1848 buf = (char *) xmalloc (bufsize + 1 /* For the terminating NUL. */);
1850 lineno = 1;
1851 c = getc (file);
1852 len = 0;
1853 outsym_off = 0;
1854 while (c != EOF)
1856 /* Collect the input symbol name. */
1857 while (! IS_WHITESPACE (c) && ! IS_LINE_TERMINATOR (c) && c != EOF)
1859 if (c == '#')
1860 goto comment;
1861 buf[len++] = c;
1862 if (len >= bufsize)
1864 bufsize *= 2;
1865 buf = (char *) xrealloc (buf, bufsize + 1);
1867 c = getc (file);
1869 buf[len++] = '\0';
1870 if (c == EOF)
1871 break;
1873 /* Eat white space between the symbol names. */
1874 while (IS_WHITESPACE (c))
1875 c = getc (file);
1876 if (c == '#' || IS_LINE_TERMINATOR (c))
1877 goto comment;
1878 if (c == EOF)
1879 break;
1881 /* Collect the output symbol name. */
1882 outsym_off = len;
1883 while (! IS_WHITESPACE (c) && ! IS_LINE_TERMINATOR (c) && c != EOF)
1885 if (c == '#')
1886 goto comment;
1887 buf[len++] = c;
1888 if (len >= bufsize)
1890 bufsize *= 2;
1891 buf = (char *) xrealloc (buf, bufsize + 1);
1893 c = getc (file);
1895 buf[len++] = '\0';
1896 if (c == EOF)
1897 break;
1899 /* Eat white space at end of line. */
1900 while (! IS_LINE_TERMINATOR(c) && c != EOF && IS_WHITESPACE (c))
1901 c = getc (file);
1902 if (c == '#')
1903 goto comment;
1904 /* Handle \r\n. */
1905 if ((c == '\r' && (c = getc (file)) == '\n')
1906 || c == '\n' || c == EOF)
1908 end_of_line:
1909 /* Append the redefinition to the list. */
1910 if (buf[0] != '\0')
1911 add_redefine_and_check (filename, &buf[0], &buf[outsym_off]);
1913 lineno++;
1914 len = 0;
1915 outsym_off = 0;
1916 if (c == EOF)
1917 break;
1918 c = getc (file);
1919 continue;
1921 else
1922 fatal (_("%s:%d: garbage found at end of line"), filename, lineno);
1923 comment:
1924 if (len != 0 && (outsym_off == 0 || outsym_off == len))
1925 fatal (_("%s:%d: missing new symbol name"), filename, lineno);
1926 buf[len++] = '\0';
1928 /* Eat the rest of the line and finish it. */
1929 while (c != '\n' && c != EOF)
1930 c = getc (file);
1931 goto end_of_line;
1934 if (len != 0)
1935 fatal (_("%s:%d: premature end of file"), filename, lineno);
1937 free (buf);
1938 fclose (file);
1941 /* Copy unknown object file IBFD onto OBFD.
1942 Returns TRUE upon success, FALSE otherwise. */
1944 static bool
1945 copy_unknown_object (bfd *ibfd, bfd *obfd)
1947 char *cbuf;
1948 bfd_size_type tocopy;
1949 off_t size;
1950 struct stat buf;
1952 if (bfd_stat_arch_elt (ibfd, &buf) != 0)
1954 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1955 return false;
1958 size = buf.st_size;
1959 if (size < 0)
1961 non_fatal (_("stat returns negative size for `%s'"),
1962 bfd_get_archive_filename (ibfd));
1963 return false;
1966 if (bfd_seek (ibfd, 0, SEEK_SET) != 0)
1968 bfd_nonfatal (bfd_get_archive_filename (ibfd));
1969 return false;
1972 if (verbose)
1973 printf (_("copy from `%s' [unknown] to `%s' [unknown]\n"),
1974 bfd_get_archive_filename (ibfd), bfd_get_filename (obfd));
1976 cbuf = (char *) xmalloc (BUFSIZE);
1977 while (size != 0)
1979 if (size > BUFSIZE)
1980 tocopy = BUFSIZE;
1981 else
1982 tocopy = size;
1984 if (bfd_read (cbuf, tocopy, ibfd) != tocopy)
1986 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1987 free (cbuf);
1988 return false;
1991 if (bfd_write (cbuf, tocopy, obfd) != tocopy)
1993 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
1994 free (cbuf);
1995 return false;
1998 size -= tocopy;
2001 /* We should at least to be able to read it back when copying an
2002 unknown object in an archive. */
2003 chmod (bfd_get_filename (obfd), buf.st_mode | S_IRUSR);
2004 free (cbuf);
2005 return true;
2008 typedef struct objcopy_internal_note
2010 Elf_Internal_Note note;
2011 unsigned long padded_namesz;
2012 bfd_vma start;
2013 bfd_vma end;
2014 } objcopy_internal_note;
2016 #define DEBUG_MERGE 0
2018 #if DEBUG_MERGE
2019 #define merge_debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
2020 #else
2021 #define merge_debug(format, ...)
2022 #endif
2024 /* Returns TRUE iff PNOTE1 overlaps or adjoins PNOTE2. */
2026 static bool
2027 overlaps_or_adjoins (objcopy_internal_note * pnote1,
2028 objcopy_internal_note * pnote2)
2030 if (pnote1->end < pnote2->start)
2031 /* FIXME: Alignment of 16 bytes taken from x86_64 binaries.
2032 Really we should extract the alignment of the section
2033 covered by the notes. */
2034 return BFD_ALIGN (pnote1->end, 16) < pnote2->start;
2036 if (pnote2->end < pnote2->start)
2037 return BFD_ALIGN (pnote2->end, 16) < pnote1->start;
2039 if (pnote1->end < pnote2->end)
2040 return true;
2042 if (pnote2->end < pnote1->end)
2043 return true;
2045 return false;
2048 /* Returns TRUE iff NEEDLE is fully contained by HAYSTACK. */
2050 static bool
2051 contained_by (objcopy_internal_note * needle,
2052 objcopy_internal_note * haystack)
2054 return needle->start >= haystack->start && needle->end <= haystack->end;
2057 static inline bool
2058 is_open_note (objcopy_internal_note * pnote)
2060 return pnote->note.type == NT_GNU_BUILD_ATTRIBUTE_OPEN;
2063 static inline bool
2064 is_func_note (objcopy_internal_note * pnote)
2066 return pnote->note.type == NT_GNU_BUILD_ATTRIBUTE_FUNC;
2069 static inline bool
2070 is_deleted_note (objcopy_internal_note * pnote)
2072 return pnote->note.type == 0;
2075 static bool
2076 is_version_note (objcopy_internal_note * pnote)
2078 return (pnote->note.namesz > 4
2079 && pnote->note.namedata[0] == 'G'
2080 && pnote->note.namedata[1] == 'A'
2081 && pnote->note.namedata[2] == '$'
2082 && pnote->note.namedata[3] == GNU_BUILD_ATTRIBUTE_VERSION);
2085 static bool
2086 is_64bit (bfd * abfd)
2088 /* Should never happen, but let's be paranoid. */
2089 if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
2090 return false;
2092 return elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64;
2095 /* This sorting function is used to get the notes into an order
2096 that makes merging easy. */
2098 static int
2099 compare_gnu_build_notes (const void * data1, const void * data2)
2101 objcopy_internal_note * pnote1 = (objcopy_internal_note *) data1;
2102 objcopy_internal_note * pnote2 = (objcopy_internal_note *) data2;
2104 /* Sort notes based upon the attribute they record. */
2105 int cmp = memcmp (pnote1->note.namedata + 3,
2106 pnote2->note.namedata + 3,
2107 pnote1->note.namesz < pnote2->note.namesz ?
2108 pnote1->note.namesz - 3 : pnote2->note.namesz - 3);
2109 if (cmp)
2110 return cmp;
2112 if (pnote1->end < pnote2->start)
2113 return -1;
2114 if (pnote1->start > pnote2->end)
2115 return 1;
2117 /* Overlaps - we should merge the two ranges. */
2118 if (pnote1->start < pnote2->start)
2119 return -1;
2120 if (pnote1->end > pnote2->end)
2121 return 1;
2122 if (pnote1->end < pnote2->end)
2123 return -1;
2125 /* Put OPEN notes before function notes. */
2126 if (is_open_note (pnote1) && ! is_open_note (pnote2))
2127 return -1;
2128 if (! is_open_note (pnote1) && is_open_note (pnote2))
2129 return 1;
2131 return 0;
2134 /* This sorting function is used to get the notes into an order
2135 that makes eliminating address ranges easier. */
2137 static int
2138 sort_gnu_build_notes (const void * data1, const void * data2)
2140 objcopy_internal_note * pnote1 = (objcopy_internal_note *) data1;
2141 objcopy_internal_note * pnote2 = (objcopy_internal_note *) data2;
2143 if (pnote1->note.type != pnote2->note.type)
2145 /* Move deleted notes to the end. */
2146 if (is_deleted_note (pnote1)) /* 1: OFD 2: OFD */
2147 return 1;
2149 /* Move OPEN notes to the start. */
2150 if (is_open_note (pnote1)) /* 1: OF 2: OFD */
2151 return -1;
2153 if (is_deleted_note (pnote2)) /* 1: F 2: O D */
2154 return -1;
2156 return 1; /* 1: F 2: O */
2159 /* Sort by starting address. */
2160 if (pnote1->start < pnote2->start)
2161 return -1;
2162 if (pnote1->start > pnote2->start)
2163 return 1;
2165 /* Then by end address (bigger range first). */
2166 if (pnote1->end > pnote2->end)
2167 return -1;
2168 if (pnote1->end < pnote2->end)
2169 return 1;
2171 /* Then by attribute type. */
2172 if (pnote1->note.namesz > 4
2173 && pnote2->note.namesz > 4
2174 && pnote1->note.namedata[3] != pnote2->note.namedata[3])
2175 return pnote1->note.namedata[3] - pnote2->note.namedata[3];
2177 return 0;
2180 /* Merge the notes on SEC, removing redundant entries. NEW_SIZE is
2181 set to the new, smaller size of the section. Returns true on
2182 success, false on errors that result in objcopy failing. */
2184 static bool
2185 merge_gnu_build_notes (bfd * abfd,
2186 asection * sec,
2187 bfd_size_type size,
2188 bfd_byte * contents,
2189 bfd_size_type *new_size)
2191 objcopy_internal_note * pnotes_end;
2192 objcopy_internal_note * pnotes = NULL;
2193 objcopy_internal_note * pnote;
2194 bfd_size_type remain = size;
2195 unsigned version_1_seen = 0;
2196 unsigned version_2_seen = 0;
2197 unsigned version_3_seen = 0;
2198 const char * err = NULL;
2199 bfd_byte * in = contents;
2200 unsigned long previous_func_start = 0;
2201 unsigned long previous_open_start = 0;
2202 unsigned long previous_func_end = 0;
2203 unsigned long previous_open_end = 0;
2204 long relsize;
2206 *new_size = size;
2207 relsize = bfd_get_reloc_upper_bound (abfd, sec);
2208 if (relsize > 0)
2210 arelent ** relpp;
2211 long relcount;
2213 /* If there are relocs associated with this section then we
2214 cannot safely merge it. */
2215 relpp = (arelent **) xmalloc (relsize);
2216 relcount = bfd_canonicalize_reloc (abfd, sec, relpp, isympp);
2217 free (relpp);
2218 if (relcount != 0)
2220 if (! is_strip)
2221 non_fatal (_("%s[%s]: Cannot merge - there are relocations against this section"),
2222 bfd_get_filename (abfd), bfd_section_name (sec));
2223 goto done;
2227 /* Make a copy of the notes and convert to our internal format.
2228 Minimum size of a note is 12 bytes. Also locate the version
2229 notes and check them. */
2230 pnote = pnotes = (objcopy_internal_note *)
2231 xcalloc ((size / 12), sizeof (* pnote));
2232 while (remain >= 12)
2234 bfd_vma start, end;
2236 pnote->note.namesz = bfd_get_32 (abfd, in);
2237 pnote->note.descsz = bfd_get_32 (abfd, in + 4);
2238 pnote->note.type = bfd_get_32 (abfd, in + 8);
2239 pnote->padded_namesz = (pnote->note.namesz + 3) & ~3;
2241 if (((pnote->note.descsz + 3) & ~3) != pnote->note.descsz)
2243 err = _("corrupt GNU build attribute note: description size not a factor of 4");
2244 goto done;
2247 if (pnote->note.type != NT_GNU_BUILD_ATTRIBUTE_OPEN
2248 && pnote->note.type != NT_GNU_BUILD_ATTRIBUTE_FUNC)
2250 err = _("corrupt GNU build attribute note: wrong note type");
2251 goto done;
2254 if (pnote->padded_namesz + pnote->note.descsz + 12 > remain)
2256 err = _("corrupt GNU build attribute note: note too big");
2257 goto done;
2260 if (pnote->note.namesz < 2)
2262 err = _("corrupt GNU build attribute note: name too small");
2263 goto done;
2266 pnote->note.namedata = (char *)(in + 12);
2267 pnote->note.descdata = (char *)(in + 12 + pnote->padded_namesz);
2269 remain -= 12 + pnote->padded_namesz + pnote->note.descsz;
2270 in += 12 + pnote->padded_namesz + pnote->note.descsz;
2272 if (pnote->note.namesz > 2
2273 && pnote->note.namedata[0] == '$'
2274 && pnote->note.namedata[1] == GNU_BUILD_ATTRIBUTE_VERSION
2275 && pnote->note.namedata[2] == '1')
2276 ++ version_1_seen;
2277 else if (is_version_note (pnote))
2279 if (pnote->note.namedata[4] == '2')
2280 ++ version_2_seen;
2281 else if (pnote->note.namedata[4] == '3')
2282 ++ version_3_seen;
2283 else
2285 err = _("corrupt GNU build attribute note: unsupported version");
2286 goto done;
2290 switch (pnote->note.descsz)
2292 case 0:
2293 start = end = 0;
2294 break;
2296 case 4:
2297 start = bfd_get_32 (abfd, pnote->note.descdata);
2298 /* FIXME: For version 1 and 2 notes we should try to
2299 calculate the end address by finding a symbol whose
2300 value is START, and then adding in its size.
2302 For now though, since v1 and v2 was not intended to
2303 handle gaps, we chose an artificially large end
2304 address. */
2305 end = (bfd_vma) -1;
2306 break;
2308 case 8:
2309 start = bfd_get_32 (abfd, pnote->note.descdata);
2310 end = bfd_get_32 (abfd, pnote->note.descdata + 4);
2311 break;
2313 case 16:
2314 start = bfd_get_64 (abfd, pnote->note.descdata);
2315 end = bfd_get_64 (abfd, pnote->note.descdata + 8);
2316 break;
2318 default:
2319 err = _("corrupt GNU build attribute note: bad description size");
2320 goto done;
2323 if (start > end)
2324 /* This can happen with PPC64LE binaries where empty notes are
2325 encoded as start = end + 4. */
2326 start = end;
2328 if (is_open_note (pnote))
2330 if (start)
2331 previous_open_start = start;
2333 pnote->start = previous_open_start;
2335 if (end)
2336 previous_open_end = end;
2338 pnote->end = previous_open_end;
2340 else
2342 if (start)
2343 previous_func_start = start;
2345 pnote->start = previous_func_start;
2347 if (end)
2348 previous_func_end = end;
2350 pnote->end = previous_func_end;
2353 if (pnote->note.namedata[pnote->note.namesz - 1] != 0)
2355 err = _("corrupt GNU build attribute note: name not NUL terminated");
2356 goto done;
2359 pnote ++;
2362 pnotes_end = pnote;
2364 /* Check that the notes are valid. */
2365 if (remain != 0)
2367 err = _("corrupt GNU build attribute notes: excess data at end");
2368 goto done;
2371 if (version_1_seen == 0 && version_2_seen == 0 && version_3_seen == 0)
2373 #if 0
2374 err = _("bad GNU build attribute notes: no known versions detected");
2375 goto done;
2376 #else
2377 /* This happens with glibc. No idea why. */
2378 non_fatal (_("%s[%s]: Warning: version note missing - assuming version 3"),
2379 bfd_get_filename (abfd), bfd_section_name (sec));
2380 version_3_seen = 2;
2381 #endif
2384 if ( (version_1_seen > 0 && version_2_seen > 0)
2385 || (version_1_seen > 0 && version_3_seen > 0)
2386 || (version_2_seen > 0 && version_3_seen > 0))
2388 err = _("bad GNU build attribute notes: multiple different versions");
2389 goto done;
2392 /* We are now only supporting the merging v3+ notes
2393 - it makes things much simpler. */
2394 if (version_3_seen == 0)
2396 merge_debug ("%s: skipping merge - not using v3 notes", bfd_section_name (sec));
2397 goto done;
2400 merge_debug ("Merging section %s which contains %ld notes\n",
2401 sec->name, pnotes_end - pnotes);
2403 /* Sort the notes. */
2404 qsort (pnotes, pnotes_end - pnotes, sizeof (* pnotes),
2405 compare_gnu_build_notes);
2407 #if DEBUG_MERGE
2408 merge_debug ("Results of initial sort:\n");
2409 for (pnote = pnotes; pnote < pnotes_end; pnote ++)
2410 merge_debug ("offset %#08lx range %#08lx..%#08lx type %ld attribute %d namesz %ld\n",
2411 (pnote->note.namedata - (char *) contents) - 12,
2412 pnote->start, pnote->end,
2413 pnote->note.type,
2414 pnote->note.namedata[3],
2415 pnote->note.namesz
2417 #endif
2419 /* Now merge the notes. The rules are:
2420 1. If a note has a zero range, it can be eliminated.
2421 2. If two notes have the same namedata then:
2422 2a. If one note's range is fully covered by the other note
2423 then it can be deleted.
2424 2b. If one note's range partially overlaps or adjoins the
2425 other note then if they are both of the same type (open
2426 or func) then they can be merged and one deleted. If
2427 they are of different types then they cannot be merged. */
2428 objcopy_internal_note * prev_note = NULL;
2430 for (pnote = pnotes; pnote < pnotes_end; pnote ++)
2432 /* Skip already deleted notes.
2433 FIXME: Can this happen ? We are scanning forwards and
2434 deleting backwards after all. */
2435 if (is_deleted_note (pnote))
2436 continue;
2438 /* Rule 1 - delete 0-range notes. */
2439 if (pnote->start == pnote->end)
2441 merge_debug ("Delete note at offset %#08lx - empty range\n",
2442 (pnote->note.namedata - (char *) contents) - 12);
2443 pnote->note.type = 0;
2444 continue;
2447 int iter;
2448 objcopy_internal_note * back;
2450 /* Rule 2: Check to see if there is an identical previous note. */
2451 for (iter = 0, back = prev_note ? prev_note : pnote - 1;
2452 back >= pnotes;
2453 back --)
2455 if (is_deleted_note (back))
2456 continue;
2458 /* Our sorting function should have placed all identically
2459 attributed notes together, so if we see a note of a different
2460 attribute type stop searching. */
2461 if (back->note.namesz != pnote->note.namesz
2462 || memcmp (back->note.namedata,
2463 pnote->note.namedata, pnote->note.namesz) != 0)
2464 break;
2466 if (back->start == pnote->start
2467 && back->end == pnote->end)
2469 merge_debug ("Delete note at offset %#08lx - duplicate of note at offset %#08lx\n",
2470 (pnote->note.namedata - (char *) contents) - 12,
2471 (back->note.namedata - (char *) contents) - 12);
2472 pnote->note.type = 0;
2473 break;
2476 /* Rule 2a. */
2477 if (contained_by (pnote, back))
2479 merge_debug ("Delete note at offset %#08lx - fully contained by note at %#08lx\n",
2480 (pnote->note.namedata - (char *) contents) - 12,
2481 (back->note.namedata - (char *) contents) - 12);
2482 pnote->note.type = 0;
2483 break;
2486 #if DEBUG_MERGE
2487 /* This should not happen as we have sorted the
2488 notes with earlier starting addresses first. */
2489 if (contained_by (back, pnote))
2490 merge_debug ("ERROR: UNEXPECTED CONTAINMENT\n");
2491 #endif
2493 /* Rule 2b. */
2494 if (overlaps_or_adjoins (back, pnote)
2495 && is_func_note (back) == is_func_note (pnote))
2497 merge_debug ("Delete note at offset %#08lx - merge into note at %#08lx\n",
2498 (pnote->note.namedata - (char *) contents) - 12,
2499 (back->note.namedata - (char *) contents) - 12);
2501 back->end = back->end > pnote->end ? back->end : pnote->end;
2502 back->start = back->start < pnote->start ? back->start : pnote->start;
2503 pnote->note.type = 0;
2504 break;
2507 /* Don't scan too far back however. */
2508 if (iter ++ > 16)
2510 /* FIXME: Not sure if this can ever be triggered. */
2511 merge_debug ("ITERATION LIMIT REACHED\n");
2512 break;
2516 if (! is_deleted_note (pnote))
2518 /* Keep a pointer to this note, so that we can
2519 start the next search for rule 2 matches here. */
2520 prev_note = pnote;
2521 #if DEBUG_MERGE
2522 merge_debug ("Unable to do anything with note at %#08lx\n",
2523 (pnote->note.namedata - (char *) contents) - 12);
2524 #endif
2528 /* Resort the notes. */
2529 merge_debug ("Final sorting of notes\n");
2530 qsort (pnotes, pnotes_end - pnotes, sizeof (* pnotes), sort_gnu_build_notes);
2532 /* Reconstruct the ELF notes. */
2533 bfd_byte * new_contents;
2534 bfd_byte * old;
2535 bfd_byte * new;
2536 bfd_vma prev_start = 0;
2537 bfd_vma prev_end = 0;
2539 /* Not sure how, but the notes might grow in size.
2540 (eg see PR 1774507). Allow for this here. */
2541 new = new_contents = xmalloc (size * 2);
2542 for (pnote = pnotes, old = contents;
2543 pnote < pnotes_end;
2544 pnote ++)
2546 bfd_size_type note_size = 12 + pnote->padded_namesz + pnote->note.descsz;
2548 if (! is_deleted_note (pnote))
2550 /* Create the note, potentially using the
2551 address range of the previous note. */
2552 if (pnote->start == prev_start && pnote->end == prev_end)
2554 bfd_put_32 (abfd, pnote->note.namesz, new);
2555 bfd_put_32 (abfd, 0, new + 4);
2556 bfd_put_32 (abfd, pnote->note.type, new + 8);
2557 new += 12;
2558 memcpy (new, pnote->note.namedata, pnote->note.namesz);
2559 if (pnote->note.namesz < pnote->padded_namesz)
2560 memset (new + pnote->note.namesz, 0, pnote->padded_namesz - pnote->note.namesz);
2561 new += pnote->padded_namesz;
2563 else
2565 bfd_put_32 (abfd, pnote->note.namesz, new);
2566 bfd_put_32 (abfd, is_64bit (abfd) ? 16 : 8, new + 4);
2567 bfd_put_32 (abfd, pnote->note.type, new + 8);
2568 new += 12;
2569 memcpy (new, pnote->note.namedata, pnote->note.namesz);
2570 if (pnote->note.namesz < pnote->padded_namesz)
2571 memset (new + pnote->note.namesz, 0, pnote->padded_namesz - pnote->note.namesz);
2572 new += pnote->padded_namesz;
2573 if (is_64bit (abfd))
2575 bfd_put_64 (abfd, pnote->start, new);
2576 bfd_put_64 (abfd, pnote->end, new + 8);
2577 new += 16;
2579 else
2581 bfd_put_32 (abfd, pnote->start, new);
2582 bfd_put_32 (abfd, pnote->end, new + 4);
2583 new += 8;
2586 prev_start = pnote->start;
2587 prev_end = pnote->end;
2591 old += note_size;
2594 #if DEBUG_MERGE
2595 merge_debug ("Results of merge:\n");
2596 for (pnote = pnotes; pnote < pnotes_end; pnote ++)
2597 if (! is_deleted_note (pnote))
2598 merge_debug ("offset %#08lx range %#08lx..%#08lx type %ld attribute %d namesz %ld\n",
2599 (pnote->note.namedata - (char *) contents) - 12,
2600 pnote->start, pnote->end,
2601 pnote->note.type,
2602 pnote->note.namedata[3],
2603 pnote->note.namesz
2605 #endif
2607 size_t nsize = new - new_contents;
2608 if (nsize < size)
2610 *new_size = nsize;
2611 memcpy (contents, new_contents, nsize);
2613 free (new_contents);
2615 done:
2616 if (err)
2618 bfd_set_error (bfd_error_bad_value);
2619 bfd_nonfatal_message (NULL, abfd, sec, err);
2622 free (pnotes);
2623 return !err;
2626 static flagword
2627 check_new_section_flags (flagword flags, bfd *abfd, const char * secname)
2629 /* Only set the SEC_COFF_SHARED flag on COFF files.
2630 The same bit value is used by ELF targets to indicate
2631 compressed sections, and setting that flag here breaks
2632 things. */
2633 if ((flags & SEC_COFF_SHARED)
2634 && bfd_get_flavour (abfd) != bfd_target_coff_flavour)
2636 non_fatal (_("%s[%s]: Note - dropping 'share' flag as output format is not COFF"),
2637 bfd_get_filename (abfd), secname);
2638 flags &= ~ SEC_COFF_SHARED;
2641 /* Report a fatal error if 'large' is used with a non-x86-64 ELF target.
2642 Suppress the error for non-ELF targets to allow -O binary and formats that
2643 use the bit value SEC_ELF_LARGE for other purposes. */
2644 if ((flags & SEC_ELF_LARGE) != 0
2645 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
2646 && get_elf_backend_data (abfd)->elf_machine_code != EM_X86_64)
2648 fatal (_ ("%s[%s]: 'large' flag is ELF x86-64 specific"),
2649 bfd_get_filename (abfd), secname);
2650 flags &= ~SEC_ELF_LARGE;
2653 return flags;
2656 static void
2657 set_long_section_mode (bfd *output_bfd, bfd *input_bfd, enum long_section_name_handling style)
2659 /* This is only relevant to Coff targets. */
2660 if (bfd_get_flavour (output_bfd) == bfd_target_coff_flavour)
2662 if (style == KEEP
2663 && bfd_get_flavour (input_bfd) == bfd_target_coff_flavour)
2664 style = bfd_coff_long_section_names (input_bfd) ? ENABLE : DISABLE;
2665 bfd_coff_set_long_section_names (output_bfd, style != DISABLE);
2669 /* Copy object file IBFD onto OBFD.
2670 Returns TRUE upon success, FALSE otherwise. */
2672 static bool
2673 copy_object (bfd *ibfd, bfd *obfd, const bfd_arch_info_type *input_arch)
2675 bfd_vma start;
2676 long symcount;
2677 asection **osections = NULL;
2678 asection *osec;
2679 asection *gnu_debuglink_section = NULL;
2680 bfd_size_type *gaps = NULL;
2681 bfd_size_type max_gap = 0;
2682 long symsize;
2683 void *dhandle;
2684 enum bfd_architecture iarch;
2685 unsigned int imach;
2686 unsigned int num_sec, i;
2688 if (ibfd->xvec->byteorder != obfd->xvec->byteorder
2689 && ibfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN
2690 && obfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN)
2692 /* PR 17636: Call non-fatal so that we return to our parent who
2693 may need to tidy temporary files. */
2694 non_fatal (_("unable to change endianness of '%s'"),
2695 bfd_get_archive_filename (ibfd));
2696 return false;
2699 if (ibfd->read_only)
2701 non_fatal (_("unable to modify '%s' due to errors"),
2702 bfd_get_archive_filename (ibfd));
2703 return false;
2706 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
2708 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
2709 return false;
2712 if (ibfd->sections == NULL)
2714 non_fatal (_("error: the input file '%s' has no sections"),
2715 bfd_get_archive_filename (ibfd));
2716 return false;
2719 /* This is a no-op on non-Coff targets. */
2720 set_long_section_mode (obfd, ibfd, long_section_names);
2722 /* Set the Verilog output endianness based upon the input file's
2723 endianness. We may not be producing verilog format output,
2724 but testing this just adds extra code this is not really
2725 necessary. */
2726 VerilogDataEndianness = ibfd->xvec->byteorder;
2728 if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour)
2730 if (strip_section_headers)
2732 ibfd->flags |= BFD_NO_SECTION_HEADER;
2733 strip_symbols = STRIP_ALL;
2734 merge_notes = true;
2737 else
2739 if ((do_debug_sections & compress) != 0
2740 && do_debug_sections != compress)
2742 non_fatal (_ ("--compress-debug-sections=[zlib|zlib-gnu|zlib-gabi|"
2743 "zstd] is unsupported on `%s'"),
2744 bfd_get_archive_filename (ibfd));
2745 return false;
2748 if (do_elf_stt_common)
2750 non_fatal (_("--elf-stt-common=[yes|no] is unsupported on `%s'"),
2751 bfd_get_archive_filename (ibfd));
2752 return false;
2755 if (strip_section_headers)
2757 non_fatal (_("--strip-section-headers is unsupported on `%s'"),
2758 bfd_get_archive_filename (ibfd));
2759 return false;
2763 if (verbose)
2764 printf (_("copy from `%s' [%s] to `%s' [%s]\n"),
2765 bfd_get_archive_filename (ibfd), bfd_get_target (ibfd),
2766 bfd_get_filename (obfd), bfd_get_target (obfd));
2768 if (extract_symbol)
2769 start = 0;
2770 else
2772 if (set_start_set)
2773 start = set_start;
2774 else
2775 start = bfd_get_start_address (ibfd);
2776 start += change_start;
2779 /* Neither the start address nor the flags
2780 need to be set for a core file. */
2781 if (bfd_get_format (obfd) != bfd_core)
2783 flagword flags;
2785 flags = bfd_get_file_flags (ibfd);
2786 flags |= bfd_flags_to_set;
2787 flags &= ~bfd_flags_to_clear;
2788 flags &= bfd_applicable_file_flags (obfd);
2790 if (strip_symbols == STRIP_ALL)
2791 flags &= ~HAS_RELOC;
2793 if (!bfd_set_start_address (obfd, start)
2794 || !bfd_set_file_flags (obfd, flags))
2796 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2797 return false;
2801 /* Copy architecture of input file to output file. */
2802 iarch = bfd_get_arch (ibfd);
2803 imach = bfd_get_mach (ibfd);
2804 if (input_arch)
2806 if (iarch == bfd_arch_unknown)
2808 iarch = input_arch->arch;
2809 imach = input_arch->mach;
2811 else
2812 non_fatal (_("Input file `%s' ignores binary architecture parameter."),
2813 bfd_get_archive_filename (ibfd));
2815 if (iarch == bfd_arch_unknown
2816 && bfd_get_flavour (ibfd) != bfd_target_elf_flavour
2817 && bfd_get_flavour (obfd) == bfd_target_elf_flavour)
2819 const struct elf_backend_data *bed = get_elf_backend_data (obfd);
2820 iarch = bed->arch;
2821 imach = 0;
2823 if (!bfd_set_arch_mach (obfd, iarch, imach)
2824 && (ibfd->target_defaulted
2825 || bfd_get_arch (ibfd) != bfd_get_arch (obfd)))
2827 if (bfd_get_arch (ibfd) == bfd_arch_unknown)
2828 non_fatal (_("Unable to recognise the format of the input file `%s'"),
2829 bfd_get_archive_filename (ibfd));
2830 else
2831 non_fatal (_("Output file cannot represent architecture `%s'"),
2832 bfd_printable_arch_mach (bfd_get_arch (ibfd),
2833 bfd_get_mach (ibfd)));
2834 return false;
2837 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
2839 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2840 return false;
2843 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
2844 && bfd_pei_p (obfd))
2846 /* Set up PE parameters. */
2847 pe_data_type *pe = pe_data (obfd);
2849 /* Copy PE parameters before changing them. */
2850 if (bfd_get_flavour (ibfd) == bfd_target_coff_flavour
2851 && bfd_pei_p (ibfd))
2853 pe->pe_opthdr = pe_data (ibfd)->pe_opthdr;
2855 if (preserve_dates)
2856 pe->timestamp = pe_data (ibfd)->coff.timestamp;
2857 else
2858 pe->timestamp = -1;
2861 if (pe_file_alignment != (bfd_vma) -1)
2862 pe->pe_opthdr.FileAlignment = pe_file_alignment;
2863 else
2864 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
2866 if (pe_heap_commit != (bfd_vma) -1)
2867 pe->pe_opthdr.SizeOfHeapCommit = pe_heap_commit;
2869 if (pe_heap_reserve != (bfd_vma) -1)
2870 pe->pe_opthdr.SizeOfHeapCommit = pe_heap_reserve;
2872 if (pe_image_base != (bfd_vma) -1)
2873 pe->pe_opthdr.ImageBase = pe_image_base;
2875 if (pe_section_alignment != (bfd_vma) -1)
2876 pe->pe_opthdr.SectionAlignment = pe_section_alignment;
2877 else
2878 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
2880 if (pe_stack_commit != (bfd_vma) -1)
2881 pe->pe_opthdr.SizeOfStackCommit = pe_stack_commit;
2883 if (pe_stack_reserve != (bfd_vma) -1)
2884 pe->pe_opthdr.SizeOfStackReserve = pe_stack_reserve;
2886 if (pe_subsystem != -1)
2887 pe->pe_opthdr.Subsystem = pe_subsystem;
2889 if (pe_major_subsystem_version != -1)
2890 pe->pe_opthdr.MajorSubsystemVersion = pe_major_subsystem_version;
2892 if (pe_minor_subsystem_version != -1)
2893 pe->pe_opthdr.MinorSubsystemVersion = pe_minor_subsystem_version;
2895 if (pe_file_alignment > pe_section_alignment)
2897 non_fatal (_("warning: file alignment (0x%" PRIx64
2898 ") > section alignment (0x%" PRIx64 ")"),
2899 (uint64_t) pe_file_alignment,
2900 (uint64_t) pe_section_alignment);
2904 free (isympp);
2906 if (osympp != isympp)
2907 free (osympp);
2909 isympp = NULL;
2910 osympp = NULL;
2912 symsize = bfd_get_symtab_upper_bound (ibfd);
2913 if (symsize < 0)
2915 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2916 return false;
2919 osympp = isympp = (asymbol **) xmalloc (symsize);
2920 symcount = bfd_canonicalize_symtab (ibfd, isympp);
2921 if (symcount < 0)
2923 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2924 return false;
2926 /* PR 17512: file: d6323821
2927 If the symbol table could not be loaded do not pretend that we have
2928 any symbols. This trips us up later on when we load the relocs. */
2929 if (symcount == 0)
2931 free (isympp);
2932 osympp = isympp = NULL;
2935 /* BFD mandates that all output sections be created and sizes set before
2936 any output is done. Thus, we traverse all sections multiple times. */
2937 for (asection *s = ibfd->sections; s != NULL; s = s->next)
2938 if (!setup_section (ibfd, s, obfd))
2939 return false;
2941 if (!extract_symbol)
2943 if (!setup_bfd_headers (ibfd, obfd))
2944 return false;
2947 if (add_sections != NULL)
2949 struct section_add *padd;
2950 struct section_list *pset;
2952 for (padd = add_sections; padd != NULL; padd = padd->next)
2954 flagword flags;
2956 pset = find_section_list (padd->name, false,
2957 SECTION_CONTEXT_SET_FLAGS);
2958 if (pset != NULL)
2960 flags = pset->flags | SEC_HAS_CONTENTS;
2961 flags = check_new_section_flags (flags, obfd, padd->name);
2963 else
2964 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DATA;
2966 /* bfd_make_section_with_flags() does not return very helpful
2967 error codes, so check for the most likely user error first. */
2968 if (bfd_get_section_by_name (obfd, padd->name))
2970 bfd_nonfatal_message (NULL, obfd, NULL,
2971 _("can't add section '%s'"), padd->name);
2972 return false;
2974 else
2976 /* We use LINKER_CREATED here so that the backend hooks
2977 will create any special section type information,
2978 instead of presuming we know what we're doing merely
2979 because we set the flags. */
2980 padd->section = bfd_make_section_with_flags
2981 (obfd, padd->name, flags | SEC_LINKER_CREATED);
2982 if (padd->section == NULL)
2984 bfd_nonfatal_message (NULL, obfd, NULL,
2985 _("can't create section `%s'"),
2986 padd->name);
2987 return false;
2991 if (!bfd_set_section_size (padd->section, padd->size))
2993 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2994 return false;
2997 pset = find_section_list (padd->name, false,
2998 SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA);
2999 if (pset != NULL
3000 && !bfd_set_section_vma (padd->section, pset->vma_val))
3002 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
3003 return false;
3006 pset = find_section_list (padd->name, false,
3007 SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA);
3008 if (pset != NULL)
3010 padd->section->lma = pset->lma_val;
3012 if (!bfd_set_section_alignment
3013 (padd->section, bfd_section_alignment (padd->section)))
3015 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
3016 return false;
3022 if (update_sections != NULL)
3024 struct section_add *pupdate;
3026 for (pupdate = update_sections;
3027 pupdate != NULL;
3028 pupdate = pupdate->next)
3030 pupdate->section = bfd_get_section_by_name (ibfd, pupdate->name);
3031 if (pupdate->section == NULL)
3033 non_fatal (_("error: %s not found, can't be updated"), pupdate->name);
3034 return false;
3037 osec = pupdate->section->output_section;
3038 if (!bfd_set_section_size (osec, pupdate->size))
3040 bfd_nonfatal_message (NULL, obfd, osec, NULL);
3041 return false;
3046 merged_note_section * merged_note_sections = NULL;
3047 if (merge_notes)
3049 /* This palaver is necessary because we must set the output
3050 section size first, before its contents are ready. */
3051 for (osec = ibfd->sections; osec != NULL; osec = osec->next)
3053 if (! is_mergeable_note_section (ibfd, osec))
3054 continue;
3056 /* If the section is going to be completly deleted then
3057 do not bother to merge it. */
3058 if (osec->output_section == NULL)
3059 continue;
3061 bfd_size_type size = bfd_section_size (osec);
3063 if (size == 0)
3064 /* This can happen, eg when stripping a binary for a second
3065 time. See BZ 2121365 for an example. */
3066 continue;
3068 merged_note_section * merged = xmalloc (sizeof * merged);
3069 merged->contents = NULL;
3070 if (! bfd_get_full_section_contents (ibfd, osec, & merged->contents))
3072 bfd_nonfatal_message (NULL, ibfd, osec,
3073 _("warning: could not load note section"));
3074 free (merged);
3075 continue;
3078 if (!merge_gnu_build_notes (ibfd, osec, size,
3079 merged->contents, &merged->size))
3081 free (merged->contents);
3082 free (merged);
3083 return false;
3086 /* FIXME: Once we have read the contents in, we must write
3087 them out again. So even if the merging has achieved
3088 nothing we still add this entry to the merge list. */
3090 if (size != merged->size
3091 && !bfd_set_section_size (osec->output_section, merged->size))
3093 bfd_nonfatal_message (NULL, obfd, osec,
3094 _("warning: failed to set merged notes size"));
3095 free (merged->contents);
3096 free (merged);
3097 continue;
3100 /* Add section to list of merged sections. */
3101 merged->sec = osec;
3102 merged->next = merged_note_sections;
3103 merged_note_sections = merged;
3107 if (dump_sections != NULL)
3109 struct section_add * pdump;
3111 for (pdump = dump_sections; pdump != NULL; pdump = pdump->next)
3113 FILE * f;
3114 bfd_byte *contents;
3116 osec = bfd_get_section_by_name (ibfd, pdump->name);
3117 if (osec == NULL)
3119 bfd_nonfatal_message (NULL, ibfd, NULL,
3120 _("can't dump section '%s' - it does not exist"),
3121 pdump->name);
3122 continue;
3125 if ((bfd_section_flags (osec) & SEC_HAS_CONTENTS) == 0)
3127 bfd_nonfatal_message (NULL, ibfd, osec,
3128 _("can't dump section - it has no contents"));
3129 continue;
3132 bfd_size_type size = bfd_section_size (osec);
3133 /* Note - we allow the dumping of zero-sized sections,
3134 creating an empty file. */
3136 f = fopen (pdump->filename, FOPEN_WB);
3137 if (f == NULL)
3139 bfd_nonfatal_message (pdump->filename, NULL, NULL,
3140 _("could not open section dump file"));
3141 continue;
3144 if (bfd_malloc_and_get_section (ibfd, osec, &contents))
3146 if (size != 0 && fwrite (contents, 1, size, f) != size)
3148 non_fatal (_("error writing section contents to %s (error: %s)"),
3149 pdump->filename,
3150 strerror (errno));
3151 free (contents);
3152 fclose (f);
3153 goto fail;
3156 else
3157 bfd_nonfatal_message (NULL, ibfd, osec,
3158 _("could not retrieve section contents"));
3160 fclose (f);
3161 free (contents);
3165 if (gnu_debuglink_filename != NULL)
3167 /* PR 15125: Give a helpful warning message if
3168 the debuglink section already exists, and
3169 allow the rest of the copy to complete. */
3170 if (bfd_get_section_by_name (obfd, ".gnu_debuglink"))
3172 non_fatal (_("%s: debuglink section already exists"),
3173 bfd_get_filename (ibfd));
3174 gnu_debuglink_filename = NULL;
3176 else
3178 gnu_debuglink_section = bfd_create_gnu_debuglink_section
3179 (obfd, gnu_debuglink_filename);
3181 if (gnu_debuglink_section == NULL)
3183 bfd_nonfatal_message (NULL, obfd, NULL,
3184 _("cannot create debug link section `%s'"),
3185 gnu_debuglink_filename);
3186 goto fail;
3189 /* Special processing for PE format files. We
3190 have no way to distinguish PE from COFF here. */
3191 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour)
3193 bfd_vma debuglink_vma;
3194 asection * highest_section;
3196 /* The PE spec requires that all sections be adjacent and sorted
3197 in ascending order of VMA. It also specifies that debug
3198 sections should be last. This is despite the fact that debug
3199 sections are not loaded into memory and so in theory have no
3200 use for a VMA.
3202 This means that the debuglink section must be given a non-zero
3203 VMA which makes it contiguous with other debug sections. So
3204 walk the current section list, find the section with the
3205 highest VMA and start the debuglink section after that one. */
3206 for (osec = obfd->sections, highest_section = NULL;
3207 osec != NULL;
3208 osec = osec->next)
3209 if (osec->vma > 0
3210 && (highest_section == NULL
3211 || osec->vma > highest_section->vma))
3212 highest_section = osec;
3214 if (highest_section)
3215 debuglink_vma = BFD_ALIGN (highest_section->vma
3216 + highest_section->size,
3217 /* FIXME: We ought to be using
3218 COFF_PAGE_SIZE here or maybe
3219 bfd_section_alignment() (if it
3220 was set) but since this is for PE
3221 and we know the required alignment
3222 it is easier just to hard code it. */
3223 0x1000);
3224 else
3225 /* Umm, not sure what to do in this case. */
3226 debuglink_vma = 0x1000;
3228 bfd_set_section_vma (gnu_debuglink_section, debuglink_vma);
3233 num_sec = bfd_count_sections (obfd);
3234 if (num_sec != 0
3235 && (gap_fill_set || pad_to_set))
3237 /* We must fill in gaps between the sections and/or we must pad
3238 the last section to a specified address. We do this by
3239 grabbing a list of the sections, sorting them by VMA, and
3240 increasing the section sizes as required to fill the gaps.
3241 We write out the gap contents below. */
3243 osections = xmalloc (num_sec * sizeof (*osections));
3244 asection **set = osections;
3245 for (asection *s = obfd->sections; s != NULL; s = s->next)
3246 *set++ = s;
3248 qsort (osections, num_sec, sizeof (*osections), compare_section_lma);
3250 gaps = xmalloc (num_sec * sizeof (*gaps));
3251 memset (gaps, 0, num_sec * sizeof (*gaps));
3253 if (gap_fill_set)
3255 for (i = 0; i < num_sec - 1; i++)
3257 flagword flags;
3258 bfd_size_type size; /* Octets. */
3259 bfd_vma gap_start, gap_stop; /* Octets. */
3260 unsigned int opb1 = bfd_octets_per_byte (obfd, osections[i]);
3261 unsigned int opb2 = bfd_octets_per_byte (obfd, osections[i+1]);
3263 flags = bfd_section_flags (osections[i]);
3264 if ((flags & SEC_HAS_CONTENTS) == 0
3265 || (flags & SEC_LOAD) == 0)
3266 continue;
3268 size = bfd_section_size (osections[i]);
3269 gap_start = bfd_section_lma (osections[i]) * opb1 + size;
3270 gap_stop = bfd_section_lma (osections[i + 1]) * opb2;
3271 if (gap_start < gap_stop)
3273 if (!bfd_set_section_size (osections[i],
3274 size + (gap_stop - gap_start)))
3276 bfd_nonfatal_message (NULL, obfd, osections[i],
3277 _("Can't fill gap after section"));
3278 goto fail;
3280 gaps[i] = gap_stop - gap_start;
3281 if (max_gap < gap_stop - gap_start)
3282 max_gap = gap_stop - gap_start;
3287 if (pad_to_set)
3289 bfd_vma lma; /* Octets. */
3290 bfd_size_type size; /* Octets. */
3291 unsigned int opb = bfd_octets_per_byte (obfd, osections[num_sec - 1]);
3292 bfd_vma _pad_to = pad_to * opb;
3294 lma = bfd_section_lma (osections[num_sec - 1]) * opb;
3295 size = bfd_section_size (osections[num_sec - 1]);
3296 if (lma + size < _pad_to)
3298 if (!bfd_set_section_size (osections[num_sec - 1], _pad_to - lma))
3300 bfd_nonfatal_message (NULL, obfd, osections[num_sec - 1],
3301 _("can't add padding"));
3302 goto fail;
3304 else
3306 gaps[num_sec - 1] = _pad_to - (lma + size);
3307 if (max_gap < _pad_to - (lma + size))
3308 max_gap = _pad_to - (lma + size);
3314 /* Symbol filtering must happen after the output sections
3315 have been created, but before their contents are set. */
3316 dhandle = NULL;
3317 if (convert_debugging)
3318 dhandle = read_debugging_info (ibfd, isympp, symcount, false);
3320 if ((obfd->flags & (EXEC_P | DYNAMIC)) != 0
3321 && (obfd->flags & HAS_RELOC) == 0)
3323 if (bfd_keep_unused_section_symbols (obfd) || keep_section_symbols)
3325 /* Non-relocatable inputs may not have the unused section
3326 symbols. Mark all section symbols as used to generate
3327 section symbols. */
3328 asection *asect;
3329 for (asect = obfd->sections; asect != NULL; asect = asect->next)
3330 if (asect->symbol)
3331 asect->symbol->flags |= BSF_SECTION_SYM_USED;
3333 else
3335 /* Non-relocatable inputs may have the unused section symbols.
3336 Mark all section symbols as unused to excluded them. */
3337 long s;
3338 for (s = 0; s < symcount; s++)
3339 if ((isympp[s]->flags & BSF_SECTION_SYM_USED))
3340 isympp[s]->flags &= ~BSF_SECTION_SYM_USED;
3344 if (strip_symbols == STRIP_DEBUG
3345 || strip_symbols == STRIP_ALL
3346 || strip_symbols == STRIP_UNNEEDED
3347 || strip_symbols == STRIP_NONDEBUG
3348 || strip_symbols == STRIP_DWO
3349 || strip_symbols == STRIP_NONDWO
3350 || discard_locals != LOCALS_UNDEF
3351 || localize_hidden
3352 || htab_elements (strip_specific_htab) != 0
3353 || htab_elements (keep_specific_htab) != 0
3354 || htab_elements (localize_specific_htab) != 0
3355 || htab_elements (globalize_specific_htab) != 0
3356 || htab_elements (keepglobal_specific_htab) != 0
3357 || htab_elements (weaken_specific_htab) != 0
3358 || htab_elements (redefine_specific_htab) != 0
3359 || prefix_symbols_string
3360 || sections_removed
3361 || sections_copied
3362 || convert_debugging
3363 || change_leading_char
3364 || remove_leading_char
3365 || section_rename_list
3366 || weaken
3367 || add_symbols)
3369 /* Mark symbols used in output relocations so that they
3370 are kept, even if they are local labels or static symbols.
3372 Note we iterate over the input sections examining their
3373 relocations since the relocations for the output sections
3374 haven't been set yet. mark_symbols_used_in_relocations will
3375 ignore input sections which have no corresponding output
3376 section. */
3377 if (strip_symbols != STRIP_ALL)
3379 bfd_set_error (bfd_error_no_error);
3380 for (asection *s = ibfd->sections; s != NULL; s = s->next)
3381 if (!mark_symbols_used_in_relocations (ibfd, s, isympp)
3382 || bfd_get_error () != bfd_error_no_error)
3383 goto fail;
3386 osympp = (asymbol **) xmalloc ((symcount + add_symbols + 1) * sizeof (asymbol *));
3387 if (!filter_symbols (ibfd, obfd, osympp, isympp, &symcount))
3388 goto fail;
3391 for (long s = 0; s < symcount; s++)
3392 if (!bfd_copy_private_symbol_data (ibfd, osympp[s], obfd, osympp[s]))
3393 goto fail;
3395 if (dhandle != NULL)
3397 if (!write_debugging_info (obfd, dhandle, &symcount, &osympp))
3398 goto fail;
3401 bfd_set_symtab (obfd, osympp, symcount);
3403 /* This has to happen before section positions are set. */
3404 for (asection *s = ibfd->sections; s != NULL; s = s->next)
3405 if (!copy_relocations_in_section (ibfd, s, obfd))
3406 goto fail;
3408 /* This has to happen after the symbol table has been set. */
3409 for (asection *s = ibfd->sections; s != NULL; s = s->next)
3410 if (!copy_section (ibfd, s, obfd))
3411 goto fail;
3413 if (add_sections != NULL)
3415 struct section_add *padd;
3417 for (padd = add_sections; padd != NULL; padd = padd->next)
3419 if (! bfd_set_section_contents (obfd, padd->section, padd->contents,
3420 0, padd->size))
3422 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
3423 goto fail;
3428 if (update_sections != NULL)
3430 struct section_add *pupdate;
3432 for (pupdate = update_sections;
3433 pupdate != NULL;
3434 pupdate = pupdate->next)
3436 osec = pupdate->section->output_section;
3437 if (! bfd_set_section_contents (obfd, osec, pupdate->contents,
3438 0, pupdate->size))
3440 bfd_nonfatal_message (NULL, obfd, osec, NULL);
3441 goto fail;
3446 if (merged_note_sections != NULL)
3448 merged_note_section * merged = NULL;
3450 for (osec = obfd->sections; osec != NULL; osec = osec->next)
3452 if (! is_mergeable_note_section (obfd, osec))
3453 continue;
3455 if (merged == NULL)
3456 merged = merged_note_sections;
3458 /* It is likely that output sections are in the same order
3459 as the input sections, but do not assume that this is
3460 the case. */
3461 if (merged->sec->output_section != osec)
3463 for (merged = merged_note_sections;
3464 merged != NULL;
3465 merged = merged->next)
3466 if (merged->sec->output_section == osec)
3467 break;
3469 if (merged == NULL)
3471 bfd_nonfatal_message
3472 (NULL, obfd, osec,
3473 _("error: failed to locate merged notes"));
3474 continue;
3478 if (merged->contents == NULL)
3480 bfd_nonfatal_message
3481 (NULL, obfd, osec,
3482 _("error: failed to merge notes"));
3483 continue;
3486 if (! bfd_set_section_contents (obfd, osec, merged->contents, 0,
3487 merged->size))
3489 bfd_nonfatal_message
3490 (NULL, obfd, osec,
3491 _("error: failed to copy merged notes into output"));
3492 goto fail;
3495 merged = merged->next;
3498 /* Free the memory. */
3499 while (merged_note_sections != NULL)
3501 merged_note_section *next = merged_note_sections->next;
3502 free (merged_note_sections->contents);
3503 free (merged_note_sections);
3504 merged_note_sections = next;
3507 else if (merge_notes && ! is_strip && ! strip_section_headers)
3508 non_fatal (_("%s: Could not find any mergeable note sections"),
3509 bfd_get_filename (ibfd));
3511 if (gnu_debuglink_filename != NULL)
3513 if (! bfd_fill_in_gnu_debuglink_section
3514 (obfd, gnu_debuglink_section, gnu_debuglink_filename))
3516 bfd_nonfatal_message (NULL, obfd, NULL,
3517 _("cannot fill debug link section `%s'"),
3518 gnu_debuglink_filename);
3519 goto fail;
3523 if (gaps != NULL)
3525 bfd_byte *buf;
3527 /* Fill in the gaps. */
3528 if (max_gap > 8192)
3529 max_gap = 8192;
3530 buf = (bfd_byte *) xmalloc (max_gap);
3531 memset (buf, gap_fill, max_gap);
3533 for (i = 0; i < num_sec; i++)
3535 if (gaps[i] != 0)
3537 bfd_size_type left;
3538 file_ptr off;
3540 left = gaps[i];
3541 off = bfd_section_size (osections[i]) - left;
3543 while (left > 0)
3545 bfd_size_type now;
3547 if (left > 8192)
3548 now = 8192;
3549 else
3550 now = left;
3552 if (! bfd_set_section_contents (obfd, osections[i], buf,
3553 off, now))
3555 bfd_nonfatal_message (NULL, obfd, osections[i], NULL);
3556 free (buf);
3557 goto fail;
3560 left -= now;
3561 off += now;
3566 free (buf);
3567 free (gaps);
3568 gaps = NULL;
3569 free (osections);
3570 osections = NULL;
3573 /* Allow the BFD backend to copy any private data it understands
3574 from the input BFD to the output BFD. This is done last to
3575 permit the routine to look at the filtered symbol table, which is
3576 important for the ECOFF code at least. */
3577 if (! bfd_copy_private_bfd_data (ibfd, obfd))
3579 bfd_nonfatal_message (NULL, obfd, NULL,
3580 _("error copying private BFD data"));
3581 goto fail;
3584 /* Switch to the alternate machine code. We have to do this at the
3585 very end, because we only initialize the header when we create
3586 the first section. */
3587 if (use_alt_mach_code != 0)
3589 if (! bfd_alt_mach_code (obfd, use_alt_mach_code))
3591 non_fatal (_("this target does not support %lu alternative machine codes"),
3592 use_alt_mach_code);
3593 if (bfd_get_flavour (obfd) == bfd_target_elf_flavour)
3595 non_fatal (_("treating that number as an absolute e_machine value instead"));
3596 elf_elfheader (obfd)->e_machine = use_alt_mach_code;
3598 else
3599 non_fatal (_("ignoring the alternative value"));
3603 return true;
3605 fail:
3606 while (merged_note_sections != NULL)
3608 merged_note_section *next = merged_note_sections->next;
3609 free (merged_note_sections->contents);
3610 free (merged_note_sections);
3611 merged_note_sections = next;
3613 free (gaps);
3614 free (osections);
3615 return false;
3618 /* Read each archive element in turn from IBFD, copy the
3619 contents to temp file, and keep the temp file handle.
3620 If 'force_output_target' is TRUE then make sure that
3621 all elements in the new archive are of the type
3622 'output_target'. */
3624 static bool
3625 copy_archive (bfd *ibfd, bfd *obfd, const char *output_target,
3626 bool force_output_target,
3627 const bfd_arch_info_type *input_arch)
3629 struct name_list
3631 struct name_list *next;
3632 char *name;
3633 bfd *obfd;
3634 } *list;
3635 bfd **ptr = &obfd->archive_head;
3636 bfd *this_element;
3637 char *dir = NULL;
3638 char *filename;
3639 bool ok = true;
3641 list = NULL;
3643 /* PR 24281: It is not clear what should happen when copying a thin archive.
3644 One part is straight forward - if the output archive is in a different
3645 directory from the input archive then any relative paths in the library
3646 should be adjusted to the new location. But if any transformation
3647 options are active (eg strip, rename, add, etc) then the implication is
3648 that these should be applied to the files pointed to by the archive.
3649 But since objcopy is not destructive, this means that new files must be
3650 created, and there is no guidance for the names of the new files. (Plus
3651 this conflicts with one of the goals of thin libraries - only taking up
3652 a minimal amount of space in the file system).
3654 So for now we fail if an attempt is made to copy such libraries. */
3655 if (ibfd->is_thin_archive)
3657 ok = false;
3658 bfd_set_error (bfd_error_invalid_operation);
3659 bfd_nonfatal_message (NULL, ibfd, NULL,
3660 _("sorry: copying thin archives is not currently supported"));
3661 goto cleanup_and_exit;
3664 /* Make a temp directory to hold the contents. */
3665 dir = make_tempdir (bfd_get_filename (obfd));
3666 if (dir == NULL)
3667 fatal (_("cannot create tempdir for archive copying (error: %s)"),
3668 strerror (errno));
3670 if (strip_symbols == STRIP_ALL)
3671 obfd->has_armap = false;
3672 else
3673 obfd->has_armap = ibfd->has_armap;
3674 obfd->is_thin_archive = ibfd->is_thin_archive;
3676 if (deterministic)
3677 obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
3679 this_element = bfd_openr_next_archived_file (ibfd, NULL);
3681 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
3683 ok = false;
3684 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
3685 goto cleanup_and_exit;
3688 while (ok && this_element != NULL)
3690 char *output_name;
3691 bfd *output_element;
3692 struct stat buf;
3693 int stat_status = 0;
3694 bool ok_object;
3695 const char *element_name;
3697 element_name = bfd_get_filename (this_element);
3698 /* PR binutils/17533: Do not allow directory traversal
3699 outside of the current directory tree by archive members. */
3700 if (! is_valid_archive_path (element_name))
3702 non_fatal (_("warning: illegal pathname found in archive member: %s"),
3703 element_name);
3704 /* PR binutils/31250: But there tools which create archives
3705 containing absolute paths, so instead of failing here, try to
3706 create a suitable alternative pathname. */
3707 element_name = lbasename (element_name);
3708 non_fatal (_("warning: using the basename of the member instead: %s"),
3709 element_name);
3712 /* Create an output file for this member. */
3713 output_name = concat (dir, "/", element_name, (char *) 0);
3715 /* If the file already exists, make another temp dir. */
3716 if (stat (output_name, &buf) >= 0)
3718 char * tmpdir = make_tempdir (output_name);
3720 free (output_name);
3721 if (tmpdir == NULL)
3723 non_fatal (_("cannot create tempdir for archive copying (error: %s)"),
3724 strerror (errno));
3725 bfd_close (this_element);
3726 ok = false;
3727 goto cleanup_and_exit;
3730 struct name_list *l = xmalloc (sizeof (*l));
3731 l->name = tmpdir;
3732 l->next = list;
3733 l->obfd = NULL;
3734 list = l;
3735 output_name = concat (tmpdir, "/", element_name, (char *) 0);
3738 if (preserve_dates)
3740 memset (&buf, 0, sizeof (buf));
3741 stat_status = bfd_stat_arch_elt (this_element, &buf);
3743 if (stat_status != 0)
3744 non_fatal (_("internal stat error on %s"), element_name);
3747 struct name_list *l = xmalloc (sizeof (*l));
3748 l->name = output_name;
3749 l->next = list;
3750 l->obfd = NULL;
3751 list = l;
3753 ok_object = bfd_check_format (this_element, bfd_object);
3754 if (!ok_object)
3755 bfd_nonfatal_message (NULL, this_element, NULL,
3756 _("Unable to recognise the format of file"));
3758 /* PR binutils/3110: Cope with archives
3759 containing multiple target types. */
3760 if (force_output_target || !ok_object)
3761 output_element = bfd_openw (output_name, output_target);
3762 else
3763 output_element = bfd_openw (output_name, bfd_get_target (this_element));
3765 if (output_element == NULL)
3767 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
3768 bfd_close (this_element);
3769 ok = false;
3770 goto cleanup_and_exit;
3773 if (ok_object)
3775 ok = copy_object (this_element, output_element, input_arch);
3777 if (!ok && bfd_get_arch (this_element) == bfd_arch_unknown)
3778 /* Try again as an unknown object file. */
3779 ok_object = false;
3782 if (!ok_object)
3783 ok = copy_unknown_object (this_element, output_element);
3785 if (!(ok_object && ok
3786 ? bfd_close : bfd_close_all_done) (output_element))
3788 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
3789 /* Error in new object file. Don't change archive. */
3790 ok = false;
3793 if (!ok)
3795 unlink (output_name);
3796 free (output_name);
3797 list->name = NULL;
3798 bfd_close (this_element);
3800 else
3802 if (preserve_dates && stat_status == 0)
3803 set_times (output_name, &buf);
3805 /* Open the newly created output file and attach to our list. */
3806 output_element = bfd_openr (output_name, output_target);
3808 list->obfd = output_element;
3810 *ptr = output_element;
3811 ptr = &output_element->archive_next;
3813 bfd *last_element = this_element;
3814 this_element = bfd_openr_next_archived_file (ibfd, last_element);
3815 bfd_close (last_element);
3818 *ptr = NULL;
3820 cleanup_and_exit:
3821 filename = xstrdup (bfd_get_filename (obfd));
3822 if (!(ok ? bfd_close : bfd_close_all_done) (obfd))
3824 if (ok)
3825 bfd_nonfatal_message (filename, NULL, NULL, NULL);
3826 ok = false;
3828 free (filename);
3830 filename = xstrdup (bfd_get_filename (ibfd));
3831 if (!bfd_close (ibfd))
3833 if (ok)
3834 bfd_nonfatal_message (filename, NULL, NULL, NULL);
3835 ok = false;
3837 free (filename);
3839 /* Delete all the files that we opened. */
3840 struct name_list *l, *next;
3841 for (l = list; l != NULL; l = next)
3843 if (l->name != NULL)
3845 if (l->obfd == NULL)
3846 rmdir (l->name);
3847 else
3848 unlink (l->name);
3849 free (l->name);
3851 next = l->next;
3852 free (l);
3855 if (dir)
3857 rmdir (dir);
3858 free (dir);
3860 return ok;
3863 /* The top-level control. */
3865 static void
3866 copy_file (const char *input_filename, const char *output_filename, int ofd,
3867 struct stat *in_stat, const char *input_target,
3868 const char *output_target, const bfd_arch_info_type *input_arch)
3870 bfd *ibfd;
3871 char **obj_matching;
3872 char **core_matching;
3873 off_t size = get_file_size (input_filename);
3875 if (size < 1)
3877 if (size == 0)
3878 non_fatal (_("error: the input file '%s' is empty"),
3879 input_filename);
3880 status = 1;
3881 return;
3884 /* To allow us to do "strip *" without dying on the first
3885 non-object file, failures are nonfatal. */
3886 ibfd = bfd_openr (input_filename, input_target);
3887 if (ibfd == NULL || bfd_stat (ibfd, in_stat) != 0)
3889 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
3890 if (ibfd != NULL)
3891 bfd_close (ibfd);
3892 status = 1;
3893 return;
3896 switch (do_debug_sections)
3898 case compress_gnu_zlib:
3899 ibfd->flags |= BFD_COMPRESS;
3900 break;
3901 case compress:
3902 case compress_zlib:
3903 /* The above two cases ought to just set BFD_COMPRESS for non-ELF
3904 but we can't tell whether a file is ELF or not until after
3905 bfd_check_format_matches. FIXME maybe: decide compression
3906 style in BFD after bfd_check_format_matches. */
3907 case compress_gabi_zlib:
3908 ibfd->flags |= BFD_COMPRESS | BFD_COMPRESS_GABI;
3909 break;
3910 case compress_zstd:
3911 ibfd->flags |= BFD_COMPRESS | BFD_COMPRESS_GABI | BFD_COMPRESS_ZSTD;
3912 #ifndef HAVE_ZSTD
3913 fatal (_ ("--compress-debug-sections=zstd: binutils is not built with "
3914 "zstd support"));
3915 #endif
3916 break;
3917 case decompress:
3918 ibfd->flags |= BFD_DECOMPRESS;
3919 break;
3920 default:
3921 break;
3924 switch (do_elf_stt_common)
3926 case elf_stt_common:
3927 ibfd->flags |= BFD_CONVERT_ELF_COMMON | BFD_USE_ELF_STT_COMMON;
3928 break;
3929 break;
3930 case no_elf_stt_common:
3931 ibfd->flags |= BFD_CONVERT_ELF_COMMON;
3932 break;
3933 default:
3934 break;
3937 if (bfd_check_format (ibfd, bfd_archive))
3939 bool force_output_target;
3940 bfd *obfd;
3942 /* bfd_get_target does not return the correct value until
3943 bfd_check_format succeeds. */
3944 if (output_target == NULL)
3946 output_target = bfd_get_target (ibfd);
3947 force_output_target = false;
3949 else
3950 force_output_target = true;
3952 if (ofd >= 0)
3953 obfd = bfd_fdopenw (output_filename, output_target, ofd);
3954 else
3955 obfd = bfd_openw (output_filename, output_target);
3957 if (obfd == NULL)
3959 if (ofd >= 0)
3960 close (ofd);
3961 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
3962 bfd_close (ibfd);
3963 status = 1;
3964 return;
3967 if (gnu_debuglink_filename != NULL)
3969 non_fatal (_("--add-gnu-debuglink ignored for archive %s"),
3970 bfd_get_filename (ibfd));
3971 gnu_debuglink_filename = NULL;
3974 if (!copy_archive (ibfd, obfd, output_target, force_output_target,
3975 input_arch))
3976 status = 1;
3978 else if (bfd_check_format_matches (ibfd, bfd_object, &obj_matching))
3980 bfd *obfd;
3981 do_copy:
3983 /* bfd_get_target does not return the correct value until
3984 bfd_check_format succeeds. */
3985 if (output_target == NULL)
3986 output_target = bfd_get_target (ibfd);
3988 if (ofd >= 0)
3989 obfd = bfd_fdopenw (output_filename, output_target, ofd);
3990 else
3991 obfd = bfd_openw (output_filename, output_target);
3993 if (obfd == NULL)
3995 if (ofd >= 0)
3996 close (ofd);
3997 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
3998 bfd_close (ibfd);
3999 status = 1;
4000 return;
4003 if (! copy_object (ibfd, obfd, input_arch))
4004 status = 1;
4006 /* PR 17512: file: 0f15796a.
4007 If the file could not be copied it may not be in a writeable
4008 state. So use bfd_close_all_done to avoid the possibility of
4009 writing uninitialised data into the file. */
4010 if (! (status ? bfd_close_all_done (obfd) : bfd_close (obfd)))
4012 status = 1;
4013 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
4016 if (!bfd_close (ibfd))
4018 status = 1;
4019 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
4022 else
4024 bfd_error_type obj_error = bfd_get_error ();
4025 bfd_error_type core_error;
4027 if (bfd_check_format_matches (ibfd, bfd_core, &core_matching))
4029 /* This probably can't happen.. */
4030 if (obj_error == bfd_error_file_ambiguously_recognized)
4031 free (obj_matching);
4032 goto do_copy;
4035 core_error = bfd_get_error ();
4036 /* Report the object error in preference to the core error. */
4037 if (obj_error != core_error)
4038 bfd_set_error (obj_error);
4040 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
4042 if (obj_error == bfd_error_file_ambiguously_recognized)
4043 list_matching_formats (obj_matching);
4044 if (core_error == bfd_error_file_ambiguously_recognized)
4045 list_matching_formats (core_matching);
4047 bfd_close (ibfd);
4048 status = 1;
4052 /* Add a name to the section renaming list. */
4054 static void
4055 add_section_rename (const char * old_name, const char * new_name,
4056 flagword flags)
4058 section_rename * srename;
4060 /* Check for conflicts first. */
4061 for (srename = section_rename_list; srename != NULL; srename = srename->next)
4062 if (strcmp (srename->old_name, old_name) == 0)
4064 /* Silently ignore duplicate definitions. */
4065 if (strcmp (srename->new_name, new_name) == 0
4066 && srename->flags == flags)
4067 return;
4069 fatal (_("Multiple renames of section %s"), old_name);
4072 srename = (section_rename *) xmalloc (sizeof (* srename));
4074 srename->old_name = old_name;
4075 srename->new_name = new_name;
4076 srename->flags = flags;
4077 srename->next = section_rename_list;
4079 section_rename_list = srename;
4082 /* Check the section rename list for a new name of the input section
4083 called OLD_NAME. Returns the new name if one is found and sets
4084 RETURNED_FLAGS if non-NULL to the flags to be used for this section. */
4086 static const char *
4087 find_section_rename (const char *old_name, flagword *returned_flags)
4089 const section_rename *srename;
4091 for (srename = section_rename_list; srename != NULL; srename = srename->next)
4092 if (strcmp (srename->old_name, old_name) == 0)
4094 if (returned_flags != NULL && srename->flags != (flagword) -1)
4095 *returned_flags = srename->flags;
4097 return srename->new_name;
4100 return old_name;
4103 /* Once each of the sections is copied, we may still need to do some
4104 finalization work for private section headers. Do that here. */
4106 static bool
4107 setup_bfd_headers (bfd *ibfd, bfd *obfd)
4109 /* Allow the BFD backend to copy any private data it understands
4110 from the input section to the output section. */
4111 if (! bfd_copy_private_header_data (ibfd, obfd))
4113 bfd_nonfatal_message (NULL, ibfd, NULL,
4114 _("error in private header data"));
4115 return false;
4118 /* All went well. */
4119 return true;
4122 static inline signed int
4123 power_of_two (bfd_vma val)
4125 signed int result = 0;
4127 if (val == 0)
4128 return 0;
4130 while ((val & 1) == 0)
4132 val >>= 1;
4133 ++result;
4136 if (val != 1)
4137 /* Number has more than one 1, i.e. wasn't a power of 2. */
4138 return -1;
4140 return result;
4143 static unsigned int
4144 image_scn_align (unsigned int alignment)
4146 switch (alignment)
4148 case 8192: return IMAGE_SCN_ALIGN_8192BYTES;
4149 case 4096: return IMAGE_SCN_ALIGN_4096BYTES;
4150 case 2048: return IMAGE_SCN_ALIGN_2048BYTES;
4151 case 1024: return IMAGE_SCN_ALIGN_1024BYTES;
4152 case 512: return IMAGE_SCN_ALIGN_512BYTES;
4153 case 256: return IMAGE_SCN_ALIGN_256BYTES;
4154 case 128: return IMAGE_SCN_ALIGN_128BYTES;
4155 case 64: return IMAGE_SCN_ALIGN_64BYTES;
4156 case 32: return IMAGE_SCN_ALIGN_32BYTES;
4157 case 16: return IMAGE_SCN_ALIGN_16BYTES;
4158 case 8: return IMAGE_SCN_ALIGN_8BYTES;
4159 case 4: return IMAGE_SCN_ALIGN_4BYTES;
4160 case 2: return IMAGE_SCN_ALIGN_2BYTES;
4161 case 1: return IMAGE_SCN_ALIGN_1BYTES;
4162 default: return 0;
4166 /* Create a section in OBFD with the same
4167 name and attributes as ISECTION in IBFD. */
4169 static bool
4170 setup_section (bfd *ibfd, sec_ptr isection, bfd *obfd)
4172 struct section_list *p;
4173 sec_ptr osection;
4174 bfd_size_type size;
4175 bfd_vma vma;
4176 bfd_vma lma;
4177 flagword flags;
4178 const char *err = NULL;
4179 const char * name;
4180 const char * new_name;
4181 char *prefix = NULL;
4182 bool make_nobits;
4183 unsigned int alignment;
4185 if (is_strip_section (ibfd, isection))
4186 return true;
4188 /* Get the, possibly new, name of the output section. */
4189 name = bfd_section_name (isection);
4190 flags = bfd_section_flags (isection);
4191 if (bfd_get_flavour (ibfd) != bfd_get_flavour (obfd))
4193 flags &= bfd_applicable_section_flags (ibfd);
4194 flags &= bfd_applicable_section_flags (obfd);
4196 new_name = find_section_rename (name, &flags);
4197 if (new_name != name)
4199 name = new_name;
4200 flags = check_new_section_flags (flags, obfd, name);
4203 /* Prefix sections. */
4204 if (prefix_alloc_sections_string
4205 && (bfd_section_flags (isection) & SEC_ALLOC) != 0)
4206 prefix = prefix_alloc_sections_string;
4207 else if (prefix_sections_string)
4208 prefix = prefix_sections_string;
4210 if (prefix)
4212 char *n;
4214 n = (char *) xmalloc (strlen (prefix) + strlen (name) + 1);
4215 strcpy (n, prefix);
4216 strcat (n, name);
4217 name = n;
4220 make_nobits = false;
4222 p = find_section_list (bfd_section_name (isection), false,
4223 SECTION_CONTEXT_SET_FLAGS);
4224 if (p != NULL)
4226 flags = p->flags | (flags & (SEC_HAS_CONTENTS | SEC_RELOC));
4227 flags = check_new_section_flags (flags, obfd, bfd_section_name (isection));
4229 else
4231 flagword clr = 0;
4233 /* For --extract-symbols where section sizes are zeroed, clear
4234 SEC_LOAD to indicate to coff_compute_section_file_positions that
4235 section sizes should not be adjusted for ALIGN_SECTIONS_IN_FILE.
4236 We don't want to clear SEC_HAS_CONTENTS as that will result
4237 in symbols being classified as 'B' by nm. */
4238 if (extract_symbol)
4239 clr = SEC_LOAD;
4240 /* If only keeping debug sections then we'll be keeping section
4241 sizes in headers but making the sections have no contents. */
4242 else if (strip_symbols == STRIP_NONDEBUG
4243 && (flags & (SEC_ALLOC | SEC_GROUP)) != 0
4244 && !is_nondebug_keep_contents_section (ibfd, isection))
4245 clr = SEC_HAS_CONTENTS | SEC_LOAD | SEC_GROUP;
4247 if (clr && bfd_get_flavour (obfd) == bfd_target_elf_flavour)
4249 /* PR 29532: Copy group sections intact as otherwise we end up with
4250 empty groups. This prevents separate debug info files from
4251 being used with GDB, if they were based upon files that
4252 originally contained groups. */
4253 if (flags & SEC_GROUP)
4254 clr = SEC_LOAD;
4255 if ((clr & SEC_HAS_CONTENTS) != 0)
4256 make_nobits = true;
4258 /* Twiddle the input section flags so that it seems to
4259 elf.c:copy_private_bfd_data that section flags have not
4260 changed between input and output sections. This hack
4261 prevents wholesale rewriting of the program headers. */
4262 isection->flags &= ~clr;
4264 flags &= ~clr;
4267 if (!bfd_convert_section_setup (ibfd, isection, obfd, &name, &size))
4269 osection = NULL;
4270 err = _("failed to create output section");
4271 goto loser;
4274 osection = bfd_make_section_anyway_with_flags (obfd, name, flags);
4276 if (osection == NULL)
4278 err = _("failed to create output section");
4279 goto loser;
4282 if (copy_byte >= 0)
4283 size = (size + interleave - 1) / interleave * copy_width;
4284 else if (extract_symbol)
4285 size = 0;
4286 if (!bfd_set_section_size (osection, size))
4287 err = _("failed to set size");
4289 bool vma_set_by_user = false;
4291 vma = bfd_section_vma (isection);
4292 p = find_section_list (bfd_section_name (isection), false,
4293 SECTION_CONTEXT_ALTER_VMA | SECTION_CONTEXT_SET_VMA);
4294 if (p != NULL)
4296 if (p->context & SECTION_CONTEXT_SET_VMA)
4297 vma = p->vma_val;
4298 else
4299 vma += p->vma_val;
4300 vma_set_by_user = true;
4302 else
4303 vma += change_section_address;
4305 if (!bfd_set_section_vma (osection, vma))
4306 err = _("failed to set vma");
4308 bool lma_set_by_user = false;
4310 lma = isection->lma;
4311 p = find_section_list (bfd_section_name (isection), false,
4312 SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_SET_LMA);
4313 if (p != NULL)
4315 if (p->context & SECTION_CONTEXT_ALTER_LMA)
4316 lma += p->lma_val;
4317 else
4318 lma = p->lma_val;
4319 lma_set_by_user = true;
4321 else
4322 lma += change_section_address;
4324 osection->lma = lma;
4326 p = find_section_list (bfd_section_name (isection), false,
4327 SECTION_CONTEXT_SET_ALIGNMENT);
4328 if (p != NULL)
4329 alignment = p->alignment;
4330 else if (pe_section_alignment != (bfd_vma) -1
4331 && bfd_get_flavour (ibfd) == bfd_target_coff_flavour
4332 && bfd_get_flavour (obfd) == bfd_target_coff_flavour)
4334 alignment = power_of_two (pe_section_alignment);
4336 if (coff_section_data (ibfd, isection))
4338 struct pei_section_tdata * pei_data = pei_section_data (ibfd, isection);
4340 if (pei_data != NULL)
4342 /* Set the alignment flag of the input section, which will
4343 be copied to the output section later on. */
4344 pei_data->pe_flags &= ~IMAGE_SCN_ALIGN_POWER_BIT_MASK;
4345 pei_data->pe_flags |= image_scn_align (pe_section_alignment);
4349 else
4350 alignment = bfd_section_alignment (isection);
4352 /* FIXME: This is probably not enough. If we change the LMA we
4353 may have to recompute the header for the file as well. */
4354 if (!bfd_set_section_alignment (osection, alignment))
4355 err = _("failed to set alignment");
4357 /* If the output section's VMA is not aligned
4358 and the alignment has changed
4359 and the VMA was not set by the user
4360 and the section does not have relocations associated with it
4361 then warn the user. */
4362 if (osection->vma != 0
4363 && (alignment >= sizeof (bfd_vma) * CHAR_BIT
4364 || (osection->vma & (((bfd_vma) 1 << alignment) - 1)) != 0)
4365 && alignment != bfd_section_alignment (isection)
4366 && change_section_address == 0
4367 && ! vma_set_by_user
4368 && bfd_get_reloc_upper_bound (ibfd, isection) < 1)
4370 non_fatal (_("output section %s's alignment does not match its VMA"), name);
4373 /* Similar check for a non-aligned LMA.
4374 FIXME: Since this is only an LMA, maybe it does not matter if
4375 it is not aligned ? */
4376 if (osection->lma != 0
4377 && (alignment >= sizeof (bfd_vma) * CHAR_BIT
4378 || (osection->lma & (((bfd_vma) 1 << alignment) - 1)) != 0)
4379 && alignment != bfd_section_alignment (isection)
4380 && change_section_address == 0
4381 && ! lma_set_by_user
4382 && bfd_get_reloc_upper_bound (ibfd, isection) < 1)
4384 non_fatal (_("output section %s's alignment does not match its LMA"), name);
4387 /* Copy merge entity size. */
4388 osection->entsize = isection->entsize;
4390 /* Copy compress status. */
4391 osection->compress_status = isection->compress_status;
4393 /* This used to be mangle_section; we do here to avoid using
4394 bfd_get_section_by_name since some formats allow multiple
4395 sections with the same name. */
4396 isection->output_section = osection;
4397 isection->output_offset = 0;
4399 if ((isection->flags & SEC_GROUP) != 0)
4401 asymbol *gsym = group_signature (isection);
4403 if (gsym != NULL)
4405 gsym->flags |= BSF_KEEP;
4406 if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour)
4407 elf_group_id (isection) = gsym;
4411 /* Allow the BFD backend to copy any private data it understands
4412 from the input section to the output section. */
4413 if (!bfd_copy_private_section_data (ibfd, isection, obfd, osection))
4414 err = _("failed to copy private data");
4416 if (make_nobits)
4417 elf_section_type (osection) = SHT_NOBITS;
4419 if (!err)
4420 return true;
4422 loser:
4423 bfd_nonfatal_message (NULL, obfd, osection, err);
4424 return false;
4427 /* Return TRUE if input section ISECTION should be skipped. */
4429 static bool
4430 skip_section (bfd *ibfd, sec_ptr isection, bool skip_copy)
4432 sec_ptr osection;
4433 bfd_size_type size;
4434 flagword flags;
4436 /* If we have already failed earlier on,
4437 do not keep on generating complaints now. */
4438 if (status != 0)
4439 return true;
4441 if (extract_symbol)
4442 return true;
4444 if (is_strip_section (ibfd, isection))
4445 return true;
4447 if (is_update_section (ibfd, isection))
4448 return true;
4450 /* When merging a note section we skip the copying of the contents,
4451 but not the copying of the relocs associated with the contents. */
4452 if (skip_copy && is_mergeable_note_section (ibfd, isection))
4453 return true;
4455 flags = bfd_section_flags (isection);
4456 if ((flags & SEC_GROUP) != 0)
4457 return true;
4459 osection = isection->output_section;
4460 size = bfd_section_size (isection);
4462 if (size == 0 || osection == 0)
4463 return true;
4465 return false;
4468 /* Add section SECTION_PATTERN to the list of sections that will have their
4469 relocations removed. */
4471 static void
4472 handle_remove_relocations_option (const char *section_pattern)
4474 find_section_list (section_pattern, true, SECTION_CONTEXT_REMOVE_RELOCS);
4477 /* Return TRUE if ISECTION from IBFD should have its relocations removed,
4478 otherwise return FALSE. If the user has requested that relocations be
4479 removed from a section that does not have relocations then this
4480 function will still return TRUE. */
4482 static bool
4483 discard_relocations (bfd *ibfd ATTRIBUTE_UNUSED, asection *isection)
4485 return (find_section_list (bfd_section_name (isection), false,
4486 SECTION_CONTEXT_REMOVE_RELOCS) != NULL);
4489 /* Wrapper for dealing with --remove-section (-R) command line arguments.
4490 A special case is detected here, if the user asks to remove a relocation
4491 section (one starting with ".rela" or ".rel") then this removal must
4492 be done using a different technique in a relocatable object. */
4494 static void
4495 handle_remove_section_option (const char *section_pattern)
4497 find_section_list (section_pattern, true, SECTION_CONTEXT_REMOVE);
4498 if (startswith (section_pattern, ".rel"))
4500 section_pattern += 4;
4501 if (*section_pattern == 'a')
4502 section_pattern++;
4503 if (*section_pattern)
4504 handle_remove_relocations_option (section_pattern);
4506 sections_removed = true;
4509 /* Copy relocations in input section ISECTION of IBFD to an output
4510 section with the same name in OBFDARG. If stripping then don't
4511 copy any relocation info. */
4513 static bool
4514 copy_relocations_in_section (bfd *ibfd, sec_ptr isection, bfd *obfd)
4516 long relsize;
4517 arelent **relpp;
4518 long relcount;
4519 sec_ptr osection;
4521 if (skip_section (ibfd, isection, false))
4522 return true;
4524 osection = isection->output_section;
4526 /* Core files and DWO files do not need to be relocated. */
4527 if (bfd_get_format (obfd) == bfd_core
4528 || strip_symbols == STRIP_NONDWO
4529 || (strip_symbols == STRIP_ALL
4530 && htab_elements (keep_specific_htab) == 0)
4531 || discard_relocations (ibfd, isection))
4532 relsize = 0;
4533 else
4535 relsize = bfd_get_reloc_upper_bound (ibfd, isection);
4537 if (relsize < 0)
4539 /* Do not complain if the target does not support relocations. */
4540 if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
4541 relsize = 0;
4542 else
4544 bfd_nonfatal_message (NULL, ibfd, isection, NULL);
4545 return false;
4550 if (relsize == 0)
4551 bfd_set_reloc (obfd, osection, NULL, 0);
4552 else
4554 if (isection->orelocation != NULL)
4556 /* Some other function has already set up the output relocs
4557 for us, so scan those instead of the default relocs. */
4558 relcount = isection->reloc_count;
4559 relpp = isection->orelocation;
4561 else
4563 relpp = bfd_xalloc (obfd, relsize);
4564 relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, isympp);
4565 if (relcount < 0)
4567 bfd_nonfatal_message (NULL, ibfd, isection,
4568 _("relocation count is negative"));
4569 return false;
4573 if (strip_symbols == STRIP_ALL)
4575 /* Remove relocations which are not in
4576 keep_strip_specific_list. */
4577 arelent **w_relpp;
4578 long i;
4580 for (w_relpp = relpp, i = 0; i < relcount; i++)
4581 /* PR 17512: file: 9e907e0c. */
4582 if (relpp[i]->sym_ptr_ptr
4583 /* PR 20096 */
4584 && *relpp[i]->sym_ptr_ptr
4585 && is_specified_symbol (bfd_asymbol_name (*relpp[i]->sym_ptr_ptr),
4586 keep_specific_htab))
4587 *w_relpp++ = relpp[i];
4588 relcount = w_relpp - relpp;
4589 *w_relpp = 0;
4592 bfd_set_reloc (obfd, osection, relcount == 0 ? NULL : relpp, relcount);
4594 return true;
4597 /* Copy the data of input section ISECTION of IBFD
4598 to an output section with the same name in OBFD. */
4600 static bool
4601 copy_section (bfd *ibfd, sec_ptr isection, bfd *obfd)
4603 struct section_list *p;
4604 sec_ptr osection;
4605 bfd_size_type size;
4607 if (skip_section (ibfd, isection, true))
4608 return true;
4610 osection = isection->output_section;
4611 /* The output SHF_COMPRESSED section size is different from input if
4612 ELF classes of input and output aren't the same. We can't use
4613 the output section size since --interleave will shrink the output
4614 section. Size will be updated if the section is converted. */
4615 size = bfd_section_size (isection);
4617 if (bfd_section_flags (isection) & SEC_HAS_CONTENTS
4618 && bfd_section_flags (osection) & SEC_HAS_CONTENTS)
4620 bfd_byte *memhunk = NULL;
4622 if (!bfd_get_full_section_contents (ibfd, isection, &memhunk)
4623 || !bfd_convert_section_contents (ibfd, isection, obfd,
4624 &memhunk, &size))
4626 bfd_set_section_size (osection, 0);
4627 bfd_nonfatal_message (NULL, ibfd, isection, NULL);
4628 free (memhunk);
4629 return false;
4632 if (reverse_bytes)
4634 /* We don't handle leftover bytes (too many possible behaviors,
4635 and we don't know what the user wants). The section length
4636 must be a multiple of the number of bytes to swap. */
4637 if ((size % reverse_bytes) == 0)
4639 unsigned long i, j;
4640 bfd_byte b;
4642 for (i = 0; i < size; i += reverse_bytes)
4643 for (j = 0; j < (unsigned long)(reverse_bytes / 2); j++)
4645 bfd_byte *m = (bfd_byte *) memhunk;
4647 b = m[i + j];
4648 m[i + j] = m[(i + reverse_bytes) - (j + 1)];
4649 m[(i + reverse_bytes) - (j + 1)] = b;
4652 else
4653 /* User must pad the section up in order to do this. */
4654 fatal (_("cannot reverse bytes: length of section %s must be evenly divisible by %d"),
4655 bfd_section_name (isection), reverse_bytes);
4658 if (copy_byte >= 0)
4660 /* Keep only every `copy_byte'th byte in MEMHUNK. */
4661 char *from = (char *) memhunk + copy_byte;
4662 char *to = (char *) memhunk;
4663 char *end = (char *) memhunk + size;
4664 int i;
4666 /* If the section address is not exactly divisible by the interleave,
4667 then we must bias the from address. If the copy_byte is less than
4668 the bias, then we must skip forward one interleave, and increment
4669 the final lma. */
4670 int extra = isection->lma % interleave;
4671 from -= extra;
4672 if (copy_byte < extra)
4673 from += interleave;
4675 for (; from < end; from += interleave)
4676 for (i = 0; i < copy_width; i++)
4678 if (&from[i] >= end)
4679 break;
4680 *to++ = from[i];
4683 size = (size + interleave - 1 - copy_byte) / interleave * copy_width;
4684 osection->lma /= interleave;
4685 if (copy_byte < extra)
4686 osection->lma++;
4689 if (!bfd_set_section_contents (obfd, osection, memhunk, 0, size))
4691 bfd_nonfatal_message (NULL, obfd, osection, NULL);
4692 free (memhunk);
4693 return false;
4695 free (memhunk);
4697 else if ((p = find_section_list (bfd_section_name (isection),
4698 false, SECTION_CONTEXT_SET_FLAGS)) != NULL
4699 && (p->flags & SEC_HAS_CONTENTS) != 0)
4701 void *memhunk = xmalloc (size);
4703 /* We don't permit the user to turn off the SEC_HAS_CONTENTS
4704 flag--they can just remove the section entirely and add it
4705 back again. However, we do permit them to turn on the
4706 SEC_HAS_CONTENTS flag, and take it to mean that the section
4707 contents should be zeroed out. */
4709 memset (memhunk, 0, size);
4710 if (! bfd_set_section_contents (obfd, osection, memhunk, 0, size))
4712 bfd_nonfatal_message (NULL, obfd, osection, NULL);
4713 free (memhunk);
4714 return false;
4716 free (memhunk);
4718 return true;
4721 /* Sort sections by LMA. This is called via qsort, and is used when
4722 --gap-fill or --pad-to is used. We force non loadable or empty
4723 sections to the front, where they are easier to ignore. */
4725 static int
4726 compare_section_lma (const void *arg1, const void *arg2)
4728 const asection *sec1 = *(const asection **) arg1;
4729 const asection *sec2 = *(const asection **) arg2;
4730 flagword flags1, flags2;
4732 /* Sort non loadable sections to the front. */
4733 flags1 = sec1->flags;
4734 flags2 = sec2->flags;
4735 if ((flags1 & SEC_HAS_CONTENTS) == 0
4736 || (flags1 & SEC_LOAD) == 0)
4738 if ((flags2 & SEC_HAS_CONTENTS) != 0
4739 && (flags2 & SEC_LOAD) != 0)
4740 return -1;
4742 else
4744 if ((flags2 & SEC_HAS_CONTENTS) == 0
4745 || (flags2 & SEC_LOAD) == 0)
4746 return 1;
4749 /* Sort sections by LMA. */
4750 if (sec1->lma > sec2->lma)
4751 return 1;
4752 if (sec1->lma < sec2->lma)
4753 return -1;
4755 /* Sort sections with the same LMA by size. */
4756 if (bfd_section_size (sec1) > bfd_section_size (sec2))
4757 return 1;
4758 if (bfd_section_size (sec1) < bfd_section_size (sec2))
4759 return -1;
4761 if (sec1->id > sec2->id)
4762 return 1;
4763 if (sec1->id < sec2->id)
4764 return -1;
4765 return 0;
4768 /* Mark all the symbols which will be used in output relocations with
4769 the BSF_KEEP flag so that those symbols will not be stripped.
4771 Ignore relocations which will not appear in the output file. */
4773 static bool
4774 mark_symbols_used_in_relocations (bfd *ibfd, sec_ptr isection, asymbol **symbols)
4776 long relsize;
4777 arelent **relpp;
4778 long relcount, i;
4780 /* Ignore an input section with no corresponding output section. */
4781 if (isection->output_section == NULL)
4782 return true;
4784 relsize = bfd_get_reloc_upper_bound (ibfd, isection);
4785 if (relsize < 0)
4787 /* Do not complain if the target does not support relocations. */
4788 if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
4789 return true;
4790 return false;
4793 if (relsize == 0)
4794 return true;
4796 relpp = (arelent **) xmalloc (relsize);
4797 relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, symbols);
4798 if (relcount < 0)
4800 free (relpp);
4801 return false;
4804 /* Examine each symbol used in a relocation. If it's not one of the
4805 special bfd section symbols, then mark it with BSF_KEEP. */
4806 for (i = 0; i < relcount; i++)
4808 /* See PRs 20923 and 20930 for reproducers for the NULL tests. */
4809 if (relpp[i]->sym_ptr_ptr != NULL
4810 && * relpp[i]->sym_ptr_ptr != NULL
4811 && *relpp[i]->sym_ptr_ptr != bfd_com_section_ptr->symbol
4812 && *relpp[i]->sym_ptr_ptr != bfd_abs_section_ptr->symbol
4813 && *relpp[i]->sym_ptr_ptr != bfd_und_section_ptr->symbol)
4814 (*relpp[i]->sym_ptr_ptr)->flags |= BSF_KEEP;
4817 free (relpp);
4818 return true;
4821 /* Write out debugging information. */
4823 static bool
4824 write_debugging_info (bfd *obfd, void *dhandle,
4825 long *symcountp ATTRIBUTE_UNUSED,
4826 asymbol ***symppp ATTRIBUTE_UNUSED)
4828 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
4829 || bfd_get_flavour (obfd) == bfd_target_elf_flavour)
4831 bfd_byte *syms, *strings = NULL;
4832 bfd_size_type symsize, stringsize;
4833 asection *stabsec, *stabstrsec;
4834 flagword flags;
4835 bool ret;
4837 if (! write_stabs_in_sections_debugging_info (obfd, dhandle, &syms,
4838 &symsize, &strings,
4839 &stringsize))
4840 return false;
4842 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DEBUGGING;
4843 stabsec = bfd_make_section_with_flags (obfd, ".stab", flags);
4844 stabstrsec = bfd_make_section_with_flags (obfd, ".stabstr", flags);
4845 ret = true;
4846 if (stabsec == NULL
4847 || stabstrsec == NULL
4848 || !bfd_set_section_size (stabsec, symsize)
4849 || !bfd_set_section_size (stabstrsec, stringsize)
4850 || !bfd_set_section_alignment (stabsec, 2)
4851 || !bfd_set_section_alignment (stabstrsec, 0))
4853 bfd_nonfatal_message (NULL, obfd, NULL,
4854 _("can't create debugging section"));
4855 ret = false;
4858 /* We can get away with setting the section contents now because
4859 the next thing the caller is going to do is copy over the
4860 real sections. We may someday have to split the contents
4861 setting out of this function. */
4862 if (ret
4863 && (!bfd_set_section_contents (obfd, stabsec, syms, 0, symsize)
4864 || !bfd_set_section_contents (obfd, stabstrsec, strings, 0,
4865 stringsize)))
4867 bfd_nonfatal_message (NULL, obfd, NULL,
4868 _("can't set debugging section contents"));
4869 ret = false;
4872 free (strings);
4873 free (syms);
4874 return ret;
4877 bfd_nonfatal_message (NULL, obfd, NULL,
4878 _("don't know how to write debugging information for %s"),
4879 bfd_get_target (obfd));
4880 return false;
4883 /* If neither -D nor -U was specified explicitly,
4884 then use the configured default. */
4885 static void
4886 default_deterministic (void)
4888 if (deterministic < 0)
4889 deterministic = DEFAULT_AR_DETERMINISTIC;
4892 static int
4893 strip_main (int argc, char *argv[])
4895 char *input_target = NULL;
4896 char *output_target = NULL;
4897 bool show_version = false;
4898 bool formats_info = false;
4899 int c;
4900 int i;
4901 char *output_file = NULL;
4902 bool merge_notes_set = false;
4904 while ((c = getopt_long (argc, argv, "I:O:F:K:MN:R:o:sSpdgxXHhVvwDU",
4905 strip_options, (int *) 0)) != EOF)
4907 switch (c)
4909 case 'I':
4910 input_target = optarg;
4911 break;
4912 case 'O':
4913 output_target = optarg;
4914 break;
4915 case 'F':
4916 input_target = output_target = optarg;
4917 break;
4918 case 'R':
4919 handle_remove_section_option (optarg);
4920 break;
4921 case OPTION_KEEP_SECTION:
4922 find_section_list (optarg, true, SECTION_CONTEXT_KEEP);
4923 break;
4924 case OPTION_REMOVE_RELOCS:
4925 handle_remove_relocations_option (optarg);
4926 break;
4927 case OPTION_STRIP_SECTION_HEADERS:
4928 strip_section_headers = true;
4929 break;
4930 case 's':
4931 strip_symbols = STRIP_ALL;
4932 break;
4933 case 'S':
4934 case 'g':
4935 case 'd': /* Historic BSD alias for -g. Used by early NetBSD. */
4936 strip_symbols = STRIP_DEBUG;
4937 break;
4938 case OPTION_STRIP_DWO:
4939 strip_symbols = STRIP_DWO;
4940 break;
4941 case OPTION_STRIP_UNNEEDED:
4942 strip_symbols = STRIP_UNNEEDED;
4943 break;
4944 case 'K':
4945 add_specific_symbol (optarg, keep_specific_htab);
4946 break;
4947 case 'M':
4948 merge_notes = true;
4949 merge_notes_set = true;
4950 break;
4951 case OPTION_NO_MERGE_NOTES:
4952 merge_notes = false;
4953 merge_notes_set = true;
4954 break;
4955 case 'N':
4956 add_specific_symbol (optarg, strip_specific_htab);
4957 break;
4958 case 'o':
4959 output_file = optarg;
4960 break;
4961 case 'p':
4962 preserve_dates = true;
4963 break;
4964 case 'D':
4965 deterministic = true;
4966 break;
4967 case 'U':
4968 deterministic = false;
4969 break;
4970 case 'x':
4971 discard_locals = LOCALS_ALL;
4972 break;
4973 case 'X':
4974 discard_locals = LOCALS_START_L;
4975 break;
4976 case 'v':
4977 verbose = true;
4978 break;
4979 case 'V':
4980 show_version = true;
4981 break;
4982 case OPTION_FORMATS_INFO:
4983 formats_info = true;
4984 break;
4985 case OPTION_ONLY_KEEP_DEBUG:
4986 strip_symbols = STRIP_NONDEBUG;
4987 break;
4988 case OPTION_KEEP_FILE_SYMBOLS:
4989 keep_file_symbols = 1;
4990 break;
4991 case OPTION_KEEP_SECTION_SYMBOLS:
4992 keep_section_symbols = true;
4993 break;
4994 case 0:
4995 /* We've been given a long option. */
4996 break;
4997 case 'w':
4998 wildcard = true;
4999 break;
5000 case 'H':
5001 case 'h':
5002 strip_usage (stdout, 0);
5003 default:
5004 strip_usage (stderr, 1);
5008 /* If the user has not expressly chosen to merge/not-merge ELF notes
5009 then enable the merging unless we are stripping debug or dwo info. */
5010 if (! merge_notes_set
5011 && (strip_symbols == STRIP_UNDEF
5012 || strip_symbols == STRIP_ALL
5013 || strip_symbols == STRIP_UNNEEDED
5014 || strip_symbols == STRIP_NONDEBUG
5015 || strip_symbols == STRIP_NONDWO))
5016 merge_notes = true;
5018 if (formats_info)
5020 display_info ();
5021 return 0;
5024 if (show_version)
5025 print_version ("strip");
5027 default_deterministic ();
5029 /* Default is to strip all symbols. */
5030 if (strip_symbols == STRIP_UNDEF
5031 && discard_locals == LOCALS_UNDEF
5032 && htab_elements (strip_specific_htab) == 0)
5033 strip_symbols = STRIP_ALL;
5035 if (output_target == NULL)
5036 output_target = input_target;
5038 i = optind;
5039 if (i == argc
5040 || (output_file != NULL && (i + 1) < argc))
5041 strip_usage (stderr, 1);
5043 for (; i < argc; i++)
5045 int hold_status = status;
5046 struct stat statbuf;
5047 char *tmpname;
5048 int tmpfd = -1;
5049 int copyfd = -1;
5051 if (get_file_size (argv[i]) < 1)
5053 status = 1;
5054 continue;
5057 if (output_file == NULL
5058 || filename_cmp (argv[i], output_file) == 0)
5060 tmpname = make_tempname (argv[i], &tmpfd);
5061 if (tmpfd >= 0)
5062 copyfd = dup (tmpfd);
5064 else
5065 tmpname = output_file;
5067 if (tmpname == NULL)
5069 bfd_nonfatal_message (argv[i], NULL, NULL,
5070 _("could not create temporary file to hold stripped copy"));
5071 status = 1;
5072 continue;
5075 status = 0;
5076 copy_file (argv[i], tmpname, tmpfd, &statbuf, input_target,
5077 output_target, NULL);
5078 if (status == 0)
5080 const char *oname = output_file ? output_file : argv[i];
5081 status = smart_rename (tmpname, oname, copyfd,
5082 &statbuf, preserve_dates) != 0;
5083 if (status == 0)
5084 status = hold_status;
5086 else
5088 if (copyfd >= 0)
5089 close (copyfd);
5090 unlink_if_ordinary (tmpname);
5092 if (output_file != tmpname)
5093 free (tmpname);
5096 return status;
5099 /* Set up PE subsystem. */
5101 static void
5102 set_pe_subsystem (const char *s)
5104 const char *version, *subsystem;
5105 size_t i;
5106 static const struct
5108 const char *name;
5109 const char set_def;
5110 const short value;
5112 v[] =
5114 { "native", 0, IMAGE_SUBSYSTEM_NATIVE },
5115 { "windows", 0, IMAGE_SUBSYSTEM_WINDOWS_GUI },
5116 { "console", 0, IMAGE_SUBSYSTEM_WINDOWS_CUI },
5117 { "posix", 0, IMAGE_SUBSYSTEM_POSIX_CUI },
5118 { "wince", 0, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI },
5119 { "efi-app", 1, IMAGE_SUBSYSTEM_EFI_APPLICATION },
5120 { "efi-bsd", 1, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER },
5121 { "efi-rtd", 1, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER },
5122 { "sal-rtd", 1, IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER },
5123 { "xbox", 0, IMAGE_SUBSYSTEM_XBOX }
5125 short value;
5126 char *copy;
5127 int set_def = -1;
5129 /* Check for the presence of a version number. */
5130 version = strchr (s, ':');
5131 if (version == NULL)
5132 subsystem = s;
5133 else
5135 int len = version - s;
5136 copy = xstrdup (s);
5137 subsystem = copy;
5138 copy[len] = '\0';
5139 version = copy + 1 + len;
5140 pe_major_subsystem_version = strtoul (version, &copy, 0);
5141 if (*copy == '.')
5142 pe_minor_subsystem_version = strtoul (copy + 1, &copy, 0);
5143 if (*copy != '\0')
5144 non_fatal (_("%s: bad version in PE subsystem"), s);
5147 /* Check for numeric subsystem. */
5148 value = (short) strtol (subsystem, &copy, 0);
5149 if (*copy == '\0')
5151 for (i = 0; i < ARRAY_SIZE (v); i++)
5152 if (v[i].value == value)
5154 pe_subsystem = value;
5155 set_def = v[i].set_def;
5156 break;
5159 else
5161 /* Search for subsystem by name. */
5162 for (i = 0; i < ARRAY_SIZE (v); i++)
5163 if (strcmp (subsystem, v[i].name) == 0)
5165 pe_subsystem = v[i].value;
5166 set_def = v[i].set_def;
5167 break;
5171 switch (set_def)
5173 case -1:
5174 fatal (_("unknown PE subsystem: %s"), s);
5175 break;
5176 case 0:
5177 break;
5178 default:
5179 if (pe_file_alignment == (bfd_vma) -1)
5180 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
5181 if (pe_section_alignment == (bfd_vma) -1)
5182 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
5183 break;
5185 if (s != subsystem)
5186 free ((char *) subsystem);
5189 /* Convert EFI target to PEI target. */
5191 static int
5192 convert_efi_target (char **targ)
5194 size_t len;
5195 char *pei;
5196 char *efi = *targ + 4;
5197 int subsys = -1;
5199 if (startswith (efi, "app-"))
5200 subsys = IMAGE_SUBSYSTEM_EFI_APPLICATION;
5201 else if (startswith (efi, "bsdrv-"))
5203 subsys = IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
5204 efi += 2;
5206 else if (startswith (efi, "rtdrv-"))
5208 subsys = IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER;
5209 efi += 2;
5211 else
5212 return subsys;
5214 len = strlen (efi);
5215 pei = xmalloc (len + sizeof ("-little"));
5216 memcpy (pei, efi, len + 1);
5217 pei[0] = 'p';
5218 pei[1] = 'e';
5219 pei[2] = 'i';
5221 if (strcmp (efi + 4, "ia32") == 0)
5223 /* Change ia32 to i386. */
5224 pei[5]= '3';
5225 pei[6]= '8';
5226 pei[7]= '6';
5228 else if (strcmp (efi + 4, "x86_64") == 0)
5230 /* Change x86_64 to x86-64. */
5231 pei[7] = '-';
5233 else if (strcmp (efi + 4, "aarch64") == 0)
5235 /* Change aarch64 to aarch64-little. */
5236 memcpy (pei + 4 + sizeof ("aarch64") - 1, "-little", sizeof ("-little"));
5238 else if (strcmp (efi + 4, "riscv64") == 0)
5240 /* Change riscv64 to riscv64-little. */
5241 memcpy (pei + 4 + sizeof ("riscv64") - 1, "-little", sizeof ("-little"));
5243 *targ = pei;
5244 return subsys;
5247 /* Allocate and return a pointer to a struct section_add, initializing the
5248 structure using ARG, a string in the format "sectionname=filename".
5249 The returned structure will have its next pointer set to NEXT. The
5250 OPTION field is the name of the command line option currently being
5251 parsed, and is only used if an error needs to be reported. */
5253 static struct section_add *
5254 init_section_add (const char *arg,
5255 struct section_add *next,
5256 const char *option)
5258 struct section_add *pa;
5259 const char *s;
5261 s = strchr (arg, '=');
5262 if (s == NULL)
5263 fatal (_("bad format for %s"), option);
5265 pa = (struct section_add *) xmalloc (sizeof (struct section_add));
5266 pa->name = xstrndup (arg, s - arg);
5267 pa->filename = s + 1;
5268 pa->next = next;
5269 pa->contents = NULL;
5270 pa->size = 0;
5272 return pa;
5275 /* Load the file specified in PA, allocating memory to hold the file
5276 contents, and store a pointer to the allocated memory in the contents
5277 field of PA. The size field of PA is also updated. All errors call
5278 FATAL. */
5280 static void
5281 section_add_load_file (struct section_add *pa)
5283 size_t off, alloc;
5284 FILE *f;
5286 /* We don't use get_file_size so that we can do
5287 --add-section .note.GNU_stack=/dev/null
5288 get_file_size doesn't work on /dev/null. */
5290 f = fopen (pa->filename, FOPEN_RB);
5291 if (f == NULL)
5292 fatal (_("cannot open: %s: %s"),
5293 pa->filename, strerror (errno));
5295 off = 0;
5296 alloc = 4096;
5297 pa->contents = (bfd_byte *) xmalloc (alloc);
5298 while (!feof (f))
5300 off_t got;
5302 if (off == alloc)
5304 alloc <<= 1;
5305 pa->contents = (bfd_byte *) xrealloc (pa->contents, alloc);
5308 got = fread (pa->contents + off, 1, alloc - off, f);
5309 if (ferror (f))
5310 fatal (_("%s: fread failed"), pa->filename);
5312 off += got;
5315 pa->size = off;
5317 fclose (f);
5320 static int
5321 copy_main (int argc, char *argv[])
5323 char *input_filename = NULL;
5324 char *output_filename = NULL;
5325 char *tmpname;
5326 char *input_target = NULL;
5327 char *output_target = NULL;
5328 bool show_version = false;
5329 bool change_warn = true;
5330 bool formats_info = false;
5331 bool use_globalize = false;
5332 bool use_keep_global = false;
5333 int c;
5334 int tmpfd = -1;
5335 int copyfd;
5336 struct stat statbuf;
5337 const bfd_arch_info_type *input_arch = NULL;
5339 while ((c = getopt_long (argc, argv, "b:B:i:I:j:K:MN:s:O:d:F:L:G:R:SpgxXHhVvW:wDU",
5340 copy_options, (int *) 0)) != EOF)
5342 switch (c)
5344 case 'b':
5345 copy_byte = atoi (optarg);
5346 if (copy_byte < 0)
5347 fatal (_("byte number must be non-negative"));
5348 break;
5350 case 'B':
5351 input_arch = bfd_scan_arch (optarg);
5352 if (input_arch == NULL)
5353 fatal (_("architecture %s unknown"), optarg);
5354 break;
5356 case 'i':
5357 if (optarg)
5359 interleave = atoi (optarg);
5360 if (interleave < 1)
5361 fatal (_("interleave must be positive"));
5363 else
5364 interleave = 4;
5365 break;
5367 case OPTION_INTERLEAVE_WIDTH:
5368 copy_width = atoi (optarg);
5369 if (copy_width < 1)
5370 fatal(_("interleave width must be positive"));
5371 break;
5373 case 'I':
5374 case 's': /* "source" - 'I' is preferred */
5375 input_target = optarg;
5376 break;
5378 case 'O':
5379 case 'd': /* "destination" - 'O' is preferred */
5380 output_target = optarg;
5381 break;
5383 case 'F':
5384 input_target = output_target = optarg;
5385 break;
5387 case 'j':
5388 find_section_list (optarg, true, SECTION_CONTEXT_COPY);
5389 sections_copied = true;
5390 break;
5392 case 'R':
5393 handle_remove_section_option (optarg);
5394 break;
5396 case OPTION_KEEP_SECTION:
5397 find_section_list (optarg, true, SECTION_CONTEXT_KEEP);
5398 break;
5400 case OPTION_REMOVE_RELOCS:
5401 handle_remove_relocations_option (optarg);
5402 break;
5404 case OPTION_STRIP_SECTION_HEADERS:
5405 strip_section_headers = true;
5406 break;
5408 case 'S':
5409 strip_symbols = STRIP_ALL;
5410 break;
5412 case 'g':
5413 strip_symbols = STRIP_DEBUG;
5414 break;
5416 case OPTION_STRIP_DWO:
5417 strip_symbols = STRIP_DWO;
5418 break;
5420 case OPTION_STRIP_UNNEEDED:
5421 strip_symbols = STRIP_UNNEEDED;
5422 break;
5424 case OPTION_ONLY_KEEP_DEBUG:
5425 strip_symbols = STRIP_NONDEBUG;
5426 break;
5428 case OPTION_KEEP_FILE_SYMBOLS:
5429 keep_file_symbols = 1;
5430 break;
5432 case OPTION_ADD_GNU_DEBUGLINK:
5433 long_section_names = ENABLE ;
5434 gnu_debuglink_filename = optarg;
5435 break;
5437 case 'K':
5438 add_specific_symbol (optarg, keep_specific_htab);
5439 break;
5441 case 'M':
5442 merge_notes = true;
5443 break;
5444 case OPTION_NO_MERGE_NOTES:
5445 merge_notes = false;
5446 break;
5448 case 'N':
5449 add_specific_symbol (optarg, strip_specific_htab);
5450 break;
5452 case OPTION_STRIP_UNNEEDED_SYMBOL:
5453 add_specific_symbol (optarg, strip_unneeded_htab);
5454 break;
5456 case 'L':
5457 add_specific_symbol (optarg, localize_specific_htab);
5458 break;
5460 case OPTION_GLOBALIZE_SYMBOL:
5461 use_globalize = true;
5462 add_specific_symbol (optarg, globalize_specific_htab);
5463 break;
5465 case 'G':
5466 use_keep_global = true;
5467 add_specific_symbol (optarg, keepglobal_specific_htab);
5468 break;
5470 case 'W':
5471 add_specific_symbol (optarg, weaken_specific_htab);
5472 break;
5474 case 'p':
5475 preserve_dates = true;
5476 break;
5478 case 'D':
5479 deterministic = true;
5480 break;
5482 case 'U':
5483 deterministic = false;
5484 break;
5486 case 'w':
5487 wildcard = true;
5488 break;
5490 case 'x':
5491 discard_locals = LOCALS_ALL;
5492 break;
5494 case 'X':
5495 discard_locals = LOCALS_START_L;
5496 break;
5498 case 'v':
5499 verbose = true;
5500 break;
5502 case 'V':
5503 show_version = true;
5504 break;
5506 case OPTION_FORMATS_INFO:
5507 formats_info = true;
5508 break;
5510 case OPTION_WEAKEN:
5511 weaken = true;
5512 break;
5514 case OPTION_ADD_SECTION:
5515 add_sections = init_section_add (optarg, add_sections,
5516 "--add-section");
5517 section_add_load_file (add_sections);
5518 break;
5520 case OPTION_UPDATE_SECTION:
5521 update_sections = init_section_add (optarg, update_sections,
5522 "--update-section");
5523 section_add_load_file (update_sections);
5524 break;
5526 case OPTION_DUMP_SECTION:
5527 dump_sections = init_section_add (optarg, dump_sections,
5528 "--dump-section");
5529 break;
5531 case OPTION_ADD_SYMBOL:
5533 char *s, *t;
5534 struct addsym_node *newsym = xmalloc (sizeof *newsym);
5536 newsym->next = NULL;
5537 s = strchr (optarg, '=');
5538 if (s == NULL)
5539 fatal (_("bad format for %s"), "--add-symbol");
5540 t = strchr (s + 1, ':');
5542 newsym->symdef = xstrndup (optarg, s - optarg);
5543 if (t)
5545 newsym->section = xstrndup (s + 1, t - (s + 1));
5546 newsym->symval = strtol (t + 1, NULL, 0);
5548 else
5550 newsym->section = NULL;
5551 newsym->symval = strtol (s + 1, NULL, 0);
5552 t = s;
5555 t = strchr (t + 1, ',');
5556 newsym->othersym = NULL;
5557 if (t)
5558 newsym->flags = parse_symflags (t+1, &newsym->othersym);
5559 else
5560 newsym->flags = BSF_GLOBAL;
5562 /* Keep 'othersym' symbols at the front of the list. */
5563 if (newsym->othersym)
5565 newsym->next = add_sym_list;
5566 if (!add_sym_list)
5567 add_sym_tail = &newsym->next;
5568 add_sym_list = newsym;
5570 else
5572 *add_sym_tail = newsym;
5573 add_sym_tail = &newsym->next;
5575 add_symbols++;
5577 break;
5579 case OPTION_CHANGE_START:
5580 change_start = parse_vma (optarg, "--change-start");
5581 break;
5583 case OPTION_CHANGE_SECTION_ADDRESS:
5584 case OPTION_CHANGE_SECTION_LMA:
5585 case OPTION_CHANGE_SECTION_VMA:
5587 struct section_list * p;
5588 unsigned int context = 0;
5589 const char *s;
5590 int len;
5591 char *name;
5592 char *option = NULL;
5593 bfd_vma val;
5595 switch (c)
5597 case OPTION_CHANGE_SECTION_ADDRESS:
5598 option = "--change-section-address";
5599 context = SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_ALTER_VMA;
5600 break;
5601 case OPTION_CHANGE_SECTION_LMA:
5602 option = "--change-section-lma";
5603 context = SECTION_CONTEXT_ALTER_LMA;
5604 break;
5605 case OPTION_CHANGE_SECTION_VMA:
5606 option = "--change-section-vma";
5607 context = SECTION_CONTEXT_ALTER_VMA;
5608 break;
5611 s = strchr (optarg, '=');
5612 if (s == NULL)
5614 s = strchr (optarg, '+');
5615 if (s == NULL)
5617 s = strchr (optarg, '-');
5618 if (s == NULL)
5619 fatal (_("bad format for %s"), option);
5622 else
5624 /* Correct the context. */
5625 switch (c)
5627 case OPTION_CHANGE_SECTION_ADDRESS:
5628 context = SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_SET_VMA;
5629 break;
5630 case OPTION_CHANGE_SECTION_LMA:
5631 context = SECTION_CONTEXT_SET_LMA;
5632 break;
5633 case OPTION_CHANGE_SECTION_VMA:
5634 context = SECTION_CONTEXT_SET_VMA;
5635 break;
5639 len = s - optarg;
5640 name = (char *) xmalloc (len + 1);
5641 strncpy (name, optarg, len);
5642 name[len] = '\0';
5644 p = find_section_list (name, true, context);
5646 val = parse_vma (s + 1, option);
5647 if (*s == '-')
5648 val = - val;
5650 switch (c)
5652 case OPTION_CHANGE_SECTION_ADDRESS:
5653 p->vma_val = val;
5654 /* Fall through. */
5656 case OPTION_CHANGE_SECTION_LMA:
5657 p->lma_val = val;
5658 break;
5660 case OPTION_CHANGE_SECTION_VMA:
5661 p->vma_val = val;
5662 break;
5665 break;
5667 case OPTION_CHANGE_ADDRESSES:
5668 change_section_address = parse_vma (optarg, "--change-addresses");
5669 change_start = change_section_address;
5670 break;
5672 case OPTION_CHANGE_WARNINGS:
5673 change_warn = true;
5674 break;
5676 case OPTION_CHANGE_LEADING_CHAR:
5677 change_leading_char = true;
5678 break;
5680 case OPTION_COMPRESS_DEBUG_SECTIONS:
5681 if (optarg)
5683 if (strcasecmp (optarg, "none") == 0)
5684 do_debug_sections = decompress;
5685 else if (strcasecmp (optarg, "zlib") == 0)
5686 do_debug_sections = compress_zlib;
5687 else if (strcasecmp (optarg, "zlib-gnu") == 0)
5688 do_debug_sections = compress_gnu_zlib;
5689 else if (strcasecmp (optarg, "zlib-gabi") == 0)
5690 do_debug_sections = compress_gabi_zlib;
5691 else if (strcasecmp (optarg, "zstd") == 0)
5692 do_debug_sections = compress_zstd;
5693 else
5694 fatal (_("unrecognized --compress-debug-sections type `%s'"),
5695 optarg);
5697 else
5698 do_debug_sections = compress;
5699 break;
5701 case OPTION_DEBUGGING:
5702 convert_debugging = true;
5703 break;
5705 case OPTION_DECOMPRESS_DEBUG_SECTIONS:
5706 do_debug_sections = decompress;
5707 break;
5709 case OPTION_ELF_STT_COMMON:
5710 if (strcasecmp (optarg, "yes") == 0)
5711 do_elf_stt_common = elf_stt_common;
5712 else if (strcasecmp (optarg, "no") == 0)
5713 do_elf_stt_common = no_elf_stt_common;
5714 else
5715 fatal (_("unrecognized --elf-stt-common= option `%s'"),
5716 optarg);
5717 break;
5719 case OPTION_GAP_FILL:
5721 bfd_vma gap_fill_vma;
5723 gap_fill_vma = parse_vma (optarg, "--gap-fill");
5724 gap_fill = (bfd_byte) gap_fill_vma;
5725 if ((bfd_vma) gap_fill != gap_fill_vma)
5726 non_fatal (_("Warning: truncating gap-fill from 0x%" PRIx64
5727 " to 0x%x"),
5728 (uint64_t) gap_fill_vma, gap_fill);
5729 gap_fill_set = true;
5731 break;
5733 case OPTION_NO_CHANGE_WARNINGS:
5734 change_warn = false;
5735 break;
5737 case OPTION_PAD_TO:
5738 pad_to = parse_vma (optarg, "--pad-to");
5739 pad_to_set = true;
5740 break;
5742 case OPTION_REMOVE_LEADING_CHAR:
5743 remove_leading_char = true;
5744 break;
5746 case OPTION_REDEFINE_SYM:
5748 /* Insert this redefinition onto redefine_specific_htab. */
5750 int len;
5751 const char *s;
5752 const char *nextarg;
5753 char *source, *target;
5755 s = strchr (optarg, '=');
5756 if (s == NULL)
5757 fatal (_("bad format for %s"), "--redefine-sym");
5759 len = s - optarg;
5760 source = (char *) xmalloc (len + 1);
5761 strncpy (source, optarg, len);
5762 source[len] = '\0';
5764 nextarg = s + 1;
5765 len = strlen (nextarg);
5766 target = (char *) xmalloc (len + 1);
5767 strcpy (target, nextarg);
5769 add_redefine_and_check ("--redefine-sym", source, target);
5771 free (source);
5772 free (target);
5774 break;
5776 case OPTION_REDEFINE_SYMS:
5777 add_redefine_syms_file (optarg);
5778 break;
5780 case OPTION_SET_SECTION_FLAGS:
5782 struct section_list *p;
5783 const char *s;
5784 int len;
5785 char *name;
5787 s = strchr (optarg, '=');
5788 if (s == NULL)
5789 fatal (_("bad format for %s"), "--set-section-flags");
5791 len = s - optarg;
5792 name = (char *) xmalloc (len + 1);
5793 strncpy (name, optarg, len);
5794 name[len] = '\0';
5796 p = find_section_list (name, true, SECTION_CONTEXT_SET_FLAGS);
5798 p->flags = parse_flags (s + 1);
5800 break;
5802 case OPTION_SET_SECTION_ALIGNMENT:
5804 struct section_list *p;
5805 const char *s;
5806 int len;
5807 char *name;
5808 int palign, align;
5810 s = strchr (optarg, '=');
5811 if (s == NULL)
5812 fatal (_("bad format for --set-section-alignment: argument needed"));
5814 align = atoi (s + 1);
5815 if (align <= 0)
5816 fatal (_("bad format for --set-section-alignment: numeric argument needed"));
5818 /* Convert integer alignment into a power-of-two alignment. */
5819 palign = power_of_two (align);
5820 if (palign == -1)
5821 fatal (_("bad format for --set-section-alignment: alignment is not a power of two"));
5823 /* Add the alignment setting to the section list. */
5824 len = s - optarg;
5825 name = (char *) xmalloc (len + 1);
5826 strncpy (name, optarg, len);
5827 name[len] = '\0';
5829 p = find_section_list (name, true, SECTION_CONTEXT_SET_ALIGNMENT);
5830 if (p)
5831 p->alignment = palign;
5833 break;
5835 case OPTION_RENAME_SECTION:
5837 flagword flags;
5838 const char *eq, *fl;
5839 char *old_name;
5840 char *new_name;
5841 unsigned int len;
5843 eq = strchr (optarg, '=');
5844 if (eq == NULL)
5845 fatal (_("bad format for %s"), "--rename-section");
5847 len = eq - optarg;
5848 if (len == 0)
5849 fatal (_("bad format for %s"), "--rename-section");
5851 old_name = (char *) xmalloc (len + 1);
5852 strncpy (old_name, optarg, len);
5853 old_name[len] = 0;
5855 eq++;
5856 fl = strchr (eq, ',');
5857 if (fl)
5859 flags = parse_flags (fl + 1);
5860 len = fl - eq;
5862 else
5864 flags = -1;
5865 len = strlen (eq);
5868 if (len == 0)
5869 fatal (_("bad format for %s"), "--rename-section");
5871 new_name = (char *) xmalloc (len + 1);
5872 strncpy (new_name, eq, len);
5873 new_name[len] = 0;
5875 add_section_rename (old_name, new_name, flags);
5877 break;
5879 case OPTION_SET_START:
5880 set_start = parse_vma (optarg, "--set-start");
5881 set_start_set = true;
5882 break;
5884 case OPTION_SREC_LEN:
5885 _bfd_srec_len = parse_vma (optarg, "--srec-len");
5886 break;
5888 case OPTION_SREC_FORCES3:
5889 _bfd_srec_forceS3 = true;
5890 break;
5892 case OPTION_STRIP_SYMBOLS:
5893 add_specific_symbols (optarg, strip_specific_htab,
5894 &strip_specific_buffer);
5895 break;
5897 case OPTION_STRIP_UNNEEDED_SYMBOLS:
5898 add_specific_symbols (optarg, strip_unneeded_htab,
5899 &strip_unneeded_buffer);
5900 break;
5902 case OPTION_KEEP_SYMBOLS:
5903 add_specific_symbols (optarg, keep_specific_htab,
5904 &keep_specific_buffer);
5905 break;
5907 case OPTION_KEEP_SECTION_SYMBOLS:
5908 keep_section_symbols = true;
5909 break;
5911 case OPTION_LOCALIZE_HIDDEN:
5912 localize_hidden = true;
5913 break;
5915 case OPTION_LOCALIZE_SYMBOLS:
5916 add_specific_symbols (optarg, localize_specific_htab,
5917 &localize_specific_buffer);
5918 break;
5920 case OPTION_LONG_SECTION_NAMES:
5921 if (!strcmp ("enable", optarg))
5922 long_section_names = ENABLE;
5923 else if (!strcmp ("disable", optarg))
5924 long_section_names = DISABLE;
5925 else if (!strcmp ("keep", optarg))
5926 long_section_names = KEEP;
5927 else
5928 fatal (_("unknown long section names option '%s'"), optarg);
5929 break;
5931 case OPTION_GLOBALIZE_SYMBOLS:
5932 use_globalize = true;
5933 add_specific_symbols (optarg, globalize_specific_htab,
5934 &globalize_specific_buffer);
5935 break;
5937 case OPTION_KEEPGLOBAL_SYMBOLS:
5938 use_keep_global = true;
5939 add_specific_symbols (optarg, keepglobal_specific_htab,
5940 &keepglobal_specific_buffer);
5941 break;
5943 case OPTION_WEAKEN_SYMBOLS:
5944 add_specific_symbols (optarg, weaken_specific_htab,
5945 &weaken_specific_buffer);
5946 break;
5948 case OPTION_ALT_MACH_CODE:
5949 use_alt_mach_code = strtoul (optarg, NULL, 0);
5950 if (use_alt_mach_code == 0)
5951 fatal (_("unable to parse alternative machine code"));
5952 break;
5954 case OPTION_PREFIX_SYMBOLS:
5955 prefix_symbols_string = optarg;
5956 break;
5958 case OPTION_PREFIX_SECTIONS:
5959 prefix_sections_string = optarg;
5960 break;
5962 case OPTION_PREFIX_ALLOC_SECTIONS:
5963 prefix_alloc_sections_string = optarg;
5964 break;
5966 case OPTION_READONLY_TEXT:
5967 bfd_flags_to_set |= WP_TEXT;
5968 bfd_flags_to_clear &= ~WP_TEXT;
5969 break;
5971 case OPTION_WRITABLE_TEXT:
5972 bfd_flags_to_clear |= WP_TEXT;
5973 bfd_flags_to_set &= ~WP_TEXT;
5974 break;
5976 case OPTION_PURE:
5977 bfd_flags_to_set |= D_PAGED;
5978 bfd_flags_to_clear &= ~D_PAGED;
5979 break;
5981 case OPTION_IMPURE:
5982 bfd_flags_to_clear |= D_PAGED;
5983 bfd_flags_to_set &= ~D_PAGED;
5984 break;
5986 case OPTION_EXTRACT_DWO:
5987 strip_symbols = STRIP_NONDWO;
5988 break;
5990 case OPTION_EXTRACT_SYMBOL:
5991 extract_symbol = true;
5992 break;
5994 case OPTION_REVERSE_BYTES:
5996 int prev = reverse_bytes;
5998 reverse_bytes = atoi (optarg);
5999 if ((reverse_bytes <= 0) || ((reverse_bytes % 2) != 0))
6000 fatal (_("number of bytes to reverse must be positive and even"));
6002 if (prev && prev != reverse_bytes)
6003 non_fatal (_("Warning: ignoring previous --reverse-bytes value of %d"),
6004 prev);
6005 break;
6008 case OPTION_FILE_ALIGNMENT:
6009 pe_file_alignment = parse_vma (optarg, "--file-alignment");
6010 break;
6012 case OPTION_HEAP:
6014 char *end;
6015 pe_heap_reserve = strtoul (optarg, &end, 0);
6016 if (end == optarg
6017 || (*end != ',' && *end != '\0'))
6018 non_fatal (_("%s: invalid reserve value for --heap"),
6019 optarg);
6020 else if (*end != '\0')
6022 pe_heap_commit = strtoul (end + 1, &end, 0);
6023 if (*end != '\0')
6024 non_fatal (_("%s: invalid commit value for --heap"),
6025 optarg);
6028 break;
6030 case OPTION_IMAGE_BASE:
6031 pe_image_base = parse_vma (optarg, "--image-base");
6032 break;
6034 case OPTION_PE_SECTION_ALIGNMENT:
6035 pe_section_alignment = parse_vma (optarg,
6036 "--section-alignment");
6037 if (power_of_two (pe_section_alignment) == -1)
6039 non_fatal (_("--section-alignment argument is not a power of two: %s - ignoring"), optarg);
6040 pe_section_alignment = (bfd_vma) -1;
6042 break;
6044 case OPTION_SUBSYSTEM:
6045 set_pe_subsystem (optarg);
6046 break;
6048 case OPTION_STACK:
6050 char *end;
6051 pe_stack_reserve = strtoul (optarg, &end, 0);
6052 if (end == optarg
6053 || (*end != ',' && *end != '\0'))
6054 non_fatal (_("%s: invalid reserve value for --stack"),
6055 optarg);
6056 else if (*end != '\0')
6058 pe_stack_commit = strtoul (end + 1, &end, 0);
6059 if (*end != '\0')
6060 non_fatal (_("%s: invalid commit value for --stack"),
6061 optarg);
6064 break;
6066 case OPTION_VERILOG_DATA_WIDTH:
6067 VerilogDataWidth = parse_vma (optarg, "--verilog-data-width");
6068 switch (VerilogDataWidth)
6070 case 1:
6071 case 2:
6072 case 4:
6073 case 8:
6074 case 16: /* We do not support widths > 16 because the verilog
6075 data is handled internally in 16 byte wide packets. */
6076 break;
6077 default:
6078 fatal (_("error: verilog data width must be 1, 2, 4, 8 or 16"));
6080 break;
6082 case 0:
6083 /* We've been given a long option. */
6084 break;
6086 case 'H':
6087 case 'h':
6088 copy_usage (stdout, 0);
6090 default:
6091 copy_usage (stderr, 1);
6095 if (use_globalize && use_keep_global)
6096 fatal(_("--globalize-symbol(s) is incompatible with -G/--keep-global-symbol(s)"));
6098 if (formats_info)
6100 display_info ();
6101 return 0;
6104 if (show_version)
6105 print_version ("objcopy");
6107 if (interleave && copy_byte == -1)
6108 fatal (_("interleave start byte must be set with --byte"));
6110 if (copy_byte >= interleave)
6111 fatal (_("byte number must be less than interleave"));
6113 if (copy_width > interleave - copy_byte)
6114 fatal (_("interleave width must be less than or equal to interleave - byte`"));
6116 if (optind == argc || optind + 2 < argc)
6117 copy_usage (stderr, 1);
6119 input_filename = argv[optind];
6120 if (optind + 1 < argc)
6121 output_filename = argv[optind + 1];
6123 default_deterministic ();
6125 /* Default is to strip no symbols. */
6126 if (strip_symbols == STRIP_UNDEF && discard_locals == LOCALS_UNDEF)
6127 strip_symbols = STRIP_NONE;
6129 if (output_target == NULL)
6130 output_target = input_target;
6132 /* Convert input EFI target to PEI target. */
6133 if (input_target != NULL
6134 && startswith (input_target, "efi-"))
6136 if (convert_efi_target (&input_target) < 0)
6137 fatal (_("unknown input EFI target: %s"), input_target);
6140 /* Convert output EFI target to PEI target. */
6141 if (output_target != NULL
6142 && startswith (output_target, "efi-"))
6144 int subsys = convert_efi_target (&output_target);
6146 if (subsys < 0)
6147 fatal (_("unknown output EFI target: %s"), output_target);
6148 if (pe_subsystem == -1)
6149 pe_subsystem = subsys;
6150 if (pe_file_alignment == (bfd_vma) -1)
6151 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
6152 if (pe_section_alignment == (bfd_vma) -1)
6153 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
6156 /* If there is no destination file, or the source and destination files
6157 are the same, then create a temp and copy the result into the input. */
6158 copyfd = -1;
6159 if (output_filename == NULL
6160 || filename_cmp (input_filename, output_filename) == 0)
6162 tmpname = make_tempname (input_filename, &tmpfd);
6163 if (tmpfd >= 0)
6164 copyfd = dup (tmpfd);
6166 else
6167 tmpname = output_filename;
6169 if (tmpname == NULL)
6171 fatal (_("warning: could not create temporary file whilst copying '%s', (error: %s)"),
6172 input_filename, strerror (errno));
6175 copy_file (input_filename, tmpname, tmpfd, &statbuf, input_target,
6176 output_target, input_arch);
6177 if (status == 0)
6179 const char *oname = output_filename ? output_filename : input_filename;
6180 status = smart_rename (tmpname, oname, copyfd,
6181 &statbuf, preserve_dates) != 0;
6183 else
6185 if (copyfd >= 0)
6186 close (copyfd);
6187 unlink_if_ordinary (tmpname);
6190 if (tmpname != output_filename)
6191 free (tmpname);
6193 if (change_warn)
6195 struct section_list *p;
6197 for (p = change_sections; p != NULL; p = p->next)
6199 if (! p->used)
6201 if (p->context & (SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA))
6202 /* xgettext:c-format */
6203 non_fatal (_("%s %s%c0x%" PRIx64 " never used"),
6204 "--change-section-vma",
6205 p->pattern,
6206 p->context & SECTION_CONTEXT_SET_VMA ? '=' : '+',
6207 (uint64_t) p->vma_val);
6209 if (p->context & (SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA))
6210 /* xgettext:c-format */
6211 non_fatal (_("%s %s%c0x%" PRIx64 " never used"),
6212 "--change-section-lma",
6213 p->pattern,
6214 p->context & SECTION_CONTEXT_SET_LMA ? '=' : '+',
6215 (uint64_t) p->lma_val);
6220 free (strip_specific_buffer);
6221 free (strip_unneeded_buffer);
6222 free (keep_specific_buffer);
6223 free (localize_specific_buffer);
6224 free (globalize_specific_buffer);
6225 free (keepglobal_specific_buffer);
6226 free (weaken_specific_buffer);
6228 return 0;
6232 main (int argc, char *argv[])
6234 #ifdef HAVE_LC_MESSAGES
6235 setlocale (LC_MESSAGES, "");
6236 #endif
6237 setlocale (LC_CTYPE, "");
6238 bindtextdomain (PACKAGE, LOCALEDIR);
6239 textdomain (PACKAGE);
6241 program_name = argv[0];
6242 xmalloc_set_program_name (program_name);
6244 expandargv (&argc, &argv);
6246 strip_symbols = STRIP_UNDEF;
6247 discard_locals = LOCALS_UNDEF;
6249 if (bfd_init () != BFD_INIT_MAGIC)
6250 fatal (_("fatal error: libbfd ABI mismatch"));
6251 set_default_bfd_target ();
6253 if (is_strip < 0)
6255 int i = strlen (program_name);
6256 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
6257 /* Drop the .exe suffix, if any. */
6258 if (i > 4 && FILENAME_CMP (program_name + i - 4, ".exe") == 0)
6260 i -= 4;
6261 program_name[i] = '\0';
6263 #endif
6264 is_strip = (i >= 5 && FILENAME_CMP (program_name + i - 5, "strip") == 0);
6267 create_symbol_htabs ();
6268 xatexit (delete_symbol_htabs);
6270 if (argv != NULL)
6271 bfd_set_error_program_name (argv[0]);
6273 if (is_strip)
6274 strip_main (argc, argv);
6275 else
6276 copy_main (argc, argv);
6278 xexit (status);
6279 return status;