1/* elf.c -- Get debug data from an ELF file for backtraces.
2   Copyright (C) 2012-2016 Free Software Foundation, Inc.
3   Written by Ian Lance Taylor, Google.
4
5Redistribution and use in source and binary forms, with or without
6modification, are permitted provided that the following conditions are
7met:
8
9    (1) Redistributions of source code must retain the above copyright
10    notice, this list of conditions and the following disclaimer.
11
12    (2) Redistributions in binary form must reproduce the above copyright
13    notice, this list of conditions and the following disclaimer in
14    the documentation and/or other materials provided with the
15    distribution.
16
17    (3) The name of the author may not be used to
18    endorse or promote products derived from this software without
19    specific prior written permission.
20
21THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
25INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31POSSIBILITY OF SUCH DAMAGE.  */
32
33#include "config.h"
34
35#include <stdlib.h>
36#include <string.h>
37#include <sys/types.h>
38
39#ifdef HAVE_DL_ITERATE_PHDR
40#include <link.h>
41#endif
42
43#include "backtrace.h"
44#include "internal.h"
45
46/* ELF-specific state.  */
47
48struct elf_state
49{
50  /* The "view" of the strtab section.  */
51  struct backtrace_view strtab_view;
52
53  /* Non-zero if valid.  */
54  int strtab_view_valid;
55
56  /* The "view" of the debug sections.
57     All debug sections are loaded into one view since they're generally
58     contiguous in the file.  */
59  struct backtrace_view debug_view;
60
61  /* Non-zero if valid.  */
62  int debug_view_valid;
63};
64
65#ifndef HAVE_DL_ITERATE_PHDR
66
67/* Dummy version of dl_iterate_phdr for systems that don't have it.  */
68
69#define dl_phdr_info x_dl_phdr_info
70#define dl_iterate_phdr x_dl_iterate_phdr
71
72struct dl_phdr_info
73{
74  uintptr_t dlpi_addr;
75  const char *dlpi_name;
76};
77
78static int
79dl_iterate_phdr (int (*callback) (struct dl_phdr_info *,
80				  size_t, void *) ATTRIBUTE_UNUSED,
81		 void *data ATTRIBUTE_UNUSED)
82{
83  return 0;
84}
85
86#endif /* ! defined (HAVE_DL_ITERATE_PHDR) */
87
88/* The configure script must tell us whether we are 32-bit or 64-bit
89   ELF.  We could make this code test and support either possibility,
90   but there is no point.  This code only works for the currently
91   running executable, which means that we know the ELF mode at
92   configure mode.  */
93
94#if BACKTRACE_ELF_SIZE != 32 && BACKTRACE_ELF_SIZE != 64
95#error "Unknown BACKTRACE_ELF_SIZE"
96#endif
97
98/* <link.h> might #include <elf.h> which might define our constants
99   with slightly different values.  Undefine them to be safe.  */
100
101#undef EI_NIDENT
102#undef EI_MAG0
103#undef EI_MAG1
104#undef EI_MAG2
105#undef EI_MAG3
106#undef EI_CLASS
107#undef EI_DATA
108#undef EI_VERSION
109#undef ELF_MAG0
110#undef ELF_MAG1
111#undef ELF_MAG2
112#undef ELF_MAG3
113#undef ELFCLASS32
114#undef ELFCLASS64
115#undef ELFDATA2LSB
116#undef ELFDATA2MSB
117#undef EV_CURRENT
118#undef ET_DYN
119#undef SHN_LORESERVE
120#undef SHN_XINDEX
121#undef SHN_UNDEF
122#undef SHT_SYMTAB
123#undef SHT_STRTAB
124#undef SHT_DYNSYM
125#undef STT_OBJECT
126#undef STT_FUNC
127
128/* Basic types.  */
129
130typedef uint16_t b_elf_half;    /* Elf_Half.  */
131typedef uint32_t b_elf_word;    /* Elf_Word.  */
132typedef int32_t  b_elf_sword;   /* Elf_Sword.  */
133
134#if BACKTRACE_ELF_SIZE == 32
135
136typedef uint32_t b_elf_addr;    /* Elf_Addr.  */
137typedef uint32_t b_elf_off;     /* Elf_Off.  */
138
139typedef uint32_t b_elf_wxword;  /* 32-bit Elf_Word, 64-bit ELF_Xword.  */
140
141#else
142
143typedef uint64_t b_elf_addr;    /* Elf_Addr.  */
144typedef uint64_t b_elf_off;     /* Elf_Off.  */
145typedef uint64_t b_elf_xword;   /* Elf_Xword.  */
146typedef int64_t  b_elf_sxword;  /* Elf_Sxword.  */
147
148typedef uint64_t b_elf_wxword;  /* 32-bit Elf_Word, 64-bit ELF_Xword.  */
149
150#endif
151
152/* Data structures and associated constants.  */
153
154#define EI_NIDENT 16
155
156typedef struct {
157  unsigned char	e_ident[EI_NIDENT];	/* ELF "magic number" */
158  b_elf_half	e_type;			/* Identifies object file type */
159  b_elf_half	e_machine;		/* Specifies required architecture */
160  b_elf_word	e_version;		/* Identifies object file version */
161  b_elf_addr	e_entry;		/* Entry point virtual address */
162  b_elf_off	e_phoff;		/* Program header table file offset */
163  b_elf_off	e_shoff;		/* Section header table file offset */
164  b_elf_word	e_flags;		/* Processor-specific flags */
165  b_elf_half	e_ehsize;		/* ELF header size in bytes */
166  b_elf_half	e_phentsize;		/* Program header table entry size */
167  b_elf_half	e_phnum;		/* Program header table entry count */
168  b_elf_half	e_shentsize;		/* Section header table entry size */
169  b_elf_half	e_shnum;		/* Section header table entry count */
170  b_elf_half	e_shstrndx;		/* Section header string table index */
171} b_elf_ehdr;  /* Elf_Ehdr.  */
172
173#define EI_MAG0 0
174#define EI_MAG1 1
175#define EI_MAG2 2
176#define EI_MAG3 3
177#define EI_CLASS 4
178#define EI_DATA 5
179#define EI_VERSION 6
180
181#define ELFMAG0 0x7f
182#define ELFMAG1 'E'
183#define ELFMAG2 'L'
184#define ELFMAG3 'F'
185
186#define ELFCLASS32 1
187#define ELFCLASS64 2
188
189#define ELFDATA2LSB 1
190#define ELFDATA2MSB 2
191
192#define EV_CURRENT 1
193
194#define ET_DYN 3
195
196typedef struct {
197  b_elf_word	sh_name;		/* Section name, index in string tbl */
198  b_elf_word	sh_type;		/* Type of section */
199  b_elf_wxword	sh_flags;		/* Miscellaneous section attributes */
200  b_elf_addr	sh_addr;		/* Section virtual addr at execution */
201  b_elf_off	sh_offset;		/* Section file offset */
202  b_elf_wxword	sh_size;		/* Size of section in bytes */
203  b_elf_word	sh_link;		/* Index of another section */
204  b_elf_word	sh_info;		/* Additional section information */
205  b_elf_wxword	sh_addralign;		/* Section alignment */
206  b_elf_wxword	sh_entsize;		/* Entry size if section holds table */
207} b_elf_shdr;  /* Elf_Shdr.  */
208
209#define SHN_UNDEF	0x0000		/* Undefined section */
210#define SHN_LORESERVE	0xFF00		/* Begin range of reserved indices */
211#define SHN_XINDEX	0xFFFF		/* Section index is held elsewhere */
212
213#define SHT_SYMTAB 2
214#define SHT_STRTAB 3
215#define SHT_DYNSYM 11
216
217#if BACKTRACE_ELF_SIZE == 32
218
219typedef struct
220{
221  b_elf_word	st_name;		/* Symbol name, index in string tbl */
222  b_elf_addr	st_value;		/* Symbol value */
223  b_elf_word	st_size;		/* Symbol size */
224  unsigned char	st_info;		/* Symbol binding and type */
225  unsigned char	st_other;		/* Visibility and other data */
226  b_elf_half	st_shndx;		/* Symbol section index */
227} b_elf_sym;  /* Elf_Sym.  */
228
229#else /* BACKTRACE_ELF_SIZE != 32 */
230
231typedef struct
232{
233  b_elf_word	st_name;		/* Symbol name, index in string tbl */
234  unsigned char	st_info;		/* Symbol binding and type */
235  unsigned char	st_other;		/* Visibility and other data */
236  b_elf_half	st_shndx;		/* Symbol section index */
237  b_elf_addr	st_value;		/* Symbol value */
238  b_elf_xword	st_size;		/* Symbol size */
239} b_elf_sym;  /* Elf_Sym.  */
240
241#endif /* BACKTRACE_ELF_SIZE != 32 */
242
243#define STT_OBJECT 1
244#define STT_FUNC 2
245
246/* An index of ELF sections we care about.  */
247
248enum debug_section
249{
250  DEBUG_INFO,
251  DEBUG_LINE,
252  DEBUG_ABBREV,
253  DEBUG_RANGES,
254  DEBUG_STR,
255  DEBUG_MAX
256};
257
258/* Names of sections, indexed by enum elf_section.  */
259
260static const char * const debug_section_names[DEBUG_MAX] =
261{
262  ".debug_info",
263  ".debug_line",
264  ".debug_abbrev",
265  ".debug_ranges",
266  ".debug_str"
267};
268
269/* Information we gather for the sections we care about.  */
270
271struct debug_section_info
272{
273  /* Section file offset.  */
274  off_t offset;
275  /* Section size.  */
276  size_t size;
277  /* Section contents, after read from file.  */
278  const unsigned char *data;
279};
280
281/* Information we keep for an ELF symbol.  */
282
283struct elf_symbol
284{
285  /* The name of the symbol.  */
286  const char *name;
287  /* The address of the symbol.  */
288  uintptr_t address;
289  /* The size of the symbol.  */
290  size_t size;
291};
292
293/* Information to pass to elf_syminfo.  */
294
295struct elf_syminfo_data
296{
297  /* Symbols for the next module.  */
298  struct elf_syminfo_data *next;
299  /* The ELF symbols, sorted by address.  */
300  struct elf_symbol *symbols;
301  /* The number of symbols.  */
302  size_t count;
303};
304
305/* A dummy callback function used when we can't find any debug info.  */
306
307static int
308elf_nodebug (struct backtrace_state *state ATTRIBUTE_UNUSED,
309	     uintptr_t pc ATTRIBUTE_UNUSED,
310	     backtrace_full_callback callback ATTRIBUTE_UNUSED,
311	     backtrace_error_callback error_callback, void *data)
312{
313  error_callback (data, "no debug info in ELF executable", -1);
314  return 0;
315}
316
317/* A dummy callback function used when we can't find a symbol
318   table.  */
319
320static void
321elf_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED,
322	    uintptr_t addr ATTRIBUTE_UNUSED,
323	    backtrace_syminfo_callback callback ATTRIBUTE_UNUSED,
324	    backtrace_error_callback error_callback, void *data)
325{
326  error_callback (data, "no symbol table in ELF executable", -1);
327}
328
329/* Compare struct elf_symbol for qsort.  */
330
331static int
332elf_symbol_compare (const void *v1, const void *v2)
333{
334  const struct elf_symbol *e1 = (const struct elf_symbol *) v1;
335  const struct elf_symbol *e2 = (const struct elf_symbol *) v2;
336
337  if (e1->address < e2->address)
338    return -1;
339  else if (e1->address > e2->address)
340    return 1;
341  else
342    return 0;
343}
344
345/* Compare an ADDR against an elf_symbol for bsearch.  We allocate one
346   extra entry in the array so that this can look safely at the next
347   entry.  */
348
349static int
350elf_symbol_search (const void *vkey, const void *ventry)
351{
352  const uintptr_t *key = (const uintptr_t *) vkey;
353  const struct elf_symbol *entry = (const struct elf_symbol *) ventry;
354  uintptr_t addr;
355
356  addr = *key;
357  if (addr < entry->address)
358    return -1;
359  else if (addr >= entry->address + entry->size)
360    return 1;
361  else
362    return 0;
363}
364
365/* Initialize the symbol table info for elf_syminfo.  */
366
367static int
368elf_initialize_syminfo (struct backtrace_state *state,
369			uintptr_t base_address,
370			const unsigned char *symtab_data, size_t symtab_size,
371			const unsigned char *strtab, size_t strtab_size,
372			backtrace_error_callback error_callback,
373			void *data, struct elf_syminfo_data *sdata)
374{
375  size_t sym_count;
376  const b_elf_sym *sym;
377  size_t elf_symbol_count;
378  size_t elf_symbol_size;
379  struct elf_symbol *elf_symbols;
380  size_t i;
381  unsigned int j;
382
383  sym_count = symtab_size / sizeof (b_elf_sym);
384
385  /* We only care about function symbols.  Count them.  */
386  sym = (const b_elf_sym *) symtab_data;
387  elf_symbol_count = 0;
388  for (i = 0; i < sym_count; ++i, ++sym)
389    {
390      int info;
391
392      info = sym->st_info & 0xf;
393      if ((info == STT_FUNC || info == STT_OBJECT)
394	  && sym->st_shndx != SHN_UNDEF)
395	++elf_symbol_count;
396    }
397
398  elf_symbol_size = elf_symbol_count * sizeof (struct elf_symbol);
399  elf_symbols = ((struct elf_symbol *)
400		 backtrace_alloc (state, elf_symbol_size, error_callback,
401				  data));
402  if (elf_symbols == NULL)
403    return 0;
404
405  sym = (const b_elf_sym *) symtab_data;
406  j = 0;
407  for (i = 0; i < sym_count; ++i, ++sym)
408    {
409      int info;
410
411      info = sym->st_info & 0xf;
412      if (info != STT_FUNC && info != STT_OBJECT)
413	continue;
414      if (sym->st_shndx == SHN_UNDEF)
415	continue;
416      if (sym->st_name >= strtab_size)
417	{
418	  error_callback (data, "symbol string index out of range", 0);
419	  backtrace_free (state, elf_symbols, elf_symbol_size, error_callback,
420			  data);
421	  return 0;
422	}
423      elf_symbols[j].name = (const char *) strtab + sym->st_name;
424      elf_symbols[j].address = sym->st_value + base_address;
425      elf_symbols[j].size = sym->st_size;
426      ++j;
427    }
428
429  backtrace_qsort (elf_symbols, elf_symbol_count, sizeof (struct elf_symbol),
430		   elf_symbol_compare);
431
432  sdata->next = NULL;
433  sdata->symbols = elf_symbols;
434  sdata->count = elf_symbol_count;
435
436  return 1;
437}
438
439/* Add EDATA to the list in STATE.  */
440
441static void
442elf_add_syminfo_data (struct backtrace_state *state,
443		      struct elf_syminfo_data *edata)
444{
445  if (!state->threaded)
446    {
447      struct elf_syminfo_data **pp;
448
449      for (pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
450	   *pp != NULL;
451	   pp = &(*pp)->next)
452	;
453      *pp = edata;
454    }
455  else
456    {
457      while (1)
458	{
459	  struct elf_syminfo_data **pp;
460
461	  pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
462
463	  while (1)
464	    {
465	      struct elf_syminfo_data *p;
466
467	      p = backtrace_atomic_load_pointer (pp);
468
469	      if (p == NULL)
470		break;
471
472	      pp = &p->next;
473	    }
474
475	  if (__sync_bool_compare_and_swap (pp, NULL, edata))
476	    break;
477	}
478    }
479}
480
481/* Return the symbol name and value for an ADDR.  */
482
483static void
484elf_syminfo (struct backtrace_state *state, uintptr_t addr,
485	     backtrace_syminfo_callback callback,
486	     backtrace_error_callback error_callback ATTRIBUTE_UNUSED,
487	     void *data)
488{
489  struct elf_syminfo_data *edata;
490  struct elf_symbol *sym = NULL;
491
492  if (!state->threaded)
493    {
494      for (edata = (struct elf_syminfo_data *) state->syminfo_data;
495	   edata != NULL;
496	   edata = edata->next)
497	{
498	  sym = ((struct elf_symbol *)
499		 bsearch (&addr, edata->symbols, edata->count,
500			  sizeof (struct elf_symbol), elf_symbol_search));
501	  if (sym != NULL)
502	    break;
503	}
504    }
505  else
506    {
507      struct elf_syminfo_data **pp;
508
509      pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
510      while (1)
511	{
512	  edata = backtrace_atomic_load_pointer (pp);
513	  if (edata == NULL)
514	    break;
515
516	  sym = ((struct elf_symbol *)
517		 bsearch (&addr, edata->symbols, edata->count,
518			  sizeof (struct elf_symbol), elf_symbol_search));
519	  if (sym != NULL)
520	    break;
521
522	  pp = &edata->next;
523	}
524    }
525
526  if (sym == NULL)
527    callback (data, addr, NULL, 0, 0);
528  else
529    callback (data, addr, sym->name, sym->address, sym->size);
530}
531
532/* Add the backtrace data for one ELF file.  Returns 1 on success,
533   0 on failure (in both cases descriptor is closed) or -1 if exe
534   is non-zero and the ELF file is ET_DYN and !BASE_ADDRESS_SET,
535   which tells the caller that elf_add will need to be called on the
536   descriptor again after base_address is determined.  */
537
538static int
539elf_add (struct backtrace_state *state, int descriptor,
540	 uintptr_t base_address, int base_address_set,
541	 backtrace_error_callback error_callback, void *data,
542	 fileline *fileline_fn, int *found_sym, int *found_dwarf, int exe)
543{
544  struct elf_state *elf_state = state->target_state;
545  struct backtrace_view ehdr_view;
546  b_elf_ehdr ehdr;
547  off_t shoff;
548  unsigned int shnum;
549  unsigned int shstrndx;
550  struct backtrace_view shdrs_view;
551  int shdrs_view_valid;
552  const b_elf_shdr *shdrs;
553  const b_elf_shdr *shstrhdr;
554  size_t shstr_size;
555  off_t shstr_off;
556  struct backtrace_view names_view;
557  int names_view_valid;
558  const char *names;
559  unsigned int symtab_shndx;
560  unsigned int dynsym_shndx;
561  unsigned int i;
562  struct debug_section_info sections[DEBUG_MAX];
563  struct backtrace_view symtab_view;
564  int symtab_view_valid;
565  struct backtrace_view strtab_view;
566  int strtab_view_valid;
567  off_t min_offset;
568  off_t max_offset;
569  struct backtrace_view debug_view;
570  int debug_view_valid;
571
572  *found_sym = 0;
573  *found_dwarf = 0;
574
575  shdrs_view_valid = 0;
576  names_view_valid = 0;
577  symtab_view_valid = 0;
578  strtab_view_valid = 0;
579  debug_view_valid = 0;
580
581  if (!backtrace_get_view (state, descriptor, 0, sizeof ehdr, error_callback,
582			   data, &ehdr_view))
583    goto fail;
584
585  memcpy (&ehdr, ehdr_view.data, sizeof ehdr);
586
587  backtrace_release_view (state, &ehdr_view, error_callback, data);
588
589  if (ehdr.e_ident[EI_MAG0] != ELFMAG0
590      || ehdr.e_ident[EI_MAG1] != ELFMAG1
591      || ehdr.e_ident[EI_MAG2] != ELFMAG2
592      || ehdr.e_ident[EI_MAG3] != ELFMAG3)
593    {
594      error_callback (data, "executable file is not ELF", 0);
595      goto fail;
596    }
597  if (ehdr.e_ident[EI_VERSION] != EV_CURRENT)
598    {
599      error_callback (data, "executable file is unrecognized ELF version", 0);
600      goto fail;
601    }
602
603#if BACKTRACE_ELF_SIZE == 32
604#define BACKTRACE_ELFCLASS ELFCLASS32
605#else
606#define BACKTRACE_ELFCLASS ELFCLASS64
607#endif
608
609  if (ehdr.e_ident[EI_CLASS] != BACKTRACE_ELFCLASS)
610    {
611      error_callback (data, "executable file is unexpected ELF class", 0);
612      goto fail;
613    }
614
615  if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB
616      && ehdr.e_ident[EI_DATA] != ELFDATA2MSB)
617    {
618      error_callback (data, "executable file has unknown endianness", 0);
619      goto fail;
620    }
621
622  /* If the executable is ET_DYN, it is either a PIE, or we are running
623     directly a shared library with .interp.  If we don't know the base
624     address yet then we need to wait for dl_iterate_phdr (or equivalent)
625     to determine the actual base_address.  */
626  if (exe && ehdr.e_type == ET_DYN && !base_address_set)
627    return -1;
628
629  shoff = ehdr.e_shoff;
630  shnum = ehdr.e_shnum;
631  shstrndx = ehdr.e_shstrndx;
632
633  if ((shnum == 0 || shstrndx == SHN_XINDEX)
634      && shoff != 0)
635    {
636      struct backtrace_view shdr_view;
637      const b_elf_shdr *shdr;
638
639      if (!backtrace_get_view (state, descriptor, shoff, sizeof shdr,
640			       error_callback, data, &shdr_view))
641	goto fail;
642
643      shdr = (const b_elf_shdr *) shdr_view.data;
644
645      if (shnum == 0)
646	shnum = shdr->sh_size;
647
648      if (shstrndx == SHN_XINDEX)
649	{
650	  shstrndx = shdr->sh_link;
651
652	  /* Versions of the GNU binutils between 2.12 and 2.18 did
653	     not handle objects with more than SHN_LORESERVE sections
654	     correctly.  All large section indexes were offset by
655	     0x100.  There is more information at
656	     http://sourceware.org/bugzilla/show_bug.cgi?id-5900 .
657	     Fortunately these object files are easy to detect, as the
658	     GNU binutils always put the section header string table
659	     near the end of the list of sections.  Thus if the
660	     section header string table index is larger than the
661	     number of sections, then we know we have to subtract
662	     0x100 to get the real section index.  */
663	  if (shstrndx >= shnum && shstrndx >= SHN_LORESERVE + 0x100)
664	    shstrndx -= 0x100;
665	}
666
667      backtrace_release_view (state, &shdr_view, error_callback, data);
668    }
669
670  /* To translate PC to file/line when using DWARF, we need to find
671     the .debug_info and .debug_line sections.  */
672
673  /* Read the section headers, skipping the first one.  */
674
675  if (!backtrace_get_view (state, descriptor, shoff + sizeof (b_elf_shdr),
676			   (shnum - 1) * sizeof (b_elf_shdr),
677			   error_callback, data, &shdrs_view))
678    goto fail;
679  shdrs_view_valid = 1;
680  shdrs = (const b_elf_shdr *) shdrs_view.data;
681
682  /* Read the section names.  */
683
684  shstrhdr = &shdrs[shstrndx - 1];
685  shstr_size = shstrhdr->sh_size;
686  shstr_off = shstrhdr->sh_offset;
687
688  if (!backtrace_get_view (state, descriptor, shstr_off, shstr_size,
689			   error_callback, data, &names_view))
690    goto fail;
691  names_view_valid = 1;
692  names = (const char *) names_view.data;
693
694  symtab_shndx = 0;
695  dynsym_shndx = 0;
696
697  memset (sections, 0, sizeof sections);
698
699  /* Look for the symbol table.  */
700  for (i = 1; i < shnum; ++i)
701    {
702      const b_elf_shdr *shdr;
703      unsigned int sh_name;
704      const char *name;
705      int j;
706
707      shdr = &shdrs[i - 1];
708
709      if (shdr->sh_type == SHT_SYMTAB)
710	symtab_shndx = i;
711      else if (shdr->sh_type == SHT_DYNSYM)
712	dynsym_shndx = i;
713
714      sh_name = shdr->sh_name;
715      if (sh_name >= shstr_size)
716	{
717	  error_callback (data, "ELF section name out of range", 0);
718	  goto fail;
719	}
720
721      name = names + sh_name;
722
723      for (j = 0; j < (int) DEBUG_MAX; ++j)
724	{
725	  if (strcmp (name, debug_section_names[j]) == 0)
726	    {
727	      sections[j].offset = shdr->sh_offset;
728	      sections[j].size = shdr->sh_size;
729	      break;
730	    }
731	}
732    }
733
734  if (symtab_shndx == 0)
735    symtab_shndx = dynsym_shndx;
736  if (symtab_shndx != 0)
737    {
738      const b_elf_shdr *symtab_shdr;
739      unsigned int strtab_shndx;
740      const b_elf_shdr *strtab_shdr;
741      struct elf_syminfo_data *sdata;
742
743      symtab_shdr = &shdrs[symtab_shndx - 1];
744      strtab_shndx = symtab_shdr->sh_link;
745      if (strtab_shndx >= shnum)
746	{
747	  error_callback (data,
748			  "ELF symbol table strtab link out of range", 0);
749	  goto fail;
750	}
751      strtab_shdr = &shdrs[strtab_shndx - 1];
752
753      if (!backtrace_get_view (state, descriptor, symtab_shdr->sh_offset,
754			       symtab_shdr->sh_size, error_callback, data,
755			       &symtab_view))
756	goto fail;
757      symtab_view_valid = 1;
758
759      if (!backtrace_get_view (state, descriptor, strtab_shdr->sh_offset,
760			       strtab_shdr->sh_size, error_callback, data,
761			       &strtab_view))
762	goto fail;
763      strtab_view_valid = 1;
764
765      sdata = ((struct elf_syminfo_data *)
766	       backtrace_alloc (state, sizeof *sdata, error_callback, data));
767      if (sdata == NULL)
768	goto fail;
769
770      if (!elf_initialize_syminfo (state, base_address,
771				   symtab_view.data, symtab_shdr->sh_size,
772				   strtab_view.data, strtab_shdr->sh_size,
773				   error_callback, data, sdata))
774	{
775	  backtrace_free (state, sdata, sizeof *sdata, error_callback, data);
776	  goto fail;
777	}
778
779      /* We no longer need the symbol table, but we hold on to the
780	 string table permanently.  */
781      backtrace_release_view (state, &symtab_view, error_callback, data);
782
783      *found_sym = 1;
784
785      elf_add_syminfo_data (state, sdata);
786    }
787
788  /* FIXME: Need to handle compressed debug sections.  */
789
790  backtrace_release_view (state, &shdrs_view, error_callback, data);
791  shdrs_view_valid = 0;
792  backtrace_release_view (state, &names_view, error_callback, data);
793  names_view_valid = 0;
794
795  /* Read all the debug sections in a single view, since they are
796     probably adjacent in the file.  We never release this view.  */
797
798  min_offset = 0;
799  max_offset = 0;
800  for (i = 0; i < (int) DEBUG_MAX; ++i)
801    {
802      off_t end;
803
804      if (sections[i].size == 0)
805	continue;
806      if (min_offset == 0 || sections[i].offset < min_offset)
807	min_offset = sections[i].offset;
808      end = sections[i].offset + sections[i].size;
809      if (end > max_offset)
810	max_offset = end;
811    }
812  if (min_offset == 0 || max_offset == 0)
813    {
814      if (!backtrace_close (descriptor, error_callback, data))
815	goto fail;
816      elf_state->strtab_view = strtab_view;
817      elf_state->strtab_view_valid = 1;
818      return 1;
819    }
820
821  if (!backtrace_get_view (state, descriptor, min_offset,
822			   max_offset - min_offset,
823			   error_callback, data, &debug_view))
824    goto fail;
825  debug_view_valid = 1;
826
827  /* We've read all we need from the executable.  */
828  if (!backtrace_close (descriptor, error_callback, data))
829    goto fail;
830  descriptor = -1;
831
832  for (i = 0; i < (int) DEBUG_MAX; ++i)
833    {
834      if (sections[i].size == 0)
835	sections[i].data = NULL;
836      else
837	sections[i].data = ((const unsigned char *) debug_view.data
838			    + (sections[i].offset - min_offset));
839    }
840
841  if (!backtrace_dwarf_add (state, base_address,
842			    sections[DEBUG_INFO].data,
843			    sections[DEBUG_INFO].size,
844			    sections[DEBUG_LINE].data,
845			    sections[DEBUG_LINE].size,
846			    sections[DEBUG_ABBREV].data,
847			    sections[DEBUG_ABBREV].size,
848			    sections[DEBUG_RANGES].data,
849			    sections[DEBUG_RANGES].size,
850			    sections[DEBUG_STR].data,
851			    sections[DEBUG_STR].size,
852			    ehdr.e_ident[EI_DATA] == ELFDATA2MSB,
853			    error_callback, data, fileline_fn))
854    goto fail;
855
856  *found_dwarf = 1;
857  elf_state->strtab_view = strtab_view;
858  elf_state->strtab_view_valid = 1;
859  elf_state->debug_view = debug_view;
860  elf_state->debug_view_valid = 1;
861
862  return 1;
863
864 fail:
865  if (shdrs_view_valid)
866    backtrace_release_view (state, &shdrs_view, error_callback, data);
867  if (names_view_valid)
868    backtrace_release_view (state, &names_view, error_callback, data);
869  if (symtab_view_valid)
870    backtrace_release_view (state, &symtab_view, error_callback, data);
871  if (strtab_view_valid)
872    backtrace_release_view (state, &strtab_view, error_callback, data);
873  if (debug_view_valid)
874    backtrace_release_view (state, &debug_view, error_callback, data);
875  if (descriptor != -1)
876    backtrace_close (descriptor, error_callback, data);
877  return 0;
878}
879
880/* Data passed to phdr_callback.  */
881
882struct phdr_data
883{
884  struct backtrace_state *state;
885  backtrace_error_callback error_callback;
886  void *data;
887  fileline *fileline_fn;
888  int *found_sym;
889  int *found_dwarf;
890  int exe_descriptor;
891};
892
893/* Shared lib iterator callback to load the debug info.  */
894
895static int
896#ifdef __i386__
897__attribute__ ((__force_align_arg_pointer__))
898#endif
899phdr_callback (const char *name, uintptr_t addr, void *pdata)
900{
901  struct phdr_data *pd = (struct phdr_data *) pdata;
902  int descriptor;
903  int does_not_exist;
904  fileline elf_fileline_fn;
905  int found_dwarf;
906
907  /* There is not much we can do if we don't have the module name,
908     unless executable is ET_DYN, where we expect the very first
909     phdr_callback to be for the PIE.  */
910  if (name == NULL || name[0] == '\0')
911    {
912      if (pd->exe_descriptor == -1)
913	return 0;
914      descriptor = pd->exe_descriptor;
915      pd->exe_descriptor = -1;
916    }
917  else
918    {
919      if (pd->exe_descriptor != -1)
920	{
921	  backtrace_close (pd->exe_descriptor, pd->error_callback, pd->data);
922	  pd->exe_descriptor = -1;
923	}
924
925      descriptor = backtrace_open (name, pd->error_callback,
926				   pd->data, &does_not_exist);
927      if (descriptor < 0)
928	return 0;
929    }
930
931  if (elf_add (pd->state, descriptor, addr, 1, pd->error_callback,
932	       pd->data, &elf_fileline_fn, pd->found_sym, &found_dwarf, 0))
933    {
934      if (found_dwarf)
935	{
936	  *pd->found_dwarf = 1;
937	  *pd->fileline_fn = elf_fileline_fn;
938	}
939    }
940
941  return 0;
942}
943
944/* Translate dl_iterate_phdr's args to ours.  */
945
946struct dl_iterate_data
947{
948  backtrace_so_callback *callback;
949  void *data;
950};
951
952static int
953dl_iterate_phdr_callback (struct dl_phdr_info *info,
954			  size_t size ATTRIBUTE_UNUSED,
955			  void *data)
956{
957  struct dl_iterate_data *dl_data = data;
958  return dl_data->callback (info->dlpi_name, info->dlpi_addr, dl_data->data);
959}
960
961static int
962dl_iterate_phdr_wrapper (void *iter_state ATTRIBUTE_UNUSED,
963			 backtrace_so_callback *func, void *data)
964{
965  struct dl_iterate_data dl_data;
966  dl_data.callback = phdr_callback;
967  dl_data.data = data;
968  return dl_iterate_phdr (dl_iterate_phdr_callback, &dl_data);
969}
970
971/* Initialize the backtrace data we need from an ELF executable.  At
972   the ELF level, all we need to do is find the debug info
973   sections.
974   Returns non-zero for success, zero for failure.  */
975
976int
977backtrace_initialize (struct backtrace_state *state, int descriptor,
978		      backtrace_error_callback error_callback,
979		      void *data, fileline *fileline_fn)
980{
981  int ret;
982  int found_sym;
983  int found_dwarf;
984  fileline elf_fileline_fn = elf_nodebug;
985  struct phdr_data pd;
986
987  state->target_state =
988    backtrace_alloc (state, sizeof (struct elf_state), error_callback, data);
989  if (state->target_state == NULL)
990    return 0;
991  memset (state->target_state, 0, sizeof (*state->target_state));
992
993  ret = elf_add (state, descriptor,
994		 state->base_address, state->base_address_set,
995		 error_callback, data, &elf_fileline_fn,
996		 &found_sym, &found_dwarf, 1);
997  if (!ret)
998    return 0;
999
1000  pd.state = state;
1001  pd.error_callback = error_callback;
1002  pd.data = data;
1003  pd.fileline_fn = &elf_fileline_fn;
1004  pd.found_sym = &found_sym;
1005  pd.found_dwarf = &found_dwarf;
1006  pd.exe_descriptor = ret < 0 ? descriptor : -1;
1007
1008  backtrace_so_iterator *iter_func = state->so_iterator;
1009  if (iter_func == NULL)
1010      iter_func = dl_iterate_phdr_wrapper;
1011  iter_func (state->iter_state, phdr_callback, (void *) &pd);
1012
1013  if (!state->threaded)
1014    {
1015      if (found_sym)
1016	state->syminfo_fn = elf_syminfo;
1017      else if (state->syminfo_fn == NULL)
1018	state->syminfo_fn = elf_nosyms;
1019    }
1020  else
1021    {
1022      if (found_sym)
1023	backtrace_atomic_store_pointer (&state->syminfo_fn, elf_syminfo);
1024      else
1025	(void) __sync_bool_compare_and_swap (&state->syminfo_fn, NULL,
1026					     elf_nosyms);
1027    }
1028
1029  if (!state->threaded)
1030    {
1031      if (state->fileline_fn == NULL || state->fileline_fn == elf_nodebug)
1032	*fileline_fn = elf_fileline_fn;
1033    }
1034  else
1035    {
1036      fileline current_fn;
1037
1038      current_fn = backtrace_atomic_load_pointer (&state->fileline_fn);
1039      if (current_fn == NULL || current_fn == elf_nodebug)
1040	*fileline_fn = elf_fileline_fn;
1041    }
1042
1043  return 1;
1044}
1045
1046/* Free ELF-specific state.
1047   I desperately want to name this backtrace_finalize.  */
1048
1049void
1050backtrace_destroy_target (struct backtrace_state *state,
1051                          backtrace_error_callback error_callback,
1052                          void *data)
1053{
1054  struct elf_syminfo_data *sdata = state->syminfo_data;
1055
1056  while (sdata != NULL)
1057    {
1058      struct elf_syminfo_data *next = sdata->next;
1059      backtrace_free (state, sdata->symbols,
1060                      sdata->count * sizeof (struct elf_symbol),
1061                      error_callback, data);
1062      backtrace_free (state, sdata, sizeof (*sdata), error_callback, data);
1063      sdata = next;
1064    }
1065
1066  struct elf_state *elf = state->target_state;
1067
1068  if (elf == NULL)
1069    return;
1070
1071  if (elf->strtab_view_valid)
1072    backtrace_release_view (state, &elf->strtab_view, error_callback, data);
1073  if (elf->debug_view_valid)
1074    backtrace_release_view (state, &elf->debug_view, error_callback, data);
1075
1076  backtrace_free (state, elf, sizeof (*elf), error_callback, data);
1077}
1078