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