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