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