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