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