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