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