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