Coverage Report

Created: 2024-05-21 06:29

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