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