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