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