gdb
[platform/upstream/binutils.git] / gdb / elfread.c
1 /* Read ELF (Executable and Linking Format) object files for GDB.
2
3    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5    Free Software Foundation, Inc.
6
7    Written by Fred Fish at Cygnus Support.
8
9    This file is part of GDB.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
23
24 #include "defs.h"
25 #include "bfd.h"
26 #include "gdb_string.h"
27 #include "elf-bfd.h"
28 #include "elf/common.h"
29 #include "elf/internal.h"
30 #include "elf/mips.h"
31 #include "symtab.h"
32 #include "symfile.h"
33 #include "objfiles.h"
34 #include "buildsym.h"
35 #include "stabsread.h"
36 #include "gdb-stabs.h"
37 #include "complaints.h"
38 #include "demangle.h"
39 #include "psympriv.h"
40
41 extern void _initialize_elfread (void);
42
43 /* The struct elfinfo is available only during ELF symbol table and
44    psymtab reading.  It is destroyed at the completion of psymtab-reading.
45    It's local to elf_symfile_read.  */
46
47 struct elfinfo
48   {
49     asection *stabsect;         /* Section pointer for .stab section */
50     asection *stabindexsect;    /* Section pointer for .stab.index section */
51     asection *mdebugsect;       /* Section pointer for .mdebug section */
52   };
53
54 static void free_elfinfo (void *);
55
56 /* Locate the segments in ABFD.  */
57
58 static struct symfile_segment_data *
59 elf_symfile_segments (bfd *abfd)
60 {
61   Elf_Internal_Phdr *phdrs, **segments;
62   long phdrs_size;
63   int num_phdrs, num_segments, num_sections, i;
64   asection *sect;
65   struct symfile_segment_data *data;
66
67   phdrs_size = bfd_get_elf_phdr_upper_bound (abfd);
68   if (phdrs_size == -1)
69     return NULL;
70
71   phdrs = alloca (phdrs_size);
72   num_phdrs = bfd_get_elf_phdrs (abfd, phdrs);
73   if (num_phdrs == -1)
74     return NULL;
75
76   num_segments = 0;
77   segments = alloca (sizeof (Elf_Internal_Phdr *) * num_phdrs);
78   for (i = 0; i < num_phdrs; i++)
79     if (phdrs[i].p_type == PT_LOAD)
80       segments[num_segments++] = &phdrs[i];
81
82   if (num_segments == 0)
83     return NULL;
84
85   data = XZALLOC (struct symfile_segment_data);
86   data->num_segments = num_segments;
87   data->segment_bases = XCALLOC (num_segments, CORE_ADDR);
88   data->segment_sizes = XCALLOC (num_segments, CORE_ADDR);
89
90   for (i = 0; i < num_segments; i++)
91     {
92       data->segment_bases[i] = segments[i]->p_vaddr;
93       data->segment_sizes[i] = segments[i]->p_memsz;
94     }
95
96   num_sections = bfd_count_sections (abfd);
97   data->segment_info = XCALLOC (num_sections, int);
98
99   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
100     {
101       int j;
102       CORE_ADDR vma;
103
104       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
105         continue;
106
107       vma = bfd_get_section_vma (abfd, sect);
108
109       for (j = 0; j < num_segments; j++)
110         if (segments[j]->p_memsz > 0
111             && vma >= segments[j]->p_vaddr
112             && (vma - segments[j]->p_vaddr) < segments[j]->p_memsz)
113           {
114             data->segment_info[i] = j + 1;
115             break;
116           }
117
118       /* We should have found a segment for every non-empty section.
119          If we haven't, we will not relocate this section by any
120          offsets we apply to the segments.  As an exception, do not
121          warn about SHT_NOBITS sections; in normal ELF execution
122          environments, SHT_NOBITS means zero-initialized and belongs
123          in a segment, but in no-OS environments some tools (e.g. ARM
124          RealView) use SHT_NOBITS for uninitialized data.  Since it is
125          uninitialized, it doesn't need a program header.  Such
126          binaries are not relocatable.  */
127       if (bfd_get_section_size (sect) > 0 && j == num_segments
128           && (bfd_get_section_flags (abfd, sect) & SEC_LOAD) != 0)
129         warning (_("Loadable segment \"%s\" outside of ELF segments"),
130                  bfd_section_name (abfd, sect));
131     }
132
133   return data;
134 }
135
136 /* We are called once per section from elf_symfile_read.  We
137    need to examine each section we are passed, check to see
138    if it is something we are interested in processing, and
139    if so, stash away some access information for the section.
140
141    For now we recognize the dwarf debug information sections and
142    line number sections from matching their section names.  The
143    ELF definition is no real help here since it has no direct
144    knowledge of DWARF (by design, so any debugging format can be
145    used).
146
147    We also recognize the ".stab" sections used by the Sun compilers
148    released with Solaris 2.
149
150    FIXME: The section names should not be hardwired strings (what
151    should they be?  I don't think most object file formats have enough
152    section flags to specify what kind of debug section it is
153    -kingdon).  */
154
155 static void
156 elf_locate_sections (bfd *ignore_abfd, asection *sectp, void *eip)
157 {
158   struct elfinfo *ei;
159
160   ei = (struct elfinfo *) eip;
161   if (strcmp (sectp->name, ".stab") == 0)
162     {
163       ei->stabsect = sectp;
164     }
165   else if (strcmp (sectp->name, ".stab.index") == 0)
166     {
167       ei->stabindexsect = sectp;
168     }
169   else if (strcmp (sectp->name, ".mdebug") == 0)
170     {
171       ei->mdebugsect = sectp;
172     }
173 }
174
175 static struct minimal_symbol *
176 record_minimal_symbol (const char *name, int name_len, int copy_name,
177                        CORE_ADDR address,
178                        enum minimal_symbol_type ms_type,
179                        asection *bfd_section, struct objfile *objfile)
180 {
181   struct gdbarch *gdbarch = get_objfile_arch (objfile);
182
183   if (ms_type == mst_text || ms_type == mst_file_text)
184     address = gdbarch_smash_text_address (gdbarch, address);
185
186   return prim_record_minimal_symbol_full (name, name_len, copy_name, address,
187                                           ms_type, bfd_section->index,
188                                           bfd_section, objfile);
189 }
190
191 /*
192
193    LOCAL FUNCTION
194
195    elf_symtab_read -- read the symbol table of an ELF file
196
197    SYNOPSIS
198
199    void elf_symtab_read (struct objfile *objfile, int type,
200                          long number_of_symbols, asymbol **symbol_table)
201
202    DESCRIPTION
203
204    Given an objfile, a symbol table, and a flag indicating whether the
205    symbol table contains regular, dynamic, or synthetic symbols, add all
206    the global function and data symbols to the minimal symbol table.
207
208    In stabs-in-ELF, as implemented by Sun, there are some local symbols
209    defined in the ELF symbol table, which can be used to locate
210    the beginnings of sections from each ".o" file that was linked to
211    form the executable objfile.  We gather any such info and record it
212    in data structures hung off the objfile's private data.
213
214  */
215
216 #define ST_REGULAR 0
217 #define ST_DYNAMIC 1
218 #define ST_SYNTHETIC 2
219
220 static void
221 elf_symtab_read (struct objfile *objfile, int type,
222                  long number_of_symbols, asymbol **symbol_table,
223                  int copy_names)
224 {
225   struct gdbarch *gdbarch = get_objfile_arch (objfile);
226   long storage_needed;
227   asymbol *sym;
228   long i;
229   CORE_ADDR symaddr;
230   CORE_ADDR offset;
231   enum minimal_symbol_type ms_type;
232   /* If sectinfo is nonNULL, it contains section info that should end up
233      filed in the objfile.  */
234   struct stab_section_info *sectinfo = NULL;
235   /* If filesym is nonzero, it points to a file symbol, but we haven't
236      seen any section info for it yet.  */
237   asymbol *filesym = 0;
238   /* Name of filesym.  This is either a constant string or is saved on
239      the objfile's obstack.  */
240   char *filesymname = "";
241   struct dbx_symfile_info *dbx = objfile->deprecated_sym_stab_info;
242   int stripped = (bfd_get_symcount (objfile->obfd) == 0);
243
244   for (i = 0; i < number_of_symbols; i++)
245     {
246       sym = symbol_table[i];
247       if (sym->name == NULL || *sym->name == '\0')
248         {
249           /* Skip names that don't exist (shouldn't happen), or names
250              that are null strings (may happen). */
251           continue;
252         }
253
254       /* Skip "special" symbols, e.g. ARM mapping symbols.  These are
255          symbols which do not correspond to objects in the symbol table,
256          but have some other target-specific meaning.  */
257       if (bfd_is_target_special_symbol (objfile->obfd, sym))
258         {
259           if (gdbarch_record_special_symbol_p (gdbarch))
260             gdbarch_record_special_symbol (gdbarch, objfile, sym);
261           continue;
262         }
263
264       offset = ANOFFSET (objfile->section_offsets, sym->section->index);
265       if (type == ST_DYNAMIC
266           && sym->section == &bfd_und_section
267           && (sym->flags & BSF_FUNCTION))
268         {
269           struct minimal_symbol *msym;
270           bfd *abfd = objfile->obfd;
271           asection *sect; 
272
273           /* Symbol is a reference to a function defined in
274              a shared library.
275              If its value is non zero then it is usually the address
276              of the corresponding entry in the procedure linkage table,
277              plus the desired section offset.
278              If its value is zero then the dynamic linker has to resolve
279              the symbol. We are unable to find any meaningful address
280              for this symbol in the executable file, so we skip it.  */
281           symaddr = sym->value;
282           if (symaddr == 0)
283             continue;
284
285           /* sym->section is the undefined section.  However, we want to
286              record the section where the PLT stub resides with the
287              minimal symbol.  Search the section table for the one that
288              covers the stub's address.  */
289           for (sect = abfd->sections; sect != NULL; sect = sect->next)
290             {
291               if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
292                 continue;
293
294               if (symaddr >= bfd_get_section_vma (abfd, sect)
295                   && symaddr < bfd_get_section_vma (abfd, sect)
296                                + bfd_get_section_size (sect))
297                 break;
298             }
299           if (!sect)
300             continue;
301
302           symaddr += ANOFFSET (objfile->section_offsets, sect->index);
303
304           msym = record_minimal_symbol
305             (sym->name, strlen (sym->name), copy_names,
306              symaddr, mst_solib_trampoline, sect, objfile);
307           if (msym != NULL)
308             msym->filename = filesymname;
309           continue;
310         }
311
312       /* If it is a nonstripped executable, do not enter dynamic
313          symbols, as the dynamic symbol table is usually a subset
314          of the main symbol table.  */
315       if (type == ST_DYNAMIC && !stripped)
316         continue;
317       if (sym->flags & BSF_FILE)
318         {
319           /* STT_FILE debugging symbol that helps stabs-in-elf debugging.
320              Chain any old one onto the objfile; remember new sym.  */
321           if (sectinfo != NULL)
322             {
323               sectinfo->next = dbx->stab_section_info;
324               dbx->stab_section_info = sectinfo;
325               sectinfo = NULL;
326             }
327           filesym = sym;
328           filesymname =
329             obsavestring ((char *) filesym->name, strlen (filesym->name),
330                           &objfile->objfile_obstack);
331         }
332       else if (sym->flags & BSF_SECTION_SYM)
333         continue;
334       else if (sym->flags & (BSF_GLOBAL | BSF_LOCAL | BSF_WEAK))
335         {
336           struct minimal_symbol *msym;
337
338           /* Select global/local/weak symbols.  Note that bfd puts abs
339              symbols in their own section, so all symbols we are
340              interested in will have a section. */
341           /* Bfd symbols are section relative. */
342           symaddr = sym->value + sym->section->vma;
343           /* Relocate all non-absolute and non-TLS symbols by the
344              section offset.  */
345           if (sym->section != &bfd_abs_section
346               && !(sym->section->flags & SEC_THREAD_LOCAL))
347             {
348               symaddr += offset;
349             }
350           /* For non-absolute symbols, use the type of the section
351              they are relative to, to intuit text/data.  Bfd provides
352              no way of figuring this out for absolute symbols. */
353           if (sym->section == &bfd_abs_section)
354             {
355               /* This is a hack to get the minimal symbol type
356                  right for Irix 5, which has absolute addresses
357                  with special section indices for dynamic symbols.
358
359                  NOTE: uweigand-20071112: Synthetic symbols do not
360                  have an ELF-private part, so do not touch those.  */
361               unsigned int shndx = type == ST_SYNTHETIC ? 0 : 
362                 ((elf_symbol_type *) sym)->internal_elf_sym.st_shndx;
363
364               switch (shndx)
365                 {
366                 case SHN_MIPS_TEXT:
367                   ms_type = mst_text;
368                   break;
369                 case SHN_MIPS_DATA:
370                   ms_type = mst_data;
371                   break;
372                 case SHN_MIPS_ACOMMON:
373                   ms_type = mst_bss;
374                   break;
375                 default:
376                   ms_type = mst_abs;
377                 }
378
379               /* If it is an Irix dynamic symbol, skip section name
380                  symbols, relocate all others by section offset. */
381               if (ms_type != mst_abs)
382                 {
383                   if (sym->name[0] == '.')
384                     continue;
385                   symaddr += offset;
386                 }
387             }
388           else if (sym->section->flags & SEC_CODE)
389             {
390               if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
391                 {
392                   ms_type = mst_text;
393                 }
394               else if ((sym->name[0] == '.' && sym->name[1] == 'L')
395                        || ((sym->flags & BSF_LOCAL)
396                            && sym->name[0] == '$'
397                            && sym->name[1] == 'L'))
398                 /* Looks like a compiler-generated label.  Skip
399                    it.  The assembler should be skipping these (to
400                    keep executables small), but apparently with
401                    gcc on the (deleted) delta m88k SVR4, it loses.
402                    So to have us check too should be harmless (but
403                    I encourage people to fix this in the assembler
404                    instead of adding checks here).  */
405                 continue;
406               else
407                 {
408                   ms_type = mst_file_text;
409                 }
410             }
411           else if (sym->section->flags & SEC_ALLOC)
412             {
413               if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
414                 {
415                   if (sym->section->flags & SEC_LOAD)
416                     {
417                       ms_type = mst_data;
418                     }
419                   else
420                     {
421                       ms_type = mst_bss;
422                     }
423                 }
424               else if (sym->flags & BSF_LOCAL)
425                 {
426                   /* Named Local variable in a Data section.
427                      Check its name for stabs-in-elf.  */
428                   int special_local_sect;
429                   if (strcmp ("Bbss.bss", sym->name) == 0)
430                     special_local_sect = SECT_OFF_BSS (objfile);
431                   else if (strcmp ("Ddata.data", sym->name) == 0)
432                     special_local_sect = SECT_OFF_DATA (objfile);
433                   else if (strcmp ("Drodata.rodata", sym->name) == 0)
434                     special_local_sect = SECT_OFF_RODATA (objfile);
435                   else
436                     special_local_sect = -1;
437                   if (special_local_sect >= 0)
438                     {
439                       /* Found a special local symbol.  Allocate a
440                          sectinfo, if needed, and fill it in.  */
441                       if (sectinfo == NULL)
442                         {
443                           int max_index;
444                           size_t size;
445
446                           max_index = SECT_OFF_BSS (objfile);
447                           if (objfile->sect_index_data > max_index)
448                             max_index = objfile->sect_index_data;
449                           if (objfile->sect_index_rodata > max_index)
450                             max_index = objfile->sect_index_rodata;
451
452                           /* max_index is the largest index we'll
453                              use into this array, so we must
454                              allocate max_index+1 elements for it.
455                              However, 'struct stab_section_info'
456                              already includes one element, so we
457                              need to allocate max_index aadditional
458                              elements.  */
459                           size = (sizeof (struct stab_section_info) 
460                                   + (sizeof (CORE_ADDR)
461                                      * max_index));
462                           sectinfo = (struct stab_section_info *)
463                             xmalloc (size);
464                           memset (sectinfo, 0, size);
465                           sectinfo->num_sections = max_index;
466                           if (filesym == NULL)
467                             {
468                               complaint (&symfile_complaints,
469                                          _("elf/stab section information %s without a preceding file symbol"),
470                                          sym->name);
471                             }
472                           else
473                             {
474                               sectinfo->filename =
475                                 (char *) filesym->name;
476                             }
477                         }
478                       if (sectinfo->sections[special_local_sect] != 0)
479                         complaint (&symfile_complaints,
480                                    _("duplicated elf/stab section information for %s"),
481                                    sectinfo->filename);
482                       /* BFD symbols are section relative.  */
483                       symaddr = sym->value + sym->section->vma;
484                       /* Relocate non-absolute symbols by the
485                          section offset.  */
486                       if (sym->section != &bfd_abs_section)
487                         symaddr += offset;
488                       sectinfo->sections[special_local_sect] = symaddr;
489                       /* The special local symbols don't go in the
490                          minimal symbol table, so ignore this one.  */
491                       continue;
492                     }
493                   /* Not a special stabs-in-elf symbol, do regular
494                      symbol processing.  */
495                   if (sym->section->flags & SEC_LOAD)
496                     {
497                       ms_type = mst_file_data;
498                     }
499                   else
500                     {
501                       ms_type = mst_file_bss;
502                     }
503                 }
504               else
505                 {
506                   ms_type = mst_unknown;
507                 }
508             }
509           else
510             {
511               /* FIXME:  Solaris2 shared libraries include lots of
512                  odd "absolute" and "undefined" symbols, that play 
513                  hob with actions like finding what function the PC
514                  is in.  Ignore them if they aren't text, data, or bss.  */
515               /* ms_type = mst_unknown; */
516               continue; /* Skip this symbol. */
517             }
518           msym = record_minimal_symbol
519             (sym->name, strlen (sym->name), copy_names, symaddr,
520              ms_type, sym->section, objfile);
521
522           if (msym)
523             {
524               /* Pass symbol size field in via BFD.  FIXME!!!  */
525               elf_symbol_type *elf_sym;
526
527               /* NOTE: uweigand-20071112: A synthetic symbol does not have an
528                  ELF-private part.  However, in some cases (e.g. synthetic
529                  'dot' symbols on ppc64) the udata.p entry is set to point back
530                  to the original ELF symbol it was derived from.  Get the size
531                  from that symbol.  */ 
532               if (type != ST_SYNTHETIC)
533                 elf_sym = (elf_symbol_type *) sym;
534               else
535                 elf_sym = (elf_symbol_type *) sym->udata.p;
536
537               if (elf_sym)
538                 MSYMBOL_SIZE(msym) = elf_sym->internal_elf_sym.st_size;
539           
540               msym->filename = filesymname;
541               gdbarch_elf_make_msymbol_special (gdbarch, sym, msym);
542             }
543
544           /* For @plt symbols, also record a trampoline to the
545              destination symbol.  The @plt symbol will be used in
546              disassembly, and the trampoline will be used when we are
547              trying to find the target.  */
548           if (msym && ms_type == mst_text && type == ST_SYNTHETIC)
549             {
550               int len = strlen (sym->name);
551
552               if (len > 4 && strcmp (sym->name + len - 4, "@plt") == 0)
553                 {
554                   struct minimal_symbol *mtramp;
555
556                   mtramp = record_minimal_symbol (sym->name, len - 4, 1,
557                                                   symaddr,
558                                                   mst_solib_trampoline,
559                                                   sym->section, objfile);
560                   if (mtramp)
561                     {
562                       MSYMBOL_SIZE (mtramp) = MSYMBOL_SIZE (msym);
563                       mtramp->filename = filesymname;
564                       gdbarch_elf_make_msymbol_special (gdbarch, sym, mtramp);
565                     }
566                 }
567             }
568         }
569     }
570 }
571
572 struct build_id
573   {
574     size_t size;
575     gdb_byte data[1];
576   };
577
578 /* Locate NT_GNU_BUILD_ID from ABFD and return its content.  */
579
580 static struct build_id *
581 build_id_bfd_get (bfd *abfd)
582 {
583   struct build_id *retval;
584
585   if (!bfd_check_format (abfd, bfd_object)
586       || bfd_get_flavour (abfd) != bfd_target_elf_flavour
587       || elf_tdata (abfd)->build_id == NULL)
588     return NULL;
589
590   retval = xmalloc (sizeof *retval - 1 + elf_tdata (abfd)->build_id_size);
591   retval->size = elf_tdata (abfd)->build_id_size;
592   memcpy (retval->data, elf_tdata (abfd)->build_id, retval->size);
593
594   return retval;
595 }
596
597 /* Return if FILENAME has NT_GNU_BUILD_ID matching the CHECK value.  */
598
599 static int
600 build_id_verify (const char *filename, struct build_id *check)
601 {
602   bfd *abfd;
603   struct build_id *found = NULL;
604   int retval = 0;
605
606   /* We expect to be silent on the non-existing files.  */
607   abfd = bfd_open_maybe_remote (filename);
608   if (abfd == NULL)
609     return 0;
610
611   found = build_id_bfd_get (abfd);
612
613   if (found == NULL)
614     warning (_("File \"%s\" has no build-id, file skipped"), filename);
615   else if (found->size != check->size
616            || memcmp (found->data, check->data, found->size) != 0)
617     warning (_("File \"%s\" has a different build-id, file skipped"), filename);
618   else
619     retval = 1;
620
621   if (!bfd_close (abfd))
622     warning (_("cannot close \"%s\": %s"), filename,
623              bfd_errmsg (bfd_get_error ()));
624
625   xfree (found);
626
627   return retval;
628 }
629
630 static char *
631 build_id_to_debug_filename (struct build_id *build_id)
632 {
633   char *link, *debugdir, *retval = NULL;
634
635   /* DEBUG_FILE_DIRECTORY/.build-id/ab/cdef */
636   link = alloca (strlen (debug_file_directory) + (sizeof "/.build-id/" - 1) + 1
637                  + 2 * build_id->size + (sizeof ".debug" - 1) + 1);
638
639   /* Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will
640      cause "/.build-id/..." lookups.  */
641
642   debugdir = debug_file_directory;
643   do
644     {
645       char *s, *debugdir_end;
646       gdb_byte *data = build_id->data;
647       size_t size = build_id->size;
648
649       while (*debugdir == DIRNAME_SEPARATOR)
650         debugdir++;
651
652       debugdir_end = strchr (debugdir, DIRNAME_SEPARATOR);
653       if (debugdir_end == NULL)
654         debugdir_end = &debugdir[strlen (debugdir)];
655
656       memcpy (link, debugdir, debugdir_end - debugdir);
657       s = &link[debugdir_end - debugdir];
658       s += sprintf (s, "/.build-id/");
659       if (size > 0)
660         {
661           size--;
662           s += sprintf (s, "%02x", (unsigned) *data++);
663         }
664       if (size > 0)
665         *s++ = '/';
666       while (size-- > 0)
667         s += sprintf (s, "%02x", (unsigned) *data++);
668       strcpy (s, ".debug");
669
670       /* lrealpath() is expensive even for the usually non-existent files.  */
671       if (access (link, F_OK) == 0)
672         retval = lrealpath (link);
673
674       if (retval != NULL && !build_id_verify (retval, build_id))
675         {
676           xfree (retval);
677           retval = NULL;
678         }
679
680       if (retval != NULL)
681         break;
682
683       debugdir = debugdir_end;
684     }
685   while (*debugdir != 0);
686
687   return retval;
688 }
689
690 static char *
691 find_separate_debug_file_by_buildid (struct objfile *objfile)
692 {
693   asection *sect;
694   char *basename, *name_copy, *debugdir;
695   char *dir = NULL;
696   char *debugfile = NULL;
697   char *canon_name = NULL;
698   bfd_size_type debuglink_size;
699   unsigned long crc32;
700   int i;
701   struct build_id *build_id;
702
703   build_id = build_id_bfd_get (objfile->obfd);
704   if (build_id != NULL)
705     {
706       char *build_id_name;
707
708       build_id_name = build_id_to_debug_filename (build_id);
709       xfree (build_id);
710       /* Prevent looping on a stripped .debug file.  */
711       if (build_id_name != NULL && strcmp (build_id_name, objfile->name) == 0)
712         {
713           warning (_("\"%s\": separate debug info file has no debug info"),
714                    build_id_name);
715           xfree (build_id_name);
716         }
717       else if (build_id_name != NULL)
718         return build_id_name;
719     }
720   return NULL;
721 }
722
723 /* Scan and build partial symbols for a symbol file.
724    We have been initialized by a call to elf_symfile_init, which 
725    currently does nothing.
726
727    SECTION_OFFSETS is a set of offsets to apply to relocate the symbols
728    in each section.  We simplify it down to a single offset for all
729    symbols.  FIXME.
730
731    This function only does the minimum work necessary for letting the
732    user "name" things symbolically; it does not read the entire symtab.
733    Instead, it reads the external and static symbols and puts them in partial
734    symbol tables.  When more extensive information is requested of a
735    file, the corresponding partial symbol table is mutated into a full
736    fledged symbol table by going back and reading the symbols
737    for real.
738
739    We look for sections with specific names, to tell us what debug
740    format to look for:  FIXME!!!
741
742    elfstab_build_psymtabs() handles STABS symbols;
743    mdebug_build_psymtabs() handles ECOFF debugging information.
744
745    Note that ELF files have a "minimal" symbol table, which looks a lot
746    like a COFF symbol table, but has only the minimal information necessary
747    for linking.  We process this also, and use the information to
748    build gdb's minimal symbol table.  This gives us some minimal debugging
749    capability even for files compiled without -g.  */
750
751 static void
752 elf_symfile_read (struct objfile *objfile, int symfile_flags)
753 {
754   bfd *abfd = objfile->obfd;
755   struct elfinfo ei;
756   struct cleanup *back_to;
757   CORE_ADDR offset;
758   long symcount = 0, dynsymcount = 0, synthcount, storage_needed;
759   asymbol **symbol_table = NULL, **dyn_symbol_table = NULL;
760   asymbol *synthsyms;
761
762   init_minimal_symbol_collection ();
763   back_to = make_cleanup_discard_minimal_symbols ();
764
765   memset ((char *) &ei, 0, sizeof (ei));
766
767   /* Allocate struct to keep track of the symfile */
768   objfile->deprecated_sym_stab_info = (struct dbx_symfile_info *)
769     xmalloc (sizeof (struct dbx_symfile_info));
770   memset ((char *) objfile->deprecated_sym_stab_info, 0, sizeof (struct dbx_symfile_info));
771   make_cleanup (free_elfinfo, (void *) objfile);
772
773   /* Process the normal ELF symbol table first.  This may write some 
774      chain of info into the dbx_symfile_info in objfile->deprecated_sym_stab_info,
775      which can later be used by elfstab_offset_sections.  */
776
777   storage_needed = bfd_get_symtab_upper_bound (objfile->obfd);
778   if (storage_needed < 0)
779     error (_("Can't read symbols from %s: %s"), bfd_get_filename (objfile->obfd),
780            bfd_errmsg (bfd_get_error ()));
781
782   if (storage_needed > 0)
783     {
784       symbol_table = (asymbol **) xmalloc (storage_needed);
785       make_cleanup (xfree, symbol_table);
786       symcount = bfd_canonicalize_symtab (objfile->obfd, symbol_table);
787
788       if (symcount < 0)
789         error (_("Can't read symbols from %s: %s"), bfd_get_filename (objfile->obfd),
790                bfd_errmsg (bfd_get_error ()));
791
792       elf_symtab_read (objfile, ST_REGULAR, symcount, symbol_table, 0);
793     }
794
795   /* Add the dynamic symbols.  */
796
797   storage_needed = bfd_get_dynamic_symtab_upper_bound (objfile->obfd);
798
799   if (storage_needed > 0)
800     {
801       dyn_symbol_table = (asymbol **) xmalloc (storage_needed);
802       make_cleanup (xfree, dyn_symbol_table);
803       dynsymcount = bfd_canonicalize_dynamic_symtab (objfile->obfd,
804                                                      dyn_symbol_table);
805
806       if (dynsymcount < 0)
807         error (_("Can't read symbols from %s: %s"), bfd_get_filename (objfile->obfd),
808                bfd_errmsg (bfd_get_error ()));
809
810       elf_symtab_read (objfile, ST_DYNAMIC, dynsymcount, dyn_symbol_table, 0);
811     }
812
813   /* Add synthetic symbols - for instance, names for any PLT entries.  */
814
815   synthcount = bfd_get_synthetic_symtab (abfd, symcount, symbol_table,
816                                          dynsymcount, dyn_symbol_table,
817                                          &synthsyms);
818   if (synthcount > 0)
819     {
820       asymbol **synth_symbol_table;
821       long i;
822
823       make_cleanup (xfree, synthsyms);
824       synth_symbol_table = xmalloc (sizeof (asymbol *) * synthcount);
825       for (i = 0; i < synthcount; i++)
826         synth_symbol_table[i] = synthsyms + i;
827       make_cleanup (xfree, synth_symbol_table);
828       elf_symtab_read (objfile, ST_SYNTHETIC, synthcount, synth_symbol_table, 1);
829     }
830
831   /* Install any minimal symbols that have been collected as the current
832      minimal symbols for this objfile.  The debug readers below this point
833      should not generate new minimal symbols; if they do it's their
834      responsibility to install them.  "mdebug" appears to be the only one
835      which will do this.  */
836
837   install_minimal_symbols (objfile);
838   do_cleanups (back_to);
839
840   /* Now process debugging information, which is contained in
841      special ELF sections. */
842
843   /* We first have to find them... */
844   bfd_map_over_sections (abfd, elf_locate_sections, (void *) & ei);
845
846   /* ELF debugging information is inserted into the psymtab in the
847      order of least informative first - most informative last.  Since
848      the psymtab table is searched `most recent insertion first' this
849      increases the probability that more detailed debug information
850      for a section is found.
851
852      For instance, an object file might contain both .mdebug (XCOFF)
853      and .debug_info (DWARF2) sections then .mdebug is inserted first
854      (searched last) and DWARF2 is inserted last (searched first).  If
855      we don't do this then the XCOFF info is found first - for code in
856      an included file XCOFF info is useless. */
857
858   if (ei.mdebugsect)
859     {
860       const struct ecoff_debug_swap *swap;
861
862       /* .mdebug section, presumably holding ECOFF debugging
863          information.  */
864       swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
865       if (swap)
866         elfmdebug_build_psymtabs (objfile, swap, ei.mdebugsect);
867     }
868   if (ei.stabsect)
869     {
870       asection *str_sect;
871
872       /* Stab sections have an associated string table that looks like
873          a separate section.  */
874       str_sect = bfd_get_section_by_name (abfd, ".stabstr");
875
876       /* FIXME should probably warn about a stab section without a stabstr.  */
877       if (str_sect)
878         elfstab_build_psymtabs (objfile,
879                                 ei.stabsect,
880                                 str_sect->filepos,
881                                 bfd_section_size (abfd, str_sect));
882     }
883   if (dwarf2_has_info (objfile))
884     {
885       /* DWARF 2 sections */
886       dwarf2_build_psymtabs (objfile);
887     }
888
889   /* FIXME: kettenis/20030504: This still needs to be integrated with
890      dwarf2read.c in a better way.  */
891   dwarf2_build_frame_info (objfile);
892
893   /* If the file has its own symbol tables it has no separate debug info.
894      `.dynsym'/`.symtab' go to MSYMBOLS, `.debug_info' goes to SYMTABS/PSYMTABS.
895      `.gnu_debuglink' may no longer be present with `.note.gnu.build-id'.  */
896   if (!objfile_has_partial_symbols (objfile))
897     {
898       char *debugfile;
899
900       debugfile = find_separate_debug_file_by_buildid (objfile);
901
902       if (debugfile == NULL)
903         debugfile = find_separate_debug_file_by_debuglink (objfile);
904
905       if (debugfile)
906         {
907           bfd *abfd = symfile_bfd_open (debugfile);
908           symbol_file_add_separate (abfd, symfile_flags, objfile);
909           xfree (debugfile);
910         }
911     }
912 }
913
914 /* This cleans up the objfile's deprecated_sym_stab_info pointer, and
915    the chain of stab_section_info's, that might be dangling from
916    it.  */
917
918 static void
919 free_elfinfo (void *objp)
920 {
921   struct objfile *objfile = (struct objfile *) objp;
922   struct dbx_symfile_info *dbxinfo = objfile->deprecated_sym_stab_info;
923   struct stab_section_info *ssi, *nssi;
924
925   ssi = dbxinfo->stab_section_info;
926   while (ssi)
927     {
928       nssi = ssi->next;
929       xfree (ssi);
930       ssi = nssi;
931     }
932
933   dbxinfo->stab_section_info = 0;       /* Just say No mo info about this.  */
934 }
935
936
937 /* Initialize anything that needs initializing when a completely new symbol
938    file is specified (not just adding some symbols from another file, e.g. a
939    shared library).
940
941    We reinitialize buildsym, since we may be reading stabs from an ELF file.  */
942
943 static void
944 elf_new_init (struct objfile *ignore)
945 {
946   stabsread_new_init ();
947   buildsym_new_init ();
948 }
949
950 /* Perform any local cleanups required when we are done with a particular
951    objfile.  I.E, we are in the process of discarding all symbol information
952    for an objfile, freeing up all memory held for it, and unlinking the
953    objfile struct from the global list of known objfiles. */
954
955 static void
956 elf_symfile_finish (struct objfile *objfile)
957 {
958   if (objfile->deprecated_sym_stab_info != NULL)
959     {
960       xfree (objfile->deprecated_sym_stab_info);
961     }
962
963   dwarf2_free_objfile (objfile);
964 }
965
966 /* ELF specific initialization routine for reading symbols.
967
968    It is passed a pointer to a struct sym_fns which contains, among other
969    things, the BFD for the file whose symbols are being read, and a slot for
970    a pointer to "private data" which we can fill with goodies.
971
972    For now at least, we have nothing in particular to do, so this function is
973    just a stub. */
974
975 static void
976 elf_symfile_init (struct objfile *objfile)
977 {
978   /* ELF objects may be reordered, so set OBJF_REORDERED.  If we
979      find this causes a significant slowdown in gdb then we could
980      set it in the debug symbol readers only when necessary.  */
981   objfile->flags |= OBJF_REORDERED;
982 }
983
984 /* When handling an ELF file that contains Sun STABS debug info,
985    some of the debug info is relative to the particular chunk of the
986    section that was generated in its individual .o file.  E.g.
987    offsets to static variables are relative to the start of the data
988    segment *for that module before linking*.  This information is
989    painfully squirreled away in the ELF symbol table as local symbols
990    with wierd names.  Go get 'em when needed.  */
991
992 void
993 elfstab_offset_sections (struct objfile *objfile, struct partial_symtab *pst)
994 {
995   char *filename = pst->filename;
996   struct dbx_symfile_info *dbx = objfile->deprecated_sym_stab_info;
997   struct stab_section_info *maybe = dbx->stab_section_info;
998   struct stab_section_info *questionable = 0;
999   int i;
1000   char *p;
1001
1002   /* The ELF symbol info doesn't include path names, so strip the path
1003      (if any) from the psymtab filename.  */
1004   while (0 != (p = strchr (filename, '/')))
1005     filename = p + 1;
1006
1007   /* FIXME:  This linear search could speed up significantly
1008      if it was chained in the right order to match how we search it,
1009      and if we unchained when we found a match. */
1010   for (; maybe; maybe = maybe->next)
1011     {
1012       if (filename[0] == maybe->filename[0]
1013           && strcmp (filename, maybe->filename) == 0)
1014         {
1015           /* We found a match.  But there might be several source files
1016              (from different directories) with the same name.  */
1017           if (0 == maybe->found)
1018             break;
1019           questionable = maybe; /* Might use it later.  */
1020         }
1021     }
1022
1023   if (maybe == 0 && questionable != 0)
1024     {
1025       complaint (&symfile_complaints,
1026                  _("elf/stab section information questionable for %s"), filename);
1027       maybe = questionable;
1028     }
1029
1030   if (maybe)
1031     {
1032       /* Found it!  Allocate a new psymtab struct, and fill it in.  */
1033       maybe->found++;
1034       pst->section_offsets = (struct section_offsets *)
1035         obstack_alloc (&objfile->objfile_obstack, 
1036                        SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
1037       for (i = 0; i < maybe->num_sections; i++)
1038         (pst->section_offsets)->offsets[i] = maybe->sections[i];
1039       return;
1040     }
1041
1042   /* We were unable to find any offsets for this file.  Complain.  */
1043   if (dbx->stab_section_info)   /* If there *is* any info, */
1044     complaint (&symfile_complaints,
1045                _("elf/stab section information missing for %s"), filename);
1046 }
1047 \f
1048 /* Register that we are able to handle ELF object file formats.  */
1049
1050 static struct sym_fns elf_sym_fns =
1051 {
1052   bfd_target_elf_flavour,
1053   elf_new_init,                 /* sym_new_init: init anything gbl to entire symtab */
1054   elf_symfile_init,             /* sym_init: read initial info, setup for sym_read() */
1055   elf_symfile_read,             /* sym_read: read a symbol file into symtab */
1056   elf_symfile_finish,           /* sym_finish: finished with file, cleanup */
1057   default_symfile_offsets,      /* sym_offsets:  Translate ext. to int. relocation */
1058   elf_symfile_segments,         /* sym_segments: Get segment information from
1059                                    a file.  */
1060   NULL,                         /* sym_read_linetable */
1061   default_symfile_relocate,     /* sym_relocate: Relocate a debug section.  */
1062   &psym_functions,
1063   NULL                          /* next: pointer to next struct sym_fns */
1064 };
1065
1066 void
1067 _initialize_elfread (void)
1068 {
1069   add_symtab_fns (&elf_sym_fns);
1070 }