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