4a9f043d2ecb961160d492c922005bb154bbd88b
[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 = xstrndup (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   if ((isection->flags & SEC_GROUP) != 0)
3093     {
3094       asymbol *gsym = group_signature (isection);
3095
3096       if (gsym != NULL)
3097         {
3098           gsym->flags |= BSF_KEEP;
3099           if (ibfd->xvec->flavour == bfd_target_elf_flavour)
3100             elf_group_id (isection) = gsym;
3101         }
3102     }
3103
3104   /* Allow the BFD backend to copy any private data it understands
3105      from the input section to the output section.  */
3106   if (!bfd_copy_private_section_data (ibfd, isection, obfd, osection))
3107     {
3108       err = _("failed to copy private data");
3109       goto loser;
3110     }
3111
3112   /* All went well.  */
3113   return;
3114
3115 loser:
3116   status = 1;
3117   bfd_nonfatal_message (NULL, obfd, osection, err);
3118 }
3119
3120 /* Return TRUE if input section ISECTION should be skipped.  */
3121
3122 static bfd_boolean
3123 skip_section (bfd *ibfd, sec_ptr isection)
3124 {
3125   sec_ptr osection;
3126   bfd_size_type size;
3127   flagword flags;
3128
3129   /* If we have already failed earlier on,
3130      do not keep on generating complaints now.  */
3131   if (status != 0)
3132     return TRUE;
3133
3134   if (extract_symbol)
3135     return TRUE;
3136
3137   if (is_strip_section (ibfd, isection))
3138     return TRUE;
3139
3140   if (is_update_section (ibfd, isection))
3141     return TRUE;
3142
3143   flags = bfd_get_section_flags (ibfd, isection);
3144   if ((flags & SEC_GROUP) != 0)
3145     return TRUE;
3146
3147   osection = isection->output_section;
3148   size = bfd_get_section_size (isection);
3149
3150   if (size == 0 || osection == 0)
3151     return TRUE;
3152
3153   return FALSE;
3154 }
3155
3156 /* Copy relocations in input section ISECTION of IBFD to an output
3157    section with the same name in OBFDARG.  If stripping then don't
3158    copy any relocation info.  */
3159
3160 static void
3161 copy_relocations_in_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
3162 {
3163   bfd *obfd = (bfd *) obfdarg;
3164   long relsize;
3165   arelent **relpp;
3166   long relcount;
3167   sec_ptr osection;
3168
3169   if (skip_section (ibfd, isection))
3170     return;
3171
3172   osection = isection->output_section;
3173
3174   /* Core files and DWO files do not need to be relocated.  */
3175   if (bfd_get_format (obfd) == bfd_core || strip_symbols == STRIP_NONDWO)
3176     relsize = 0;
3177   else
3178     {
3179       relsize = bfd_get_reloc_upper_bound (ibfd, isection);
3180
3181       if (relsize < 0)
3182         {
3183           /* Do not complain if the target does not support relocations.  */
3184           if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
3185             relsize = 0;
3186           else
3187             {
3188               status = 1;
3189               bfd_nonfatal_message (NULL, ibfd, isection, NULL);
3190               return;
3191             }
3192         }
3193     }
3194
3195   if (relsize == 0)
3196     {
3197       bfd_set_reloc (obfd, osection, NULL, 0);
3198       osection->flags &= ~SEC_RELOC;
3199     }
3200   else
3201     {
3202       relpp = (arelent **) xmalloc (relsize);
3203       relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, isympp);
3204       if (relcount < 0)
3205         {
3206           status = 1;
3207           bfd_nonfatal_message (NULL, ibfd, isection,
3208                                 _("relocation count is negative"));
3209           return;
3210         }
3211
3212       if (strip_symbols == STRIP_ALL)
3213         {
3214           /* Remove relocations which are not in
3215              keep_strip_specific_list.  */
3216           arelent **temp_relpp;
3217           long temp_relcount = 0;
3218           long i;
3219
3220           temp_relpp = (arelent **) xmalloc (relsize);
3221           for (i = 0; i < relcount; i++)
3222             {
3223               /* PR 17512: file: 9e907e0c.  */
3224               if (relpp[i]->sym_ptr_ptr)
3225                 if (is_specified_symbol (bfd_asymbol_name (*relpp[i]->sym_ptr_ptr),
3226                                          keep_specific_htab))
3227                   temp_relpp [temp_relcount++] = relpp [i];
3228             }
3229           relcount = temp_relcount;
3230           free (relpp);
3231           relpp = temp_relpp;
3232         }
3233
3234       bfd_set_reloc (obfd, osection, relcount == 0 ? NULL : relpp, relcount);
3235       if (relcount == 0)
3236         {
3237           osection->flags &= ~SEC_RELOC;
3238           free (relpp);
3239         }
3240     }
3241 }
3242
3243 /* Copy the data of input section ISECTION of IBFD
3244    to an output section with the same name in OBFD.  */
3245
3246 static void
3247 copy_section (bfd *ibfd, sec_ptr isection, void *obfdarg)
3248 {
3249   bfd *obfd = (bfd *) obfdarg;
3250   struct section_list *p;
3251   sec_ptr osection;
3252   bfd_size_type size;
3253
3254   if (skip_section (ibfd, isection))
3255     return;
3256
3257   osection = isection->output_section;
3258   /* The output SHF_COMPRESSED section size is different from input if
3259      ELF classes of input and output aren't the same.  We can't use
3260      the output section size since --interleave will shrink the output
3261      section.   Size will be updated if the section is converted.   */
3262   size = bfd_get_section_size (isection);
3263
3264   if (bfd_get_section_flags (ibfd, isection) & SEC_HAS_CONTENTS
3265       && bfd_get_section_flags (obfd, osection) & SEC_HAS_CONTENTS)
3266     {
3267       bfd_byte *memhunk = NULL;
3268
3269       if (!bfd_get_full_section_contents (ibfd, isection, &memhunk)
3270           || !bfd_convert_section_contents (ibfd, isection, obfd,
3271                                             &memhunk, &size))
3272         {
3273           status = 1;
3274           bfd_nonfatal_message (NULL, ibfd, isection, NULL);
3275           return;
3276         }
3277
3278       if (reverse_bytes)
3279         {
3280           /* We don't handle leftover bytes (too many possible behaviors,
3281              and we don't know what the user wants).  The section length
3282              must be a multiple of the number of bytes to swap.  */
3283           if ((size % reverse_bytes) == 0)
3284             {
3285               unsigned long i, j;
3286               bfd_byte b;
3287
3288               for (i = 0; i < size; i += reverse_bytes)
3289                 for (j = 0; j < (unsigned long)(reverse_bytes / 2); j++)
3290                   {
3291                     bfd_byte *m = (bfd_byte *) memhunk;
3292
3293                     b = m[i + j];
3294                     m[i + j] = m[(i + reverse_bytes) - (j + 1)];
3295                     m[(i + reverse_bytes) - (j + 1)] = b;
3296                   }
3297             }
3298           else
3299             /* User must pad the section up in order to do this.  */
3300             fatal (_("cannot reverse bytes: length of section %s must be evenly divisible by %d"),
3301                    bfd_section_name (ibfd, isection), reverse_bytes);
3302         }
3303
3304       if (copy_byte >= 0)
3305         {
3306           /* Keep only every `copy_byte'th byte in MEMHUNK.  */
3307           char *from = (char *) memhunk + copy_byte;
3308           char *to = (char *) memhunk;
3309           char *end = (char *) memhunk + size;
3310           int i;
3311
3312           for (; from < end; from += interleave)
3313             for (i = 0; i < copy_width; i++)
3314               {
3315                 if (&from[i] >= end)
3316                   break;
3317                 *to++ = from[i];
3318               }
3319
3320           size = (size + interleave - 1 - copy_byte) / interleave * copy_width;
3321           osection->lma /= interleave;
3322         }
3323
3324       if (!bfd_set_section_contents (obfd, osection, memhunk, 0, size))
3325         {
3326           status = 1;
3327           bfd_nonfatal_message (NULL, obfd, osection, NULL);
3328           return;
3329         }
3330       free (memhunk);
3331     }
3332   else if ((p = find_section_list (bfd_get_section_name (ibfd, isection),
3333                                    FALSE, SECTION_CONTEXT_SET_FLAGS)) != NULL
3334            && (p->flags & SEC_HAS_CONTENTS) != 0)
3335     {
3336       void *memhunk = xmalloc (size);
3337
3338       /* We don't permit the user to turn off the SEC_HAS_CONTENTS
3339          flag--they can just remove the section entirely and add it
3340          back again.  However, we do permit them to turn on the
3341          SEC_HAS_CONTENTS flag, and take it to mean that the section
3342          contents should be zeroed out.  */
3343
3344       memset (memhunk, 0, size);
3345       if (! bfd_set_section_contents (obfd, osection, memhunk, 0, size))
3346         {
3347           status = 1;
3348           bfd_nonfatal_message (NULL, obfd, osection, NULL);
3349           return;
3350         }
3351       free (memhunk);
3352     }
3353 }
3354
3355 /* Get all the sections.  This is used when --gap-fill or --pad-to is
3356    used.  */
3357
3358 static void
3359 get_sections (bfd *obfd ATTRIBUTE_UNUSED, asection *osection, void *secppparg)
3360 {
3361   asection ***secppp = (asection ***) secppparg;
3362
3363   **secppp = osection;
3364   ++(*secppp);
3365 }
3366
3367 /* Sort sections by VMA.  This is called via qsort, and is used when
3368    --gap-fill or --pad-to is used.  We force non loadable or empty
3369    sections to the front, where they are easier to ignore.  */
3370
3371 static int
3372 compare_section_lma (const void *arg1, const void *arg2)
3373 {
3374   const asection *const *sec1 = (const asection * const *) arg1;
3375   const asection *const *sec2 = (const asection * const *) arg2;
3376   flagword flags1, flags2;
3377
3378   /* Sort non loadable sections to the front.  */
3379   flags1 = (*sec1)->flags;
3380   flags2 = (*sec2)->flags;
3381   if ((flags1 & SEC_HAS_CONTENTS) == 0
3382       || (flags1 & SEC_LOAD) == 0)
3383     {
3384       if ((flags2 & SEC_HAS_CONTENTS) != 0
3385           && (flags2 & SEC_LOAD) != 0)
3386         return -1;
3387     }
3388   else
3389     {
3390       if ((flags2 & SEC_HAS_CONTENTS) == 0
3391           || (flags2 & SEC_LOAD) == 0)
3392         return 1;
3393     }
3394
3395   /* Sort sections by LMA.  */
3396   if ((*sec1)->lma > (*sec2)->lma)
3397     return 1;
3398   else if ((*sec1)->lma < (*sec2)->lma)
3399     return -1;
3400
3401   /* Sort sections with the same LMA by size.  */
3402   if (bfd_get_section_size (*sec1) > bfd_get_section_size (*sec2))
3403     return 1;
3404   else if (bfd_get_section_size (*sec1) < bfd_get_section_size (*sec2))
3405     return -1;
3406
3407   return 0;
3408 }
3409
3410 /* Mark all the symbols which will be used in output relocations with
3411    the BSF_KEEP flag so that those symbols will not be stripped.
3412
3413    Ignore relocations which will not appear in the output file.  */
3414
3415 static void
3416 mark_symbols_used_in_relocations (bfd *ibfd, sec_ptr isection, void *symbolsarg)
3417 {
3418   asymbol **symbols = (asymbol **) symbolsarg;
3419   long relsize;
3420   arelent **relpp;
3421   long relcount, i;
3422
3423   /* Ignore an input section with no corresponding output section.  */
3424   if (isection->output_section == NULL)
3425     return;
3426
3427   relsize = bfd_get_reloc_upper_bound (ibfd, isection);
3428   if (relsize < 0)
3429     {
3430       /* Do not complain if the target does not support relocations.  */
3431       if (relsize == -1 && bfd_get_error () == bfd_error_invalid_operation)
3432         return;
3433       bfd_fatal (bfd_get_filename (ibfd));
3434     }
3435
3436   if (relsize == 0)
3437     return;
3438
3439   relpp = (arelent **) xmalloc (relsize);
3440   relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, symbols);
3441   if (relcount < 0)
3442     bfd_fatal (bfd_get_filename (ibfd));
3443
3444   /* Examine each symbol used in a relocation.  If it's not one of the
3445      special bfd section symbols, then mark it with BSF_KEEP.  */
3446   for (i = 0; i < relcount; i++)
3447     {
3448       if (*relpp[i]->sym_ptr_ptr != bfd_com_section_ptr->symbol
3449           && *relpp[i]->sym_ptr_ptr != bfd_abs_section_ptr->symbol
3450           && *relpp[i]->sym_ptr_ptr != bfd_und_section_ptr->symbol)
3451         (*relpp[i]->sym_ptr_ptr)->flags |= BSF_KEEP;
3452     }
3453
3454   if (relpp != NULL)
3455     free (relpp);
3456 }
3457
3458 /* Write out debugging information.  */
3459
3460 static bfd_boolean
3461 write_debugging_info (bfd *obfd, void *dhandle,
3462                       long *symcountp ATTRIBUTE_UNUSED,
3463                       asymbol ***symppp ATTRIBUTE_UNUSED)
3464 {
3465   if (bfd_get_flavour (obfd) == bfd_target_ieee_flavour)
3466     return write_ieee_debugging_info (obfd, dhandle);
3467
3468   if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
3469       || bfd_get_flavour (obfd) == bfd_target_elf_flavour)
3470     {
3471       bfd_byte *syms, *strings;
3472       bfd_size_type symsize, stringsize;
3473       asection *stabsec, *stabstrsec;
3474       flagword flags;
3475
3476       if (! write_stabs_in_sections_debugging_info (obfd, dhandle, &syms,
3477                                                     &symsize, &strings,
3478                                                     &stringsize))
3479         return FALSE;
3480
3481       flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DEBUGGING;
3482       stabsec = bfd_make_section_with_flags (obfd, ".stab", flags);
3483       stabstrsec = bfd_make_section_with_flags (obfd, ".stabstr", flags);
3484       if (stabsec == NULL
3485           || stabstrsec == NULL
3486           || ! bfd_set_section_size (obfd, stabsec, symsize)
3487           || ! bfd_set_section_size (obfd, stabstrsec, stringsize)
3488           || ! bfd_set_section_alignment (obfd, stabsec, 2)
3489           || ! bfd_set_section_alignment (obfd, stabstrsec, 0))
3490         {
3491           bfd_nonfatal_message (NULL, obfd, NULL,
3492                                 _("can't create debugging section"));
3493           return FALSE;
3494         }
3495
3496       /* We can get away with setting the section contents now because
3497          the next thing the caller is going to do is copy over the
3498          real sections.  We may someday have to split the contents
3499          setting out of this function.  */
3500       if (! bfd_set_section_contents (obfd, stabsec, syms, 0, symsize)
3501           || ! bfd_set_section_contents (obfd, stabstrsec, strings, 0,
3502                                          stringsize))
3503         {
3504           bfd_nonfatal_message (NULL, obfd, NULL,
3505                                 _("can't set debugging section contents"));
3506           return FALSE;
3507         }
3508
3509       return TRUE;
3510     }
3511
3512   bfd_nonfatal_message (NULL, obfd, NULL,
3513                         _("don't know how to write debugging information for %s"),
3514              bfd_get_target (obfd));
3515   return FALSE;
3516 }
3517
3518 /* If neither -D nor -U was specified explicitly,
3519    then use the configured default.  */
3520 static void
3521 default_deterministic (void)
3522 {
3523   if (deterministic < 0)
3524     deterministic = DEFAULT_AR_DETERMINISTIC;
3525 }
3526
3527 static int
3528 strip_main (int argc, char *argv[])
3529 {
3530   char *input_target = NULL;
3531   char *output_target = NULL;
3532   bfd_boolean show_version = FALSE;
3533   bfd_boolean formats_info = FALSE;
3534   int c;
3535   int i;
3536   char *output_file = NULL;
3537
3538   while ((c = getopt_long (argc, argv, "I:O:F:K:N:R:o:sSpdgxXHhVvwDU",
3539                            strip_options, (int *) 0)) != EOF)
3540     {
3541       switch (c)
3542         {
3543         case 'I':
3544           input_target = optarg;
3545           break;
3546         case 'O':
3547           output_target = optarg;
3548           break;
3549         case 'F':
3550           input_target = output_target = optarg;
3551           break;
3552         case 'R':
3553           find_section_list (optarg, TRUE, SECTION_CONTEXT_REMOVE);
3554           sections_removed = TRUE;
3555           break;
3556         case 's':
3557           strip_symbols = STRIP_ALL;
3558           break;
3559         case 'S':
3560         case 'g':
3561         case 'd':       /* Historic BSD alias for -g.  Used by early NetBSD.  */
3562           strip_symbols = STRIP_DEBUG;
3563           break;
3564         case OPTION_STRIP_DWO:
3565           strip_symbols = STRIP_DWO;
3566           break;
3567         case OPTION_STRIP_UNNEEDED:
3568           strip_symbols = STRIP_UNNEEDED;
3569           break;
3570         case 'K':
3571           add_specific_symbol (optarg, keep_specific_htab);
3572           break;
3573         case 'N':
3574           add_specific_symbol (optarg, strip_specific_htab);
3575           break;
3576         case 'o':
3577           output_file = optarg;
3578           break;
3579         case 'p':
3580           preserve_dates = TRUE;
3581           break;
3582         case 'D':
3583           deterministic = TRUE;
3584           break;
3585         case 'U':
3586           deterministic = FALSE;
3587           break;
3588         case 'x':
3589           discard_locals = LOCALS_ALL;
3590           break;
3591         case 'X':
3592           discard_locals = LOCALS_START_L;
3593           break;
3594         case 'v':
3595           verbose = TRUE;
3596           break;
3597         case 'V':
3598           show_version = TRUE;
3599           break;
3600         case OPTION_FORMATS_INFO:
3601           formats_info = TRUE;
3602           break;
3603         case OPTION_ONLY_KEEP_DEBUG:
3604           strip_symbols = STRIP_NONDEBUG;
3605           break;
3606         case OPTION_KEEP_FILE_SYMBOLS:
3607           keep_file_symbols = 1;
3608           break;
3609         case 0:
3610           /* We've been given a long option.  */
3611           break;
3612         case 'w':
3613           wildcard = TRUE;
3614           break;
3615         case 'H':
3616         case 'h':
3617           strip_usage (stdout, 0);
3618         default:
3619           strip_usage (stderr, 1);
3620         }
3621     }
3622
3623   if (formats_info)
3624     {
3625       display_info ();
3626       return 0;
3627     }
3628
3629   if (show_version)
3630     print_version ("strip");
3631
3632   default_deterministic ();
3633
3634   /* Default is to strip all symbols.  */
3635   if (strip_symbols == STRIP_UNDEF
3636       && discard_locals == LOCALS_UNDEF
3637       && htab_elements (strip_specific_htab) == 0)
3638     strip_symbols = STRIP_ALL;
3639
3640   if (output_target == NULL)
3641     output_target = input_target;
3642
3643   i = optind;
3644   if (i == argc
3645       || (output_file != NULL && (i + 1) < argc))
3646     strip_usage (stderr, 1);
3647
3648   for (; i < argc; i++)
3649     {
3650       int hold_status = status;
3651       struct stat statbuf;
3652       char *tmpname;
3653
3654       if (get_file_size (argv[i]) < 1)
3655         {
3656           status = 1;
3657           continue;
3658         }
3659
3660       if (preserve_dates)
3661         /* No need to check the return value of stat().
3662            It has already been checked in get_file_size().  */
3663         stat (argv[i], &statbuf);
3664
3665       if (output_file == NULL
3666           || filename_cmp (argv[i], output_file) == 0)
3667         tmpname = make_tempname (argv[i]);
3668       else
3669         tmpname = output_file;
3670
3671       if (tmpname == NULL)
3672         {
3673           bfd_nonfatal_message (argv[i], NULL, NULL,
3674                                 _("could not create temporary file to hold stripped copy"));
3675           status = 1;
3676           continue;
3677         }
3678
3679       status = 0;
3680       copy_file (argv[i], tmpname, input_target, output_target, NULL);
3681       if (status == 0)
3682         {
3683           if (preserve_dates)
3684             set_times (tmpname, &statbuf);
3685           if (output_file != tmpname)
3686             status = (smart_rename (tmpname,
3687                                     output_file ? output_file : argv[i],
3688                                     preserve_dates) != 0);
3689           if (status == 0)
3690             status = hold_status;
3691         }
3692       else
3693         unlink_if_ordinary (tmpname);
3694       if (output_file != tmpname)
3695         free (tmpname);
3696     }
3697
3698   return status;
3699 }
3700
3701 /* Set up PE subsystem.  */
3702
3703 static void
3704 set_pe_subsystem (const char *s)
3705 {
3706   const char *version, *subsystem;
3707   size_t i;
3708   static const struct
3709     {
3710       const char *name;
3711       const char set_def;
3712       const short value;
3713     }
3714   v[] =
3715     {
3716       { "native", 0, IMAGE_SUBSYSTEM_NATIVE },
3717       { "windows", 0, IMAGE_SUBSYSTEM_WINDOWS_GUI },
3718       { "console", 0, IMAGE_SUBSYSTEM_WINDOWS_CUI },
3719       { "posix", 0, IMAGE_SUBSYSTEM_POSIX_CUI },
3720       { "wince", 0, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI },
3721       { "efi-app", 1, IMAGE_SUBSYSTEM_EFI_APPLICATION },
3722       { "efi-bsd", 1, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER },
3723       { "efi-rtd", 1, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER },
3724       { "sal-rtd", 1, IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER },
3725       { "xbox", 0, IMAGE_SUBSYSTEM_XBOX }
3726     };
3727   short value;
3728   char *copy;
3729   int set_def = -1;
3730
3731   /* Check for the presence of a version number.  */
3732   version = strchr (s, ':');
3733   if (version == NULL)
3734     subsystem = s;
3735   else
3736     {
3737       int len = version - s;
3738       copy = xstrdup (s);
3739       subsystem = copy;
3740       copy[len] = '\0';
3741       version = copy + 1 + len;
3742       pe_major_subsystem_version = strtoul (version, &copy, 0);
3743       if (*copy == '.')
3744         pe_minor_subsystem_version = strtoul (copy + 1, &copy, 0);
3745       if (*copy != '\0')
3746         non_fatal (_("%s: bad version in PE subsystem"), s);
3747     }
3748
3749   /* Check for numeric subsystem.  */
3750   value = (short) strtol (subsystem, &copy, 0);
3751   if (*copy == '\0')
3752     {
3753       for (i = 0; i < ARRAY_SIZE (v); i++)
3754         if (v[i].value == value)
3755           {
3756             pe_subsystem = value;
3757             set_def = v[i].set_def;
3758             break;
3759           }
3760     }
3761   else
3762     {
3763       /* Search for subsystem by name.  */
3764       for (i = 0; i < ARRAY_SIZE (v); i++)
3765         if (strcmp (subsystem, v[i].name) == 0)
3766           {
3767             pe_subsystem = v[i].value;
3768             set_def = v[i].set_def;
3769             break;
3770           }
3771     }
3772
3773   switch (set_def)
3774     {
3775     case -1:
3776       fatal (_("unknown PE subsystem: %s"), s);
3777       break;
3778     case 0:
3779       break;
3780     default:
3781       if (pe_file_alignment == (bfd_vma) -1)
3782         pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
3783       if (pe_section_alignment == (bfd_vma) -1)
3784         pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
3785       break;
3786     }
3787   if (s != subsystem)
3788     free ((char *) subsystem);
3789 }
3790
3791 /* Convert EFI target to PEI target.  */
3792
3793 static void
3794 convert_efi_target (char *efi)
3795 {
3796   efi[0] = 'p';
3797   efi[1] = 'e';
3798   efi[2] = 'i';
3799
3800   if (strcmp (efi + 4, "ia32") == 0)
3801     {
3802       /* Change ia32 to i386.  */
3803       efi[5]= '3';
3804       efi[6]= '8';
3805       efi[7]= '6';
3806     }
3807   else if (strcmp (efi + 4, "x86_64") == 0)
3808     {
3809       /* Change x86_64 to x86-64.  */
3810       efi[7] = '-';
3811     }
3812 }
3813
3814 /* Allocate and return a pointer to a struct section_add, initializing the
3815    structure using ARG, a string in the format "sectionname=filename".
3816    The returned structure will have its next pointer set to NEXT.  The
3817    OPTION field is the name of the command line option currently being
3818    parsed, and is only used if an error needs to be reported.  */
3819
3820 static struct section_add *
3821 init_section_add (const char *arg,
3822                   struct section_add *next,
3823                   const char *option)
3824 {
3825   struct section_add *pa;
3826   const char *s;
3827
3828   s = strchr (arg, '=');
3829   if (s == NULL)
3830     fatal (_("bad format for %s"), option);
3831
3832   pa = (struct section_add *) xmalloc (sizeof (struct section_add));
3833   pa->name = xstrndup (arg, s - arg);
3834   pa->filename = s + 1;
3835   pa->next = next;
3836   pa->contents = NULL;
3837   pa->size = 0;
3838
3839   return pa;
3840 }
3841
3842 /* Load the file specified in PA, allocating memory to hold the file
3843    contents, and store a pointer to the allocated memory in the contents
3844    field of PA.  The size field of PA is also updated.  All errors call
3845    FATAL.  */
3846
3847 static void
3848 section_add_load_file (struct section_add *pa)
3849 {
3850   size_t off, alloc;
3851   FILE *f;
3852
3853   /* We don't use get_file_size so that we can do
3854      --add-section .note.GNU_stack=/dev/null
3855      get_file_size doesn't work on /dev/null.  */
3856
3857   f = fopen (pa->filename, FOPEN_RB);
3858   if (f == NULL)
3859     fatal (_("cannot open: %s: %s"),
3860            pa->filename, strerror (errno));
3861
3862   off = 0;
3863   alloc = 4096;
3864   pa->contents = (bfd_byte *) xmalloc (alloc);
3865   while (!feof (f))
3866     {
3867       off_t got;
3868
3869       if (off == alloc)
3870         {
3871           alloc <<= 1;
3872           pa->contents = (bfd_byte *) xrealloc (pa->contents, alloc);
3873         }
3874
3875       got = fread (pa->contents + off, 1, alloc - off, f);
3876       if (ferror (f))
3877         fatal (_("%s: fread failed"), pa->filename);
3878
3879       off += got;
3880     }
3881
3882   pa->size = off;
3883
3884   fclose (f);
3885 }
3886
3887 static int
3888 copy_main (int argc, char *argv[])
3889 {
3890   char *input_filename = NULL;
3891   char *output_filename = NULL;
3892   char *tmpname;
3893   char *input_target = NULL;
3894   char *output_target = NULL;
3895   bfd_boolean show_version = FALSE;
3896   bfd_boolean change_warn = TRUE;
3897   bfd_boolean formats_info = FALSE;
3898   int c;
3899   struct stat statbuf;
3900   const bfd_arch_info_type *input_arch = NULL;
3901
3902   while ((c = getopt_long (argc, argv, "b:B:i:I:j:K:N:s:O:d:F:L:G:R:SpgxXHhVvW:wDU",
3903                            copy_options, (int *) 0)) != EOF)
3904     {
3905       switch (c)
3906         {
3907         case 'b':
3908           copy_byte = atoi (optarg);
3909           if (copy_byte < 0)
3910             fatal (_("byte number must be non-negative"));
3911           break;
3912
3913         case 'B':
3914           input_arch = bfd_scan_arch (optarg);
3915           if (input_arch == NULL)
3916             fatal (_("architecture %s unknown"), optarg);
3917           break;
3918
3919         case 'i':
3920           if (optarg)
3921             {
3922               interleave = atoi (optarg);
3923               if (interleave < 1)
3924                 fatal (_("interleave must be positive"));
3925             }
3926           else
3927             interleave = 4;
3928           break;
3929
3930         case OPTION_INTERLEAVE_WIDTH:
3931           copy_width = atoi (optarg);
3932           if (copy_width < 1)
3933             fatal(_("interleave width must be positive"));
3934           break;
3935
3936         case 'I':
3937         case 's':               /* "source" - 'I' is preferred */
3938           input_target = optarg;
3939           break;
3940
3941         case 'O':
3942         case 'd':               /* "destination" - 'O' is preferred */
3943           output_target = optarg;
3944           break;
3945
3946         case 'F':
3947           input_target = output_target = optarg;
3948           break;
3949
3950         case 'j':
3951           find_section_list (optarg, TRUE, SECTION_CONTEXT_COPY);
3952           sections_copied = TRUE;
3953           break;
3954
3955         case 'R':
3956           find_section_list (optarg, TRUE, SECTION_CONTEXT_REMOVE);
3957           sections_removed = TRUE;
3958           break;
3959
3960         case 'S':
3961           strip_symbols = STRIP_ALL;
3962           break;
3963
3964         case 'g':
3965           strip_symbols = STRIP_DEBUG;
3966           break;
3967
3968         case OPTION_STRIP_DWO:
3969           strip_symbols = STRIP_DWO;
3970           break;
3971
3972         case OPTION_STRIP_UNNEEDED:
3973           strip_symbols = STRIP_UNNEEDED;
3974           break;
3975
3976         case OPTION_ONLY_KEEP_DEBUG:
3977           strip_symbols = STRIP_NONDEBUG;
3978           break;
3979
3980         case OPTION_KEEP_FILE_SYMBOLS:
3981           keep_file_symbols = 1;
3982           break;
3983
3984         case OPTION_ADD_GNU_DEBUGLINK:
3985           long_section_names = ENABLE ;
3986           gnu_debuglink_filename = optarg;
3987           break;
3988
3989         case 'K':
3990           add_specific_symbol (optarg, keep_specific_htab);
3991           break;
3992
3993         case 'N':
3994           add_specific_symbol (optarg, strip_specific_htab);
3995           break;
3996
3997         case OPTION_STRIP_UNNEEDED_SYMBOL:
3998           add_specific_symbol (optarg, strip_unneeded_htab);
3999           break;
4000
4001         case 'L':
4002           add_specific_symbol (optarg, localize_specific_htab);
4003           break;
4004
4005         case OPTION_GLOBALIZE_SYMBOL:
4006           add_specific_symbol (optarg, globalize_specific_htab);
4007           break;
4008
4009         case 'G':
4010           add_specific_symbol (optarg, keepglobal_specific_htab);
4011           break;
4012
4013         case 'W':
4014           add_specific_symbol (optarg, weaken_specific_htab);
4015           break;
4016
4017         case 'p':
4018           preserve_dates = TRUE;
4019           break;
4020
4021         case 'D':
4022           deterministic = TRUE;
4023           break;
4024
4025         case 'U':
4026           deterministic = FALSE;
4027           break;
4028
4029         case 'w':
4030           wildcard = TRUE;
4031           break;
4032
4033         case 'x':
4034           discard_locals = LOCALS_ALL;
4035           break;
4036
4037         case 'X':
4038           discard_locals = LOCALS_START_L;
4039           break;
4040
4041         case 'v':
4042           verbose = TRUE;
4043           break;
4044
4045         case 'V':
4046           show_version = TRUE;
4047           break;
4048
4049         case OPTION_FORMATS_INFO:
4050           formats_info = TRUE;
4051           break;
4052
4053         case OPTION_WEAKEN:
4054           weaken = TRUE;
4055           break;
4056
4057         case OPTION_ADD_SECTION:
4058           add_sections = init_section_add (optarg, add_sections,
4059                                            "--add-section");
4060           section_add_load_file (add_sections);
4061           break;
4062
4063         case OPTION_UPDATE_SECTION:
4064           update_sections = init_section_add (optarg, update_sections,
4065                                               "--update-section");
4066           section_add_load_file (update_sections);
4067           break;
4068
4069         case OPTION_DUMP_SECTION:
4070           dump_sections = init_section_add (optarg, dump_sections,
4071                                             "--dump-section");
4072           break;
4073
4074         case OPTION_ADD_SYMBOL:
4075           {
4076             char *s, *t;
4077             struct addsym_node *newsym = xmalloc (sizeof *newsym);
4078
4079             newsym->next = NULL;
4080             s = strchr (optarg, '=');
4081             if (s == NULL)
4082               fatal (_("bad format for %s"), "--add-symbol");
4083             t = strchr (s + 1, ':');
4084
4085             newsym->symdef = xstrndup (optarg, s - optarg);
4086             if (t)
4087               {
4088                 newsym->section = xstrndup (s + 1, t - (s + 1));
4089                 newsym->symval = strtol (t + 1, NULL, 0);
4090               }
4091             else
4092               {
4093                 newsym->section = NULL;
4094                 newsym->symval = strtol (s + 1, NULL, 0);
4095                 t = s;
4096               }
4097
4098             t = strchr (t + 1, ',');
4099             if (t)
4100               newsym->flags = parse_symflags (t+1, &newsym->othersym);
4101             else
4102               newsym->flags = BSF_GLOBAL;
4103
4104             /* Keep 'othersym' symbols at the front of the list.  */
4105             if (newsym->othersym)
4106               {
4107                 newsym->next = add_sym_list;
4108                 if (!add_sym_list)
4109                   add_sym_tail = &newsym->next;
4110                 add_sym_list = newsym;
4111               }
4112             else
4113               {
4114                 *add_sym_tail = newsym;
4115                 add_sym_tail = &newsym->next;
4116               }
4117             add_symbols++;
4118           }
4119           break;
4120
4121         case OPTION_CHANGE_START:
4122           change_start = parse_vma (optarg, "--change-start");
4123           break;
4124
4125         case OPTION_CHANGE_SECTION_ADDRESS:
4126         case OPTION_CHANGE_SECTION_LMA:
4127         case OPTION_CHANGE_SECTION_VMA:
4128           {
4129             struct section_list * p;
4130             unsigned int context = 0;
4131             const char *s;
4132             int len;
4133             char *name;
4134             char *option = NULL;
4135             bfd_vma val;
4136
4137             switch (c)
4138               {
4139               case OPTION_CHANGE_SECTION_ADDRESS:
4140                 option = "--change-section-address";
4141                 context = SECTION_CONTEXT_ALTER_LMA | SECTION_CONTEXT_ALTER_VMA;
4142                 break;
4143               case OPTION_CHANGE_SECTION_LMA:
4144                 option = "--change-section-lma";
4145                 context = SECTION_CONTEXT_ALTER_LMA;
4146                 break;
4147               case OPTION_CHANGE_SECTION_VMA:
4148                 option = "--change-section-vma";
4149                 context = SECTION_CONTEXT_ALTER_VMA;
4150                 break;
4151               }
4152
4153             s = strchr (optarg, '=');
4154             if (s == NULL)
4155               {
4156                 s = strchr (optarg, '+');
4157                 if (s == NULL)
4158                   {
4159                     s = strchr (optarg, '-');
4160                     if (s == NULL)
4161                       fatal (_("bad format for %s"), option);
4162                   }
4163               }
4164             else
4165               {
4166                 /* Correct the context.  */
4167                 switch (c)
4168                   {
4169                   case OPTION_CHANGE_SECTION_ADDRESS:
4170                     context = SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_SET_VMA;
4171                     break;
4172                   case OPTION_CHANGE_SECTION_LMA:
4173                     context = SECTION_CONTEXT_SET_LMA;
4174                     break;
4175                   case OPTION_CHANGE_SECTION_VMA:
4176                     context = SECTION_CONTEXT_SET_VMA;
4177                     break;
4178                   }
4179               }
4180
4181             len = s - optarg;
4182             name = (char *) xmalloc (len + 1);
4183             strncpy (name, optarg, len);
4184             name[len] = '\0';
4185
4186             p = find_section_list (name, TRUE, context);
4187
4188             val = parse_vma (s + 1, option);
4189             if (*s == '-')
4190               val = - val;
4191
4192             switch (c)
4193               {
4194               case OPTION_CHANGE_SECTION_ADDRESS:
4195                 p->vma_val = val;
4196                 /* Drop through.  */
4197
4198               case OPTION_CHANGE_SECTION_LMA:
4199                 p->lma_val = val;
4200                 break;
4201
4202               case OPTION_CHANGE_SECTION_VMA:
4203                 p->vma_val = val;
4204                 break;
4205               }
4206           }
4207           break;
4208
4209         case OPTION_CHANGE_ADDRESSES:
4210           change_section_address = parse_vma (optarg, "--change-addresses");
4211           change_start = change_section_address;
4212           break;
4213
4214         case OPTION_CHANGE_WARNINGS:
4215           change_warn = TRUE;
4216           break;
4217
4218         case OPTION_CHANGE_LEADING_CHAR:
4219           change_leading_char = TRUE;
4220           break;
4221
4222         case OPTION_COMPRESS_DEBUG_SECTIONS:
4223           if (optarg)
4224             {
4225               if (strcasecmp (optarg, "none") == 0)
4226                 do_debug_sections = decompress;
4227               else if (strcasecmp (optarg, "zlib") == 0)
4228                 do_debug_sections = compress_zlib;
4229               else if (strcasecmp (optarg, "zlib-gnu") == 0)
4230                 do_debug_sections = compress_gnu_zlib;
4231               else if (strcasecmp (optarg, "zlib-gabi") == 0)
4232                 do_debug_sections = compress_gabi_zlib;
4233               else
4234                 fatal (_("unrecognized --compress-debug-sections type `%s'"),
4235                        optarg);
4236             }
4237           else
4238             do_debug_sections = compress;
4239           break;
4240
4241         case OPTION_DEBUGGING:
4242           convert_debugging = TRUE;
4243           break;
4244
4245         case OPTION_DECOMPRESS_DEBUG_SECTIONS:
4246           do_debug_sections = decompress;
4247           break;
4248
4249         case OPTION_GAP_FILL:
4250           {
4251             bfd_vma gap_fill_vma;
4252
4253             gap_fill_vma = parse_vma (optarg, "--gap-fill");
4254             gap_fill = (bfd_byte) gap_fill_vma;
4255             if ((bfd_vma) gap_fill != gap_fill_vma)
4256               {
4257                 char buff[20];
4258
4259                 sprintf_vma (buff, gap_fill_vma);
4260
4261                 non_fatal (_("Warning: truncating gap-fill from 0x%s to 0x%x"),
4262                            buff, gap_fill);
4263               }
4264             gap_fill_set = TRUE;
4265           }
4266           break;
4267
4268         case OPTION_NO_CHANGE_WARNINGS:
4269           change_warn = FALSE;
4270           break;
4271
4272         case OPTION_PAD_TO:
4273           pad_to = parse_vma (optarg, "--pad-to");
4274           pad_to_set = TRUE;
4275           break;
4276
4277         case OPTION_REMOVE_LEADING_CHAR:
4278           remove_leading_char = TRUE;
4279           break;
4280
4281         case OPTION_REDEFINE_SYM:
4282           {
4283             /* Push this redefinition onto redefine_symbol_list.  */
4284
4285             int len;
4286             const char *s;
4287             const char *nextarg;
4288             char *source, *target;
4289
4290             s = strchr (optarg, '=');
4291             if (s == NULL)
4292               fatal (_("bad format for %s"), "--redefine-sym");
4293
4294             len = s - optarg;
4295             source = (char *) xmalloc (len + 1);
4296             strncpy (source, optarg, len);
4297             source[len] = '\0';
4298
4299             nextarg = s + 1;
4300             len = strlen (nextarg);
4301             target = (char *) xmalloc (len + 1);
4302             strcpy (target, nextarg);
4303
4304             redefine_list_append ("--redefine-sym", source, target);
4305
4306             free (source);
4307             free (target);
4308           }
4309           break;
4310
4311         case OPTION_REDEFINE_SYMS:
4312           add_redefine_syms_file (optarg);
4313           break;
4314
4315         case OPTION_SET_SECTION_FLAGS:
4316           {
4317             struct section_list *p;
4318             const char *s;
4319             int len;
4320             char *name;
4321
4322             s = strchr (optarg, '=');
4323             if (s == NULL)
4324               fatal (_("bad format for %s"), "--set-section-flags");
4325
4326             len = s - optarg;
4327             name = (char *) xmalloc (len + 1);
4328             strncpy (name, optarg, len);
4329             name[len] = '\0';
4330
4331             p = find_section_list (name, TRUE, SECTION_CONTEXT_SET_FLAGS);
4332
4333             p->flags = parse_flags (s + 1);
4334           }
4335           break;
4336
4337         case OPTION_RENAME_SECTION:
4338           {
4339             flagword flags;
4340             const char *eq, *fl;
4341             char *old_name;
4342             char *new_name;
4343             unsigned int len;
4344
4345             eq = strchr (optarg, '=');
4346             if (eq == NULL)
4347               fatal (_("bad format for %s"), "--rename-section");
4348
4349             len = eq - optarg;
4350             if (len == 0)
4351               fatal (_("bad format for %s"), "--rename-section");
4352
4353             old_name = (char *) xmalloc (len + 1);
4354             strncpy (old_name, optarg, len);
4355             old_name[len] = 0;
4356
4357             eq++;
4358             fl = strchr (eq, ',');
4359             if (fl)
4360               {
4361                 flags = parse_flags (fl + 1);
4362                 len = fl - eq;
4363               }
4364             else
4365               {
4366                 flags = -1;
4367                 len = strlen (eq);
4368               }
4369
4370             if (len == 0)
4371               fatal (_("bad format for %s"), "--rename-section");
4372
4373             new_name = (char *) xmalloc (len + 1);
4374             strncpy (new_name, eq, len);
4375             new_name[len] = 0;
4376
4377             add_section_rename (old_name, new_name, flags);
4378           }
4379           break;
4380
4381         case OPTION_SET_START:
4382           set_start = parse_vma (optarg, "--set-start");
4383           set_start_set = TRUE;
4384           break;
4385
4386         case OPTION_SREC_LEN:
4387           Chunk = parse_vma (optarg, "--srec-len");
4388           break;
4389
4390         case OPTION_SREC_FORCES3:
4391           S3Forced = TRUE;
4392           break;
4393
4394         case OPTION_STRIP_SYMBOLS:
4395           add_specific_symbols (optarg, strip_specific_htab);
4396           break;
4397
4398         case OPTION_STRIP_UNNEEDED_SYMBOLS:
4399           add_specific_symbols (optarg, strip_unneeded_htab);
4400           break;
4401
4402         case OPTION_KEEP_SYMBOLS:
4403           add_specific_symbols (optarg, keep_specific_htab);
4404           break;
4405
4406         case OPTION_LOCALIZE_HIDDEN:
4407           localize_hidden = TRUE;
4408           break;
4409
4410         case OPTION_LOCALIZE_SYMBOLS:
4411           add_specific_symbols (optarg, localize_specific_htab);
4412           break;
4413
4414         case OPTION_LONG_SECTION_NAMES:
4415           if (!strcmp ("enable", optarg))
4416             long_section_names = ENABLE;
4417           else if (!strcmp ("disable", optarg))
4418             long_section_names = DISABLE;
4419           else if (!strcmp ("keep", optarg))
4420             long_section_names = KEEP;
4421           else
4422             fatal (_("unknown long section names option '%s'"), optarg);
4423           break;
4424
4425         case OPTION_GLOBALIZE_SYMBOLS:
4426           add_specific_symbols (optarg, globalize_specific_htab);
4427           break;
4428
4429         case OPTION_KEEPGLOBAL_SYMBOLS:
4430           add_specific_symbols (optarg, keepglobal_specific_htab);
4431           break;
4432
4433         case OPTION_WEAKEN_SYMBOLS:
4434           add_specific_symbols (optarg, weaken_specific_htab);
4435           break;
4436
4437         case OPTION_ALT_MACH_CODE:
4438           use_alt_mach_code = strtoul (optarg, NULL, 0);
4439           if (use_alt_mach_code == 0)
4440             fatal (_("unable to parse alternative machine code"));
4441           break;
4442
4443         case OPTION_PREFIX_SYMBOLS:
4444           prefix_symbols_string = optarg;
4445           break;
4446
4447         case OPTION_PREFIX_SECTIONS:
4448           prefix_sections_string = optarg;
4449           break;
4450
4451         case OPTION_PREFIX_ALLOC_SECTIONS:
4452           prefix_alloc_sections_string = optarg;
4453           break;
4454
4455         case OPTION_READONLY_TEXT:
4456           bfd_flags_to_set |= WP_TEXT;
4457           bfd_flags_to_clear &= ~WP_TEXT;
4458           break;
4459
4460         case OPTION_WRITABLE_TEXT:
4461           bfd_flags_to_clear |= WP_TEXT;
4462           bfd_flags_to_set &= ~WP_TEXT;
4463           break;
4464
4465         case OPTION_PURE:
4466           bfd_flags_to_set |= D_PAGED;
4467           bfd_flags_to_clear &= ~D_PAGED;
4468           break;
4469
4470         case OPTION_IMPURE:
4471           bfd_flags_to_clear |= D_PAGED;
4472           bfd_flags_to_set &= ~D_PAGED;
4473           break;
4474
4475         case OPTION_EXTRACT_DWO:
4476           strip_symbols = STRIP_NONDWO;
4477           break;
4478
4479         case OPTION_EXTRACT_SYMBOL:
4480           extract_symbol = TRUE;
4481           break;
4482
4483         case OPTION_REVERSE_BYTES:
4484           {
4485             int prev = reverse_bytes;
4486
4487             reverse_bytes = atoi (optarg);
4488             if ((reverse_bytes <= 0) || ((reverse_bytes % 2) != 0))
4489               fatal (_("number of bytes to reverse must be positive and even"));
4490
4491             if (prev && prev != reverse_bytes)
4492               non_fatal (_("Warning: ignoring previous --reverse-bytes value of %d"),
4493                          prev);
4494             break;
4495           }
4496
4497         case OPTION_FILE_ALIGNMENT:
4498           pe_file_alignment = parse_vma (optarg, "--file-alignment");
4499           break;
4500
4501         case OPTION_HEAP:
4502             {
4503               char *end;
4504               pe_heap_reserve = strtoul (optarg, &end, 0);
4505               if (end == optarg
4506                   || (*end != '.' && *end != '\0'))
4507                 non_fatal (_("%s: invalid reserve value for --heap"),
4508                            optarg);
4509               else if (*end != '\0')
4510                 {
4511                   pe_heap_commit = strtoul (end + 1, &end, 0);
4512                   if (*end != '\0')
4513                     non_fatal (_("%s: invalid commit value for --heap"),
4514                                optarg);
4515                 }
4516             }
4517           break;
4518
4519         case OPTION_IMAGE_BASE:
4520           pe_image_base = parse_vma (optarg, "--image-base");
4521           break;
4522
4523         case OPTION_SECTION_ALIGNMENT:
4524           pe_section_alignment = parse_vma (optarg,
4525                                             "--section-alignment");
4526           break;
4527
4528         case OPTION_SUBSYSTEM:
4529           set_pe_subsystem (optarg);
4530           break;
4531
4532         case OPTION_STACK:
4533             {
4534               char *end;
4535               pe_stack_reserve = strtoul (optarg, &end, 0);
4536               if (end == optarg
4537                   || (*end != '.' && *end != '\0'))
4538                 non_fatal (_("%s: invalid reserve value for --stack"),
4539                            optarg);
4540               else if (*end != '\0')
4541                 {
4542                   pe_stack_commit = strtoul (end + 1, &end, 0);
4543                   if (*end != '\0')
4544                     non_fatal (_("%s: invalid commit value for --stack"),
4545                                optarg);
4546                 }
4547             }
4548           break;
4549
4550         case 0:
4551           /* We've been given a long option.  */
4552           break;
4553
4554         case 'H':
4555         case 'h':
4556           copy_usage (stdout, 0);
4557
4558         default:
4559           copy_usage (stderr, 1);
4560         }
4561     }
4562
4563   if (formats_info)
4564     {
4565       display_info ();
4566       return 0;
4567     }
4568
4569   if (show_version)
4570     print_version ("objcopy");
4571
4572   if (interleave && copy_byte == -1)
4573     fatal (_("interleave start byte must be set with --byte"));
4574
4575   if (copy_byte >= interleave)
4576     fatal (_("byte number must be less than interleave"));
4577
4578   if (copy_width > interleave - copy_byte)
4579     fatal (_("interleave width must be less than or equal to interleave - byte`"));
4580
4581   if (optind == argc || optind + 2 < argc)
4582     copy_usage (stderr, 1);
4583
4584   input_filename = argv[optind];
4585   if (optind + 1 < argc)
4586     output_filename = argv[optind + 1];
4587
4588   default_deterministic ();
4589
4590   /* Default is to strip no symbols.  */
4591   if (strip_symbols == STRIP_UNDEF && discard_locals == LOCALS_UNDEF)
4592     strip_symbols = STRIP_NONE;
4593
4594   if (output_target == NULL)
4595     output_target = input_target;
4596
4597   /* Convert input EFI target to PEI target.  */
4598   if (input_target != NULL
4599       && strncmp (input_target, "efi-", 4) == 0)
4600     {
4601       char *efi;
4602
4603       efi = xstrdup (output_target + 4);
4604       if (strncmp (efi, "bsdrv-", 6) == 0
4605           || strncmp (efi, "rtdrv-", 6) == 0)
4606         efi += 2;
4607       else if (strncmp (efi, "app-", 4) != 0)
4608         fatal (_("unknown input EFI target: %s"), input_target);
4609
4610       input_target = efi;
4611       convert_efi_target (efi);
4612     }
4613
4614   /* Convert output EFI target to PEI target.  */
4615   if (output_target != NULL
4616       && strncmp (output_target, "efi-", 4) == 0)
4617     {
4618       char *efi;
4619
4620       efi = xstrdup (output_target + 4);
4621       if (strncmp (efi, "app-", 4) == 0)
4622         {
4623           if (pe_subsystem == -1)
4624             pe_subsystem = IMAGE_SUBSYSTEM_EFI_APPLICATION;
4625         }
4626       else if (strncmp (efi, "bsdrv-", 6) == 0)
4627         {
4628           if (pe_subsystem == -1)
4629             pe_subsystem = IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
4630           efi += 2;
4631         }
4632       else if (strncmp (efi, "rtdrv-", 6) == 0)
4633         {
4634           if (pe_subsystem == -1)
4635             pe_subsystem = IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER;
4636           efi += 2;
4637         }
4638       else
4639         fatal (_("unknown output EFI target: %s"), output_target);
4640
4641       if (pe_file_alignment == (bfd_vma) -1)
4642         pe_file_alignment = PE_DEF_FILE_ALIGNMENT;
4643       if (pe_section_alignment == (bfd_vma) -1)
4644         pe_section_alignment = PE_DEF_SECTION_ALIGNMENT;
4645
4646       output_target = efi;
4647       convert_efi_target (efi);
4648     }
4649
4650   if (preserve_dates)
4651     if (stat (input_filename, & statbuf) < 0)
4652       fatal (_("warning: could not locate '%s'.  System error message: %s"),
4653              input_filename, strerror (errno));
4654
4655   /* If there is no destination file, or the source and destination files
4656      are the same, then create a temp and rename the result into the input.  */
4657   if (output_filename == NULL
4658       || filename_cmp (input_filename, output_filename) == 0)
4659     tmpname = make_tempname (input_filename);
4660   else
4661     tmpname = output_filename;
4662
4663   if (tmpname == NULL)
4664     fatal (_("warning: could not create temporary file whilst copying '%s', (error: %s)"),
4665            input_filename, strerror (errno));
4666
4667   copy_file (input_filename, tmpname, input_target, output_target, input_arch);
4668   if (status == 0)
4669     {
4670       if (preserve_dates)
4671         set_times (tmpname, &statbuf);
4672       if (tmpname != output_filename)
4673         status = (smart_rename (tmpname, input_filename,
4674                                 preserve_dates) != 0);
4675     }
4676   else
4677     unlink_if_ordinary (tmpname);
4678
4679   if (change_warn)
4680     {
4681       struct section_list *p;
4682
4683       for (p = change_sections; p != NULL; p = p->next)
4684         {
4685           if (! p->used)
4686             {
4687               if (p->context & (SECTION_CONTEXT_SET_VMA | SECTION_CONTEXT_ALTER_VMA))
4688                 {
4689                   char buff [20];
4690
4691                   sprintf_vma (buff, p->vma_val);
4692
4693                   /* xgettext:c-format */
4694                   non_fatal (_("%s %s%c0x%s never used"),
4695                              "--change-section-vma",
4696                              p->pattern,
4697                              p->context & SECTION_CONTEXT_SET_VMA ? '=' : '+',
4698                              buff);
4699                 }
4700
4701               if (p->context & (SECTION_CONTEXT_SET_LMA | SECTION_CONTEXT_ALTER_LMA))
4702                 {
4703                   char buff [20];
4704
4705                   sprintf_vma (buff, p->lma_val);
4706
4707                   /* xgettext:c-format */
4708                   non_fatal (_("%s %s%c0x%s never used"),
4709                              "--change-section-lma",
4710                              p->pattern,
4711                              p->context & SECTION_CONTEXT_SET_LMA ? '=' : '+',
4712                              buff);
4713                 }
4714             }
4715         }
4716     }
4717
4718   return 0;
4719 }
4720
4721 int
4722 main (int argc, char *argv[])
4723 {
4724 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
4725   setlocale (LC_MESSAGES, "");
4726 #endif
4727 #if defined (HAVE_SETLOCALE)
4728   setlocale (LC_CTYPE, "");
4729 #endif
4730   bindtextdomain (PACKAGE, LOCALEDIR);
4731   textdomain (PACKAGE);
4732
4733   program_name = argv[0];
4734   xmalloc_set_program_name (program_name);
4735
4736   START_PROGRESS (program_name, 0);
4737
4738   expandargv (&argc, &argv);
4739
4740   strip_symbols = STRIP_UNDEF;
4741   discard_locals = LOCALS_UNDEF;
4742
4743   bfd_init ();
4744   set_default_bfd_target ();
4745
4746   if (is_strip < 0)
4747     {
4748       int i = strlen (program_name);
4749 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
4750       /* Drop the .exe suffix, if any.  */
4751       if (i > 4 && FILENAME_CMP (program_name + i - 4, ".exe") == 0)
4752         {
4753           i -= 4;
4754           program_name[i] = '\0';
4755         }
4756 #endif
4757       is_strip = (i >= 5 && FILENAME_CMP (program_name + i - 5, "strip") == 0);
4758     }
4759
4760   create_symbol_htabs ();
4761
4762   if (argv != NULL)
4763     bfd_set_error_program_name (argv[0]);
4764
4765   if (is_strip)
4766     strip_main (argc, argv);
4767   else
4768     copy_main (argc, argv);
4769
4770   END_PROGRESS (program_name);
4771
4772   return status;
4773 }