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