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