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