Add --binary-architecture switch to objcopy to allow the output architecture
[external/binutils.git] / binutils / objcopy.c
1 /* objcopy.c -- copy object file from input to output, optionally massaging it.
2    Copyright (C) 1991, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2001
3    Free Software Foundation, Inc.
4
5    This file is part of GNU Binutils.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.  */
21 \f
22 #include "bfd.h"
23 #include "progress.h"
24 #include "bucomm.h"
25 #include "getopt.h"
26 #include "libiberty.h"
27 #include "budbg.h"
28 #include "filenames.h"
29 #include <sys/stat.h>
30
31 /* A list of symbols to explicitly strip out, or to keep.  A linked
32    list is good enough for a small number from the command line, but
33    this will slow things down a lot if many symbols are being
34    deleted. */
35
36 struct symlist
37 {
38   const char *name;
39   struct symlist *next;
40 };
41
42 /* A list to support redefine_sym.  */
43 struct redefine_node
44 {
45   char *source;
46   char *target;
47   struct redefine_node *next;
48 };
49
50 static void copy_usage PARAMS ((FILE *, int));
51 static void strip_usage PARAMS ((FILE *, int));
52 static flagword parse_flags PARAMS ((const char *));
53 static struct section_list *find_section_list PARAMS ((const char *, boolean));
54 static void setup_section PARAMS ((bfd *, asection *, PTR));
55 static void copy_section PARAMS ((bfd *, asection *, PTR));
56 static void get_sections PARAMS ((bfd *, asection *, PTR));
57 static int compare_section_lma PARAMS ((const PTR, const PTR));
58 static void add_specific_symbol PARAMS ((const char *, struct symlist **));
59 static boolean is_specified_symbol PARAMS ((const char *, struct symlist *));
60 static boolean is_strip_section PARAMS ((bfd *, asection *));
61 static unsigned int filter_symbols
62   PARAMS ((bfd *, bfd *, asymbol **, asymbol **, long));
63 static void mark_symbols_used_in_relocations PARAMS ((bfd *, asection *, PTR));
64 static void filter_bytes PARAMS ((char *, bfd_size_type *));
65 static boolean write_debugging_info PARAMS ((bfd *, PTR, long *, asymbol ***));
66 static void copy_object PARAMS ((bfd *, bfd *));
67 static void copy_archive PARAMS ((bfd *, bfd *, const char *));
68 static void copy_file
69   PARAMS ((const char *, const char *, const char *, const char *));
70 static int strip_main PARAMS ((int, char **));
71 static int copy_main PARAMS ((int, char **));
72 static const char *lookup_sym_redefinition PARAMS((const char *));
73 static void redefine_list_append PARAMS ((const char *, const char *));
74
75 #define RETURN_NONFATAL(s) {bfd_nonfatal (s); status = 1; return;}
76
77 static asymbol **isympp = NULL; /* Input symbols */
78 static asymbol **osympp = NULL; /* Output symbols that survive stripping */
79
80 /* If `copy_byte' >= 0, copy only that byte of every `interleave' bytes.  */
81 static int copy_byte = -1;
82 static int interleave = 4;
83
84 static boolean verbose;         /* Print file and target names. */
85 static boolean preserve_dates;  /* Preserve input file timestamp.  */
86 static int status = 0;          /* Exit status.  */
87
88 enum strip_action
89   {
90     STRIP_UNDEF,
91     STRIP_NONE,                 /* don't strip */
92     STRIP_DEBUG,                /* strip all debugger symbols */
93     STRIP_UNNEEDED,             /* strip unnecessary symbols */
94     STRIP_ALL                   /* strip all symbols */
95   };
96
97 /* Which symbols to remove. */
98 static enum strip_action strip_symbols;
99
100 enum locals_action
101   {
102     LOCALS_UNDEF,
103     LOCALS_START_L,             /* discard locals starting with L */
104     LOCALS_ALL                  /* discard all locals */
105   };
106
107 /* Which local symbols to remove.  Overrides STRIP_ALL.  */
108 static enum locals_action discard_locals;
109
110 /* What kind of change to perform.  */
111 enum change_action
112 {
113   CHANGE_IGNORE,
114   CHANGE_MODIFY,
115   CHANGE_SET
116 };
117
118 /* Structure used to hold lists of sections and actions to take.  */
119 struct section_list
120 {
121   struct section_list * next;      /* Next section to change.  */
122   const char *          name;      /* Section name.  */
123   boolean               used;      /* Whether this entry was used.  */
124   boolean               remove;    /* Whether to remove this section.  */
125   boolean               copy;      /* Whether to copy this section.  */
126   enum change_action    change_vma;/* Whether to change or set VMA.  */
127   bfd_vma               vma_val;   /* Amount to change by or set to.  */
128   enum change_action    change_lma;/* Whether to change or set LMA.  */
129   bfd_vma               lma_val;   /* Amount to change by or set to.  */
130   boolean               set_flags; /* Whether to set the section flags.  */
131   flagword              flags;     /* What to set the section flags to.  */
132 };
133
134 static struct section_list *change_sections;
135 static boolean sections_removed;
136 static boolean sections_copied;
137
138 /* Changes to the start address.  */
139 static bfd_vma change_start = 0;
140 static boolean set_start_set = false;
141 static bfd_vma set_start;
142
143 /* Changes to section addresses.  */
144 static bfd_vma change_section_address = 0;
145
146 /* Filling gaps between sections.  */
147 static boolean gap_fill_set = false;
148 static bfd_byte gap_fill = 0;
149
150 /* Pad to a given address.  */
151 static boolean pad_to_set = false;
152 static bfd_vma pad_to;
153
154 /* List of sections to add.  */
155
156 struct section_add
157 {
158   /* Next section to add.  */
159   struct section_add *next;
160   /* Name of section to add.  */
161   const char *name;
162   /* Name of file holding section contents.  */
163   const char *filename;
164   /* Size of file.  */
165   size_t size;
166   /* Contents of file.  */
167   bfd_byte *contents;
168   /* BFD section, after it has been added.  */
169   asection *section;
170 };
171
172 static struct section_add *add_sections;
173
174 /* Whether to convert debugging information.  */
175
176 static boolean convert_debugging = false;
177
178 /* Whether to change the leading character in symbol names.  */
179
180 static boolean change_leading_char = false;
181
182 /* Whether to remove the leading character from global symbol names.  */
183
184 static boolean remove_leading_char = false;
185
186 /* List of symbols to strip, keep, localize, weaken, or redefine.  */
187
188 static struct symlist *strip_specific_list = NULL;
189 static struct symlist *keep_specific_list = NULL;
190 static struct symlist *localize_specific_list = NULL;
191 static struct symlist *weaken_specific_list = NULL;
192 static struct redefine_node *redefine_sym_list = NULL;
193
194 /* If this is true, we weaken global symbols (set BSF_WEAK).  */
195
196 static boolean weaken = false;
197
198 /* 150 isn't special; it's just an arbitrary non-ASCII char value.  */
199
200 #define OPTION_ADD_SECTION 150
201 #define OPTION_CHANGE_ADDRESSES (OPTION_ADD_SECTION + 1)
202 #define OPTION_CHANGE_LEADING_CHAR (OPTION_CHANGE_ADDRESSES + 1)
203 #define OPTION_CHANGE_START (OPTION_CHANGE_LEADING_CHAR + 1)
204 #define OPTION_CHANGE_SECTION_ADDRESS (OPTION_CHANGE_START + 1)
205 #define OPTION_CHANGE_SECTION_LMA (OPTION_CHANGE_SECTION_ADDRESS + 1)
206 #define OPTION_CHANGE_SECTION_VMA (OPTION_CHANGE_SECTION_LMA + 1)
207 #define OPTION_CHANGE_WARNINGS (OPTION_CHANGE_SECTION_VMA + 1)
208 #define OPTION_DEBUGGING (OPTION_CHANGE_WARNINGS + 1)
209 #define OPTION_GAP_FILL (OPTION_DEBUGGING + 1)
210 #define OPTION_NO_CHANGE_WARNINGS (OPTION_GAP_FILL + 1)
211 #define OPTION_PAD_TO (OPTION_NO_CHANGE_WARNINGS + 1)
212 #define OPTION_REMOVE_LEADING_CHAR (OPTION_PAD_TO + 1)
213 #define OPTION_SET_SECTION_FLAGS (OPTION_REMOVE_LEADING_CHAR + 1)
214 #define OPTION_SET_START (OPTION_SET_SECTION_FLAGS + 1)
215 #define OPTION_STRIP_UNNEEDED (OPTION_SET_START + 1)
216 #define OPTION_WEAKEN (OPTION_STRIP_UNNEEDED + 1)
217 #define OPTION_REDEFINE_SYM (OPTION_WEAKEN + 1)
218 #define OPTION_SREC_LEN (OPTION_REDEFINE_SYM + 1)
219 #define OPTION_SREC_FORCES3 (OPTION_SREC_LEN + 1)
220
221 /* Options to handle if running as "strip".  */
222
223 static struct option strip_options[] =
224 {
225   {"discard-all", no_argument, 0, 'x'},
226   {"discard-locals", no_argument, 0, 'X'},
227   {"format", required_argument, 0, 'F'}, /* Obsolete */
228   {"help", no_argument, 0, 'h'},
229   {"input-format", required_argument, 0, 'I'}, /* Obsolete */
230   {"input-target", required_argument, 0, 'I'},
231   {"keep-symbol", required_argument, 0, 'K'},
232   {"output-format", required_argument, 0, 'O'}, /* Obsolete */
233   {"output-target", required_argument, 0, 'O'},
234   {"preserve-dates", no_argument, 0, 'p'},
235   {"remove-section", required_argument, 0, 'R'},
236   {"strip-all", no_argument, 0, 's'},
237   {"strip-debug", no_argument, 0, 'S'},
238   {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
239   {"strip-symbol", required_argument, 0, 'N'},
240   {"target", required_argument, 0, 'F'},
241   {"verbose", no_argument, 0, 'v'},
242   {"version", no_argument, 0, 'V'},
243   {0, no_argument, 0, 0}
244 };
245
246 /* Options to handle if running as "objcopy".  */
247
248 static struct option copy_options[] =
249 {
250   {"add-section", required_argument, 0, OPTION_ADD_SECTION},
251   {"adjust-start", required_argument, 0, OPTION_CHANGE_START},
252   {"adjust-vma", required_argument, 0, OPTION_CHANGE_ADDRESSES},
253   {"adjust-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
254   {"adjust-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
255   {"binary-architecture", required_argument, 0, 'B'},
256   {"byte", required_argument, 0, 'b'},
257   {"change-addresses", required_argument, 0, OPTION_CHANGE_ADDRESSES},
258   {"change-leading-char", no_argument, 0, OPTION_CHANGE_LEADING_CHAR},
259   {"change-section-address", required_argument, 0, OPTION_CHANGE_SECTION_ADDRESS},
260   {"change-section-lma", required_argument, 0, OPTION_CHANGE_SECTION_LMA},
261   {"change-section-vma", required_argument, 0, OPTION_CHANGE_SECTION_VMA},
262   {"change-start", required_argument, 0, OPTION_CHANGE_START},
263   {"change-warnings", no_argument, 0, OPTION_CHANGE_WARNINGS},
264   {"debugging", no_argument, 0, OPTION_DEBUGGING},
265   {"discard-all", no_argument, 0, 'x'},
266   {"discard-locals", no_argument, 0, 'X'},
267   {"only-section", required_argument, 0, 'j'},
268   {"format", required_argument, 0, 'F'}, /* Obsolete */
269   {"gap-fill", required_argument, 0, OPTION_GAP_FILL},
270   {"help", no_argument, 0, 'h'},
271   {"input-format", required_argument, 0, 'I'}, /* Obsolete */
272   {"input-target", required_argument, 0, 'I'},
273   {"interleave", required_argument, 0, 'i'},
274   {"keep-symbol", required_argument, 0, 'K'},
275   {"no-adjust-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
276   {"no-change-warnings", no_argument, 0, OPTION_NO_CHANGE_WARNINGS},
277   {"output-format", required_argument, 0, 'O'}, /* Obsolete */
278   {"output-target", required_argument, 0, 'O'},
279   {"pad-to", required_argument, 0, OPTION_PAD_TO},
280   {"preserve-dates", no_argument, 0, 'p'},
281   {"localize-symbol", required_argument, 0, 'L'},
282   {"remove-leading-char", no_argument, 0, OPTION_REMOVE_LEADING_CHAR},
283   {"remove-section", required_argument, 0, 'R'},
284   {"set-section-flags", required_argument, 0, OPTION_SET_SECTION_FLAGS},
285   {"set-start", required_argument, 0, OPTION_SET_START},
286   {"strip-all", no_argument, 0, 'S'},
287   {"strip-debug", no_argument, 0, 'g'},
288   {"strip-unneeded", no_argument, 0, OPTION_STRIP_UNNEEDED},
289   {"strip-symbol", required_argument, 0, 'N'},
290   {"target", required_argument, 0, 'F'},
291   {"verbose", no_argument, 0, 'v'},
292   {"version", no_argument, 0, 'V'},
293   {"weaken", no_argument, 0, OPTION_WEAKEN},
294   {"weaken-symbol", required_argument, 0, 'W'},
295   {"redefine-sym", required_argument, 0, OPTION_REDEFINE_SYM},
296   {"srec-len", required_argument, 0, OPTION_SREC_LEN},
297   {"srec-forceS3", no_argument, 0, OPTION_SREC_FORCES3},
298   {0, no_argument, 0, 0}
299 };
300
301 /* IMPORTS */
302 extern char *program_name;
303
304 /* This flag distinguishes between strip and objcopy:
305    1 means this is 'strip'; 0 means this is 'objcopy'.
306    -1 means if we should use argv[0] to decide. */
307 extern int is_strip;
308
309 /* The maximum length of an S record.  This variable is declared in srec.c
310    and can be modified by the --srec-len parameter.  */
311 extern unsigned int Chunk;
312
313 /* Restrict the generation of Srecords to type S3 only.
314    This variable is declare in bfd/srec.c and can be toggled
315    on by the --srec-forceS3 command line switch.  */
316 extern boolean S3Forced;
317
318 /* Defined in bfd/binary.c.  Used to set architecture of input binary files.  */
319 extern enum bfd_architecture bfd_external_binary_architecture;
320
321 static void
322 copy_usage (stream, exit_status)
323      FILE *stream;
324      int exit_status;
325 {
326   fprintf (stream, _("Usage: %s <switches> in-file [out-file]\n"), program_name);
327   fprintf (stream, _(" The switches are:\n"));
328   fprintf (stream, _("\
329   -I --input-target <bfdname>      Assume input file is in format <bfdname>\n\
330   -O --output-target <bfdname>     Create an output file in format <bfdname>\n\
331   -B --binary-architecture <arch>  Set arch of output file, when input is binary\n\
332   -F --target <bfdname>            Set both input and output format to <bfdname>\n\
333      --debugging                   Convert debugging information, if possible\n\
334   -p --preserve-dates              Copy modified/access timestamps to the output\n\
335   -j --only-section <name>         Only copy section <name> into the output\n\
336   -R --remove-section <name>       Remove section <name> from the output\n\
337   -S --strip-all                   Remove all symbol and relocation information\n\
338   -g --strip-debug                 Remove all debugging symbols\n\
339      --strip-unneeded              Remove all symbols not needed by relocations\n\
340   -N --strip-symbol <name>         Do not copy symbol <name>\n\
341   -K --keep-symbol <name>          Only copy symbol <name>\n\
342   -L --localize-symbol <name>      Force symbol <name> to be marked as a local\n\
343   -W --weaken-symbol <name>        Force symbol <name> to be marked as a weak\n\
344      --weaken                      Force all global symbols to be marked as weak\n\
345   -x --discard-all                 Remove all non-global symbols\n\
346   -X --discard-locals              Remove any compiler-generated symbols\n\
347   -i --interleave <number>         Only copy one out of every <number> bytes\n\
348   -b --byte <num>                  Select byte <num> in every interleaved block\n\
349      --gap-fill <val>              Fill gaps between sections with <val>\n\
350      --pad-to <addr>               Pad the last section up to address <addr>\n\
351      --set-start <addr>            Set the start address to <addr>\n\
352     {--change-start|--adjust-start} <incr>\n\
353                                    Add <incr> to the start address\n\
354     {--change-addresses|--adjust-vma} <incr>\n\
355                                    Add <incr> to LMA, VMA and start addresses\n\
356     {--change-section-address|--adjust-section-vma} <name>{=|+|-}<val>\n\
357                                    Change LMA and VMA of section <name> by <val>\n\
358      --change-section-lma <name>{=|+|-}<val>\n\
359                                    Change the LMA of section <name> by <val>\n\
360      --change-section-vma <name>{=|+|-}<val>\n\
361                                    Change the VMA of section <name> by <val>\n\
362     {--[no-]change-warnings|--[no-]adjust-warnings}\n\
363                                    Warn if a named section does not exist\n\
364      --set-section-flags <name>=<flags>\n\
365                                    Set section <name>'s properties to <flags>\n\
366      --add-section <name>=<file>   Add section <name> found in <file> to output\n\
367      --change-leading-char         Force output format's leading character style\n\
368      --remove-leading-char         Remove leading character from global symbols\n\
369      --redefine-sym <old>=<new>    Redefine symbol name <old> to <new>\n\
370      --srec-len <number>           Restrict the length of generated Srecords\n\
371      --srec-forceS3                Restrict the type of generated Srecords to S3\n\
372   -v --verbose                     List all object files modified\n\
373   -V --version                     Display this program's version number\n\
374   -h --help                        Display this output\n\
375 "));
376   list_supported_targets (program_name, stream);
377   if (exit_status == 0)
378     fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
379   exit (exit_status);
380 }
381
382 static void
383 strip_usage (stream, exit_status)
384      FILE *stream;
385      int exit_status;
386 {
387   fprintf (stream, _("Usage: %s <switches> in-file(s)\n"), program_name);
388   fprintf (stream, _(" The switches are:\n"));
389   fprintf (stream, _("\
390   -I --input-target <bfdname>      Assume input file is in format <bfdname>\n\
391   -O --output-target <bfdname>     Create an output file in format <bfdname>\n\
392   -F --target <bfdname>            Set both input and output format to <bfdname>\n\
393   -p --preserve-dates              Copy modified/access timestamps to the output\n\
394   -R --remove-section <name>       Remove section <name> from the output\n\
395   -s --strip-all                   Remove all symbol and relocation information\n\
396   -g -S --strip-debug              Remove all debugging symbols\n\
397      --strip-unneeded              Remove all symbols not needed by relocations\n\
398   -N --strip-symbol <name>         Do not copy symbol <name>\n\
399   -K --keep-symbol <name>          Only copy symbol <name>\n\
400   -x --discard-all                 Remove all non-global symbols\n\
401   -X --discard-locals              Remove any compiler-generated symbols\n\
402   -v --verbose                     List all object files modified\n\
403   -V --version                     Display this program's version number\n\
404   -h --help                        Display this output\n\
405   -o <file>                        Place stripped output into <file>\n\
406 "));
407
408   list_supported_targets (program_name, stream);
409   if (exit_status == 0)
410     fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
411   exit (exit_status);
412 }
413
414 /* Parse section flags into a flagword, with a fatal error if the
415    string can't be parsed.  */
416
417 static flagword
418 parse_flags (s)
419      const char *s;
420 {
421   flagword ret;
422   const char *snext;
423   int len;
424
425   ret = SEC_NO_FLAGS;
426
427   do
428     {
429       snext = strchr (s, ',');
430       if (snext == NULL)
431         len = strlen (s);
432       else
433         {
434           len = snext - s;
435           ++snext;
436         }
437
438       if (0) ;
439 #define PARSE_FLAG(fname,fval) \
440   else if (strncasecmp (fname, s, len) == 0) ret |= fval
441       PARSE_FLAG ("alloc", SEC_ALLOC);
442       PARSE_FLAG ("load", SEC_LOAD);
443       PARSE_FLAG ("noload", SEC_NEVER_LOAD);
444       PARSE_FLAG ("readonly", SEC_READONLY);
445       PARSE_FLAG ("debug", SEC_DEBUGGING);
446       PARSE_FLAG ("code", SEC_CODE);
447       PARSE_FLAG ("data", SEC_DATA);
448       PARSE_FLAG ("rom", SEC_ROM);
449       PARSE_FLAG ("share", SEC_SHARED);
450       PARSE_FLAG ("contents", SEC_HAS_CONTENTS);
451 #undef PARSE_FLAG
452       else
453         {
454           char *copy;
455
456           copy = xmalloc (len + 1);
457           strncpy (copy, s, len);
458           copy[len] = '\0';
459           non_fatal (_("unrecognized section flag `%s'"), copy);
460           fatal (_("supported flags: %s"),
461                  "alloc, load, noload, readonly, debug, code, data, rom, share, contents");
462         }
463
464       s = snext;
465     }
466   while (s != NULL);
467
468   return ret;
469 }
470
471 /* Find and optionally add an entry in the change_sections list.  */
472
473 static struct section_list *
474 find_section_list (name, add)
475      const char *name;
476      boolean add;
477 {
478   register struct section_list *p;
479
480   for (p = change_sections; p != NULL; p = p->next)
481     if (strcmp (p->name, name) == 0)
482       return p;
483
484   if (! add)
485     return NULL;
486
487   p = (struct section_list *) xmalloc (sizeof (struct section_list));
488   p->name = name;
489   p->used = false;
490   p->remove = false;
491   p->copy = false;
492   p->change_vma = CHANGE_IGNORE;
493   p->change_lma = CHANGE_IGNORE;
494   p->vma_val = 0;
495   p->lma_val = 0;
496   p->set_flags = false;
497   p->flags = 0;
498
499   p->next = change_sections;
500   change_sections = p;
501
502   return p;
503 }
504
505 /* Add a symbol to strip_specific_list.  */
506
507 static void
508 add_specific_symbol (name, list)
509      const char *name;
510      struct symlist **list;
511 {
512   struct symlist *tmp_list;
513
514   tmp_list = (struct symlist *) xmalloc (sizeof (struct symlist));
515   tmp_list->name = name;
516   tmp_list->next = *list;
517   *list = tmp_list;
518 }
519
520 /* See whether a symbol should be stripped or kept based on
521    strip_specific_list and keep_symbols.  */
522
523 static boolean
524 is_specified_symbol (name, list)
525      const char *name;
526      struct symlist *list;
527 {
528   struct symlist *tmp_list;
529
530   for (tmp_list = list; tmp_list; tmp_list = tmp_list->next)
531     {
532       if (strcmp (name, tmp_list->name) == 0)
533         return true;
534     }
535   return false;
536 }
537
538 /* See if a section is being removed.  */
539
540 static boolean
541 is_strip_section (abfd, sec)
542      bfd *abfd ATTRIBUTE_UNUSED;
543      asection *sec;
544 {
545   struct section_list *p;
546
547   if ((bfd_get_section_flags (abfd, sec) & SEC_DEBUGGING) != 0
548       && (strip_symbols == STRIP_DEBUG
549           || strip_symbols == STRIP_UNNEEDED
550           || strip_symbols == STRIP_ALL
551           || discard_locals == LOCALS_ALL
552           || convert_debugging))
553     return true;
554
555   if (! sections_removed && ! sections_copied)
556     return false;
557
558   p = find_section_list (bfd_get_section_name (abfd, sec), false);
559   if (sections_removed && p != NULL && p->remove)
560     return true;
561   if (sections_copied && (p == NULL || ! p->copy))
562     return true;
563   return false;
564 }
565
566 /* Choose which symbol entries to copy; put the result in OSYMS.
567    We don't copy in place, because that confuses the relocs.
568    Return the number of symbols to print.  */
569
570 static unsigned int
571 filter_symbols (abfd, obfd, osyms, isyms, symcount)
572      bfd *abfd;
573      bfd *obfd;
574      asymbol **osyms, **isyms;
575      long symcount;
576 {
577   register asymbol **from = isyms, **to = osyms;
578   long src_count = 0, dst_count = 0;
579   int relocatable = (abfd->flags & (HAS_RELOC | EXEC_P | DYNAMIC))
580                     == HAS_RELOC;
581
582   for (; src_count < symcount; src_count++)
583     {
584       asymbol *sym = from[src_count];
585       flagword flags = sym->flags;
586       const char *name = bfd_asymbol_name (sym);
587       int keep;
588
589       if (redefine_sym_list)
590         {
591           const char *old_name, *new_name;
592
593           old_name = bfd_asymbol_name (sym);
594           new_name = lookup_sym_redefinition (old_name);
595           name = bfd_asymbol_name (sym) = new_name;
596         }
597
598       if (change_leading_char
599           && (bfd_get_symbol_leading_char (abfd)
600               != bfd_get_symbol_leading_char (obfd))
601           && (bfd_get_symbol_leading_char (abfd) == '\0'
602               || (name[0] == bfd_get_symbol_leading_char (abfd))))
603         {
604           if (bfd_get_symbol_leading_char (obfd) == '\0')
605             name = bfd_asymbol_name (sym) = name + 1;
606           else
607             {
608               char *n;
609
610               n = xmalloc (strlen (name) + 2);
611               n[0] = bfd_get_symbol_leading_char (obfd);
612               if (bfd_get_symbol_leading_char (abfd) == '\0')
613                 strcpy (n + 1, name);
614               else
615                 strcpy (n + 1, name + 1);
616               name = bfd_asymbol_name (sym) = n;
617             }
618         }
619
620       if (remove_leading_char
621           && ((flags & BSF_GLOBAL) != 0
622               || (flags & BSF_WEAK) != 0
623               || bfd_is_und_section (bfd_get_section (sym))
624               || bfd_is_com_section (bfd_get_section (sym)))
625           && name[0] == bfd_get_symbol_leading_char (abfd))
626         name = bfd_asymbol_name (sym) = name + 1;
627
628       if (strip_symbols == STRIP_ALL)
629         keep = 0;
630       else if ((flags & BSF_KEEP) != 0          /* Used in relocation.  */
631                || ((flags & BSF_SECTION_SYM) != 0
632                    && ((*bfd_get_section (sym)->symbol_ptr_ptr)->flags
633                        & BSF_KEEP) != 0))
634         keep = 1;
635       else if (relocatable                      /* Relocatable file. */
636                && (flags & (BSF_GLOBAL | BSF_WEAK)) != 0)
637         keep = 1;
638       else if ((flags & BSF_GLOBAL) != 0        /* Global symbol.  */
639                || (flags & BSF_WEAK) != 0
640                || bfd_is_und_section (bfd_get_section (sym))
641                || bfd_is_com_section (bfd_get_section (sym)))
642         keep = strip_symbols != STRIP_UNNEEDED;
643       else if ((flags & BSF_DEBUGGING) != 0)    /* Debugging symbol.  */
644         keep = (strip_symbols != STRIP_DEBUG
645                 && strip_symbols != STRIP_UNNEEDED
646                 && ! convert_debugging);
647       else                      /* Local symbol.  */
648         keep = (strip_symbols != STRIP_UNNEEDED
649                 && (discard_locals != LOCALS_ALL
650                     && (discard_locals != LOCALS_START_L
651                         || ! bfd_is_local_label (abfd, sym))));
652
653       if (keep && is_specified_symbol (name, strip_specific_list))
654         keep = 0;
655       if (!keep && is_specified_symbol (name, keep_specific_list))
656         keep = 1;
657       if (keep && is_strip_section (abfd, bfd_get_section (sym)))
658         keep = 0;
659
660       if (keep && (flags & BSF_GLOBAL) != 0
661           && (weaken || is_specified_symbol (name, weaken_specific_list)))
662         {
663           sym->flags &=~ BSF_GLOBAL;
664           sym->flags |= BSF_WEAK;
665         }
666       if (keep && (flags & (BSF_GLOBAL | BSF_WEAK))
667           && is_specified_symbol (name, localize_specific_list))
668         {
669           sym->flags &= ~(BSF_GLOBAL | BSF_WEAK);
670           sym->flags |= BSF_LOCAL;
671         }
672
673       if (keep)
674         to[dst_count++] = sym;
675     }
676
677   to[dst_count] = NULL;
678
679   return dst_count;
680 }
681
682 static const char *
683 lookup_sym_redefinition (source)
684      const char *source;
685 {
686   const char *result;
687   struct redefine_node *list;
688
689   result = source;
690
691   for (list = redefine_sym_list; list != NULL; list = list->next)
692     {
693       if (strcmp (source, list->source) == 0)
694         {
695           result = list->target;
696           break;
697         }
698     }
699   return result;
700 }
701
702 /* Add a node to a symbol redefine list */
703
704 static void
705 redefine_list_append (source, target)
706      const char *source;
707      const char *target;
708 {
709   struct redefine_node **p;
710   struct redefine_node *list;
711   struct redefine_node *new_node;
712
713   for (p = &redefine_sym_list; (list = *p) != NULL; p = &list->next)
714     {
715       if (strcmp (source, list->source) == 0)
716         {
717           fatal (_("%s: Multiple redefinition of symbol \"%s\""),
718                  "--redefine-sym",
719                   source);
720         }
721
722       if (strcmp (target, list->target) == 0)
723         {
724           fatal (_("%s: Symbol \"%s\" is target of more than one redefinition"),
725                  "--redefine-sym",
726                   target);
727         }
728     }
729
730   new_node = (struct redefine_node *) xmalloc (sizeof (struct redefine_node));
731
732   new_node->source = strdup (source);
733   new_node->target = strdup (target);
734   new_node->next = NULL;
735
736   *p = new_node;
737 }
738
739
740 /* Keep only every `copy_byte'th byte in MEMHUNK, which is *SIZE bytes long.
741    Adjust *SIZE.  */
742
743 static void
744 filter_bytes (memhunk, size)
745      char *memhunk;
746      bfd_size_type *size;
747 {
748   char *from = memhunk + copy_byte, *to = memhunk, *end = memhunk + *size;
749
750   for (; from < end; from += interleave)
751     *to++ = *from;
752   if (*size % interleave > (bfd_size_type) copy_byte)
753     *size = (*size / interleave) + 1;
754   else
755     *size /= interleave;
756 }
757
758 /* Copy object file IBFD onto OBFD.  */
759
760 static void
761 copy_object (ibfd, obfd)
762      bfd *ibfd;
763      bfd *obfd;
764 {
765   bfd_vma start;
766   long symcount;
767   asection **osections = NULL;
768   bfd_size_type *gaps = NULL;
769   bfd_size_type max_gap = 0;
770   long symsize;
771   PTR dhandle;
772
773   if (ibfd->xvec->byteorder != obfd->xvec->byteorder
774       && ibfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN
775       && obfd->xvec->byteorder != BFD_ENDIAN_UNKNOWN)
776     {
777       fatal (_("Unable to change endianness of input file(s)"));
778       return;
779     }
780
781   if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
782     RETURN_NONFATAL (bfd_get_filename (obfd));
783
784   if (verbose)
785     printf (_("copy from %s(%s) to %s(%s)\n"),
786             bfd_get_filename (ibfd), bfd_get_target (ibfd),
787             bfd_get_filename (obfd), bfd_get_target (obfd));
788
789   if (set_start_set)
790     start = set_start;
791   else
792     start = bfd_get_start_address (ibfd);
793   start += change_start;
794
795   if (!bfd_set_start_address (obfd, start)
796       || !bfd_set_file_flags (obfd,
797                               (bfd_get_file_flags (ibfd)
798                                & bfd_applicable_file_flags (obfd))))
799     RETURN_NONFATAL (bfd_get_filename (ibfd));
800
801   /* Copy architecture of input file to output file */
802   if (!bfd_set_arch_mach (obfd, bfd_get_arch (ibfd),
803                           bfd_get_mach (ibfd)))
804     non_fatal (_("Warning: Output file cannot represent architecture %s"),
805                bfd_printable_arch_mach (bfd_get_arch (ibfd),
806                                         bfd_get_mach (ibfd)));
807
808   if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
809     RETURN_NONFATAL (bfd_get_filename (ibfd));
810
811   if (isympp)
812     free (isympp);
813
814   if (osympp != isympp)
815     free (osympp);
816
817   /* BFD mandates that all output sections be created and sizes set before
818      any output is done.  Thus, we traverse all sections multiple times.  */
819   bfd_map_over_sections (ibfd, setup_section, (void *) obfd);
820
821   if (add_sections != NULL)
822     {
823       struct section_add *padd;
824       struct section_list *pset;
825
826       for (padd = add_sections; padd != NULL; padd = padd->next)
827         {
828           padd->section = bfd_make_section (obfd, padd->name);
829           if (padd->section == NULL)
830             {
831               non_fatal (_("can't create section `%s': %s"),
832                        padd->name, bfd_errmsg (bfd_get_error ()));
833               status = 1;
834               return;
835             }
836           else
837             {
838               flagword flags;
839
840               if (! bfd_set_section_size (obfd, padd->section, padd->size))
841                 RETURN_NONFATAL (bfd_get_filename (obfd));
842
843               pset = find_section_list (padd->name, false);
844               if (pset != NULL)
845                 pset->used = true;
846
847               if (pset != NULL && pset->set_flags)
848                 flags = pset->flags | SEC_HAS_CONTENTS;
849               else
850                 flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DATA;
851
852               if (! bfd_set_section_flags (obfd, padd->section, flags))
853                 RETURN_NONFATAL (bfd_get_filename (obfd));
854
855               if (pset != NULL)
856                 {
857                   if (pset->change_vma != CHANGE_IGNORE)
858                     if (! bfd_set_section_vma (obfd, padd->section, pset->vma_val))
859                       RETURN_NONFATAL (bfd_get_filename (obfd));
860
861                   if (pset->change_lma != CHANGE_IGNORE)
862                     {
863                       padd->section->lma = pset->lma_val;
864
865                       if (! bfd_set_section_alignment
866                           (obfd, padd->section,
867                            bfd_section_alignment (obfd, padd->section)))
868                         RETURN_NONFATAL (bfd_get_filename (obfd));
869                     }
870                 }
871             }
872         }
873     }
874
875   if (gap_fill_set || pad_to_set)
876     {
877       asection **set;
878       unsigned int c, i;
879
880       /* We must fill in gaps between the sections and/or we must pad
881          the last section to a specified address.  We do this by
882          grabbing a list of the sections, sorting them by VMA, and
883          increasing the section sizes as required to fill the gaps.
884          We write out the gap contents below.  */
885
886       c = bfd_count_sections (obfd);
887       osections = (asection **) xmalloc (c * sizeof (asection *));
888       set = osections;
889       bfd_map_over_sections (obfd, get_sections, (void *) &set);
890
891       qsort (osections, c, sizeof (asection *), compare_section_lma);
892
893       gaps = (bfd_size_type *) xmalloc (c * sizeof (bfd_size_type));
894       memset (gaps, 0, c * sizeof (bfd_size_type));
895
896       if (gap_fill_set)
897         {
898           for (i = 0; i < c - 1; i++)
899             {
900               flagword flags;
901               bfd_size_type size;
902               bfd_vma gap_start, gap_stop;
903
904               flags = bfd_get_section_flags (obfd, osections[i]);
905               if ((flags & SEC_HAS_CONTENTS) == 0
906                   || (flags & SEC_LOAD) == 0)
907                 continue;
908
909               size = bfd_section_size (obfd, osections[i]);
910               gap_start = bfd_section_lma (obfd, osections[i]) + size;
911               gap_stop = bfd_section_lma (obfd, osections[i + 1]);
912               if (gap_start < gap_stop)
913                 {
914                   if (! bfd_set_section_size (obfd, osections[i],
915                                               size + (gap_stop - gap_start)))
916                     {
917                       non_fatal (_("Can't fill gap after %s: %s"),
918                                bfd_get_section_name (obfd, osections[i]),
919                                bfd_errmsg (bfd_get_error ()));
920                       status = 1;
921                       break;
922                     }
923                   gaps[i] = gap_stop - gap_start;
924                   if (max_gap < gap_stop - gap_start)
925                     max_gap = gap_stop - gap_start;
926                 }
927             }
928         }
929
930       if (pad_to_set)
931         {
932           bfd_vma lma;
933           bfd_size_type size;
934
935           lma = bfd_section_lma (obfd, osections[c - 1]);
936           size = bfd_section_size (obfd, osections[c - 1]);
937           if (lma + size < pad_to)
938             {
939               if (! bfd_set_section_size (obfd, osections[c - 1],
940                                           pad_to - lma))
941                 {
942                   non_fatal (_("Can't add padding to %s: %s"),
943                            bfd_get_section_name (obfd, osections[c - 1]),
944                            bfd_errmsg (bfd_get_error ()));
945                   status = 1;
946                 }
947               else
948                 {
949                   gaps[c - 1] = pad_to - (lma + size);
950                   if (max_gap < pad_to - (lma + size))
951                     max_gap = pad_to - (lma + size);
952                 }
953             }
954         }
955     }
956
957   /* Symbol filtering must happen after the output sections have
958      been created, but before their contents are set.  */
959   dhandle = NULL;
960   symsize = bfd_get_symtab_upper_bound (ibfd);
961   if (symsize < 0)
962     RETURN_NONFATAL (bfd_get_filename (ibfd));
963
964   osympp = isympp = (asymbol **) xmalloc (symsize);
965   symcount = bfd_canonicalize_symtab (ibfd, isympp);
966   if (symcount < 0)
967     RETURN_NONFATAL (bfd_get_filename (ibfd));
968
969   if (convert_debugging)
970     dhandle = read_debugging_info (ibfd, isympp, symcount);
971
972   if (strip_symbols == STRIP_DEBUG
973       || strip_symbols == STRIP_ALL
974       || strip_symbols == STRIP_UNNEEDED
975       || discard_locals != LOCALS_UNDEF
976       || strip_specific_list != NULL
977       || keep_specific_list != NULL
978       || localize_specific_list != NULL
979       || weaken_specific_list != NULL
980       || sections_removed
981       || sections_copied
982       || convert_debugging
983       || change_leading_char
984       || remove_leading_char
985       || redefine_sym_list
986       || weaken)
987     {
988       /* Mark symbols used in output relocations so that they
989          are kept, even if they are local labels or static symbols.
990
991          Note we iterate over the input sections examining their
992          relocations since the relocations for the output sections
993          haven't been set yet.  mark_symbols_used_in_relocations will
994          ignore input sections which have no corresponding output
995          section.  */
996       if (strip_symbols != STRIP_ALL)
997         bfd_map_over_sections (ibfd,
998                                mark_symbols_used_in_relocations,
999                                (PTR)isympp);
1000       osympp = (asymbol **) xmalloc ((symcount + 1) * sizeof (asymbol *));
1001       symcount = filter_symbols (ibfd, obfd, osympp, isympp, symcount);
1002     }
1003
1004   if (convert_debugging && dhandle != NULL)
1005     {
1006       if (! write_debugging_info (obfd, dhandle, &symcount, &osympp))
1007         {
1008           status = 1;
1009           return;
1010         }
1011     }
1012
1013   bfd_set_symtab (obfd, osympp, symcount);
1014
1015   /* This has to happen after the symbol table has been set.  */
1016   bfd_map_over_sections (ibfd, copy_section, (void *) obfd);
1017
1018   if (add_sections != NULL)
1019     {
1020       struct section_add *padd;
1021
1022       for (padd = add_sections; padd != NULL; padd = padd->next)
1023         {
1024           if (! bfd_set_section_contents (obfd, padd->section,
1025                                           (PTR) padd->contents,
1026                                           (file_ptr) 0,
1027                                           (bfd_size_type) padd->size))
1028             RETURN_NONFATAL (bfd_get_filename (obfd));
1029         }
1030     }
1031
1032   if (gap_fill_set || pad_to_set)
1033     {
1034       bfd_byte *buf;
1035       int c, i;
1036
1037       /* Fill in the gaps.  */
1038
1039       if (max_gap > 8192)
1040         max_gap = 8192;
1041       buf = (bfd_byte *) xmalloc (max_gap);
1042       memset (buf, gap_fill, (size_t) max_gap);
1043
1044       c = bfd_count_sections (obfd);
1045       for (i = 0; i < c; i++)
1046         {
1047           if (gaps[i] != 0)
1048             {
1049               bfd_size_type left;
1050               file_ptr off;
1051
1052               left = gaps[i];
1053               off = bfd_section_size (obfd, osections[i]) - left;
1054               while (left > 0)
1055                 {
1056                   bfd_size_type now;
1057
1058                   if (left > 8192)
1059                     now = 8192;
1060                   else
1061                     now = left;
1062
1063                   if (! bfd_set_section_contents (obfd, osections[i], buf,
1064                                                   off, now))
1065                     RETURN_NONFATAL (bfd_get_filename (obfd));
1066
1067                   left -= now;
1068                   off += now;
1069                 }
1070             }
1071         }
1072     }
1073
1074   /* Allow the BFD backend to copy any private data it understands
1075      from the input BFD to the output BFD.  This is done last to
1076      permit the routine to look at the filtered symbol table, which is
1077      important for the ECOFF code at least.  */
1078   if (!bfd_copy_private_bfd_data (ibfd, obfd))
1079     {
1080       non_fatal (_("%s: error copying private BFD data: %s"),
1081                  bfd_get_filename (obfd),
1082                  bfd_errmsg (bfd_get_error ()));
1083       status = 1;
1084       return;
1085     }
1086 }
1087
1088 /* Read each archive element in turn from IBFD, copy the
1089    contents to temp file, and keep the temp file handle.  */
1090
1091 static void
1092 copy_archive (ibfd, obfd, output_target)
1093      bfd *ibfd;
1094      bfd *obfd;
1095      const char *output_target;
1096 {
1097   struct name_list
1098     {
1099       struct name_list *next;
1100       char *name;
1101       bfd *obfd;
1102     } *list, *l;
1103   bfd **ptr = &obfd->archive_head;
1104   bfd *this_element;
1105   char *dir = make_tempname (bfd_get_filename (obfd));
1106
1107   /* Make a temp directory to hold the contents.  */
1108 #if defined (_WIN32) && !defined (__CYGWIN32__)
1109   if (mkdir (dir) != 0)
1110 #else
1111   if (mkdir (dir, 0700) != 0)
1112 #endif
1113     {
1114       fatal (_("cannot mkdir %s for archive copying (error: %s)"),
1115              dir, strerror (errno));
1116     }
1117   obfd->has_armap = ibfd->has_armap;
1118
1119   list = NULL;
1120
1121   this_element = bfd_openr_next_archived_file (ibfd, NULL);
1122   while (!status && this_element != (bfd *) NULL)
1123     {
1124       /* Create an output file for this member.  */
1125       char *output_name = concat (dir, "/", bfd_get_filename (this_element),
1126                                   (char *) NULL);
1127       bfd *output_bfd = bfd_openw (output_name, output_target);
1128       bfd *last_element;
1129       struct stat buf;
1130       int stat_status = 0;
1131
1132       if (preserve_dates)
1133         {
1134           stat_status = bfd_stat_arch_elt (this_element, &buf);
1135           if (stat_status != 0)
1136             non_fatal (_("internal stat error on %s"),
1137                        bfd_get_filename (this_element));
1138         }
1139
1140       l = (struct name_list *) xmalloc (sizeof (struct name_list));
1141       l->name = output_name;
1142       l->next = list;
1143       list = l;
1144
1145       if (output_bfd == (bfd *) NULL)
1146         RETURN_NONFATAL (output_name);
1147
1148       if (!bfd_set_format (obfd, bfd_get_format (ibfd)))
1149         RETURN_NONFATAL (bfd_get_filename (obfd));
1150
1151       if (bfd_check_format (this_element, bfd_object) == true)
1152         copy_object (this_element, output_bfd);
1153
1154       if (!bfd_close (output_bfd))
1155         {
1156           bfd_nonfatal (bfd_get_filename (output_bfd));
1157           /* Error in new object file. Don't change archive. */
1158           status = 1;
1159         }
1160
1161       if (preserve_dates && stat_status == 0)
1162         set_times (output_name, &buf);
1163
1164       /* Open the newly output file and attach to our list.  */
1165       output_bfd = bfd_openr (output_name, output_target);
1166
1167       l->obfd = output_bfd;
1168
1169       *ptr = output_bfd;
1170       ptr = &output_bfd->next;
1171
1172       last_element = this_element;
1173
1174       this_element = bfd_openr_next_archived_file (ibfd, last_element);
1175
1176       bfd_close (last_element);
1177     }
1178   *ptr = (bfd *) NULL;
1179
1180   if (!bfd_close (obfd))
1181     RETURN_NONFATAL (bfd_get_filename (obfd));
1182
1183   if (!bfd_close (ibfd))
1184     RETURN_NONFATAL (bfd_get_filename (ibfd));
1185
1186   /* Delete all the files that we opened.  */
1187   for (l = list; l != NULL; l = l->next)
1188     {
1189       bfd_close (l->obfd);
1190       unlink (l->name);
1191     }
1192   rmdir (dir);
1193 }
1194
1195 /* The top-level control.  */
1196
1197 static void
1198 copy_file (input_filename, output_filename, input_target, output_target)
1199      const char *input_filename;
1200      const char *output_filename;
1201      const char *input_target;
1202      const char *output_target;
1203 {
1204   bfd *ibfd;
1205   char **matching;
1206
1207   /* To allow us to do "strip *" without dying on the first
1208      non-object file, failures are nonfatal.  */
1209
1210   ibfd = bfd_openr (input_filename, input_target);
1211   if (ibfd == NULL)
1212     RETURN_NONFATAL (input_filename);
1213
1214   if (bfd_check_format (ibfd, bfd_archive))
1215     {
1216       bfd *obfd;
1217
1218       /* bfd_get_target does not return the correct value until
1219          bfd_check_format succeeds.  */
1220       if (output_target == NULL)
1221         output_target = bfd_get_target (ibfd);
1222
1223       obfd = bfd_openw (output_filename, output_target);
1224       if (obfd == NULL)
1225         RETURN_NONFATAL (output_filename);
1226
1227       copy_archive (ibfd, obfd, output_target);
1228     }
1229   else if (bfd_check_format_matches (ibfd, bfd_object, &matching))
1230     {
1231       bfd *obfd;
1232
1233       /* bfd_get_target does not return the correct value until
1234          bfd_check_format succeeds.  */
1235       if (output_target == NULL)
1236         output_target = bfd_get_target (ibfd);
1237
1238       obfd = bfd_openw (output_filename, output_target);
1239       if (obfd == NULL)
1240         RETURN_NONFATAL (output_filename);
1241
1242       copy_object (ibfd, obfd);
1243
1244       if (!bfd_close (obfd))
1245         RETURN_NONFATAL (output_filename);
1246
1247       if (!bfd_close (ibfd))
1248         RETURN_NONFATAL (input_filename);
1249     }
1250   else
1251     {
1252       bfd_nonfatal (input_filename);
1253
1254       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1255         {
1256           list_matching_formats (matching);
1257           free (matching);
1258         }
1259
1260       status = 1;
1261     }
1262 }
1263
1264 /* Create a section in OBFD with the same name and attributes
1265    as ISECTION in IBFD.  */
1266
1267 static void
1268 setup_section (ibfd, isection, obfdarg)
1269      bfd *ibfd;
1270      sec_ptr isection;
1271      PTR obfdarg;
1272 {
1273   bfd *obfd = (bfd *) obfdarg;
1274   struct section_list *p;
1275   sec_ptr osection;
1276   bfd_size_type size;
1277   bfd_vma vma;
1278   bfd_vma lma;
1279   flagword flags;
1280   const char *err;
1281
1282   if ((bfd_get_section_flags (ibfd, isection) & SEC_DEBUGGING) != 0
1283       && (strip_symbols == STRIP_DEBUG
1284           || strip_symbols == STRIP_UNNEEDED
1285           || strip_symbols == STRIP_ALL
1286           || discard_locals == LOCALS_ALL
1287           || convert_debugging))
1288     return;
1289
1290   p = find_section_list (bfd_section_name (ibfd, isection), false);
1291   if (p != NULL)
1292     p->used = true;
1293
1294   if (sections_removed && p != NULL && p->remove)
1295     return;
1296   if (sections_copied && (p == NULL || ! p->copy))
1297     return;
1298
1299   osection = bfd_make_section_anyway (obfd, bfd_section_name (ibfd, isection));
1300
1301   if (osection == NULL)
1302     {
1303       err = _("making");
1304       goto loser;
1305     }
1306
1307   size = bfd_section_size (ibfd, isection);
1308   if (copy_byte >= 0)
1309     size = (size + interleave - 1) / interleave;
1310   if (! bfd_set_section_size (obfd, osection, size))
1311     {
1312       err = _("size");
1313       goto loser;
1314     }
1315
1316   vma = bfd_section_vma (ibfd, isection);
1317   if (p != NULL && p->change_vma == CHANGE_MODIFY)
1318     vma += p->vma_val;
1319   else if (p != NULL && p->change_vma == CHANGE_SET)
1320     vma = p->vma_val;
1321   else
1322     vma += change_section_address;
1323
1324   if (! bfd_set_section_vma (obfd, osection, vma))
1325     {
1326       err = _("vma");
1327       goto loser;
1328     }
1329
1330   lma = isection->lma;
1331   if ((p != NULL) && p->change_lma != CHANGE_IGNORE)
1332     {
1333       if (p->change_lma == CHANGE_MODIFY)
1334         lma += p->lma_val;
1335       else if (p->change_lma == CHANGE_SET)
1336         lma = p->lma_val;
1337       else
1338         abort ();
1339     }
1340   else
1341     lma += change_section_address;
1342
1343   osection->lma = lma;
1344
1345   /* FIXME: This is probably not enough.  If we change the LMA we
1346      may have to recompute the header for the file as well.  */
1347   if (bfd_set_section_alignment (obfd,
1348                                  osection,
1349                                  bfd_section_alignment (ibfd, isection))
1350       == false)
1351     {
1352       err = _("alignment");
1353       goto loser;
1354     }
1355
1356   flags = bfd_get_section_flags (ibfd, isection);
1357   if (p != NULL && p->set_flags)
1358     flags = p->flags | (flags & SEC_HAS_CONTENTS);
1359   if (!bfd_set_section_flags (obfd, osection, flags))
1360     {
1361       err = _("flags");
1362       goto loser;
1363     }
1364
1365   /* This used to be mangle_section; we do here to avoid using
1366      bfd_get_section_by_name since some formats allow multiple
1367      sections with the same name.  */
1368   isection->output_section = osection;
1369   isection->output_offset = 0;
1370
1371   /* Allow the BFD backend to copy any private data it understands
1372      from the input section to the output section.  */
1373   if (!bfd_copy_private_section_data (ibfd, isection, obfd, osection))
1374     {
1375       err = _("private data");
1376       goto loser;
1377     }
1378
1379   /* All went well */
1380   return;
1381
1382 loser:
1383   non_fatal (_("%s: section `%s': error in %s: %s"),
1384              bfd_get_filename (ibfd),
1385              bfd_section_name (ibfd, isection),
1386              err, bfd_errmsg (bfd_get_error ()));
1387   status = 1;
1388 }
1389
1390 /* Copy the data of input section ISECTION of IBFD
1391    to an output section with the same name in OBFD.
1392    If stripping then don't copy any relocation info.  */
1393
1394 static void
1395 copy_section (ibfd, isection, obfdarg)
1396      bfd *ibfd;
1397      sec_ptr isection;
1398      PTR obfdarg;
1399 {
1400   bfd *obfd = (bfd *) obfdarg;
1401   struct section_list *p;
1402   arelent **relpp;
1403   long relcount;
1404   sec_ptr osection;
1405   bfd_size_type size;
1406   long relsize;
1407
1408   /* If we have already failed earlier on, do not keep on generating
1409      complaints now.  */
1410   if (status != 0)
1411     return;
1412
1413   if ((bfd_get_section_flags (ibfd, isection) & SEC_DEBUGGING) != 0
1414       && (strip_symbols == STRIP_DEBUG
1415           || strip_symbols == STRIP_UNNEEDED
1416           || strip_symbols == STRIP_ALL
1417           || discard_locals == LOCALS_ALL
1418           || convert_debugging))
1419     {
1420       return;
1421     }
1422
1423   p = find_section_list (bfd_section_name (ibfd, isection), false);
1424
1425   if (sections_removed && p != NULL && p->remove)
1426     return;
1427   if (sections_copied && (p == NULL || ! p->copy))
1428     return;
1429
1430   osection = isection->output_section;
1431   size = bfd_get_section_size_before_reloc (isection);
1432
1433   if (size == 0 || osection == 0)
1434     return;
1435
1436
1437   relsize = bfd_get_reloc_upper_bound (ibfd, isection);
1438   if (relsize < 0)
1439     RETURN_NONFATAL (bfd_get_filename (ibfd));
1440
1441   if (relsize == 0)
1442     bfd_set_reloc (obfd, osection, (arelent **) NULL, 0);
1443   else
1444     {
1445       relpp = (arelent **) xmalloc (relsize);
1446       relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, isympp);
1447       if (relcount < 0)
1448         RETURN_NONFATAL (bfd_get_filename (ibfd));
1449
1450       if (strip_symbols == STRIP_ALL)
1451         {
1452           /* Remove relocations which are not in
1453              keep_strip_specific_list. */
1454           arelent **temp_relpp;
1455           long temp_relcount = 0;
1456           long i;
1457
1458           temp_relpp = (arelent **) xmalloc (relsize);
1459           for (i = 0; i < relcount; i++)
1460             if (is_specified_symbol
1461                 (bfd_asymbol_name (*relpp [i]->sym_ptr_ptr),
1462                  keep_specific_list))
1463               temp_relpp [temp_relcount++] = relpp [i];
1464           relcount = temp_relcount;
1465           free (relpp);
1466           relpp = temp_relpp;
1467         }
1468       bfd_set_reloc (obfd, osection,
1469                      (relcount == 0 ? (arelent **) NULL : relpp), relcount);
1470     }
1471
1472   isection->_cooked_size = isection->_raw_size;
1473   isection->reloc_done = true;
1474
1475   if (bfd_get_section_flags (ibfd, isection) & SEC_HAS_CONTENTS)
1476     {
1477       PTR memhunk = (PTR) xmalloc ((unsigned) size);
1478
1479       if (!bfd_get_section_contents (ibfd, isection, memhunk, (file_ptr) 0,
1480                                      size))
1481         RETURN_NONFATAL (bfd_get_filename (ibfd));
1482
1483       if (copy_byte >= 0)
1484         filter_bytes (memhunk, &size);
1485
1486       if (!bfd_set_section_contents (obfd, osection, memhunk, (file_ptr) 0,
1487                                      size))
1488         RETURN_NONFATAL (bfd_get_filename (obfd));
1489
1490       free (memhunk);
1491     }
1492   else if (p != NULL && p->set_flags && (p->flags & SEC_HAS_CONTENTS) != 0)
1493     {
1494       PTR memhunk = (PTR) xmalloc ((unsigned) size);
1495
1496       /* We don't permit the user to turn off the SEC_HAS_CONTENTS
1497          flag--they can just remove the section entirely and add it
1498          back again.  However, we do permit them to turn on the
1499          SEC_HAS_CONTENTS flag, and take it to mean that the section
1500          contents should be zeroed out.  */
1501
1502       memset (memhunk, 0, size);
1503       if (! bfd_set_section_contents (obfd, osection, memhunk, (file_ptr) 0,
1504                                       size))
1505         RETURN_NONFATAL (bfd_get_filename (obfd));
1506       free (memhunk);
1507     }
1508 }
1509
1510 /* Get all the sections.  This is used when --gap-fill or --pad-to is
1511    used.  */
1512
1513 static void
1514 get_sections (obfd, osection, secppparg)
1515      bfd *obfd ATTRIBUTE_UNUSED;
1516      asection *osection;
1517      PTR secppparg;
1518 {
1519   asection ***secppp = (asection ***) secppparg;
1520
1521   **secppp = osection;
1522   ++(*secppp);
1523 }
1524
1525 /* Sort sections by VMA.  This is called via qsort, and is used when
1526    --gap-fill or --pad-to is used.  We force non loadable or empty
1527    sections to the front, where they are easier to ignore.  */
1528
1529 static int
1530 compare_section_lma (arg1, arg2)
1531      const PTR arg1;
1532      const PTR arg2;
1533 {
1534   const asection **sec1 = (const asection **) arg1;
1535   const asection **sec2 = (const asection **) arg2;
1536   flagword flags1, flags2;
1537
1538   /* Sort non loadable sections to the front.  */
1539   flags1 = (*sec1)->flags;
1540   flags2 = (*sec2)->flags;
1541   if ((flags1 & SEC_HAS_CONTENTS) == 0
1542       || (flags1 & SEC_LOAD) == 0)
1543     {
1544       if ((flags2 & SEC_HAS_CONTENTS) != 0
1545           && (flags2 & SEC_LOAD) != 0)
1546         return -1;
1547     }
1548   else
1549     {
1550       if ((flags2 & SEC_HAS_CONTENTS) == 0
1551           || (flags2 & SEC_LOAD) == 0)
1552         return 1;
1553     }
1554
1555   /* Sort sections by LMA.  */
1556   if ((*sec1)->lma > (*sec2)->lma)
1557     return 1;
1558   else if ((*sec1)->lma < (*sec2)->lma)
1559     return -1;
1560
1561   /* Sort sections with the same LMA by size.  */
1562   if ((*sec1)->_raw_size > (*sec2)->_raw_size)
1563     return 1;
1564   else if ((*sec1)->_raw_size < (*sec2)->_raw_size)
1565     return -1;
1566
1567   return 0;
1568 }
1569
1570 /* Mark all the symbols which will be used in output relocations with
1571    the BSF_KEEP flag so that those symbols will not be stripped.
1572
1573    Ignore relocations which will not appear in the output file.  */
1574
1575 static void
1576 mark_symbols_used_in_relocations (ibfd, isection, symbolsarg)
1577      bfd *ibfd;
1578      sec_ptr isection;
1579      PTR symbolsarg;
1580 {
1581   asymbol **symbols = (asymbol **) symbolsarg;
1582   long relsize;
1583   arelent **relpp;
1584   long relcount, i;
1585
1586   /* Ignore an input section with no corresponding output section.  */
1587   if (isection->output_section == NULL)
1588     return;
1589
1590   relsize = bfd_get_reloc_upper_bound (ibfd, isection);
1591   if (relsize < 0)
1592     bfd_fatal (bfd_get_filename (ibfd));
1593
1594   if (relsize == 0)
1595     return;
1596
1597   relpp = (arelent **) xmalloc (relsize);
1598   relcount = bfd_canonicalize_reloc (ibfd, isection, relpp, symbols);
1599   if (relcount < 0)
1600     bfd_fatal (bfd_get_filename (ibfd));
1601
1602   /* Examine each symbol used in a relocation.  If it's not one of the
1603      special bfd section symbols, then mark it with BSF_KEEP.  */
1604   for (i = 0; i < relcount; i++)
1605     {
1606       if (*relpp[i]->sym_ptr_ptr != bfd_com_section_ptr->symbol
1607           && *relpp[i]->sym_ptr_ptr != bfd_abs_section_ptr->symbol
1608           && *relpp[i]->sym_ptr_ptr != bfd_und_section_ptr->symbol)
1609         (*relpp[i]->sym_ptr_ptr)->flags |= BSF_KEEP;
1610     }
1611
1612   if (relpp != NULL)
1613     free (relpp);
1614 }
1615
1616 /* Write out debugging information.  */
1617
1618 static boolean
1619 write_debugging_info (obfd, dhandle, symcountp, symppp)
1620      bfd *obfd;
1621      PTR dhandle;
1622      long *symcountp ATTRIBUTE_UNUSED;
1623      asymbol ***symppp ATTRIBUTE_UNUSED;
1624 {
1625   if (bfd_get_flavour (obfd) == bfd_target_ieee_flavour)
1626     return write_ieee_debugging_info (obfd, dhandle);
1627
1628   if (bfd_get_flavour (obfd) == bfd_target_coff_flavour
1629       || bfd_get_flavour (obfd) == bfd_target_elf_flavour)
1630     {
1631       bfd_byte *syms, *strings;
1632       bfd_size_type symsize, stringsize;
1633       asection *stabsec, *stabstrsec;
1634
1635       if (! write_stabs_in_sections_debugging_info (obfd, dhandle, &syms,
1636                                                     &symsize, &strings,
1637                                                     &stringsize))
1638         return false;
1639
1640       stabsec = bfd_make_section (obfd, ".stab");
1641       stabstrsec = bfd_make_section (obfd, ".stabstr");
1642       if (stabsec == NULL
1643           || stabstrsec == NULL
1644           || ! bfd_set_section_size (obfd, stabsec, symsize)
1645           || ! bfd_set_section_size (obfd, stabstrsec, stringsize)
1646           || ! bfd_set_section_alignment (obfd, stabsec, 2)
1647           || ! bfd_set_section_alignment (obfd, stabstrsec, 0)
1648           || ! bfd_set_section_flags (obfd, stabsec,
1649                                    (SEC_HAS_CONTENTS
1650                                     | SEC_READONLY
1651                                     | SEC_DEBUGGING))
1652           || ! bfd_set_section_flags (obfd, stabstrsec,
1653                                       (SEC_HAS_CONTENTS
1654                                        | SEC_READONLY
1655                                        | SEC_DEBUGGING)))
1656         {
1657           non_fatal (_("%s: can't create debugging section: %s"),
1658                      bfd_get_filename (obfd),
1659                      bfd_errmsg (bfd_get_error ()));
1660           return false;
1661         }
1662
1663       /* We can get away with setting the section contents now because
1664          the next thing the caller is going to do is copy over the
1665          real sections.  We may someday have to split the contents
1666          setting out of this function.  */
1667       if (! bfd_set_section_contents (obfd, stabsec, syms, (file_ptr) 0,
1668                                       symsize)
1669           || ! bfd_set_section_contents (obfd, stabstrsec, strings,
1670                                          (file_ptr) 0, stringsize))
1671         {
1672           non_fatal (_("%s: can't set debugging section contents: %s"),
1673                      bfd_get_filename (obfd),
1674                      bfd_errmsg (bfd_get_error ()));
1675           return false;
1676         }
1677
1678       return true;
1679     }
1680
1681   non_fatal (_("%s: don't know how to write debugging information for %s"),
1682              bfd_get_filename (obfd), bfd_get_target (obfd));
1683   return false;
1684 }
1685
1686 static int
1687 strip_main (argc, argv)
1688      int argc;
1689      char *argv[];
1690 {
1691   char *input_target = NULL, *output_target = NULL;
1692   boolean show_version = false;
1693   int c, i;
1694   struct section_list *p;
1695   char *output_file = NULL;
1696
1697   while ((c = getopt_long (argc, argv, "I:O:F:K:N:R:o:sSpdgxXVv",
1698                            strip_options, (int *) 0)) != EOF)
1699     {
1700       switch (c)
1701         {
1702         case 'I':
1703           input_target = optarg;
1704           break;
1705         case 'O':
1706           output_target = optarg;
1707           break;
1708         case 'F':
1709           input_target = output_target = optarg;
1710           break;
1711         case 'R':
1712           p = find_section_list (optarg, true);
1713           p->remove = true;
1714           sections_removed = true;
1715           break;
1716         case 's':
1717           strip_symbols = STRIP_ALL;
1718           break;
1719         case 'S':
1720         case 'g':
1721         case 'd':       /* Historic BSD alias for -g.  Used by early NetBSD.  */
1722           strip_symbols = STRIP_DEBUG;
1723           break;
1724         case OPTION_STRIP_UNNEEDED:
1725           strip_symbols = STRIP_UNNEEDED;
1726           break;
1727         case 'K':
1728           add_specific_symbol (optarg, &keep_specific_list);
1729           break;
1730         case 'N':
1731           add_specific_symbol (optarg, &strip_specific_list);
1732           break;
1733         case 'o':
1734           output_file = optarg;
1735           break;
1736         case 'p':
1737           preserve_dates = true;
1738           break;
1739         case 'x':
1740           discard_locals = LOCALS_ALL;
1741           break;
1742         case 'X':
1743           discard_locals = LOCALS_START_L;
1744           break;
1745         case 'v':
1746           verbose = true;
1747           break;
1748         case 'V':
1749           show_version = true;
1750           break;
1751         case 0:
1752           break;                /* we've been given a long option */
1753         case 'h':
1754           strip_usage (stdout, 0);
1755         default:
1756           strip_usage (stderr, 1);
1757         }
1758     }
1759
1760   if (show_version)
1761     print_version ("strip");
1762
1763   /* Default is to strip all symbols.  */
1764   if (strip_symbols == STRIP_UNDEF
1765       && discard_locals == LOCALS_UNDEF
1766       && strip_specific_list == NULL)
1767     strip_symbols = STRIP_ALL;
1768
1769   if (output_target == (char *) NULL)
1770     output_target = input_target;
1771
1772   i = optind;
1773   if (i == argc
1774       || (output_file != NULL && (i + 1) < argc))
1775     strip_usage (stderr, 1);
1776
1777   for (; i < argc; i++)
1778     {
1779       int hold_status = status;
1780       struct stat statbuf;
1781       char *tmpname;
1782
1783       if (preserve_dates)
1784         {
1785           if (stat (argv[i], &statbuf) < 0)
1786             {
1787               non_fatal (_("%s: cannot stat: %s"), argv[i], strerror (errno));
1788               continue;
1789             }
1790         }
1791
1792       if (output_file != NULL)
1793         tmpname = output_file;
1794       else
1795         tmpname = make_tempname (argv[i]);
1796       status = 0;
1797
1798       copy_file (argv[i], tmpname, input_target, output_target);
1799       if (status == 0)
1800         {
1801           if (preserve_dates)
1802             set_times (tmpname, &statbuf);
1803           if (output_file == NULL)
1804             smart_rename (tmpname, argv[i], preserve_dates);
1805           status = hold_status;
1806         }
1807       else
1808         unlink (tmpname);
1809       if (output_file == NULL)
1810         free (tmpname);
1811     }
1812
1813   return 0;
1814 }
1815
1816 static int
1817 copy_main (argc, argv)
1818      int argc;
1819      char *argv[];
1820 {
1821   char * binary_architecture = NULL;
1822   char *input_filename = NULL, *output_filename = NULL;
1823   char *input_target = NULL, *output_target = NULL;
1824   boolean show_version = false;
1825   boolean change_warn = true;
1826   int c;
1827   struct section_list *p;
1828   struct stat statbuf;
1829
1830   while ((c = getopt_long (argc, argv, "b:B:i:I:j:K:N:s:O:d:F:L:R:SpgxXVvW:",
1831                            copy_options, (int *) 0)) != EOF)
1832     {
1833       switch (c)
1834         {
1835         case 'b':
1836           copy_byte = atoi (optarg);
1837           if (copy_byte < 0)
1838             fatal (_("byte number must be non-negative"));
1839           break;
1840
1841         case 'B':
1842           binary_architecture = optarg;
1843           break;
1844
1845         case 'i':
1846           interleave = atoi (optarg);
1847           if (interleave < 1)
1848             fatal (_("interleave must be positive"));
1849           break;
1850
1851         case 'I':
1852         case 's':               /* "source" - 'I' is preferred */
1853           input_target = optarg;
1854           break;
1855
1856         case 'O':
1857         case 'd':               /* "destination" - 'O' is preferred */
1858           output_target = optarg;
1859           break;
1860
1861         case 'F':
1862           input_target = output_target = optarg;
1863           break;
1864
1865         case 'j':
1866           p = find_section_list (optarg, true);
1867           if (p->remove)
1868             fatal (_("%s both copied and removed"), optarg);
1869           p->copy = true;
1870           sections_copied = true;
1871           break;
1872
1873         case 'R':
1874           p = find_section_list (optarg, true);
1875           if (p->copy)
1876             fatal (_("%s both copied and removed"), optarg);
1877           p->remove = true;
1878           sections_removed = true;
1879           break;
1880
1881         case 'S':
1882           strip_symbols = STRIP_ALL;
1883           break;
1884
1885         case 'g':
1886           strip_symbols = STRIP_DEBUG;
1887           break;
1888
1889         case OPTION_STRIP_UNNEEDED:
1890           strip_symbols = STRIP_UNNEEDED;
1891           break;
1892
1893         case 'K':
1894           add_specific_symbol (optarg, &keep_specific_list);
1895           break;
1896
1897         case 'N':
1898           add_specific_symbol (optarg, &strip_specific_list);
1899           break;
1900
1901         case 'L':
1902           add_specific_symbol (optarg, &localize_specific_list);
1903           break;
1904
1905         case 'W':
1906           add_specific_symbol (optarg, &weaken_specific_list);
1907           break;
1908
1909         case 'p':
1910           preserve_dates = true;
1911           break;
1912
1913         case 'x':
1914           discard_locals = LOCALS_ALL;
1915           break;
1916
1917         case 'X':
1918           discard_locals = LOCALS_START_L;
1919           break;
1920
1921         case 'v':
1922           verbose = true;
1923           break;
1924
1925         case 'V':
1926           show_version = true;
1927           break;
1928
1929         case OPTION_WEAKEN:
1930           weaken = true;
1931           break;
1932
1933         case OPTION_ADD_SECTION:
1934           {
1935             const char *s;
1936             struct stat st;
1937             struct section_add *pa;
1938             int len;
1939             char *name;
1940             FILE *f;
1941
1942             s = strchr (optarg, '=');
1943
1944             if (s == NULL)
1945               fatal (_("bad format for %s"), "--add-section");
1946
1947             if (stat (s + 1, & st) < 0)
1948               fatal (_("cannot stat: %s: %s"), s + 1, strerror (errno));
1949
1950             pa = (struct section_add *) xmalloc (sizeof (struct section_add));
1951
1952             len = s - optarg;
1953             name = (char *) xmalloc (len + 1);
1954             strncpy (name, optarg, len);
1955             name[len] = '\0';
1956             pa->name = name;
1957
1958             pa->filename = s + 1;
1959
1960             pa->size = st.st_size;
1961
1962             pa->contents = (bfd_byte *) xmalloc (pa->size);
1963             f = fopen (pa->filename, FOPEN_RB);
1964
1965             if (f == NULL)
1966               fatal (_("cannot open: %s: %s"), pa->filename, strerror (errno));
1967
1968             if (fread (pa->contents, 1, pa->size, f) == 0
1969                 || ferror (f))
1970               fatal (_("%s: fread failed"), pa->filename);
1971
1972             fclose (f);
1973
1974             pa->next = add_sections;
1975             add_sections = pa;
1976           }
1977           break;
1978
1979         case OPTION_CHANGE_START:
1980           change_start = parse_vma (optarg, "--change-start");
1981           break;
1982
1983         case OPTION_CHANGE_SECTION_ADDRESS:
1984         case OPTION_CHANGE_SECTION_LMA:
1985         case OPTION_CHANGE_SECTION_VMA:
1986           {
1987             const char *s;
1988             int len;
1989             char *name;
1990             char *option = NULL;
1991             bfd_vma val;
1992             enum change_action what = CHANGE_IGNORE;
1993
1994             switch (c)
1995               {
1996               case OPTION_CHANGE_SECTION_ADDRESS:
1997                 option = "--change-section-address";
1998                 break;
1999               case OPTION_CHANGE_SECTION_LMA:
2000                 option = "--change-section-lma";
2001                 break;
2002               case OPTION_CHANGE_SECTION_VMA:
2003                 option = "--change-section-vma";
2004                 break;
2005               }
2006
2007             s = strchr (optarg, '=');
2008             if (s == NULL)
2009               {
2010                 s = strchr (optarg, '+');
2011                 if (s == NULL)
2012                   {
2013                     s = strchr (optarg, '-');
2014                     if (s == NULL)
2015                       fatal (_("bad format for %s"), option);
2016                   }
2017               }
2018
2019             len = s - optarg;
2020             name = (char *) xmalloc (len + 1);
2021             strncpy (name, optarg, len);
2022             name[len] = '\0';
2023
2024             p = find_section_list (name, true);
2025
2026             val = parse_vma (s + 1, option);
2027
2028             switch (*s)
2029               {
2030               case '=': what = CHANGE_SET; break;
2031               case '-': val  = - val; /* Drop through.  */
2032               case '+': what = CHANGE_MODIFY; break;
2033               }
2034
2035             switch (c)
2036               {
2037               case OPTION_CHANGE_SECTION_ADDRESS:
2038                 p->change_vma = what;
2039                 p->vma_val    = val;
2040                 /* Drop through.  */
2041
2042               case OPTION_CHANGE_SECTION_LMA:
2043                 p->change_lma = what;
2044                 p->lma_val    = val;
2045                 break;
2046
2047               case OPTION_CHANGE_SECTION_VMA:
2048                 p->change_vma = what;
2049                 p->vma_val    = val;
2050                 break;
2051               }
2052           }
2053           break;
2054
2055         case OPTION_CHANGE_ADDRESSES:
2056           change_section_address = parse_vma (optarg, "--change-addresses");
2057           change_start = change_section_address;
2058           break;
2059
2060         case OPTION_CHANGE_WARNINGS:
2061           change_warn = true;
2062           break;
2063
2064         case OPTION_CHANGE_LEADING_CHAR:
2065           change_leading_char = true;
2066           break;
2067
2068         case OPTION_DEBUGGING:
2069           convert_debugging = true;
2070           break;
2071
2072         case OPTION_GAP_FILL:
2073           {
2074             bfd_vma gap_fill_vma;
2075
2076             gap_fill_vma = parse_vma (optarg, "--gap-fill");
2077             gap_fill = (bfd_byte) gap_fill_vma;
2078             if ((bfd_vma) gap_fill != gap_fill_vma)
2079               {
2080                 char buff[20];
2081
2082                 sprintf_vma (buff, gap_fill_vma);
2083
2084                 non_fatal (_("Warning: truncating gap-fill from 0x%s to 0x%x"),
2085                            buff, gap_fill);
2086               }
2087             gap_fill_set = true;
2088           }
2089           break;
2090
2091         case OPTION_NO_CHANGE_WARNINGS:
2092           change_warn = false;
2093           break;
2094
2095         case OPTION_PAD_TO:
2096           pad_to = parse_vma (optarg, "--pad-to");
2097           pad_to_set = true;
2098           break;
2099
2100         case OPTION_REMOVE_LEADING_CHAR:
2101           remove_leading_char = true;
2102           break;
2103
2104         case OPTION_REDEFINE_SYM:
2105           {
2106             /* Push this redefinition onto redefine_symbol_list.  */
2107
2108             int len;
2109             const char *s;
2110             const char *nextarg;
2111             char *source, *target;
2112
2113             s = strchr (optarg, '=');
2114             if (s == NULL)
2115               {
2116                 fatal (_("bad format for %s"), "--redefine-sym");
2117               }
2118
2119             len = s - optarg;
2120             source = (char *) xmalloc (len + 1);
2121             strncpy (source, optarg, len);
2122             source[len] = '\0';
2123
2124             nextarg = s + 1;
2125             len = strlen (nextarg);
2126             target = (char *) xmalloc (len + 1);
2127             strcpy (target, nextarg);
2128
2129             redefine_list_append (source, target);
2130
2131             free (source);
2132             free (target);
2133           }
2134           break;
2135
2136         case OPTION_SET_SECTION_FLAGS:
2137           {
2138             const char *s;
2139             int len;
2140             char *name;
2141
2142             s = strchr (optarg, '=');
2143             if (s == NULL)
2144               fatal (_("bad format for %s"), "--set-section-flags");
2145
2146             len = s - optarg;
2147             name = (char *) xmalloc (len + 1);
2148             strncpy (name, optarg, len);
2149             name[len] = '\0';
2150
2151             p = find_section_list (name, true);
2152
2153             p->set_flags = true;
2154             p->flags = parse_flags (s + 1);
2155           }
2156           break;
2157
2158         case OPTION_SET_START:
2159           set_start = parse_vma (optarg, "--set-start");
2160           set_start_set = true;
2161           break;
2162
2163         case OPTION_SREC_LEN:
2164           Chunk = parse_vma (optarg, "--srec-len");
2165           break;
2166
2167         case OPTION_SREC_FORCES3:
2168           S3Forced = true;
2169           break;
2170
2171         case 0:
2172           break;                /* we've been given a long option */
2173
2174         case 'h':
2175           copy_usage (stdout, 0);
2176
2177         default:
2178           copy_usage (stderr, 1);
2179         }
2180     }
2181
2182   if (show_version)
2183     print_version ("objcopy");
2184
2185   if (copy_byte >= interleave)
2186     fatal (_("byte number must be less than interleave"));
2187
2188   if (optind == argc || optind + 2 < argc)
2189     copy_usage (stderr, 1);
2190
2191   input_filename = argv[optind];
2192   if (optind + 1 < argc)
2193     output_filename = argv[optind + 1];
2194
2195   /* Default is to strip no symbols.  */
2196   if (strip_symbols == STRIP_UNDEF && discard_locals == LOCALS_UNDEF)
2197     strip_symbols = STRIP_NONE;
2198
2199   if (output_target == (char *) NULL)
2200     output_target = input_target;
2201
2202   if (binary_architecture != (char *) NULL)
2203     {
2204       if (input_target && strcmp (input_target, "binary") == 0)
2205         {
2206           const bfd_arch_info_type * temp_arch_info;
2207
2208           temp_arch_info = bfd_scan_arch (binary_architecture);
2209
2210           if (temp_arch_info != NULL)
2211             bfd_external_binary_architecture = temp_arch_info->arch;
2212           else
2213             fatal (_("architecture %s unknown"), binary_architecture);
2214         }
2215       else
2216         {
2217           non_fatal (_("Warning: input target 'binary' required for binary architecture parameter."));
2218           non_fatal (_(" Argument %s ignored"), binary_architecture);
2219         }
2220     }
2221
2222   if (preserve_dates)
2223     if (stat (input_filename, & statbuf) < 0)
2224       fatal (_("Cannot stat: %s: %s"), input_filename, strerror (errno));
2225
2226   /* If there is no destination file then create a temp and rename
2227      the result into the input.  */
2228
2229   if (output_filename == (char *) NULL)
2230     {
2231       char *tmpname = make_tempname (input_filename);
2232
2233       copy_file (input_filename, tmpname, input_target, output_target);
2234       if (status == 0)
2235         {
2236           if (preserve_dates)
2237             set_times (tmpname, &statbuf);
2238           smart_rename (tmpname, input_filename, preserve_dates);
2239         }
2240       else
2241         unlink (tmpname);
2242     }
2243   else
2244     {
2245       copy_file (input_filename, output_filename, input_target, output_target);
2246       if (status == 0 && preserve_dates)
2247         set_times (output_filename, &statbuf);
2248     }
2249
2250   if (change_warn)
2251     {
2252       for (p = change_sections; p != NULL; p = p->next)
2253         {
2254           if (! p->used)
2255             {
2256               if (p->change_vma != CHANGE_IGNORE)
2257                 {
2258                   char buff [20];
2259
2260                   sprintf_vma (buff, p->vma_val);
2261
2262                   /* xgettext:c-format */
2263                   non_fatal (_("%s %s%c0x%s never used"),
2264                              "--change-section-vma",
2265                              p->name,
2266                              p->change_vma == CHANGE_SET ? '=' : '+',
2267                              buff);
2268                 }
2269
2270               if (p->change_lma != CHANGE_IGNORE)
2271                 {
2272                   char buff [20];
2273
2274                   sprintf_vma (buff, p->lma_val);
2275
2276                   /* xgettext:c-format */
2277                   non_fatal (_("%s %s%c0x%s never used"),
2278                              "--change-section-lma",
2279                              p->name,
2280                              p->change_lma == CHANGE_SET ? '=' : '+',
2281                              buff);
2282                 }
2283             }
2284         }
2285     }
2286
2287   return 0;
2288 }
2289
2290 int
2291 main (argc, argv)
2292      int argc;
2293      char *argv[];
2294 {
2295 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
2296   setlocale (LC_MESSAGES, "");
2297 #endif
2298   bindtextdomain (PACKAGE, LOCALEDIR);
2299   textdomain (PACKAGE);
2300
2301   program_name = argv[0];
2302   xmalloc_set_program_name (program_name);
2303
2304   START_PROGRESS (program_name, 0);
2305
2306   strip_symbols = STRIP_UNDEF;
2307   discard_locals = LOCALS_UNDEF;
2308
2309   bfd_init ();
2310   set_default_bfd_target ();
2311
2312   if (is_strip < 0)
2313     {
2314       int i = strlen (program_name);
2315 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
2316       /* Drop the .exe suffix, if any.  */
2317       if (i > 4 && FILENAME_CMP (program_name + i - 4, ".exe") == 0)
2318         {
2319           i -= 4;
2320           program_name[i] = '\0';
2321         }
2322 #endif
2323       is_strip = (i >= 5 && FILENAME_CMP (program_name + i - 5, "strip") == 0);
2324     }
2325
2326   if (is_strip)
2327     strip_main (argc, argv);
2328   else
2329     copy_main (argc, argv);
2330
2331   END_PROGRESS (program_name);
2332
2333   return status;
2334 }