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