fix mistakes in last change
[platform/upstream/binutils.git] / bfd / bfd.c
1 /* Generic BFD library interface and support routines.
2    Copyright (C) 1990, 1991, 1992, 1993 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 2 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., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 /*
22 SECTION
23         <<typedef bfd>>
24
25         A BFD has type <<bfd>>; objects of this type are the
26         cornerstone of any application using <<libbfd>>. Using BFD
27         consists of making references though the BFD and to data in the BFD.
28
29         Here is the structure that defines the type <<bfd>>.  It
30         contains the major data about the file and pointers
31         to the rest of the data.
32
33 CODE_FRAGMENT
34 .
35 .struct _bfd 
36 .{
37 .    {* The filename the application opened the BFD with.  *}
38 .    CONST char *filename;                
39 .
40 .    {* A pointer to the target jump table.             *}
41 .    struct bfd_target *xvec;
42 .
43 .    {* To avoid dragging too many header files into every file that
44 .       includes `<<bfd.h>>', IOSTREAM has been declared as a "char
45 .       *", and MTIME as a "long".  Their correct types, to which they
46 .       are cast when used, are "FILE *" and "time_t".    The iostream
47 .       is the result of an fopen on the filename. *}
48 .    char *iostream;
49 .
50 .    {* Is the file descriptor being cached?  That is, can it be closed as
51 .       needed, and re-opened when accessed later?  *}
52 .
53 .    boolean cacheable;
54 .
55 .    {* Marks whether there was a default target specified when the
56 .       BFD was opened. This is used to select which matching algorithm
57 .       to use to choose the back end. *}
58 .
59 .    boolean target_defaulted;
60 .
61 .    {* The caching routines use these to maintain a
62 .       least-recently-used list of BFDs *}
63 .
64 .    struct _bfd *lru_prev, *lru_next;
65 .
66 .    {* When a file is closed by the caching routines, BFD retains
67 .       state information on the file here: *}
68 .
69 .    file_ptr where;              
70 .
71 .    {* and here: (``once'' means at least once) *}
72 .
73 .    boolean opened_once;
74 .
75 .    {* Set if we have a locally maintained mtime value, rather than
76 .       getting it from the file each time: *}
77 .
78 .    boolean mtime_set;
79 .
80 .    {* File modified time, if mtime_set is true: *}
81 .
82 .    long mtime;          
83 .
84 .    {* Reserved for an unimplemented file locking extension.*}
85 .
86 .    int ifd;
87 .
88 .    {* The format which belongs to the BFD. (object, core, etc.) *}
89 .
90 .    bfd_format format;
91 .
92 .    {* The direction the BFD was opened with*}
93 .
94 .    enum bfd_direction {no_direction = 0,
95 .                        read_direction = 1,
96 .                        write_direction = 2,
97 .                        both_direction = 3} direction;
98 .
99 .    {* Format_specific flags*}
100 .
101 .    flagword flags;              
102 .
103 .    {* Currently my_archive is tested before adding origin to
104 .       anything. I believe that this can become always an add of
105 .       origin, with origin set to 0 for non archive files.   *}
106 .
107 .    file_ptr origin;             
108 .
109 .    {* Remember when output has begun, to stop strange things
110 .       from happening. *}
111 .    boolean output_has_begun;
112 .
113 .    {* Pointer to linked list of sections*}
114 .    struct sec  *sections;
115 .
116 .    {* The number of sections *}
117 .    unsigned int section_count;
118 .
119 .    {* Stuff only useful for object files: 
120 .       The start address. *}
121 .    bfd_vma start_address;
122 .
123 .    {* Used for input and output*}
124 .    unsigned int symcount;
125 .
126 .    {* Symbol table for output BFD (with symcount entries) *}
127 .    struct symbol_cache_entry  **outsymbols;             
128 .
129 .    {* Pointer to structure which contains architecture information*}
130 .    struct bfd_arch_info *arch_info;
131 .
132 .    {* Stuff only useful for archives:*}
133 .    PTR arelt_data;              
134 .    struct _bfd *my_archive;     {* The containing archive BFD.  *}
135 .    struct _bfd *next;           {* The next BFD in the archive.  *}
136 .    struct _bfd *archive_head;   {* The first BFD in the archive.  *}
137 .    boolean has_armap;           
138 .
139 .    {* Used by the back end to hold private data. *}
140 .
141 .    union 
142 .      {
143 .      struct aout_data_struct *aout_data;
144 .      struct artdata *aout_ar_data;
145 .      struct _oasys_data *oasys_obj_data;
146 .      struct _oasys_ar_data *oasys_ar_data;
147 .      struct coff_tdata *coff_obj_data;
148 .      struct ecoff_tdata *ecoff_obj_data;
149 .      struct ieee_data_struct *ieee_data;
150 .      struct ieee_ar_data_struct *ieee_ar_data;
151 .      struct srec_data_struct *srec_data;
152 .      struct tekhex_data_struct *tekhex_data;
153 .      struct elf_obj_tdata *elf_obj_data;
154 .      struct nlm_obj_tdata *nlm_obj_data;
155 .      struct bout_data_struct *bout_data;
156 .      struct sun_core_struct *sun_core_data;
157 .      struct trad_core_struct *trad_core_data;
158 .      struct som_data_struct *som_data;
159 .      struct hpux_core_struct *hpux_core_data;
160 .      struct sgi_core_struct *sgi_core_data;
161 .      struct lynx_core_struct *lynx_core_data;
162 .      struct osf_core_struct *osf_core_data;
163 .      PTR any;
164 .      } tdata;
165 .  
166 .    {* Used by the application to hold private data*}
167 .    PTR usrdata;
168 .
169 .    {* Where all the allocated stuff under this BFD goes *}
170 .    struct obstack memory;
171 .
172 .    {* Is this really needed in addition to usrdata?  *}
173 .    asymbol **ld_symbols;
174 .};
175 .
176 */
177
178 #include "bfd.h"
179 #include "sysdep.h"
180 #include "libbfd.h"
181 #include "coff/internal.h"
182 #include "coff/sym.h"
183 #include "libcoff.h"
184 #include "libecoff.h"
185 #undef obj_symbols
186 #include "libelf.h"
187
188 #undef strerror
189 extern char *strerror();
190
191 /** Error handling
192     o - Most functions return nonzero on success (check doc for
193         precise semantics); 0 or NULL on error.
194     o - Internal errors are documented by the value of bfd_error.
195         If that is system_call_error then check errno.
196     o - The easiest way to report this to the user is to use bfd_perror.
197 */
198
199 bfd_ec bfd_error = no_error;
200
201 CONST char *CONST bfd_errmsgs[] = {
202                         "No error",
203                         "System call error",
204                         "Invalid target",
205                         "File in wrong format",
206                         "Invalid operation",
207                         "Memory exhausted",
208                         "No symbols",
209                         "No relocation info",
210                         "No more archived files",
211                         "Malformed archive",
212                         "Symbol not found",
213                         "File format not recognized",
214                         "File format is ambiguous",
215                         "Section has no contents",
216                         "Nonrepresentable section on output",
217                         "Symbol needs debug section which does not exist",
218                         "Bad value",
219                         "File truncated",
220                         "#<Invalid error code>"
221                        };
222
223 static 
224 void 
225 DEFUN(bfd_nonrepresentable_section,(abfd, name),
226          CONST  bfd * CONST abfd AND
227          CONST  char * CONST name)
228 {
229   fprintf(stderr,
230           "bfd error writing file %s, format %s can't represent section %s\n",
231           abfd->filename, 
232           abfd->xvec->name,
233           name);
234   exit(1);
235 }
236
237 /*ARGSUSED*/
238 static 
239 void 
240 DEFUN(bfd_undefined_symbol,(relent, seclet),
241       CONST  arelent *relent AND
242       CONST  struct bfd_seclet *seclet)
243 {
244   asymbol *symbol = *(relent->sym_ptr_ptr);
245   fprintf(stderr, "bfd error relocating, symbol %s is undefined\n",
246           symbol->name);
247   exit(1);
248 }
249 /*ARGSUSED*/
250 static 
251 void 
252 DEFUN(bfd_reloc_value_truncated,(relent, seclet),
253          CONST  arelent *relent AND
254       struct bfd_seclet *seclet)
255 {
256   fprintf(stderr, "bfd error relocating, value truncated\n");
257   exit(1);
258 }
259 /*ARGSUSED*/
260 static 
261 void 
262 DEFUN(bfd_reloc_is_dangerous,(relent, seclet),
263       CONST  arelent *relent AND
264      CONST  struct bfd_seclet *seclet)
265 {
266   fprintf(stderr, "bfd error relocating, dangerous\n");
267   exit(1);
268 }
269
270 bfd_error_vector_type bfd_error_vector = 
271   {
272   bfd_nonrepresentable_section ,
273   bfd_undefined_symbol,
274   bfd_reloc_value_truncated,
275   bfd_reloc_is_dangerous,
276   };
277
278
279 CONST char *
280 bfd_errmsg (error_tag)
281      bfd_ec error_tag;
282 {
283 #ifndef errno
284   extern int errno;
285 #endif
286   if (error_tag == system_call_error)
287     return strerror (errno);
288
289   if ((((int)error_tag <(int) no_error) ||
290        ((int)error_tag > (int)invalid_error_code)))
291     error_tag = invalid_error_code;/* sanity check */
292
293   return bfd_errmsgs [(int)error_tag];
294 }
295
296 void
297 DEFUN (bfd_default_error_trap, (error_tag),
298        bfd_ec error_tag)
299 {
300   fprintf(stderr, "bfd assert fail (%s)\n", bfd_errmsg(error_tag));
301 }
302
303 void (*bfd_error_trap) PARAMS ((bfd_ec)) = bfd_default_error_trap;
304 void (*bfd_error_nonrepresentabltrap) PARAMS ((bfd_ec)) = bfd_default_error_trap;
305
306 void
307 DEFUN(bfd_perror,(message),
308       CONST char *message)
309 {
310   if (bfd_error == system_call_error)
311     perror((char *)message);            /* must be system error then... */
312   else {
313     if (message == NULL || *message == '\0')
314       fprintf (stderr, "%s\n", bfd_errmsg (bfd_error));
315     else
316       fprintf (stderr, "%s: %s\n", message, bfd_errmsg (bfd_error));
317   }
318 }
319
320  \f
321 /** Symbols */
322
323
324 /*
325 FUNCTION
326         bfd_get_reloc_upper_bound
327
328 SYNOPSIS
329         unsigned int bfd_get_reloc_upper_bound(bfd *abfd, asection *sect);
330
331 DESCRIPTION
332         Return the number of bytes required to store the
333         relocation information associated with section @var{sect}
334         attached to bfd @var{abfd}.
335
336 */
337
338
339 unsigned int
340 DEFUN(bfd_get_reloc_upper_bound,(abfd, asect),
341      bfd *abfd AND
342      sec_ptr asect)
343 {
344   if (abfd->format != bfd_object) {
345     bfd_error = invalid_operation;
346     return 0;
347   }
348
349   return BFD_SEND (abfd, _get_reloc_upper_bound, (abfd, asect));
350 }
351
352 /*
353 FUNCTION
354         bfd_canonicalize_reloc
355
356 SYNOPSIS
357         unsigned int bfd_canonicalize_reloc
358                 (bfd *abfd,
359                 asection *sec,
360                 arelent **loc,
361                 asymbol **syms);
362
363 DESCRIPTION
364         Call the back end associated with the open BFD
365         @var{abfd} and translate the external form of the relocation
366         information attached to @var{sec} into the internal canonical
367         form.  Place the table into memory at @var{loc}, which has
368         been preallocated, usually by a call to
369         <<bfd_get_reloc_upper_bound>>.
370
371         The @var{syms} table is also needed for horrible internal magic
372         reasons.
373
374
375 */
376 unsigned int
377 DEFUN(bfd_canonicalize_reloc,(abfd, asect, location, symbols),
378      bfd *abfd AND
379      sec_ptr asect AND
380      arelent **location AND
381      asymbol **symbols)
382 {
383   if (abfd->format != bfd_object) {
384     bfd_error = invalid_operation;
385     return 0;
386   }
387   return BFD_SEND (abfd, _bfd_canonicalize_reloc,
388                    (abfd, asect, location, symbols));
389 }
390
391 /*
392 FUNCTION
393         bfd_set_reloc
394
395 SYNOPSIS
396         void bfd_set_reloc
397           (bfd *abfd, asection *sec, arelent **rel, unsigned int count)
398
399 DESCRIPTION
400         Set the relocation pointer and count within
401         section @var{sec} to the values @var{rel} and @var{count}.
402         The argument @var{abfd} is ignored.
403
404 */
405 /*ARGSUSED*/
406 void
407 bfd_set_reloc (ignore_abfd, asect, location, count)
408      bfd *ignore_abfd;
409      sec_ptr asect;
410      arelent **location;
411      unsigned int count;
412 {
413   asect->orelocation  = location;
414   asect->reloc_count = count;
415 }
416
417 /*
418 FUNCTION
419         bfd_set_file_flags
420
421 SYNOPSIS
422         boolean bfd_set_file_flags(bfd *abfd, flagword flags);
423
424 DESCRIPTION
425         Set the flag word in the BFD @var{abfd} to the value @var{flags}.
426
427         Possible errors are:
428         o wrong_format - The target bfd was not of object format.
429         o invalid_operation - The target bfd was open for reading.
430         o invalid_operation -
431         The flag word contained a bit which was not applicable to the
432         type of file.  E.g., an attempt was made to set the D_PAGED bit
433         on a bfd format which does not support demand paging.
434
435 */
436
437 boolean
438 bfd_set_file_flags (abfd, flags)
439      bfd *abfd;
440      flagword flags;
441 {
442   if (abfd->format != bfd_object) {
443     bfd_error = wrong_format;
444     return false;
445   }
446
447   if (bfd_read_p (abfd)) {
448     bfd_error = invalid_operation;
449     return false;
450   }
451
452   bfd_get_file_flags (abfd) = flags;
453   if ((flags & bfd_applicable_file_flags (abfd)) != flags) {
454     bfd_error = invalid_operation;
455     return false;
456   }
457
458 return true;
459 }
460
461 void
462 bfd_assert(file, line)
463 char *file;
464 int line;
465 {
466   fprintf(stderr, "bfd assertion fail %s:%d\n",file,line);
467 }
468
469
470 /*
471 FUNCTION
472         bfd_set_start_address
473
474 SYNOPSIS
475         boolean bfd_set_start_address(bfd *abfd, bfd_vma vma);
476
477 DESCRIPTION
478         Make @var{vma} the entry point of output BFD @var{abfd}.
479
480 RETURNS
481         Returns <<true>> on success, <<false>> otherwise.
482 */
483
484 boolean
485 bfd_set_start_address(abfd, vma)
486 bfd *abfd;
487 bfd_vma vma;
488 {
489   abfd->start_address = vma;
490   return true;
491 }
492
493
494 /*
495 FUNCTION
496         bfd_get_mtime
497
498 SYNOPSIS
499         long bfd_get_mtime(bfd *abfd);
500
501 DESCRIPTION
502         Return the file modification time (as read from the file system, or
503         from the archive header for archive members).
504
505 */
506
507 long
508 bfd_get_mtime (abfd)
509      bfd *abfd;
510 {
511   FILE *fp;
512   struct stat buf;
513
514   if (abfd->mtime_set)
515     return abfd->mtime;
516
517   fp = bfd_cache_lookup (abfd);
518   if (0 != fstat (fileno (fp), &buf))
519     return 0;
520
521   abfd->mtime = buf.st_mtime;           /* Save value in case anyone wants it */
522   return buf.st_mtime;
523 }
524
525 /*
526 FUNCTION
527         bfd_get_size
528
529 SYNOPSIS
530         long bfd_get_size(bfd *abfd);
531
532 DESCRIPTION
533         Return the file size (as read from file system) for the file
534         associated with BFD @var{abfd}.
535
536         The initial motivation for, and use of, this routine is not
537         so we can get the exact size of the object the BFD applies to, since
538         that might not be generally possible (archive members for example).
539         It would be ideal if someone could eventually modify
540         it so that such results were guaranteed.
541
542         Instead, we want to ask questions like "is this NNN byte sized
543         object I'm about to try read from file offset YYY reasonable?"
544         As as example of where we might do this, some object formats
545         use string tables for which the first <<sizeof(long)>> bytes of the
546         table contain the size of the table itself, including the size bytes.
547         If an application tries to read what it thinks is one of these
548         string tables, without some way to validate the size, and for
549         some reason the size is wrong (byte swapping error, wrong location
550         for the string table, etc.), the only clue is likely to be a read
551         error when it tries to read the table, or a "virtual memory
552         exhausted" error when it tries to allocate 15 bazillon bytes
553         of space for the 15 bazillon byte table it is about to read.
554         This function at least allows us to answer the quesion, "is the
555         size reasonable?".
556 */
557
558 long
559 bfd_get_size (abfd)
560      bfd *abfd;
561 {
562   FILE *fp;
563   struct stat buf;
564
565   fp = bfd_cache_lookup (abfd);
566   if (0 != fstat (fileno (fp), &buf))
567     return 0;
568
569   return buf.st_size;
570 }
571
572 /*
573 FUNCTION
574         bfd_get_gp_size
575
576 SYNOPSIS
577         int bfd_get_gp_size(bfd *abfd);
578
579 DESCRIPTION
580         Return the maximum size of objects to be optimized using the GP
581         register under MIPS ECOFF.  This is typically set by the -G
582         argument to the compiler, assembler or linker.
583 */
584
585 int
586 bfd_get_gp_size (abfd)
587      bfd *abfd;
588 {
589   if (abfd->xvec->flavour == bfd_target_ecoff_flavour)
590     return ecoff_data (abfd)->gp_size;
591   return 0;
592 }
593
594 /*
595 FUNCTION
596         bfd_set_gp_size
597
598 SYNOPSIS
599         void bfd_set_gp_size(bfd *abfd, int i);
600
601 DESCRIPTION
602         Set the maximum size of objects to be optimized using the GP
603         register under ECOFF or MIPS ELF.  This is typically set by
604         the -G argument to the compiler, assembler or linker.
605 */
606
607 void
608 bfd_set_gp_size (abfd, i)
609      bfd *abfd;
610      int i;
611 {
612   if (abfd->xvec->flavour == bfd_target_ecoff_flavour)
613     ecoff_data (abfd)->gp_size = i;
614   else if (abfd->xvec->flavour == bfd_target_elf_flavour)
615     elf_gp_size (abfd) = i;
616 }
617
618 /*
619 FUNCTION
620         bfd_scan_vma
621
622 SYNOPSIS
623         bfd_vma bfd_scan_vma(CONST char *string, CONST char **end, int base);
624
625 DESCRIPTION
626         Convert, like <<strtoul>>, a numerical expression
627         @var{string} into a bfd_vma integer, and returns that integer.
628         (Though without as many bells and whistles as <<strtoul>>.)
629         The expression is assumed to be unsigned (i.e. positive).
630         If given a @var{base}, it is used as the base for conversion.
631         A base of 0 causes the function to interpret the string
632         in hex if a leading "0x" or "0X" is found, otherwise
633         in octal if a leading zero is found, otherwise in decimal.
634
635         Overflow is not detected.
636 */
637
638 bfd_vma
639 DEFUN(bfd_scan_vma,(string, end, base),
640       CONST char *string AND
641       CONST char **end AND
642       int base)
643 {
644   bfd_vma value;
645   int digit;
646
647   /* Let the host do it if possible.  */
648   if (sizeof(bfd_vma) <= sizeof(unsigned long))
649     return (bfd_vma) strtoul (string, 0, base);
650
651   /* A negative base makes no sense, and we only need to go as high as hex.  */
652   if ((base < 0) || (base > 16))
653     return (bfd_vma) 0;
654
655   if (base == 0)
656     {
657       if (string[0] == '0')
658         {
659           if ((string[1] == 'x') || (string[1] == 'X'))
660             base = 16;
661           /* XXX should we also allow "0b" or "0B" to set base to 2? */
662           else
663             base = 8;
664         }
665       else
666         base = 10;
667     }
668   if ((base == 16) &&
669       (string[0] == '0') && ((string[1] == 'x') || (string[1] == 'X')))
670     string += 2;
671   /* XXX should we also skip over "0b" or "0B" if base is 2? */
672     
673 /* Speed could be improved with a table like hex_value[] in gas.  */
674 #define HEX_VALUE(c) \
675   (isxdigit(c) ?                                \
676     (isdigit(c) ?                               \
677       (c - '0') :                               \
678       (10 + c - (islower(c) ? 'a' : 'A'))) :    \
679     42)
680
681   for (value = 0; (digit = HEX_VALUE(*string)) < base; string++)
682     {
683       value = value * base + digit;
684     }
685
686   if (end)
687     *end = string;
688
689   return value;
690 }
691
692 /*
693 FUNCTION
694         stuff
695
696 DESCRIPTION
697         Stuff which should be documented:
698
699 .#define bfd_sizeof_headers(abfd, reloc) \
700 .     BFD_SEND (abfd, _bfd_sizeof_headers, (abfd, reloc))
701 .
702 .#define bfd_find_nearest_line(abfd, sec, syms, off, file, func, line) \
703 .     BFD_SEND (abfd, _bfd_find_nearest_line,  (abfd, sec, syms, off, file, func, line))
704 .
705 .       {* Do these three do anything useful at all, for any back end?  *}
706 .#define bfd_debug_info_start(abfd) \
707 .        BFD_SEND (abfd, _bfd_debug_info_start, (abfd))
708 .
709 .#define bfd_debug_info_end(abfd) \
710 .        BFD_SEND (abfd, _bfd_debug_info_end, (abfd))
711 .
712 .#define bfd_debug_info_accumulate(abfd, section) \
713 .        BFD_SEND (abfd, _bfd_debug_info_accumulate, (abfd, section))
714 .
715 .
716 .#define bfd_stat_arch_elt(abfd, stat) \
717 .        BFD_SEND (abfd, _bfd_stat_arch_elt,(abfd, stat))
718 .
719 .#define bfd_set_arch_mach(abfd, arch, mach)\
720 .        BFD_SEND ( abfd, _bfd_set_arch_mach, (abfd, arch, mach))
721 .
722 .#define bfd_get_relocated_section_contents(abfd, seclet, data, relocateable) \
723 .       BFD_SEND (abfd, _bfd_get_relocated_section_contents, (abfd, seclet, data, relocateable))
724
725 .#define bfd_relax_section(abfd, section, symbols) \
726 .       BFD_SEND (abfd, _bfd_relax_section, (abfd, section, symbols))
727 .
728 .#define bfd_seclet_link(abfd, data, relocateable) \
729 .       BFD_SEND (abfd, _bfd_seclet_link, (abfd, data, relocateable))
730
731 */