1999-09-11 Donn Terry <donn@interix.com>
[external/binutils.git] / bfd / syms.c
1 /* Generic symbol-table support for the BFD library.
2    Copyright (C) 1990, 91, 92, 93, 94, 95, 96, 97, 98, 1999
3    Free Software Foundation, Inc.
4    Written by Cygnus Support.
5
6 This file is part of BFD, the Binary File Descriptor library.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 /*
23 SECTION
24         Symbols
25
26         BFD tries to maintain as much symbol information as it can when
27         it moves information from file to file. BFD passes information
28         to applications though the <<asymbol>> structure. When the
29         application requests the symbol table, BFD reads the table in
30         the native form and translates parts of it into the internal
31         format. To maintain more than the information passed to
32         applications, some targets keep some information ``behind the
33         scenes'' in a structure only the particular back end knows
34         about. For example, the coff back end keeps the original
35         symbol table structure as well as the canonical structure when
36         a BFD is read in. On output, the coff back end can reconstruct
37         the output symbol table so that no information is lost, even
38         information unique to coff which BFD doesn't know or
39         understand. If a coff symbol table were read, but were written
40         through an a.out back end, all the coff specific information
41         would be lost. The symbol table of a BFD
42         is not necessarily read in until a canonicalize request is
43         made. Then the BFD back end fills in a table provided by the
44         application with pointers to the canonical information.  To
45         output symbols, the application provides BFD with a table of
46         pointers to pointers to <<asymbol>>s. This allows applications
47         like the linker to output a symbol as it was read, since the ``behind
48         the scenes'' information will be still available.
49 @menu
50 @* Reading Symbols::
51 @* Writing Symbols::
52 @* Mini Symbols::
53 @* typedef asymbol::
54 @* symbol handling functions::
55 @end menu
56
57 INODE
58 Reading Symbols, Writing Symbols, Symbols, Symbols
59 SUBSECTION
60         Reading symbols
61
62         There are two stages to reading a symbol table from a BFD:
63         allocating storage, and the actual reading process. This is an
64         excerpt from an application which reads the symbol table:
65
66 |         long storage_needed;
67 |         asymbol **symbol_table;
68 |         long number_of_symbols;
69 |         long i;
70 |
71 |         storage_needed = bfd_get_symtab_upper_bound (abfd);
72 |
73 |         if (storage_needed < 0)
74 |           FAIL
75 |
76 |         if (storage_needed == 0) {
77 |            return ;
78 |         }
79 |         symbol_table = (asymbol **) xmalloc (storage_needed);
80 |           ...
81 |         number_of_symbols =
82 |            bfd_canonicalize_symtab (abfd, symbol_table);
83 |
84 |         if (number_of_symbols < 0)
85 |           FAIL
86 |
87 |         for (i = 0; i < number_of_symbols; i++) {
88 |            process_symbol (symbol_table[i]);
89 |         }
90
91         All storage for the symbols themselves is in an objalloc
92         connected to the BFD; it is freed when the BFD is closed.
93
94
95 INODE
96 Writing Symbols, Mini Symbols, Reading Symbols, Symbols
97 SUBSECTION
98         Writing symbols
99
100         Writing of a symbol table is automatic when a BFD open for
101         writing is closed. The application attaches a vector of
102         pointers to pointers to symbols to the BFD being written, and
103         fills in the symbol count. The close and cleanup code reads
104         through the table provided and performs all the necessary
105         operations. The BFD output code must always be provided with an
106         ``owned'' symbol: one which has come from another BFD, or one
107         which has been created using <<bfd_make_empty_symbol>>.  Here is an
108         example showing the creation of a symbol table with only one element:
109
110 |       #include "bfd.h"
111 |       main()
112 |       {
113 |         bfd *abfd;
114 |         asymbol *ptrs[2];
115 |         asymbol *new;
116 |
117 |         abfd = bfd_openw("foo","a.out-sunos-big");
118 |         bfd_set_format(abfd, bfd_object);
119 |         new = bfd_make_empty_symbol(abfd);
120 |         new->name = "dummy_symbol";
121 |         new->section = bfd_make_section_old_way(abfd, ".text");
122 |         new->flags = BSF_GLOBAL;
123 |         new->value = 0x12345;
124 |
125 |         ptrs[0] = new;
126 |         ptrs[1] = (asymbol *)0;
127 |
128 |         bfd_set_symtab(abfd, ptrs, 1);
129 |         bfd_close(abfd);
130 |       }
131 |
132 |       ./makesym
133 |       nm foo
134 |       00012345 A dummy_symbol
135
136         Many formats cannot represent arbitary symbol information; for
137         instance, the <<a.out>> object format does not allow an
138         arbitary number of sections. A symbol pointing to a section
139         which is not one  of <<.text>>, <<.data>> or <<.bss>> cannot
140         be described.
141
142 INODE
143 Mini Symbols, typedef asymbol, Writing Symbols, Symbols
144 SUBSECTION
145         Mini Symbols
146
147         Mini symbols provide read-only access to the symbol table.
148         They use less memory space, but require more time to access.
149         They can be useful for tools like nm or objdump, which may
150         have to handle symbol tables of extremely large executables.
151
152         The <<bfd_read_minisymbols>> function will read the symbols
153         into memory in an internal form.  It will return a <<void *>>
154         pointer to a block of memory, a symbol count, and the size of
155         each symbol.  The pointer is allocated using <<malloc>>, and
156         should be freed by the caller when it is no longer needed.
157
158         The function <<bfd_minisymbol_to_symbol>> will take a pointer
159         to a minisymbol, and a pointer to a structure returned by
160         <<bfd_make_empty_symbol>>, and return a <<asymbol>> structure.
161         The return value may or may not be the same as the value from
162         <<bfd_make_empty_symbol>> which was passed in.
163
164 */
165
166
167
168 /*
169 DOCDD
170 INODE
171 typedef asymbol, symbol handling functions, Mini Symbols, Symbols
172
173 */
174 /*
175 SUBSECTION
176         typedef asymbol
177
178         An <<asymbol>> has the form:
179
180 */
181
182 /*
183 CODE_FRAGMENT
184
185 .
186 .typedef struct symbol_cache_entry
187 .{
188 .       {* A pointer to the BFD which owns the symbol. This information
189 .          is necessary so that a back end can work out what additional
190 .          information (invisible to the application writer) is carried
191 .          with the symbol.
192 .
193 .          This field is *almost* redundant, since you can use section->owner
194 .          instead, except that some symbols point to the global sections
195 .          bfd_{abs,com,und}_section.  This could be fixed by making
196 .          these globals be per-bfd (or per-target-flavor).  FIXME. *}
197 .
198 .  struct _bfd *the_bfd; {* Use bfd_asymbol_bfd(sym) to access this field. *}
199 .
200 .       {* The text of the symbol. The name is left alone, and not copied; the
201 .          application may not alter it. *}
202 .  CONST char *name;
203 .
204 .       {* The value of the symbol.  This really should be a union of a
205 .          numeric value with a pointer, since some flags indicate that
206 .          a pointer to another symbol is stored here.  *}
207 .  symvalue value;
208 .
209 .       {* Attributes of a symbol: *}
210 .
211 .#define BSF_NO_FLAGS    0x00
212 .
213 .       {* The symbol has local scope; <<static>> in <<C>>. The value
214 .          is the offset into the section of the data. *}
215 .#define BSF_LOCAL      0x01
216 .
217 .       {* The symbol has global scope; initialized data in <<C>>. The
218 .          value is the offset into the section of the data. *}
219 .#define BSF_GLOBAL     0x02
220 .
221 .       {* The symbol has global scope and is exported. The value is
222 .          the offset into the section of the data. *}
223 .#define BSF_EXPORT     BSF_GLOBAL {* no real difference *}
224 .
225 .       {* A normal C symbol would be one of:
226 .          <<BSF_LOCAL>>, <<BSF_FORT_COMM>>,  <<BSF_UNDEFINED>> or
227 .          <<BSF_GLOBAL>> *}
228 .
229 .       {* The symbol is a debugging record. The value has an arbitary
230 .          meaning, unless BSF_DEBUGGING_RELOC is also set.  *}
231 .#define BSF_DEBUGGING  0x08
232 .
233 .       {* The symbol denotes a function entry point.  Used in ELF,
234 .          perhaps others someday.  *}
235 .#define BSF_FUNCTION    0x10
236 .
237 .       {* Used by the linker. *}
238 .#define BSF_KEEP        0x20
239 .#define BSF_KEEP_G      0x40
240 .
241 .       {* A weak global symbol, overridable without warnings by
242 .          a regular global symbol of the same name.  *}
243 .#define BSF_WEAK        0x80
244 .
245 .       {* This symbol was created to point to a section, e.g. ELF's
246 .          STT_SECTION symbols.  *}
247 .#define BSF_SECTION_SYM 0x100
248 .
249 .       {* The symbol used to be a common symbol, but now it is
250 .          allocated. *}
251 .#define BSF_OLD_COMMON  0x200
252 .
253 .       {* The default value for common data. *}
254 .#define BFD_FORT_COMM_DEFAULT_VALUE 0
255 .
256 .       {* In some files the type of a symbol sometimes alters its
257 .          location in an output file - ie in coff a <<ISFCN>> symbol
258 .          which is also <<C_EXT>> symbol appears where it was
259 .          declared and not at the end of a section.  This bit is set
260 .          by the target BFD part to convey this information. *}
261 .
262 .#define BSF_NOT_AT_END    0x400
263 .
264 .       {* Signal that the symbol is the label of constructor section. *}
265 .#define BSF_CONSTRUCTOR   0x800
266 .
267 .       {* Signal that the symbol is a warning symbol.  The name is a
268 .          warning.  The name of the next symbol is the one to warn about;
269 .          if a reference is made to a symbol with the same name as the next
270 .          symbol, a warning is issued by the linker. *}
271 .#define BSF_WARNING       0x1000
272 .
273 .       {* Signal that the symbol is indirect.  This symbol is an indirect
274 .          pointer to the symbol with the same name as the next symbol. *}
275 .#define BSF_INDIRECT      0x2000
276 .
277 .       {* BSF_FILE marks symbols that contain a file name.  This is used
278 .          for ELF STT_FILE symbols.  *}
279 .#define BSF_FILE          0x4000
280 .
281 .       {* Symbol is from dynamic linking information.  *}
282 .#define BSF_DYNAMIC       0x8000
283 .
284 .       {* The symbol denotes a data object.  Used in ELF, and perhaps
285 .          others someday.  *}
286 .#define BSF_OBJECT        0x10000
287 .
288 .       {* This symbol is a debugging symbol.  The value is the offset
289 .          into the section of the data.  BSF_DEBUGGING should be set
290 .          as well.  *}
291 .#define BSF_DEBUGGING_RELOC 0x20000
292 .
293 .  flagword flags;
294 .
295 .       {* A pointer to the section to which this symbol is
296 .          relative.  This will always be non NULL, there are special
297 .          sections for undefined and absolute symbols.  *}
298 .  struct sec *section;
299 .
300 .       {* Back end special data.  *}
301 .  union
302 .    {
303 .      PTR p;
304 .      bfd_vma i;
305 .    } udata;
306 .
307 .} asymbol;
308 */
309
310 #include "bfd.h"
311 #include "sysdep.h"
312 #include "libbfd.h"
313 #include "bfdlink.h"
314 #include "aout/stab_gnu.h"
315
316 static char coff_section_type PARAMS ((const char *));
317
318 /*
319 DOCDD
320 INODE
321 symbol handling functions,  , typedef asymbol, Symbols
322 SUBSECTION
323         Symbol handling functions
324 */
325
326 /*
327 FUNCTION
328         bfd_get_symtab_upper_bound
329
330 DESCRIPTION
331         Return the number of bytes required to store a vector of pointers
332         to <<asymbols>> for all the symbols in the BFD @var{abfd},
333         including a terminal NULL pointer. If there are no symbols in
334         the BFD, then return 0.  If an error occurs, return -1.
335
336 .#define bfd_get_symtab_upper_bound(abfd) \
337 .     BFD_SEND (abfd, _bfd_get_symtab_upper_bound, (abfd))
338
339 */
340
341 /*
342 FUNCTION
343         bfd_is_local_label
344
345 SYNOPSIS
346         boolean bfd_is_local_label(bfd *abfd, asymbol *sym);
347
348 DESCRIPTION
349         Return true if the given symbol @var{sym} in the BFD @var{abfd} is
350         a compiler generated local label, else return false.
351 */
352
353 boolean
354 bfd_is_local_label (abfd, sym)
355      bfd *abfd;
356      asymbol *sym;
357 {
358   if ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0)
359     return false;
360   if (sym->name == NULL)
361     return false;
362   return bfd_is_local_label_name (abfd, sym->name);
363 }
364
365 /*
366 FUNCTION
367         bfd_is_local_label_name
368
369 SYNOPSIS
370         boolean bfd_is_local_label_name(bfd *abfd, const char *name);
371
372 DESCRIPTION
373         Return true if a symbol with the name @var{name} in the BFD
374         @var{abfd} is a compiler generated local label, else return
375         false.  This just checks whether the name has the form of a
376         local label.
377
378 .#define bfd_is_local_label_name(abfd, name) \
379 .     BFD_SEND (abfd, _bfd_is_local_label_name, (abfd, name))
380 */
381
382 /*
383 FUNCTION
384         bfd_canonicalize_symtab
385
386 DESCRIPTION
387         Read the symbols from the BFD @var{abfd}, and fills in
388         the vector @var{location} with pointers to the symbols and
389         a trailing NULL.
390         Return the actual number of symbol pointers, not
391         including the NULL.
392
393
394 .#define bfd_canonicalize_symtab(abfd, location) \
395 .     BFD_SEND (abfd, _bfd_canonicalize_symtab,\
396 .                  (abfd, location))
397
398 */
399
400
401 /*
402 FUNCTION
403         bfd_set_symtab
404
405 SYNOPSIS
406         boolean bfd_set_symtab (bfd *abfd, asymbol **location, unsigned int count);
407
408 DESCRIPTION
409         Arrange that when the output BFD @var{abfd} is closed,
410         the table @var{location} of @var{count} pointers to symbols
411         will be written.
412 */
413
414 boolean
415 bfd_set_symtab (abfd, location, symcount)
416      bfd *abfd;
417      asymbol **location;
418      unsigned int symcount;
419 {
420   if ((abfd->format != bfd_object) || (bfd_read_p (abfd)))
421     {
422       bfd_set_error (bfd_error_invalid_operation);
423       return false;
424     }
425
426   bfd_get_outsymbols (abfd) = location;
427   bfd_get_symcount (abfd) = symcount;
428   return true;
429 }
430
431 /*
432 FUNCTION
433         bfd_print_symbol_vandf
434
435 SYNOPSIS
436         void bfd_print_symbol_vandf(PTR file, asymbol *symbol);
437
438 DESCRIPTION
439         Print the value and flags of the @var{symbol} supplied to the
440         stream @var{file}.
441 */
442 void
443 bfd_print_symbol_vandf (arg, symbol)
444      PTR arg;
445      asymbol *symbol;
446 {
447   FILE *file = (FILE *) arg;
448   flagword type = symbol->flags;
449   if (symbol->section != (asection *) NULL)
450     {
451       fprintf_vma (file, symbol->value + symbol->section->vma);
452     }
453   else
454     {
455       fprintf_vma (file, symbol->value);
456     }
457
458   /* This presumes that a symbol can not be both BSF_DEBUGGING and
459      BSF_DYNAMIC, nor more than one of BSF_FUNCTION, BSF_FILE, and
460      BSF_OBJECT.  */
461   fprintf (file, " %c%c%c%c%c%c%c",
462            ((type & BSF_LOCAL)
463             ? (type & BSF_GLOBAL) ? '!' : 'l'
464             : (type & BSF_GLOBAL) ? 'g' : ' '),
465            (type & BSF_WEAK) ? 'w' : ' ',
466            (type & BSF_CONSTRUCTOR) ? 'C' : ' ',
467            (type & BSF_WARNING) ? 'W' : ' ',
468            (type & BSF_INDIRECT) ? 'I' : ' ',
469            (type & BSF_DEBUGGING) ? 'd' : (type & BSF_DYNAMIC) ? 'D' : ' ',
470            ((type & BSF_FUNCTION)
471             ? 'F'
472             : ((type & BSF_FILE)
473                ? 'f'
474                : ((type & BSF_OBJECT) ? 'O' : ' '))));
475 }
476
477
478 /*
479 FUNCTION
480         bfd_make_empty_symbol
481
482 DESCRIPTION
483         Create a new <<asymbol>> structure for the BFD @var{abfd}
484         and return a pointer to it.
485
486         This routine is necessary because each back end has private
487         information surrounding the <<asymbol>>. Building your own
488         <<asymbol>> and pointing to it will not create the private
489         information, and will cause problems later on.
490
491 .#define bfd_make_empty_symbol(abfd) \
492 .     BFD_SEND (abfd, _bfd_make_empty_symbol, (abfd))
493 */
494
495 /*
496 FUNCTION
497         bfd_make_debug_symbol
498
499 DESCRIPTION
500         Create a new <<asymbol>> structure for the BFD @var{abfd},
501         to be used as a debugging symbol.  Further details of its use have
502         yet to be worked out.
503
504 .#define bfd_make_debug_symbol(abfd,ptr,size) \
505 .        BFD_SEND (abfd, _bfd_make_debug_symbol, (abfd, ptr, size))
506 */
507
508 struct section_to_type
509 {
510   CONST char *section;
511   char type;
512 };
513
514 /* Map section names to POSIX/BSD single-character symbol types.
515    This table is probably incomplete.  It is sorted for convenience of
516    adding entries.  Since it is so short, a linear search is used.  */
517 static CONST struct section_to_type stt[] =
518 {
519   {"*DEBUG*", 'N'},
520   {".bss", 'b'},
521   {"zerovars", 'b'},            /* MRI .bss */
522   {".data", 'd'},
523   {"vars", 'd'},                /* MRI .data */
524   {".rdata", 'r'},              /* Read only data.  */
525   {".rodata", 'r'},             /* Read only data.  */
526   {".sbss", 's'},               /* Small BSS (uninitialized data).  */
527   {".scommon", 'c'},            /* Small common.  */
528   {".sdata", 'g'},              /* Small initialized data.  */
529   {".text", 't'},
530   {"code", 't'},                /* MRI .text */
531   {".drectve", 'i'},            /* MSVC's .drective section */
532   {".idata", 'i'},              /* MSVC's .idata (import) section */
533   {".edata", 'e'},              /* MSVC's .edata (export) section */
534   {".pdata", 'p'},              /* MSVC's .pdata (stack unwind) section */
535   {".debug", 'N'},              /* MSVC's .debug (non-standard debug syms) */
536   {0, 0}
537 };
538
539 /* Return the single-character symbol type corresponding to
540    section S, or '?' for an unknown COFF section.  
541
542    Check for any leading string which matches, so .text5 returns
543    't' as well as .text */
544
545 static char
546 coff_section_type (s)
547      const char *s;
548 {
549   CONST struct section_to_type *t;
550
551   for (t = &stt[0]; t->section; t++) 
552     if (!strncmp (s, t->section, strlen (t->section)))
553       return t->type;
554
555   return '?';
556 }
557
558 #ifndef islower
559 #define islower(c) ((c) >= 'a' && (c) <= 'z')
560 #endif
561 #ifndef toupper
562 #define toupper(c) (islower(c) ? ((c) & ~0x20) : (c))
563 #endif
564
565 /*
566 FUNCTION
567         bfd_decode_symclass
568
569 DESCRIPTION
570         Return a character corresponding to the symbol
571         class of @var{symbol}, or '?' for an unknown class.
572
573 SYNOPSIS
574         int bfd_decode_symclass(asymbol *symbol);
575 */
576 int
577 bfd_decode_symclass (symbol)
578      asymbol *symbol;
579 {
580   char c;
581
582   if (bfd_is_com_section (symbol->section))
583     return 'C';
584   if (bfd_is_und_section (symbol->section))
585     {
586       if (symbol->flags & BSF_WEAK)
587         return 'w';
588       else
589         return 'U';
590     }
591   if (bfd_is_ind_section (symbol->section))
592     return 'I';
593   if (symbol->flags & BSF_WEAK)
594     return 'W';
595   if (!(symbol->flags & (BSF_GLOBAL | BSF_LOCAL)))
596     return '?';
597
598   if (bfd_is_abs_section (symbol->section))
599     c = 'a';
600   else if (symbol->section)
601     c = coff_section_type (symbol->section->name);
602   else
603     return '?';
604   if (symbol->flags & BSF_GLOBAL)
605     c = toupper (c);
606   return c;
607
608   /* We don't have to handle these cases just yet, but we will soon:
609      N_SETV: 'v';
610      N_SETA: 'l';
611      N_SETT: 'x';
612      N_SETD: 'z';
613      N_SETB: 's';
614      N_INDR: 'i';
615      */
616 }
617
618 /*
619 FUNCTION
620         bfd_symbol_info
621
622 DESCRIPTION
623         Fill in the basic info about symbol that nm needs.
624         Additional info may be added by the back-ends after
625         calling this function.
626
627 SYNOPSIS
628         void bfd_symbol_info(asymbol *symbol, symbol_info *ret);
629 */
630
631 void
632 bfd_symbol_info (symbol, ret)
633      asymbol *symbol;
634      symbol_info *ret;
635 {
636   ret->type = bfd_decode_symclass (symbol);
637   if (ret->type != 'U' && ret->type != 'w')
638     ret->value = symbol->value + symbol->section->vma;
639   else
640     ret->value = 0;
641   ret->name = symbol->name;
642 }
643
644 /*
645 FUNCTION
646         bfd_copy_private_symbol_data
647
648 SYNOPSIS
649         boolean bfd_copy_private_symbol_data(bfd *ibfd, asymbol *isym, bfd *obfd, asymbol *osym);
650
651 DESCRIPTION
652         Copy private symbol information from @var{isym} in the BFD
653         @var{ibfd} to the symbol @var{osym} in the BFD @var{obfd}.
654         Return <<true>> on success, <<false>> on error.  Possible error
655         returns are:
656
657         o <<bfd_error_no_memory>> -
658         Not enough memory exists to create private data for @var{osec}.
659
660 .#define bfd_copy_private_symbol_data(ibfd, isymbol, obfd, osymbol) \
661 .     BFD_SEND (obfd, _bfd_copy_private_symbol_data, \
662 .               (ibfd, isymbol, obfd, osymbol))
663
664 */
665
666 /* The generic version of the function which returns mini symbols.
667    This is used when the backend does not provide a more efficient
668    version.  It just uses BFD asymbol structures as mini symbols.  */
669
670 long
671 _bfd_generic_read_minisymbols (abfd, dynamic, minisymsp, sizep)
672      bfd *abfd;
673      boolean dynamic;
674      PTR *minisymsp;
675      unsigned int *sizep;
676 {
677   long storage;
678   asymbol **syms = NULL;
679   long symcount;
680
681   if (dynamic)
682     storage = bfd_get_dynamic_symtab_upper_bound (abfd);
683   else
684     storage = bfd_get_symtab_upper_bound (abfd);
685   if (storage < 0)
686     goto error_return;
687
688   syms = (asymbol **) bfd_malloc ((size_t) storage);
689   if (syms == NULL)
690     goto error_return;
691
692   if (dynamic)
693     symcount = bfd_canonicalize_dynamic_symtab (abfd, syms);
694   else
695     symcount = bfd_canonicalize_symtab (abfd, syms);
696   if (symcount < 0)
697     goto error_return;
698
699   *minisymsp = (PTR) syms;
700   *sizep = sizeof (asymbol *);
701   return symcount;
702
703  error_return:
704   if (syms != NULL)
705     free (syms);
706   return -1;
707 }
708
709 /* The generic version of the function which converts a minisymbol to
710    an asymbol.  We don't worry about the sym argument we are passed;
711    we just return the asymbol the minisymbol points to.  */
712
713 /*ARGSUSED*/
714 asymbol *
715 _bfd_generic_minisymbol_to_symbol (abfd, dynamic, minisym, sym)
716      bfd *abfd ATTRIBUTE_UNUSED;
717      boolean dynamic ATTRIBUTE_UNUSED;
718      const PTR minisym;
719      asymbol *sym ATTRIBUTE_UNUSED;
720 {
721   return *(asymbol **) minisym;
722 }
723
724 /* Look through stabs debugging information in .stab and .stabstr
725    sections to find the source file and line closest to a desired
726    location.  This is used by COFF and ELF targets.  It sets *pfound
727    to true if it finds some information.  The *pinfo field is used to
728    pass cached information in and out of this routine; this first time
729    the routine is called for a BFD, *pinfo should be NULL.  The value
730    placed in *pinfo should be saved with the BFD, and passed back each
731    time this function is called.  */
732
733 /* We use a cache by default.  */
734
735 #define ENABLE_CACHING
736
737 /* We keep an array of indexentry structures to record where in the
738    stabs section we should look to find line number information for a
739    particular address.  */
740
741 struct indexentry
742 {
743   bfd_vma val;
744   bfd_byte *stab;
745   bfd_byte *str;
746   char *directory_name;
747   char *file_name;
748   char *function_name;
749 };
750
751 /* Compare two indexentry structures.  This is called via qsort.  */
752
753 static int
754 cmpindexentry (a, b)
755      const PTR *a;
756      const PTR *b;
757 {
758   const struct indexentry *contestantA = (const struct indexentry *) a;
759   const struct indexentry *contestantB = (const struct indexentry *) b;
760
761   if (contestantA->val < contestantB->val)
762     return -1;
763   else if (contestantA->val > contestantB->val)
764     return 1;
765   else
766     return 0;
767 }
768
769 /* A pointer to this structure is stored in *pinfo.  */
770
771 struct stab_find_info
772 {
773   /* The .stab section.  */
774   asection *stabsec;
775   /* The .stabstr section.  */
776   asection *strsec;
777   /* The contents of the .stab section.  */
778   bfd_byte *stabs;
779   /* The contents of the .stabstr section.  */
780   bfd_byte *strs;
781
782   /* A table that indexes stabs by memory address.  */
783   struct indexentry *indextable;
784   /* The number of entries in indextable.  */
785   int indextablesize;
786
787 #ifdef ENABLE_CACHING
788   /* Cached values to restart quickly.  */
789   struct indexentry *cached_indexentry;
790   bfd_vma cached_offset;
791   bfd_byte *cached_stab;
792   char *cached_file_name;
793 #endif
794
795   /* Saved ptr to malloc'ed filename.  */
796   char *filename;
797 };
798
799 boolean
800 _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset, pfound,
801                                      pfilename, pfnname, pline, pinfo)
802      bfd *abfd;
803      asymbol **symbols;
804      asection *section;
805      bfd_vma offset;
806      boolean *pfound;
807      const char **pfilename;
808      const char **pfnname;
809      unsigned int *pline;
810      PTR *pinfo;
811 {
812   struct stab_find_info *info;
813   bfd_size_type stabsize, strsize;
814   bfd_byte *stab, *str;
815   bfd_byte *last_stab = NULL;
816   bfd_size_type stroff;
817   struct indexentry *indexentry;
818   char *directory_name, *file_name;
819   int saw_fun;
820
821   *pfound = false;
822   *pfilename = bfd_get_filename (abfd);
823   *pfnname = NULL;
824   *pline = 0;
825
826   /* Stabs entries use a 12 byte format:
827        4 byte string table index
828        1 byte stab type
829        1 byte stab other field
830        2 byte stab desc field
831        4 byte stab value
832      FIXME: This will have to change for a 64 bit object format.
833
834      The stabs symbols are divided into compilation units.  For the
835      first entry in each unit, the type of 0, the value is the length
836      of the string table for this unit, and the desc field is the
837      number of stabs symbols for this unit.  */
838
839 #define STRDXOFF (0)
840 #define TYPEOFF (4)
841 #define OTHEROFF (5)
842 #define DESCOFF (6)
843 #define VALOFF (8)
844 #define STABSIZE (12)
845
846   info = (struct stab_find_info *) *pinfo;
847   if (info != NULL)
848     {
849       if (info->stabsec == NULL || info->strsec == NULL)
850         {
851           /* No stabs debugging information.  */
852           return true;
853         }
854
855       stabsize = info->stabsec->_raw_size;
856       strsize = info->strsec->_raw_size;
857     }
858   else
859     {
860       long reloc_size, reloc_count;
861       arelent **reloc_vector;
862       int i;
863       char *name;
864       char *file_name;
865       char *directory_name;
866       char *function_name;
867
868       info = (struct stab_find_info *) bfd_zalloc (abfd, sizeof *info);
869       if (info == NULL)
870         return false;
871
872       /* FIXME: When using the linker --split-by-file or
873          --split-by-reloc options, it is possible for the .stab and
874          .stabstr sections to be split.  We should handle that.  */
875
876       info->stabsec = bfd_get_section_by_name (abfd, ".stab");
877       info->strsec = bfd_get_section_by_name (abfd, ".stabstr");
878
879       if (info->stabsec == NULL || info->strsec == NULL)
880         {
881           /* No stabs debugging information.  Set *pinfo so that we
882              can return quickly in the info != NULL case above.  */
883           *pinfo = (PTR) info;
884           return true;
885         }
886
887       stabsize = info->stabsec->_raw_size;
888       strsize = info->strsec->_raw_size;
889
890       info->stabs = (bfd_byte *) bfd_alloc (abfd, stabsize);
891       info->strs = (bfd_byte *) bfd_alloc (abfd, strsize);
892       if (info->stabs == NULL || info->strs == NULL)
893         return false;
894
895       if (! bfd_get_section_contents (abfd, info->stabsec, info->stabs, 0,
896                                       stabsize)
897           || ! bfd_get_section_contents (abfd, info->strsec, info->strs, 0,
898                                          strsize))
899         return false;
900
901       /* If this is a relocateable object file, we have to relocate
902          the entries in .stab.  This should always be simple 32 bit
903          relocations against symbols defined in this object file, so
904          this should be no big deal.  */
905       reloc_size = bfd_get_reloc_upper_bound (abfd, info->stabsec);
906       if (reloc_size < 0)
907         return false;
908       reloc_vector = (arelent **) bfd_malloc (reloc_size);
909       if (reloc_vector == NULL && reloc_size != 0)
910         return false;
911       reloc_count = bfd_canonicalize_reloc (abfd, info->stabsec, reloc_vector,
912                                             symbols);
913       if (reloc_count < 0)
914         {
915           if (reloc_vector != NULL)
916             free (reloc_vector);
917           return false;
918         }
919       if (reloc_count > 0)
920         {
921           arelent **pr;
922
923           for (pr = reloc_vector; *pr != NULL; pr++)
924             {
925               arelent *r;
926               unsigned long val;
927               asymbol *sym;
928
929               r = *pr;
930               if (r->howto->rightshift != 0
931                   || r->howto->size != 2
932                   || r->howto->bitsize != 32
933                   || r->howto->pc_relative
934                   || r->howto->bitpos != 0
935                   || r->howto->dst_mask != 0xffffffff)
936                 {
937                   (*_bfd_error_handler)
938                     (_("Unsupported .stab relocation"));
939                   bfd_set_error (bfd_error_invalid_operation);
940                   if (reloc_vector != NULL)
941                     free (reloc_vector);
942                   return false;
943                 }
944
945               val = bfd_get_32 (abfd, info->stabs + r->address);
946               val &= r->howto->src_mask;
947               sym = *r->sym_ptr_ptr;
948               val += sym->value + sym->section->vma + r->addend;
949               bfd_put_32 (abfd, val, info->stabs + r->address);
950             }
951         }
952
953       if (reloc_vector != NULL)
954         free (reloc_vector);
955
956       /* First time through this function, build a table matching
957          function VM addresses to stabs, then sort based on starting
958          VM address.  Do this in two passes: once to count how many
959          table entries we'll need, and a second to actually build the
960          table.  */
961
962       info->indextablesize = 0;
963       saw_fun = 1;
964       for (stab = info->stabs; stab < info->stabs + stabsize; stab += STABSIZE)
965         {
966           if (stab[TYPEOFF] == N_SO)
967             {
968               /* N_SO with null name indicates EOF */
969               if (bfd_get_32 (abfd, stab + STRDXOFF) == 0)
970                 continue;
971
972               /* if we did not see a function def, leave space for one. */
973               if (saw_fun == 0)
974                 ++info->indextablesize;
975
976               saw_fun = 0;
977
978               /* two N_SO's in a row is a filename and directory. Skip */
979               if (stab + STABSIZE < info->stabs + stabsize
980                   && *(stab + STABSIZE + TYPEOFF) == N_SO)
981                 {
982                   stab += STABSIZE;
983                 }
984             }
985           else if (stab[TYPEOFF] == N_FUN)
986             {
987               saw_fun = 1;
988               ++info->indextablesize;
989             }
990         }
991
992       if (saw_fun == 0)
993         ++info->indextablesize;
994       
995       if (info->indextablesize == 0)
996         return true;
997       ++info->indextablesize;
998
999       info->indextable = ((struct indexentry *)
1000                           bfd_alloc (abfd,
1001                                      (sizeof (struct indexentry)
1002                                       * info->indextablesize)));
1003       if (info->indextable == NULL)
1004         return false;
1005
1006       file_name = NULL;
1007       directory_name = NULL;
1008       saw_fun = 1;
1009
1010       for (i = 0, stroff = 0, stab = info->stabs, str = info->strs;
1011            i < info->indextablesize && stab < info->stabs + stabsize;
1012            stab += STABSIZE)
1013         {
1014           switch (stab[TYPEOFF])
1015             {
1016             case 0:
1017               /* This is the first entry in a compilation unit.  */
1018               if ((bfd_size_type) ((info->strs + strsize) - str) < stroff)
1019                 break;
1020               str += stroff;
1021               stroff = bfd_get_32 (abfd, stab + VALOFF);
1022               break;
1023
1024             case N_SO:
1025               /* The main file name.  */
1026
1027               /* The following code creates a new indextable entry with
1028                  a NULL function name if there were no N_FUNs in a file.
1029                  Note that a N_SO without a file name is an EOF and
1030                  there could be 2 N_SO following it with the new filename 
1031                  and directory. */
1032               if (saw_fun == 0)
1033                 {
1034                   info->indextable[i].val = bfd_get_32 (abfd, last_stab + VALOFF);
1035                   info->indextable[i].stab = last_stab;
1036                   info->indextable[i].str = str;
1037                   info->indextable[i].directory_name = directory_name;
1038                   info->indextable[i].file_name = file_name;
1039                   info->indextable[i].function_name = NULL;
1040                   ++i;
1041                 }
1042               saw_fun = 0;
1043               
1044               file_name = (char *) str + bfd_get_32 (abfd, stab + STRDXOFF);
1045               if (*file_name == '\0')
1046                 {
1047                   directory_name = NULL;
1048                   file_name = NULL;
1049                   saw_fun = 1;
1050                 }
1051               else
1052                 {
1053                   last_stab = stab;
1054                   if (stab + STABSIZE >= info->stabs + stabsize
1055                       || *(stab + STABSIZE + TYPEOFF) != N_SO)
1056                     {
1057                       directory_name = NULL;
1058                     }
1059                   else
1060                     {
1061                       /* Two consecutive N_SOs are a directory and a
1062                          file name.  */
1063                       stab += STABSIZE;
1064                       directory_name = file_name;
1065                       file_name = ((char *) str
1066                                    + bfd_get_32 (abfd, stab + STRDXOFF));
1067                     }
1068                 }
1069               break;
1070
1071             case N_SOL:
1072               /* The name of an include file.  */
1073               file_name = (char *) str + bfd_get_32 (abfd, stab + STRDXOFF);
1074               break;
1075
1076             case N_FUN:
1077               /* A function name.  */
1078               saw_fun = 1;
1079               name = (char *) str + bfd_get_32 (abfd, stab + STRDXOFF);
1080
1081               if (*name == '\0')
1082                 name = NULL;
1083
1084               function_name = name;
1085
1086               if (name == NULL)
1087                 continue;
1088
1089               info->indextable[i].val = bfd_get_32 (abfd, stab + VALOFF);
1090               info->indextable[i].stab = stab;
1091               info->indextable[i].str = str;
1092               info->indextable[i].directory_name = directory_name;
1093               info->indextable[i].file_name = file_name;
1094               info->indextable[i].function_name = function_name;
1095               ++i;
1096               break;
1097             }
1098         }
1099
1100       if (saw_fun == 0)
1101         {
1102           info->indextable[i].val = bfd_get_32 (abfd, last_stab + VALOFF);
1103           info->indextable[i].stab = last_stab;
1104           info->indextable[i].str = str;
1105           info->indextable[i].directory_name = directory_name;
1106           info->indextable[i].file_name = file_name;
1107           info->indextable[i].function_name = NULL;
1108           ++i;
1109         }
1110
1111       info->indextable[i].val = (bfd_vma) -1;
1112       info->indextable[i].stab = info->stabs + stabsize;
1113       info->indextable[i].str = str;
1114       info->indextable[i].directory_name = NULL;
1115       info->indextable[i].file_name = NULL;
1116       info->indextable[i].function_name = NULL;
1117       ++i;
1118
1119       info->indextablesize = i;
1120       qsort (info->indextable, i, sizeof (struct indexentry), cmpindexentry);
1121
1122       *pinfo = (PTR) info;
1123     }
1124
1125   /* We are passed a section relative offset.  The offsets in the
1126      stabs information are absolute.  */
1127   offset += bfd_get_section_vma (abfd, section);
1128
1129 #ifdef ENABLE_CACHING
1130   if (info->cached_indexentry != NULL
1131       && offset >= info->cached_offset
1132       && offset < (info->cached_indexentry + 1)->val)
1133     {
1134       stab = info->cached_stab;
1135       indexentry = info->cached_indexentry;
1136       file_name = info->cached_file_name;
1137     }
1138   else
1139 #endif
1140     {
1141       /* Cache non-existant or invalid.  Do binary search on
1142          indextable.  */
1143
1144       long low, high;
1145       long mid = -1;
1146
1147       indexentry = NULL;
1148
1149       low = 0;
1150       high = info->indextablesize - 1;
1151       while (low != high)
1152         {
1153           mid = (high + low) / 2;
1154           if (offset >= info->indextable[mid].val
1155               && offset < info->indextable[mid + 1].val)
1156             {
1157               indexentry = &info->indextable[mid];
1158               break;
1159             }
1160
1161           if (info->indextable[mid].val > offset)
1162             high = mid;
1163           else
1164             low = mid + 1;
1165         }
1166
1167       if (indexentry == NULL)
1168         return true;
1169
1170       stab = indexentry->stab + STABSIZE;
1171       file_name = indexentry->file_name;
1172     }
1173
1174   directory_name = indexentry->directory_name;
1175   str = indexentry->str;
1176
1177   for (; stab < (indexentry+1)->stab; stab += STABSIZE)
1178     {
1179       boolean done;
1180       bfd_vma val;
1181
1182       done = false;
1183
1184       switch (stab[TYPEOFF])
1185         {
1186         case N_SOL:
1187           /* The name of an include file.  */
1188           val = bfd_get_32 (abfd, stab + VALOFF);
1189           if (val <= offset)
1190             {
1191               file_name = (char *) str + bfd_get_32 (abfd, stab + STRDXOFF);
1192               *pline = 0;
1193             }
1194           break;
1195
1196         case N_SLINE:
1197         case N_DSLINE:
1198         case N_BSLINE:
1199           /* A line number.  The value is relative to the start of the
1200              current function.  */
1201           val = indexentry->val + bfd_get_32 (abfd, stab + VALOFF);
1202           if (val <= offset)
1203             {
1204               *pline = bfd_get_16 (abfd, stab + DESCOFF);
1205
1206 #ifdef ENABLE_CACHING
1207               info->cached_stab = stab;
1208               info->cached_offset = val;
1209               info->cached_file_name = file_name;
1210               info->cached_indexentry = indexentry;
1211 #endif
1212             }
1213           if (val > offset)
1214             done = true;
1215           break;
1216
1217         case N_FUN:
1218         case N_SO:
1219           done = true;
1220           break;
1221         }
1222
1223       if (done)
1224         break;
1225     }
1226
1227   *pfound = true;
1228
1229   if (file_name[0] == '/' || directory_name == NULL)
1230     *pfilename = file_name;
1231   else
1232     {
1233       size_t dirlen;
1234
1235       dirlen = strlen (directory_name);
1236       if (info->filename == NULL
1237           || strncmp (info->filename, directory_name, dirlen) != 0
1238           || strcmp (info->filename + dirlen, file_name) != 0)
1239         {
1240           if (info->filename != NULL)
1241             free (info->filename);
1242           info->filename = (char *) bfd_malloc (dirlen +
1243                                                 strlen (file_name)
1244                                                 + 1);
1245           if (info->filename == NULL)
1246             return false;
1247           strcpy (info->filename, directory_name);
1248           strcpy (info->filename + dirlen, file_name);
1249         }
1250
1251       *pfilename = info->filename;
1252     }
1253
1254   if (indexentry->function_name != NULL)
1255     {
1256       char *s;
1257
1258       /* This will typically be something like main:F(0,1), so we want
1259          to clobber the colon.  It's OK to change the name, since the
1260          string is in our own local storage anyhow.  */
1261
1262       s = strchr (indexentry->function_name, ':');
1263       if (s != NULL)
1264         *s = '\0';
1265
1266       *pfnname = indexentry->function_name;
1267     }
1268
1269   return true;
1270 }