1 /* Generic BFD library interface and support routines.
2    Copyright (C) 1990-2018 Free Software Foundation, Inc.
3    Written by Cygnus Support.
4 
5    This file is part of BFD, the Binary File Descriptor library.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21 
22 /*
23 INODE
24 typedef bfd, Error reporting, BFD front end, BFD front end
25 
26 SECTION
27 	<<typedef bfd>>
28 
29 	A BFD has type <<bfd>>; objects of this type are the
30 	cornerstone of any application using BFD. Using BFD
31 	consists of making references though the BFD and to data in the BFD.
32 
33 	Here is the structure that defines the type <<bfd>>.  It
34 	contains the major data about the file and pointers
35 	to the rest of the data.
36 
37 CODE_FRAGMENT
38 .
39 .enum bfd_direction
40 .  {
41 .    no_direction = 0,
42 .    read_direction = 1,
43 .    write_direction = 2,
44 .    both_direction = 3
45 .  };
46 .
47 .enum bfd_plugin_format
48 .  {
49 .    bfd_plugin_unknown = 0,
50 .    bfd_plugin_yes = 1,
51 .    bfd_plugin_no = 2
52 .  };
53 .
54 .struct bfd_build_id
55 .  {
56 .    bfd_size_type size;
57 .    bfd_byte data[1];
58 .  };
59 .
60 .struct bfd
61 .{
62 .  {* The filename the application opened the BFD with.  *}
63 .  const char *filename;
64 .
65 .  {* A pointer to the target jump table.  *}
66 .  const struct bfd_target *xvec;
67 .
68 .  {* The IOSTREAM, and corresponding IO vector that provide access
69 .     to the file backing the BFD.  *}
70 .  void *iostream;
71 .  const struct bfd_iovec *iovec;
72 .
73 .  {* The caching routines use these to maintain a
74 .     least-recently-used list of BFDs.  *}
75 .  struct bfd *lru_prev, *lru_next;
76 .
77 .  {* When a file is closed by the caching routines, BFD retains
78 .     state information on the file here...  *}
79 .  ufile_ptr where;
80 .
81 .  {* File modified time, if mtime_set is TRUE.  *}
82 .  long mtime;
83 .
84 .  {* A unique identifier of the BFD  *}
85 .  unsigned int id;
86 .
87 .  {* The format which belongs to the BFD. (object, core, etc.)  *}
88 .  ENUM_BITFIELD (bfd_format) format : 3;
89 .
90 .  {* The direction with which the BFD was opened.  *}
91 .  ENUM_BITFIELD (bfd_direction) direction : 2;
92 .
93 .  {* Format_specific flags.  *}
94 .  flagword flags : 20;
95 .
96 .  {* Values that may appear in the flags field of a BFD.  These also
97 .     appear in the object_flags field of the bfd_target structure, where
98 .     they indicate the set of flags used by that backend (not all flags
99 .     are meaningful for all object file formats) (FIXME: at the moment,
100 .     the object_flags values have mostly just been copied from backend
101 .     to another, and are not necessarily correct).  *}
102 .
103 .#define BFD_NO_FLAGS                0x0
104 .
105 .  {* BFD contains relocation entries.  *}
106 .#define HAS_RELOC                   0x1
107 .
108 .  {* BFD is directly executable.  *}
109 .#define EXEC_P                      0x2
110 .
111 .  {* BFD has line number information (basically used for F_LNNO in a
112 .     COFF header).  *}
113 .#define HAS_LINENO                  0x4
114 .
115 .  {* BFD has debugging information.  *}
116 .#define HAS_DEBUG                  0x08
117 .
118 .  {* BFD has symbols.  *}
119 .#define HAS_SYMS                   0x10
120 .
121 .  {* BFD has local symbols (basically used for F_LSYMS in a COFF
122 .     header).  *}
123 .#define HAS_LOCALS                 0x20
124 .
125 .  {* BFD is a dynamic object.  *}
126 .#define DYNAMIC                    0x40
127 .
128 .  {* Text section is write protected (if D_PAGED is not set, this is
129 .     like an a.out NMAGIC file) (the linker sets this by default, but
130 .     clears it for -r or -N).  *}
131 .#define WP_TEXT                    0x80
132 .
133 .  {* BFD is dynamically paged (this is like an a.out ZMAGIC file) (the
134 .     linker sets this by default, but clears it for -r or -n or -N).  *}
135 .#define D_PAGED                   0x100
136 .
137 .  {* BFD is relaxable (this means that bfd_relax_section may be able to
138 .     do something) (sometimes bfd_relax_section can do something even if
139 .     this is not set).  *}
140 .#define BFD_IS_RELAXABLE          0x200
141 .
142 .  {* This may be set before writing out a BFD to request using a
143 .     traditional format.  For example, this is used to request that when
144 .     writing out an a.out object the symbols not be hashed to eliminate
145 .     duplicates.  *}
146 .#define BFD_TRADITIONAL_FORMAT    0x400
147 .
148 .  {* This flag indicates that the BFD contents are actually cached
149 .     in memory.  If this is set, iostream points to a bfd_in_memory
150 .     struct.  *}
151 .#define BFD_IN_MEMORY             0x800
152 .
153 .  {* This BFD has been created by the linker and doesn't correspond
154 .     to any input file.  *}
155 .#define BFD_LINKER_CREATED       0x1000
156 .
157 .  {* This may be set before writing out a BFD to request that it
158 .     be written using values for UIDs, GIDs, timestamps, etc. that
159 .     will be consistent from run to run.  *}
160 .#define BFD_DETERMINISTIC_OUTPUT 0x2000
161 .
162 .  {* Compress sections in this BFD.  *}
163 .#define BFD_COMPRESS             0x4000
164 .
165 .  {* Decompress sections in this BFD.  *}
166 .#define BFD_DECOMPRESS           0x8000
167 .
168 .  {* BFD is a dummy, for plugins.  *}
169 .#define BFD_PLUGIN              0x10000
170 .
171 .  {* Compress sections in this BFD with SHF_COMPRESSED from gABI.  *}
172 .#define BFD_COMPRESS_GABI       0x20000
173 .
174 .  {* Convert ELF common symbol type to STT_COMMON or STT_OBJECT in this
175 .     BFD.  *}
176 .#define BFD_CONVERT_ELF_COMMON  0x40000
177 .
178 .  {* Use the ELF STT_COMMON type in this BFD.  *}
179 .#define BFD_USE_ELF_STT_COMMON  0x80000
180 .
181 .  {* Flags bits to be saved in bfd_preserve_save.  *}
182 .#define BFD_FLAGS_SAVED \
183 .  (BFD_IN_MEMORY | BFD_COMPRESS | BFD_DECOMPRESS | BFD_LINKER_CREATED \
184 .   | BFD_PLUGIN | BFD_COMPRESS_GABI | BFD_CONVERT_ELF_COMMON \
185 .   | BFD_USE_ELF_STT_COMMON)
186 .
187 .  {* Flags bits which are for BFD use only.  *}
188 .#define BFD_FLAGS_FOR_BFD_USE_MASK \
189 .  (BFD_IN_MEMORY | BFD_COMPRESS | BFD_DECOMPRESS | BFD_LINKER_CREATED \
190 .   | BFD_PLUGIN | BFD_TRADITIONAL_FORMAT | BFD_DETERMINISTIC_OUTPUT \
191 .   | BFD_COMPRESS_GABI | BFD_CONVERT_ELF_COMMON | BFD_USE_ELF_STT_COMMON)
192 .
193 .  {* Is the file descriptor being cached?  That is, can it be closed as
194 .     needed, and re-opened when accessed later?  *}
195 .  unsigned int cacheable : 1;
196 .
197 .  {* Marks whether there was a default target specified when the
198 .     BFD was opened. This is used to select which matching algorithm
199 .     to use to choose the back end.  *}
200 .  unsigned int target_defaulted : 1;
201 .
202 .  {* ... and here: (``once'' means at least once).  *}
203 .  unsigned int opened_once : 1;
204 .
205 .  {* Set if we have a locally maintained mtime value, rather than
206 .     getting it from the file each time.  *}
207 .  unsigned int mtime_set : 1;
208 .
209 .  {* Flag set if symbols from this BFD should not be exported.  *}
210 .  unsigned int no_export : 1;
211 .
212 .  {* Remember when output has begun, to stop strange things
213 .     from happening.  *}
214 .  unsigned int output_has_begun : 1;
215 .
216 .  {* Have archive map.  *}
217 .  unsigned int has_armap : 1;
218 .
219 .  {* Set if this is a thin archive.  *}
220 .  unsigned int is_thin_archive : 1;
221 .
222 .  {* Set if only required symbols should be added in the link hash table for
223 .     this object.  Used by VMS linkers.  *}
224 .  unsigned int selective_search : 1;
225 .
226 .  {* Set if this is the linker output BFD.  *}
227 .  unsigned int is_linker_output : 1;
228 .
229 .  {* Set if this is the linker input BFD.  *}
230 .  unsigned int is_linker_input : 1;
231 .
232 .  {* If this is an input for a compiler plug-in library.  *}
233 .  ENUM_BITFIELD (bfd_plugin_format) plugin_format : 2;
234 .
235 .  {* Set if this is a plugin output file.  *}
236 .  unsigned int lto_output : 1;
237 .
238 .  {* Set to dummy BFD created when claimed by a compiler plug-in
239 .     library.  *}
240 .  bfd *plugin_dummy_bfd;
241 .
242 .  {* Currently my_archive is tested before adding origin to
243 .     anything. I believe that this can become always an add of
244 .     origin, with origin set to 0 for non archive files.  *}
245 .  ufile_ptr origin;
246 .
247 .  {* The origin in the archive of the proxy entry.  This will
248 .     normally be the same as origin, except for thin archives,
249 .     when it will contain the current offset of the proxy in the
250 .     thin archive rather than the offset of the bfd in its actual
251 .     container.  *}
252 .  ufile_ptr proxy_origin;
253 .
254 .  {* A hash table for section names.  *}
255 .  struct bfd_hash_table section_htab;
256 .
257 .  {* Pointer to linked list of sections.  *}
258 .  struct bfd_section *sections;
259 .
260 .  {* The last section on the section list.  *}
261 .  struct bfd_section *section_last;
262 .
263 .  {* The number of sections.  *}
264 .  unsigned int section_count;
265 .
266 .  {* A field used by _bfd_generic_link_add_archive_symbols.  This will
267 .     be used only for archive elements.  *}
268 .  int archive_pass;
269 .
270 .  {* Stuff only useful for object files:
271 .     The start address.  *}
272 .  bfd_vma start_address;
273 .
274 .  {* Symbol table for output BFD (with symcount entries).
275 .     Also used by the linker to cache input BFD symbols.  *}
276 .  struct bfd_symbol  **outsymbols;
277 .
278 .  {* Used for input and output.  *}
279 .  unsigned int symcount;
280 .
281 .  {* Used for slurped dynamic symbol tables.  *}
282 .  unsigned int dynsymcount;
283 .
284 .  {* Pointer to structure which contains architecture information.  *}
285 .  const struct bfd_arch_info *arch_info;
286 .
287 .  {* Stuff only useful for archives.  *}
288 .  void *arelt_data;
289 .  struct bfd *my_archive;      {* The containing archive BFD.  *}
290 .  struct bfd *archive_next;    {* The next BFD in the archive.  *}
291 .  struct bfd *archive_head;    {* The first BFD in the archive.  *}
292 .  struct bfd *nested_archives; {* List of nested archive in a flattened
293 .				   thin archive.  *}
294 .
295 .  union {
296 .    {* For input BFDs, a chain of BFDs involved in a link.  *}
297 .    struct bfd *next;
298 .    {* For output BFD, the linker hash table.  *}
299 .    struct bfd_link_hash_table *hash;
300 .  } link;
301 .
302 .  {* Used by the back end to hold private data.  *}
303 .  union
304 .    {
305 .      struct aout_data_struct *aout_data;
306 .      struct artdata *aout_ar_data;
307 .      struct _oasys_data *oasys_obj_data;
308 .      struct _oasys_ar_data *oasys_ar_data;
309 .      struct coff_tdata *coff_obj_data;
310 .      struct pe_tdata *pe_obj_data;
311 .      struct xcoff_tdata *xcoff_obj_data;
312 .      struct ecoff_tdata *ecoff_obj_data;
313 .      struct ieee_data_struct *ieee_data;
314 .      struct ieee_ar_data_struct *ieee_ar_data;
315 .      struct srec_data_struct *srec_data;
316 .      struct verilog_data_struct *verilog_data;
317 .      struct ihex_data_struct *ihex_data;
318 .      struct tekhex_data_struct *tekhex_data;
319 .      struct elf_obj_tdata *elf_obj_data;
320 .      struct nlm_obj_tdata *nlm_obj_data;
321 .      struct bout_data_struct *bout_data;
322 .      struct mmo_data_struct *mmo_data;
323 .      struct sun_core_struct *sun_core_data;
324 .      struct sco5_core_struct *sco5_core_data;
325 .      struct trad_core_struct *trad_core_data;
326 .      struct som_data_struct *som_data;
327 .      struct hpux_core_struct *hpux_core_data;
328 .      struct hppabsd_core_struct *hppabsd_core_data;
329 .      struct sgi_core_struct *sgi_core_data;
330 .      struct lynx_core_struct *lynx_core_data;
331 .      struct osf_core_struct *osf_core_data;
332 .      struct cisco_core_struct *cisco_core_data;
333 .      struct versados_data_struct *versados_data;
334 .      struct netbsd_core_struct *netbsd_core_data;
335 .      struct mach_o_data_struct *mach_o_data;
336 .      struct mach_o_fat_data_struct *mach_o_fat_data;
337 .      struct plugin_data_struct *plugin_data;
338 .      struct bfd_pef_data_struct *pef_data;
339 .      struct bfd_pef_xlib_data_struct *pef_xlib_data;
340 .      struct bfd_sym_data_struct *sym_data;
341 .      struct asxxxx_data_struct *asxxxx_data;
342 .      void *any;
343 .    }
344 .  tdata;
345 .
346 .  {* Used by the application to hold private data.  *}
347 .  void *usrdata;
348 .
349 .  {* Where all the allocated stuff under this BFD goes.  This is a
350 .     struct objalloc *, but we use void * to avoid requiring the inclusion
351 .     of objalloc.h.  *}
352 .  void *memory;
353 .
354 .  {* For input BFDs, the build ID, if the object has one. *}
355 .  const struct bfd_build_id *build_id;
356 .};
357 .
358 .{* See note beside bfd_set_section_userdata.  *}
359 .static inline bfd_boolean
360 .bfd_set_cacheable (bfd * abfd, bfd_boolean val)
361 .{
362 .  abfd->cacheable = val;
363 .  return TRUE;
364 .}
365 .
366 */
367 
368 #include "sysdep.h"
369 #include <stdarg.h>
370 #include "bfd.h"
371 #include "bfdver.h"
372 #include "libiberty.h"
373 #include "demangle.h"
374 #include "safe-ctype.h"
375 #include "bfdlink.h"
376 #include "libbfd.h"
377 #include "coff/internal.h"
378 #include "coff/sym.h"
379 #include "libcoff.h"
380 #include "libecoff.h"
381 #undef obj_symbols
382 #include "elf-bfd.h"
383 
384 #ifndef EXIT_FAILURE
385 #define EXIT_FAILURE 1
386 #endif
387 
388 
389 /* provide storage for subsystem, stack and heap data which may have been
390    passed in on the command line.  Ld puts this data into a bfd_link_info
391    struct which ultimately gets passed in to the bfd.  When it arrives, copy
392    it to the following struct so that the data will be available in coffcode.h
393    where it is needed.  The typedef's used are defined in bfd.h */
394 
395 /*
396 INODE
397 Error reporting, Miscellaneous, typedef bfd, BFD front end
398 
399 SECTION
400 	Error reporting
401 
402 	Most BFD functions return nonzero on success (check their
403 	individual documentation for precise semantics).  On an error,
404 	they call <<bfd_set_error>> to set an error condition that callers
405 	can check by calling <<bfd_get_error>>.
406 	If that returns <<bfd_error_system_call>>, then check
407 	<<errno>>.
408 
409 	The easiest way to report a BFD error to the user is to
410 	use <<bfd_perror>>.
411 
412 SUBSECTION
413 	Type <<bfd_error_type>>
414 
415 	The values returned by <<bfd_get_error>> are defined by the
416 	enumerated type <<bfd_error_type>>.
417 
418 CODE_FRAGMENT
419 .
420 .typedef enum bfd_error
421 .{
422 .  bfd_error_no_error = 0,
423 .  bfd_error_system_call,
424 .  bfd_error_invalid_target,
425 .  bfd_error_wrong_format,
426 .  bfd_error_wrong_object_format,
427 .  bfd_error_invalid_operation,
428 .  bfd_error_no_memory,
429 .  bfd_error_no_symbols,
430 .  bfd_error_no_armap,
431 .  bfd_error_no_more_archived_files,
432 .  bfd_error_malformed_archive,
433 .  bfd_error_missing_dso,
434 .  bfd_error_file_not_recognized,
435 .  bfd_error_file_ambiguously_recognized,
436 .  bfd_error_no_contents,
437 .  bfd_error_nonrepresentable_section,
438 .  bfd_error_no_debug_section,
439 .  bfd_error_bad_value,
440 .  bfd_error_file_truncated,
441 .  bfd_error_file_too_big,
442 .  bfd_error_on_input,
443 .  bfd_error_invalid_error_code
444 .}
445 .bfd_error_type;
446 .
447 */
448 
449 static bfd_error_type bfd_error = bfd_error_no_error;
450 static bfd *input_bfd = NULL;
451 static bfd_error_type input_error = bfd_error_no_error;
452 
453 const char *const bfd_errmsgs[] =
454 {
455   N_("No error"),
456   N_("System call error"),
457   N_("Invalid bfd target"),
458   N_("File in wrong format"),
459   N_("Archive object file in wrong format"),
460   N_("Invalid operation"),
461   N_("Memory exhausted"),
462   N_("No symbols"),
463   N_("Archive has no index; run ranlib to add one"),
464   N_("No more archived files"),
465   N_("Malformed archive"),
466   N_("DSO missing from command line"),
467   N_("File format not recognized"),
468   N_("File format is ambiguous"),
469   N_("Section has no contents"),
470   N_("Nonrepresentable section on output"),
471   N_("Symbol needs debug section which does not exist"),
472   N_("Bad value"),
473   N_("File truncated"),
474   N_("File too big"),
475   N_("Error reading %s: %s"),
476   N_("#<Invalid error code>")
477 };
478 
479 /*
480 FUNCTION
481 	bfd_get_error
482 
483 SYNOPSIS
484 	bfd_error_type bfd_get_error (void);
485 
486 DESCRIPTION
487 	Return the current BFD error condition.
488 */
489 
490 bfd_error_type
bfd_get_error(void)491 bfd_get_error (void)
492 {
493   return bfd_error;
494 }
495 
496 /*
497 FUNCTION
498 	bfd_set_error
499 
500 SYNOPSIS
501 	void bfd_set_error (bfd_error_type error_tag);
502 
503 DESCRIPTION
504 	Set the BFD error condition to be @var{error_tag}.
505 
506 	@var{error_tag} must not be bfd_error_on_input.  Use
507 	bfd_set_input_error for input errors instead.
508 */
509 
510 void
bfd_set_error(bfd_error_type error_tag)511 bfd_set_error (bfd_error_type error_tag)
512 {
513   bfd_error = error_tag;
514   if (bfd_error >= bfd_error_on_input)
515     abort ();
516 }
517 
518 /*
519 FUNCTION
520 	bfd_set_input_error
521 
522 SYNOPSIS
523 	void bfd_set_input_error (bfd *input, bfd_error_type error_tag);
524 
525 DESCRIPTION
526 
527 	Set the BFD error condition to be bfd_error_on_input.
528 	@var{input} is the input bfd where the error occurred, and
529 	@var{error_tag} the bfd_error_type error.
530 */
531 
532 void
bfd_set_input_error(bfd * input,bfd_error_type error_tag)533 bfd_set_input_error (bfd *input, bfd_error_type error_tag)
534 {
535   /* This is an error that occurred during bfd_close when writing an
536      archive, but on one of the input files.  */
537   bfd_error = bfd_error_on_input;
538   input_bfd = input;
539   input_error = error_tag;
540   if (input_error >= bfd_error_on_input)
541     abort ();
542 }
543 
544 /*
545 FUNCTION
546 	bfd_errmsg
547 
548 SYNOPSIS
549 	const char *bfd_errmsg (bfd_error_type error_tag);
550 
551 DESCRIPTION
552 	Return a string describing the error @var{error_tag}, or
553 	the system error if @var{error_tag} is <<bfd_error_system_call>>.
554 */
555 
556 const char *
bfd_errmsg(bfd_error_type error_tag)557 bfd_errmsg (bfd_error_type error_tag)
558 {
559 #ifndef errno
560   extern int errno;
561 #endif
562   if (error_tag == bfd_error_on_input)
563     {
564       char *buf;
565       const char *msg = bfd_errmsg (input_error);
566 
567       if (asprintf (&buf, _(bfd_errmsgs [error_tag]), input_bfd->filename, msg)
568 	  != -1)
569 	return buf;
570 
571       /* Ick, what to do on out of memory?  */
572       return msg;
573     }
574 
575   if (error_tag == bfd_error_system_call)
576     return xstrerror (errno);
577 
578   if (error_tag > bfd_error_invalid_error_code)
579     error_tag = bfd_error_invalid_error_code;	/* sanity check */
580 
581   return _(bfd_errmsgs [error_tag]);
582 }
583 
584 /*
585 FUNCTION
586 	bfd_perror
587 
588 SYNOPSIS
589 	void bfd_perror (const char *message);
590 
591 DESCRIPTION
592 	Print to the standard error stream a string describing the
593 	last BFD error that occurred, or the last system error if
594 	the last BFD error was a system call failure.  If @var{message}
595 	is non-NULL and non-empty, the error string printed is preceded
596 	by @var{message}, a colon, and a space.  It is followed by a newline.
597 */
598 
599 void
bfd_perror(const char * message)600 bfd_perror (const char *message)
601 {
602   fflush (stdout);
603   if (message == NULL || *message == '\0')
604     fprintf (stderr, "%s\n", bfd_errmsg (bfd_get_error ()));
605   else
606     fprintf (stderr, "%s: %s\n", message, bfd_errmsg (bfd_get_error ()));
607   fflush (stderr);
608 }
609 
610 /*
611 SUBSECTION
612 	BFD error handler
613 
614 	Some BFD functions want to print messages describing the
615 	problem.  They call a BFD error handler function.  This
616 	function may be overridden by the program.
617 
618 	The BFD error handler acts like vprintf.
619 
620 CODE_FRAGMENT
621 .
622 .typedef void (*bfd_error_handler_type) (const char *, va_list);
623 .
624 */
625 
626 /* The program name used when printing BFD error messages.  */
627 
628 static const char *_bfd_error_program_name;
629 
630 /* Support for positional parameters.  */
631 
632 union _bfd_doprnt_args
633 {
634   int i;
635   long l;
636   long long ll;
637   double d;
638   long double ld;
639   void *p;
640   enum
641   {
642     Bad,
643     Int,
644     Long,
645     LongLong,
646     Double,
647     LongDouble,
648     Ptr
649   } type;
650 };
651 
652 /* This macro and _bfd_doprnt taken from libiberty _doprnt.c, tidied a
653    little and extended to handle '%A', '%B' and positional parameters.
654    'L' as a modifer for integer formats is used for bfd_vma and
655    bfd_size_type args, which vary in size depending on BFD
656    configuration.  */
657 
658 #define PRINT_TYPE(TYPE, FIELD) \
659   do								\
660     {								\
661       TYPE value = (TYPE) args[arg_no].FIELD;			\
662       result = fprintf (stream, specifier, value);		\
663     } while (0)
664 
665 static int
_bfd_doprnt(FILE * stream,const char * format,union _bfd_doprnt_args * args)666 _bfd_doprnt (FILE *stream, const char *format, union _bfd_doprnt_args *args)
667 {
668   const char *ptr = format;
669   char specifier[128];
670   int total_printed = 0;
671   unsigned int arg_count = 0;
672 
673   while (*ptr != '\0')
674     {
675       int result;
676 
677       if (*ptr != '%')
678 	{
679 	  /* While we have regular characters, print them.  */
680 	  char *end = strchr (ptr, '%');
681 	  if (end != NULL)
682 	    result = fprintf (stream, "%.*s", (int) (end - ptr), ptr);
683 	  else
684 	    result = fprintf (stream, "%s", ptr);
685 	  ptr += result;
686 	}
687       else if (ptr[1] == '%')
688 	{
689 	  fputc ('%', stream);
690 	  result = 1;
691 	  ptr += 2;
692 	}
693       else
694 	{
695 	  /* We have a format specifier!  */
696 	  char *sptr = specifier;
697 	  int wide_width = 0, short_width = 0;
698 	  unsigned int arg_no;
699 
700 	  /* Copy the % and move forward.  */
701 	  *sptr++ = *ptr++;
702 
703 	  /* Check for a positional parameter.  */
704 	  arg_no = -1u;
705 	  if (*ptr != '0' && ISDIGIT (*ptr) && ptr[1] == '$')
706 	    {
707 	      arg_no = *ptr - '1';
708 	      ptr += 2;
709 	    }
710 
711 	  /* Move past flags.  */
712 	  while (strchr ("-+ #0'I", *ptr))
713 	    *sptr++ = *ptr++;
714 
715 	  if (*ptr == '*')
716 	    {
717 	      int value;
718 	      unsigned int arg_index;
719 
720 	      ptr++;
721 	      arg_index = arg_count;
722 	      if (*ptr != '0' && ISDIGIT (*ptr) && ptr[1] == '$')
723 		{
724 		  arg_index = *ptr - '1';
725 		  ptr += 2;
726 		}
727 	      value = abs (args[arg_index].i);
728 	      arg_count++;
729 	      sptr += sprintf (sptr, "%d", value);
730 	    }
731 	  else
732 	    /* Handle explicit numeric value.  */
733 	    while (ISDIGIT (*ptr))
734 	      *sptr++ = *ptr++;
735 
736 	  /* Precision.  */
737 	  if (*ptr == '.')
738 	    {
739 	      /* Copy and go past the period.  */
740 	      *sptr++ = *ptr++;
741 	      if (*ptr == '*')
742 		{
743 		  int value;
744 		  unsigned int arg_index;
745 
746 		  ptr++;
747 		  arg_index = arg_count;
748 		  if (*ptr != '0' && ISDIGIT (*ptr) && ptr[1] == '$')
749 		    {
750 		      arg_index = *ptr - '1';
751 		      ptr += 2;
752 		    }
753 		  value = abs (args[arg_index].i);
754 		  arg_count++;
755 		  sptr += sprintf (sptr, "%d", value);
756 		}
757 	      else
758 		/* Handle explicit numeric value.  */
759 		while (ISDIGIT (*ptr))
760 		  *sptr++ = *ptr++;
761 	    }
762 	  while (strchr ("hlL", *ptr))
763 	    {
764 	      switch (*ptr)
765 		{
766 		case 'h':
767 		  short_width = 1;
768 		  break;
769 		case 'l':
770 		  wide_width++;
771 		  break;
772 		case 'L':
773 		  wide_width = 2;
774 		  break;
775 		default:
776 		  abort();
777 		}
778 	      *sptr++ = *ptr++;
779 	    }
780 
781 	  /* Copy the type specifier, and NULL terminate.  */
782 	  *sptr++ = *ptr++;
783 	  *sptr = '\0';
784 	  if ((int) arg_no < 0)
785 	    arg_no = arg_count;
786 
787 	  switch (ptr[-1])
788 	    {
789 	    case 'd':
790 	    case 'i':
791 	    case 'o':
792 	    case 'u':
793 	    case 'x':
794 	    case 'X':
795 	    case 'c':
796 	      {
797 		/* Short values are promoted to int, so just copy it
798 		   as an int and trust the C library printf to cast it
799 		   to the right width.  */
800 		if (short_width)
801 		  PRINT_TYPE (int, i);
802 		else
803 		  {
804 		    /* L modifier for bfd_vma or bfd_size_type may be
805 		       either long long or long.  */
806 		    if (ptr[-2] == 'L')
807 		      {
808 			sptr[-2] = 'l';
809 			if (BFD_ARCH_SIZE < 64 || BFD_HOST_64BIT_LONG)
810 			  wide_width = 1;
811 			else
812 			  {
813 			    sptr[-1] = 'l';
814 			    *sptr++ = ptr[-1];
815 			    *sptr = '\0';
816 			  }
817 		      }
818 
819 		    switch (wide_width)
820 		      {
821 		      case 0:
822 			PRINT_TYPE (int, i);
823 			break;
824 		      case 1:
825 			PRINT_TYPE (long, l);
826 			break;
827 		      case 2:
828 		      default:
829 #if defined (__MSVCRT__)
830 			sptr[-3] = 'I';
831 			sptr[-2] = '6';
832 			sptr[-1] = '4';
833 			*sptr++ = ptr[-1];
834 			*sptr = '\0';
835 #endif
836 #if defined (__GNUC__) || defined (HAVE_LONG_LONG)
837 			PRINT_TYPE (long long, ll);
838 #else
839 			/* Fake it and hope for the best.  */
840 			PRINT_TYPE (long, l);
841 #endif
842 			break;
843 		      }
844 		  }
845 	      }
846 	      break;
847 	    case 'f':
848 	    case 'e':
849 	    case 'E':
850 	    case 'g':
851 	    case 'G':
852 	      {
853 		if (wide_width == 0)
854 		  PRINT_TYPE (double, d);
855 		else
856 		  {
857 #if defined (__GNUC__) || defined (HAVE_LONG_DOUBLE)
858 		    PRINT_TYPE (long double, ld);
859 #else
860 		    /* Fake it and hope for the best.  */
861 		    PRINT_TYPE (double, d);
862 #endif
863 		  }
864 	      }
865 	      break;
866 	    case 's':
867 	      PRINT_TYPE (char *, p);
868 	      break;
869 	    case 'p':
870 	      PRINT_TYPE (void *, p);
871 	      break;
872 	    case 'A':
873 	      {
874 		asection *sec;
875 		bfd *abfd;
876 		const char *group = NULL;
877 		struct coff_comdat_info *ci;
878 
879 		sec = (asection *) args[arg_no].p;
880 		if (sec == NULL)
881 		  /* Invoking %A with a null section pointer is an
882 		     internal error.  */
883 		  abort ();
884 		abfd = sec->owner;
885 		if (abfd != NULL
886 		    && bfd_get_flavour (abfd) == bfd_target_elf_flavour
887 		    && elf_next_in_group (sec) != NULL
888 		    && (sec->flags & SEC_GROUP) == 0)
889 		  group = elf_group_name (sec);
890 		else if (abfd != NULL
891 			 && bfd_get_flavour (abfd) == bfd_target_coff_flavour
892 			 && (ci = bfd_coff_get_comdat_section (sec->owner,
893 							       sec)) != NULL)
894 		  group = ci->name;
895 		if (group != NULL)
896 		  result = fprintf (stream, "%s[%s]", sec->name, group);
897 		else
898 		  result = fprintf (stream, "%s", sec->name);
899 	      }
900 	      break;
901 	    case 'B':
902 	      {
903 		bfd *abfd;
904 
905 		abfd = (bfd *) args[arg_no].p;
906 		if (abfd == NULL)
907 		  /* Invoking %B with a null bfd pointer is an
908 		     internal error.  */
909 		  abort ();
910 		else if (abfd->my_archive
911 			 && !bfd_is_thin_archive (abfd->my_archive))
912 		  result = fprintf (stream, "%s(%s)",
913 				    abfd->my_archive->filename, abfd->filename);
914 		else
915 		  result = fprintf (stream, "%s", abfd->filename);
916 	      }
917 	      break;
918 	    default:
919 	      abort();
920 	    }
921 	  arg_count++;
922 	}
923       if (result == -1)
924 	return -1;
925       total_printed += result;
926     }
927 
928   return total_printed;
929 }
930 
931 /* First pass over FORMAT to gather ARGS.  Returns number of args.  */
932 
933 static unsigned int
_bfd_doprnt_scan(const char * format,union _bfd_doprnt_args * args)934 _bfd_doprnt_scan (const char *format, union _bfd_doprnt_args *args)
935 {
936   const char *ptr = format;
937   unsigned int arg_count = 0;
938 
939   while (*ptr != '\0')
940     {
941       if (*ptr != '%')
942 	{
943 	  ptr = strchr (ptr, '%');
944 	  if (ptr == NULL)
945 	    break;
946 	}
947       else if (ptr[1] == '%')
948 	ptr += 2;
949       else
950 	{
951 	  int wide_width = 0, short_width = 0;
952 	  unsigned int arg_no;
953 	  int arg_type;
954 
955 	  ptr++;
956 
957 	  /* Check for a positional parameter.  */
958 	  arg_no = -1u;
959 	  if (*ptr != '0' && ISDIGIT (*ptr) && ptr[1] == '$')
960 	    {
961 	      arg_no = *ptr - '1';
962 	      ptr += 2;
963 	    }
964 
965 	  /* Move past flags.  */
966 	  while (strchr ("-+ #0'I", *ptr))
967 	    ptr++;
968 
969 	  if (*ptr == '*')
970 	    {
971 	      unsigned int arg_index;
972 
973 	      ptr++;
974 	      arg_index = arg_count;
975 	      if (*ptr != '0' && ISDIGIT (*ptr) && ptr[1] == '$')
976 		{
977 		  arg_index = *ptr - '1';
978 		  ptr += 2;
979 		}
980 	      if (arg_index >= 9)
981 		abort ();
982 	      args[arg_index].type = Int;
983 	      arg_count++;
984 	    }
985 	  else
986 	    /* Handle explicit numeric value.  */
987 	    while (ISDIGIT (*ptr))
988 	      ptr++;
989 
990 	  /* Precision.  */
991 	  if (*ptr == '.')
992 	    {
993 	      ptr++;
994 	      if (*ptr == '*')
995 		{
996 		  unsigned int arg_index;
997 
998 		  ptr++;
999 		  arg_index = arg_count;
1000 		  if (*ptr != '0' && ISDIGIT (*ptr) && ptr[1] == '$')
1001 		    {
1002 		      arg_index = *ptr - '1';
1003 		      ptr += 2;
1004 		    }
1005 		  if (arg_index >= 9)
1006 		    abort ();
1007 		  args[arg_index].type = Int;
1008 		  arg_count++;
1009 		}
1010 	      else
1011 		/* Handle explicit numeric value.  */
1012 		while (ISDIGIT (*ptr))
1013 		  ptr++;
1014 	    }
1015 	  while (strchr ("hlL", *ptr))
1016 	    {
1017 	      switch (*ptr)
1018 		{
1019 		case 'h':
1020 		  short_width = 1;
1021 		  break;
1022 		case 'l':
1023 		  wide_width++;
1024 		  break;
1025 		case 'L':
1026 		  wide_width = 2;
1027 		  break;
1028 		default:
1029 		  abort();
1030 		}
1031 	      ptr++;
1032 	    }
1033 
1034 	  ptr++;
1035 	  if ((int) arg_no < 0)
1036 	    arg_no = arg_count;
1037 
1038 	  arg_type = Bad;
1039 	  switch (ptr[-1])
1040 	    {
1041 	    case 'd':
1042 	    case 'i':
1043 	    case 'o':
1044 	    case 'u':
1045 	    case 'x':
1046 	    case 'X':
1047 	    case 'c':
1048 	      {
1049 		if (short_width)
1050 		  arg_type = Int;
1051 		else
1052 		  {
1053 		    if (ptr[-2] == 'L')
1054 		      {
1055 			if (BFD_ARCH_SIZE < 64 || BFD_HOST_64BIT_LONG)
1056 			  wide_width = 1;
1057 		      }
1058 
1059 		    switch (wide_width)
1060 		      {
1061 		      case 0:
1062 			arg_type = Int;
1063 			break;
1064 		      case 1:
1065 			arg_type = Long;
1066 			break;
1067 		      case 2:
1068 		      default:
1069 #if defined (__GNUC__) || defined (HAVE_LONG_LONG)
1070 			arg_type = LongLong;
1071 #else
1072 			arg_type = Long;
1073 #endif
1074 			break;
1075 		      }
1076 		  }
1077 	      }
1078 	      break;
1079 	    case 'f':
1080 	    case 'e':
1081 	    case 'E':
1082 	    case 'g':
1083 	    case 'G':
1084 	      {
1085 		if (wide_width == 0)
1086 		  arg_type = Double;
1087 		else
1088 		  {
1089 #if defined (__GNUC__) || defined (HAVE_LONG_DOUBLE)
1090 		    arg_type = LongDouble;
1091 #else
1092 		    arg_type = Double;
1093 #endif
1094 		  }
1095 	      }
1096 	      break;
1097 	    case 's':
1098 	    case 'p':
1099 	    case 'A':
1100 	    case 'B':
1101 	      arg_type = Ptr;
1102 	      break;
1103 	    default:
1104 	      abort();
1105 	    }
1106 
1107 	  if (arg_no >= 9)
1108 	    abort ();
1109 	  args[arg_no].type = arg_type;
1110 	  arg_count++;
1111 	}
1112     }
1113 
1114   return arg_count;
1115 }
1116 
1117 /* This is the default routine to handle BFD error messages.
1118    Like fprintf (stderr, ...), but also handles some extra format specifiers.
1119 
1120    %A section name from section.  For group components, prints group name too.
1121    %B file name from bfd.  For archive components, prints archive too.
1122 
1123    Beware: Only supports a maximum of 9 format arguments.  */
1124 
1125 static void
error_handler_internal(const char * fmt,va_list ap)1126 error_handler_internal (const char *fmt, va_list ap)
1127 {
1128   unsigned int i, arg_count;
1129   union _bfd_doprnt_args args[9];
1130 
1131   for (i = 0; i < sizeof (args) / sizeof (args[0]); i++)
1132     args[i].type = Bad;
1133 
1134   arg_count = _bfd_doprnt_scan (fmt, args);
1135   for (i = 0; i < arg_count; i++)
1136     {
1137       switch (args[i].type)
1138 	{
1139 	case Int:
1140 	  args[i].i = va_arg (ap, int);
1141 	  break;
1142 	case Long:
1143 	  args[i].l = va_arg (ap, long);
1144 	  break;
1145 	case LongLong:
1146 	  args[i].ll = va_arg (ap, long long);
1147 	  break;
1148 	case Double:
1149 	  args[i].d = va_arg (ap, double);
1150 	  break;
1151 	case LongDouble:
1152 	  args[i].ld = va_arg (ap, long double);
1153 	  break;
1154 	case Ptr:
1155 	  args[i].p = va_arg (ap, void *);
1156 	  break;
1157 	default:
1158 	  abort ();
1159 	}
1160     }
1161 
1162   /* PR 4992: Don't interrupt output being sent to stdout.  */
1163   fflush (stdout);
1164 
1165   if (_bfd_error_program_name != NULL)
1166     fprintf (stderr, "%s: ", _bfd_error_program_name);
1167   else
1168     fprintf (stderr, "BFD: ");
1169 
1170   _bfd_doprnt (stderr, fmt, args);
1171 
1172   /* On AIX, putc is implemented as a macro that triggers a -Wunused-value
1173      warning, so use the fputc function to avoid it.  */
1174   fputc ('\n', stderr);
1175   fflush (stderr);
1176 }
1177 
1178 /* This is a function pointer to the routine which should handle BFD
1179    error messages.  It is called when a BFD routine encounters an
1180    error for which it wants to print a message.  Going through a
1181    function pointer permits a program linked against BFD to intercept
1182    the messages and deal with them itself.  */
1183 
1184 static bfd_error_handler_type _bfd_error_internal = error_handler_internal;
1185 
1186 void
_bfd_error_handler(const char * fmt,...)1187 _bfd_error_handler (const char *fmt, ...)
1188 {
1189   va_list ap;
1190 
1191   va_start (ap, fmt);
1192   _bfd_error_internal (fmt, ap);
1193   va_end (ap);
1194 }
1195 
1196 /*
1197 FUNCTION
1198 	bfd_set_error_handler
1199 
1200 SYNOPSIS
1201 	bfd_error_handler_type bfd_set_error_handler (bfd_error_handler_type);
1202 
1203 DESCRIPTION
1204 	Set the BFD error handler function.  Returns the previous
1205 	function.
1206 */
1207 
1208 bfd_error_handler_type
bfd_set_error_handler(bfd_error_handler_type pnew)1209 bfd_set_error_handler (bfd_error_handler_type pnew)
1210 {
1211   bfd_error_handler_type pold;
1212 
1213   pold = _bfd_error_internal;
1214   _bfd_error_internal = pnew;
1215   return pold;
1216 }
1217 
1218 /*
1219 FUNCTION
1220 	bfd_set_error_program_name
1221 
1222 SYNOPSIS
1223 	void bfd_set_error_program_name (const char *);
1224 
1225 DESCRIPTION
1226 	Set the program name to use when printing a BFD error.  This
1227 	is printed before the error message followed by a colon and
1228 	space.  The string must not be changed after it is passed to
1229 	this function.
1230 */
1231 
1232 void
bfd_set_error_program_name(const char * name)1233 bfd_set_error_program_name (const char *name)
1234 {
1235   _bfd_error_program_name = name;
1236 }
1237 
1238 /*
1239 SUBSECTION
1240 	BFD assert handler
1241 
1242 	If BFD finds an internal inconsistency, the bfd assert
1243 	handler is called with information on the BFD version, BFD
1244 	source file and line.  If this happens, most programs linked
1245 	against BFD are expected to want to exit with an error, or mark
1246 	the current BFD operation as failed, so it is recommended to
1247 	override the default handler, which just calls
1248 	_bfd_error_handler and continues.
1249 
1250 CODE_FRAGMENT
1251 .
1252 .typedef void (*bfd_assert_handler_type) (const char *bfd_formatmsg,
1253 .					  const char *bfd_version,
1254 .					  const char *bfd_file,
1255 .					  int bfd_line);
1256 .
1257 */
1258 
1259 /* Note the use of bfd_ prefix on the parameter names above: we want to
1260    show which one is the message and which is the version by naming the
1261    parameters, but avoid polluting the program-using-bfd namespace as
1262    the typedef is visible in the exported headers that the program
1263    includes.  Below, it's just for consistency.  */
1264 
1265 static void
_bfd_default_assert_handler(const char * bfd_formatmsg,const char * bfd_version,const char * bfd_file,int bfd_line)1266 _bfd_default_assert_handler (const char *bfd_formatmsg,
1267 			     const char *bfd_version,
1268 			     const char *bfd_file,
1269 			     int bfd_line)
1270 
1271 {
1272   _bfd_error_handler (bfd_formatmsg, bfd_version, bfd_file, bfd_line);
1273 }
1274 
1275 /* Similar to _bfd_error_handler, a program can decide to exit on an
1276    internal BFD error.  We use a non-variadic type to simplify passing
1277    on parameters to other functions, e.g. _bfd_error_handler.  */
1278 
1279 static bfd_assert_handler_type _bfd_assert_handler = _bfd_default_assert_handler;
1280 
1281 /*
1282 FUNCTION
1283 	bfd_set_assert_handler
1284 
1285 SYNOPSIS
1286 	bfd_assert_handler_type bfd_set_assert_handler (bfd_assert_handler_type);
1287 
1288 DESCRIPTION
1289 	Set the BFD assert handler function.  Returns the previous
1290 	function.
1291 */
1292 
1293 bfd_assert_handler_type
bfd_set_assert_handler(bfd_assert_handler_type pnew)1294 bfd_set_assert_handler (bfd_assert_handler_type pnew)
1295 {
1296   bfd_assert_handler_type pold;
1297 
1298   pold = _bfd_assert_handler;
1299   _bfd_assert_handler = pnew;
1300   return pold;
1301 }
1302 
1303 /*
1304 INODE
1305 Miscellaneous, Memory Usage, Error reporting, BFD front end
1306 
1307 SECTION
1308 	Miscellaneous
1309 
1310 SUBSECTION
1311 	Miscellaneous functions
1312 */
1313 
1314 /*
1315 FUNCTION
1316 	bfd_get_reloc_upper_bound
1317 
1318 SYNOPSIS
1319 	long bfd_get_reloc_upper_bound (bfd *abfd, asection *sect);
1320 
1321 DESCRIPTION
1322 	Return the number of bytes required to store the
1323 	relocation information associated with section @var{sect}
1324 	attached to bfd @var{abfd}.  If an error occurs, return -1.
1325 
1326 */
1327 
1328 long
bfd_get_reloc_upper_bound(bfd * abfd,sec_ptr asect)1329 bfd_get_reloc_upper_bound (bfd *abfd, sec_ptr asect)
1330 {
1331   if (abfd->format != bfd_object)
1332     {
1333       bfd_set_error (bfd_error_invalid_operation);
1334       return -1;
1335     }
1336 
1337   return BFD_SEND (abfd, _get_reloc_upper_bound, (abfd, asect));
1338 }
1339 
1340 /*
1341 FUNCTION
1342 	bfd_canonicalize_reloc
1343 
1344 SYNOPSIS
1345 	long bfd_canonicalize_reloc
1346 	  (bfd *abfd, asection *sec, arelent **loc, asymbol **syms);
1347 
1348 DESCRIPTION
1349 	Call the back end associated with the open BFD
1350 	@var{abfd} and translate the external form of the relocation
1351 	information attached to @var{sec} into the internal canonical
1352 	form.  Place the table into memory at @var{loc}, which has
1353 	been preallocated, usually by a call to
1354 	<<bfd_get_reloc_upper_bound>>.  Returns the number of relocs, or
1355 	-1 on error.
1356 
1357 	The @var{syms} table is also needed for horrible internal magic
1358 	reasons.
1359 
1360 */
1361 long
bfd_canonicalize_reloc(bfd * abfd,sec_ptr asect,arelent ** location,asymbol ** symbols)1362 bfd_canonicalize_reloc (bfd *abfd,
1363 			sec_ptr asect,
1364 			arelent **location,
1365 			asymbol **symbols)
1366 {
1367   if (abfd->format != bfd_object)
1368     {
1369       bfd_set_error (bfd_error_invalid_operation);
1370       return -1;
1371     }
1372 
1373   return BFD_SEND (abfd, _bfd_canonicalize_reloc,
1374 		   (abfd, asect, location, symbols));
1375 }
1376 
1377 /*
1378 FUNCTION
1379 	bfd_set_reloc
1380 
1381 SYNOPSIS
1382 	void bfd_set_reloc
1383 	  (bfd *abfd, asection *sec, arelent **rel, unsigned int count);
1384 
1385 DESCRIPTION
1386 	Set the relocation pointer and count within
1387 	section @var{sec} to the values @var{rel} and @var{count}.
1388 	The argument @var{abfd} is ignored.
1389 
1390 .#define bfd_set_reloc(abfd, asect, location, count) \
1391 .	BFD_SEND (abfd, _bfd_set_reloc, (abfd, asect, location, count))
1392 */
1393 
1394 /*
1395 FUNCTION
1396 	bfd_set_file_flags
1397 
1398 SYNOPSIS
1399 	bfd_boolean bfd_set_file_flags (bfd *abfd, flagword flags);
1400 
1401 DESCRIPTION
1402 	Set the flag word in the BFD @var{abfd} to the value @var{flags}.
1403 
1404 	Possible errors are:
1405 	o <<bfd_error_wrong_format>> - The target bfd was not of object format.
1406 	o <<bfd_error_invalid_operation>> - The target bfd was open for reading.
1407 	o <<bfd_error_invalid_operation>> -
1408 	The flag word contained a bit which was not applicable to the
1409 	type of file.  E.g., an attempt was made to set the <<D_PAGED>> bit
1410 	on a BFD format which does not support demand paging.
1411 
1412 */
1413 
1414 bfd_boolean
bfd_set_file_flags(bfd * abfd,flagword flags)1415 bfd_set_file_flags (bfd *abfd, flagword flags)
1416 {
1417   if (abfd->format != bfd_object)
1418     {
1419       bfd_set_error (bfd_error_wrong_format);
1420       return FALSE;
1421     }
1422 
1423   if (bfd_read_p (abfd))
1424     {
1425       bfd_set_error (bfd_error_invalid_operation);
1426       return FALSE;
1427     }
1428 
1429   bfd_get_file_flags (abfd) = flags;
1430   if ((flags & bfd_applicable_file_flags (abfd)) != flags)
1431     {
1432       bfd_set_error (bfd_error_invalid_operation);
1433       return FALSE;
1434     }
1435 
1436   return TRUE;
1437 }
1438 
1439 void
bfd_assert(const char * file,int line)1440 bfd_assert (const char *file, int line)
1441 {
1442   /* xgettext:c-format */
1443   (*_bfd_assert_handler) (_("BFD %s assertion fail %s:%d"),
1444 			  BFD_VERSION_STRING, file, line);
1445 }
1446 
1447 /* A more or less friendly abort message.  In libbfd.h abort is
1448    defined to call this function.  */
1449 
1450 void
_bfd_abort(const char * file,int line,const char * fn)1451 _bfd_abort (const char *file, int line, const char *fn)
1452 {
1453   if (fn != NULL)
1454     _bfd_error_handler
1455       /* xgettext:c-format */
1456       (_("BFD %s internal error, aborting at %s:%d in %s\n"),
1457        BFD_VERSION_STRING, file, line, fn);
1458   else
1459     _bfd_error_handler
1460       /* xgettext:c-format */
1461       (_("BFD %s internal error, aborting at %s:%d\n"),
1462        BFD_VERSION_STRING, file, line);
1463   _bfd_error_handler (_("Please report this bug.\n"));
1464   _exit (EXIT_FAILURE);
1465 }
1466 
1467 /*
1468 FUNCTION
1469 	bfd_get_arch_size
1470 
1471 SYNOPSIS
1472 	int bfd_get_arch_size (bfd *abfd);
1473 
1474 DESCRIPTION
1475 	Returns the normalized architecture address size, in bits, as
1476 	determined by the object file's format.  By normalized, we mean
1477 	either 32 or 64.  For ELF, this information is included in the
1478 	header.  Use bfd_arch_bits_per_address for number of bits in
1479 	the architecture address.
1480 
1481 RETURNS
1482 	Returns the arch size in bits if known, <<-1>> otherwise.
1483 */
1484 
1485 int
bfd_get_arch_size(bfd * abfd)1486 bfd_get_arch_size (bfd *abfd)
1487 {
1488   if (abfd->xvec->flavour == bfd_target_elf_flavour)
1489     return get_elf_backend_data (abfd)->s->arch_size;
1490 
1491   return bfd_arch_bits_per_address (abfd) > 32 ? 64 : 32;
1492 }
1493 
1494 /*
1495 FUNCTION
1496 	bfd_get_sign_extend_vma
1497 
1498 SYNOPSIS
1499 	int bfd_get_sign_extend_vma (bfd *abfd);
1500 
1501 DESCRIPTION
1502 	Indicates if the target architecture "naturally" sign extends
1503 	an address.  Some architectures implicitly sign extend address
1504 	values when they are converted to types larger than the size
1505 	of an address.  For instance, bfd_get_start_address() will
1506 	return an address sign extended to fill a bfd_vma when this is
1507 	the case.
1508 
1509 RETURNS
1510 	Returns <<1>> if the target architecture is known to sign
1511 	extend addresses, <<0>> if the target architecture is known to
1512 	not sign extend addresses, and <<-1>> otherwise.
1513 */
1514 
1515 int
bfd_get_sign_extend_vma(bfd * abfd)1516 bfd_get_sign_extend_vma (bfd *abfd)
1517 {
1518   char *name;
1519 
1520   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1521     return get_elf_backend_data (abfd)->sign_extend_vma;
1522 
1523   name = bfd_get_target (abfd);
1524 
1525   /* Return a proper value for DJGPP & PE COFF.
1526      This function is required for DWARF2 support, but there is
1527      no place to store this information in the COFF back end.
1528      Should enough other COFF targets add support for DWARF2,
1529      a place will have to be found.  Until then, this hack will do.  */
1530   if (CONST_STRNEQ (name, "coff-go32")
1531       || strcmp (name, "pe-i386") == 0
1532       || strcmp (name, "pei-i386") == 0
1533       || strcmp (name, "pe-x86-64") == 0
1534       || strcmp (name, "pei-x86-64") == 0
1535       || strcmp (name, "pe-arm-wince-little") == 0
1536       || strcmp (name, "pei-arm-wince-little") == 0
1537       || strcmp (name, "aixcoff-rs6000") == 0
1538       || strcmp (name, "aix5coff64-rs6000") == 0)
1539     return 1;
1540 
1541   if (CONST_STRNEQ (name, "mach-o"))
1542     return 0;
1543 
1544   bfd_set_error (bfd_error_wrong_format);
1545   return -1;
1546 }
1547 
1548 /*
1549 FUNCTION
1550 	bfd_set_start_address
1551 
1552 SYNOPSIS
1553 	bfd_boolean bfd_set_start_address (bfd *abfd, bfd_vma vma);
1554 
1555 DESCRIPTION
1556 	Make @var{vma} the entry point of output BFD @var{abfd}.
1557 
1558 RETURNS
1559 	Returns <<TRUE>> on success, <<FALSE>> otherwise.
1560 */
1561 
1562 bfd_boolean
bfd_set_start_address(bfd * abfd,bfd_vma vma)1563 bfd_set_start_address (bfd *abfd, bfd_vma vma)
1564 {
1565   abfd->start_address = vma;
1566   return TRUE;
1567 }
1568 
1569 /*
1570 FUNCTION
1571 	bfd_get_gp_size
1572 
1573 SYNOPSIS
1574 	unsigned int bfd_get_gp_size (bfd *abfd);
1575 
1576 DESCRIPTION
1577 	Return the maximum size of objects to be optimized using the GP
1578 	register under MIPS ECOFF.  This is typically set by the <<-G>>
1579 	argument to the compiler, assembler or linker.
1580 */
1581 
1582 unsigned int
bfd_get_gp_size(bfd * abfd)1583 bfd_get_gp_size (bfd *abfd)
1584 {
1585   if (abfd->format == bfd_object)
1586     {
1587       if (abfd->xvec->flavour == bfd_target_ecoff_flavour)
1588 	return ecoff_data (abfd)->gp_size;
1589       else if (abfd->xvec->flavour == bfd_target_elf_flavour)
1590 	return elf_gp_size (abfd);
1591     }
1592   return 0;
1593 }
1594 
1595 /*
1596 FUNCTION
1597 	bfd_set_gp_size
1598 
1599 SYNOPSIS
1600 	void bfd_set_gp_size (bfd *abfd, unsigned int i);
1601 
1602 DESCRIPTION
1603 	Set the maximum size of objects to be optimized using the GP
1604 	register under ECOFF or MIPS ELF.  This is typically set by
1605 	the <<-G>> argument to the compiler, assembler or linker.
1606 */
1607 
1608 void
bfd_set_gp_size(bfd * abfd,unsigned int i)1609 bfd_set_gp_size (bfd *abfd, unsigned int i)
1610 {
1611   /* Don't try to set GP size on an archive or core file!  */
1612   if (abfd->format != bfd_object)
1613     return;
1614 
1615   if (abfd->xvec->flavour == bfd_target_ecoff_flavour)
1616     ecoff_data (abfd)->gp_size = i;
1617   else if (abfd->xvec->flavour == bfd_target_elf_flavour)
1618     elf_gp_size (abfd) = i;
1619 }
1620 
1621 /* Get the GP value.  This is an internal function used by some of the
1622    relocation special_function routines on targets which support a GP
1623    register.  */
1624 
1625 bfd_vma
_bfd_get_gp_value(bfd * abfd)1626 _bfd_get_gp_value (bfd *abfd)
1627 {
1628   if (! abfd)
1629     return 0;
1630   if (abfd->format != bfd_object)
1631     return 0;
1632 
1633   if (abfd->xvec->flavour == bfd_target_ecoff_flavour)
1634     return ecoff_data (abfd)->gp;
1635   else if (abfd->xvec->flavour == bfd_target_elf_flavour)
1636     return elf_gp (abfd);
1637 
1638   return 0;
1639 }
1640 
1641 /* Set the GP value.  */
1642 
1643 void
_bfd_set_gp_value(bfd * abfd,bfd_vma v)1644 _bfd_set_gp_value (bfd *abfd, bfd_vma v)
1645 {
1646   if (! abfd)
1647     abort ();
1648   if (abfd->format != bfd_object)
1649     return;
1650 
1651   if (abfd->xvec->flavour == bfd_target_ecoff_flavour)
1652     ecoff_data (abfd)->gp = v;
1653   else if (abfd->xvec->flavour == bfd_target_elf_flavour)
1654     elf_gp (abfd) = v;
1655 }
1656 
1657 /*
1658 FUNCTION
1659 	bfd_scan_vma
1660 
1661 SYNOPSIS
1662 	bfd_vma bfd_scan_vma (const char *string, const char **end, int base);
1663 
1664 DESCRIPTION
1665 	Convert, like <<strtoul>>, a numerical expression
1666 	@var{string} into a <<bfd_vma>> integer, and return that integer.
1667 	(Though without as many bells and whistles as <<strtoul>>.)
1668 	The expression is assumed to be unsigned (i.e., positive).
1669 	If given a @var{base}, it is used as the base for conversion.
1670 	A base of 0 causes the function to interpret the string
1671 	in hex if a leading "0x" or "0X" is found, otherwise
1672 	in octal if a leading zero is found, otherwise in decimal.
1673 
1674 	If the value would overflow, the maximum <<bfd_vma>> value is
1675 	returned.
1676 */
1677 
1678 bfd_vma
bfd_scan_vma(const char * string,const char ** end,int base)1679 bfd_scan_vma (const char *string, const char **end, int base)
1680 {
1681   bfd_vma value;
1682   bfd_vma cutoff;
1683   unsigned int cutlim;
1684   int overflow;
1685 
1686   /* Let the host do it if possible.  */
1687   if (sizeof (bfd_vma) <= sizeof (unsigned long))
1688     return strtoul (string, (char **) end, base);
1689 
1690 #if defined (HAVE_STRTOULL) && defined (HAVE_LONG_LONG)
1691   if (sizeof (bfd_vma) <= sizeof (unsigned long long))
1692     return strtoull (string, (char **) end, base);
1693 #endif
1694 
1695   if (base == 0)
1696     {
1697       if (string[0] == '0')
1698 	{
1699 	  if ((string[1] == 'x') || (string[1] == 'X'))
1700 	    base = 16;
1701 	  else
1702 	    base = 8;
1703 	}
1704     }
1705 
1706   if ((base < 2) || (base > 36))
1707     base = 10;
1708 
1709   if (base == 16
1710       && string[0] == '0'
1711       && (string[1] == 'x' || string[1] == 'X')
1712       && ISXDIGIT (string[2]))
1713     {
1714       string += 2;
1715     }
1716 
1717   cutoff = (~ (bfd_vma) 0) / (bfd_vma) base;
1718   cutlim = (~ (bfd_vma) 0) % (bfd_vma) base;
1719   value = 0;
1720   overflow = 0;
1721   while (1)
1722     {
1723       unsigned int digit;
1724 
1725       digit = *string;
1726       if (ISDIGIT (digit))
1727 	digit = digit - '0';
1728       else if (ISALPHA (digit))
1729 	digit = TOUPPER (digit) - 'A' + 10;
1730       else
1731 	break;
1732       if (digit >= (unsigned int) base)
1733 	break;
1734       if (value > cutoff || (value == cutoff && digit > cutlim))
1735 	overflow = 1;
1736       value = value * base + digit;
1737       ++string;
1738     }
1739 
1740   if (overflow)
1741     value = ~ (bfd_vma) 0;
1742 
1743   if (end != NULL)
1744     *end = string;
1745 
1746   return value;
1747 }
1748 
1749 /*
1750 FUNCTION
1751 	bfd_copy_private_header_data
1752 
1753 SYNOPSIS
1754 	bfd_boolean bfd_copy_private_header_data (bfd *ibfd, bfd *obfd);
1755 
1756 DESCRIPTION
1757 	Copy private BFD header information from the BFD @var{ibfd} to the
1758 	the BFD @var{obfd}.  This copies information that may require
1759 	sections to exist, but does not require symbol tables.  Return
1760 	<<true>> on success, <<false>> on error.
1761 	Possible error returns are:
1762 
1763 	o <<bfd_error_no_memory>> -
1764 	Not enough memory exists to create private data for @var{obfd}.
1765 
1766 .#define bfd_copy_private_header_data(ibfd, obfd) \
1767 .	BFD_SEND (obfd, _bfd_copy_private_header_data, \
1768 .		  (ibfd, obfd))
1769 
1770 */
1771 
1772 /*
1773 FUNCTION
1774 	bfd_copy_private_bfd_data
1775 
1776 SYNOPSIS
1777 	bfd_boolean bfd_copy_private_bfd_data (bfd *ibfd, bfd *obfd);
1778 
1779 DESCRIPTION
1780 	Copy private BFD information from the BFD @var{ibfd} to the
1781 	the BFD @var{obfd}.  Return <<TRUE>> on success, <<FALSE>> on error.
1782 	Possible error returns are:
1783 
1784 	o <<bfd_error_no_memory>> -
1785 	Not enough memory exists to create private data for @var{obfd}.
1786 
1787 .#define bfd_copy_private_bfd_data(ibfd, obfd) \
1788 .	BFD_SEND (obfd, _bfd_copy_private_bfd_data, \
1789 .		  (ibfd, obfd))
1790 
1791 */
1792 
1793 /*
1794 FUNCTION
1795 	bfd_set_private_flags
1796 
1797 SYNOPSIS
1798 	bfd_boolean bfd_set_private_flags (bfd *abfd, flagword flags);
1799 
1800 DESCRIPTION
1801 	Set private BFD flag information in the BFD @var{abfd}.
1802 	Return <<TRUE>> on success, <<FALSE>> on error.  Possible error
1803 	returns are:
1804 
1805 	o <<bfd_error_no_memory>> -
1806 	Not enough memory exists to create private data for @var{obfd}.
1807 
1808 .#define bfd_set_private_flags(abfd, flags) \
1809 .	BFD_SEND (abfd, _bfd_set_private_flags, (abfd, flags))
1810 
1811 */
1812 
1813 /*
1814 FUNCTION
1815 	Other functions
1816 
1817 DESCRIPTION
1818 	The following functions exist but have not yet been documented.
1819 
1820 .#define bfd_sizeof_headers(abfd, info) \
1821 .	BFD_SEND (abfd, _bfd_sizeof_headers, (abfd, info))
1822 .
1823 .#define bfd_find_nearest_line(abfd, sec, syms, off, file, func, line) \
1824 .	BFD_SEND (abfd, _bfd_find_nearest_line, \
1825 .		  (abfd, syms, sec, off, file, func, line, NULL))
1826 .
1827 .#define bfd_find_nearest_line_discriminator(abfd, sec, syms, off, file, func, \
1828 .					    line, disc) \
1829 .	BFD_SEND (abfd, _bfd_find_nearest_line, \
1830 .		  (abfd, syms, sec, off, file, func, line, disc))
1831 .
1832 .#define bfd_find_line(abfd, syms, sym, file, line) \
1833 .	BFD_SEND (abfd, _bfd_find_line, \
1834 .		  (abfd, syms, sym, file, line))
1835 .
1836 .#define bfd_find_inliner_info(abfd, file, func, line) \
1837 .	BFD_SEND (abfd, _bfd_find_inliner_info, \
1838 .		  (abfd, file, func, line))
1839 .
1840 .#define bfd_debug_info_start(abfd) \
1841 .	BFD_SEND (abfd, _bfd_debug_info_start, (abfd))
1842 .
1843 .#define bfd_debug_info_end(abfd) \
1844 .	BFD_SEND (abfd, _bfd_debug_info_end, (abfd))
1845 .
1846 .#define bfd_debug_info_accumulate(abfd, section) \
1847 .	BFD_SEND (abfd, _bfd_debug_info_accumulate, (abfd, section))
1848 .
1849 .#define bfd_stat_arch_elt(abfd, stat) \
1850 .	BFD_SEND (abfd, _bfd_stat_arch_elt,(abfd, stat))
1851 .
1852 .#define bfd_update_armap_timestamp(abfd) \
1853 .	BFD_SEND (abfd, _bfd_update_armap_timestamp, (abfd))
1854 .
1855 .#define bfd_set_arch_mach(abfd, arch, mach)\
1856 .	BFD_SEND ( abfd, _bfd_set_arch_mach, (abfd, arch, mach))
1857 .
1858 .#define bfd_relax_section(abfd, section, link_info, again) \
1859 .	BFD_SEND (abfd, _bfd_relax_section, (abfd, section, link_info, again))
1860 .
1861 .#define bfd_gc_sections(abfd, link_info) \
1862 .	BFD_SEND (abfd, _bfd_gc_sections, (abfd, link_info))
1863 .
1864 .#define bfd_lookup_section_flags(link_info, flag_info, section) \
1865 .	BFD_SEND (abfd, _bfd_lookup_section_flags, (link_info, flag_info, section))
1866 .
1867 .#define bfd_merge_sections(abfd, link_info) \
1868 .	BFD_SEND (abfd, _bfd_merge_sections, (abfd, link_info))
1869 .
1870 .#define bfd_is_group_section(abfd, sec) \
1871 .	BFD_SEND (abfd, _bfd_is_group_section, (abfd, sec))
1872 .
1873 .#define bfd_discard_group(abfd, sec) \
1874 .	BFD_SEND (abfd, _bfd_discard_group, (abfd, sec))
1875 .
1876 .#define bfd_link_hash_table_create(abfd) \
1877 .	BFD_SEND (abfd, _bfd_link_hash_table_create, (abfd))
1878 .
1879 .#define bfd_link_add_symbols(abfd, info) \
1880 .	BFD_SEND (abfd, _bfd_link_add_symbols, (abfd, info))
1881 .
1882 .#define bfd_link_just_syms(abfd, sec, info) \
1883 .	BFD_SEND (abfd, _bfd_link_just_syms, (sec, info))
1884 .
1885 .#define bfd_final_link(abfd, info) \
1886 .	BFD_SEND (abfd, _bfd_final_link, (abfd, info))
1887 .
1888 .#define bfd_free_cached_info(abfd) \
1889 .	BFD_SEND (abfd, _bfd_free_cached_info, (abfd))
1890 .
1891 .#define bfd_get_dynamic_symtab_upper_bound(abfd) \
1892 .	BFD_SEND (abfd, _bfd_get_dynamic_symtab_upper_bound, (abfd))
1893 .
1894 .#define bfd_print_private_bfd_data(abfd, file)\
1895 .	BFD_SEND (abfd, _bfd_print_private_bfd_data, (abfd, file))
1896 .
1897 .#define bfd_canonicalize_dynamic_symtab(abfd, asymbols) \
1898 .	BFD_SEND (abfd, _bfd_canonicalize_dynamic_symtab, (abfd, asymbols))
1899 .
1900 .#define bfd_get_synthetic_symtab(abfd, count, syms, dyncount, dynsyms, ret) \
1901 .	BFD_SEND (abfd, _bfd_get_synthetic_symtab, (abfd, count, syms, \
1902 .						    dyncount, dynsyms, ret))
1903 .
1904 .#define bfd_get_dynamic_reloc_upper_bound(abfd) \
1905 .	BFD_SEND (abfd, _bfd_get_dynamic_reloc_upper_bound, (abfd))
1906 .
1907 .#define bfd_canonicalize_dynamic_reloc(abfd, arels, asyms) \
1908 .	BFD_SEND (abfd, _bfd_canonicalize_dynamic_reloc, (abfd, arels, asyms))
1909 .
1910 .extern bfd_byte *bfd_get_relocated_section_contents
1911 .  (bfd *, struct bfd_link_info *, struct bfd_link_order *, bfd_byte *,
1912 .   bfd_boolean, asymbol **);
1913 .
1914 
1915 */
1916 
1917 bfd_byte *
bfd_get_relocated_section_contents(bfd * abfd,struct bfd_link_info * link_info,struct bfd_link_order * link_order,bfd_byte * data,bfd_boolean relocatable,asymbol ** symbols)1918 bfd_get_relocated_section_contents (bfd *abfd,
1919 				    struct bfd_link_info *link_info,
1920 				    struct bfd_link_order *link_order,
1921 				    bfd_byte *data,
1922 				    bfd_boolean relocatable,
1923 				    asymbol **symbols)
1924 {
1925   bfd *abfd2;
1926   bfd_byte *(*fn) (bfd *, struct bfd_link_info *, struct bfd_link_order *,
1927 		   bfd_byte *, bfd_boolean, asymbol **);
1928 
1929   if (link_order->type == bfd_indirect_link_order)
1930     {
1931       abfd2 = link_order->u.indirect.section->owner;
1932       if (abfd2 == NULL)
1933 	abfd2 = abfd;
1934     }
1935   else
1936     abfd2 = abfd;
1937 
1938   fn = abfd2->xvec->_bfd_get_relocated_section_contents;
1939 
1940   return (*fn) (abfd, link_info, link_order, data, relocatable, symbols);
1941 }
1942 
1943 /* Record information about an ELF program header.  */
1944 
1945 bfd_boolean
bfd_record_phdr(bfd * abfd,unsigned long type,bfd_boolean flags_valid,flagword flags,bfd_boolean at_valid,bfd_vma at,bfd_boolean includes_filehdr,bfd_boolean includes_phdrs,unsigned int count,asection ** secs)1946 bfd_record_phdr (bfd *abfd,
1947 		 unsigned long type,
1948 		 bfd_boolean flags_valid,
1949 		 flagword flags,
1950 		 bfd_boolean at_valid,
1951 		 bfd_vma at,
1952 		 bfd_boolean includes_filehdr,
1953 		 bfd_boolean includes_phdrs,
1954 		 unsigned int count,
1955 		 asection **secs)
1956 {
1957   struct elf_segment_map *m, **pm;
1958   bfd_size_type amt;
1959 
1960   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
1961     return TRUE;
1962 
1963   amt = sizeof (struct elf_segment_map);
1964   amt += ((bfd_size_type) count - 1) * sizeof (asection *);
1965   m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
1966   if (m == NULL)
1967     return FALSE;
1968 
1969   m->p_type = type;
1970   m->p_flags = flags;
1971   m->p_paddr = at;
1972   m->p_flags_valid = flags_valid;
1973   m->p_paddr_valid = at_valid;
1974   m->includes_filehdr = includes_filehdr;
1975   m->includes_phdrs = includes_phdrs;
1976   m->count = count;
1977   if (count > 0)
1978     memcpy (m->sections, secs, count * sizeof (asection *));
1979 
1980   for (pm = &elf_seg_map (abfd); *pm != NULL; pm = &(*pm)->next)
1981     ;
1982   *pm = m;
1983 
1984   return TRUE;
1985 }
1986 
1987 #ifdef BFD64
1988 /* Return true iff this target is 32-bit.  */
1989 
1990 static bfd_boolean
is32bit(bfd * abfd)1991 is32bit (bfd *abfd)
1992 {
1993   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1994     {
1995       const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1996       return bed->s->elfclass == ELFCLASS32;
1997     }
1998 
1999   /* For non-ELF targets, use architecture information.  */
2000   return bfd_arch_bits_per_address (abfd) <= 32;
2001 }
2002 #endif
2003 
2004 /* bfd_sprintf_vma and bfd_fprintf_vma display an address in the
2005    target's address size.  */
2006 
2007 void
bfd_sprintf_vma(bfd * abfd ATTRIBUTE_UNUSED,char * buf,bfd_vma value)2008 bfd_sprintf_vma (bfd *abfd ATTRIBUTE_UNUSED, char *buf, bfd_vma value)
2009 {
2010 #ifdef BFD64
2011   if (is32bit (abfd))
2012     {
2013       sprintf (buf, "%08lx", (unsigned long) value & 0xffffffff);
2014       return;
2015     }
2016 #endif
2017   sprintf_vma (buf, value);
2018 }
2019 
2020 void
bfd_fprintf_vma(bfd * abfd ATTRIBUTE_UNUSED,void * stream,bfd_vma value)2021 bfd_fprintf_vma (bfd *abfd ATTRIBUTE_UNUSED, void *stream, bfd_vma value)
2022 {
2023 #ifdef BFD64
2024   if (is32bit (abfd))
2025     {
2026       fprintf ((FILE *) stream, "%08lx", (unsigned long) value & 0xffffffff);
2027       return;
2028     }
2029 #endif
2030   fprintf_vma ((FILE *) stream, value);
2031 }
2032 
2033 /*
2034 FUNCTION
2035 	bfd_alt_mach_code
2036 
2037 SYNOPSIS
2038 	bfd_boolean bfd_alt_mach_code (bfd *abfd, int alternative);
2039 
2040 DESCRIPTION
2041 
2042 	When more than one machine code number is available for the
2043 	same machine type, this function can be used to switch between
2044 	the preferred one (alternative == 0) and any others.  Currently,
2045 	only ELF supports this feature, with up to two alternate
2046 	machine codes.
2047 */
2048 
2049 bfd_boolean
bfd_alt_mach_code(bfd * abfd,int alternative)2050 bfd_alt_mach_code (bfd *abfd, int alternative)
2051 {
2052   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
2053     {
2054       int code;
2055 
2056       switch (alternative)
2057 	{
2058 	case 0:
2059 	  code = get_elf_backend_data (abfd)->elf_machine_code;
2060 	  break;
2061 
2062 	case 1:
2063 	  code = get_elf_backend_data (abfd)->elf_machine_alt1;
2064 	  if (code == 0)
2065 	    return FALSE;
2066 	  break;
2067 
2068 	case 2:
2069 	  code = get_elf_backend_data (abfd)->elf_machine_alt2;
2070 	  if (code == 0)
2071 	    return FALSE;
2072 	  break;
2073 
2074 	default:
2075 	  return FALSE;
2076 	}
2077 
2078       elf_elfheader (abfd)->e_machine = code;
2079 
2080       return TRUE;
2081     }
2082 
2083   return FALSE;
2084 }
2085 
2086 /*
2087 FUNCTION
2088 	bfd_emul_get_maxpagesize
2089 
2090 SYNOPSIS
2091 	bfd_vma bfd_emul_get_maxpagesize (const char *);
2092 
2093 DESCRIPTION
2094 	Returns the maximum page size, in bytes, as determined by
2095 	emulation.
2096 
2097 RETURNS
2098 	Returns the maximum page size in bytes for ELF, 0 otherwise.
2099 */
2100 
2101 bfd_vma
bfd_emul_get_maxpagesize(const char * emul)2102 bfd_emul_get_maxpagesize (const char *emul)
2103 {
2104   const bfd_target *target;
2105 
2106   target = bfd_find_target (emul, NULL);
2107   if (target != NULL
2108       && target->flavour == bfd_target_elf_flavour)
2109     return xvec_get_elf_backend_data (target)->maxpagesize;
2110 
2111   return 0;
2112 }
2113 
2114 static void
bfd_elf_set_pagesize(const bfd_target * target,bfd_vma size,int offset,const bfd_target * orig_target)2115 bfd_elf_set_pagesize (const bfd_target *target, bfd_vma size,
2116 		      int offset, const bfd_target *orig_target)
2117 {
2118   if (target->flavour == bfd_target_elf_flavour)
2119     {
2120       const struct elf_backend_data *bed;
2121 
2122       bed = xvec_get_elf_backend_data (target);
2123       *((bfd_vma *) ((char *) bed + offset)) = size;
2124     }
2125 
2126   if (target->alternative_target
2127       && target->alternative_target != orig_target)
2128     bfd_elf_set_pagesize (target->alternative_target, size, offset,
2129 			  orig_target);
2130 }
2131 
2132 /*
2133 FUNCTION
2134 	bfd_emul_set_maxpagesize
2135 
2136 SYNOPSIS
2137 	void bfd_emul_set_maxpagesize (const char *, bfd_vma);
2138 
2139 DESCRIPTION
2140 	For ELF, set the maximum page size for the emulation.  It is
2141 	a no-op for other formats.
2142 
2143 */
2144 
2145 void
bfd_emul_set_maxpagesize(const char * emul,bfd_vma size)2146 bfd_emul_set_maxpagesize (const char *emul, bfd_vma size)
2147 {
2148   const bfd_target *target;
2149 
2150   target = bfd_find_target (emul, NULL);
2151   if (target)
2152     bfd_elf_set_pagesize (target, size,
2153 			  offsetof (struct elf_backend_data,
2154 				    maxpagesize), target);
2155 }
2156 
2157 /*
2158 FUNCTION
2159 	bfd_emul_get_commonpagesize
2160 
2161 SYNOPSIS
2162 	bfd_vma bfd_emul_get_commonpagesize (const char *);
2163 
2164 DESCRIPTION
2165 	Returns the common page size, in bytes, as determined by
2166 	emulation.
2167 
2168 RETURNS
2169 	Returns the common page size in bytes for ELF, 0 otherwise.
2170 */
2171 
2172 bfd_vma
bfd_emul_get_commonpagesize(const char * emul)2173 bfd_emul_get_commonpagesize (const char *emul)
2174 {
2175   const bfd_target *target;
2176 
2177   target = bfd_find_target (emul, NULL);
2178   if (target != NULL
2179       && target->flavour == bfd_target_elf_flavour)
2180     return xvec_get_elf_backend_data (target)->commonpagesize;
2181 
2182   return 0;
2183 }
2184 
2185 /*
2186 FUNCTION
2187 	bfd_emul_set_commonpagesize
2188 
2189 SYNOPSIS
2190 	void bfd_emul_set_commonpagesize (const char *, bfd_vma);
2191 
2192 DESCRIPTION
2193 	For ELF, set the common page size for the emulation.  It is
2194 	a no-op for other formats.
2195 
2196 */
2197 
2198 void
bfd_emul_set_commonpagesize(const char * emul,bfd_vma size)2199 bfd_emul_set_commonpagesize (const char *emul, bfd_vma size)
2200 {
2201   const bfd_target *target;
2202 
2203   target = bfd_find_target (emul, NULL);
2204   if (target)
2205     bfd_elf_set_pagesize (target, size,
2206 			  offsetof (struct elf_backend_data,
2207 				    commonpagesize), target);
2208 }
2209 
2210 /*
2211 FUNCTION
2212 	bfd_demangle
2213 
2214 SYNOPSIS
2215 	char *bfd_demangle (bfd *, const char *, int);
2216 
2217 DESCRIPTION
2218 	Wrapper around cplus_demangle.  Strips leading underscores and
2219 	other such chars that would otherwise confuse the demangler.
2220 	If passed a g++ v3 ABI mangled name, returns a buffer allocated
2221 	with malloc holding the demangled name.  Returns NULL otherwise
2222 	and on memory alloc failure.
2223 */
2224 
2225 char *
bfd_demangle(bfd * abfd,const char * name,int options)2226 bfd_demangle (bfd *abfd, const char *name, int options)
2227 {
2228   char *res, *alloc;
2229   const char *pre, *suf;
2230   size_t pre_len;
2231   bfd_boolean skip_lead;
2232 
2233   skip_lead = (abfd != NULL
2234 	       && *name != '\0'
2235 	       && bfd_get_symbol_leading_char (abfd) == *name);
2236   if (skip_lead)
2237     ++name;
2238 
2239   /* This is a hack for better error reporting on XCOFF, PowerPC64-ELF
2240      or the MS PE format.  These formats have a number of leading '.'s
2241      on at least some symbols, so we remove all dots to avoid
2242      confusing the demangler.  */
2243   pre = name;
2244   while (*name == '.' || *name == '$')
2245     ++name;
2246   pre_len = name - pre;
2247 
2248   /* Strip off @plt and suchlike too.  */
2249   alloc = NULL;
2250   suf = strchr (name, '@');
2251   if (suf != NULL)
2252     {
2253       alloc = (char *) bfd_malloc (suf - name + 1);
2254       if (alloc == NULL)
2255 	return NULL;
2256       memcpy (alloc, name, suf - name);
2257       alloc[suf - name] = '\0';
2258       name = alloc;
2259     }
2260 
2261   res = cplus_demangle (name, options);
2262 
2263   if (alloc != NULL)
2264     free (alloc);
2265 
2266   if (res == NULL)
2267     {
2268       if (skip_lead)
2269 	{
2270 	  size_t len = strlen (pre) + 1;
2271 	  alloc = (char *) bfd_malloc (len);
2272 	  if (alloc == NULL)
2273 	    return NULL;
2274 	  memcpy (alloc, pre, len);
2275 	  return alloc;
2276 	}
2277       return NULL;
2278     }
2279 
2280   /* Put back any prefix or suffix.  */
2281   if (pre_len != 0 || suf != NULL)
2282     {
2283       size_t len;
2284       size_t suf_len;
2285       char *final;
2286 
2287       len = strlen (res);
2288       if (suf == NULL)
2289 	suf = res + len;
2290       suf_len = strlen (suf) + 1;
2291       final = (char *) bfd_malloc (pre_len + len + suf_len);
2292       if (final != NULL)
2293 	{
2294 	  memcpy (final, pre, pre_len);
2295 	  memcpy (final + pre_len, res, len);
2296 	  memcpy (final + pre_len + len, suf, suf_len);
2297 	}
2298       free (res);
2299       res = final;
2300     }
2301 
2302   return res;
2303 }
2304 
2305 /*
2306 FUNCTION
2307 	bfd_update_compression_header
2308 
2309 SYNOPSIS
2310 	void bfd_update_compression_header
2311 	  (bfd *abfd, bfd_byte *contents, asection *sec);
2312 
2313 DESCRIPTION
2314 	Set the compression header at CONTENTS of SEC in ABFD and update
2315 	elf_section_flags for compression.
2316 */
2317 
2318 void
bfd_update_compression_header(bfd * abfd,bfd_byte * contents,asection * sec)2319 bfd_update_compression_header (bfd *abfd, bfd_byte *contents,
2320 			       asection *sec)
2321 {
2322   if ((abfd->flags & BFD_COMPRESS) != 0)
2323     {
2324       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
2325 	{
2326 	  if ((abfd->flags & BFD_COMPRESS_GABI) != 0)
2327 	    {
2328 	      const struct elf_backend_data *bed
2329 		= get_elf_backend_data (abfd);
2330 
2331 	      /* Set the SHF_COMPRESSED bit.  */
2332 	      elf_section_flags (sec) |= SHF_COMPRESSED;
2333 
2334 	      if (bed->s->elfclass == ELFCLASS32)
2335 		{
2336 		  Elf32_External_Chdr *echdr
2337 		    = (Elf32_External_Chdr *) contents;
2338 		  bfd_put_32 (abfd, ELFCOMPRESS_ZLIB, &echdr->ch_type);
2339 		  bfd_put_32 (abfd, sec->size, &echdr->ch_size);
2340 		  bfd_put_32 (abfd, 1 << sec->alignment_power,
2341 			      &echdr->ch_addralign);
2342 		}
2343 	      else
2344 		{
2345 		  Elf64_External_Chdr *echdr
2346 		    = (Elf64_External_Chdr *) contents;
2347 		  bfd_put_32 (abfd, ELFCOMPRESS_ZLIB, &echdr->ch_type);
2348 		  bfd_put_32 (abfd, 0, &echdr->ch_reserved);
2349 		  bfd_put_64 (abfd, sec->size, &echdr->ch_size);
2350 		  bfd_put_64 (abfd, 1 << sec->alignment_power,
2351 			      &echdr->ch_addralign);
2352 		}
2353 	    }
2354 	  else
2355 	    {
2356 	      /* Clear the SHF_COMPRESSED bit.  */
2357 	      elf_section_flags (sec) &= ~SHF_COMPRESSED;
2358 
2359 	      /* Write the zlib header.  It should be "ZLIB" followed by
2360 		 the uncompressed section size, 8 bytes in big-endian
2361 		 order.  */
2362 	      memcpy (contents, "ZLIB", 4);
2363 	      bfd_putb64 (sec->size, contents + 4);
2364 	    }
2365 	}
2366     }
2367   else
2368     abort ();
2369 }
2370 
2371 /*
2372    FUNCTION
2373    bfd_check_compression_header
2374 
2375    SYNOPSIS
2376 	bfd_boolean bfd_check_compression_header
2377 	  (bfd *abfd, bfd_byte *contents, asection *sec,
2378 	  bfd_size_type *uncompressed_size);
2379 
2380 DESCRIPTION
2381 	Check the compression header at CONTENTS of SEC in ABFD and
2382 	store the uncompressed size in UNCOMPRESSED_SIZE if the
2383 	compression header is valid.
2384 
2385 RETURNS
2386 	Return TRUE if the compression header is valid.
2387 */
2388 
2389 bfd_boolean
bfd_check_compression_header(bfd * abfd,bfd_byte * contents,asection * sec,bfd_size_type * uncompressed_size)2390 bfd_check_compression_header (bfd *abfd, bfd_byte *contents,
2391 			      asection *sec,
2392 			      bfd_size_type *uncompressed_size)
2393 {
2394   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
2395       && (elf_section_flags (sec) & SHF_COMPRESSED) != 0)
2396     {
2397       Elf_Internal_Chdr chdr;
2398       const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2399       if (bed->s->elfclass == ELFCLASS32)
2400 	{
2401 	  Elf32_External_Chdr *echdr = (Elf32_External_Chdr *) contents;
2402 	  chdr.ch_type = bfd_get_32 (abfd, &echdr->ch_type);
2403 	  chdr.ch_size = bfd_get_32 (abfd, &echdr->ch_size);
2404 	  chdr.ch_addralign = bfd_get_32 (abfd, &echdr->ch_addralign);
2405 	}
2406       else
2407 	{
2408 	  Elf64_External_Chdr *echdr = (Elf64_External_Chdr *) contents;
2409 	  chdr.ch_type = bfd_get_32 (abfd, &echdr->ch_type);
2410 	  chdr.ch_size = bfd_get_64 (abfd, &echdr->ch_size);
2411 	  chdr.ch_addralign = bfd_get_64 (abfd, &echdr->ch_addralign);
2412 	}
2413       if (chdr.ch_type == ELFCOMPRESS_ZLIB
2414 	  && chdr.ch_addralign == 1U << sec->alignment_power)
2415 	{
2416 	  *uncompressed_size = chdr.ch_size;
2417 	  return TRUE;
2418 	}
2419     }
2420 
2421   return FALSE;
2422 }
2423 
2424 /*
2425 FUNCTION
2426 	bfd_get_compression_header_size
2427 
2428 SYNOPSIS
2429 	int bfd_get_compression_header_size (bfd *abfd, asection *sec);
2430 
2431 DESCRIPTION
2432 	Return the size of the compression header of SEC in ABFD.
2433 
2434 RETURNS
2435 	Return the size of the compression header in bytes.
2436 */
2437 
2438 int
bfd_get_compression_header_size(bfd * abfd,asection * sec)2439 bfd_get_compression_header_size (bfd *abfd, asection *sec)
2440 {
2441   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
2442     {
2443       if (sec == NULL)
2444 	{
2445 	  if (!(abfd->flags & BFD_COMPRESS_GABI))
2446 	    return 0;
2447 	}
2448       else if (!(elf_section_flags (sec) & SHF_COMPRESSED))
2449 	return 0;
2450 
2451       if (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS32)
2452 	return sizeof (Elf32_External_Chdr);
2453       else
2454 	return sizeof (Elf64_External_Chdr);
2455     }
2456 
2457   return 0;
2458 }
2459 
2460 /*
2461 FUNCTION
2462 	bfd_convert_section_size
2463 
2464 SYNOPSIS
2465 	bfd_size_type bfd_convert_section_size
2466 	  (bfd *ibfd, asection *isec, bfd *obfd, bfd_size_type size);
2467 
2468 DESCRIPTION
2469 	Convert the size @var{size} of the section @var{isec} in input
2470 	BFD @var{ibfd} to the section size in output BFD @var{obfd}.
2471 */
2472 
2473 bfd_size_type
bfd_convert_section_size(bfd * ibfd,sec_ptr isec,bfd * obfd,bfd_size_type size)2474 bfd_convert_section_size (bfd *ibfd, sec_ptr isec, bfd *obfd,
2475 			  bfd_size_type size)
2476 {
2477   bfd_size_type hdr_size;
2478 
2479   /* Do nothing if input file will be decompressed.  */
2480   if ((ibfd->flags & BFD_DECOMPRESS))
2481     return size;
2482 
2483   /* Do nothing if either input or output aren't ELF.  */
2484   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
2485       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
2486     return size;
2487 
2488   /* Do nothing if ELF classes of input and output are the same. */
2489   if (get_elf_backend_data (ibfd)->s->elfclass
2490       == get_elf_backend_data (obfd)->s->elfclass)
2491     return size;
2492 
2493   /* Do nothing if the input section isn't a SHF_COMPRESSED section. */
2494   hdr_size = bfd_get_compression_header_size (ibfd, isec);
2495   if (hdr_size == 0)
2496     return size;
2497 
2498   /* Adjust the size of the output SHF_COMPRESSED section.  */
2499   if (hdr_size == sizeof (Elf32_External_Chdr))
2500     return (size - sizeof (Elf32_External_Chdr)
2501 	    + sizeof (Elf64_External_Chdr));
2502   else
2503     return (size - sizeof (Elf64_External_Chdr)
2504 	    + sizeof (Elf32_External_Chdr));
2505 }
2506 
2507 /*
2508 FUNCTION
2509 	bfd_convert_section_contents
2510 
2511 SYNOPSIS
2512 	bfd_boolean bfd_convert_section_contents
2513 	  (bfd *ibfd, asection *isec, bfd *obfd,
2514 	   bfd_byte **ptr, bfd_size_type *ptr_size);
2515 
2516 DESCRIPTION
2517 	Convert the contents, stored in @var{*ptr}, of the section
2518 	@var{isec} in input BFD @var{ibfd} to output BFD @var{obfd}
2519 	if needed.  The original buffer pointed to by @var{*ptr} may
2520 	be freed and @var{*ptr} is returned with memory malloc'd by this
2521 	function, and the new size written to @var{ptr_size}.
2522 */
2523 
2524 bfd_boolean
bfd_convert_section_contents(bfd * ibfd,sec_ptr isec,bfd * obfd,bfd_byte ** ptr,bfd_size_type * ptr_size)2525 bfd_convert_section_contents (bfd *ibfd, sec_ptr isec, bfd *obfd,
2526 			      bfd_byte **ptr, bfd_size_type *ptr_size)
2527 {
2528   bfd_byte *contents;
2529   bfd_size_type ihdr_size, ohdr_size, size;
2530   Elf_Internal_Chdr chdr;
2531   bfd_boolean use_memmove;
2532 
2533   /* Do nothing if input file will be decompressed.  */
2534   if ((ibfd->flags & BFD_DECOMPRESS))
2535     return TRUE;
2536 
2537   /* Do nothing if either input or output aren't ELF.  */
2538   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
2539       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
2540     return TRUE;
2541 
2542   /* Do nothing if ELF classes of input and output are the same. */
2543   if (get_elf_backend_data (ibfd)->s->elfclass
2544       == get_elf_backend_data (obfd)->s->elfclass)
2545     return TRUE;
2546 
2547   /* Do nothing if the input section isn't a SHF_COMPRESSED section. */
2548   ihdr_size = bfd_get_compression_header_size (ibfd, isec);
2549   if (ihdr_size == 0)
2550     return TRUE;
2551 
2552   contents = *ptr;
2553 
2554   /* Convert the contents of the input SHF_COMPRESSED section to
2555      output.  Get the input compression header and the size of the
2556      output compression header.  */
2557   if (ihdr_size == sizeof (Elf32_External_Chdr))
2558     {
2559       Elf32_External_Chdr *echdr = (Elf32_External_Chdr *) contents;
2560       chdr.ch_type = bfd_get_32 (ibfd, &echdr->ch_type);
2561       chdr.ch_size = bfd_get_32 (ibfd, &echdr->ch_size);
2562       chdr.ch_addralign = bfd_get_32 (ibfd, &echdr->ch_addralign);
2563 
2564       ohdr_size = sizeof (Elf64_External_Chdr);
2565 
2566       use_memmove = FALSE;
2567     }
2568   else
2569     {
2570       Elf64_External_Chdr *echdr = (Elf64_External_Chdr *) contents;
2571       chdr.ch_type = bfd_get_32 (ibfd, &echdr->ch_type);
2572       chdr.ch_size = bfd_get_64 (ibfd, &echdr->ch_size);
2573       chdr.ch_addralign = bfd_get_64 (ibfd, &echdr->ch_addralign);
2574 
2575       ohdr_size = sizeof (Elf32_External_Chdr);
2576       use_memmove = TRUE;
2577     }
2578 
2579   size = bfd_get_section_size (isec) - ihdr_size + ohdr_size;
2580   if (!use_memmove)
2581     {
2582       contents = (bfd_byte *) bfd_malloc (size);
2583       if (contents == NULL)
2584 	return FALSE;
2585     }
2586 
2587   /* Write out the output compression header.  */
2588   if (ohdr_size == sizeof (Elf32_External_Chdr))
2589     {
2590       Elf32_External_Chdr *echdr = (Elf32_External_Chdr *) contents;
2591       bfd_put_32 (obfd, ELFCOMPRESS_ZLIB, &echdr->ch_type);
2592       bfd_put_32 (obfd, chdr.ch_size, &echdr->ch_size);
2593       bfd_put_32 (obfd, chdr.ch_addralign, &echdr->ch_addralign);
2594     }
2595   else
2596     {
2597       Elf64_External_Chdr *echdr = (Elf64_External_Chdr *) contents;
2598       bfd_put_32 (obfd, ELFCOMPRESS_ZLIB, &echdr->ch_type);
2599       bfd_put_32 (obfd, 0, &echdr->ch_reserved);
2600       bfd_put_64 (obfd, chdr.ch_size, &echdr->ch_size);
2601       bfd_put_64 (obfd, chdr.ch_addralign, &echdr->ch_addralign);
2602     }
2603 
2604   /* Copy the compressed contents.  */
2605   if (use_memmove)
2606     memmove (contents + ohdr_size, *ptr + ihdr_size, size - ohdr_size);
2607   else
2608     {
2609       memcpy (contents + ohdr_size, *ptr + ihdr_size, size - ohdr_size);
2610       free (*ptr);
2611       *ptr = contents;
2612     }
2613 
2614   *ptr_size = size;
2615   return TRUE;
2616 }
2617