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