[gdb/testsuite] Fix reverse attribute in tuiterm
[binutils-gdb.git] / binutils / objcopy.c
blob49d54bff9b2d45c69e677a0447caf148b72dd337
1 /* objcopy.c -- copy object file from input to output, optionally massaging it.
2 Copyright (C) 1991-2023 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. */
101 typedef struct merged_note_section
103 asection * sec; /* The section that is being merged. */
104 bfd_byte * contents;/* New contents of the section. */
105 bfd_size_type size; /* New size of the section. */
106 struct merged_note_section * next; /* Link to next merged note section. */
107 } merged_note_section;
109 enum strip_action
111 STRIP_UNDEF,
112 STRIP_NONE, /* Don't strip. */
113 STRIP_DEBUG, /* Strip all debugger symbols. */
114 STRIP_UNNEEDED, /* Strip unnecessary symbols. */
115 STRIP_NONDEBUG, /* Strip everything but debug info. */
116 STRIP_DWO, /* Strip all DWO info. */
117 STRIP_NONDWO, /* Strip everything but DWO info. */
118 STRIP_ALL /* Strip all symbols. */
121 /* Which symbols to remove. */
122 static enum strip_action strip_symbols = STRIP_UNDEF;
124 enum locals_action
126 LOCALS_UNDEF,
127 LOCALS_START_L, /* Discard locals starting with L. */
128 LOCALS_ALL /* Discard all locals. */
131 /* Which local symbols to remove. Overrides STRIP_ALL. */
132 static enum locals_action discard_locals;
134 /* Structure used to hold lists of sections and actions to take. */
135 struct section_list
137 struct section_list *next; /* Next section to change. */
138 const char *pattern; /* Section name pattern. */
139 bool used; /* Whether this entry was used. */
141 unsigned int context; /* What to do with matching sections. */
142 /* Flag bits used in the context field.
143 COPY and REMOVE are mutually exlusive.
144 SET and ALTER are mutually exclusive. */
145 #define SECTION_CONTEXT_REMOVE (1 << 0) /* Remove this section. */
146 #define SECTION_CONTEXT_COPY (1 << 1) /* Copy this section, delete all non-copied section. */
147 #define SECTION_CONTEXT_KEEP (1 << 2) /* Keep this section. */
148 #define SECTION_CONTEXT_SET_VMA (1 << 3) /* Set the sections' VMA address. */
149 #define SECTION_CONTEXT_ALTER_VMA (1 << 4) /* Increment or decrement the section's VMA address. */
150 #define SECTION_CONTEXT_SET_LMA (1 << 5) /* Set the sections' LMA address. */
151 #define SECTION_CONTEXT_ALTER_LMA (1 << 6) /* Increment or decrement the section's LMA address. */
152 #define SECTION_CONTEXT_SET_FLAGS (1 << 7) /* Set the section's flags. */
153 #define SECTION_CONTEXT_REMOVE_RELOCS (1 << 8) /* Remove relocations for this section. */
154 #define SECTION_CONTEXT_SET_ALIGNMENT (1 << 9) /* Set alignment for section. */
156 bfd_vma vma_val; /* Amount to change by or set to. */
157 bfd_vma lma_val; /* Amount to change by or set to. */
158 flagword flags; /* What to set the section flags to. */
159 unsigned int alignment; /* Alignment of output section. */
162 static struct section_list *change_sections;
164 /* TRUE if some sections are to be removed. */
165 static bool sections_removed;
167 /* TRUE if only some sections are to be copied. */
168 static bool sections_copied;
170 /* Changes to the start address. */
171 static bfd_vma change_start = 0;
172 static bool set_start_set = false;
173 static bfd_vma set_start;
175 /* Changes to section addresses. */
176 static bfd_vma change_section_address = 0;
178 /* Filling gaps between sections. */
179 static bool gap_fill_set = false;
180 static bfd_byte gap_fill = 0;
182 /* Pad to a given address. */
183 static bool pad_to_set = false;
184 static bfd_vma pad_to;
186 /* Use alternative machine code? */
187 static unsigned long use_alt_mach_code = 0;
189 /* Output BFD flags user wants to set or clear */
190 static flagword bfd_flags_to_set;
191 static flagword bfd_flags_to_clear;
193 /* List of sections to add. */
194 struct section_add
196 /* Next section to add. */
197 struct section_add *next;
198 /* Name of section to add. */
199 const char *name;
200 /* Name of file holding section contents. */
201 const char *filename;
202 /* Size of file. */
203 size_t size;
204 /* Contents of file. */
205 bfd_byte *contents;
206 /* BFD section, after it has been added. */
207 asection *section;
210 /* List of sections to add to the output BFD. */
211 static struct section_add *add_sections;
213 /* List of sections to update in the output BFD. */
214 static struct section_add *update_sections;
216 /* List of sections to dump from the output BFD. */
217 static struct section_add *dump_sections;
219 /* If non-NULL the argument to --add-gnu-debuglink.
220 This should be the filename to store in the .gnu_debuglink section. */
221 static const char * gnu_debuglink_filename = NULL;
223 /* Whether to convert debugging information. */
224 static bool convert_debugging = false;
226 /* Whether to compress/decompress DWARF debug sections. */
227 static enum
229 nothing = 0,
230 compress = 1 << 0,
231 compress_zlib = compress | 1 << 1,
232 compress_gnu_zlib = compress | 1 << 2,
233 compress_gabi_zlib = compress | 1 << 3,
234 compress_zstd = compress | 1 << 4,
235 decompress = 1 << 5
236 } do_debug_sections = nothing;
238 /* Whether to generate ELF common symbols with the STT_COMMON type. */
239 static enum bfd_link_elf_stt_common do_elf_stt_common = unchanged;
241 /* Whether to change the leading character in symbol names. */
242 static bool change_leading_char = false;
244 /* Whether to remove the leading character from global symbol names. */
245 static bool remove_leading_char = false;
247 /* Whether to permit wildcard in symbol comparison. */
248 static bool wildcard = false;
250 /* True if --localize-hidden is in effect. */
251 static bool localize_hidden = false;
253 /* List of symbols to strip, keep, localize, keep-global, weaken,
254 or redefine. */
255 static htab_t strip_specific_htab = NULL;
256 static htab_t strip_unneeded_htab = NULL;
257 static htab_t keep_specific_htab = NULL;
258 static htab_t localize_specific_htab = NULL;
259 static htab_t globalize_specific_htab = NULL;
260 static htab_t keepglobal_specific_htab = NULL;
261 static htab_t weaken_specific_htab = NULL;
262 static htab_t redefine_specific_htab = NULL;
263 static htab_t redefine_specific_reverse_htab = NULL;
264 static struct addsym_node *add_sym_list = NULL, **add_sym_tail = &add_sym_list;
265 static int add_symbols = 0;
267 static char *strip_specific_buffer = NULL;
268 static char *strip_unneeded_buffer = NULL;
269 static char *keep_specific_buffer = NULL;
270 static char *localize_specific_buffer = NULL;
271 static char *globalize_specific_buffer = NULL;
272 static char *keepglobal_specific_buffer = NULL;
273 static char *weaken_specific_buffer = NULL;
275 /* If this is TRUE, we weaken global symbols (set BSF_WEAK). */
276 static bool weaken = false;
278 /* If this is TRUE, we retain BSF_FILE symbols. */
279 static bool keep_file_symbols = false;
281 /* Prefix symbols/sections. */
282 static char *prefix_symbols_string = 0;
283 static char *prefix_sections_string = 0;
284 static char *prefix_alloc_sections_string = 0;
286 /* True if --extract-symbol was passed on the command line. */
287 static bool extract_symbol = false;
289 /* If `reverse_bytes' is nonzero, then reverse the order of every chunk
290 of <reverse_bytes> bytes within each output section. */
291 static int reverse_bytes = 0;
293 /* For Coff objects, we may want to allow or disallow long section names,
294 or preserve them where found in the inputs. Debug info relies on them. */
295 enum long_section_name_handling
297 DISABLE,
298 ENABLE,
299 KEEP
302 /* The default long section handling mode is to preserve them.
303 This is also the only behaviour for 'strip'. */
304 static enum long_section_name_handling long_section_names = KEEP;
306 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
307 enum command_line_switch
309 OPTION_ADD_SECTION=150,
310 OPTION_ADD_GNU_DEBUGLINK,
311 OPTION_ADD_SYMBOL,
312 OPTION_ALT_MACH_CODE,
313 OPTION_CHANGE_ADDRESSES,
314 OPTION_CHANGE_LEADING_CHAR,
315 OPTION_CHANGE_SECTION_ADDRESS,
316 OPTION_CHANGE_SECTION_LMA,
317 OPTION_CHANGE_SECTION_VMA,
318 OPTION_CHANGE_START,
319 OPTION_CHANGE_WARNINGS,
320 OPTION_COMPRESS_DEBUG_SECTIONS,
321 OPTION_DEBUGGING,
322 OPTION_DECOMPRESS_DEBUG_SECTIONS,
323 OPTION_DUMP_SECTION,
324 OPTION_ELF_STT_COMMON,
325 OPTION_EXTRACT_DWO,
326 OPTION_EXTRACT_SYMBOL,
327 OPTION_FILE_ALIGNMENT,
328 OPTION_FORMATS_INFO,
329 OPTION_GAP_FILL,
330 OPTION_GLOBALIZE_SYMBOL,
331 OPTION_GLOBALIZE_SYMBOLS,
332 OPTION_HEAP,
333 OPTION_IMAGE_BASE,
334 OPTION_IMPURE,
335 OPTION_INTERLEAVE_WIDTH,
336 OPTION_KEEPGLOBAL_SYMBOLS,
337 OPTION_KEEP_FILE_SYMBOLS,
338 OPTION_KEEP_SECTION,
339 OPTION_KEEP_SYMBOLS,
340 OPTION_KEEP_SECTION_SYMBOLS,
341 OPTION_LOCALIZE_HIDDEN,
342 OPTION_LOCALIZE_SYMBOLS,
343 OPTION_LONG_SECTION_NAMES,
344 OPTION_MERGE_NOTES,
345 OPTION_NO_MERGE_NOTES,
346 OPTION_NO_CHANGE_WARNINGS,
347 OPTION_ONLY_KEEP_DEBUG,
348 OPTION_PAD_TO,
349 OPTION_PREFIX_ALLOC_SECTIONS,
350 OPTION_PREFIX_SECTIONS,
351 OPTION_PREFIX_SYMBOLS,
352 OPTION_PURE,
353 OPTION_READONLY_TEXT,
354 OPTION_REDEFINE_SYM,
355 OPTION_REDEFINE_SYMS,
356 OPTION_REMOVE_LEADING_CHAR,
357 OPTION_REMOVE_RELOCS,
358 OPTION_RENAME_SECTION,
359 OPTION_REVERSE_BYTES,
360 OPTION_PE_SECTION_ALIGNMENT,
361 OPTION_SET_SECTION_FLAGS,
362 OPTION_SET_SECTION_ALIGNMENT,
363 OPTION_SET_START,
364 OPTION_SREC_FORCES3,
365 OPTION_SREC_LEN,
366 OPTION_STACK,
367 OPTION_STRIP_DWO,
368 OPTION_STRIP_SYMBOLS,
369 OPTION_STRIP_UNNEEDED,
370 OPTION_STRIP_UNNEEDED_SYMBOL,
371 OPTION_STRIP_UNNEEDED_SYMBOLS,
372 OPTION_SUBSYSTEM,
373 OPTION_UPDATE_SECTION,
374 OPTION_VERILOG_DATA_WIDTH,
375 OPTION_WEAKEN,
376 OPTION_WEAKEN_SYMBOLS,
377 OPTION_WRITABLE_TEXT
380 /* Options to handle if running as "strip". */
382 static struct option strip_options[] =
384 {"disable-deterministic-archives", no_argument, 0, 'U'},
385 {"discard-all", no_argument, 0, 'x'},
386 {"discard-locals", no_argument, 0, 'X'},
387 {"enable-deterministic-archives", no_argument, 0, 'D'},
388 {"format", required_argument, 0, 'F'}, /* Obsolete */
389 {"help", no_argument, 0, 'h'},
390 {"info", no_argument, 0, OPTION_FORMATS_INFO},
391 {"input-format", required_argument, 0, 'I'}, /* Obsolete */
392 {"input-target", required_argument, 0, 'I'},
393 {"keep-section-symbols", no_argument, 0, OPTION_KEEP_SECTION_SYMBOLS},
394 {"keep-file-symbols", no_argument, 0, OPTION_KEEP_FILE_SYMBOLS},
395 {"keep-section", required_argument, 0, OPTION_KEEP_SECTION},
396 {"keep-symbol", required_argument, 0, 'K'},
397 {"merge-notes", no_argument, 0, 'M'},
398 {"no-merge-notes", no_argument, 0, OPTION_NO_MERGE_NOTES},
399 {"only-keep-debug", no_argument, 0, OPTION_ONLY_KEEP_DEBUG},
400 {"output-file", required_argument, 0, 'o'},
401 {"output-format", required_argument, 0, 'O'}, /* Obsolete */
402 {"output-target", required_argument, 0, 'O'},
403 {"preserve-dates", no_argument, 0, 'p'},
404 {"remove-section", required_argument, 0, 'R'},
405 {"remove-relocations", required_argument, 0, OPTION_REMOVE_RELOCS},
406 {"strip-all", no_argument, 0, 's'},
407 {"strip-debug", no_argument, 0, 'S'},
408 {"strip-dwo", no_argument, 0, OPTION_STRIP_DWO},
409 {"strip-symbol", required_argument, 0, 'N'},
410 {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
411 {"target", required_argument, 0, 'F'},
412 {"verbose", no_argument, 0, 'v'},
413 {"version", no_argument, 0, 'V'},
414 {"wildcard", no_argument, 0, 'w'},
415 {0, no_argument, 0, 0}
418 /* Options to handle if running as "objcopy". */
420 static struct option copy_options[] =
422 {"add-gnu-debuglink", required_argument, 0, OPTION_ADD_GNU_DEBUGLINK},
423 {"add-section", required_argument, 0, OPTION_ADD_SECTION},
424 {"add-symbol", required_argument, 0, OPTION_ADD_SYMBOL},
425 {"adjust-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
426 {"adjust-start", required_argument, 0, OPTION_CHANGE_START},
427 {"adjust-vma", required_argument, 0, OPTION_CHANGE_ADDRESSES},
428 {"adjust-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
429 {"alt-machine-code", required_argument, 0, OPTION_ALT_MACH_CODE},
430 {"binary-architecture", required_argument, 0, 'B'},
431 {"byte", required_argument, 0, 'b'},
432 {"change-addresses", required_argument, 0, OPTION_CHANGE_ADDRESSES},
433 {"change-leading-char", no_argument, 0, OPTION_CHANGE_LEADING_CHAR},
434 {"change-section-address", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
435 {"change-section-lma", required_argument, 0, OPTION_CHANGE_SECTION_LMA},
436 {"change-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_VMA},
437 {"change-start", required_argument, 0, OPTION_CHANGE_START},
438 {"change-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
439 {"compress-debug-sections", optional_argument, 0, OPTION_COMPRESS_DEBUG_SECTIONS},
440 {"debugging", no_argument, 0, OPTION_DEBUGGING},
441 {"decompress-debug-sections", no_argument, 0, OPTION_DECOMPRESS_DEBUG_SECTIONS},
442 {"disable-deterministic-archives", no_argument, 0, 'U'},
443 {"discard-all", no_argument, 0, 'x'},
444 {"discard-locals", no_argument, 0, 'X'},
445 {"dump-section", required_argument, 0, OPTION_DUMP_SECTION},
446 {"elf-stt-common", required_argument, 0, OPTION_ELF_STT_COMMON},
447 {"enable-deterministic-archives", no_argument, 0, 'D'},
448 {"extract-dwo", no_argument, 0, OPTION_EXTRACT_DWO},
449 {"extract-symbol", no_argument, 0, OPTION_EXTRACT_SYMBOL},
450 {"file-alignment", required_argument, 0, OPTION_FILE_ALIGNMENT},
451 {"format", required_argument, 0, 'F'}, /* Obsolete */
452 {"gap-fill", required_argument, 0, OPTION_GAP_FILL},
453 {"globalize-symbol", required_argument, 0, OPTION_GLOBALIZE_SYMBOL},
454 {"globalize-symbols", required_argument, 0, OPTION_GLOBALIZE_SYMBOLS},
455 {"heap", required_argument, 0, OPTION_HEAP},
456 {"help", no_argument, 0, 'h'},
457 {"image-base", required_argument, 0 , OPTION_IMAGE_BASE},
458 {"impure", no_argument, 0, OPTION_IMPURE},
459 {"info", no_argument, 0, OPTION_FORMATS_INFO},
460 {"input-format", required_argument, 0, 'I'}, /* Obsolete */
461 {"input-target", required_argument, 0, 'I'},
462 {"interleave", optional_argument, 0, 'i'},
463 {"interleave-width", required_argument, 0, OPTION_INTERLEAVE_WIDTH},
464 {"keep-file-symbols", no_argument, 0, OPTION_KEEP_FILE_SYMBOLS},
465 {"keep-global-symbol", required_argument, 0, 'G'},
466 {"keep-global-symbols", required_argument, 0, OPTION_KEEPGLOBAL_SYMBOLS},
467 {"keep-section", required_argument, 0, OPTION_KEEP_SECTION},
468 {"keep-symbol", required_argument, 0, 'K'},
469 {"keep-symbols", required_argument, 0, OPTION_KEEP_SYMBOLS},
470 {"keep-section-symbols", required_argument, 0, OPTION_KEEP_SECTION_SYMBOLS},
471 {"localize-hidden", no_argument, 0, OPTION_LOCALIZE_HIDDEN},
472 {"localize-symbol", required_argument, 0, 'L'},
473 {"localize-symbols", required_argument, 0, OPTION_LOCALIZE_SYMBOLS},
474 {"long-section-names", required_argument, 0, OPTION_LONG_SECTION_NAMES},
475 {"merge-notes", no_argument, 0, 'M'},
476 {"no-merge-notes", no_argument, 0, OPTION_NO_MERGE_NOTES},
477 {"no-adjust-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
478 {"no-change-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
479 {"only-keep-debug", no_argument, 0, OPTION_ONLY_KEEP_DEBUG},
480 {"only-section", required_argument, 0, 'j'},
481 {"output-format", required_argument, 0, 'O'}, /* Obsolete */
482 {"output-target", required_argument, 0, 'O'},
483 {"pad-to", required_argument, 0, OPTION_PAD_TO},
484 {"prefix-alloc-sections", required_argument, 0, OPTION_PREFIX_ALLOC_SECTIONS},
485 {"prefix-sections", required_argument, 0, OPTION_PREFIX_SECTIONS},
486 {"prefix-symbols", required_argument, 0, OPTION_PREFIX_SYMBOLS},
487 {"preserve-dates", no_argument, 0, 'p'},
488 {"pure", no_argument, 0, OPTION_PURE},
489 {"readonly-text", no_argument, 0, OPTION_READONLY_TEXT},
490 {"redefine-sym", required_argument, 0, OPTION_REDEFINE_SYM},
491 {"redefine-syms", required_argument, 0, OPTION_REDEFINE_SYMS},
492 {"remove-leading-char", no_argument, 0, OPTION_REMOVE_LEADING_CHAR},
493 {"remove-section", required_argument, 0, 'R'},
494 {"remove-relocations", required_argument, 0, OPTION_REMOVE_RELOCS},
495 {"rename-section", required_argument, 0, OPTION_RENAME_SECTION},
496 {"reverse-bytes", required_argument, 0, OPTION_REVERSE_BYTES},
497 {"section-alignment", required_argument, 0, OPTION_PE_SECTION_ALIGNMENT},
498 {"set-section-flags", required_argument, 0, OPTION_SET_SECTION_FLAGS},
499 {"set-section-alignment", required_argument, 0, OPTION_SET_SECTION_ALIGNMENT},
500 {"set-start", required_argument, 0, OPTION_SET_START},
501 {"srec-forceS3", no_argument, 0, OPTION_SREC_FORCES3},
502 {"srec-len", required_argument, 0, OPTION_SREC_LEN},
503 {"stack", required_argument, 0, OPTION_STACK},
504 {"strip-all", no_argument, 0, 'S'},
505 {"strip-debug", no_argument, 0, 'g'},
506 {"strip-dwo", no_argument, 0, OPTION_STRIP_DWO},
507 {"strip-symbol", required_argument, 0, 'N'},
508 {"strip-symbols", required_argument, 0, OPTION_STRIP_SYMBOLS},
509 {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
510 {"strip-unneeded-symbol", required_argument, 0, OPTION_STRIP_UNNEEDED_SYMBOL},
511 {"strip-unneeded-symbols", required_argument, 0, OPTION_STRIP_UNNEEDED_SYMBOLS},
512 {"subsystem", required_argument, 0, OPTION_SUBSYSTEM},
513 {"target", required_argument, 0, 'F'},
514 {"update-section", required_argument, 0, OPTION_UPDATE_SECTION},
515 {"verbose", no_argument, 0, 'v'},
516 {"verilog-data-width", required_argument, 0, OPTION_VERILOG_DATA_WIDTH},
517 {"version", no_argument, 0, 'V'},
518 {"weaken", no_argument, 0, OPTION_WEAKEN},
519 {"weaken-symbol", required_argument, 0, 'W'},
520 {"weaken-symbols", required_argument, 0, OPTION_WEAKEN_SYMBOLS},
521 {"wildcard", no_argument, 0, 'w'},
522 {"writable-text", no_argument, 0, OPTION_WRITABLE_TEXT},
523 {0, no_argument, 0, 0}
526 /* IMPORTS */
527 extern char *program_name;
529 /* This flag distinguishes between strip and objcopy:
530 1 means this is 'strip'; 0 means this is 'objcopy'.
531 -1 means if we should use argv[0] to decide. */
532 extern int is_strip;
534 /* The maximum length of an S record. This variable is defined in srec.c
535 and can be modified by the --srec-len parameter. */
536 extern unsigned int _bfd_srec_len;
538 /* Restrict the generation of Srecords to type S3 only.
539 This variable is defined in bfd/srec.c and can be toggled
540 on by the --srec-forceS3 command line switch. */
541 extern bool _bfd_srec_forceS3;
543 /* Width of data in bytes for verilog output.
544 This variable is declared in bfd/verilog.c and can be modified by
545 the --verilog-data-width parameter. */
546 extern unsigned int VerilogDataWidth;
548 /* Endianness of data for verilog output.
549 This variable is declared in bfd/verilog.c and is set in the
550 copy_object() function. */
551 extern enum bfd_endian VerilogDataEndianness;
553 /* Forward declarations. */
554 static void setup_section (bfd *, asection *, void *);
555 static void setup_bfd_headers (bfd *, bfd *);
556 static void copy_relocations_in_section (bfd *, asection *, void *);
557 static void copy_section (bfd *, asection *, void *);
558 static void get_sections (bfd *, asection *, void *);
559 static int compare_section_lma (const void *, const void *);
560 static void mark_symbols_used_in_relocations (bfd *, asection *, void *);
561 static bool write_debugging_info (bfd *, void *, long *, asymbol ***);
562 static const char *lookup_sym_redefinition (const char *);
563 static const char *find_section_rename (const char *, flagword *);
565 ATTRIBUTE_NORETURN static void
566 copy_usage (FILE *stream, int exit_status)
568 fprintf (stream, _("Usage: %s [option(s)] in-file [out-file]\n"), program_name);
569 fprintf (stream, _(" Copies a binary file, possibly transforming it in the process\n"));
570 fprintf (stream, _(" The options are:\n"));
571 fprintf (stream, _("\
572 -I --input-target <bfdname> Assume input file is in format <bfdname>\n\
573 -O --output-target <bfdname> Create an output file in format <bfdname>\n\
574 -B --binary-architecture <arch> Set output arch, when input is arch-less\n\
575 -F --target <bfdname> Set both input and output format to <bfdname>\n\
576 --debugging Convert debugging information, if possible\n\
577 -p --preserve-dates Copy modified/access timestamps to the output\n"));
578 if (DEFAULT_AR_DETERMINISTIC)
579 fprintf (stream, _("\
580 -D --enable-deterministic-archives\n\
581 Produce deterministic output when stripping archives (default)\n\
582 -U --disable-deterministic-archives\n\
583 Disable -D behavior\n"));
584 else
585 fprintf (stream, _("\
586 -D --enable-deterministic-archives\n\
587 Produce deterministic output when stripping archives\n\
588 -U --disable-deterministic-archives\n\
589 Disable -D behavior (default)\n"));
590 fprintf (stream, _("\
591 -j --only-section <name> Only copy section <name> into the output\n\
592 --add-gnu-debuglink=<file> Add section .gnu_debuglink linking to <file>\n\
593 -R --remove-section <name> Remove section <name> from the output\n\
594 --remove-relocations <name> Remove relocations from section <name>\n\
595 -S --strip-all Remove all symbol and relocation information\n\
596 -g --strip-debug Remove all debugging symbols & sections\n\
597 --strip-dwo Remove all DWO sections\n\
598 --strip-unneeded Remove all symbols not needed by relocations\n\
599 -N --strip-symbol <name> Do not copy symbol <name>\n\
600 --strip-unneeded-symbol <name>\n\
601 Do not copy symbol <name> unless needed by\n\
602 relocations\n\
603 --only-keep-debug Strip everything but the debug information\n\
604 --extract-dwo Copy only DWO sections\n\
605 --extract-symbol Remove section contents but keep symbols\n\
606 --keep-section <name> Do not strip section <name>\n\
607 -K --keep-symbol <name> Do not strip symbol <name>\n\
608 --keep-section-symbols Do not strip section symbols\n\
609 --keep-file-symbols Do not strip file symbol(s)\n\
610 --localize-hidden Turn all ELF hidden symbols into locals\n\
611 -L --localize-symbol <name> Force symbol <name> to be marked as a local\n\
612 --globalize-symbol <name> Force symbol <name> to be marked as a global\n\
613 -G --keep-global-symbol <name> Localize all symbols except <name>\n\
614 -W --weaken-symbol <name> Force symbol <name> to be marked as a weak\n\
615 --weaken Force all global symbols to be marked as weak\n\
616 -w --wildcard Permit wildcard in symbol comparison\n\
617 -x --discard-all Remove all non-global symbols\n\
618 -X --discard-locals Remove any compiler-generated symbols\n\
619 -i --interleave[=<number>] Only copy N out of every <number> bytes\n\
620 --interleave-width <number> Set N for --interleave\n\
621 -b --byte <num> Select byte <num> in every interleaved block\n\
622 --gap-fill <val> Fill gaps between sections with <val>\n\
623 --pad-to <addr> Pad the last section up to address <addr>\n\
624 --set-start <addr> Set the start address to <addr>\n\
625 {--change-start|--adjust-start} <incr>\n\
626 Add <incr> to the start address\n\
627 {--change-addresses|--adjust-vma} <incr>\n\
628 Add <incr> to LMA, VMA and start addresses\n\
629 {--change-section-address|--adjust-section-vma} <name>{=|+|-}<val>\n\
630 Change LMA and VMA of section <name> by <val>\n\
631 --change-section-lma <name>{=|+|-}<val>\n\
632 Change the LMA of section <name> by <val>\n\
633 --change-section-vma <name>{=|+|-}<val>\n\
634 Change the VMA of section <name> by <val>\n\
635 {--[no-]change-warnings|--[no-]adjust-warnings}\n\
636 Warn if a named section does not exist\n\
637 --set-section-flags <name>=<flags>\n\
638 Set section <name>'s properties to <flags>\n\
639 --set-section-alignment <name>=<align>\n\
640 Set section <name>'s alignment to <align> bytes\n\
641 --add-section <name>=<file> Add section <name> found in <file> to output\n\
642 --update-section <name>=<file>\n\
643 Update contents of section <name> with\n\
644 contents found in <file>\n\
645 --dump-section <name>=<file> Dump the contents of section <name> into <file>\n\
646 --rename-section <old>=<new>[,<flags>] Rename section <old> to <new>\n\
647 --long-section-names {enable|disable|keep}\n\
648 Handle long section names in Coff objects.\n\
649 --change-leading-char Force output format's leading character style\n\
650 --remove-leading-char Remove leading character from global symbols\n\
651 --reverse-bytes=<num> Reverse <num> bytes at a time, in output sections with content\n\
652 --redefine-sym <old>=<new> Redefine symbol name <old> to <new>\n\
653 --redefine-syms <file> --redefine-sym for all symbol pairs \n\
654 listed in <file>\n\
655 --srec-len <number> Restrict the length of generated Srecords\n\
656 --srec-forceS3 Restrict the type of generated Srecords to S3\n\
657 --strip-symbols <file> -N for all symbols listed in <file>\n\
658 --strip-unneeded-symbols <file>\n\
659 --strip-unneeded-symbol for all symbols listed\n\
660 in <file>\n\
661 --keep-symbols <file> -K for all symbols listed in <file>\n\
662 --localize-symbols <file> -L for all symbols listed in <file>\n\
663 --globalize-symbols <file> --globalize-symbol for all in <file>\n\
664 --keep-global-symbols <file> -G for all symbols listed in <file>\n\
665 --weaken-symbols <file> -W for all symbols listed in <file>\n\
666 --add-symbol <name>=[<section>:]<value>[,<flags>] Add a symbol\n\
667 --alt-machine-code <index> Use the target's <index>'th alternative machine\n\
668 --writable-text Mark the output text as writable\n\
669 --readonly-text Make the output text write protected\n\
670 --pure Mark the output file as demand paged\n\
671 --impure Mark the output file as impure\n\
672 --prefix-symbols <prefix> Add <prefix> to start of every symbol name\n\
673 --prefix-sections <prefix> Add <prefix> to start of every section name\n\
674 --prefix-alloc-sections <prefix>\n\
675 Add <prefix> to start of every allocatable\n\
676 section name\n\
677 --file-alignment <num> Set PE file alignment to <num>\n\
678 --heap <reserve>[,<commit>] Set PE reserve/commit heap to <reserve>/\n\
679 <commit>\n\
680 --image-base <address> Set PE image base to <address>\n\
681 --section-alignment <num> Set PE section alignment to <num>\n\
682 --stack <reserve>[,<commit>] Set PE reserve/commit stack to <reserve>/\n\
683 <commit>\n\
684 --subsystem <name>[:<version>]\n\
685 Set PE subsystem to <name> [& <version>]\n\
686 --compress-debug-sections[={none|zlib|zlib-gnu|zlib-gabi|zstd}]\n\
687 Compress DWARF debug sections\n\
688 --decompress-debug-sections Decompress DWARF debug sections using zlib\n\
689 --elf-stt-common=[yes|no] Generate ELF common symbols with STT_COMMON\n\
690 type\n\
691 --verilog-data-width <number> Specifies data width, in bytes, for verilog output\n\
692 -M --merge-notes Remove redundant entries in note sections\n\
693 --no-merge-notes Do not attempt to remove redundant notes (default)\n\
694 -v --verbose List all object files modified\n\
695 @<file> Read options from <file>\n\
696 -V --version Display this program's version number\n\
697 -h --help Display this output\n\
698 --info List object formats & architectures supported\n\
699 "));
700 list_supported_targets (program_name, stream);
701 if (REPORT_BUGS_TO[0] && exit_status == 0)
702 fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
703 exit (exit_status);
706 ATTRIBUTE_NORETURN static void
707 strip_usage (FILE *stream, int exit_status)
709 fprintf (stream, _("Usage: %s <option(s)> in-file(s)\n"), program_name);
710 fprintf (stream, _(" Removes symbols and sections from files\n"));
711 fprintf (stream, _(" The options are:\n"));
712 fprintf (stream, _("\
713 -I --input-target=<bfdname> Assume input file is in format <bfdname>\n\
714 -O --output-target=<bfdname> Create an output file in format <bfdname>\n\
715 -F --target=<bfdname> Set both input and output format to <bfdname>\n\
716 -p --preserve-dates Copy modified/access timestamps to the output\n\
717 "));
718 if (DEFAULT_AR_DETERMINISTIC)
719 fprintf (stream, _("\
720 -D --enable-deterministic-archives\n\
721 Produce deterministic output when stripping archives (default)\n\
722 -U --disable-deterministic-archives\n\
723 Disable -D behavior\n"));
724 else
725 fprintf (stream, _("\
726 -D --enable-deterministic-archives\n\
727 Produce deterministic output when stripping archives\n\
728 -U --disable-deterministic-archives\n\
729 Disable -D behavior (default)\n"));
730 fprintf (stream, _("\
731 -R --remove-section=<name> Also remove section <name> from the output\n\
732 --remove-relocations <name> Remove relocations from section <name>\n\
733 -s --strip-all Remove all symbol and relocation information\n\
734 -g -S -d --strip-debug Remove all debugging symbols & sections\n\
735 --strip-dwo Remove all DWO sections\n\
736 --strip-unneeded Remove all symbols not needed by relocations\n\
737 --only-keep-debug Strip everything but the debug information\n\
738 -M --merge-notes Remove redundant entries in note sections (default)\n\
739 --no-merge-notes Do not attempt to remove redundant notes\n\
740 -N --strip-symbol=<name> Do not copy symbol <name>\n\
741 --keep-section=<name> Do not strip section <name>\n\
742 -K --keep-symbol=<name> Do not strip symbol <name>\n\
743 --keep-section-symbols Do not strip section symbols\n\
744 --keep-file-symbols Do not strip file symbol(s)\n\
745 -w --wildcard Permit wildcard in symbol comparison\n\
746 -x --discard-all Remove all non-global symbols\n\
747 -X --discard-locals Remove any compiler-generated symbols\n\
748 -v --verbose List all object files modified\n\
749 -V --version Display this program's version number\n\
750 -h --help Display this output\n\
751 --info List object formats & architectures supported\n\
752 -o <file> Place stripped output into <file>\n\
753 "));
755 list_supported_targets (program_name, stream);
756 if (REPORT_BUGS_TO[0] && exit_status == 0)
757 fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
758 exit (exit_status);
761 /* Parse section flags into a flagword, with a fatal error if the
762 string can't be parsed. */
764 static flagword
765 parse_flags (const char *s)
767 flagword ret;
768 const char *snext;
769 int len;
771 ret = SEC_NO_FLAGS;
775 snext = strchr (s, ',');
776 if (snext == NULL)
777 len = strlen (s);
778 else
780 len = snext - s;
781 ++snext;
784 if (0) ;
785 #define PARSE_FLAG(fname,fval) \
786 else if (strncasecmp (fname, s, len) == 0) ret |= fval
787 PARSE_FLAG ("alloc", SEC_ALLOC);
788 PARSE_FLAG ("load", SEC_LOAD);
789 PARSE_FLAG ("noload", SEC_NEVER_LOAD);
790 PARSE_FLAG ("readonly", SEC_READONLY);
791 PARSE_FLAG ("debug", SEC_DEBUGGING);
792 PARSE_FLAG ("code", SEC_CODE);
793 PARSE_FLAG ("data", SEC_DATA);
794 PARSE_FLAG ("rom", SEC_ROM);
795 PARSE_FLAG ("exclude", SEC_EXCLUDE);
796 PARSE_FLAG ("share", SEC_COFF_SHARED);
797 PARSE_FLAG ("contents", SEC_HAS_CONTENTS);
798 PARSE_FLAG ("merge", SEC_MERGE);
799 PARSE_FLAG ("strings", SEC_STRINGS);
800 #undef PARSE_FLAG
801 else
803 char *copy;
805 copy = (char *) xmalloc (len + 1);
806 strncpy (copy, s, len);
807 copy[len] = '\0';
808 non_fatal (_("unrecognized section flag `%s'"), copy);
809 fatal (_("supported flags: %s"),
810 "alloc, load, noload, readonly, debug, code, data, rom, exclude, share, contents, merge, strings");
813 s = snext;
815 while (s != NULL);
817 return ret;
820 /* Parse symbol flags into a flagword, with a fatal error if the
821 string can't be parsed. */
823 static flagword
824 parse_symflags (const char *s, const char **other)
826 flagword ret;
827 const char *snext;
828 size_t len;
830 ret = BSF_NO_FLAGS;
834 snext = strchr (s, ',');
835 if (snext == NULL)
836 len = strlen (s);
837 else
839 len = snext - s;
840 ++snext;
843 #define PARSE_FLAG(fname, fval) \
844 else if (len == sizeof fname - 1 \
845 && strncasecmp (fname, s, len) == 0) \
846 ret |= fval
848 #define PARSE_OTHER(fname, fval) \
849 else if (len >= sizeof fname \
850 && strncasecmp (fname, s, sizeof fname - 1) == 0) \
851 fval = xstrndup (s + sizeof fname - 1, len - sizeof fname + 1)
853 if (0) ;
854 PARSE_FLAG ("local", BSF_LOCAL);
855 PARSE_FLAG ("global", BSF_GLOBAL);
856 PARSE_FLAG ("export", BSF_EXPORT);
857 PARSE_FLAG ("debug", BSF_DEBUGGING);
858 PARSE_FLAG ("function", BSF_FUNCTION);
859 PARSE_FLAG ("weak", BSF_WEAK);
860 PARSE_FLAG ("section", BSF_SECTION_SYM);
861 PARSE_FLAG ("constructor", BSF_CONSTRUCTOR);
862 PARSE_FLAG ("warning", BSF_WARNING);
863 PARSE_FLAG ("indirect", BSF_INDIRECT);
864 PARSE_FLAG ("file", BSF_FILE);
865 PARSE_FLAG ("object", BSF_OBJECT);
866 PARSE_FLAG ("synthetic", BSF_SYNTHETIC);
867 PARSE_FLAG ("indirect-function", BSF_GNU_INDIRECT_FUNCTION | BSF_FUNCTION);
868 PARSE_FLAG ("unique-object", BSF_GNU_UNIQUE | BSF_OBJECT);
869 PARSE_OTHER ("before=", *other);
871 #undef PARSE_FLAG
872 #undef PARSE_OTHER
873 else
875 char *copy;
877 copy = (char *) xmalloc (len + 1);
878 strncpy (copy, s, len);
879 copy[len] = '\0';
880 non_fatal (_("unrecognized symbol flag `%s'"), copy);
881 fatal (_("supported flags: %s"),
882 "local, global, export, debug, function, weak, section, "
883 "constructor, warning, indirect, file, object, synthetic, "
884 "indirect-function, unique-object, before=<othersym>");
887 s = snext;
889 while (s != NULL);
891 return ret;
894 /* Find and optionally add an entry in the change_sections list.
896 We need to be careful in how we match section names because of the support
897 for wildcard characters. For example suppose that the user has invoked
898 objcopy like this:
900 --set-section-flags .debug_*=debug
901 --set-section-flags .debug_str=readonly,debug
902 --change-section-address .debug_*ranges=0x1000
904 With the idea that all debug sections will receive the DEBUG flag, the
905 .debug_str section will also receive the READONLY flag and the
906 .debug_ranges and .debug_aranges sections will have their address set to
907 0x1000. (This may not make much sense, but it is just an example).
909 When adding the section name patterns to the section list we need to make
910 sure that previous entries do not match with the new entry, unless the
911 match is exact. (In which case we assume that the user is overriding
912 the previous entry with the new context).
914 When matching real section names to the section list we make use of the
915 wildcard characters, but we must do so in context. Eg if we are setting
916 section addresses then we match for .debug_ranges but not for .debug_info.
918 Finally, if ADD is false and we do find a match, we mark the section list
919 entry as used. */
921 static struct section_list *
922 find_section_list (const char *name, bool add, unsigned int context)
924 struct section_list *p, *match = NULL;
926 /* assert ((context & ((1 << 7) - 1)) != 0); */
928 for (p = change_sections; p != NULL; p = p->next)
930 if (add)
932 if (strcmp (p->pattern, name) == 0)
934 /* Check for context conflicts. */
935 if (((p->context & SECTION_CONTEXT_REMOVE)
936 && (context & SECTION_CONTEXT_COPY))
937 || ((context & SECTION_CONTEXT_REMOVE)
938 && (p->context & SECTION_CONTEXT_COPY)))
939 fatal (_("error: %s both copied and removed"), name);
941 if (((p->context & SECTION_CONTEXT_SET_VMA)
942 && (context & SECTION_CONTEXT_ALTER_VMA))
943 || ((context & SECTION_CONTEXT_SET_VMA)
944 && (context & SECTION_CONTEXT_ALTER_VMA)))
945 fatal (_("error: %s both sets and alters VMA"), name);
947 if (((p->context & SECTION_CONTEXT_SET_LMA)
948 && (context & SECTION_CONTEXT_ALTER_LMA))
949 || ((context & SECTION_CONTEXT_SET_LMA)
950 && (context & SECTION_CONTEXT_ALTER_LMA)))
951 fatal (_("error: %s both sets and alters LMA"), name);
953 /* Extend the context. */
954 p->context |= context;
955 return p;
958 /* If we are not adding a new name/pattern then
959 only check for a match if the context applies. */
960 else if (p->context & context)
962 /* We could check for the presence of wildchar characters
963 first and choose between calling strcmp and fnmatch,
964 but is that really worth it ? */
965 if (p->pattern [0] == '!')
967 if (fnmatch (p->pattern + 1, name, 0) == 0)
969 p->used = true;
970 return NULL;
973 else
975 if (fnmatch (p->pattern, name, 0) == 0)
977 if (match == NULL)
978 match = p;
984 if (! add)
986 if (match != NULL)
987 match->used = true;
988 return match;
991 p = (struct section_list *) xmalloc (sizeof (struct section_list));
992 p->pattern = name;
993 p->used = false;
994 p->context = context;
995 p->vma_val = 0;
996 p->lma_val = 0;
997 p->flags = 0;
998 p->alignment = 0;
999 p->next = change_sections;
1000 change_sections = p;
1002 return p;
1005 /* S1 is the entry node already in the table, S2 is the key node. */
1007 static int
1008 eq_string_redefnode (const void *s1, const void *s2)
1010 struct redefine_node *node1 = (struct redefine_node *) s1;
1011 struct redefine_node *node2 = (struct redefine_node *) s2;
1012 return !strcmp ((const char *) node1->source, (const char *) node2->source);
1015 /* P is redefine node. Hash value is generated from its "source" filed. */
1017 static hashval_t
1018 htab_hash_redefnode (const void *p)
1020 struct redefine_node *redefnode = (struct redefine_node *) p;
1021 return htab_hash_string (redefnode->source);
1024 /* Create hashtab used for redefine node. */
1026 static htab_t
1027 create_symbol2redef_htab (void)
1029 return htab_create_alloc (16, htab_hash_redefnode, eq_string_redefnode, NULL,
1030 xcalloc, free);
1033 static htab_t
1034 create_symbol_htab (void)
1036 return htab_create_alloc (16, htab_hash_string, htab_eq_string, NULL,
1037 xcalloc, free);
1040 static void
1041 create_symbol_htabs (void)
1043 strip_specific_htab = create_symbol_htab ();
1044 strip_unneeded_htab = create_symbol_htab ();
1045 keep_specific_htab = create_symbol_htab ();
1046 localize_specific_htab = create_symbol_htab ();
1047 globalize_specific_htab = create_symbol_htab ();
1048 keepglobal_specific_htab = create_symbol_htab ();
1049 weaken_specific_htab = create_symbol_htab ();
1050 redefine_specific_htab = create_symbol2redef_htab ();
1051 /* As there is no bidirectional hash table in libiberty, need a reverse table
1052 to check duplicated target string. */
1053 redefine_specific_reverse_htab = create_symbol_htab ();
1056 static void
1057 delete_symbol_htabs (void)
1059 htab_delete (strip_specific_htab);
1060 htab_delete (strip_unneeded_htab);
1061 htab_delete (keep_specific_htab);
1062 htab_delete (localize_specific_htab);
1063 htab_delete (globalize_specific_htab);
1064 htab_delete (keepglobal_specific_htab);
1065 htab_delete (weaken_specific_htab);
1066 htab_delete (redefine_specific_htab);
1067 htab_delete (redefine_specific_reverse_htab);
1069 free (isympp);
1070 if (osympp != isympp)
1071 free (osympp);
1074 /* Add a symbol to strip_specific_list. */
1076 static void
1077 add_specific_symbol (const char *name, htab_t htab)
1079 *htab_find_slot (htab, name, INSERT) = (char *) name;
1082 /* Like add_specific_symbol, but the element type is void *. */
1084 static void
1085 add_specific_symbol_node (const void *node, htab_t htab)
1087 *htab_find_slot (htab, node, INSERT) = (void *) node;
1090 /* Add symbols listed in `filename' to strip_specific_list. */
1092 #define IS_WHITESPACE(c) ((c) == ' ' || (c) == '\t')
1093 #define IS_LINE_TERMINATOR(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
1095 static void
1096 add_specific_symbols (const char *filename, htab_t htab, char **buffer_p)
1098 off_t size;
1099 FILE * f;
1100 char * line;
1101 char * buffer;
1102 unsigned int line_count;
1104 size = get_file_size (filename);
1105 if (size == 0)
1107 status = 1;
1108 return;
1111 buffer = (char *) xmalloc (size + 2);
1112 f = fopen (filename, FOPEN_RT);
1113 if (f == NULL)
1114 fatal (_("cannot open '%s': %s"), filename, strerror (errno));
1116 if (fread (buffer, 1, size, f) == 0 || ferror (f))
1117 fatal (_("%s: fread failed"), filename);
1119 fclose (f);
1120 buffer [size] = '\n';
1121 buffer [size + 1] = '\0';
1123 line_count = 1;
1125 for (line = buffer; * line != '\0'; line ++)
1127 char * eol;
1128 char * name;
1129 char * name_end;
1130 int finished = false;
1132 for (eol = line;; eol ++)
1134 switch (* eol)
1136 case '\n':
1137 * eol = '\0';
1138 /* Cope with \n\r. */
1139 if (eol[1] == '\r')
1140 ++ eol;
1141 finished = true;
1142 break;
1144 case '\r':
1145 * eol = '\0';
1146 /* Cope with \r\n. */
1147 if (eol[1] == '\n')
1148 ++ eol;
1149 finished = true;
1150 break;
1152 case 0:
1153 finished = true;
1154 break;
1156 case '#':
1157 /* Line comment, Terminate the line here, in case a
1158 name is present and then allow the rest of the
1159 loop to find the real end of the line. */
1160 * eol = '\0';
1161 break;
1163 default:
1164 break;
1167 if (finished)
1168 break;
1171 /* A name may now exist somewhere between 'line' and 'eol'.
1172 Strip off leading whitespace and trailing whitespace,
1173 then add it to the list. */
1174 for (name = line; IS_WHITESPACE (* name); name ++)
1176 for (name_end = name;
1177 (! IS_WHITESPACE (* name_end))
1178 && (! IS_LINE_TERMINATOR (* name_end));
1179 name_end ++)
1182 if (! IS_LINE_TERMINATOR (* name_end))
1184 char * extra;
1186 for (extra = name_end + 1; IS_WHITESPACE (* extra); extra ++)
1189 if (! IS_LINE_TERMINATOR (* extra))
1190 non_fatal (_("%s:%d: Ignoring rubbish found on this line"),
1191 filename, line_count);
1194 * name_end = '\0';
1196 if (name_end > name)
1197 add_specific_symbol (name, htab);
1199 /* Advance line pointer to end of line. The 'eol ++' in the for
1200 loop above will then advance us to the start of the next line. */
1201 line = eol;
1202 line_count ++;
1205 /* Do not free the buffer. Parts of it will have been referenced
1206 in the calls to add_specific_symbol. */
1207 *buffer_p = buffer;
1210 /* See whether a symbol should be stripped or kept
1211 based on strip_specific_list and keep_symbols. */
1213 static int
1214 is_specified_symbol_predicate (void **slot, void *data)
1216 struct is_specified_symbol_predicate_data *d =
1217 (struct is_specified_symbol_predicate_data *) data;
1218 const char *slot_name = (char *) *slot;
1220 if (*slot_name != '!')
1222 if (! fnmatch (slot_name, d->name, 0))
1224 d->found = true;
1225 /* Continue traversal, there might be a non-match rule. */
1226 return 1;
1229 else
1231 if (! fnmatch (slot_name + 1, d->name, 0))
1233 d->found = false;
1234 /* Stop traversal. */
1235 return 0;
1239 /* Continue traversal. */
1240 return 1;
1243 static bool
1244 is_specified_symbol (const char *name, htab_t htab)
1246 if (wildcard)
1248 struct is_specified_symbol_predicate_data data;
1250 data.name = name;
1251 data.found = false;
1253 htab_traverse (htab, is_specified_symbol_predicate, &data);
1255 return data.found;
1258 return htab_find (htab, name) != NULL;
1261 /* Return a pointer to the symbol used as a signature for GROUP. */
1263 static asymbol *
1264 group_signature (asection *group)
1266 bfd *abfd = group->owner;
1267 Elf_Internal_Shdr *ghdr;
1269 /* PR 20089: An earlier error may have prevented us from loading the symbol table. */
1270 if (isympp == NULL)
1271 return NULL;
1273 if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
1274 return NULL;
1276 ghdr = &elf_section_data (group)->this_hdr;
1277 if (ghdr->sh_link == elf_onesymtab (abfd))
1279 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1280 Elf_Internal_Shdr *symhdr = &elf_symtab_hdr (abfd);
1282 if (ghdr->sh_info > 0
1283 && ghdr->sh_info < symhdr->sh_size / bed->s->sizeof_sym)
1284 return isympp[ghdr->sh_info - 1];
1286 return NULL;
1289 /* Return TRUE if the section is a DWO section. */
1291 static bool
1292 is_dwo_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1294 const char *name;
1295 int len;
1297 if (sec == NULL || (name = bfd_section_name (sec)) == NULL)
1298 return false;
1300 len = strlen (name);
1301 if (len < 5)
1302 return false;
1304 return startswith (name + len - 4, ".dwo");
1307 /* Return TRUE if section SEC is in the update list. */
1309 static bool
1310 is_update_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1312 if (update_sections != NULL)
1314 struct section_add *pupdate;
1316 for (pupdate = update_sections;
1317 pupdate != NULL;
1318 pupdate = pupdate->next)
1320 if (strcmp (sec->name, pupdate->name) == 0)
1321 return true;
1325 return false;
1328 static bool
1329 is_mergeable_note_section (bfd * abfd, asection * sec)
1331 if (merge_notes
1332 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
1333 && elf_section_data (sec)->this_hdr.sh_type == SHT_NOTE
1334 /* FIXME: We currently only support merging GNU_BUILD_NOTEs.
1335 We should add support for more note types. */
1336 && (startswith (sec->name, GNU_BUILD_ATTRS_SECTION_NAME)))
1337 return true;
1339 return false;
1342 /* See if a non-group section is being removed. */
1344 static bool
1345 is_strip_section_1 (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1347 if (find_section_list (bfd_section_name (sec), false, SECTION_CONTEXT_KEEP)
1348 != NULL)
1349 return false;
1351 if (sections_removed || sections_copied)
1353 struct section_list *p;
1354 struct section_list *q;
1356 p = find_section_list (bfd_section_name (sec), false,
1357 SECTION_CONTEXT_REMOVE);
1358 q = find_section_list (bfd_section_name (sec), false,
1359 SECTION_CONTEXT_COPY);
1361 if (p && q)
1362 fatal (_("error: section %s matches both remove and copy options"),
1363 bfd_section_name (sec));
1364 if (p && is_update_section (abfd, sec))
1365 fatal (_("error: section %s matches both update and remove options"),
1366 bfd_section_name (sec));
1368 if (p != NULL)
1369 return true;
1370 if (sections_copied && q == NULL)
1371 return true;
1374 if ((bfd_section_flags (sec) & SEC_DEBUGGING) != 0)
1376 if (strip_symbols == STRIP_DEBUG
1377 || strip_symbols == STRIP_UNNEEDED
1378 || strip_symbols == STRIP_ALL
1379 || discard_locals == LOCALS_ALL
1380 || convert_debugging)
1382 /* By default we don't want to strip .reloc section.
1383 This section has for pe-coff special meaning. See
1384 pe-dll.c file in ld, and peXXigen.c in bfd for details.
1385 Similarly we do not want to strip debuglink sections. */
1386 const char * kept_sections[] =
1388 ".reloc",
1389 ".gnu_debuglink",
1390 ".gnu_debugaltlink"
1392 int i;
1394 for (i = ARRAY_SIZE (kept_sections);i--;)
1395 if (strcmp (bfd_section_name (sec), kept_sections[i]) == 0)
1396 break;
1397 if (i == -1)
1398 return true;
1401 if (strip_symbols == STRIP_DWO)
1402 return is_dwo_section (abfd, sec);
1404 if (strip_symbols == STRIP_NONDEBUG)
1405 return false;
1408 if (strip_symbols == STRIP_NONDWO)
1409 return !is_dwo_section (abfd, sec);
1411 return false;
1414 /* See if a section is being removed. */
1416 static bool
1417 is_strip_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
1419 if (is_strip_section_1 (abfd, sec))
1420 return true;
1422 if ((bfd_section_flags (sec) & SEC_GROUP) != 0)
1424 asymbol *gsym;
1425 const char *gname;
1426 asection *elt, *first;
1428 gsym = group_signature (sec);
1429 /* Strip groups without a valid signature. */
1430 if (gsym == NULL)
1431 return true;
1433 /* PR binutils/3181
1434 If we are going to strip the group signature symbol, then
1435 strip the group section too. */
1436 gname = gsym->name;
1437 if ((strip_symbols == STRIP_ALL
1438 && !is_specified_symbol (gname, keep_specific_htab))
1439 || is_specified_symbol (gname, strip_specific_htab))
1440 return true;
1442 /* Remove the group section if all members are removed. */
1443 first = elt = elf_next_in_group (sec);
1444 while (elt != NULL)
1446 if (!is_strip_section_1 (abfd, elt))
1447 return false;
1448 elt = elf_next_in_group (elt);
1449 if (elt == first)
1450 break;
1453 return true;
1456 return false;
1459 static bool
1460 is_nondebug_keep_contents_section (bfd *ibfd, asection *isection)
1462 /* Always keep ELF note sections. */
1463 if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour)
1464 return elf_section_type (isection) == SHT_NOTE;
1466 /* Always keep the .buildid section for PE/COFF.
1468 Strictly, this should be written "always keep the section storing the debug
1469 directory", but that may be the .text section for objects produced by some
1470 tools, which it is not sensible to keep. */
1471 if (bfd_get_flavour (ibfd) == bfd_target_coff_flavour)
1472 return strcmp (bfd_section_name (isection), ".buildid") == 0;
1474 return false;
1477 /* Return true if SYM is a hidden symbol. */
1479 static bool
1480 is_hidden_symbol (asymbol *sym)
1482 elf_symbol_type *elf_sym;
1484 elf_sym = elf_symbol_from (sym);
1485 if (elf_sym != NULL)
1486 switch (ELF_ST_VISIBILITY (elf_sym->internal_elf_sym.st_other))
1488 case STV_HIDDEN:
1489 case STV_INTERNAL:
1490 return true;
1492 return false;
1495 /* Empty name is hopefully never a valid symbol name. */
1496 static const char * empty_name = "";
1498 static bool
1499 need_sym_before (struct addsym_node **node, const char *sym)
1501 int count;
1502 struct addsym_node *ptr = add_sym_list;
1504 /* 'othersym' symbols are at the front of the list. */
1505 for (count = 0; count < add_symbols; count++)
1507 if (!ptr->othersym)
1508 break;
1509 if (ptr->othersym == empty_name)
1510 continue;
1511 else if (strcmp (ptr->othersym, sym) == 0)
1513 free ((char *) ptr->othersym);
1514 ptr->othersym = empty_name;
1515 *node = ptr;
1516 return true;
1518 ptr = ptr->next;
1520 return false;
1523 static asymbol *
1524 create_new_symbol (struct addsym_node *ptr, bfd *obfd)
1526 asymbol *sym = bfd_make_empty_symbol (obfd);
1528 bfd_set_asymbol_name (sym, ptr->symdef);
1529 sym->value = ptr->symval;
1530 sym->flags = ptr->flags;
1531 if (ptr->section)
1533 asection *sec = bfd_get_section_by_name (obfd, ptr->section);
1534 if (!sec)
1535 fatal (_("Section %s not found"), ptr->section);
1536 sym->section = sec;
1538 else
1539 sym->section = bfd_abs_section_ptr;
1540 return sym;
1543 /* Choose which symbol entries to copy; put the result in OSYMS.
1544 We don't copy in place, because that confuses the relocs.
1545 Return the number of symbols to print. */
1547 static unsigned int
1548 filter_symbols (bfd *abfd, bfd *obfd, asymbol **osyms,
1549 asymbol **isyms, long symcount)
1551 asymbol **from = isyms, **to = osyms;
1552 long src_count = 0, dst_count = 0;
1553 int relocatable = (abfd->flags & (EXEC_P | DYNAMIC)) == 0;
1555 for (; src_count < symcount; src_count++)
1557 asymbol *sym = from[src_count];
1558 flagword flags = sym->flags;
1559 char *name = (char *) bfd_asymbol_name (sym);
1560 bool keep;
1561 bool used_in_reloc = false;
1562 bool undefined;
1563 bool rem_leading_char;
1564 bool add_leading_char;
1566 undefined = bfd_is_und_section (bfd_asymbol_section (sym));
1568 if (add_sym_list)
1570 struct addsym_node *ptr;
1572 if (need_sym_before (&ptr, name))
1573 to[dst_count++] = create_new_symbol (ptr, obfd);
1576 if (htab_elements (redefine_specific_htab) || section_rename_list)
1578 char *new_name;
1580 if (name != NULL
1581 && name[0] == '_'
1582 && name[1] == '_'
1583 && strcmp (name + (name[2] == '_'), "__gnu_lto_slim") == 0)
1585 fatal (_("redefining symbols does not work on LTO-compiled object files"));
1588 new_name = (char *) lookup_sym_redefinition (name);
1589 if (new_name == name
1590 && (flags & BSF_SECTION_SYM) != 0)
1591 new_name = (char *) find_section_rename (name, NULL);
1592 bfd_set_asymbol_name (sym, new_name);
1593 name = new_name;
1596 /* Check if we will remove the current leading character. */
1597 rem_leading_char =
1598 (name[0] != '\0'
1599 && name[0] == bfd_get_symbol_leading_char (abfd)
1600 && (change_leading_char
1601 || (remove_leading_char
1602 && ((flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1603 || undefined
1604 || bfd_is_com_section (bfd_asymbol_section (sym))))));
1606 /* Check if we will add a new leading character. */
1607 add_leading_char =
1608 change_leading_char
1609 && (bfd_get_symbol_leading_char (obfd) != '\0')
1610 && (bfd_get_symbol_leading_char (abfd) == '\0'
1611 || (name[0] == bfd_get_symbol_leading_char (abfd)));
1613 /* Short circuit for change_leading_char if we can do it in-place. */
1614 if (rem_leading_char && add_leading_char && !prefix_symbols_string)
1616 name[0] = bfd_get_symbol_leading_char (obfd);
1617 bfd_set_asymbol_name (sym, name);
1618 rem_leading_char = false;
1619 add_leading_char = false;
1622 /* Remove leading char. */
1623 if (rem_leading_char)
1624 bfd_set_asymbol_name (sym, ++name);
1626 /* Add new leading char and/or prefix. */
1627 if (add_leading_char || prefix_symbols_string)
1629 char *n, *ptr;
1630 size_t len = strlen (name) + 1;
1632 if (add_leading_char)
1633 len++;
1634 if (prefix_symbols_string)
1635 len += strlen (prefix_symbols_string);
1637 ptr = n = (char *) xmalloc (len);
1638 if (add_leading_char)
1639 *ptr++ = bfd_get_symbol_leading_char (obfd);
1641 if (prefix_symbols_string)
1643 strcpy (ptr, prefix_symbols_string);
1644 ptr += strlen (prefix_symbols_string);
1647 strcpy (ptr, name);
1648 bfd_set_asymbol_name (sym, n);
1649 name = n;
1652 if (strip_symbols == STRIP_ALL)
1653 keep = false;
1654 else if ((flags & BSF_KEEP) != 0 /* Used in relocation. */
1655 || ((flags & BSF_SECTION_SYM) != 0
1656 && ((*bfd_asymbol_section (sym)->symbol_ptr_ptr)->flags
1657 & BSF_KEEP) != 0))
1659 keep = true;
1660 used_in_reloc = true;
1662 else if (relocatable /* Relocatable file. */
1663 && ((flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1664 || bfd_is_com_section (bfd_asymbol_section (sym))))
1665 keep = true;
1666 else if (bfd_decode_symclass (sym) == 'I')
1667 /* Global symbols in $idata sections need to be retained
1668 even if relocatable is FALSE. External users of the
1669 library containing the $idata section may reference these
1670 symbols. */
1671 keep = true;
1672 else if ((flags & BSF_GLOBAL) != 0 /* Global symbol. */
1673 || (flags & BSF_WEAK) != 0
1674 || undefined
1675 || bfd_is_com_section (bfd_asymbol_section (sym)))
1676 keep = strip_symbols != STRIP_UNNEEDED;
1677 else if ((flags & BSF_DEBUGGING) != 0) /* Debugging symbol. */
1678 keep = (strip_symbols != STRIP_DEBUG
1679 && strip_symbols != STRIP_UNNEEDED
1680 && ! convert_debugging);
1681 else if (bfd_coff_get_comdat_section (abfd, bfd_asymbol_section (sym)))
1682 /* COMDAT sections store special information in local
1683 symbols, so we cannot risk stripping any of them. */
1684 keep = true;
1685 else /* Local symbol. */
1686 keep = (strip_symbols != STRIP_UNNEEDED
1687 && (discard_locals != LOCALS_ALL
1688 && (discard_locals != LOCALS_START_L
1689 || ! bfd_is_local_label (abfd, sym))));
1691 if (keep && is_specified_symbol (name, strip_specific_htab))
1693 /* There are multiple ways to set 'keep' above, but if it
1694 was the relocatable symbol case, then that's an error. */
1695 if (used_in_reloc)
1697 non_fatal (_("not stripping symbol `%s' because it is named in a relocation"), name);
1698 status = 1;
1700 else
1701 keep = false;
1704 if (keep
1705 && !(flags & BSF_KEEP)
1706 && is_specified_symbol (name, strip_unneeded_htab))
1707 keep = false;
1709 if (!keep
1710 && ((keep_file_symbols && (flags & BSF_FILE))
1711 || is_specified_symbol (name, keep_specific_htab)))
1712 keep = true;
1714 if (keep && is_strip_section (abfd, bfd_asymbol_section (sym)))
1715 keep = false;
1717 if (keep)
1719 if (((flags & (BSF_GLOBAL | BSF_GNU_UNIQUE))
1720 || undefined)
1721 && (weaken || is_specified_symbol (name, weaken_specific_htab)))
1723 sym->flags &= ~ (BSF_GLOBAL | BSF_GNU_UNIQUE);
1724 sym->flags |= BSF_WEAK;
1727 if (!undefined
1728 && (flags & (BSF_GLOBAL | BSF_WEAK))
1729 && (is_specified_symbol (name, localize_specific_htab)
1730 || (htab_elements (keepglobal_specific_htab) != 0
1731 && ! is_specified_symbol (name, keepglobal_specific_htab))
1732 || (localize_hidden && is_hidden_symbol (sym))))
1734 sym->flags &= ~ (BSF_GLOBAL | BSF_WEAK);
1735 sym->flags |= BSF_LOCAL;
1738 if (!undefined
1739 && (flags & BSF_LOCAL)
1740 && is_specified_symbol (name, globalize_specific_htab))
1742 sym->flags &= ~ BSF_LOCAL;
1743 sym->flags |= BSF_GLOBAL;
1746 to[dst_count++] = sym;
1749 if (add_sym_list)
1751 struct addsym_node *ptr = add_sym_list;
1753 for (src_count = 0; src_count < add_symbols; src_count++)
1755 if (ptr->othersym)
1757 if (ptr->othersym != empty_name)
1758 fatal (_("'before=%s' not found"), ptr->othersym);
1760 else
1761 to[dst_count++] = create_new_symbol (ptr, obfd);
1763 ptr = ptr->next;
1767 to[dst_count] = NULL;
1769 return dst_count;
1772 /* Find the redefined name of symbol SOURCE. */
1774 static const char *
1775 lookup_sym_redefinition (const char *source)
1777 struct redefine_node key_node = {(char *) source, NULL};
1778 struct redefine_node *redef_node
1779 = (struct redefine_node *) htab_find (redefine_specific_htab, &key_node);
1781 return redef_node == NULL ? source : redef_node->target;
1784 /* Insert a node into symbol redefine hash tabel. */
1786 static void
1787 add_redefine_and_check (const char *cause, const char *source,
1788 const char *target)
1790 struct redefine_node *new_node
1791 = (struct redefine_node *) xmalloc (sizeof (struct redefine_node));
1793 new_node->source = strdup (source);
1794 new_node->target = strdup (target);
1796 if (htab_find (redefine_specific_htab, new_node) != HTAB_EMPTY_ENTRY)
1797 fatal (_("%s: Multiple redefinition of symbol \"%s\""),
1798 cause, source);
1800 if (htab_find (redefine_specific_reverse_htab, target) != HTAB_EMPTY_ENTRY)
1801 fatal (_("%s: Symbol \"%s\" is target of more than one redefinition"),
1802 cause, target);
1804 /* Insert the NEW_NODE into hash table for quick search. */
1805 add_specific_symbol_node (new_node, redefine_specific_htab);
1807 /* Insert the target string into the reverse hash table, this is needed for
1808 duplicated target string check. */
1809 add_specific_symbol (new_node->target, redefine_specific_reverse_htab);
1813 /* Handle the --redefine-syms option. Read lines containing "old new"
1814 from the file, and add them to the symbol redefine list. */
1816 static void
1817 add_redefine_syms_file (const char *filename)
1819 FILE *file;
1820 char *buf;
1821 size_t bufsize;
1822 size_t len;
1823 size_t outsym_off;
1824 int c, lineno;
1826 file = fopen (filename, "r");
1827 if (file == NULL)
1828 fatal (_("couldn't open symbol redefinition file %s (error: %s)"),
1829 filename, strerror (errno));
1831 bufsize = 100;
1832 buf = (char *) xmalloc (bufsize + 1 /* For the terminating NUL. */);
1834 lineno = 1;
1835 c = getc (file);
1836 len = 0;
1837 outsym_off = 0;
1838 while (c != EOF)
1840 /* Collect the input symbol name. */
1841 while (! IS_WHITESPACE (c) && ! IS_LINE_TERMINATOR (c) && c != EOF)
1843 if (c == '#')
1844 goto comment;
1845 buf[len++] = c;
1846 if (len >= bufsize)
1848 bufsize *= 2;
1849 buf = (char *) xrealloc (buf, bufsize + 1);
1851 c = getc (file);
1853 buf[len++] = '\0';
1854 if (c == EOF)
1855 break;
1857 /* Eat white space between the symbol names. */
1858 while (IS_WHITESPACE (c))
1859 c = getc (file);
1860 if (c == '#' || IS_LINE_TERMINATOR (c))
1861 goto comment;
1862 if (c == EOF)
1863 break;
1865 /* Collect the output symbol name. */
1866 outsym_off = len;
1867 while (! IS_WHITESPACE (c) && ! IS_LINE_TERMINATOR (c) && c != EOF)
1869 if (c == '#')
1870 goto comment;
1871 buf[len++] = c;
1872 if (len >= bufsize)
1874 bufsize *= 2;
1875 buf = (char *) xrealloc (buf, bufsize + 1);
1877 c = getc (file);
1879 buf[len++] = '\0';
1880 if (c == EOF)
1881 break;
1883 /* Eat white space at end of line. */
1884 while (! IS_LINE_TERMINATOR(c) && c != EOF && IS_WHITESPACE (c))
1885 c = getc (file);
1886 if (c == '#')
1887 goto comment;
1888 /* Handle \r\n. */
1889 if ((c == '\r' && (c = getc (file)) == '\n')
1890 || c == '\n' || c == EOF)
1892 end_of_line:
1893 /* Append the redefinition to the list. */
1894 if (buf[0] != '\0')
1895 add_redefine_and_check (filename, &buf[0], &buf[outsym_off]);
1897 lineno++;
1898 len = 0;
1899 outsym_off = 0;
1900 if (c == EOF)
1901 break;
1902 c = getc (file);
1903 continue;
1905 else
1906 fatal (_("%s:%d: garbage found at end of line"), filename, lineno);
1907 comment:
1908 if (len != 0 && (outsym_off == 0 || outsym_off == len))
1909 fatal (_("%s:%d: missing new symbol name"), filename, lineno);
1910 buf[len++] = '\0';
1912 /* Eat the rest of the line and finish it. */
1913 while (c != '\n' && c != EOF)
1914 c = getc (file);
1915 goto end_of_line;
1918 if (len != 0)
1919 fatal (_("%s:%d: premature end of file"), filename, lineno);
1921 free (buf);
1922 fclose (file);
1925 /* Copy unknown object file IBFD onto OBFD.
1926 Returns TRUE upon success, FALSE otherwise. */
1928 static bool
1929 copy_unknown_object (bfd *ibfd, bfd *obfd)
1931 char *cbuf;
1932 bfd_size_type tocopy;
1933 off_t size;
1934 struct stat buf;
1936 if (bfd_stat_arch_elt (ibfd, &buf) != 0)
1938 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1939 return false;
1942 size = buf.st_size;
1943 if (size < 0)
1945 non_fatal (_("stat returns negative size for `%s'"),
1946 bfd_get_archive_filename (ibfd));
1947 return false;
1950 if (bfd_seek (ibfd, (file_ptr) 0, SEEK_SET) != 0)
1952 bfd_nonfatal (bfd_get_archive_filename (ibfd));
1953 return false;
1956 if (verbose)
1957 printf (_("copy from `%s' [unknown] to `%s' [unknown]\n"),
1958 bfd_get_archive_filename (ibfd), bfd_get_filename (obfd));
1960 cbuf = (char *) xmalloc (BUFSIZE);
1961 while (size != 0)
1963 if (size > BUFSIZE)
1964 tocopy = BUFSIZE;
1965 else
1966 tocopy = size;
1968 if (bfd_bread (cbuf, tocopy, ibfd) != tocopy)
1970 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
1971 free (cbuf);
1972 return false;
1975 if (bfd_bwrite (cbuf, tocopy, obfd) != tocopy)
1977 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
1978 free (cbuf);
1979 return false;
1982 size -= tocopy;
1985 /* We should at least to be able to read it back when copying an
1986 unknown object in an archive. */
1987 chmod (bfd_get_filename (obfd), buf.st_mode | S_IRUSR);
1988 free (cbuf);
1989 return true;
1992 typedef struct objcopy_internal_note
1994 Elf_Internal_Note note;
1995 unsigned long padded_namesz;
1996 bfd_vma start;
1997 bfd_vma end;
1998 } objcopy_internal_note;
2000 #define DEBUG_MERGE 0
2002 #if DEBUG_MERGE
2003 #define merge_debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
2004 #else
2005 #define merge_debug(format, ...)
2006 #endif
2008 /* Returns TRUE iff PNOTE1 overlaps or adjoins PNOTE2. */
2010 static bool
2011 overlaps_or_adjoins (objcopy_internal_note * pnote1,
2012 objcopy_internal_note * pnote2)
2014 if (pnote1->end < pnote2->start)
2015 /* FIXME: Alignment of 16 bytes taken from x86_64 binaries.
2016 Really we should extract the alignment of the section
2017 covered by the notes. */
2018 return BFD_ALIGN (pnote1->end, 16) < pnote2->start;
2020 if (pnote2->end < pnote2->start)
2021 return BFD_ALIGN (pnote2->end, 16) < pnote1->start;
2023 if (pnote1->end < pnote2->end)
2024 return true;
2026 if (pnote2->end < pnote1->end)
2027 return true;
2029 return false;
2032 /* Returns TRUE iff NEEDLE is fully contained by HAYSTACK. */
2034 static bool
2035 contained_by (objcopy_internal_note * needle,
2036 objcopy_internal_note * haystack)
2038 return needle->start >= haystack->start && needle->end <= haystack->end;
2041 static inline bool
2042 is_open_note (objcopy_internal_note * pnote)
2044 return pnote->note.type == NT_GNU_BUILD_ATTRIBUTE_OPEN;
2047 static inline bool
2048 is_func_note (objcopy_internal_note * pnote)
2050 return pnote->note.type == NT_GNU_BUILD_ATTRIBUTE_FUNC;
2053 static inline bool
2054 is_deleted_note (objcopy_internal_note * pnote)
2056 return pnote->note.type == 0;
2059 static bool
2060 is_version_note (objcopy_internal_note * pnote)
2062 return (pnote->note.namesz > 4
2063 && pnote->note.namedata[0] == 'G'
2064 && pnote->note.namedata[1] == 'A'
2065 && pnote->note.namedata[2] == '$'
2066 && pnote->note.namedata[3] == GNU_BUILD_ATTRIBUTE_VERSION);
2069 static bool
2070 is_64bit (bfd * abfd)
2072 /* Should never happen, but let's be paranoid. */
2073 if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
2074 return false;
2076 return elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64;
2079 /* This sorting function is used to get the notes into an order
2080 that makes merging easy. */
2082 static int
2083 compare_gnu_build_notes (const void * data1, const void * data2)
2085 objcopy_internal_note * pnote1 = (objcopy_internal_note *) data1;
2086 objcopy_internal_note * pnote2 = (objcopy_internal_note *) data2;
2088 /* Sort notes based upon the attribute they record. */
2089 int cmp = memcmp (pnote1->note.namedata + 3,
2090 pnote2->note.namedata + 3,
2091 pnote1->note.namesz < pnote2->note.namesz ?
2092 pnote1->note.namesz - 3 : pnote2->note.namesz - 3);
2093 if (cmp)
2094 return cmp;
2096 if (pnote1->end < pnote2->start)
2097 return -1;
2098 if (pnote1->start > pnote2->end)
2099 return 1;
2101 /* Overlaps - we should merge the two ranges. */
2102 if (pnote1->start < pnote2->start)
2103 return -1;
2104 if (pnote1->end > pnote2->end)
2105 return 1;
2106 if (pnote1->end < pnote2->end)
2107 return -1;
2109 /* Put OPEN notes before function notes. */
2110 if (is_open_note (pnote1) && ! is_open_note (pnote2))
2111 return -1;
2112 if (! is_open_note (pnote1) && is_open_note (pnote2))
2113 return 1;
2115 return 0;
2118 /* This sorting function is used to get the notes into an order
2119 that makes eliminating address ranges easier. */
2121 static int
2122 sort_gnu_build_notes (const void * data1, const void * data2)
2124 objcopy_internal_note * pnote1 = (objcopy_internal_note *) data1;
2125 objcopy_internal_note * pnote2 = (objcopy_internal_note *) data2;
2127 if (pnote1->note.type != pnote2->note.type)
2129 /* Move deleted notes to the end. */
2130 if (is_deleted_note (pnote1)) /* 1: OFD 2: OFD */
2131 return 1;
2133 /* Move OPEN notes to the start. */
2134 if (is_open_note (pnote1)) /* 1: OF 2: OFD */
2135 return -1;
2137 if (is_deleted_note (pnote2)) /* 1: F 2: O D */
2138 return -1;
2140 return 1; /* 1: F 2: O */
2143 /* Sort by starting address. */
2144 if (pnote1->start < pnote2->start)
2145 return -1;
2146 if (pnote1->start > pnote2->start)
2147 return 1;
2149 /* Then by end address (bigger range first). */
2150 if (pnote1->end > pnote2->end)
2151 return -1;
2152 if (pnote1->end < pnote2->end)
2153 return 1;
2155 /* Then by attribute type. */
2156 if (pnote1->note.namesz > 4
2157 && pnote2->note.namesz > 4
2158 && pnote1->note.namedata[3] != pnote2->note.namedata[3])
2159 return pnote1->note.namedata[3] - pnote2->note.namedata[3];
2161 return 0;
2164 /* Merge the notes on SEC, removing redundant entries.
2165 Returns the new, smaller size of the section upon success. */
2167 static bfd_size_type
2168 merge_gnu_build_notes (bfd * abfd,
2169 asection * sec,
2170 bfd_size_type size,
2171 bfd_byte * contents)
2173 objcopy_internal_note * pnotes_end;
2174 objcopy_internal_note * pnotes = NULL;
2175 objcopy_internal_note * pnote;
2176 bfd_size_type remain = size;
2177 unsigned version_1_seen = 0;
2178 unsigned version_2_seen = 0;
2179 unsigned version_3_seen = 0;
2180 const char * err = NULL;
2181 bfd_byte * in = contents;
2182 unsigned long previous_func_start = 0;
2183 unsigned long previous_open_start = 0;
2184 unsigned long previous_func_end = 0;
2185 unsigned long previous_open_end = 0;
2186 long relsize;
2188 relsize = bfd_get_reloc_upper_bound (abfd, sec);
2189 if (relsize > 0)
2191 arelent ** relpp;
2192 long relcount;
2194 /* If there are relocs associated with this section then we
2195 cannot safely merge it. */
2196 relpp = (arelent **) xmalloc (relsize);
2197 relcount = bfd_canonicalize_reloc (abfd, sec, relpp, isympp);
2198 free (relpp);
2199 if (relcount != 0)
2201 if (! is_strip)
2202 non_fatal (_("%s[%s]: Cannot merge - there are relocations against this section"),
2203 bfd_get_filename (abfd), bfd_section_name (sec));
2204 goto done;
2208 /* Make a copy of the notes and convert to our internal format.
2209 Minimum size of a note is 12 bytes. Also locate the version
2210 notes and check them. */
2211 pnote = pnotes = (objcopy_internal_note *)
2212 xcalloc ((size / 12), sizeof (* pnote));
2213 while (remain >= 12)
2215 bfd_vma start, end;
2217 pnote->note.namesz = bfd_get_32 (abfd, in);
2218 pnote->note.descsz = bfd_get_32 (abfd, in + 4);
2219 pnote->note.type = bfd_get_32 (abfd, in + 8);
2220 pnote->padded_namesz = (pnote->note.namesz + 3) & ~3;
2222 if (((pnote->note.descsz + 3) & ~3) != pnote->note.descsz)
2224 err = _("corrupt GNU build attribute note: description size not a factor of 4");
2225 goto done;
2228 if (pnote->note.type != NT_GNU_BUILD_ATTRIBUTE_OPEN
2229 && pnote->note.type != NT_GNU_BUILD_ATTRIBUTE_FUNC)
2231 err = _("corrupt GNU build attribute note: wrong note type");
2232 goto done;
2235 if (pnote->padded_namesz + pnote->note.descsz + 12 > remain)
2237 err = _("corrupt GNU build attribute note: note too big");
2238 goto done;
2241 if (pnote->note.namesz < 2)
2243 err = _("corrupt GNU build attribute note: name too small");
2244 goto done;
2247 pnote->note.namedata = (char *)(in + 12);
2248 pnote->note.descdata = (char *)(in + 12 + pnote->padded_namesz);
2250 remain -= 12 + pnote->padded_namesz + pnote->note.descsz;
2251 in += 12 + pnote->padded_namesz + pnote->note.descsz;
2253 if (pnote->note.namesz > 2
2254 && pnote->note.namedata[0] == '$'
2255 && pnote->note.namedata[1] == GNU_BUILD_ATTRIBUTE_VERSION
2256 && pnote->note.namedata[2] == '1')
2257 ++ version_1_seen;
2258 else if (is_version_note (pnote))
2260 if (pnote->note.namedata[4] == '2')
2261 ++ version_2_seen;
2262 else if (pnote->note.namedata[4] == '3')
2263 ++ version_3_seen;
2264 else
2266 err = _("corrupt GNU build attribute note: unsupported version");
2267 goto done;
2271 switch (pnote->note.descsz)
2273 case 0:
2274 start = end = 0;
2275 break;
2277 case 4:
2278 start = bfd_get_32 (abfd, pnote->note.descdata);
2279 /* FIXME: For version 1 and 2 notes we should try to
2280 calculate the end address by finding a symbol whose
2281 value is START, and then adding in its size.
2283 For now though, since v1 and v2 was not intended to
2284 handle gaps, we chose an artificially large end
2285 address. */
2286 end = (bfd_vma) -1;
2287 break;
2289 case 8:
2290 start = bfd_get_32 (abfd, pnote->note.descdata);
2291 end = bfd_get_32 (abfd, pnote->note.descdata + 4);
2292 break;
2294 case 16:
2295 start = bfd_get_64 (abfd, pnote->note.descdata);
2296 end = bfd_get_64 (abfd, pnote->note.descdata + 8);
2297 break;
2299 default:
2300 err = _("corrupt GNU build attribute note: bad description size");
2301 goto done;
2304 if (start > end)
2305 /* This can happen with PPC64LE binaries where empty notes are
2306 encoded as start = end + 4. */
2307 start = end;
2309 if (is_open_note (pnote))
2311 if (start)
2312 previous_open_start = start;
2314 pnote->start = previous_open_start;
2316 if (end)
2317 previous_open_end = end;
2319 pnote->end = previous_open_end;
2321 else
2323 if (start)
2324 previous_func_start = start;
2326 pnote->start = previous_func_start;
2328 if (end)
2329 previous_func_end = end;
2331 pnote->end = previous_func_end;
2334 if (pnote->note.namedata[pnote->note.namesz - 1] != 0)
2336 err = _("corrupt GNU build attribute note: name not NUL terminated");
2337 goto done;
2340 pnote ++;
2343 pnotes_end = pnote;
2345 /* Check that the notes are valid. */
2346 if (remain != 0)
2348 err = _("corrupt GNU build attribute notes: excess data at end");
2349 goto done;
2352 if (version_1_seen == 0 && version_2_seen == 0 && version_3_seen == 0)
2354 #if 0
2355 err = _("bad GNU build attribute notes: no known versions detected");
2356 goto done;
2357 #else
2358 /* This happens with glibc. No idea why. */
2359 non_fatal (_("%s[%s]: Warning: version note missing - assuming version 3"),
2360 bfd_get_filename (abfd), bfd_section_name (sec));
2361 version_3_seen = 2;
2362 #endif
2365 if ( (version_1_seen > 0 && version_2_seen > 0)
2366 || (version_1_seen > 0 && version_3_seen > 0)
2367 || (version_2_seen > 0 && version_3_seen > 0))
2369 err = _("bad GNU build attribute notes: multiple different versions");
2370 goto done;
2373 /* We are now only supporting the merging v3+ notes
2374 - it makes things much simpler. */
2375 if (version_3_seen == 0)
2377 merge_debug ("%s: skipping merge - not using v3 notes", bfd_section_name (sec));
2378 goto done;
2381 merge_debug ("Merging section %s which contains %ld notes\n",
2382 sec->name, pnotes_end - pnotes);
2384 /* Sort the notes. */
2385 qsort (pnotes, pnotes_end - pnotes, sizeof (* pnotes),
2386 compare_gnu_build_notes);
2388 #if DEBUG_MERGE
2389 merge_debug ("Results of initial sort:\n");
2390 for (pnote = pnotes; pnote < pnotes_end; pnote ++)
2391 merge_debug ("offset %#08lx range %#08lx..%#08lx type %ld attribute %d namesz %ld\n",
2392 (pnote->note.namedata - (char *) contents) - 12,
2393 pnote->start, pnote->end,
2394 pnote->note.type,
2395 pnote->note.namedata[3],
2396 pnote->note.namesz
2398 #endif
2400 /* Now merge the notes. The rules are:
2401 1. If a note has a zero range, it can be eliminated.
2402 2. If two notes have the same namedata then:
2403 2a. If one note's range is fully covered by the other note
2404 then it can be deleted.
2405 2b. If one note's range partially overlaps or adjoins the
2406 other note then if they are both of the same type (open
2407 or func) then they can be merged and one deleted. If
2408 they are of different types then they cannot be merged. */
2409 objcopy_internal_note * prev_note = NULL;
2411 for (pnote = pnotes; pnote < pnotes_end; pnote ++)
2413 /* Skip already deleted notes.
2414 FIXME: Can this happen ? We are scanning forwards and
2415 deleting backwards after all. */
2416 if (is_deleted_note (pnote))
2417 continue;
2419 /* Rule 1 - delete 0-range notes. */
2420 if (pnote->start == pnote->end)
2422 merge_debug ("Delete note at offset %#08lx - empty range\n",
2423 (pnote->note.namedata - (char *) contents) - 12);
2424 pnote->note.type = 0;
2425 continue;
2428 int iter;
2429 objcopy_internal_note * back;
2431 /* Rule 2: Check to see if there is an identical previous note. */
2432 for (iter = 0, back = prev_note ? prev_note : pnote - 1;
2433 back >= pnotes;
2434 back --)
2436 if (is_deleted_note (back))
2437 continue;
2439 /* Our sorting function should have placed all identically
2440 attributed notes together, so if we see a note of a different
2441 attribute type stop searching. */
2442 if (back->note.namesz != pnote->note.namesz
2443 || memcmp (back->note.namedata,
2444 pnote->note.namedata, pnote->note.namesz) != 0)
2445 break;
2447 if (back->start == pnote->start
2448 && back->end == pnote->end)
2450 merge_debug ("Delete note at offset %#08lx - duplicate of note at offset %#08lx\n",
2451 (pnote->note.namedata - (char *) contents) - 12,
2452 (back->note.namedata - (char *) contents) - 12);
2453 pnote->note.type = 0;
2454 break;
2457 /* Rule 2a. */
2458 if (contained_by (pnote, back))
2460 merge_debug ("Delete note at offset %#08lx - fully contained by note at %#08lx\n",
2461 (pnote->note.namedata - (char *) contents) - 12,
2462 (back->note.namedata - (char *) contents) - 12);
2463 pnote->note.type = 0;
2464 break;
2467 #if DEBUG_MERGE
2468 /* This should not happen as we have sorted the
2469 notes with earlier starting addresses first. */
2470 if (contained_by (back, pnote))
2471 merge_debug ("ERROR: UNEXPECTED CONTAINMENT\n");
2472 #endif
2474 /* Rule 2b. */
2475 if (overlaps_or_adjoins (back, pnote)
2476 && is_func_note (back) == is_func_note (pnote))
2478 merge_debug ("Delete note at offset %#08lx - merge into note at %#08lx\n",
2479 (pnote->note.namedata - (char *) contents) - 12,
2480 (back->note.namedata - (char *) contents) - 12);
2482 back->end = back->end > pnote->end ? back->end : pnote->end;
2483 back->start = back->start < pnote->start ? back->start : pnote->start;
2484 pnote->note.type = 0;
2485 break;
2488 /* Don't scan too far back however. */
2489 if (iter ++ > 16)
2491 /* FIXME: Not sure if this can ever be triggered. */
2492 merge_debug ("ITERATION LIMIT REACHED\n");
2493 break;
2497 if (! is_deleted_note (pnote))
2499 /* Keep a pointer to this note, so that we can
2500 start the next search for rule 2 matches here. */
2501 prev_note = pnote;
2502 #if DEBUG_MERGE
2503 merge_debug ("Unable to do anything with note at %#08lx\n",
2504 (pnote->note.namedata - (char *) contents) - 12);
2505 #endif
2509 /* Resort the notes. */
2510 merge_debug ("Final sorting of notes\n");
2511 qsort (pnotes, pnotes_end - pnotes, sizeof (* pnotes), sort_gnu_build_notes);
2513 /* Reconstruct the ELF notes. */
2514 bfd_byte * new_contents;
2515 bfd_byte * old;
2516 bfd_byte * new;
2517 bfd_size_type new_size;
2518 bfd_vma prev_start = 0;
2519 bfd_vma prev_end = 0;
2521 /* Not sure how, but the notes might grow in size.
2522 (eg see PR 1774507). Allow for this here. */
2523 new = new_contents = xmalloc (size * 2);
2524 for (pnote = pnotes, old = contents;
2525 pnote < pnotes_end;
2526 pnote ++)
2528 bfd_size_type note_size = 12 + pnote->padded_namesz + pnote->note.descsz;
2530 if (! is_deleted_note (pnote))
2532 /* Create the note, potentially using the
2533 address range of the previous note. */
2534 if (pnote->start == prev_start && pnote->end == prev_end)
2536 bfd_put_32 (abfd, pnote->note.namesz, new);
2537 bfd_put_32 (abfd, 0, new + 4);
2538 bfd_put_32 (abfd, pnote->note.type, new + 8);
2539 new += 12;
2540 memcpy (new, pnote->note.namedata, pnote->note.namesz);
2541 if (pnote->note.namesz < pnote->padded_namesz)
2542 memset (new + pnote->note.namesz, 0, pnote->padded_namesz - pnote->note.namesz);
2543 new += pnote->padded_namesz;
2545 else
2547 bfd_put_32 (abfd, pnote->note.namesz, new);
2548 bfd_put_32 (abfd, is_64bit (abfd) ? 16 : 8, new + 4);
2549 bfd_put_32 (abfd, pnote->note.type, new + 8);
2550 new += 12;
2551 memcpy (new, pnote->note.namedata, pnote->note.namesz);
2552 if (pnote->note.namesz < pnote->padded_namesz)
2553 memset (new + pnote->note.namesz, 0, pnote->padded_namesz - pnote->note.namesz);
2554 new += pnote->padded_namesz;
2555 if (is_64bit (abfd))
2557 bfd_put_64 (abfd, pnote->start, new);
2558 bfd_put_64 (abfd, pnote->end, new + 8);
2559 new += 16;
2561 else
2563 bfd_put_32 (abfd, pnote->start, new);
2564 bfd_put_32 (abfd, pnote->end, new + 4);
2565 new += 8;
2568 prev_start = pnote->start;
2569 prev_end = pnote->end;
2573 old += note_size;
2576 #if DEBUG_MERGE
2577 merge_debug ("Results of merge:\n");
2578 for (pnote = pnotes; pnote < pnotes_end; pnote ++)
2579 if (! is_deleted_note (pnote))
2580 merge_debug ("offset %#08lx range %#08lx..%#08lx type %ld attribute %d namesz %ld\n",
2581 (pnote->note.namedata - (char *) contents) - 12,
2582 pnote->start, pnote->end,
2583 pnote->note.type,
2584 pnote->note.namedata[3],
2585 pnote->note.namesz
2587 #endif
2589 new_size = new - new_contents;
2590 if (new_size < size)
2592 memcpy (contents, new_contents, new_size);
2593 size = new_size;
2595 free (new_contents);
2597 done:
2598 if (err)
2600 bfd_set_error (bfd_error_bad_value);
2601 bfd_nonfatal_message (NULL, abfd, sec, err);
2602 status = 1;
2605 free (pnotes);
2606 return size;
2609 static flagword
2610 check_new_section_flags (flagword flags, bfd * abfd, const char * secname)
2612 /* Only set the SEC_COFF_SHARED flag on COFF files.
2613 The same bit value is used by ELF targets to indicate
2614 compressed sections, and setting that flag here breaks
2615 things. */
2616 if ((flags & SEC_COFF_SHARED)
2617 && bfd_get_flavour (abfd) != bfd_target_coff_flavour)
2619 non_fatal (_("%s[%s]: Note - dropping 'share' flag as output format is not COFF"),
2620 bfd_get_filename (abfd), secname);
2621 flags &= ~ SEC_COFF_SHARED;
2623 return flags;
2626 static void
2627 set_long_section_mode (bfd *output_bfd, bfd *input_bfd, enum long_section_name_handling style)
2629 /* This is only relevant to Coff targets. */
2630 if (bfd_get_flavour (output_bfd) == bfd_target_coff_flavour)
2632 if (style == KEEP
2633 && bfd_get_flavour (input_bfd) == bfd_target_coff_flavour)
2634 style = bfd_coff_long_section_names (input_bfd) ? ENABLE : DISABLE;
2635 bfd_coff_set_long_section_names (output_bfd, style != DISABLE);
2639 /* Copy object file IBFD onto OBFD.
2640 Returns TRUE upon success, FALSE otherwise. */
2642 static bool
2643 copy_object (bfd *ibfd, bfd *obfd, const bfd_arch_info_type *input_arch)
2645 bfd_vma start;
2646 long symcount;
2647 asection **osections = NULL;
2648 asection *osec;
2649 asection *gnu_debuglink_section = NULL;
2650 bfd_size_type *gaps = NULL;
2651 bfd_size_type max_gap = 0;
2652 long symsize;
2653 void *dhandle;
2654 enum bfd_architecture iarch;
2655 unsigned int imach;
2656 unsigned int num_sec, i;
2658 if (ibfd->xvec->byteorder != obfd->xvec->byteorder
2659 && ibfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN
2660 && obfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN)
2662 /* PR 17636: Call non-fatal so that we return to our parent who
2663 may need to tidy temporary files. */
2664 non_fatal (_("unable to change endianness of '%s'"),
2665 bfd_get_archive_filename (ibfd));
2666 return false;
2669 if (ibfd->read_only)
2671 non_fatal (_("unable to modify '%s' due to errors"),
2672 bfd_get_archive_filename (ibfd));
2673 return false;
2676 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
2678 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
2679 return false;
2682 if (ibfd->sections == NULL)
2684 non_fatal (_("error: the input file '%s' has no sections"),
2685 bfd_get_archive_filename (ibfd));
2686 return false;
2689 /* This is a no-op on non-Coff targets. */
2690 set_long_section_mode (obfd, ibfd, long_section_names);
2692 /* Set the Verilog output endianness based upon the input file's
2693 endianness. We may not be producing verilog format output,
2694 but testing this just adds extra code this is not really
2695 necessary. */
2696 VerilogDataEndianness = ibfd->xvec->byteorder;
2698 if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
2700 if ((do_debug_sections & compress) != 0
2701 && do_debug_sections != compress)
2703 non_fatal (_ ("--compress-debug-sections=[zlib|zlib-gnu|zlib-gabi|"
2704 "zstd] is unsupported on `%s'"),
2705 bfd_get_archive_filename (ibfd));
2706 return false;
2709 if (do_elf_stt_common)
2711 non_fatal (_("--elf-stt-common=[yes|no] is unsupported on `%s'"),
2712 bfd_get_archive_filename (ibfd));
2713 return false;
2717 if (verbose)
2718 printf (_("copy from `%s' [%s] to `%s' [%s]\n"),
2719 bfd_get_archive_filename (ibfd), bfd_get_target (ibfd),
2720 bfd_get_filename (obfd), bfd_get_target (obfd));
2722 if (extract_symbol)
2723 start = 0;
2724 else
2726 if (set_start_set)
2727 start = set_start;
2728 else
2729 start = bfd_get_start_address (ibfd);
2730 start += change_start;
2733 /* Neither the start address nor the flags
2734 need to be set for a core file. */
2735 if (bfd_get_format (obfd) != bfd_core)
2737 flagword flags;
2739 flags = bfd_get_file_flags (ibfd);
2740 flags |= bfd_flags_to_set;
2741 flags &= ~bfd_flags_to_clear;
2742 flags &= bfd_applicable_file_flags (obfd);
2744 if (strip_symbols == STRIP_ALL)
2745 flags &= ~HAS_RELOC;
2747 if (!bfd_set_start_address (obfd, start)
2748 || !bfd_set_file_flags (obfd, flags))
2750 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2751 return false;
2755 /* Copy architecture of input file to output file. */
2756 iarch = bfd_get_arch (ibfd);
2757 imach = bfd_get_mach (ibfd);
2758 if (input_arch)
2760 if (iarch == bfd_arch_unknown)
2762 iarch = input_arch->arch;
2763 imach = input_arch->mach;
2765 else
2766 non_fatal (_("Input file `%s' ignores binary architecture parameter."),
2767 bfd_get_archive_filename (ibfd));
2769 if (iarch == bfd_arch_unknown
2770 && bfd_get_flavour (ibfd) != bfd_target_elf_flavour
2771 && bfd_get_flavour (obfd) == bfd_target_elf_flavour)
2773 const struct elf_backend_data *bed = get_elf_backend_data (obfd);
2774 iarch = bed->arch;
2775 imach = 0;
2777 if (!bfd_set_arch_mach (obfd, iarch, imach)
2778 && (ibfd->target_defaulted
2779 || bfd_get_arch (ibfd) != bfd_get_arch (obfd)))
2781 if (bfd_get_arch (ibfd) == bfd_arch_unknown)
2782 non_fatal (_("Unable to recognise the format of the input file `%s'"),
2783 bfd_get_archive_filename (ibfd));
2784 else
2785 non_fatal (_("Output file cannot represent architecture `%s'"),
2786 bfd_printable_arch_mach (bfd_get_arch (ibfd),
2787 bfd_get_mach (ibfd)));
2788 return false;
2791 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
2793 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2794 return false;
2797 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
2798 && bfd_pei_p (obfd))
2800 /* Set up PE parameters. */
2801 pe_data_type *pe = pe_data (obfd);
2803 /* Copy PE parameters before changing them. */
2804 if (bfd_get_flavour (ibfd) == bfd_target_coff_flavour
2805 && bfd_pei_p (ibfd))
2807 pe->pe_opthdr = pe_data (ibfd)->pe_opthdr;
2809 if (preserve_dates)
2810 pe->timestamp = pe_data (ibfd)->coff.timestamp;
2811 else
2812 pe->timestamp = -1;
2815 if (pe_file_alignment != (bfd_vma) -1)
2816 pe->pe_opthdr.FileAlignment = pe_file_alignment;
2817 else
2818 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
2820 if (pe_heap_commit != (bfd_vma) -1)
2821 pe->pe_opthdr.SizeOfHeapCommit = pe_heap_commit;
2823 if (pe_heap_reserve != (bfd_vma) -1)
2824 pe->pe_opthdr.SizeOfHeapCommit = pe_heap_reserve;
2826 if (pe_image_base != (bfd_vma) -1)
2827 pe->pe_opthdr.ImageBase = pe_image_base;
2829 if (pe_section_alignment != (bfd_vma) -1)
2830 pe->pe_opthdr.SectionAlignment = pe_section_alignment;
2831 else
2832 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
2834 if (pe_stack_commit != (bfd_vma) -1)
2835 pe->pe_opthdr.SizeOfStackCommit = pe_stack_commit;
2837 if (pe_stack_reserve != (bfd_vma) -1)
2838 pe->pe_opthdr.SizeOfStackCommit = pe_stack_reserve;
2840 if (pe_subsystem != -1)
2841 pe->pe_opthdr.Subsystem = pe_subsystem;
2843 if (pe_major_subsystem_version != -1)
2844 pe->pe_opthdr.MajorSubsystemVersion = pe_major_subsystem_version;
2846 if (pe_minor_subsystem_version != -1)
2847 pe->pe_opthdr.MinorSubsystemVersion = pe_minor_subsystem_version;
2849 if (pe_file_alignment > pe_section_alignment)
2851 non_fatal (_("warning: file alignment (0x%" PRIx64
2852 ") > section alignment (0x%" PRIx64 ")"),
2853 (uint64_t) pe_file_alignment,
2854 (uint64_t) pe_section_alignment);
2858 free (isympp);
2860 if (osympp != isympp)
2861 free (osympp);
2863 isympp = NULL;
2864 osympp = NULL;
2866 symsize = bfd_get_symtab_upper_bound (ibfd);
2867 if (symsize < 0)
2869 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2870 return false;
2873 osympp = isympp = (asymbol **) xmalloc (symsize);
2874 symcount = bfd_canonicalize_symtab (ibfd, isympp);
2875 if (symcount < 0)
2877 bfd_nonfatal_message (NULL, ibfd, NULL, NULL);
2878 return false;
2880 /* PR 17512: file: d6323821
2881 If the symbol table could not be loaded do not pretend that we have
2882 any symbols. This trips us up later on when we load the relocs. */
2883 if (symcount == 0)
2885 free (isympp);
2886 osympp = isympp = NULL;
2889 /* BFD mandates that all output sections be created and sizes set before
2890 any output is done. Thus, we traverse all sections multiple times. */
2891 bfd_map_over_sections (ibfd, setup_section, obfd);
2893 if (!extract_symbol)
2894 setup_bfd_headers (ibfd, obfd);
2896 if (add_sections != NULL)
2898 struct section_add *padd;
2899 struct section_list *pset;
2901 for (padd = add_sections; padd != NULL; padd = padd->next)
2903 flagword flags;
2905 pset = find_section_list (padd->name, false,
2906 SECTION_CONTEXT_SET_FLAGS);
2907 if (pset != NULL)
2909 flags = pset->flags | SEC_HAS_CONTENTS;
2910 flags = check_new_section_flags (flags, obfd, padd->name);
2912 else
2913 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DATA;
2915 /* bfd_make_section_with_flags() does not return very helpful
2916 error codes, so check for the most likely user error first. */
2917 if (bfd_get_section_by_name (obfd, padd->name))
2919 bfd_nonfatal_message (NULL, obfd, NULL,
2920 _("can't add section '%s'"), padd->name);
2921 return false;
2923 else
2925 /* We use LINKER_CREATED here so that the backend hooks
2926 will create any special section type information,
2927 instead of presuming we know what we're doing merely
2928 because we set the flags. */
2929 padd->section = bfd_make_section_with_flags
2930 (obfd, padd->name, flags | SEC_LINKER_CREATED);
2931 if (padd->section == NULL)
2933 bfd_nonfatal_message (NULL, obfd, NULL,
2934 _("can't create section `%s'"),
2935 padd->name);
2936 return false;
2940 if (!bfd_set_section_size (padd->section, padd->size))
2942 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2943 return false;
2946 pset = find_section_list (padd->name, false,
2947 SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA);
2948 if (pset != NULL
2949 && !bfd_set_section_vma (padd->section, pset->vma_val))
2951 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2952 return false;
2955 pset = find_section_list (padd->name, false,
2956 SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA);
2957 if (pset != NULL)
2959 padd->section->lma = pset->lma_val;
2961 if (!bfd_set_section_alignment
2962 (padd->section, bfd_section_alignment (padd->section)))
2964 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
2965 return false;
2971 if (update_sections != NULL)
2973 struct section_add *pupdate;
2975 for (pupdate = update_sections;
2976 pupdate != NULL;
2977 pupdate = pupdate->next)
2979 pupdate->section = bfd_get_section_by_name (ibfd, pupdate->name);
2980 if (pupdate->section == NULL)
2982 non_fatal (_("error: %s not found, can't be updated"), pupdate->name);
2983 return false;
2986 osec = pupdate->section->output_section;
2987 if (!bfd_set_section_size (osec, pupdate->size))
2989 bfd_nonfatal_message (NULL, obfd, osec, NULL);
2990 return false;
2995 merged_note_section * merged_note_sections = NULL;
2996 if (merge_notes)
2998 /* This palaver is necessary because we must set the output
2999 section size first, before its contents are ready. */
3000 for (osec = ibfd->sections; osec != NULL; osec = osec->next)
3002 if (! is_mergeable_note_section (ibfd, osec))
3003 continue;
3005 /* If the section is going to be completly deleted then
3006 do not bother to merge it. */
3007 if (osec->output_section == NULL)
3008 continue;
3010 bfd_size_type size = bfd_section_size (osec);
3012 if (size == 0)
3013 /* This can happen, eg when stripping a binary for a second
3014 time. See BZ 2121365 for an example. */
3015 continue;
3017 merged_note_section * merged = xmalloc (sizeof * merged);
3018 merged->contents = NULL;
3019 if (! bfd_get_full_section_contents (ibfd, osec, & merged->contents))
3021 bfd_nonfatal_message (NULL, ibfd, osec,
3022 _("warning: could not load note section"));
3023 free (merged);
3024 continue;
3027 merged->size = merge_gnu_build_notes (ibfd, osec, size,
3028 merged->contents);
3030 /* FIXME: Once we have read the contents in, we must write
3031 them out again. So even if the mergeing has achieved
3032 nothing we still add this entry to the merge list. */
3034 if (size != merged->size
3035 && !bfd_set_section_size (osec->output_section, merged->size))
3037 bfd_nonfatal_message (NULL, obfd, osec,
3038 _("warning: failed to set merged notes size"));
3039 free (merged->contents);
3040 free (merged);
3041 continue;
3044 /* Add section to list of merged sections. */
3045 merged->sec = osec;
3046 merged->next = merged_note_sections;
3047 merged_note_sections = merged;
3051 if (dump_sections != NULL)
3053 struct section_add * pdump;
3055 for (pdump = dump_sections; pdump != NULL; pdump = pdump->next)
3057 FILE * f;
3058 bfd_byte *contents;
3060 osec = bfd_get_section_by_name (ibfd, pdump->name);
3061 if (osec == NULL)
3063 bfd_nonfatal_message (NULL, ibfd, NULL,
3064 _("can't dump section '%s' - it does not exist"),
3065 pdump->name);
3066 continue;
3069 if ((bfd_section_flags (osec) & SEC_HAS_CONTENTS) == 0)
3071 bfd_nonfatal_message (NULL, ibfd, osec,
3072 _("can't dump section - it has no contents"));
3073 continue;
3076 bfd_size_type size = bfd_section_size (osec);
3077 /* Note - we allow the dumping of zero-sized sections,
3078 creating an empty file. */
3080 f = fopen (pdump->filename, FOPEN_WB);
3081 if (f == NULL)
3083 bfd_nonfatal_message (pdump->filename, NULL, NULL,
3084 _("could not open section dump file"));
3085 continue;
3088 if (bfd_malloc_and_get_section (ibfd, osec, &contents))
3090 if (size != 0 && fwrite (contents, 1, size, f) != size)
3092 non_fatal (_("error writing section contents to %s (error: %s)"),
3093 pdump->filename,
3094 strerror (errno));
3095 free (contents);
3096 fclose (f);
3097 return false;
3100 else
3101 bfd_nonfatal_message (NULL, ibfd, osec,
3102 _("could not retrieve section contents"));
3104 fclose (f);
3105 free (contents);
3109 if (gnu_debuglink_filename != NULL)
3111 /* PR 15125: Give a helpful warning message if
3112 the debuglink section already exists, and
3113 allow the rest of the copy to complete. */
3114 if (bfd_get_section_by_name (obfd, ".gnu_debuglink"))
3116 non_fatal (_("%s: debuglink section already exists"),
3117 bfd_get_filename (ibfd));
3118 gnu_debuglink_filename = NULL;
3120 else
3122 gnu_debuglink_section = bfd_create_gnu_debuglink_section
3123 (obfd, gnu_debuglink_filename);
3125 if (gnu_debuglink_section == NULL)
3127 bfd_nonfatal_message (NULL, obfd, NULL,
3128 _("cannot create debug link section `%s'"),
3129 gnu_debuglink_filename);
3130 return false;
3133 /* Special processing for PE format files. We
3134 have no way to distinguish PE from COFF here. */
3135 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour)
3137 bfd_vma debuglink_vma;
3138 asection * highest_section;
3140 /* The PE spec requires that all sections be adjacent and sorted
3141 in ascending order of VMA. It also specifies that debug
3142 sections should be last. This is despite the fact that debug
3143 sections are not loaded into memory and so in theory have no
3144 use for a VMA.
3146 This means that the debuglink section must be given a non-zero
3147 VMA which makes it contiguous with other debug sections. So
3148 walk the current section list, find the section with the
3149 highest VMA and start the debuglink section after that one. */
3150 for (osec = obfd->sections, highest_section = NULL;
3151 osec != NULL;
3152 osec = osec->next)
3153 if (osec->vma > 0
3154 && (highest_section == NULL
3155 || osec->vma > highest_section->vma))
3156 highest_section = osec;
3158 if (highest_section)
3159 debuglink_vma = BFD_ALIGN (highest_section->vma
3160 + highest_section->size,
3161 /* FIXME: We ought to be using
3162 COFF_PAGE_SIZE here or maybe
3163 bfd_section_alignment() (if it
3164 was set) but since this is for PE
3165 and we know the required alignment
3166 it is easier just to hard code it. */
3167 0x1000);
3168 else
3169 /* Umm, not sure what to do in this case. */
3170 debuglink_vma = 0x1000;
3172 bfd_set_section_vma (gnu_debuglink_section, debuglink_vma);
3177 num_sec = bfd_count_sections (obfd);
3178 if (num_sec != 0
3179 && (gap_fill_set || pad_to_set))
3181 asection **set;
3183 /* We must fill in gaps between the sections and/or we must pad
3184 the last section to a specified address. We do this by
3185 grabbing a list of the sections, sorting them by VMA, and
3186 increasing the section sizes as required to fill the gaps.
3187 We write out the gap contents below. */
3189 osections = xmalloc (num_sec * sizeof (*osections));
3190 set = osections;
3191 bfd_map_over_sections (obfd, get_sections, &set);
3193 qsort (osections, num_sec, sizeof (*osections), compare_section_lma);
3195 gaps = xmalloc (num_sec * sizeof (*gaps));
3196 memset (gaps, 0, num_sec * sizeof (*gaps));
3198 if (gap_fill_set)
3200 for (i = 0; i < num_sec - 1; i++)
3202 flagword flags;
3203 bfd_size_type size; /* Octets. */
3204 bfd_vma gap_start, gap_stop; /* Octets. */
3205 unsigned int opb1 = bfd_octets_per_byte (obfd, osections[i]);
3206 unsigned int opb2 = bfd_octets_per_byte (obfd, osections[i+1]);
3208 flags = bfd_section_flags (osections[i]);
3209 if ((flags & SEC_HAS_CONTENTS) == 0
3210 || (flags & SEC_LOAD) == 0)
3211 continue;
3213 size = bfd_section_size (osections[i]);
3214 gap_start = bfd_section_lma (osections[i]) * opb1 + size;
3215 gap_stop = bfd_section_lma (osections[i + 1]) * opb2;
3216 if (gap_start < gap_stop)
3218 if (!bfd_set_section_size (osections[i],
3219 size + (gap_stop - gap_start)))
3221 bfd_nonfatal_message (NULL, obfd, osections[i],
3222 _("Can't fill gap after section"));
3223 status = 1;
3224 break;
3226 gaps[i] = gap_stop - gap_start;
3227 if (max_gap < gap_stop - gap_start)
3228 max_gap = gap_stop - gap_start;
3233 if (pad_to_set)
3235 bfd_vma lma; /* Octets. */
3236 bfd_size_type size; /* Octets. */
3237 unsigned int opb = bfd_octets_per_byte (obfd, osections[num_sec - 1]);
3238 bfd_vma _pad_to = pad_to * opb;
3240 lma = bfd_section_lma (osections[num_sec - 1]) * opb;
3241 size = bfd_section_size (osections[num_sec - 1]);
3242 if (lma + size < _pad_to)
3244 if (!bfd_set_section_size (osections[num_sec - 1], _pad_to - lma))
3246 bfd_nonfatal_message (NULL, obfd, osections[num_sec - 1],
3247 _("can't add padding"));
3248 status = 1;
3250 else
3252 gaps[num_sec - 1] = _pad_to - (lma + size);
3253 if (max_gap < _pad_to - (lma + size))
3254 max_gap = _pad_to - (lma + size);
3260 /* Symbol filtering must happen after the output sections
3261 have been created, but before their contents are set. */
3262 dhandle = NULL;
3263 if (convert_debugging)
3264 dhandle = read_debugging_info (ibfd, isympp, symcount, false);
3266 if ((obfd->flags & (EXEC_P | DYNAMIC)) != 0
3267 && (obfd->flags & HAS_RELOC) == 0)
3269 if (bfd_keep_unused_section_symbols (obfd) || keep_section_symbols)
3271 /* Non-relocatable inputs may not have the unused section
3272 symbols. Mark all section symbols as used to generate
3273 section symbols. */
3274 asection *asect;
3275 for (asect = obfd->sections; asect != NULL; asect = asect->next)
3276 if (asect->symbol)
3277 asect->symbol->flags |= BSF_SECTION_SYM_USED;
3279 else
3281 /* Non-relocatable inputs may have the unused section symbols.
3282 Mark all section symbols as unused to excluded them. */
3283 long s;
3284 for (s = 0; s < symcount; s++)
3285 if ((isympp[s]->flags & BSF_SECTION_SYM_USED))
3286 isympp[s]->flags &= ~BSF_SECTION_SYM_USED;
3290 if (strip_symbols == STRIP_DEBUG
3291 || strip_symbols == STRIP_ALL
3292 || strip_symbols == STRIP_UNNEEDED
3293 || strip_symbols == STRIP_NONDEBUG
3294 || strip_symbols == STRIP_DWO
3295 || strip_symbols == STRIP_NONDWO
3296 || discard_locals != LOCALS_UNDEF
3297 || localize_hidden
3298 || htab_elements (strip_specific_htab) != 0
3299 || htab_elements (keep_specific_htab) != 0
3300 || htab_elements (localize_specific_htab) != 0
3301 || htab_elements (globalize_specific_htab) != 0
3302 || htab_elements (keepglobal_specific_htab) != 0
3303 || htab_elements (weaken_specific_htab) != 0
3304 || htab_elements (redefine_specific_htab) != 0
3305 || prefix_symbols_string
3306 || sections_removed
3307 || sections_copied
3308 || convert_debugging
3309 || change_leading_char
3310 || remove_leading_char
3311 || section_rename_list
3312 || weaken
3313 || add_symbols)
3315 /* Mark symbols used in output relocations so that they
3316 are kept, even if they are local labels or static symbols.
3318 Note we iterate over the input sections examining their
3319 relocations since the relocations for the output sections
3320 haven't been set yet. mark_symbols_used_in_relocations will
3321 ignore input sections which have no corresponding output
3322 section. */
3323 if (strip_symbols != STRIP_ALL)
3325 bfd_set_error (bfd_error_no_error);
3326 bfd_map_over_sections (ibfd,
3327 mark_symbols_used_in_relocations,
3328 isympp);
3329 if (bfd_get_error () != bfd_error_no_error)
3331 status = 1;
3332 return false;
3336 osympp = (asymbol **) xmalloc ((symcount + add_symbols + 1) * sizeof (asymbol *));
3337 symcount = filter_symbols (ibfd, obfd, osympp, isympp, symcount);
3340 if (dhandle != NULL)
3342 bool res;
3344 res = write_debugging_info (obfd, dhandle, &symcount, &osympp);
3346 if (! res)
3348 status = 1;
3349 return false;
3353 bfd_set_symtab (obfd, osympp, symcount);
3355 /* This has to happen before section positions are set. */
3356 bfd_map_over_sections (ibfd, copy_relocations_in_section, obfd);
3357 if (status != 0)
3358 return false;
3360 /* This has to happen after the symbol table has been set. */
3361 bfd_map_over_sections (ibfd, copy_section, obfd);
3362 if (status != 0)
3363 return false;
3365 if (add_sections != NULL)
3367 struct section_add *padd;
3369 for (padd = add_sections; padd != NULL; padd = padd->next)
3371 if (! bfd_set_section_contents (obfd, padd->section, padd->contents,
3372 0, padd->size))
3374 bfd_nonfatal_message (NULL, obfd, padd->section, NULL);
3375 return false;
3380 if (update_sections != NULL)
3382 struct section_add *pupdate;
3384 for (pupdate = update_sections;
3385 pupdate != NULL;
3386 pupdate = pupdate->next)
3388 osec = pupdate->section->output_section;
3389 if (! bfd_set_section_contents (obfd, osec, pupdate->contents,
3390 0, pupdate->size))
3392 bfd_nonfatal_message (NULL, obfd, osec, NULL);
3393 return false;
3398 if (merged_note_sections != NULL)
3400 merged_note_section * merged = NULL;
3402 for (osec = obfd->sections; osec != NULL; osec = osec->next)
3404 if (! is_mergeable_note_section (obfd, osec))
3405 continue;
3407 if (merged == NULL)
3408 merged = merged_note_sections;
3410 /* It is likely that output sections are in the same order
3411 as the input sections, but do not assume that this is
3412 the case. */
3413 if (merged->sec->output_section != osec)
3415 for (merged = merged_note_sections;
3416 merged != NULL;
3417 merged = merged->next)
3418 if (merged->sec->output_section == osec)
3419 break;
3421 if (merged == NULL)
3423 bfd_nonfatal_message
3424 (NULL, obfd, osec,
3425 _("error: failed to locate merged notes"));
3426 continue;
3430 if (merged->contents == NULL)
3432 bfd_nonfatal_message
3433 (NULL, obfd, osec,
3434 _("error: failed to merge notes"));
3435 continue;
3438 if (! bfd_set_section_contents (obfd, osec, merged->contents, 0,
3439 merged->size))
3441 bfd_nonfatal_message
3442 (NULL, obfd, osec,
3443 _("error: failed to copy merged notes into output"));
3444 return false;
3447 merged = merged->next;
3450 /* Free the memory. */
3451 merged_note_section * next;
3452 for (merged = merged_note_sections; merged != NULL; merged = next)
3454 next = merged->next;
3455 free (merged->contents);
3456 free (merged);
3459 else if (merge_notes && ! is_strip)
3460 non_fatal (_("%s: Could not find any mergeable note sections"),
3461 bfd_get_filename (ibfd));
3463 if (gnu_debuglink_filename != NULL)
3465 if (! bfd_fill_in_gnu_debuglink_section
3466 (obfd, gnu_debuglink_section, gnu_debuglink_filename))
3468 bfd_nonfatal_message (NULL, obfd, NULL,
3469 _("cannot fill debug link section `%s'"),
3470 gnu_debuglink_filename);
3471 return false;
3475 if (gaps != NULL)
3477 bfd_byte *buf;
3479 /* Fill in the gaps. */
3480 if (max_gap > 8192)
3481 max_gap = 8192;
3482 buf = (bfd_byte *) xmalloc (max_gap);
3483 memset (buf, gap_fill, max_gap);
3485 for (i = 0; i < num_sec; i++)
3487 if (gaps[i] != 0)
3489 bfd_size_type left;
3490 file_ptr off;
3492 left = gaps[i];
3493 off = bfd_section_size (osections[i]) - left;
3495 while (left > 0)
3497 bfd_size_type now;
3499 if (left > 8192)
3500 now = 8192;
3501 else
3502 now = left;
3504 if (! bfd_set_section_contents (obfd, osections[i], buf,
3505 off, now))
3507 bfd_nonfatal_message (NULL, obfd, osections[i], NULL);
3508 free (buf);
3509 return false;
3512 left -= now;
3513 off += now;
3518 free (buf);
3519 free (gaps);
3520 gaps = NULL;
3523 /* Allow the BFD backend to copy any private data it understands
3524 from the input BFD to the output BFD. This is done last to
3525 permit the routine to look at the filtered symbol table, which is
3526 important for the ECOFF code at least. */
3527 if (! bfd_copy_private_bfd_data (ibfd, obfd))
3529 bfd_nonfatal_message (NULL, obfd, NULL,
3530 _("error copying private BFD data"));
3531 return false;
3534 /* Switch to the alternate machine code. We have to do this at the
3535 very end, because we only initialize the header when we create
3536 the first section. */
3537 if (use_alt_mach_code != 0)
3539 if (! bfd_alt_mach_code (obfd, use_alt_mach_code))
3541 non_fatal (_("this target does not support %lu alternative machine codes"),
3542 use_alt_mach_code);
3543 if (bfd_get_flavour (obfd) == bfd_target_elf_flavour)
3545 non_fatal (_("treating that number as an absolute e_machine value instead"));
3546 elf_elfheader (obfd)->e_machine = use_alt_mach_code;
3548 else
3549 non_fatal (_("ignoring the alternative value"));
3553 return true;
3556 /* Read each archive element in turn from IBFD, copy the
3557 contents to temp file, and keep the temp file handle.
3558 If 'force_output_target' is TRUE then make sure that
3559 all elements in the new archive are of the type
3560 'output_target'. */
3562 static void
3563 copy_archive (bfd *ibfd, bfd *obfd, const char *output_target,
3564 bool force_output_target,
3565 const bfd_arch_info_type *input_arch)
3567 struct name_list
3569 struct name_list *next;
3570 const char *name;
3571 bfd *obfd;
3572 } *list, *l;
3573 bfd **ptr = &obfd->archive_head;
3574 bfd *this_element;
3575 char *dir;
3576 char *filename;
3578 /* PR 24281: It is not clear what should happen when copying a thin archive.
3579 One part is straight forward - if the output archive is in a different
3580 directory from the input archive then any relative paths in the library
3581 should be adjusted to the new location. But if any transformation
3582 options are active (eg strip, rename, add, etc) then the implication is
3583 that these should be applied to the files pointed to by the archive.
3584 But since objcopy is not destructive, this means that new files must be
3585 created, and there is no guidance for the names of the new files. (Plus
3586 this conflicts with one of the goals of thin libraries - only taking up
3587 a minimal amount of space in the file system).
3589 So for now we fail if an attempt is made to copy such libraries. */
3590 if (ibfd->is_thin_archive)
3592 status = 1;
3593 bfd_set_error (bfd_error_invalid_operation);
3594 bfd_nonfatal_message (NULL, ibfd, NULL,
3595 _("sorry: copying thin archives is not currently supported"));
3596 return;
3599 /* Make a temp directory to hold the contents. */
3600 dir = make_tempdir (bfd_get_filename (obfd));
3601 if (dir == NULL)
3602 fatal (_("cannot create tempdir for archive copying (error: %s)"),
3603 strerror (errno));
3605 if (strip_symbols == STRIP_ALL)
3606 obfd->has_armap = false;
3607 else
3608 obfd->has_armap = ibfd->has_armap;
3609 obfd->is_thin_archive = ibfd->is_thin_archive;
3611 if (deterministic)
3612 obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
3614 list = NULL;
3616 this_element = bfd_openr_next_archived_file (ibfd, NULL);
3618 if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
3620 status = 1;
3621 bfd_nonfatal_message (NULL, obfd, NULL, NULL);
3622 goto cleanup_and_exit;
3625 while (!status && this_element != NULL)
3627 char *output_name;
3628 bfd *output_element;
3629 struct stat buf;
3630 int stat_status = 0;
3631 bool del = true;
3632 bool ok_object;
3634 /* PR binutils/17533: Do not allow directory traversal
3635 outside of the current directory tree by archive members. */
3636 if (! is_valid_archive_path (bfd_get_filename (this_element)))
3638 non_fatal (_("illegal pathname found in archive member: %s"),
3639 bfd_get_filename (this_element));
3640 bfd_close (this_element);
3641 status = 1;
3642 goto cleanup_and_exit;
3645 /* Create an output file for this member. */
3646 output_name = concat (dir, "/",
3647 bfd_get_filename (this_element), (char *) 0);
3649 /* If the file already exists, make another temp dir. */
3650 if (stat (output_name, &buf) >= 0)
3652 char * tmpdir = make_tempdir (output_name);
3654 free (output_name);
3655 if (tmpdir == NULL)
3657 non_fatal (_("cannot create tempdir for archive copying (error: %s)"),
3658 strerror (errno));
3659 bfd_close (this_element);
3660 status = 1;
3661 goto cleanup_and_exit;
3664 l = (struct name_list *) xmalloc (sizeof (struct name_list));
3665 l->name = tmpdir;
3666 l->next = list;
3667 l->obfd = NULL;
3668 list = l;
3669 output_name = concat (tmpdir, "/",
3670 bfd_get_filename (this_element), (char *) 0);
3673 if (preserve_dates)
3675 memset (&buf, 0, sizeof (buf));
3676 stat_status = bfd_stat_arch_elt (this_element, &buf);
3678 if (stat_status != 0)
3679 non_fatal (_("internal stat error on %s"),
3680 bfd_get_filename (this_element));
3683 l = (struct name_list *) xmalloc (sizeof (struct name_list));
3684 l->name = output_name;
3685 l->next = list;
3686 l->obfd = NULL;
3687 list = l;
3689 ok_object = bfd_check_format (this_element, bfd_object);
3690 if (!ok_object)
3691 bfd_nonfatal_message (NULL, this_element, NULL,
3692 _("Unable to recognise the format of file"));
3694 /* PR binutils/3110: Cope with archives
3695 containing multiple target types. */
3696 if (force_output_target || !ok_object)
3697 output_element = bfd_openw (output_name, output_target);
3698 else
3699 output_element = bfd_openw (output_name, bfd_get_target (this_element));
3701 if (output_element == NULL)
3703 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
3704 bfd_close (this_element);
3705 status = 1;
3706 goto cleanup_and_exit;
3709 if (ok_object)
3711 del = !copy_object (this_element, output_element, input_arch);
3713 if (del && bfd_get_arch (this_element) == bfd_arch_unknown)
3714 /* Try again as an unknown object file. */
3715 ok_object = false;
3718 if (!ok_object)
3719 del = !copy_unknown_object (this_element, output_element);
3721 if (!(ok_object && !del && !status
3722 ? bfd_close : bfd_close_all_done) (output_element))
3724 bfd_nonfatal_message (output_name, NULL, NULL, NULL);
3725 /* Error in new object file. Don't change archive. */
3726 status = 1;
3729 if (del)
3731 unlink (output_name);
3732 status = 1;
3735 if (status)
3736 bfd_close (this_element);
3737 else
3739 if (preserve_dates && stat_status == 0)
3740 set_times (output_name, &buf);
3742 /* Open the newly created output file and attach to our list. */
3743 output_element = bfd_openr (output_name, output_target);
3745 l->obfd = output_element;
3747 *ptr = output_element;
3748 ptr = &output_element->archive_next;
3750 bfd *last_element = this_element;
3751 this_element = bfd_openr_next_archived_file (ibfd, last_element);
3752 bfd_close (last_element);
3755 *ptr = NULL;
3757 filename = xstrdup (bfd_get_filename (obfd));
3758 if (!(status == 0 ? bfd_close : bfd_close_all_done) (obfd))
3760 status = 1;
3761 bfd_nonfatal_message (filename, NULL, NULL, NULL);
3763 free (filename);
3765 filename = xstrdup (bfd_get_filename (ibfd));
3766 if (!bfd_close (ibfd))
3768 status = 1;
3769 bfd_nonfatal_message (filename, NULL, NULL, NULL);
3771 free (filename);
3773 cleanup_and_exit:
3774 /* Delete all the files that we opened. */
3776 struct name_list * next;
3778 for (l = list; l != NULL; l = next)
3780 if (l->obfd == NULL)
3781 rmdir (l->name);
3782 else
3784 bfd_close (l->obfd);
3785 unlink (l->name);
3787 free ((char *) l->name);
3788 next = l->next;
3789 free (l);
3793 rmdir (dir);
3794 free (dir);
3797 /* The top-level control. */
3799 static void
3800 copy_file (const char *input_filename, const char *output_filename, int ofd,
3801 struct stat *in_stat, const char *input_target,
3802 const char *output_target, const bfd_arch_info_type *input_arch)
3804 bfd *ibfd;
3805 char **obj_matching;
3806 char **core_matching;
3807 off_t size = get_file_size (input_filename);
3809 if (size < 1)
3811 if (size == 0)
3812 non_fatal (_("error: the input file '%s' is empty"),
3813 input_filename);
3814 status = 1;
3815 return;
3818 /* To allow us to do "strip *" without dying on the first
3819 non-object file, failures are nonfatal. */
3820 ibfd = bfd_openr (input_filename, input_target);
3821 if (ibfd == NULL || bfd_stat (ibfd, in_stat) != 0)
3823 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
3824 status = 1;
3825 return;
3828 switch (do_debug_sections)
3830 case compress_gnu_zlib:
3831 ibfd->flags |= BFD_COMPRESS;
3832 break;
3833 case compress:
3834 case compress_zlib:
3835 /* The above two cases ought to just set BFD_COMPRESS for non-ELF
3836 but we can't tell whether a file is ELF or not until after
3837 bfd_check_format_matches. FIXME maybe: decide compression
3838 style in BFD after bfd_check_format_matches. */
3839 case compress_gabi_zlib:
3840 ibfd->flags |= BFD_COMPRESS | BFD_COMPRESS_GABI;
3841 break;
3842 case compress_zstd:
3843 ibfd->flags |= BFD_COMPRESS | BFD_COMPRESS_GABI | BFD_COMPRESS_ZSTD;
3844 #ifndef HAVE_ZSTD
3845 fatal (_ ("--compress-debug-sections=zstd: binutils is not built with "
3846 "zstd support"));
3847 #endif
3848 break;
3849 case decompress:
3850 ibfd->flags |= BFD_DECOMPRESS;
3851 break;
3852 default:
3853 break;
3856 switch (do_elf_stt_common)
3858 case elf_stt_common:
3859 ibfd->flags |= BFD_CONVERT_ELF_COMMON | BFD_USE_ELF_STT_COMMON;
3860 break;
3861 break;
3862 case no_elf_stt_common:
3863 ibfd->flags |= BFD_CONVERT_ELF_COMMON;
3864 break;
3865 default:
3866 break;
3869 if (bfd_check_format (ibfd, bfd_archive))
3871 bool force_output_target;
3872 bfd *obfd;
3874 /* bfd_get_target does not return the correct value until
3875 bfd_check_format succeeds. */
3876 if (output_target == NULL)
3878 output_target = bfd_get_target (ibfd);
3879 force_output_target = false;
3881 else
3882 force_output_target = true;
3884 if (ofd >= 0)
3885 obfd = bfd_fdopenw (output_filename, output_target, ofd);
3886 else
3887 obfd = bfd_openw (output_filename, output_target);
3889 if (obfd == NULL)
3891 close (ofd);
3892 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
3893 status = 1;
3894 return;
3897 if (gnu_debuglink_filename != NULL)
3899 non_fatal (_("--add-gnu-debuglink ignored for archive %s"),
3900 bfd_get_filename (ibfd));
3901 gnu_debuglink_filename = NULL;
3904 copy_archive (ibfd, obfd, output_target, force_output_target, input_arch);
3906 else if (bfd_check_format_matches (ibfd, bfd_object, &obj_matching))
3908 bfd *obfd;
3909 do_copy:
3911 /* bfd_get_target does not return the correct value until
3912 bfd_check_format succeeds. */
3913 if (output_target == NULL)
3914 output_target = bfd_get_target (ibfd);
3916 if (ofd >= 0)
3917 obfd = bfd_fdopenw (output_filename, output_target, ofd);
3918 else
3919 obfd = bfd_openw (output_filename, output_target);
3921 if (obfd == NULL)
3923 close (ofd);
3924 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
3925 status = 1;
3926 return;
3929 if (! copy_object (ibfd, obfd, input_arch))
3930 status = 1;
3932 /* PR 17512: file: 0f15796a.
3933 If the file could not be copied it may not be in a writeable
3934 state. So use bfd_close_all_done to avoid the possibility of
3935 writing uninitialised data into the file. */
3936 if (! (status ? bfd_close_all_done (obfd) : bfd_close (obfd)))
3938 status = 1;
3939 bfd_nonfatal_message (output_filename, NULL, NULL, NULL);
3942 if (!bfd_close (ibfd))
3944 status = 1;
3945 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
3948 else
3950 bfd_error_type obj_error = bfd_get_error ();
3951 bfd_error_type core_error;
3953 if (bfd_check_format_matches (ibfd, bfd_core, &core_matching))
3955 /* This probably can't happen.. */
3956 if (obj_error == bfd_error_file_ambiguously_recognized)
3957 free (obj_matching);
3958 goto do_copy;
3961 core_error = bfd_get_error ();
3962 /* Report the object error in preference to the core error. */
3963 if (obj_error != core_error)
3964 bfd_set_error (obj_error);
3966 bfd_nonfatal_message (input_filename, NULL, NULL, NULL);
3968 if (obj_error == bfd_error_file_ambiguously_recognized)
3969 list_matching_formats (obj_matching);
3970 if (core_error == bfd_error_file_ambiguously_recognized)
3971 list_matching_formats (core_matching);
3973 status = 1;
3977 /* Add a name to the section renaming list. */
3979 static void
3980 add_section_rename (const char * old_name, const char * new_name,
3981 flagword flags)
3983 section_rename * srename;
3985 /* Check for conflicts first. */
3986 for (srename = section_rename_list; srename != NULL; srename = srename->next)
3987 if (strcmp (srename->old_name, old_name) == 0)
3989 /* Silently ignore duplicate definitions. */
3990 if (strcmp (srename->new_name, new_name) == 0
3991 && srename->flags == flags)
3992 return;
3994 fatal (_("Multiple renames of section %s"), old_name);
3997 srename = (section_rename *) xmalloc (sizeof (* srename));
3999 srename->old_name = old_name;
4000 srename->new_name = new_name;
4001 srename->flags = flags;
4002 srename->next = section_rename_list;
4004 section_rename_list = srename;
4007 /* Check the section rename list for a new name of the input section
4008 called OLD_NAME. Returns the new name if one is found and sets
4009 RETURNED_FLAGS if non-NULL to the flags to be used for this section. */
4011 static const char *
4012 find_section_rename (const char *old_name, flagword *returned_flags)
4014 const section_rename *srename;
4016 for (srename = section_rename_list; srename != NULL; srename = srename->next)
4017 if (strcmp (srename->old_name, old_name) == 0)
4019 if (returned_flags != NULL && srename->flags != (flagword) -1)
4020 *returned_flags = srename->flags;
4022 return srename->new_name;
4025 return old_name;
4028 /* Once each of the sections is copied, we may still need to do some
4029 finalization work for private section headers. Do that here. */
4031 static void
4032 setup_bfd_headers (bfd *ibfd, bfd *obfd)
4034 /* Allow the BFD backend to copy any private data it understands
4035 from the input section to the output section. */
4036 if (! bfd_copy_private_header_data (ibfd, obfd))
4038 status = 1;
4039 bfd_nonfatal_message (NULL, ibfd, NULL,
4040 _("error in private header data"));
4041 return;
4044 /* All went well. */
4045 return;
4048 /* Create a section in OBFD with the same
4049 name and attributes as ISECTION in IBFD. */
4051 static void
4052 setup_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
4054 bfd *obfd = (bfd *) obfdarg;
4055 struct section_list *p;
4056 sec_ptr osection;
4057 bfd_size_type size;
4058 bfd_vma vma;
4059 bfd_vma lma;
4060 flagword flags;
4061 const char *err = NULL;
4062 const char * name;
4063 const char * new_name;
4064 char *prefix = NULL;
4065 bool make_nobits;
4066 unsigned int alignment;
4068 if (is_strip_section (ibfd, isection))
4069 return;
4071 /* Get the, possibly new, name of the output section. */
4072 name = bfd_section_name (isection);
4073 flags = bfd_section_flags (isection);
4074 if (bfd_get_flavour (ibfd) != bfd_get_flavour (obfd))
4076 flags &= bfd_applicable_section_flags (ibfd);
4077 flags &= bfd_applicable_section_flags (obfd);
4079 new_name = find_section_rename (name, &flags);
4080 if (new_name != name)
4082 name = new_name;
4083 flags = check_new_section_flags (flags, obfd, name);
4086 /* Prefix sections. */
4087 if (prefix_alloc_sections_string
4088 && (bfd_section_flags (isection) & SEC_ALLOC) != 0)
4089 prefix = prefix_alloc_sections_string;
4090 else if (prefix_sections_string)
4091 prefix = prefix_sections_string;
4093 if (prefix)
4095 char *n;
4097 n = (char *) xmalloc (strlen (prefix) + strlen (name) + 1);
4098 strcpy (n, prefix);
4099 strcat (n, name);
4100 name = n;
4103 make_nobits = false;
4105 p = find_section_list (bfd_section_name (isection), false,
4106 SECTION_CONTEXT_SET_FLAGS);
4107 if (p != NULL)
4109 flags = p->flags | (flags & (SEC_HAS_CONTENTS | SEC_RELOC));
4110 flags = check_new_section_flags (flags, obfd, bfd_section_name (isection));
4112 else if (strip_symbols == STRIP_NONDEBUG
4113 && (flags & (SEC_ALLOC | SEC_GROUP)) != 0
4114 && !is_nondebug_keep_contents_section (ibfd, isection))
4116 flagword clr = SEC_HAS_CONTENTS | SEC_LOAD | SEC_GROUP;
4118 if (bfd_get_flavour (obfd) == bfd_target_elf_flavour)
4120 /* PR 29532: Copy group sections intact as otherwise we end up with
4121 empty groups. This prevents separate debug info files from
4122 being used with GDB, if they were based upon files that
4123 originally contained groups. */
4124 if (flags & SEC_GROUP)
4125 clr = SEC_LOAD;
4126 else
4127 make_nobits = true;
4129 /* Twiddle the input section flags so that it seems to
4130 elf.c:copy_private_bfd_data that section flags have not
4131 changed between input and output sections. This hack
4132 prevents wholesale rewriting of the program headers. */
4133 isection->flags &= ~clr;
4135 flags &= ~clr;
4138 if (!bfd_convert_section_setup (ibfd, isection, obfd, &name, &size))
4140 osection = NULL;
4141 err = _("failed to create output section");
4142 goto loser;
4145 osection = bfd_make_section_anyway_with_flags (obfd, name, flags);
4147 if (osection == NULL)
4149 err = _("failed to create output section");
4150 goto loser;
4153 if (copy_byte >= 0)
4154 size = (size + interleave - 1) / interleave * copy_width;
4155 else if (extract_symbol)
4156 size = 0;
4157 if (!bfd_set_section_size (osection, size))
4158 err = _("failed to set size");
4160 vma = bfd_section_vma (isection);
4161 p = find_section_list (bfd_section_name (isection), false,
4162 SECTION_CONTEXT_ALTER_VMA | SECTION_CONTEXT_SET_VMA);
4163 if (p != NULL)
4165 if (p->context & SECTION_CONTEXT_SET_VMA)
4166 vma = p->vma_val;
4167 else
4168 vma += p->vma_val;
4170 else
4171 vma += change_section_address;
4173 if (!bfd_set_section_vma (osection, vma))
4174 err = _("failed to set vma");
4176 lma = isection->lma;
4177 p = find_section_list (bfd_section_name (isection), false,
4178 SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_SET_LMA);
4179 if (p != NULL)
4181 if (p->context & SECTION_CONTEXT_ALTER_LMA)
4182 lma += p->lma_val;
4183 else
4184 lma = p->lma_val;
4186 else
4187 lma += change_section_address;
4189 osection->lma = lma;
4191 p = find_section_list (bfd_section_name (isection), false,
4192 SECTION_CONTEXT_SET_ALIGNMENT);
4193 if (p != NULL)
4194 alignment = p->alignment;
4195 else
4196 alignment = bfd_section_alignment (isection);
4198 /* FIXME: This is probably not enough. If we change the LMA we
4199 may have to recompute the header for the file as well. */
4200 if (!bfd_set_section_alignment (osection, alignment))
4201 err = _("failed to set alignment");
4203 /* Copy merge entity size. */
4204 osection->entsize = isection->entsize;
4206 /* Copy compress status. */
4207 osection->compress_status = isection->compress_status;
4209 /* This used to be mangle_section; we do here to avoid using
4210 bfd_get_section_by_name since some formats allow multiple
4211 sections with the same name. */
4212 isection->output_section = osection;
4213 isection->output_offset = 0;
4215 if ((isection->flags & SEC_GROUP) != 0)
4217 asymbol *gsym = group_signature (isection);
4219 if (gsym != NULL)
4221 gsym->flags |= BSF_KEEP;
4222 if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour)
4223 elf_group_id (isection) = gsym;
4227 /* Allow the BFD backend to copy any private data it understands
4228 from the input section to the output section. */
4229 if (!bfd_copy_private_section_data (ibfd, isection, obfd, osection))
4230 err = _("failed to copy private data");
4232 if (make_nobits)
4233 elf_section_type (osection) = SHT_NOBITS;
4235 if (!err)
4236 return;
4238 loser:
4239 status = 1;
4240 bfd_nonfatal_message (NULL, obfd, osection, err);
4243 /* Return TRUE if input section ISECTION should be skipped. */
4245 static bool
4246 skip_section (bfd *ibfd, sec_ptr isection, bool skip_copy)
4248 sec_ptr osection;
4249 bfd_size_type size;
4250 flagword flags;
4252 /* If we have already failed earlier on,
4253 do not keep on generating complaints now. */
4254 if (status != 0)
4255 return true;
4257 if (extract_symbol)
4258 return true;
4260 if (is_strip_section (ibfd, isection))
4261 return true;
4263 if (is_update_section (ibfd, isection))
4264 return true;
4266 /* When merging a note section we skip the copying of the contents,
4267 but not the copying of the relocs associated with the contents. */
4268 if (skip_copy && is_mergeable_note_section (ibfd, isection))
4269 return true;
4271 flags = bfd_section_flags (isection);
4272 if ((flags & SEC_GROUP) != 0)
4273 return true;
4275 osection = isection->output_section;
4276 size = bfd_section_size (isection);
4278 if (size == 0 || osection == 0)
4279 return true;
4281 return false;
4284 /* Add section SECTION_PATTERN to the list of sections that will have their
4285 relocations removed. */
4287 static void
4288 handle_remove_relocations_option (const char *section_pattern)
4290 find_section_list (section_pattern, true, SECTION_CONTEXT_REMOVE_RELOCS);
4293 /* Return TRUE if ISECTION from IBFD should have its relocations removed,
4294 otherwise return FALSE. If the user has requested that relocations be
4295 removed from a section that does not have relocations then this
4296 function will still return TRUE. */
4298 static bool
4299 discard_relocations (bfd *ibfd ATTRIBUTE_UNUSED, asection *isection)
4301 return (find_section_list (bfd_section_name (isection), false,
4302 SECTION_CONTEXT_REMOVE_RELOCS) != NULL);
4305 /* Wrapper for dealing with --remove-section (-R) command line arguments.
4306 A special case is detected here, if the user asks to remove a relocation
4307 section (one starting with ".rela" or ".rel") then this removal must
4308 be done using a different technique in a relocatable object. */
4310 static void
4311 handle_remove_section_option (const char *section_pattern)
4313 find_section_list (section_pattern, true, SECTION_CONTEXT_REMOVE);
4314 if (startswith (section_pattern, ".rel"))
4316 section_pattern += 4;
4317 if (*section_pattern == 'a')
4318 section_pattern++;
4319 if (*section_pattern)
4320 handle_remove_relocations_option (section_pattern);
4322 sections_removed = true;
4325 /* Copy relocations in input section ISECTION of IBFD to an output
4326 section with the same name in OBFDARG. If stripping then don't
4327 copy any relocation info. */
4329 static void
4330 copy_relocations_in_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
4332 bfd *obfd = (bfd *) obfdarg;
4333 long relsize;
4334 arelent **relpp;
4335 long relcount;
4336 sec_ptr osection;
4338 if (skip_section (ibfd, isection, false))
4339 return;
4341 osection = isection->output_section;
4343 /* Core files and DWO files do not need to be relocated. */
4344 if (bfd_get_format (obfd) == bfd_core
4345 || strip_symbols == STRIP_NONDWO
4346 || discard_relocations (ibfd, isection))
4347 relsize = 0;
4348 else
4350 relsize = bfd_get_reloc_upper_bound (ibfd, isection);
4352 if (relsize < 0)
4354 /* Do not complain if the target does not support relocations. */
4355 if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
4356 relsize = 0;
4357 else
4359 status = 1;
4360 bfd_nonfatal_message (NULL, ibfd, isection, NULL);
4361 return;
4366 if (relsize == 0)
4367 bfd_set_reloc (obfd, osection, NULL, 0);
4368 else
4370 if (isection->orelocation != NULL)
4372 /* Some other function has already set up the output relocs
4373 for us, so scan those instead of the default relocs. */
4374 relcount = isection->reloc_count;
4375 relpp = isection->orelocation;
4377 else
4379 relpp = bfd_xalloc (obfd, relsize);
4380 relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, isympp);
4381 if (relcount < 0)
4383 status = 1;
4384 bfd_nonfatal_message (NULL, ibfd, isection,
4385 _("relocation count is negative"));
4386 return;
4390 if (strip_symbols == STRIP_ALL)
4392 /* Remove relocations which are not in
4393 keep_strip_specific_list. */
4394 arelent **w_relpp;
4395 long i;
4397 for (w_relpp = relpp, i = 0; i < relcount; i++)
4398 /* PR 17512: file: 9e907e0c. */
4399 if (relpp[i]->sym_ptr_ptr
4400 /* PR 20096 */
4401 && *relpp[i]->sym_ptr_ptr
4402 && is_specified_symbol (bfd_asymbol_name (*relpp[i]->sym_ptr_ptr),
4403 keep_specific_htab))
4404 *w_relpp++ = relpp[i];
4405 relcount = w_relpp - relpp;
4406 *w_relpp = 0;
4409 bfd_set_reloc (obfd, osection, relcount == 0 ? NULL : relpp, relcount);
4413 /* Copy the data of input section ISECTION of IBFD
4414 to an output section with the same name in OBFD. */
4416 static void
4417 copy_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
4419 bfd *obfd = (bfd *) obfdarg;
4420 struct section_list *p;
4421 sec_ptr osection;
4422 bfd_size_type size;
4424 if (skip_section (ibfd, isection, true))
4425 return;
4427 osection = isection->output_section;
4428 /* The output SHF_COMPRESSED section size is different from input if
4429 ELF classes of input and output aren't the same. We can't use
4430 the output section size since --interleave will shrink the output
4431 section. Size will be updated if the section is converted. */
4432 size = bfd_section_size (isection);
4434 if (bfd_section_flags (isection) & SEC_HAS_CONTENTS
4435 && bfd_section_flags (osection) & SEC_HAS_CONTENTS)
4437 bfd_byte *memhunk = NULL;
4439 if (!bfd_get_full_section_contents (ibfd, isection, &memhunk)
4440 || !bfd_convert_section_contents (ibfd, isection, obfd,
4441 &memhunk, &size))
4443 bfd_set_section_size (osection, 0);
4444 status = 1;
4445 bfd_nonfatal_message (NULL, ibfd, isection, NULL);
4446 free (memhunk);
4447 return;
4450 if (reverse_bytes)
4452 /* We don't handle leftover bytes (too many possible behaviors,
4453 and we don't know what the user wants). The section length
4454 must be a multiple of the number of bytes to swap. */
4455 if ((size % reverse_bytes) == 0)
4457 unsigned long i, j;
4458 bfd_byte b;
4460 for (i = 0; i < size; i += reverse_bytes)
4461 for (j = 0; j < (unsigned long)(reverse_bytes / 2); j++)
4463 bfd_byte *m = (bfd_byte *) memhunk;
4465 b = m[i + j];
4466 m[i + j] = m[(i + reverse_bytes) - (j + 1)];
4467 m[(i + reverse_bytes) - (j + 1)] = b;
4470 else
4471 /* User must pad the section up in order to do this. */
4472 fatal (_("cannot reverse bytes: length of section %s must be evenly divisible by %d"),
4473 bfd_section_name (isection), reverse_bytes);
4476 if (copy_byte >= 0)
4478 /* Keep only every `copy_byte'th byte in MEMHUNK. */
4479 char *from = (char *) memhunk + copy_byte;
4480 char *to = (char *) memhunk;
4481 char *end = (char *) memhunk + size;
4482 int i;
4484 /* If the section address is not exactly divisible by the interleave,
4485 then we must bias the from address. If the copy_byte is less than
4486 the bias, then we must skip forward one interleave, and increment
4487 the final lma. */
4488 int extra = isection->lma % interleave;
4489 from -= extra;
4490 if (copy_byte < extra)
4491 from += interleave;
4493 for (; from < end; from += interleave)
4494 for (i = 0; i < copy_width; i++)
4496 if (&from[i] >= end)
4497 break;
4498 *to++ = from[i];
4501 size = (size + interleave - 1 - copy_byte) / interleave * copy_width;
4502 osection->lma /= interleave;
4503 if (copy_byte < extra)
4504 osection->lma++;
4507 if (!bfd_set_section_contents (obfd, osection, memhunk, 0, size))
4509 status = 1;
4510 bfd_nonfatal_message (NULL, obfd, osection, NULL);
4511 free (memhunk);
4512 return;
4514 free (memhunk);
4516 else if ((p = find_section_list (bfd_section_name (isection),
4517 false, SECTION_CONTEXT_SET_FLAGS)) != NULL
4518 && (p->flags & SEC_HAS_CONTENTS) != 0)
4520 void *memhunk = xmalloc (size);
4522 /* We don't permit the user to turn off the SEC_HAS_CONTENTS
4523 flag--they can just remove the section entirely and add it
4524 back again. However, we do permit them to turn on the
4525 SEC_HAS_CONTENTS flag, and take it to mean that the section
4526 contents should be zeroed out. */
4528 memset (memhunk, 0, size);
4529 if (! bfd_set_section_contents (obfd, osection, memhunk, 0, size))
4531 status = 1;
4532 bfd_nonfatal_message (NULL, obfd, osection, NULL);
4533 free (memhunk);
4534 return;
4536 free (memhunk);
4540 /* Get all the sections. This is used when --gap-fill or --pad-to is
4541 used. */
4543 static void
4544 get_sections (bfd *obfd ATTRIBUTE_UNUSED, asection *osection, void *secppparg)
4546 asection ***secppp = (asection ***) secppparg;
4548 **secppp = osection;
4549 ++(*secppp);
4552 /* Sort sections by LMA. This is called via qsort, and is used when
4553 --gap-fill or --pad-to is used. We force non loadable or empty
4554 sections to the front, where they are easier to ignore. */
4556 static int
4557 compare_section_lma (const void *arg1, const void *arg2)
4559 const asection *sec1 = *(const asection **) arg1;
4560 const asection *sec2 = *(const asection **) arg2;
4561 flagword flags1, flags2;
4563 /* Sort non loadable sections to the front. */
4564 flags1 = sec1->flags;
4565 flags2 = sec2->flags;
4566 if ((flags1 & SEC_HAS_CONTENTS) == 0
4567 || (flags1 & SEC_LOAD) == 0)
4569 if ((flags2 & SEC_HAS_CONTENTS) != 0
4570 && (flags2 & SEC_LOAD) != 0)
4571 return -1;
4573 else
4575 if ((flags2 & SEC_HAS_CONTENTS) == 0
4576 || (flags2 & SEC_LOAD) == 0)
4577 return 1;
4580 /* Sort sections by LMA. */
4581 if (sec1->lma > sec2->lma)
4582 return 1;
4583 if (sec1->lma < sec2->lma)
4584 return -1;
4586 /* Sort sections with the same LMA by size. */
4587 if (bfd_section_size (sec1) > bfd_section_size (sec2))
4588 return 1;
4589 if (bfd_section_size (sec1) < bfd_section_size (sec2))
4590 return -1;
4592 if (sec1->id > sec2->id)
4593 return 1;
4594 if (sec1->id < sec2->id)
4595 return -1;
4596 return 0;
4599 /* Mark all the symbols which will be used in output relocations with
4600 the BSF_KEEP flag so that those symbols will not be stripped.
4602 Ignore relocations which will not appear in the output file. */
4604 static void
4605 mark_symbols_used_in_relocations (bfd *ibfd, sec_ptr isection, void *symbolsarg)
4607 asymbol **symbols = (asymbol **) symbolsarg;
4608 long relsize;
4609 arelent **relpp;
4610 long relcount, i;
4612 /* Ignore an input section with no corresponding output section. */
4613 if (isection->output_section == NULL)
4614 return;
4616 relsize = bfd_get_reloc_upper_bound (ibfd, isection);
4617 if (relsize < 0)
4619 /* Do not complain if the target does not support relocations. */
4620 if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
4621 return;
4622 bfd_fatal (bfd_get_filename (ibfd));
4625 if (relsize == 0)
4626 return;
4628 relpp = (arelent **) xmalloc (relsize);
4629 relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, symbols);
4630 if (relcount < 0)
4631 bfd_fatal (bfd_get_filename (ibfd));
4633 /* Examine each symbol used in a relocation. If it's not one of the
4634 special bfd section symbols, then mark it with BSF_KEEP. */
4635 for (i = 0; i < relcount; i++)
4637 /* See PRs 20923 and 20930 for reproducers for the NULL tests. */
4638 if (relpp[i]->sym_ptr_ptr != NULL
4639 && * relpp[i]->sym_ptr_ptr != NULL
4640 && *relpp[i]->sym_ptr_ptr != bfd_com_section_ptr->symbol
4641 && *relpp[i]->sym_ptr_ptr != bfd_abs_section_ptr->symbol
4642 && *relpp[i]->sym_ptr_ptr != bfd_und_section_ptr->symbol)
4643 (*relpp[i]->sym_ptr_ptr)->flags |= BSF_KEEP;
4646 free (relpp);
4649 /* Write out debugging information. */
4651 static bool
4652 write_debugging_info (bfd *obfd, void *dhandle,
4653 long *symcountp ATTRIBUTE_UNUSED,
4654 asymbol ***symppp ATTRIBUTE_UNUSED)
4656 if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
4657 || bfd_get_flavour (obfd) == bfd_target_elf_flavour)
4659 bfd_byte *syms, *strings = NULL;
4660 bfd_size_type symsize, stringsize;
4661 asection *stabsec, *stabstrsec;
4662 flagword flags;
4663 bool ret;
4665 if (! write_stabs_in_sections_debugging_info (obfd, dhandle, &syms,
4666 &symsize, &strings,
4667 &stringsize))
4668 return false;
4670 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DEBUGGING;
4671 stabsec = bfd_make_section_with_flags (obfd, ".stab", flags);
4672 stabstrsec = bfd_make_section_with_flags (obfd, ".stabstr", flags);
4673 ret = true;
4674 if (stabsec == NULL
4675 || stabstrsec == NULL
4676 || !bfd_set_section_size (stabsec, symsize)
4677 || !bfd_set_section_size (stabstrsec, stringsize)
4678 || !bfd_set_section_alignment (stabsec, 2)
4679 || !bfd_set_section_alignment (stabstrsec, 0))
4681 bfd_nonfatal_message (NULL, obfd, NULL,
4682 _("can't create debugging section"));
4683 ret = false;
4686 /* We can get away with setting the section contents now because
4687 the next thing the caller is going to do is copy over the
4688 real sections. We may someday have to split the contents
4689 setting out of this function. */
4690 if (ret
4691 && (!bfd_set_section_contents (obfd, stabsec, syms, 0, symsize)
4692 || !bfd_set_section_contents (obfd, stabstrsec, strings, 0,
4693 stringsize)))
4695 bfd_nonfatal_message (NULL, obfd, NULL,
4696 _("can't set debugging section contents"));
4697 ret = false;
4700 free (strings);
4701 free (syms);
4702 return ret;
4705 bfd_nonfatal_message (NULL, obfd, NULL,
4706 _("don't know how to write debugging information for %s"),
4707 bfd_get_target (obfd));
4708 return false;
4711 /* If neither -D nor -U was specified explicitly,
4712 then use the configured default. */
4713 static void
4714 default_deterministic (void)
4716 if (deterministic < 0)
4717 deterministic = DEFAULT_AR_DETERMINISTIC;
4720 static int
4721 strip_main (int argc, char *argv[])
4723 char *input_target = NULL;
4724 char *output_target = NULL;
4725 bool show_version = false;
4726 bool formats_info = false;
4727 int c;
4728 int i;
4729 char *output_file = NULL;
4730 bool merge_notes_set = false;
4732 while ((c = getopt_long (argc, argv, "I:O:F:K:MN:R:o:sSpdgxXHhVvwDU",
4733 strip_options, (int *) 0)) != EOF)
4735 switch (c)
4737 case 'I':
4738 input_target = optarg;
4739 break;
4740 case 'O':
4741 output_target = optarg;
4742 break;
4743 case 'F':
4744 input_target = output_target = optarg;
4745 break;
4746 case 'R':
4747 handle_remove_section_option (optarg);
4748 break;
4749 case OPTION_KEEP_SECTION:
4750 find_section_list (optarg, true, SECTION_CONTEXT_KEEP);
4751 break;
4752 case OPTION_REMOVE_RELOCS:
4753 handle_remove_relocations_option (optarg);
4754 break;
4755 case 's':
4756 strip_symbols = STRIP_ALL;
4757 break;
4758 case 'S':
4759 case 'g':
4760 case 'd': /* Historic BSD alias for -g. Used by early NetBSD. */
4761 strip_symbols = STRIP_DEBUG;
4762 break;
4763 case OPTION_STRIP_DWO:
4764 strip_symbols = STRIP_DWO;
4765 break;
4766 case OPTION_STRIP_UNNEEDED:
4767 strip_symbols = STRIP_UNNEEDED;
4768 break;
4769 case 'K':
4770 add_specific_symbol (optarg, keep_specific_htab);
4771 break;
4772 case 'M':
4773 merge_notes = true;
4774 merge_notes_set = true;
4775 break;
4776 case OPTION_NO_MERGE_NOTES:
4777 merge_notes = false;
4778 merge_notes_set = true;
4779 break;
4780 case 'N':
4781 add_specific_symbol (optarg, strip_specific_htab);
4782 break;
4783 case 'o':
4784 output_file = optarg;
4785 break;
4786 case 'p':
4787 preserve_dates = true;
4788 break;
4789 case 'D':
4790 deterministic = true;
4791 break;
4792 case 'U':
4793 deterministic = false;
4794 break;
4795 case 'x':
4796 discard_locals = LOCALS_ALL;
4797 break;
4798 case 'X':
4799 discard_locals = LOCALS_START_L;
4800 break;
4801 case 'v':
4802 verbose = true;
4803 break;
4804 case 'V':
4805 show_version = true;
4806 break;
4807 case OPTION_FORMATS_INFO:
4808 formats_info = true;
4809 break;
4810 case OPTION_ONLY_KEEP_DEBUG:
4811 strip_symbols = STRIP_NONDEBUG;
4812 break;
4813 case OPTION_KEEP_FILE_SYMBOLS:
4814 keep_file_symbols = 1;
4815 break;
4816 case OPTION_KEEP_SECTION_SYMBOLS:
4817 keep_section_symbols = true;
4818 break;
4819 case 0:
4820 /* We've been given a long option. */
4821 break;
4822 case 'w':
4823 wildcard = true;
4824 break;
4825 case 'H':
4826 case 'h':
4827 strip_usage (stdout, 0);
4828 default:
4829 strip_usage (stderr, 1);
4833 /* If the user has not expressly chosen to merge/not-merge ELF notes
4834 then enable the merging unless we are stripping debug or dwo info. */
4835 if (! merge_notes_set
4836 && (strip_symbols == STRIP_UNDEF
4837 || strip_symbols == STRIP_ALL
4838 || strip_symbols == STRIP_UNNEEDED
4839 || strip_symbols == STRIP_NONDEBUG
4840 || strip_symbols == STRIP_NONDWO))
4841 merge_notes = true;
4843 if (formats_info)
4845 display_info ();
4846 return 0;
4849 if (show_version)
4850 print_version ("strip");
4852 default_deterministic ();
4854 /* Default is to strip all symbols. */
4855 if (strip_symbols == STRIP_UNDEF
4856 && discard_locals == LOCALS_UNDEF
4857 && htab_elements (strip_specific_htab) == 0)
4858 strip_symbols = STRIP_ALL;
4860 if (output_target == NULL)
4861 output_target = input_target;
4863 i = optind;
4864 if (i == argc
4865 || (output_file != NULL && (i + 1) < argc))
4866 strip_usage (stderr, 1);
4868 for (; i < argc; i++)
4870 int hold_status = status;
4871 struct stat statbuf;
4872 char *tmpname;
4873 int tmpfd = -1;
4874 int copyfd = -1;
4876 if (get_file_size (argv[i]) < 1)
4878 status = 1;
4879 continue;
4882 if (output_file == NULL
4883 || filename_cmp (argv[i], output_file) == 0)
4885 tmpname = make_tempname (argv[i], &tmpfd);
4886 if (tmpfd >= 0)
4887 copyfd = dup (tmpfd);
4889 else
4890 tmpname = output_file;
4892 if (tmpname == NULL)
4894 bfd_nonfatal_message (argv[i], NULL, NULL,
4895 _("could not create temporary file to hold stripped copy"));
4896 status = 1;
4897 continue;
4900 status = 0;
4901 copy_file (argv[i], tmpname, tmpfd, &statbuf, input_target,
4902 output_target, NULL);
4903 if (status == 0)
4905 const char *oname = output_file ? output_file : argv[i];
4906 status = smart_rename (tmpname, oname, copyfd,
4907 &statbuf, preserve_dates) != 0;
4908 if (status == 0)
4909 status = hold_status;
4911 else
4913 if (copyfd >= 0)
4914 close (copyfd);
4915 unlink_if_ordinary (tmpname);
4917 if (output_file != tmpname)
4918 free (tmpname);
4921 return status;
4924 /* Set up PE subsystem. */
4926 static void
4927 set_pe_subsystem (const char *s)
4929 const char *version, *subsystem;
4930 size_t i;
4931 static const struct
4933 const char *name;
4934 const char set_def;
4935 const short value;
4937 v[] =
4939 { "native", 0, IMAGE_SUBSYSTEM_NATIVE },
4940 { "windows", 0, IMAGE_SUBSYSTEM_WINDOWS_GUI },
4941 { "console", 0, IMAGE_SUBSYSTEM_WINDOWS_CUI },
4942 { "posix", 0, IMAGE_SUBSYSTEM_POSIX_CUI },
4943 { "wince", 0, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI },
4944 { "efi-app", 1, IMAGE_SUBSYSTEM_EFI_APPLICATION },
4945 { "efi-bsd", 1, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER },
4946 { "efi-rtd", 1, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER },
4947 { "sal-rtd", 1, IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER },
4948 { "xbox", 0, IMAGE_SUBSYSTEM_XBOX }
4950 short value;
4951 char *copy;
4952 int set_def = -1;
4954 /* Check for the presence of a version number. */
4955 version = strchr (s, ':');
4956 if (version == NULL)
4957 subsystem = s;
4958 else
4960 int len = version - s;
4961 copy = xstrdup (s);
4962 subsystem = copy;
4963 copy[len] = '\0';
4964 version = copy + 1 + len;
4965 pe_major_subsystem_version = strtoul (version, &copy, 0);
4966 if (*copy == '.')
4967 pe_minor_subsystem_version = strtoul (copy + 1, &copy, 0);
4968 if (*copy != '\0')
4969 non_fatal (_("%s: bad version in PE subsystem"), s);
4972 /* Check for numeric subsystem. */
4973 value = (short) strtol (subsystem, &copy, 0);
4974 if (*copy == '\0')
4976 for (i = 0; i < ARRAY_SIZE (v); i++)
4977 if (v[i].value == value)
4979 pe_subsystem = value;
4980 set_def = v[i].set_def;
4981 break;
4984 else
4986 /* Search for subsystem by name. */
4987 for (i = 0; i < ARRAY_SIZE (v); i++)
4988 if (strcmp (subsystem, v[i].name) == 0)
4990 pe_subsystem = v[i].value;
4991 set_def = v[i].set_def;
4992 break;
4996 switch (set_def)
4998 case -1:
4999 fatal (_("unknown PE subsystem: %s"), s);
5000 break;
5001 case 0:
5002 break;
5003 default:
5004 if (pe_file_alignment == (bfd_vma) -1)
5005 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
5006 if (pe_section_alignment == (bfd_vma) -1)
5007 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
5008 break;
5010 if (s != subsystem)
5011 free ((char *) subsystem);
5014 /* Convert EFI target to PEI target. */
5016 static int
5017 convert_efi_target (char **targ)
5019 size_t len;
5020 char *pei;
5021 char *efi = *targ + 4;
5022 int subsys = -1;
5024 if (startswith (efi, "app-"))
5025 subsys = IMAGE_SUBSYSTEM_EFI_APPLICATION;
5026 else if (startswith (efi, "bsdrv-"))
5028 subsys = IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
5029 efi += 2;
5031 else if (startswith (efi, "rtdrv-"))
5033 subsys = IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER;
5034 efi += 2;
5036 else
5037 return subsys;
5039 len = strlen (efi);
5040 pei = xmalloc (len + sizeof ("-little"));
5041 memcpy (pei, efi, len + 1);
5042 pei[0] = 'p';
5043 pei[1] = 'e';
5044 pei[2] = 'i';
5046 if (strcmp (efi + 4, "ia32") == 0)
5048 /* Change ia32 to i386. */
5049 pei[5]= '3';
5050 pei[6]= '8';
5051 pei[7]= '6';
5053 else if (strcmp (efi + 4, "x86_64") == 0)
5055 /* Change x86_64 to x86-64. */
5056 pei[7] = '-';
5058 else if (strcmp (efi + 4, "aarch64") == 0)
5060 /* Change aarch64 to aarch64-little. */
5061 memcpy (pei + 4 + sizeof ("aarch64") - 1, "-little", sizeof ("-little"));
5063 *targ = pei;
5064 return subsys;
5067 /* Allocate and return a pointer to a struct section_add, initializing the
5068 structure using ARG, a string in the format "sectionname=filename".
5069 The returned structure will have its next pointer set to NEXT. The
5070 OPTION field is the name of the command line option currently being
5071 parsed, and is only used if an error needs to be reported. */
5073 static struct section_add *
5074 init_section_add (const char *arg,
5075 struct section_add *next,
5076 const char *option)
5078 struct section_add *pa;
5079 const char *s;
5081 s = strchr (arg, '=');
5082 if (s == NULL)
5083 fatal (_("bad format for %s"), option);
5085 pa = (struct section_add *) xmalloc (sizeof (struct section_add));
5086 pa->name = xstrndup (arg, s - arg);
5087 pa->filename = s + 1;
5088 pa->next = next;
5089 pa->contents = NULL;
5090 pa->size = 0;
5092 return pa;
5095 /* Load the file specified in PA, allocating memory to hold the file
5096 contents, and store a pointer to the allocated memory in the contents
5097 field of PA. The size field of PA is also updated. All errors call
5098 FATAL. */
5100 static void
5101 section_add_load_file (struct section_add *pa)
5103 size_t off, alloc;
5104 FILE *f;
5106 /* We don't use get_file_size so that we can do
5107 --add-section .note.GNU_stack=/dev/null
5108 get_file_size doesn't work on /dev/null. */
5110 f = fopen (pa->filename, FOPEN_RB);
5111 if (f == NULL)
5112 fatal (_("cannot open: %s: %s"),
5113 pa->filename, strerror (errno));
5115 off = 0;
5116 alloc = 4096;
5117 pa->contents = (bfd_byte *) xmalloc (alloc);
5118 while (!feof (f))
5120 off_t got;
5122 if (off == alloc)
5124 alloc <<= 1;
5125 pa->contents = (bfd_byte *) xrealloc (pa->contents, alloc);
5128 got = fread (pa->contents + off, 1, alloc - off, f);
5129 if (ferror (f))
5130 fatal (_("%s: fread failed"), pa->filename);
5132 off += got;
5135 pa->size = off;
5137 fclose (f);
5140 static int
5141 copy_main (int argc, char *argv[])
5143 char *input_filename = NULL;
5144 char *output_filename = NULL;
5145 char *tmpname;
5146 char *input_target = NULL;
5147 char *output_target = NULL;
5148 bool show_version = false;
5149 bool change_warn = true;
5150 bool formats_info = false;
5151 bool use_globalize = false;
5152 bool use_keep_global = false;
5153 int c;
5154 int tmpfd = -1;
5155 int copyfd;
5156 struct stat statbuf;
5157 const bfd_arch_info_type *input_arch = NULL;
5159 while ((c = getopt_long (argc, argv, "b:B:i:I:j:K:MN:s:O:d:F:L:G:R:SpgxXHhVvW:wDU",
5160 copy_options, (int *) 0)) != EOF)
5162 switch (c)
5164 case 'b':
5165 copy_byte = atoi (optarg);
5166 if (copy_byte < 0)
5167 fatal (_("byte number must be non-negative"));
5168 break;
5170 case 'B':
5171 input_arch = bfd_scan_arch (optarg);
5172 if (input_arch == NULL)
5173 fatal (_("architecture %s unknown"), optarg);
5174 break;
5176 case 'i':
5177 if (optarg)
5179 interleave = atoi (optarg);
5180 if (interleave < 1)
5181 fatal (_("interleave must be positive"));
5183 else
5184 interleave = 4;
5185 break;
5187 case OPTION_INTERLEAVE_WIDTH:
5188 copy_width = atoi (optarg);
5189 if (copy_width < 1)
5190 fatal(_("interleave width must be positive"));
5191 break;
5193 case 'I':
5194 case 's': /* "source" - 'I' is preferred */
5195 input_target = optarg;
5196 break;
5198 case 'O':
5199 case 'd': /* "destination" - 'O' is preferred */
5200 output_target = optarg;
5201 break;
5203 case 'F':
5204 input_target = output_target = optarg;
5205 break;
5207 case 'j':
5208 find_section_list (optarg, true, SECTION_CONTEXT_COPY);
5209 sections_copied = true;
5210 break;
5212 case 'R':
5213 handle_remove_section_option (optarg);
5214 break;
5216 case OPTION_KEEP_SECTION:
5217 find_section_list (optarg, true, SECTION_CONTEXT_KEEP);
5218 break;
5220 case OPTION_REMOVE_RELOCS:
5221 handle_remove_relocations_option (optarg);
5222 break;
5224 case 'S':
5225 strip_symbols = STRIP_ALL;
5226 break;
5228 case 'g':
5229 strip_symbols = STRIP_DEBUG;
5230 break;
5232 case OPTION_STRIP_DWO:
5233 strip_symbols = STRIP_DWO;
5234 break;
5236 case OPTION_STRIP_UNNEEDED:
5237 strip_symbols = STRIP_UNNEEDED;
5238 break;
5240 case OPTION_ONLY_KEEP_DEBUG:
5241 strip_symbols = STRIP_NONDEBUG;
5242 break;
5244 case OPTION_KEEP_FILE_SYMBOLS:
5245 keep_file_symbols = 1;
5246 break;
5248 case OPTION_ADD_GNU_DEBUGLINK:
5249 long_section_names = ENABLE ;
5250 gnu_debuglink_filename = optarg;
5251 break;
5253 case 'K':
5254 add_specific_symbol (optarg, keep_specific_htab);
5255 break;
5257 case 'M':
5258 merge_notes = true;
5259 break;
5260 case OPTION_NO_MERGE_NOTES:
5261 merge_notes = false;
5262 break;
5264 case 'N':
5265 add_specific_symbol (optarg, strip_specific_htab);
5266 break;
5268 case OPTION_STRIP_UNNEEDED_SYMBOL:
5269 add_specific_symbol (optarg, strip_unneeded_htab);
5270 break;
5272 case 'L':
5273 add_specific_symbol (optarg, localize_specific_htab);
5274 break;
5276 case OPTION_GLOBALIZE_SYMBOL:
5277 use_globalize = true;
5278 add_specific_symbol (optarg, globalize_specific_htab);
5279 break;
5281 case 'G':
5282 use_keep_global = true;
5283 add_specific_symbol (optarg, keepglobal_specific_htab);
5284 break;
5286 case 'W':
5287 add_specific_symbol (optarg, weaken_specific_htab);
5288 break;
5290 case 'p':
5291 preserve_dates = true;
5292 break;
5294 case 'D':
5295 deterministic = true;
5296 break;
5298 case 'U':
5299 deterministic = false;
5300 break;
5302 case 'w':
5303 wildcard = true;
5304 break;
5306 case 'x':
5307 discard_locals = LOCALS_ALL;
5308 break;
5310 case 'X':
5311 discard_locals = LOCALS_START_L;
5312 break;
5314 case 'v':
5315 verbose = true;
5316 break;
5318 case 'V':
5319 show_version = true;
5320 break;
5322 case OPTION_FORMATS_INFO:
5323 formats_info = true;
5324 break;
5326 case OPTION_WEAKEN:
5327 weaken = true;
5328 break;
5330 case OPTION_ADD_SECTION:
5331 add_sections = init_section_add (optarg, add_sections,
5332 "--add-section");
5333 section_add_load_file (add_sections);
5334 break;
5336 case OPTION_UPDATE_SECTION:
5337 update_sections = init_section_add (optarg, update_sections,
5338 "--update-section");
5339 section_add_load_file (update_sections);
5340 break;
5342 case OPTION_DUMP_SECTION:
5343 dump_sections = init_section_add (optarg, dump_sections,
5344 "--dump-section");
5345 break;
5347 case OPTION_ADD_SYMBOL:
5349 char *s, *t;
5350 struct addsym_node *newsym = xmalloc (sizeof *newsym);
5352 newsym->next = NULL;
5353 s = strchr (optarg, '=');
5354 if (s == NULL)
5355 fatal (_("bad format for %s"), "--add-symbol");
5356 t = strchr (s + 1, ':');
5358 newsym->symdef = xstrndup (optarg, s - optarg);
5359 if (t)
5361 newsym->section = xstrndup (s + 1, t - (s + 1));
5362 newsym->symval = strtol (t + 1, NULL, 0);
5364 else
5366 newsym->section = NULL;
5367 newsym->symval = strtol (s + 1, NULL, 0);
5368 t = s;
5371 t = strchr (t + 1, ',');
5372 newsym->othersym = NULL;
5373 if (t)
5374 newsym->flags = parse_symflags (t+1, &newsym->othersym);
5375 else
5376 newsym->flags = BSF_GLOBAL;
5378 /* Keep 'othersym' symbols at the front of the list. */
5379 if (newsym->othersym)
5381 newsym->next = add_sym_list;
5382 if (!add_sym_list)
5383 add_sym_tail = &newsym->next;
5384 add_sym_list = newsym;
5386 else
5388 *add_sym_tail = newsym;
5389 add_sym_tail = &newsym->next;
5391 add_symbols++;
5393 break;
5395 case OPTION_CHANGE_START:
5396 change_start = parse_vma (optarg, "--change-start");
5397 break;
5399 case OPTION_CHANGE_SECTION_ADDRESS:
5400 case OPTION_CHANGE_SECTION_LMA:
5401 case OPTION_CHANGE_SECTION_VMA:
5403 struct section_list * p;
5404 unsigned int context = 0;
5405 const char *s;
5406 int len;
5407 char *name;
5408 char *option = NULL;
5409 bfd_vma val;
5411 switch (c)
5413 case OPTION_CHANGE_SECTION_ADDRESS:
5414 option = "--change-section-address";
5415 context = SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_ALTER_VMA;
5416 break;
5417 case OPTION_CHANGE_SECTION_LMA:
5418 option = "--change-section-lma";
5419 context = SECTION_CONTEXT_ALTER_LMA;
5420 break;
5421 case OPTION_CHANGE_SECTION_VMA:
5422 option = "--change-section-vma";
5423 context = SECTION_CONTEXT_ALTER_VMA;
5424 break;
5427 s = strchr (optarg, '=');
5428 if (s == NULL)
5430 s = strchr (optarg, '+');
5431 if (s == NULL)
5433 s = strchr (optarg, '-');
5434 if (s == NULL)
5435 fatal (_("bad format for %s"), option);
5438 else
5440 /* Correct the context. */
5441 switch (c)
5443 case OPTION_CHANGE_SECTION_ADDRESS:
5444 context = SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_SET_VMA;
5445 break;
5446 case OPTION_CHANGE_SECTION_LMA:
5447 context = SECTION_CONTEXT_SET_LMA;
5448 break;
5449 case OPTION_CHANGE_SECTION_VMA:
5450 context = SECTION_CONTEXT_SET_VMA;
5451 break;
5455 len = s - optarg;
5456 name = (char *) xmalloc (len + 1);
5457 strncpy (name, optarg, len);
5458 name[len] = '\0';
5460 p = find_section_list (name, true, context);
5462 val = parse_vma (s + 1, option);
5463 if (*s == '-')
5464 val = - val;
5466 switch (c)
5468 case OPTION_CHANGE_SECTION_ADDRESS:
5469 p->vma_val = val;
5470 /* Fall through. */
5472 case OPTION_CHANGE_SECTION_LMA:
5473 p->lma_val = val;
5474 break;
5476 case OPTION_CHANGE_SECTION_VMA:
5477 p->vma_val = val;
5478 break;
5481 break;
5483 case OPTION_CHANGE_ADDRESSES:
5484 change_section_address = parse_vma (optarg, "--change-addresses");
5485 change_start = change_section_address;
5486 break;
5488 case OPTION_CHANGE_WARNINGS:
5489 change_warn = true;
5490 break;
5492 case OPTION_CHANGE_LEADING_CHAR:
5493 change_leading_char = true;
5494 break;
5496 case OPTION_COMPRESS_DEBUG_SECTIONS:
5497 if (optarg)
5499 if (strcasecmp (optarg, "none") == 0)
5500 do_debug_sections = decompress;
5501 else if (strcasecmp (optarg, "zlib") == 0)
5502 do_debug_sections = compress_zlib;
5503 else if (strcasecmp (optarg, "zlib-gnu") == 0)
5504 do_debug_sections = compress_gnu_zlib;
5505 else if (strcasecmp (optarg, "zlib-gabi") == 0)
5506 do_debug_sections = compress_gabi_zlib;
5507 else if (strcasecmp (optarg, "zstd") == 0)
5508 do_debug_sections = compress_zstd;
5509 else
5510 fatal (_("unrecognized --compress-debug-sections type `%s'"),
5511 optarg);
5513 else
5514 do_debug_sections = compress;
5515 break;
5517 case OPTION_DEBUGGING:
5518 convert_debugging = true;
5519 break;
5521 case OPTION_DECOMPRESS_DEBUG_SECTIONS:
5522 do_debug_sections = decompress;
5523 break;
5525 case OPTION_ELF_STT_COMMON:
5526 if (strcasecmp (optarg, "yes") == 0)
5527 do_elf_stt_common = elf_stt_common;
5528 else if (strcasecmp (optarg, "no") == 0)
5529 do_elf_stt_common = no_elf_stt_common;
5530 else
5531 fatal (_("unrecognized --elf-stt-common= option `%s'"),
5532 optarg);
5533 break;
5535 case OPTION_GAP_FILL:
5537 bfd_vma gap_fill_vma;
5539 gap_fill_vma = parse_vma (optarg, "--gap-fill");
5540 gap_fill = (bfd_byte) gap_fill_vma;
5541 if ((bfd_vma) gap_fill != gap_fill_vma)
5542 non_fatal (_("Warning: truncating gap-fill from 0x%" PRIx64
5543 " to 0x%x"),
5544 (uint64_t) gap_fill_vma, gap_fill);
5545 gap_fill_set = true;
5547 break;
5549 case OPTION_NO_CHANGE_WARNINGS:
5550 change_warn = false;
5551 break;
5553 case OPTION_PAD_TO:
5554 pad_to = parse_vma (optarg, "--pad-to");
5555 pad_to_set = true;
5556 break;
5558 case OPTION_REMOVE_LEADING_CHAR:
5559 remove_leading_char = true;
5560 break;
5562 case OPTION_REDEFINE_SYM:
5564 /* Insert this redefinition onto redefine_specific_htab. */
5566 int len;
5567 const char *s;
5568 const char *nextarg;
5569 char *source, *target;
5571 s = strchr (optarg, '=');
5572 if (s == NULL)
5573 fatal (_("bad format for %s"), "--redefine-sym");
5575 len = s - optarg;
5576 source = (char *) xmalloc (len + 1);
5577 strncpy (source, optarg, len);
5578 source[len] = '\0';
5580 nextarg = s + 1;
5581 len = strlen (nextarg);
5582 target = (char *) xmalloc (len + 1);
5583 strcpy (target, nextarg);
5585 add_redefine_and_check ("--redefine-sym", source, target);
5587 free (source);
5588 free (target);
5590 break;
5592 case OPTION_REDEFINE_SYMS:
5593 add_redefine_syms_file (optarg);
5594 break;
5596 case OPTION_SET_SECTION_FLAGS:
5598 struct section_list *p;
5599 const char *s;
5600 int len;
5601 char *name;
5603 s = strchr (optarg, '=');
5604 if (s == NULL)
5605 fatal (_("bad format for %s"), "--set-section-flags");
5607 len = s - optarg;
5608 name = (char *) xmalloc (len + 1);
5609 strncpy (name, optarg, len);
5610 name[len] = '\0';
5612 p = find_section_list (name, true, SECTION_CONTEXT_SET_FLAGS);
5614 p->flags = parse_flags (s + 1);
5616 break;
5618 case OPTION_SET_SECTION_ALIGNMENT:
5620 struct section_list *p;
5621 const char *s;
5622 int len;
5623 char *name;
5624 int palign, align;
5626 s = strchr (optarg, '=');
5627 if (s == NULL)
5628 fatal (_("bad format for --set-section-alignment: argument needed"));
5630 align = atoi (s + 1);
5631 if (align <= 0)
5632 fatal (_("bad format for --set-section-alignment: numeric argument needed"));
5634 /* Convert integer alignment into a power-of-two alignment. */
5635 palign = 0;
5636 while ((align & 1) == 0)
5638 align >>= 1;
5639 ++palign;
5642 if (align != 1)
5643 /* Number has more than on 1, i.e. wasn't a power of 2. */
5644 fatal (_("bad format for --set-section-alignment: alignment is not a power of two"));
5646 /* Add the alignment setting to the section list. */
5647 len = s - optarg;
5648 name = (char *) xmalloc (len + 1);
5649 strncpy (name, optarg, len);
5650 name[len] = '\0';
5652 p = find_section_list (name, true, SECTION_CONTEXT_SET_ALIGNMENT);
5653 if (p)
5654 p->alignment = palign;
5656 break;
5658 case OPTION_RENAME_SECTION:
5660 flagword flags;
5661 const char *eq, *fl;
5662 char *old_name;
5663 char *new_name;
5664 unsigned int len;
5666 eq = strchr (optarg, '=');
5667 if (eq == NULL)
5668 fatal (_("bad format for %s"), "--rename-section");
5670 len = eq - optarg;
5671 if (len == 0)
5672 fatal (_("bad format for %s"), "--rename-section");
5674 old_name = (char *) xmalloc (len + 1);
5675 strncpy (old_name, optarg, len);
5676 old_name[len] = 0;
5678 eq++;
5679 fl = strchr (eq, ',');
5680 if (fl)
5682 flags = parse_flags (fl + 1);
5683 len = fl - eq;
5685 else
5687 flags = -1;
5688 len = strlen (eq);
5691 if (len == 0)
5692 fatal (_("bad format for %s"), "--rename-section");
5694 new_name = (char *) xmalloc (len + 1);
5695 strncpy (new_name, eq, len);
5696 new_name[len] = 0;
5698 add_section_rename (old_name, new_name, flags);
5700 break;
5702 case OPTION_SET_START:
5703 set_start = parse_vma (optarg, "--set-start");
5704 set_start_set = true;
5705 break;
5707 case OPTION_SREC_LEN:
5708 _bfd_srec_len = parse_vma (optarg, "--srec-len");
5709 break;
5711 case OPTION_SREC_FORCES3:
5712 _bfd_srec_forceS3 = true;
5713 break;
5715 case OPTION_STRIP_SYMBOLS:
5716 add_specific_symbols (optarg, strip_specific_htab,
5717 &strip_specific_buffer);
5718 break;
5720 case OPTION_STRIP_UNNEEDED_SYMBOLS:
5721 add_specific_symbols (optarg, strip_unneeded_htab,
5722 &strip_unneeded_buffer);
5723 break;
5725 case OPTION_KEEP_SYMBOLS:
5726 add_specific_symbols (optarg, keep_specific_htab,
5727 &keep_specific_buffer);
5728 break;
5730 case OPTION_KEEP_SECTION_SYMBOLS:
5731 keep_section_symbols = true;
5732 break;
5734 case OPTION_LOCALIZE_HIDDEN:
5735 localize_hidden = true;
5736 break;
5738 case OPTION_LOCALIZE_SYMBOLS:
5739 add_specific_symbols (optarg, localize_specific_htab,
5740 &localize_specific_buffer);
5741 break;
5743 case OPTION_LONG_SECTION_NAMES:
5744 if (!strcmp ("enable", optarg))
5745 long_section_names = ENABLE;
5746 else if (!strcmp ("disable", optarg))
5747 long_section_names = DISABLE;
5748 else if (!strcmp ("keep", optarg))
5749 long_section_names = KEEP;
5750 else
5751 fatal (_("unknown long section names option '%s'"), optarg);
5752 break;
5754 case OPTION_GLOBALIZE_SYMBOLS:
5755 use_globalize = true;
5756 add_specific_symbols (optarg, globalize_specific_htab,
5757 &globalize_specific_buffer);
5758 break;
5760 case OPTION_KEEPGLOBAL_SYMBOLS:
5761 use_keep_global = true;
5762 add_specific_symbols (optarg, keepglobal_specific_htab,
5763 &keepglobal_specific_buffer);
5764 break;
5766 case OPTION_WEAKEN_SYMBOLS:
5767 add_specific_symbols (optarg, weaken_specific_htab,
5768 &weaken_specific_buffer);
5769 break;
5771 case OPTION_ALT_MACH_CODE:
5772 use_alt_mach_code = strtoul (optarg, NULL, 0);
5773 if (use_alt_mach_code == 0)
5774 fatal (_("unable to parse alternative machine code"));
5775 break;
5777 case OPTION_PREFIX_SYMBOLS:
5778 prefix_symbols_string = optarg;
5779 break;
5781 case OPTION_PREFIX_SECTIONS:
5782 prefix_sections_string = optarg;
5783 break;
5785 case OPTION_PREFIX_ALLOC_SECTIONS:
5786 prefix_alloc_sections_string = optarg;
5787 break;
5789 case OPTION_READONLY_TEXT:
5790 bfd_flags_to_set |= WP_TEXT;
5791 bfd_flags_to_clear &= ~WP_TEXT;
5792 break;
5794 case OPTION_WRITABLE_TEXT:
5795 bfd_flags_to_clear |= WP_TEXT;
5796 bfd_flags_to_set &= ~WP_TEXT;
5797 break;
5799 case OPTION_PURE:
5800 bfd_flags_to_set |= D_PAGED;
5801 bfd_flags_to_clear &= ~D_PAGED;
5802 break;
5804 case OPTION_IMPURE:
5805 bfd_flags_to_clear |= D_PAGED;
5806 bfd_flags_to_set &= ~D_PAGED;
5807 break;
5809 case OPTION_EXTRACT_DWO:
5810 strip_symbols = STRIP_NONDWO;
5811 break;
5813 case OPTION_EXTRACT_SYMBOL:
5814 extract_symbol = true;
5815 break;
5817 case OPTION_REVERSE_BYTES:
5819 int prev = reverse_bytes;
5821 reverse_bytes = atoi (optarg);
5822 if ((reverse_bytes <= 0) || ((reverse_bytes % 2) != 0))
5823 fatal (_("number of bytes to reverse must be positive and even"));
5825 if (prev && prev != reverse_bytes)
5826 non_fatal (_("Warning: ignoring previous --reverse-bytes value of %d"),
5827 prev);
5828 break;
5831 case OPTION_FILE_ALIGNMENT:
5832 pe_file_alignment = parse_vma (optarg, "--file-alignment");
5833 break;
5835 case OPTION_HEAP:
5837 char *end;
5838 pe_heap_reserve = strtoul (optarg, &end, 0);
5839 if (end == optarg
5840 || (*end != '.' && *end != '\0'))
5841 non_fatal (_("%s: invalid reserve value for --heap"),
5842 optarg);
5843 else if (*end != '\0')
5845 pe_heap_commit = strtoul (end + 1, &end, 0);
5846 if (*end != '\0')
5847 non_fatal (_("%s: invalid commit value for --heap"),
5848 optarg);
5851 break;
5853 case OPTION_IMAGE_BASE:
5854 pe_image_base = parse_vma (optarg, "--image-base");
5855 break;
5857 case OPTION_PE_SECTION_ALIGNMENT:
5858 pe_section_alignment = parse_vma (optarg,
5859 "--section-alignment");
5860 break;
5862 case OPTION_SUBSYSTEM:
5863 set_pe_subsystem (optarg);
5864 break;
5866 case OPTION_STACK:
5868 char *end;
5869 pe_stack_reserve = strtoul (optarg, &end, 0);
5870 if (end == optarg
5871 || (*end != '.' && *end != '\0'))
5872 non_fatal (_("%s: invalid reserve value for --stack"),
5873 optarg);
5874 else if (*end != '\0')
5876 pe_stack_commit = strtoul (end + 1, &end, 0);
5877 if (*end != '\0')
5878 non_fatal (_("%s: invalid commit value for --stack"),
5879 optarg);
5882 break;
5884 case OPTION_VERILOG_DATA_WIDTH:
5885 VerilogDataWidth = parse_vma (optarg, "--verilog-data-width");
5886 switch (VerilogDataWidth)
5888 case 1:
5889 case 2:
5890 case 4:
5891 case 8:
5892 case 16: /* We do not support widths > 16 because the verilog
5893 data is handled internally in 16 byte wide packets. */
5894 break;
5895 default:
5896 fatal (_("error: verilog data width must be 1, 2, 4, 8 or 16"));
5898 break;
5900 case 0:
5901 /* We've been given a long option. */
5902 break;
5904 case 'H':
5905 case 'h':
5906 copy_usage (stdout, 0);
5908 default:
5909 copy_usage (stderr, 1);
5913 if (use_globalize && use_keep_global)
5914 fatal(_("--globalize-symbol(s) is incompatible with -G/--keep-global-symbol(s)"));
5916 if (formats_info)
5918 display_info ();
5919 return 0;
5922 if (show_version)
5923 print_version ("objcopy");
5925 if (interleave && copy_byte == -1)
5926 fatal (_("interleave start byte must be set with --byte"));
5928 if (copy_byte >= interleave)
5929 fatal (_("byte number must be less than interleave"));
5931 if (copy_width > interleave - copy_byte)
5932 fatal (_("interleave width must be less than or equal to interleave - byte`"));
5934 if (optind == argc || optind + 2 < argc)
5935 copy_usage (stderr, 1);
5937 input_filename = argv[optind];
5938 if (optind + 1 < argc)
5939 output_filename = argv[optind + 1];
5941 default_deterministic ();
5943 /* Default is to strip no symbols. */
5944 if (strip_symbols == STRIP_UNDEF && discard_locals == LOCALS_UNDEF)
5945 strip_symbols = STRIP_NONE;
5947 if (output_target == NULL)
5948 output_target = input_target;
5950 /* Convert input EFI target to PEI target. */
5951 if (input_target != NULL
5952 && startswith (input_target, "efi-"))
5954 if (convert_efi_target (&input_target) < 0)
5955 fatal (_("unknown input EFI target: %s"), input_target);
5958 /* Convert output EFI target to PEI target. */
5959 if (output_target != NULL
5960 && startswith (output_target, "efi-"))
5962 int subsys = convert_efi_target (&output_target);
5964 if (subsys < 0)
5965 fatal (_("unknown output EFI target: %s"), output_target);
5966 if (pe_subsystem == -1)
5967 pe_subsystem = subsys;
5968 if (pe_file_alignment == (bfd_vma) -1)
5969 pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
5970 if (pe_section_alignment == (bfd_vma) -1)
5971 pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
5974 /* If there is no destination file, or the source and destination files
5975 are the same, then create a temp and copy the result into the input. */
5976 copyfd = -1;
5977 if (output_filename == NULL
5978 || filename_cmp (input_filename, output_filename) == 0)
5980 tmpname = make_tempname (input_filename, &tmpfd);
5981 if (tmpfd >= 0)
5982 copyfd = dup (tmpfd);
5984 else
5985 tmpname = output_filename;
5987 if (tmpname == NULL)
5989 fatal (_("warning: could not create temporary file whilst copying '%s', (error: %s)"),
5990 input_filename, strerror (errno));
5993 copy_file (input_filename, tmpname, tmpfd, &statbuf, input_target,
5994 output_target, input_arch);
5995 if (status == 0)
5997 const char *oname = output_filename ? output_filename : input_filename;
5998 status = smart_rename (tmpname, oname, copyfd,
5999 &statbuf, preserve_dates) != 0;
6001 else
6003 if (copyfd >= 0)
6004 close (copyfd);
6005 unlink_if_ordinary (tmpname);
6008 if (tmpname != output_filename)
6009 free (tmpname);
6011 if (change_warn)
6013 struct section_list *p;
6015 for (p = change_sections; p != NULL; p = p->next)
6017 if (! p->used)
6019 if (p->context & (SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA))
6020 /* xgettext:c-format */
6021 non_fatal (_("%s %s%c0x%" PRIx64 " never used"),
6022 "--change-section-vma",
6023 p->pattern,
6024 p->context & SECTION_CONTEXT_SET_VMA ? '=' : '+',
6025 (uint64_t) p->vma_val);
6027 if (p->context & (SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA))
6028 /* xgettext:c-format */
6029 non_fatal (_("%s %s%c0x%" PRIx64 " never used"),
6030 "--change-section-lma",
6031 p->pattern,
6032 p->context & SECTION_CONTEXT_SET_LMA ? '=' : '+',
6033 (uint64_t) p->lma_val);
6038 free (strip_specific_buffer);
6039 free (strip_unneeded_buffer);
6040 free (keep_specific_buffer);
6041 free (localize_specific_buffer);
6042 free (globalize_specific_buffer);
6043 free (keepglobal_specific_buffer);
6044 free (weaken_specific_buffer);
6046 return 0;
6050 main (int argc, char *argv[])
6052 #ifdef HAVE_LC_MESSAGES
6053 setlocale (LC_MESSAGES, "");
6054 #endif
6055 setlocale (LC_CTYPE, "");
6056 bindtextdomain (PACKAGE, LOCALEDIR);
6057 textdomain (PACKAGE);
6059 program_name = argv[0];
6060 xmalloc_set_program_name (program_name);
6062 expandargv (&argc, &argv);
6064 strip_symbols = STRIP_UNDEF;
6065 discard_locals = LOCALS_UNDEF;
6067 if (bfd_init () != BFD_INIT_MAGIC)
6068 fatal (_("fatal error: libbfd ABI mismatch"));
6069 set_default_bfd_target ();
6071 if (is_strip < 0)
6073 int i = strlen (program_name);
6074 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
6075 /* Drop the .exe suffix, if any. */
6076 if (i > 4 && FILENAME_CMP (program_name + i - 4, ".exe") == 0)
6078 i -= 4;
6079 program_name[i] = '\0';
6081 #endif
6082 is_strip = (i >= 5 && FILENAME_CMP (program_name + i - 5, "strip") == 0);
6085 create_symbol_htabs ();
6086 xatexit (delete_symbol_htabs);
6088 if (argv != NULL)
6089 bfd_set_error_program_name (argv[0]);
6091 if (is_strip)
6092 strip_main (argc, argv);
6093 else
6094 copy_main (argc, argv);
6096 xexit (status);
6097 return status;