OSDN Git Service

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