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