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