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