2012-05-18 Sergio Durigan Junior <sergiodj@redhat.com>
[platform/upstream/binutils.git] / gdb / elfread.c
1 /* Read ELF (Executable and Linking Format) object files for GDB.
2
3    Copyright (C) 1991-2012 Free Software Foundation, Inc.
4
5    Written by Fred Fish at Cygnus Support.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "bfd.h"
24 #include "gdb_string.h"
25 #include "elf-bfd.h"
26 #include "elf/common.h"
27 #include "elf/internal.h"
28 #include "elf/mips.h"
29 #include "symtab.h"
30 #include "symfile.h"
31 #include "objfiles.h"
32 #include "buildsym.h"
33 #include "stabsread.h"
34 #include "gdb-stabs.h"
35 #include "complaints.h"
36 #include "demangle.h"
37 #include "psympriv.h"
38 #include "filenames.h"
39 #include "probe.h"
40 #include "arch-utils.h"
41 #include "gdbtypes.h"
42 #include "value.h"
43 #include "infcall.h"
44 #include "gdbthread.h"
45 #include "regcache.h"
46 #include "bcache.h"
47
48 extern void _initialize_elfread (void);
49
50 /* Forward declarations.  */
51 static const struct sym_fns elf_sym_fns_gdb_index;
52 static const struct sym_fns elf_sym_fns_lazy_psyms;
53
54 /* The struct elfinfo is available only during ELF symbol table and
55    psymtab reading.  It is destroyed at the completion of psymtab-reading.
56    It's local to elf_symfile_read.  */
57
58 struct elfinfo
59   {
60     asection *stabsect;         /* Section pointer for .stab section */
61     asection *stabindexsect;    /* Section pointer for .stab.index section */
62     asection *mdebugsect;       /* Section pointer for .mdebug section */
63   };
64
65 /* Per-objfile data for probe info.  */
66
67 static const struct objfile_data *probe_key = NULL;
68
69 static void free_elfinfo (void *);
70
71 /* Minimal symbols located at the GOT entries for .plt - that is the real
72    pointer where the given entry will jump to.  It gets updated by the real
73    function address during lazy ld.so resolving in the inferior.  These
74    minimal symbols are indexed for <tab>-completion.  */
75
76 #define SYMBOL_GOT_PLT_SUFFIX "@got.plt"
77
78 /* Locate the segments in ABFD.  */
79
80 static struct symfile_segment_data *
81 elf_symfile_segments (bfd *abfd)
82 {
83   Elf_Internal_Phdr *phdrs, **segments;
84   long phdrs_size;
85   int num_phdrs, num_segments, num_sections, i;
86   asection *sect;
87   struct symfile_segment_data *data;
88
89   phdrs_size = bfd_get_elf_phdr_upper_bound (abfd);
90   if (phdrs_size == -1)
91     return NULL;
92
93   phdrs = alloca (phdrs_size);
94   num_phdrs = bfd_get_elf_phdrs (abfd, phdrs);
95   if (num_phdrs == -1)
96     return NULL;
97
98   num_segments = 0;
99   segments = alloca (sizeof (Elf_Internal_Phdr *) * num_phdrs);
100   for (i = 0; i < num_phdrs; i++)
101     if (phdrs[i].p_type == PT_LOAD)
102       segments[num_segments++] = &phdrs[i];
103
104   if (num_segments == 0)
105     return NULL;
106
107   data = XZALLOC (struct symfile_segment_data);
108   data->num_segments = num_segments;
109   data->segment_bases = XCALLOC (num_segments, CORE_ADDR);
110   data->segment_sizes = XCALLOC (num_segments, CORE_ADDR);
111
112   for (i = 0; i < num_segments; i++)
113     {
114       data->segment_bases[i] = segments[i]->p_vaddr;
115       data->segment_sizes[i] = segments[i]->p_memsz;
116     }
117
118   num_sections = bfd_count_sections (abfd);
119   data->segment_info = XCALLOC (num_sections, int);
120
121   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
122     {
123       int j;
124       CORE_ADDR vma;
125
126       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
127         continue;
128
129       vma = bfd_get_section_vma (abfd, sect);
130
131       for (j = 0; j < num_segments; j++)
132         if (segments[j]->p_memsz > 0
133             && vma >= segments[j]->p_vaddr
134             && (vma - segments[j]->p_vaddr) < segments[j]->p_memsz)
135           {
136             data->segment_info[i] = j + 1;
137             break;
138           }
139
140       /* We should have found a segment for every non-empty section.
141          If we haven't, we will not relocate this section by any
142          offsets we apply to the segments.  As an exception, do not
143          warn about SHT_NOBITS sections; in normal ELF execution
144          environments, SHT_NOBITS means zero-initialized and belongs
145          in a segment, but in no-OS environments some tools (e.g. ARM
146          RealView) use SHT_NOBITS for uninitialized data.  Since it is
147          uninitialized, it doesn't need a program header.  Such
148          binaries are not relocatable.  */
149       if (bfd_get_section_size (sect) > 0 && j == num_segments
150           && (bfd_get_section_flags (abfd, sect) & SEC_LOAD) != 0)
151         warning (_("Loadable section \"%s\" outside of ELF segments"),
152                  bfd_section_name (abfd, sect));
153     }
154
155   return data;
156 }
157
158 /* We are called once per section from elf_symfile_read.  We
159    need to examine each section we are passed, check to see
160    if it is something we are interested in processing, and
161    if so, stash away some access information for the section.
162
163    For now we recognize the dwarf debug information sections and
164    line number sections from matching their section names.  The
165    ELF definition is no real help here since it has no direct
166    knowledge of DWARF (by design, so any debugging format can be
167    used).
168
169    We also recognize the ".stab" sections used by the Sun compilers
170    released with Solaris 2.
171
172    FIXME: The section names should not be hardwired strings (what
173    should they be?  I don't think most object file formats have enough
174    section flags to specify what kind of debug section it is.
175    -kingdon).  */
176
177 static void
178 elf_locate_sections (bfd *ignore_abfd, asection *sectp, void *eip)
179 {
180   struct elfinfo *ei;
181
182   ei = (struct elfinfo *) eip;
183   if (strcmp (sectp->name, ".stab") == 0)
184     {
185       ei->stabsect = sectp;
186     }
187   else if (strcmp (sectp->name, ".stab.index") == 0)
188     {
189       ei->stabindexsect = sectp;
190     }
191   else if (strcmp (sectp->name, ".mdebug") == 0)
192     {
193       ei->mdebugsect = sectp;
194     }
195 }
196
197 static struct minimal_symbol *
198 record_minimal_symbol (const char *name, int name_len, int copy_name,
199                        CORE_ADDR address,
200                        enum minimal_symbol_type ms_type,
201                        asection *bfd_section, struct objfile *objfile)
202 {
203   struct gdbarch *gdbarch = get_objfile_arch (objfile);
204
205   if (ms_type == mst_text || ms_type == mst_file_text
206       || ms_type == mst_text_gnu_ifunc)
207     address = gdbarch_smash_text_address (gdbarch, address);
208
209   return prim_record_minimal_symbol_full (name, name_len, copy_name, address,
210                                           ms_type, bfd_section->index,
211                                           bfd_section, objfile);
212 }
213
214 /* Read the symbol table of an ELF file.
215
216    Given an objfile, a symbol table, and a flag indicating whether the
217    symbol table contains regular, dynamic, or synthetic symbols, add all
218    the global function and data symbols to the minimal symbol table.
219
220    In stabs-in-ELF, as implemented by Sun, there are some local symbols
221    defined in the ELF symbol table, which can be used to locate
222    the beginnings of sections from each ".o" file that was linked to
223    form the executable objfile.  We gather any such info and record it
224    in data structures hung off the objfile's private data.  */
225
226 #define ST_REGULAR 0
227 #define ST_DYNAMIC 1
228 #define ST_SYNTHETIC 2
229
230 static void
231 elf_symtab_read (struct objfile *objfile, int type,
232                  long number_of_symbols, asymbol **symbol_table,
233                  int copy_names)
234 {
235   struct gdbarch *gdbarch = get_objfile_arch (objfile);
236   asymbol *sym;
237   long i;
238   CORE_ADDR symaddr;
239   CORE_ADDR offset;
240   enum minimal_symbol_type ms_type;
241   /* If sectinfo is nonNULL, it contains section info that should end up
242      filed in the objfile.  */
243   struct stab_section_info *sectinfo = NULL;
244   /* If filesym is nonzero, it points to a file symbol, but we haven't
245      seen any section info for it yet.  */
246   asymbol *filesym = 0;
247   /* Name of filesym.  This is either a constant string or is saved on
248      the objfile's filename cache.  */
249   const char *filesymname = "";
250   struct dbx_symfile_info *dbx = objfile->deprecated_sym_stab_info;
251   int stripped = (bfd_get_symcount (objfile->obfd) == 0);
252
253   for (i = 0; i < number_of_symbols; i++)
254     {
255       sym = symbol_table[i];
256       if (sym->name == NULL || *sym->name == '\0')
257         {
258           /* Skip names that don't exist (shouldn't happen), or names
259              that are null strings (may happen).  */
260           continue;
261         }
262
263       /* Skip "special" symbols, e.g. ARM mapping symbols.  These are
264          symbols which do not correspond to objects in the symbol table,
265          but have some other target-specific meaning.  */
266       if (bfd_is_target_special_symbol (objfile->obfd, sym))
267         {
268           if (gdbarch_record_special_symbol_p (gdbarch))
269             gdbarch_record_special_symbol (gdbarch, objfile, sym);
270           continue;
271         }
272
273       offset = ANOFFSET (objfile->section_offsets, sym->section->index);
274       if (type == ST_DYNAMIC
275           && sym->section == bfd_und_section_ptr
276           && (sym->flags & BSF_FUNCTION))
277         {
278           struct minimal_symbol *msym;
279           bfd *abfd = objfile->obfd;
280           asection *sect;
281
282           /* Symbol is a reference to a function defined in
283              a shared library.
284              If its value is non zero then it is usually the address
285              of the corresponding entry in the procedure linkage table,
286              plus the desired section offset.
287              If its value is zero then the dynamic linker has to resolve
288              the symbol.  We are unable to find any meaningful address
289              for this symbol in the executable file, so we skip it.  */
290           symaddr = sym->value;
291           if (symaddr == 0)
292             continue;
293
294           /* sym->section is the undefined section.  However, we want to
295              record the section where the PLT stub resides with the
296              minimal symbol.  Search the section table for the one that
297              covers the stub's address.  */
298           for (sect = abfd->sections; sect != NULL; sect = sect->next)
299             {
300               if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
301                 continue;
302
303               if (symaddr >= bfd_get_section_vma (abfd, sect)
304                   && symaddr < bfd_get_section_vma (abfd, sect)
305                                + bfd_get_section_size (sect))
306                 break;
307             }
308           if (!sect)
309             continue;
310
311           /* On ia64-hpux, we have discovered that the system linker
312              adds undefined symbols with nonzero addresses that cannot
313              be right (their address points inside the code of another
314              function in the .text section).  This creates problems
315              when trying to determine which symbol corresponds to
316              a given address.
317
318              We try to detect those buggy symbols by checking which
319              section we think they correspond to.  Normally, PLT symbols
320              are stored inside their own section, and the typical name
321              for that section is ".plt".  So, if there is a ".plt"
322              section, and yet the section name of our symbol does not
323              start with ".plt", we ignore that symbol.  */
324           if (strncmp (sect->name, ".plt", 4) != 0
325               && bfd_get_section_by_name (abfd, ".plt") != NULL)
326             continue;
327
328           symaddr += ANOFFSET (objfile->section_offsets, sect->index);
329
330           msym = record_minimal_symbol
331             (sym->name, strlen (sym->name), copy_names,
332              symaddr, mst_solib_trampoline, sect, objfile);
333           if (msym != NULL)
334             msym->filename = filesymname;
335           continue;
336         }
337
338       /* If it is a nonstripped executable, do not enter dynamic
339          symbols, as the dynamic symbol table is usually a subset
340          of the main symbol table.  */
341       if (type == ST_DYNAMIC && !stripped)
342         continue;
343       if (sym->flags & BSF_FILE)
344         {
345           /* STT_FILE debugging symbol that helps stabs-in-elf debugging.
346              Chain any old one onto the objfile; remember new sym.  */
347           if (sectinfo != NULL)
348             {
349               sectinfo->next = dbx->stab_section_info;
350               dbx->stab_section_info = sectinfo;
351               sectinfo = NULL;
352             }
353           filesym = sym;
354           filesymname = bcache (filesym->name, strlen (filesym->name) + 1,
355                                 objfile->filename_cache);
356         }
357       else if (sym->flags & BSF_SECTION_SYM)
358         continue;
359       else if (sym->flags & (BSF_GLOBAL | BSF_LOCAL | BSF_WEAK))
360         {
361           struct minimal_symbol *msym;
362
363           /* Select global/local/weak symbols.  Note that bfd puts abs
364              symbols in their own section, so all symbols we are
365              interested in will have a section.  */
366           /* Bfd symbols are section relative.  */
367           symaddr = sym->value + sym->section->vma;
368           /* Relocate all non-absolute and non-TLS symbols by the
369              section offset.  */
370           if (sym->section != bfd_abs_section_ptr
371               && !(sym->section->flags & SEC_THREAD_LOCAL))
372             {
373               symaddr += offset;
374             }
375           /* For non-absolute symbols, use the type of the section
376              they are relative to, to intuit text/data.  Bfd provides
377              no way of figuring this out for absolute symbols.  */
378           if (sym->section == bfd_abs_section_ptr)
379             {
380               /* This is a hack to get the minimal symbol type
381                  right for Irix 5, which has absolute addresses
382                  with special section indices for dynamic symbols.
383
384                  NOTE: uweigand-20071112: Synthetic symbols do not
385                  have an ELF-private part, so do not touch those.  */
386               unsigned int shndx = type == ST_SYNTHETIC ? 0 :
387                 ((elf_symbol_type *) sym)->internal_elf_sym.st_shndx;
388
389               switch (shndx)
390                 {
391                 case SHN_MIPS_TEXT:
392                   ms_type = mst_text;
393                   break;
394                 case SHN_MIPS_DATA:
395                   ms_type = mst_data;
396                   break;
397                 case SHN_MIPS_ACOMMON:
398                   ms_type = mst_bss;
399                   break;
400                 default:
401                   ms_type = mst_abs;
402                 }
403
404               /* If it is an Irix dynamic symbol, skip section name
405                  symbols, relocate all others by section offset.  */
406               if (ms_type != mst_abs)
407                 {
408                   if (sym->name[0] == '.')
409                     continue;
410                   symaddr += offset;
411                 }
412             }
413           else if (sym->section->flags & SEC_CODE)
414             {
415               if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
416                 {
417                   if (sym->flags & BSF_GNU_INDIRECT_FUNCTION)
418                     ms_type = mst_text_gnu_ifunc;
419                   else
420                     ms_type = mst_text;
421                 }
422               /* The BSF_SYNTHETIC check is there to omit ppc64 function
423                  descriptors mistaken for static functions starting with 'L'.
424                  */
425               else if ((sym->name[0] == '.' && sym->name[1] == 'L'
426                         && (sym->flags & BSF_SYNTHETIC) == 0)
427                        || ((sym->flags & BSF_LOCAL)
428                            && sym->name[0] == '$'
429                            && sym->name[1] == 'L'))
430                 /* Looks like a compiler-generated label.  Skip
431                    it.  The assembler should be skipping these (to
432                    keep executables small), but apparently with
433                    gcc on the (deleted) delta m88k SVR4, it loses.
434                    So to have us check too should be harmless (but
435                    I encourage people to fix this in the assembler
436                    instead of adding checks here).  */
437                 continue;
438               else
439                 {
440                   ms_type = mst_file_text;
441                 }
442             }
443           else if (sym->section->flags & SEC_ALLOC)
444             {
445               if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
446                 {
447                   if (sym->section->flags & SEC_LOAD)
448                     {
449                       ms_type = mst_data;
450                     }
451                   else
452                     {
453                       ms_type = mst_bss;
454                     }
455                 }
456               else if (sym->flags & BSF_LOCAL)
457                 {
458                   /* Named Local variable in a Data section.
459                      Check its name for stabs-in-elf.  */
460                   int special_local_sect;
461
462                   if (strcmp ("Bbss.bss", sym->name) == 0)
463                     special_local_sect = SECT_OFF_BSS (objfile);
464                   else if (strcmp ("Ddata.data", sym->name) == 0)
465                     special_local_sect = SECT_OFF_DATA (objfile);
466                   else if (strcmp ("Drodata.rodata", sym->name) == 0)
467                     special_local_sect = SECT_OFF_RODATA (objfile);
468                   else
469                     special_local_sect = -1;
470                   if (special_local_sect >= 0)
471                     {
472                       /* Found a special local symbol.  Allocate a
473                          sectinfo, if needed, and fill it in.  */
474                       if (sectinfo == NULL)
475                         {
476                           int max_index;
477                           size_t size;
478
479                           max_index = SECT_OFF_BSS (objfile);
480                           if (objfile->sect_index_data > max_index)
481                             max_index = objfile->sect_index_data;
482                           if (objfile->sect_index_rodata > max_index)
483                             max_index = objfile->sect_index_rodata;
484
485                           /* max_index is the largest index we'll
486                              use into this array, so we must
487                              allocate max_index+1 elements for it.
488                              However, 'struct stab_section_info'
489                              already includes one element, so we
490                              need to allocate max_index aadditional
491                              elements.  */
492                           size = (sizeof (struct stab_section_info)
493                                   + (sizeof (CORE_ADDR) * max_index));
494                           sectinfo = (struct stab_section_info *)
495                             xmalloc (size);
496                           memset (sectinfo, 0, size);
497                           sectinfo->num_sections = max_index;
498                           if (filesym == NULL)
499                             {
500                               complaint (&symfile_complaints,
501                                          _("elf/stab section information %s "
502                                            "without a preceding file symbol"),
503                                          sym->name);
504                             }
505                           else
506                             {
507                               sectinfo->filename =
508                                 (char *) filesym->name;
509                             }
510                         }
511                       if (sectinfo->sections[special_local_sect] != 0)
512                         complaint (&symfile_complaints,
513                                    _("duplicated elf/stab section "
514                                      "information for %s"),
515                                    sectinfo->filename);
516                       /* BFD symbols are section relative.  */
517                       symaddr = sym->value + sym->section->vma;
518                       /* Relocate non-absolute symbols by the
519                          section offset.  */
520                       if (sym->section != bfd_abs_section_ptr)
521                         symaddr += offset;
522                       sectinfo->sections[special_local_sect] = symaddr;
523                       /* The special local symbols don't go in the
524                          minimal symbol table, so ignore this one.  */
525                       continue;
526                     }
527                   /* Not a special stabs-in-elf symbol, do regular
528                      symbol processing.  */
529                   if (sym->section->flags & SEC_LOAD)
530                     {
531                       ms_type = mst_file_data;
532                     }
533                   else
534                     {
535                       ms_type = mst_file_bss;
536                     }
537                 }
538               else
539                 {
540                   ms_type = mst_unknown;
541                 }
542             }
543           else
544             {
545               /* FIXME:  Solaris2 shared libraries include lots of
546                  odd "absolute" and "undefined" symbols, that play
547                  hob with actions like finding what function the PC
548                  is in.  Ignore them if they aren't text, data, or bss.  */
549               /* ms_type = mst_unknown; */
550               continue; /* Skip this symbol.  */
551             }
552           msym = record_minimal_symbol
553             (sym->name, strlen (sym->name), copy_names, symaddr,
554              ms_type, sym->section, objfile);
555
556           if (msym)
557             {
558               /* Pass symbol size field in via BFD.  FIXME!!!  */
559               elf_symbol_type *elf_sym;
560
561               /* NOTE: uweigand-20071112: A synthetic symbol does not have an
562                  ELF-private part.  However, in some cases (e.g. synthetic
563                  'dot' symbols on ppc64) the udata.p entry is set to point back
564                  to the original ELF symbol it was derived from.  Get the size
565                  from that symbol.  */
566               if (type != ST_SYNTHETIC)
567                 elf_sym = (elf_symbol_type *) sym;
568               else
569                 elf_sym = (elf_symbol_type *) sym->udata.p;
570
571               if (elf_sym)
572                 MSYMBOL_SIZE(msym) = elf_sym->internal_elf_sym.st_size;
573
574               msym->filename = filesymname;
575               gdbarch_elf_make_msymbol_special (gdbarch, sym, msym);
576             }
577
578           /* For @plt symbols, also record a trampoline to the
579              destination symbol.  The @plt symbol will be used in
580              disassembly, and the trampoline will be used when we are
581              trying to find the target.  */
582           if (msym && ms_type == mst_text && type == ST_SYNTHETIC)
583             {
584               int len = strlen (sym->name);
585
586               if (len > 4 && strcmp (sym->name + len - 4, "@plt") == 0)
587                 {
588                   struct minimal_symbol *mtramp;
589
590                   mtramp = record_minimal_symbol (sym->name, len - 4, 1,
591                                                   symaddr,
592                                                   mst_solib_trampoline,
593                                                   sym->section, objfile);
594                   if (mtramp)
595                     {
596                       MSYMBOL_SIZE (mtramp) = MSYMBOL_SIZE (msym);
597                       mtramp->filename = filesymname;
598                       gdbarch_elf_make_msymbol_special (gdbarch, sym, mtramp);
599                     }
600                 }
601             }
602         }
603     }
604 }
605
606 /* Build minimal symbols named `function@got.plt' (see SYMBOL_GOT_PLT_SUFFIX)
607    for later look ups of which function to call when user requests
608    a STT_GNU_IFUNC function.  As the STT_GNU_IFUNC type is found at the target
609    library defining `function' we cannot yet know while reading OBJFILE which
610    of the SYMBOL_GOT_PLT_SUFFIX entries will be needed and later
611    DYN_SYMBOL_TABLE is no longer easily available for OBJFILE.  */
612
613 static void
614 elf_rel_plt_read (struct objfile *objfile, asymbol **dyn_symbol_table)
615 {
616   bfd *obfd = objfile->obfd;
617   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
618   asection *plt, *relplt, *got_plt;
619   int plt_elf_idx;
620   bfd_size_type reloc_count, reloc;
621   char *string_buffer = NULL;
622   size_t string_buffer_size = 0;
623   struct cleanup *back_to;
624   struct gdbarch *gdbarch = objfile->gdbarch;
625   struct type *ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
626   size_t ptr_size = TYPE_LENGTH (ptr_type);
627
628   if (objfile->separate_debug_objfile_backlink)
629     return;
630
631   plt = bfd_get_section_by_name (obfd, ".plt");
632   if (plt == NULL)
633     return;
634   plt_elf_idx = elf_section_data (plt)->this_idx;
635
636   got_plt = bfd_get_section_by_name (obfd, ".got.plt");
637   if (got_plt == NULL)
638     return;
639
640   /* This search algorithm is from _bfd_elf_canonicalize_dynamic_reloc.  */
641   for (relplt = obfd->sections; relplt != NULL; relplt = relplt->next)
642     if (elf_section_data (relplt)->this_hdr.sh_info == plt_elf_idx
643         && (elf_section_data (relplt)->this_hdr.sh_type == SHT_REL
644             || elf_section_data (relplt)->this_hdr.sh_type == SHT_RELA))
645       break;
646   if (relplt == NULL)
647     return;
648
649   if (! bed->s->slurp_reloc_table (obfd, relplt, dyn_symbol_table, TRUE))
650     return;
651
652   back_to = make_cleanup (free_current_contents, &string_buffer);
653
654   reloc_count = relplt->size / elf_section_data (relplt)->this_hdr.sh_entsize;
655   for (reloc = 0; reloc < reloc_count; reloc++)
656     {
657       const char *name;
658       struct minimal_symbol *msym;
659       CORE_ADDR address;
660       const size_t got_suffix_len = strlen (SYMBOL_GOT_PLT_SUFFIX);
661       size_t name_len;
662
663       name = bfd_asymbol_name (*relplt->relocation[reloc].sym_ptr_ptr);
664       name_len = strlen (name);
665       address = relplt->relocation[reloc].address;
666
667       /* Does the pointer reside in the .got.plt section?  */
668       if (!(bfd_get_section_vma (obfd, got_plt) <= address
669             && address < bfd_get_section_vma (obfd, got_plt)
670                          + bfd_get_section_size (got_plt)))
671         continue;
672
673       /* We cannot check if NAME is a reference to mst_text_gnu_ifunc as in
674          OBJFILE the symbol is undefined and the objfile having NAME defined
675          may not yet have been loaded.  */
676
677       if (string_buffer_size < name_len + got_suffix_len + 1)
678         {
679           string_buffer_size = 2 * (name_len + got_suffix_len);
680           string_buffer = xrealloc (string_buffer, string_buffer_size);
681         }
682       memcpy (string_buffer, name, name_len);
683       memcpy (&string_buffer[name_len], SYMBOL_GOT_PLT_SUFFIX,
684               got_suffix_len + 1);
685
686       msym = record_minimal_symbol (string_buffer, name_len + got_suffix_len,
687                                     1, address, mst_slot_got_plt, got_plt,
688                                     objfile);
689       if (msym)
690         MSYMBOL_SIZE (msym) = ptr_size;
691     }
692
693   do_cleanups (back_to);
694 }
695
696 /* The data pointer is htab_t for gnu_ifunc_record_cache_unchecked.  */
697
698 static const struct objfile_data *elf_objfile_gnu_ifunc_cache_data;
699
700 /* Map function names to CORE_ADDR in elf_objfile_gnu_ifunc_cache_data.  */
701
702 struct elf_gnu_ifunc_cache
703 {
704   /* This is always a function entry address, not a function descriptor.  */
705   CORE_ADDR addr;
706
707   char name[1];
708 };
709
710 /* htab_hash for elf_objfile_gnu_ifunc_cache_data.  */
711
712 static hashval_t
713 elf_gnu_ifunc_cache_hash (const void *a_voidp)
714 {
715   const struct elf_gnu_ifunc_cache *a = a_voidp;
716
717   return htab_hash_string (a->name);
718 }
719
720 /* htab_eq for elf_objfile_gnu_ifunc_cache_data.  */
721
722 static int
723 elf_gnu_ifunc_cache_eq (const void *a_voidp, const void *b_voidp)
724 {
725   const struct elf_gnu_ifunc_cache *a = a_voidp;
726   const struct elf_gnu_ifunc_cache *b = b_voidp;
727
728   return strcmp (a->name, b->name) == 0;
729 }
730
731 /* Record the target function address of a STT_GNU_IFUNC function NAME is the
732    function entry address ADDR.  Return 1 if NAME and ADDR are considered as
733    valid and therefore they were successfully recorded, return 0 otherwise.
734
735    Function does not expect a duplicate entry.  Use
736    elf_gnu_ifunc_resolve_by_cache first to check if the entry for NAME already
737    exists.  */
738
739 static int
740 elf_gnu_ifunc_record_cache (const char *name, CORE_ADDR addr)
741 {
742   struct minimal_symbol *msym;
743   asection *sect;
744   struct objfile *objfile;
745   htab_t htab;
746   struct elf_gnu_ifunc_cache entry_local, *entry_p;
747   void **slot;
748
749   msym = lookup_minimal_symbol_by_pc (addr);
750   if (msym == NULL)
751     return 0;
752   if (SYMBOL_VALUE_ADDRESS (msym) != addr)
753     return 0;
754   /* minimal symbols have always SYMBOL_OBJ_SECTION non-NULL.  */
755   sect = SYMBOL_OBJ_SECTION (msym)->the_bfd_section;
756   objfile = SYMBOL_OBJ_SECTION (msym)->objfile;
757
758   /* If .plt jumps back to .plt the symbol is still deferred for later
759      resolution and it has no use for GDB.  Besides ".text" this symbol can
760      reside also in ".opd" for ppc64 function descriptor.  */
761   if (strcmp (bfd_get_section_name (objfile->obfd, sect), ".plt") == 0)
762     return 0;
763
764   htab = objfile_data (objfile, elf_objfile_gnu_ifunc_cache_data);
765   if (htab == NULL)
766     {
767       htab = htab_create_alloc_ex (1, elf_gnu_ifunc_cache_hash,
768                                    elf_gnu_ifunc_cache_eq,
769                                    NULL, &objfile->objfile_obstack,
770                                    hashtab_obstack_allocate,
771                                    dummy_obstack_deallocate);
772       set_objfile_data (objfile, elf_objfile_gnu_ifunc_cache_data, htab);
773     }
774
775   entry_local.addr = addr;
776   obstack_grow (&objfile->objfile_obstack, &entry_local,
777                 offsetof (struct elf_gnu_ifunc_cache, name));
778   obstack_grow_str0 (&objfile->objfile_obstack, name);
779   entry_p = obstack_finish (&objfile->objfile_obstack);
780
781   slot = htab_find_slot (htab, entry_p, INSERT);
782   if (*slot != NULL)
783     {
784       struct elf_gnu_ifunc_cache *entry_found_p = *slot;
785       struct gdbarch *gdbarch = objfile->gdbarch;
786
787       if (entry_found_p->addr != addr)
788         {
789           /* This case indicates buggy inferior program, the resolved address
790              should never change.  */
791
792             warning (_("gnu-indirect-function \"%s\" has changed its resolved "
793                        "function_address from %s to %s"),
794                      name, paddress (gdbarch, entry_found_p->addr),
795                      paddress (gdbarch, addr));
796         }
797
798       /* New ENTRY_P is here leaked/duplicate in the OBJFILE obstack.  */
799     }
800   *slot = entry_p;
801
802   return 1;
803 }
804
805 /* Try to find the target resolved function entry address of a STT_GNU_IFUNC
806    function NAME.  If the address is found it is stored to *ADDR_P (if ADDR_P
807    is not NULL) and the function returns 1.  It returns 0 otherwise.
808
809    Only the elf_objfile_gnu_ifunc_cache_data hash table is searched by this
810    function.  */
811
812 static int
813 elf_gnu_ifunc_resolve_by_cache (const char *name, CORE_ADDR *addr_p)
814 {
815   struct objfile *objfile;
816
817   ALL_PSPACE_OBJFILES (current_program_space, objfile)
818     {
819       htab_t htab;
820       struct elf_gnu_ifunc_cache *entry_p;
821       void **slot;
822
823       htab = objfile_data (objfile, elf_objfile_gnu_ifunc_cache_data);
824       if (htab == NULL)
825         continue;
826
827       entry_p = alloca (sizeof (*entry_p) + strlen (name));
828       strcpy (entry_p->name, name);
829
830       slot = htab_find_slot (htab, entry_p, NO_INSERT);
831       if (slot == NULL)
832         continue;
833       entry_p = *slot;
834       gdb_assert (entry_p != NULL);
835
836       if (addr_p)
837         *addr_p = entry_p->addr;
838       return 1;
839     }
840
841   return 0;
842 }
843
844 /* Try to find the target resolved function entry address of a STT_GNU_IFUNC
845    function NAME.  If the address is found it is stored to *ADDR_P (if ADDR_P
846    is not NULL) and the function returns 1.  It returns 0 otherwise.
847
848    Only the SYMBOL_GOT_PLT_SUFFIX locations are searched by this function.
849    elf_gnu_ifunc_resolve_by_cache must have been already called for NAME to
850    prevent cache entries duplicates.  */
851
852 static int
853 elf_gnu_ifunc_resolve_by_got (const char *name, CORE_ADDR *addr_p)
854 {
855   char *name_got_plt;
856   struct objfile *objfile;
857   const size_t got_suffix_len = strlen (SYMBOL_GOT_PLT_SUFFIX);
858
859   name_got_plt = alloca (strlen (name) + got_suffix_len + 1);
860   sprintf (name_got_plt, "%s" SYMBOL_GOT_PLT_SUFFIX, name);
861
862   ALL_PSPACE_OBJFILES (current_program_space, objfile)
863     {
864       bfd *obfd = objfile->obfd;
865       struct gdbarch *gdbarch = objfile->gdbarch;
866       struct type *ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
867       size_t ptr_size = TYPE_LENGTH (ptr_type);
868       CORE_ADDR pointer_address, addr;
869       asection *plt;
870       gdb_byte *buf = alloca (ptr_size);
871       struct minimal_symbol *msym;
872
873       msym = lookup_minimal_symbol (name_got_plt, NULL, objfile);
874       if (msym == NULL)
875         continue;
876       if (MSYMBOL_TYPE (msym) != mst_slot_got_plt)
877         continue;
878       pointer_address = SYMBOL_VALUE_ADDRESS (msym);
879
880       plt = bfd_get_section_by_name (obfd, ".plt");
881       if (plt == NULL)
882         continue;
883
884       if (MSYMBOL_SIZE (msym) != ptr_size)
885         continue;
886       if (target_read_memory (pointer_address, buf, ptr_size) != 0)
887         continue;
888       addr = extract_typed_address (buf, ptr_type);
889       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
890                                                  &current_target);
891
892       if (addr_p)
893         *addr_p = addr;
894       if (elf_gnu_ifunc_record_cache (name, addr))
895         return 1;
896     }
897
898   return 0;
899 }
900
901 /* Try to find the target resolved function entry address of a STT_GNU_IFUNC
902    function NAME.  If the address is found it is stored to *ADDR_P (if ADDR_P
903    is not NULL) and the function returns 1.  It returns 0 otherwise.
904
905    Both the elf_objfile_gnu_ifunc_cache_data hash table and
906    SYMBOL_GOT_PLT_SUFFIX locations are searched by this function.  */
907
908 static int
909 elf_gnu_ifunc_resolve_name (const char *name, CORE_ADDR *addr_p)
910 {
911   if (elf_gnu_ifunc_resolve_by_cache (name, addr_p))
912     return 1;
913
914   if (elf_gnu_ifunc_resolve_by_got (name, addr_p))
915     return 1;
916
917   return 0;
918 }
919
920 /* Call STT_GNU_IFUNC - a function returning addresss of a real function to
921    call.  PC is theSTT_GNU_IFUNC resolving function entry.  The value returned
922    is the entry point of the resolved STT_GNU_IFUNC target function to call.
923    */
924
925 static CORE_ADDR
926 elf_gnu_ifunc_resolve_addr (struct gdbarch *gdbarch, CORE_ADDR pc)
927 {
928   const char *name_at_pc;
929   CORE_ADDR start_at_pc, address;
930   struct type *func_func_type = builtin_type (gdbarch)->builtin_func_func;
931   struct value *function, *address_val;
932
933   /* Try first any non-intrusive methods without an inferior call.  */
934
935   if (find_pc_partial_function (pc, &name_at_pc, &start_at_pc, NULL)
936       && start_at_pc == pc)
937     {
938       if (elf_gnu_ifunc_resolve_name (name_at_pc, &address))
939         return address;
940     }
941   else
942     name_at_pc = NULL;
943
944   function = allocate_value (func_func_type);
945   set_value_address (function, pc);
946
947   /* STT_GNU_IFUNC resolver functions have no parameters.  FUNCTION is the
948      function entry address.  ADDRESS may be a function descriptor.  */
949
950   address_val = call_function_by_hand (function, 0, NULL);
951   address = value_as_address (address_val);
952   address = gdbarch_convert_from_func_ptr_addr (gdbarch, address,
953                                                 &current_target);
954
955   if (name_at_pc)
956     elf_gnu_ifunc_record_cache (name_at_pc, address);
957
958   return address;
959 }
960
961 /* Handle inferior hit of bp_gnu_ifunc_resolver, see its definition.  */
962
963 static void
964 elf_gnu_ifunc_resolver_stop (struct breakpoint *b)
965 {
966   struct breakpoint *b_return;
967   struct frame_info *prev_frame = get_prev_frame (get_current_frame ());
968   struct frame_id prev_frame_id = get_stack_frame_id (prev_frame);
969   CORE_ADDR prev_pc = get_frame_pc (prev_frame);
970   int thread_id = pid_to_thread_id (inferior_ptid);
971
972   gdb_assert (b->type == bp_gnu_ifunc_resolver);
973
974   for (b_return = b->related_breakpoint; b_return != b;
975        b_return = b_return->related_breakpoint)
976     {
977       gdb_assert (b_return->type == bp_gnu_ifunc_resolver_return);
978       gdb_assert (b_return->loc != NULL && b_return->loc->next == NULL);
979       gdb_assert (frame_id_p (b_return->frame_id));
980
981       if (b_return->thread == thread_id
982           && b_return->loc->requested_address == prev_pc
983           && frame_id_eq (b_return->frame_id, prev_frame_id))
984         break;
985     }
986
987   if (b_return == b)
988     {
989       struct symtab_and_line sal;
990
991       /* No need to call find_pc_line for symbols resolving as this is only
992          a helper breakpointer never shown to the user.  */
993
994       init_sal (&sal);
995       sal.pspace = current_inferior ()->pspace;
996       sal.pc = prev_pc;
997       sal.section = find_pc_overlay (sal.pc);
998       sal.explicit_pc = 1;
999       b_return = set_momentary_breakpoint (get_frame_arch (prev_frame), sal,
1000                                            prev_frame_id,
1001                                            bp_gnu_ifunc_resolver_return);
1002
1003       /* set_momentary_breakpoint invalidates PREV_FRAME.  */
1004       prev_frame = NULL;
1005
1006       /* Add new b_return to the ring list b->related_breakpoint.  */
1007       gdb_assert (b_return->related_breakpoint == b_return);
1008       b_return->related_breakpoint = b->related_breakpoint;
1009       b->related_breakpoint = b_return;
1010     }
1011 }
1012
1013 /* Handle inferior hit of bp_gnu_ifunc_resolver_return, see its definition.  */
1014
1015 static void
1016 elf_gnu_ifunc_resolver_return_stop (struct breakpoint *b)
1017 {
1018   struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
1019   struct type *func_func_type = builtin_type (gdbarch)->builtin_func_func;
1020   struct type *value_type = TYPE_TARGET_TYPE (func_func_type);
1021   struct regcache *regcache = get_thread_regcache (inferior_ptid);
1022   struct value *func_func;
1023   struct value *value;
1024   CORE_ADDR resolved_address, resolved_pc;
1025   struct symtab_and_line sal;
1026   struct symtabs_and_lines sals, sals_end;
1027
1028   gdb_assert (b->type == bp_gnu_ifunc_resolver_return);
1029
1030   while (b->related_breakpoint != b)
1031     {
1032       struct breakpoint *b_next = b->related_breakpoint;
1033
1034       switch (b->type)
1035         {
1036         case bp_gnu_ifunc_resolver:
1037           break;
1038         case bp_gnu_ifunc_resolver_return:
1039           delete_breakpoint (b);
1040           break;
1041         default:
1042           internal_error (__FILE__, __LINE__,
1043                           _("handle_inferior_event: Invalid "
1044                             "gnu-indirect-function breakpoint type %d"),
1045                           (int) b->type);
1046         }
1047       b = b_next;
1048     }
1049   gdb_assert (b->type == bp_gnu_ifunc_resolver);
1050   gdb_assert (b->loc->next == NULL);
1051
1052   func_func = allocate_value (func_func_type);
1053   set_value_address (func_func, b->loc->related_address);
1054
1055   value = allocate_value (value_type);
1056   gdbarch_return_value (gdbarch, func_func, value_type, regcache,
1057                         value_contents_raw (value), NULL);
1058   resolved_address = value_as_address (value);
1059   resolved_pc = gdbarch_convert_from_func_ptr_addr (gdbarch,
1060                                                     resolved_address,
1061                                                     &current_target);
1062
1063   gdb_assert (current_program_space == b->pspace || b->pspace == NULL);
1064   elf_gnu_ifunc_record_cache (b->addr_string, resolved_pc);
1065
1066   sal = find_pc_line (resolved_pc, 0);
1067   sals.nelts = 1;
1068   sals.sals = &sal;
1069   sals_end.nelts = 0;
1070
1071   b->type = bp_breakpoint;
1072   update_breakpoint_locations (b, sals, sals_end);
1073 }
1074
1075 struct build_id
1076   {
1077     size_t size;
1078     gdb_byte data[1];
1079   };
1080
1081 /* Locate NT_GNU_BUILD_ID from ABFD and return its content.  */
1082
1083 static struct build_id *
1084 build_id_bfd_get (bfd *abfd)
1085 {
1086   struct build_id *retval;
1087
1088   if (!bfd_check_format (abfd, bfd_object)
1089       || bfd_get_flavour (abfd) != bfd_target_elf_flavour
1090       || elf_tdata (abfd)->build_id == NULL)
1091     return NULL;
1092
1093   retval = xmalloc (sizeof *retval - 1 + elf_tdata (abfd)->build_id_size);
1094   retval->size = elf_tdata (abfd)->build_id_size;
1095   memcpy (retval->data, elf_tdata (abfd)->build_id, retval->size);
1096
1097   return retval;
1098 }
1099
1100 /* Return if FILENAME has NT_GNU_BUILD_ID matching the CHECK value.  */
1101
1102 static int
1103 build_id_verify (const char *filename, struct build_id *check)
1104 {
1105   bfd *abfd;
1106   struct build_id *found = NULL;
1107   int retval = 0;
1108
1109   /* We expect to be silent on the non-existing files.  */
1110   abfd = bfd_open_maybe_remote (filename);
1111   if (abfd == NULL)
1112     return 0;
1113
1114   found = build_id_bfd_get (abfd);
1115
1116   if (found == NULL)
1117     warning (_("File \"%s\" has no build-id, file skipped"), filename);
1118   else if (found->size != check->size
1119            || memcmp (found->data, check->data, found->size) != 0)
1120     warning (_("File \"%s\" has a different build-id, file skipped"),
1121              filename);
1122   else
1123     retval = 1;
1124
1125   gdb_bfd_close_or_warn (abfd);
1126
1127   xfree (found);
1128
1129   return retval;
1130 }
1131
1132 static char *
1133 build_id_to_debug_filename (struct build_id *build_id)
1134 {
1135   char *link, *debugdir, *retval = NULL;
1136   VEC (char_ptr) *debugdir_vec;
1137   struct cleanup *back_to;
1138   int ix;
1139
1140   /* DEBUG_FILE_DIRECTORY/.build-id/ab/cdef */
1141   link = alloca (strlen (debug_file_directory) + (sizeof "/.build-id/" - 1) + 1
1142                  + 2 * build_id->size + (sizeof ".debug" - 1) + 1);
1143
1144   /* Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will
1145      cause "/.build-id/..." lookups.  */
1146
1147   debugdir_vec = dirnames_to_char_ptr_vec (debug_file_directory);
1148   back_to = make_cleanup_free_char_ptr_vec (debugdir_vec);
1149
1150   for (ix = 0; VEC_iterate (char_ptr, debugdir_vec, ix, debugdir); ++ix)
1151     {
1152       size_t debugdir_len = strlen (debugdir);
1153       gdb_byte *data = build_id->data;
1154       size_t size = build_id->size;
1155       char *s;
1156
1157       memcpy (link, debugdir, debugdir_len);
1158       s = &link[debugdir_len];
1159       s += sprintf (s, "/.build-id/");
1160       if (size > 0)
1161         {
1162           size--;
1163           s += sprintf (s, "%02x", (unsigned) *data++);
1164         }
1165       if (size > 0)
1166         *s++ = '/';
1167       while (size-- > 0)
1168         s += sprintf (s, "%02x", (unsigned) *data++);
1169       strcpy (s, ".debug");
1170
1171       /* lrealpath() is expensive even for the usually non-existent files.  */
1172       if (access (link, F_OK) == 0)
1173         retval = lrealpath (link);
1174
1175       if (retval != NULL && !build_id_verify (retval, build_id))
1176         {
1177           xfree (retval);
1178           retval = NULL;
1179         }
1180
1181       if (retval != NULL)
1182         break;
1183     }
1184
1185   do_cleanups (back_to);
1186   return retval;
1187 }
1188
1189 static char *
1190 find_separate_debug_file_by_buildid (struct objfile *objfile)
1191 {
1192   struct build_id *build_id;
1193
1194   build_id = build_id_bfd_get (objfile->obfd);
1195   if (build_id != NULL)
1196     {
1197       char *build_id_name;
1198
1199       build_id_name = build_id_to_debug_filename (build_id);
1200       xfree (build_id);
1201       /* Prevent looping on a stripped .debug file.  */
1202       if (build_id_name != NULL
1203           && filename_cmp (build_id_name, objfile->name) == 0)
1204         {
1205           warning (_("\"%s\": separate debug info file has no debug info"),
1206                    build_id_name);
1207           xfree (build_id_name);
1208         }
1209       else if (build_id_name != NULL)
1210         return build_id_name;
1211     }
1212   return NULL;
1213 }
1214
1215 /* Scan and build partial symbols for a symbol file.
1216    We have been initialized by a call to elf_symfile_init, which
1217    currently does nothing.
1218
1219    SECTION_OFFSETS is a set of offsets to apply to relocate the symbols
1220    in each section.  We simplify it down to a single offset for all
1221    symbols.  FIXME.
1222
1223    This function only does the minimum work necessary for letting the
1224    user "name" things symbolically; it does not read the entire symtab.
1225    Instead, it reads the external and static symbols and puts them in partial
1226    symbol tables.  When more extensive information is requested of a
1227    file, the corresponding partial symbol table is mutated into a full
1228    fledged symbol table by going back and reading the symbols
1229    for real.
1230
1231    We look for sections with specific names, to tell us what debug
1232    format to look for:  FIXME!!!
1233
1234    elfstab_build_psymtabs() handles STABS symbols;
1235    mdebug_build_psymtabs() handles ECOFF debugging information.
1236
1237    Note that ELF files have a "minimal" symbol table, which looks a lot
1238    like a COFF symbol table, but has only the minimal information necessary
1239    for linking.  We process this also, and use the information to
1240    build gdb's minimal symbol table.  This gives us some minimal debugging
1241    capability even for files compiled without -g.  */
1242
1243 static void
1244 elf_symfile_read (struct objfile *objfile, int symfile_flags)
1245 {
1246   bfd *synth_abfd, *abfd = objfile->obfd;
1247   struct elfinfo ei;
1248   struct cleanup *back_to;
1249   long symcount = 0, dynsymcount = 0, synthcount, storage_needed;
1250   asymbol **symbol_table = NULL, **dyn_symbol_table = NULL;
1251   asymbol *synthsyms;
1252
1253   init_minimal_symbol_collection ();
1254   back_to = make_cleanup_discard_minimal_symbols ();
1255
1256   memset ((char *) &ei, 0, sizeof (ei));
1257
1258   /* Allocate struct to keep track of the symfile.  */
1259   objfile->deprecated_sym_stab_info = (struct dbx_symfile_info *)
1260     xmalloc (sizeof (struct dbx_symfile_info));
1261   memset ((char *) objfile->deprecated_sym_stab_info,
1262           0, sizeof (struct dbx_symfile_info));
1263   make_cleanup (free_elfinfo, (void *) objfile);
1264
1265   /* Process the normal ELF symbol table first.  This may write some
1266      chain of info into the dbx_symfile_info in
1267      objfile->deprecated_sym_stab_info, which can later be used by
1268      elfstab_offset_sections.  */
1269
1270   storage_needed = bfd_get_symtab_upper_bound (objfile->obfd);
1271   if (storage_needed < 0)
1272     error (_("Can't read symbols from %s: %s"),
1273            bfd_get_filename (objfile->obfd),
1274            bfd_errmsg (bfd_get_error ()));
1275
1276   if (storage_needed > 0)
1277     {
1278       symbol_table = (asymbol **) xmalloc (storage_needed);
1279       make_cleanup (xfree, symbol_table);
1280       symcount = bfd_canonicalize_symtab (objfile->obfd, symbol_table);
1281
1282       if (symcount < 0)
1283         error (_("Can't read symbols from %s: %s"),
1284                bfd_get_filename (objfile->obfd),
1285                bfd_errmsg (bfd_get_error ()));
1286
1287       elf_symtab_read (objfile, ST_REGULAR, symcount, symbol_table, 0);
1288     }
1289
1290   /* Add the dynamic symbols.  */
1291
1292   storage_needed = bfd_get_dynamic_symtab_upper_bound (objfile->obfd);
1293
1294   if (storage_needed > 0)
1295     {
1296       /* Memory gets permanently referenced from ABFD after
1297          bfd_get_synthetic_symtab so it must not get freed before ABFD gets.
1298          It happens only in the case when elf_slurp_reloc_table sees
1299          asection->relocation NULL.  Determining which section is asection is
1300          done by _bfd_elf_get_synthetic_symtab which is all a bfd
1301          implementation detail, though.  */
1302
1303       dyn_symbol_table = bfd_alloc (abfd, storage_needed);
1304       dynsymcount = bfd_canonicalize_dynamic_symtab (objfile->obfd,
1305                                                      dyn_symbol_table);
1306
1307       if (dynsymcount < 0)
1308         error (_("Can't read symbols from %s: %s"),
1309                bfd_get_filename (objfile->obfd),
1310                bfd_errmsg (bfd_get_error ()));
1311
1312       elf_symtab_read (objfile, ST_DYNAMIC, dynsymcount, dyn_symbol_table, 0);
1313
1314       elf_rel_plt_read (objfile, dyn_symbol_table);
1315     }
1316
1317   /* Contrary to binutils --strip-debug/--only-keep-debug the strip command from
1318      elfutils (eu-strip) moves even the .symtab section into the .debug file.
1319
1320      bfd_get_synthetic_symtab on ppc64 for each function descriptor ELF symbol
1321      'name' creates a new BSF_SYNTHETIC ELF symbol '.name' with its code
1322      address.  But with eu-strip files bfd_get_synthetic_symtab would fail to
1323      read the code address from .opd while it reads the .symtab section from
1324      a separate debug info file as the .opd section is SHT_NOBITS there.
1325
1326      With SYNTH_ABFD the .opd section will be read from the original
1327      backlinked binary where it is valid.  */
1328
1329   if (objfile->separate_debug_objfile_backlink)
1330     synth_abfd = objfile->separate_debug_objfile_backlink->obfd;
1331   else
1332     synth_abfd = abfd;
1333
1334   /* Add synthetic symbols - for instance, names for any PLT entries.  */
1335
1336   synthcount = bfd_get_synthetic_symtab (synth_abfd, symcount, symbol_table,
1337                                          dynsymcount, dyn_symbol_table,
1338                                          &synthsyms);
1339   if (synthcount > 0)
1340     {
1341       asymbol **synth_symbol_table;
1342       long i;
1343
1344       make_cleanup (xfree, synthsyms);
1345       synth_symbol_table = xmalloc (sizeof (asymbol *) * synthcount);
1346       for (i = 0; i < synthcount; i++)
1347         synth_symbol_table[i] = synthsyms + i;
1348       make_cleanup (xfree, synth_symbol_table);
1349       elf_symtab_read (objfile, ST_SYNTHETIC, synthcount,
1350                        synth_symbol_table, 1);
1351     }
1352
1353   /* Install any minimal symbols that have been collected as the current
1354      minimal symbols for this objfile.  The debug readers below this point
1355      should not generate new minimal symbols; if they do it's their
1356      responsibility to install them.  "mdebug" appears to be the only one
1357      which will do this.  */
1358
1359   install_minimal_symbols (objfile);
1360   do_cleanups (back_to);
1361
1362   /* Now process debugging information, which is contained in
1363      special ELF sections.  */
1364
1365   /* We first have to find them...  */
1366   bfd_map_over_sections (abfd, elf_locate_sections, (void *) & ei);
1367
1368   /* ELF debugging information is inserted into the psymtab in the
1369      order of least informative first - most informative last.  Since
1370      the psymtab table is searched `most recent insertion first' this
1371      increases the probability that more detailed debug information
1372      for a section is found.
1373
1374      For instance, an object file might contain both .mdebug (XCOFF)
1375      and .debug_info (DWARF2) sections then .mdebug is inserted first
1376      (searched last) and DWARF2 is inserted last (searched first).  If
1377      we don't do this then the XCOFF info is found first - for code in
1378      an included file XCOFF info is useless.  */
1379
1380   if (ei.mdebugsect)
1381     {
1382       const struct ecoff_debug_swap *swap;
1383
1384       /* .mdebug section, presumably holding ECOFF debugging
1385          information.  */
1386       swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap;
1387       if (swap)
1388         elfmdebug_build_psymtabs (objfile, swap, ei.mdebugsect);
1389     }
1390   if (ei.stabsect)
1391     {
1392       asection *str_sect;
1393
1394       /* Stab sections have an associated string table that looks like
1395          a separate section.  */
1396       str_sect = bfd_get_section_by_name (abfd, ".stabstr");
1397
1398       /* FIXME should probably warn about a stab section without a stabstr.  */
1399       if (str_sect)
1400         elfstab_build_psymtabs (objfile,
1401                                 ei.stabsect,
1402                                 str_sect->filepos,
1403                                 bfd_section_size (abfd, str_sect));
1404     }
1405
1406   if (dwarf2_has_info (objfile, NULL))
1407     {
1408       /* elf_sym_fns_gdb_index cannot handle simultaneous non-DWARF debug
1409          information present in OBJFILE.  If there is such debug info present
1410          never use .gdb_index.  */
1411
1412       if (!objfile_has_partial_symbols (objfile)
1413           && dwarf2_initialize_objfile (objfile))
1414         objfile->sf = &elf_sym_fns_gdb_index;
1415       else
1416         {
1417           /* It is ok to do this even if the stabs reader made some
1418              partial symbols, because OBJF_PSYMTABS_READ has not been
1419              set, and so our lazy reader function will still be called
1420              when needed.  */
1421           objfile->sf = &elf_sym_fns_lazy_psyms;
1422         }
1423     }
1424   /* If the file has its own symbol tables it has no separate debug
1425      info.  `.dynsym'/`.symtab' go to MSYMBOLS, `.debug_info' goes to
1426      SYMTABS/PSYMTABS.  `.gnu_debuglink' may no longer be present with
1427      `.note.gnu.build-id'.  */
1428   else if (!objfile_has_partial_symbols (objfile))
1429     {
1430       char *debugfile;
1431
1432       debugfile = find_separate_debug_file_by_buildid (objfile);
1433
1434       if (debugfile == NULL)
1435         debugfile = find_separate_debug_file_by_debuglink (objfile);
1436
1437       if (debugfile)
1438         {
1439           bfd *abfd = symfile_bfd_open (debugfile);
1440
1441           symbol_file_add_separate (abfd, symfile_flags, objfile);
1442           xfree (debugfile);
1443         }
1444     }
1445 }
1446
1447 /* Callback to lazily read psymtabs.  */
1448
1449 static void
1450 read_psyms (struct objfile *objfile)
1451 {
1452   if (dwarf2_has_info (objfile, NULL))
1453     dwarf2_build_psymtabs (objfile);
1454 }
1455
1456 /* This cleans up the objfile's deprecated_sym_stab_info pointer, and
1457    the chain of stab_section_info's, that might be dangling from
1458    it.  */
1459
1460 static void
1461 free_elfinfo (void *objp)
1462 {
1463   struct objfile *objfile = (struct objfile *) objp;
1464   struct dbx_symfile_info *dbxinfo = objfile->deprecated_sym_stab_info;
1465   struct stab_section_info *ssi, *nssi;
1466
1467   ssi = dbxinfo->stab_section_info;
1468   while (ssi)
1469     {
1470       nssi = ssi->next;
1471       xfree (ssi);
1472       ssi = nssi;
1473     }
1474
1475   dbxinfo->stab_section_info = 0;       /* Just say No mo info about this.  */
1476 }
1477
1478
1479 /* Initialize anything that needs initializing when a completely new symbol
1480    file is specified (not just adding some symbols from another file, e.g. a
1481    shared library).
1482
1483    We reinitialize buildsym, since we may be reading stabs from an ELF
1484    file.  */
1485
1486 static void
1487 elf_new_init (struct objfile *ignore)
1488 {
1489   stabsread_new_init ();
1490   buildsym_new_init ();
1491 }
1492
1493 /* Perform any local cleanups required when we are done with a particular
1494    objfile.  I.E, we are in the process of discarding all symbol information
1495    for an objfile, freeing up all memory held for it, and unlinking the
1496    objfile struct from the global list of known objfiles.  */
1497
1498 static void
1499 elf_symfile_finish (struct objfile *objfile)
1500 {
1501   if (objfile->deprecated_sym_stab_info != NULL)
1502     {
1503       xfree (objfile->deprecated_sym_stab_info);
1504     }
1505
1506   dwarf2_free_objfile (objfile);
1507 }
1508
1509 /* ELF specific initialization routine for reading symbols.
1510
1511    It is passed a pointer to a struct sym_fns which contains, among other
1512    things, the BFD for the file whose symbols are being read, and a slot for
1513    a pointer to "private data" which we can fill with goodies.
1514
1515    For now at least, we have nothing in particular to do, so this function is
1516    just a stub.  */
1517
1518 static void
1519 elf_symfile_init (struct objfile *objfile)
1520 {
1521   /* ELF objects may be reordered, so set OBJF_REORDERED.  If we
1522      find this causes a significant slowdown in gdb then we could
1523      set it in the debug symbol readers only when necessary.  */
1524   objfile->flags |= OBJF_REORDERED;
1525 }
1526
1527 /* When handling an ELF file that contains Sun STABS debug info,
1528    some of the debug info is relative to the particular chunk of the
1529    section that was generated in its individual .o file.  E.g.
1530    offsets to static variables are relative to the start of the data
1531    segment *for that module before linking*.  This information is
1532    painfully squirreled away in the ELF symbol table as local symbols
1533    with wierd names.  Go get 'em when needed.  */
1534
1535 void
1536 elfstab_offset_sections (struct objfile *objfile, struct partial_symtab *pst)
1537 {
1538   const char *filename = pst->filename;
1539   struct dbx_symfile_info *dbx = objfile->deprecated_sym_stab_info;
1540   struct stab_section_info *maybe = dbx->stab_section_info;
1541   struct stab_section_info *questionable = 0;
1542   int i;
1543
1544   /* The ELF symbol info doesn't include path names, so strip the path
1545      (if any) from the psymtab filename.  */
1546   filename = lbasename (filename);
1547
1548   /* FIXME:  This linear search could speed up significantly
1549      if it was chained in the right order to match how we search it,
1550      and if we unchained when we found a match.  */
1551   for (; maybe; maybe = maybe->next)
1552     {
1553       if (filename[0] == maybe->filename[0]
1554           && filename_cmp (filename, maybe->filename) == 0)
1555         {
1556           /* We found a match.  But there might be several source files
1557              (from different directories) with the same name.  */
1558           if (0 == maybe->found)
1559             break;
1560           questionable = maybe; /* Might use it later.  */
1561         }
1562     }
1563
1564   if (maybe == 0 && questionable != 0)
1565     {
1566       complaint (&symfile_complaints,
1567                  _("elf/stab section information questionable for %s"),
1568                  filename);
1569       maybe = questionable;
1570     }
1571
1572   if (maybe)
1573     {
1574       /* Found it!  Allocate a new psymtab struct, and fill it in.  */
1575       maybe->found++;
1576       pst->section_offsets = (struct section_offsets *)
1577         obstack_alloc (&objfile->objfile_obstack,
1578                        SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
1579       for (i = 0; i < maybe->num_sections; i++)
1580         (pst->section_offsets)->offsets[i] = maybe->sections[i];
1581       return;
1582     }
1583
1584   /* We were unable to find any offsets for this file.  Complain.  */
1585   if (dbx->stab_section_info)   /* If there *is* any info, */
1586     complaint (&symfile_complaints,
1587                _("elf/stab section information missing for %s"), filename);
1588 }
1589
1590 /* Implementation of `sym_get_probes', as documented in symfile.h.  */
1591
1592 static VEC (probe_p) *
1593 elf_get_probes (struct objfile *objfile)
1594 {
1595   VEC (probe_p) *probes_per_objfile;
1596
1597   /* Have we parsed this objfile's probes already?  */
1598   probes_per_objfile = objfile_data (objfile, probe_key);
1599
1600   if (!probes_per_objfile)
1601     {
1602       int ix;
1603       const struct probe_ops *probe_ops;
1604
1605       /* Here we try to gather information about all types of probes from the
1606          objfile.  */
1607       for (ix = 0; VEC_iterate (probe_ops_cp, all_probe_ops, ix, probe_ops);
1608            ix++)
1609         probe_ops->get_probes (&probes_per_objfile, objfile);
1610
1611       if (probes_per_objfile == NULL)
1612         {
1613           VEC_reserve (probe_p, probes_per_objfile, 1);
1614           gdb_assert (probes_per_objfile != NULL);
1615         }
1616
1617       set_objfile_data (objfile, probe_key, probes_per_objfile);
1618     }
1619
1620   return probes_per_objfile;
1621 }
1622
1623 /* Implementation of `sym_get_probe_argument_count', as documented in
1624    symfile.h.  */
1625
1626 static unsigned
1627 elf_get_probe_argument_count (struct objfile *objfile,
1628                               struct probe *probe)
1629 {
1630   return probe->pops->get_probe_argument_count (probe, objfile);
1631 }
1632
1633 /* Implementation of `sym_evaluate_probe_argument', as documented in
1634    symfile.h.  */
1635
1636 static struct value *
1637 elf_evaluate_probe_argument (struct objfile *objfile,
1638                              struct probe *probe,
1639                              unsigned n)
1640 {
1641   return probe->pops->evaluate_probe_argument (probe, objfile, n);
1642 }
1643
1644 /* Implementation of `sym_compile_to_ax', as documented in symfile.h.  */
1645
1646 static void
1647 elf_compile_to_ax (struct objfile *objfile,
1648                    struct probe *probe,
1649                    struct agent_expr *expr,
1650                    struct axs_value *value,
1651                    unsigned n)
1652 {
1653   probe->pops->compile_to_ax (probe, objfile, expr, value, n);
1654 }
1655
1656 /* Implementation of `sym_relocate_probe', as documented in symfile.h.  */
1657
1658 static void
1659 elf_symfile_relocate_probe (struct objfile *objfile,
1660                             struct section_offsets *new_offsets,
1661                             struct section_offsets *delta)
1662 {
1663   int ix;
1664   VEC (probe_p) *probes = objfile_data (objfile, probe_key);
1665   struct probe *probe;
1666
1667   for (ix = 0; VEC_iterate (probe_p, probes, ix, probe); ix++)
1668     probe->pops->relocate (probe, ANOFFSET (delta, SECT_OFF_TEXT (objfile)));
1669 }
1670
1671 /* Helper function used to free the space allocated for storing SystemTap
1672    probe information.  */
1673
1674 static void
1675 probe_key_free (struct objfile *objfile, void *d)
1676 {
1677   int ix;
1678   VEC (probe_p) *probes = d;
1679   struct probe *probe;
1680
1681   for (ix = 0; VEC_iterate (probe_p, probes, ix, probe); ix++)
1682     probe->pops->destroy (probe);
1683
1684   VEC_free (probe_p, probes);
1685 }
1686
1687 \f
1688
1689 /* Implementation `sym_probe_fns', as documented in symfile.h.  */
1690
1691 static const struct sym_probe_fns elf_probe_fns =
1692 {
1693   elf_get_probes,               /* sym_get_probes */
1694   elf_get_probe_argument_count, /* sym_get_probe_argument_count */
1695   elf_evaluate_probe_argument,  /* sym_evaluate_probe_argument */
1696   elf_compile_to_ax,            /* sym_compile_to_ax */
1697   elf_symfile_relocate_probe,   /* sym_relocate_probe */
1698 };
1699
1700 /* Register that we are able to handle ELF object file formats.  */
1701
1702 static const struct sym_fns elf_sym_fns =
1703 {
1704   bfd_target_elf_flavour,
1705   elf_new_init,                 /* init anything gbl to entire symtab */
1706   elf_symfile_init,             /* read initial info, setup for sym_read() */
1707   elf_symfile_read,             /* read a symbol file into symtab */
1708   NULL,                         /* sym_read_psymbols */
1709   elf_symfile_finish,           /* finished with file, cleanup */
1710   default_symfile_offsets,      /* Translate ext. to int. relocation */
1711   elf_symfile_segments,         /* Get segment information from a file.  */
1712   NULL,
1713   default_symfile_relocate,     /* Relocate a debug section.  */
1714   &elf_probe_fns,               /* sym_probe_fns */
1715   &psym_functions
1716 };
1717
1718 /* The same as elf_sym_fns, but not registered and lazily reads
1719    psymbols.  */
1720
1721 static const struct sym_fns elf_sym_fns_lazy_psyms =
1722 {
1723   bfd_target_elf_flavour,
1724   elf_new_init,                 /* init anything gbl to entire symtab */
1725   elf_symfile_init,             /* read initial info, setup for sym_read() */
1726   elf_symfile_read,             /* read a symbol file into symtab */
1727   read_psyms,                   /* sym_read_psymbols */
1728   elf_symfile_finish,           /* finished with file, cleanup */
1729   default_symfile_offsets,      /* Translate ext. to int. relocation */
1730   elf_symfile_segments,         /* Get segment information from a file.  */
1731   NULL,
1732   default_symfile_relocate,     /* Relocate a debug section.  */
1733   &elf_probe_fns,               /* sym_probe_fns */
1734   &psym_functions
1735 };
1736
1737 /* The same as elf_sym_fns, but not registered and uses the
1738    DWARF-specific GNU index rather than psymtab.  */
1739 static const struct sym_fns elf_sym_fns_gdb_index =
1740 {
1741   bfd_target_elf_flavour,
1742   elf_new_init,                 /* init anything gbl to entire symab */
1743   elf_symfile_init,             /* read initial info, setup for sym_red() */
1744   elf_symfile_read,             /* read a symbol file into symtab */
1745   NULL,                         /* sym_read_psymbols */
1746   elf_symfile_finish,           /* finished with file, cleanup */
1747   default_symfile_offsets,      /* Translate ext. to int. relocatin */
1748   elf_symfile_segments,         /* Get segment information from a file.  */
1749   NULL,
1750   default_symfile_relocate,     /* Relocate a debug section.  */
1751   &elf_probe_fns,               /* sym_probe_fns */
1752   &dwarf2_gdb_index_functions
1753 };
1754
1755 /* STT_GNU_IFUNC resolver vector to be installed to gnu_ifunc_fns_p.  */
1756
1757 static const struct gnu_ifunc_fns elf_gnu_ifunc_fns =
1758 {
1759   elf_gnu_ifunc_resolve_addr,
1760   elf_gnu_ifunc_resolve_name,
1761   elf_gnu_ifunc_resolver_stop,
1762   elf_gnu_ifunc_resolver_return_stop
1763 };
1764
1765 void
1766 _initialize_elfread (void)
1767 {
1768   probe_key = register_objfile_data_with_cleanup (NULL, probe_key_free);
1769   add_symtab_fns (&elf_sym_fns);
1770
1771   elf_objfile_gnu_ifunc_cache_data = register_objfile_data ();
1772   gnu_ifunc_fns_p = &elf_gnu_ifunc_fns;
1773 }