ELF.h revision 263508
1//===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file declares the ELFFile template class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_OBJECT_ELF_H
15#define LLVM_OBJECT_ELF_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/Object/ELFTypes.h"
24#include "llvm/Object/Error.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/ELF.h"
27#include "llvm/Support/Endian.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/ErrorOr.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
32#include <algorithm>
33#include <limits>
34#include <utility>
35
36namespace llvm {
37namespace object {
38
39StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
40
41// Subclasses of ELFFile may need this for template instantiation
42inline std::pair<unsigned char, unsigned char>
43getElfArchType(MemoryBuffer *Object) {
44  if (Object->getBufferSize() < ELF::EI_NIDENT)
45    return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATANONE);
46  return std::make_pair((uint8_t) Object->getBufferStart()[ELF::EI_CLASS],
47                        (uint8_t) Object->getBufferStart()[ELF::EI_DATA]);
48}
49
50template <class ELFT>
51class ELFFile {
52public:
53  LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
54  typedef typename conditional<ELFT::Is64Bits,
55                               uint64_t, uint32_t>::type uintX_t;
56
57  /// \brief Iterate over constant sized entities.
58  template <class EntT>
59  class ELFEntityIterator {
60  public:
61    typedef ptrdiff_t difference_type;
62    typedef EntT value_type;
63    typedef std::random_access_iterator_tag iterator_category;
64    typedef value_type &reference;
65    typedef value_type *pointer;
66
67    /// \brief Default construct iterator.
68    ELFEntityIterator() : EntitySize(0), Current(0) {}
69    ELFEntityIterator(uintX_t EntSize, const char *Start)
70        : EntitySize(EntSize), Current(Start) {}
71
72    reference operator *() {
73      assert(Current && "Attempted to dereference an invalid iterator!");
74      return *reinterpret_cast<pointer>(Current);
75    }
76
77    pointer operator ->() {
78      assert(Current && "Attempted to dereference an invalid iterator!");
79      return reinterpret_cast<pointer>(Current);
80    }
81
82    bool operator ==(const ELFEntityIterator &Other) {
83      return Current == Other.Current;
84    }
85
86    bool operator !=(const ELFEntityIterator &Other) {
87      return !(*this == Other);
88    }
89
90    ELFEntityIterator &operator ++() {
91      assert(Current && "Attempted to increment an invalid iterator!");
92      Current += EntitySize;
93      return *this;
94    }
95
96    ELFEntityIterator operator ++(int) {
97      ELFEntityIterator Tmp = *this;
98      ++*this;
99      return Tmp;
100    }
101
102    ELFEntityIterator &operator =(const ELFEntityIterator &Other) {
103      EntitySize = Other.EntitySize;
104      Current = Other.Current;
105      return *this;
106    }
107
108    difference_type operator -(const ELFEntityIterator &Other) const {
109      assert(EntitySize == Other.EntitySize &&
110             "Subtracting iterators of different EntitySize!");
111      return (Current - Other.Current) / EntitySize;
112    }
113
114    const char *get() const { return Current; }
115
116    uintX_t getEntSize() const { return EntitySize; }
117
118  private:
119    uintX_t EntitySize;
120    const char *Current;
121  };
122
123  typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
124  typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
125  typedef Elf_Sym_Impl<ELFT> Elf_Sym;
126  typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
127  typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
128  typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
129  typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
130  typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
131  typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
132  typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
133  typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
134  typedef Elf_Versym_Impl<ELFT> Elf_Versym;
135  typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
136  typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
137  typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
138  typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
139
140  /// \brief Archive files are 2 byte aligned, so we need this for
141  ///     PointerIntPair to work.
142  template <typename T>
143  class ArchivePointerTypeTraits {
144  public:
145    static inline const void *getAsVoidPointer(T *P) { return P; }
146    static inline T *getFromVoidPointer(const void *P) {
147      return static_cast<T *>(P);
148    }
149    enum { NumLowBitsAvailable = 1 };
150  };
151
152  class Elf_Sym_Iter {
153  public:
154    typedef ptrdiff_t difference_type;
155    typedef const Elf_Sym value_type;
156    typedef std::random_access_iterator_tag iterator_category;
157    typedef value_type &reference;
158    typedef value_type *pointer;
159
160    /// \brief Default construct iterator.
161    Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
162    Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
163        : EntitySize(EntSize), Current(Start, IsDynamic) {}
164
165    reference operator*() {
166      assert(Current.getPointer() &&
167             "Attempted to dereference an invalid iterator!");
168      return *reinterpret_cast<pointer>(Current.getPointer());
169    }
170
171    pointer operator->() {
172      assert(Current.getPointer() &&
173             "Attempted to dereference an invalid iterator!");
174      return reinterpret_cast<pointer>(Current.getPointer());
175    }
176
177    bool operator==(const Elf_Sym_Iter &Other) {
178      return Current == Other.Current;
179    }
180
181    bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
182
183    Elf_Sym_Iter &operator++() {
184      assert(Current.getPointer() &&
185             "Attempted to increment an invalid iterator!");
186      Current.setPointer(Current.getPointer() + EntitySize);
187      return *this;
188    }
189
190    Elf_Sym_Iter operator++(int) {
191      Elf_Sym_Iter Tmp = *this;
192      ++*this;
193      return Tmp;
194    }
195
196    Elf_Sym_Iter operator+(difference_type Dist) {
197      assert(Current.getPointer() &&
198             "Attempted to increment an invalid iterator!");
199      Current.setPointer(Current.getPointer() + EntitySize * Dist);
200      return *this;
201    }
202
203    Elf_Sym_Iter &operator=(const Elf_Sym_Iter &Other) {
204      EntitySize = Other.EntitySize;
205      Current = Other.Current;
206      return *this;
207    }
208
209    difference_type operator-(const Elf_Sym_Iter &Other) const {
210      assert(EntitySize == Other.EntitySize &&
211             "Subtracting iterators of different EntitySize!");
212      return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
213    }
214
215    const char *get() const { return Current.getPointer(); }
216
217    bool isDynamic() const { return Current.getInt(); }
218
219    uintX_t getEntSize() const { return EntitySize; }
220
221  private:
222    uintX_t EntitySize;
223    PointerIntPair<const char *, 1, bool,
224                   ArchivePointerTypeTraits<const char> > Current;
225  };
226
227private:
228  typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
229  typedef DenseMap<unsigned, unsigned> IndexMap_t;
230
231  MemoryBuffer *Buf;
232
233  const uint8_t *base() const {
234    return reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
235  }
236
237  const Elf_Ehdr *Header;
238  const Elf_Shdr *SectionHeaderTable;
239  const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
240  const Elf_Shdr *dot_strtab_sec;   // Symbol header string table.
241  const Elf_Shdr *dot_symtab_sec;   // Symbol table section.
242
243  const Elf_Shdr *SymbolTableSectionHeaderIndex;
244  DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
245
246  const Elf_Shdr *dot_gnu_version_sec;   // .gnu.version
247  const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
248  const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
249
250  /// \brief Represents a region described by entries in the .dynamic table.
251  struct DynRegionInfo {
252    DynRegionInfo() : Addr(0), Size(0), EntSize(0) {}
253    /// \brief Address in current address space.
254    const void *Addr;
255    /// \brief Size in bytes of the region.
256    uintX_t Size;
257    /// \brief Size of each entity in the region.
258    uintX_t EntSize;
259  };
260
261  DynRegionInfo DynamicRegion;
262  DynRegionInfo DynHashRegion;
263  DynRegionInfo DynStrRegion;
264  DynRegionInfo DynSymRegion;
265
266  // Pointer to SONAME entry in dynamic string table
267  // This is set the first time getLoadName is called.
268  mutable const char *dt_soname;
269
270  // Records for each version index the corresponding Verdef or Vernaux entry.
271  // This is filled the first time LoadVersionMap() is called.
272  class VersionMapEntry : public PointerIntPair<const void*, 1> {
273    public:
274    // If the integer is 0, this is an Elf_Verdef*.
275    // If the integer is 1, this is an Elf_Vernaux*.
276    VersionMapEntry() : PointerIntPair<const void*, 1>(NULL, 0) { }
277    VersionMapEntry(const Elf_Verdef *verdef)
278        : PointerIntPair<const void*, 1>(verdef, 0) { }
279    VersionMapEntry(const Elf_Vernaux *vernaux)
280        : PointerIntPair<const void*, 1>(vernaux, 1) { }
281    bool isNull() const { return getPointer() == NULL; }
282    bool isVerdef() const { return !isNull() && getInt() == 0; }
283    bool isVernaux() const { return !isNull() && getInt() == 1; }
284    const Elf_Verdef *getVerdef() const {
285      return isVerdef() ? (const Elf_Verdef*)getPointer() : NULL;
286    }
287    const Elf_Vernaux *getVernaux() const {
288      return isVernaux() ? (const Elf_Vernaux*)getPointer() : NULL;
289    }
290  };
291  mutable SmallVector<VersionMapEntry, 16> VersionMap;
292  void LoadVersionDefs(const Elf_Shdr *sec) const;
293  void LoadVersionNeeds(const Elf_Shdr *ec) const;
294  void LoadVersionMap() const;
295
296public:
297  template<typename T>
298  const T        *getEntry(uint32_t Section, uint32_t Entry) const;
299  template <typename T>
300  const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
301  const char     *getString(uint32_t section, uint32_t offset) const;
302  const char     *getString(const Elf_Shdr *section, uint32_t offset) const;
303  const char *getDynamicString(uintX_t Offset) const;
304  ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
305                                      const Elf_Sym *Symb,
306                                      bool &IsDefault) const;
307  void VerifyStrTab(const Elf_Shdr *sh) const;
308
309  StringRef getRelocationTypeName(uint32_t Type) const;
310  void getRelocationTypeName(uint32_t Type,
311                             SmallVectorImpl<char> &Result) const;
312
313  /// \brief Get the symbol table section and symbol for a given relocation.
314  template <class RelT>
315  std::pair<const Elf_Shdr *, const Elf_Sym *>
316  getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
317
318  ELFFile(MemoryBuffer *Object, error_code &ec);
319
320  bool isMips64EL() const {
321    return Header->e_machine == ELF::EM_MIPS &&
322      Header->getFileClass() == ELF::ELFCLASS64 &&
323      Header->getDataEncoding() == ELF::ELFDATA2LSB;
324  }
325
326  Elf_Shdr_Iter begin_sections() const;
327  Elf_Shdr_Iter end_sections() const;
328
329  Elf_Sym_Iter begin_symbols() const;
330  Elf_Sym_Iter end_symbols() const;
331
332  Elf_Dyn_Iter begin_dynamic_table() const;
333  /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
334  /// the section size.
335  Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
336
337  Elf_Sym_Iter begin_dynamic_symbols() const {
338    if (DynSymRegion.Addr)
339      return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
340                          true);
341    return Elf_Sym_Iter(0, 0, true);
342  }
343
344  Elf_Sym_Iter end_dynamic_symbols() const {
345    if (DynSymRegion.Addr)
346      return Elf_Sym_Iter(DynSymRegion.EntSize,
347                          (const char *)DynSymRegion.Addr + DynSymRegion.Size,
348                          true);
349    return Elf_Sym_Iter(0, 0, true);
350  }
351
352  Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
353    return Elf_Rela_Iter(sec->sh_entsize,
354                         (const char *)(base() + sec->sh_offset));
355  }
356
357  Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
358    return Elf_Rela_Iter(
359        sec->sh_entsize,
360        (const char *)(base() + sec->sh_offset + sec->sh_size));
361  }
362
363  Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
364    return Elf_Rel_Iter(sec->sh_entsize,
365                        (const char *)(base() + sec->sh_offset));
366  }
367
368  Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
369    return Elf_Rel_Iter(sec->sh_entsize,
370                        (const char *)(base() + sec->sh_offset + sec->sh_size));
371  }
372
373  /// \brief Iterate over program header table.
374  typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
375
376  Elf_Phdr_Iter begin_program_headers() const {
377    return Elf_Phdr_Iter(Header->e_phentsize,
378                         (const char*)base() + Header->e_phoff);
379  }
380
381  Elf_Phdr_Iter end_program_headers() const {
382    return Elf_Phdr_Iter(Header->e_phentsize,
383                         (const char*)base() +
384                           Header->e_phoff +
385                           (Header->e_phnum * Header->e_phentsize));
386  }
387
388  uint64_t getNumSections() const;
389  uintX_t getStringTableIndex() const;
390  ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
391  const Elf_Ehdr *getHeader() const { return Header; }
392  const Elf_Shdr *getSection(const Elf_Sym *symb) const;
393  const Elf_Shdr *getSection(uint32_t Index) const;
394  const Elf_Sym *getSymbol(uint32_t index) const;
395
396  ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
397
398  /// \brief Get the name of \p Symb.
399  /// \param SymTab The symbol table section \p Symb is contained in.
400  /// \param Symb The symbol to get the name of.
401  ///
402  /// \p SymTab is used to lookup the string table to use to get the symbol's
403  /// name.
404  ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
405                                   const Elf_Sym *Symb) const;
406  ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
407  uint64_t getSymbolIndex(const Elf_Sym *sym) const;
408  ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
409  StringRef getLoadName() const;
410};
411
412// Use an alignment of 2 for the typedefs since that is the worst case for
413// ELF files in archives.
414typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
415typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
416typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
417typedef ELFFile<ELFType<support::big, 2, true> > ELF64BEFile;
418
419// Iterate through the version definitions, and place each Elf_Verdef
420// in the VersionMap according to its index.
421template <class ELFT>
422void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
423  unsigned vd_size = sec->sh_size;  // Size of section in bytes
424  unsigned vd_count = sec->sh_info; // Number of Verdef entries
425  const char *sec_start = (const char*)base() + sec->sh_offset;
426  const char *sec_end = sec_start + vd_size;
427  // The first Verdef entry is at the start of the section.
428  const char *p = sec_start;
429  for (unsigned i = 0; i < vd_count; i++) {
430    if (p + sizeof(Elf_Verdef) > sec_end)
431      report_fatal_error("Section ended unexpectedly while scanning "
432                         "version definitions.");
433    const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
434    if (vd->vd_version != ELF::VER_DEF_CURRENT)
435      report_fatal_error("Unexpected verdef version");
436    size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
437    if (index >= VersionMap.size())
438      VersionMap.resize(index + 1);
439    VersionMap[index] = VersionMapEntry(vd);
440    p += vd->vd_next;
441  }
442}
443
444// Iterate through the versions needed section, and place each Elf_Vernaux
445// in the VersionMap according to its index.
446template <class ELFT>
447void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
448  unsigned vn_size = sec->sh_size;  // Size of section in bytes
449  unsigned vn_count = sec->sh_info; // Number of Verneed entries
450  const char *sec_start = (const char *)base() + sec->sh_offset;
451  const char *sec_end = sec_start + vn_size;
452  // The first Verneed entry is at the start of the section.
453  const char *p = sec_start;
454  for (unsigned i = 0; i < vn_count; i++) {
455    if (p + sizeof(Elf_Verneed) > sec_end)
456      report_fatal_error("Section ended unexpectedly while scanning "
457                         "version needed records.");
458    const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
459    if (vn->vn_version != ELF::VER_NEED_CURRENT)
460      report_fatal_error("Unexpected verneed version");
461    // Iterate through the Vernaux entries
462    const char *paux = p + vn->vn_aux;
463    for (unsigned j = 0; j < vn->vn_cnt; j++) {
464      if (paux + sizeof(Elf_Vernaux) > sec_end)
465        report_fatal_error("Section ended unexpected while scanning auxiliary "
466                           "version needed records.");
467      const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
468      size_t index = vna->vna_other & ELF::VERSYM_VERSION;
469      if (index >= VersionMap.size())
470        VersionMap.resize(index + 1);
471      VersionMap[index] = VersionMapEntry(vna);
472      paux += vna->vna_next;
473    }
474    p += vn->vn_next;
475  }
476}
477
478template <class ELFT>
479void ELFFile<ELFT>::LoadVersionMap() const {
480  // If there is no dynamic symtab or version table, there is nothing to do.
481  if (DynSymRegion.Addr == NULL || dot_gnu_version_sec == NULL)
482    return;
483
484  // Has the VersionMap already been loaded?
485  if (VersionMap.size() > 0)
486    return;
487
488  // The first two version indexes are reserved.
489  // Index 0 is LOCAL, index 1 is GLOBAL.
490  VersionMap.push_back(VersionMapEntry());
491  VersionMap.push_back(VersionMapEntry());
492
493  if (dot_gnu_version_d_sec)
494    LoadVersionDefs(dot_gnu_version_d_sec);
495
496  if (dot_gnu_version_r_sec)
497    LoadVersionNeeds(dot_gnu_version_r_sec);
498}
499
500template <class ELFT>
501ELF::Elf64_Word ELFFile<ELFT>::getSymbolTableIndex(const Elf_Sym *symb) const {
502  if (symb->st_shndx == ELF::SHN_XINDEX)
503    return ExtendedSymbolTable.lookup(symb);
504  return symb->st_shndx;
505}
506
507template <class ELFT>
508const typename ELFFile<ELFT>::Elf_Shdr *
509ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
510  if (symb->st_shndx == ELF::SHN_XINDEX)
511    return getSection(ExtendedSymbolTable.lookup(symb));
512  if (symb->st_shndx >= ELF::SHN_LORESERVE)
513    return 0;
514  return getSection(symb->st_shndx);
515}
516
517template <class ELFT>
518const typename ELFFile<ELFT>::Elf_Sym *
519ELFFile<ELFT>::getSymbol(uint32_t Index) const {
520  return &*(begin_symbols() + Index);
521}
522
523template <class ELFT>
524ErrorOr<ArrayRef<uint8_t> >
525ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
526  if (Sec->sh_offset + Sec->sh_size > Buf->getBufferSize())
527    return object_error::parse_failed;
528  const uint8_t *Start = base() + Sec->sh_offset;
529  return ArrayRef<uint8_t>(Start, Sec->sh_size);
530}
531
532template <class ELFT>
533StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
534  return getELFRelocationTypeName(Header->e_machine, Type);
535}
536
537template <class ELFT>
538void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
539                                          SmallVectorImpl<char> &Result) const {
540  if (!isMips64EL()) {
541    StringRef Name = getRelocationTypeName(Type);
542    Result.append(Name.begin(), Name.end());
543  } else {
544    uint8_t Type1 = (Type >> 0) & 0xFF;
545    uint8_t Type2 = (Type >> 8) & 0xFF;
546    uint8_t Type3 = (Type >> 16) & 0xFF;
547
548    // Concat all three relocation type names.
549    StringRef Name = getRelocationTypeName(Type1);
550    Result.append(Name.begin(), Name.end());
551
552    Name = getRelocationTypeName(Type2);
553    Result.append(1, '/');
554    Result.append(Name.begin(), Name.end());
555
556    Name = getRelocationTypeName(Type3);
557    Result.append(1, '/');
558    Result.append(Name.begin(), Name.end());
559  }
560}
561
562template <class ELFT>
563template <class RelT>
564std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
565          const typename ELFFile<ELFT>::Elf_Sym *>
566ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
567  if (!Sec->sh_link)
568    return std::make_pair((const Elf_Shdr *)0, (const Elf_Sym *)0);
569  const Elf_Shdr *SymTable = getSection(Sec->sh_link);
570  return std::make_pair(
571      SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
572}
573
574// Verify that the last byte in the string table in a null.
575template <class ELFT>
576void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
577  const char *strtab = (const char *)base() + sh->sh_offset;
578  if (strtab[sh->sh_size - 1] != 0)
579    // FIXME: Proper error handling.
580    report_fatal_error("String table must end with a null terminator!");
581}
582
583template <class ELFT>
584uint64_t ELFFile<ELFT>::getNumSections() const {
585  assert(Header && "Header not initialized!");
586  if (Header->e_shnum == ELF::SHN_UNDEF) {
587    assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
588    return SectionHeaderTable->sh_size;
589  }
590  return Header->e_shnum;
591}
592
593template <class ELFT>
594typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
595  if (Header->e_shnum == ELF::SHN_UNDEF) {
596    if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
597      return SectionHeaderTable->sh_link;
598    if (Header->e_shstrndx >= getNumSections())
599      return 0;
600  }
601  return Header->e_shstrndx;
602}
603
604template <class ELFT>
605ELFFile<ELFT>::ELFFile(MemoryBuffer *Object, error_code &ec)
606    : Buf(Object),
607      SectionHeaderTable(0),
608      dot_shstrtab_sec(0),
609      dot_strtab_sec(0),
610      dot_symtab_sec(0),
611      SymbolTableSectionHeaderIndex(0),
612      dot_gnu_version_sec(0),
613      dot_gnu_version_r_sec(0),
614      dot_gnu_version_d_sec(0),
615      dt_soname(0) {
616  const uint64_t FileSize = Buf->getBufferSize();
617
618  if (sizeof(Elf_Ehdr) > FileSize)
619    // FIXME: Proper error handling.
620    report_fatal_error("File too short!");
621
622  Header = reinterpret_cast<const Elf_Ehdr *>(base());
623
624  if (Header->e_shoff == 0)
625    return;
626
627  const uint64_t SectionTableOffset = Header->e_shoff;
628
629  if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
630    // FIXME: Proper error handling.
631    report_fatal_error("Section header table goes past end of file!");
632
633  // The getNumSections() call below depends on SectionHeaderTable being set.
634  SectionHeaderTable =
635    reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
636  const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
637
638  if (SectionTableOffset + SectionTableSize > FileSize)
639    // FIXME: Proper error handling.
640    report_fatal_error("Section table goes past end of file!");
641
642  // Scan sections for special sections.
643
644  for (Elf_Shdr_Iter SecI = begin_sections(), SecE = end_sections();
645       SecI != SecE; ++SecI) {
646    switch (SecI->sh_type) {
647    case ELF::SHT_SYMTAB_SHNDX:
648      if (SymbolTableSectionHeaderIndex)
649        // FIXME: Proper error handling.
650        report_fatal_error("More than one .symtab_shndx!");
651      SymbolTableSectionHeaderIndex = &*SecI;
652      break;
653    case ELF::SHT_SYMTAB:
654      if (dot_symtab_sec)
655        // FIXME: Proper error handling.
656        report_fatal_error("More than one .symtab!");
657      dot_symtab_sec = &*SecI;
658      dot_strtab_sec = getSection(SecI->sh_link);
659      break;
660    case ELF::SHT_DYNSYM: {
661      if (DynSymRegion.Addr)
662        // FIXME: Proper error handling.
663        report_fatal_error("More than one .dynsym!");
664      DynSymRegion.Addr = base() + SecI->sh_offset;
665      DynSymRegion.Size = SecI->sh_size;
666      DynSymRegion.EntSize = SecI->sh_entsize;
667      const Elf_Shdr *DynStr = getSection(SecI->sh_link);
668      DynStrRegion.Addr = base() + DynStr->sh_offset;
669      DynStrRegion.Size = DynStr->sh_size;
670      DynStrRegion.EntSize = DynStr->sh_entsize;
671      break;
672    }
673    case ELF::SHT_DYNAMIC:
674      if (DynamicRegion.Addr)
675        // FIXME: Proper error handling.
676        report_fatal_error("More than one .dynamic!");
677      DynamicRegion.Addr = base() + SecI->sh_offset;
678      DynamicRegion.Size = SecI->sh_size;
679      DynamicRegion.EntSize = SecI->sh_entsize;
680      break;
681    case ELF::SHT_GNU_versym:
682      if (dot_gnu_version_sec != NULL)
683        // FIXME: Proper error handling.
684        report_fatal_error("More than one .gnu.version section!");
685      dot_gnu_version_sec = &*SecI;
686      break;
687    case ELF::SHT_GNU_verdef:
688      if (dot_gnu_version_d_sec != NULL)
689        // FIXME: Proper error handling.
690        report_fatal_error("More than one .gnu.version_d section!");
691      dot_gnu_version_d_sec = &*SecI;
692      break;
693    case ELF::SHT_GNU_verneed:
694      if (dot_gnu_version_r_sec != NULL)
695        // FIXME: Proper error handling.
696        report_fatal_error("More than one .gnu.version_r section!");
697      dot_gnu_version_r_sec = &*SecI;
698      break;
699    }
700  }
701
702  // Get string table sections.
703  dot_shstrtab_sec = getSection(getStringTableIndex());
704  if (dot_shstrtab_sec) {
705    // Verify that the last byte in the string table in a null.
706    VerifyStrTab(dot_shstrtab_sec);
707  }
708
709  // Build symbol name side-mapping if there is one.
710  if (SymbolTableSectionHeaderIndex) {
711    const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
712                                      SymbolTableSectionHeaderIndex->sh_offset);
713    for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
714         ++SI) {
715      if (*ShndxTable != ELF::SHN_UNDEF)
716        ExtendedSymbolTable[&*SI] = *ShndxTable;
717      ++ShndxTable;
718    }
719  }
720
721  // Scan program headers.
722  for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
723                     PhdrE = end_program_headers();
724       PhdrI != PhdrE; ++PhdrI) {
725    if (PhdrI->p_type == ELF::PT_DYNAMIC) {
726      DynamicRegion.Addr = base() + PhdrI->p_offset;
727      DynamicRegion.Size = PhdrI->p_filesz;
728      DynamicRegion.EntSize = sizeof(Elf_Dyn);
729      break;
730    }
731  }
732
733  ec = error_code::success();
734}
735
736// Get the symbol table index in the symtab section given a symbol
737template <class ELFT>
738uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
739  uintptr_t SymLoc = uintptr_t(Sym);
740  uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
741  assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
742  uint64_t SymOffset = SymLoc - SymTabLoc;
743  assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
744         "Symbol not multiple of symbol size!");
745  return SymOffset / dot_symtab_sec->sh_entsize;
746}
747
748template <class ELFT>
749typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
750  return Elf_Shdr_Iter(Header->e_shentsize,
751                       (const char *)base() + Header->e_shoff);
752}
753
754template <class ELFT>
755typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
756  return Elf_Shdr_Iter(Header->e_shentsize,
757                       (const char *)base() + Header->e_shoff +
758                           (getNumSections() * Header->e_shentsize));
759}
760
761template <class ELFT>
762typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
763  if (!dot_symtab_sec)
764    return Elf_Sym_Iter(0, 0, false);
765  return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
766                      (const char *)base() + dot_symtab_sec->sh_offset, false);
767}
768
769template <class ELFT>
770typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
771  if (!dot_symtab_sec)
772    return Elf_Sym_Iter(0, 0, false);
773  return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
774                      (const char *)base() + dot_symtab_sec->sh_offset +
775                          dot_symtab_sec->sh_size,
776                      false);
777}
778
779template <class ELFT>
780typename ELFFile<ELFT>::Elf_Dyn_Iter
781ELFFile<ELFT>::begin_dynamic_table() const {
782  if (DynamicRegion.Addr)
783    return Elf_Dyn_Iter(DynamicRegion.EntSize,
784                        (const char *)DynamicRegion.Addr);
785  return Elf_Dyn_Iter(0, 0);
786}
787
788template <class ELFT>
789typename ELFFile<ELFT>::Elf_Dyn_Iter
790ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
791  if (!DynamicRegion.Addr)
792    return Elf_Dyn_Iter(0, 0);
793  Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
794                    (const char *)DynamicRegion.Addr + DynamicRegion.Size);
795
796  if (NULLEnd) {
797    Elf_Dyn_Iter Start = begin_dynamic_table();
798    while (Start != Ret && Start->getTag() != ELF::DT_NULL)
799      ++Start;
800
801    // Include the DT_NULL.
802    if (Start != Ret)
803      ++Start;
804    Ret = Start;
805  }
806  return Ret;
807}
808
809template <class ELFT>
810StringRef ELFFile<ELFT>::getLoadName() const {
811  if (!dt_soname) {
812    // Find the DT_SONAME entry
813    Elf_Dyn_Iter it = begin_dynamic_table();
814    Elf_Dyn_Iter ie = end_dynamic_table();
815    while (it != ie && it->getTag() != ELF::DT_SONAME)
816      ++it;
817
818    if (it != ie) {
819      dt_soname = getDynamicString(it->getVal());
820    } else {
821      dt_soname = "";
822    }
823  }
824  return dt_soname;
825}
826
827template <class ELFT>
828template <typename T>
829const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
830  return getEntry<T>(getSection(Section), Entry);
831}
832
833template <class ELFT>
834template <typename T>
835const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
836                                 uint32_t Entry) const {
837  return reinterpret_cast<const T *>(base() + Section->sh_offset +
838                                     (Entry * Section->sh_entsize));
839}
840
841template <class ELFT>
842const typename ELFFile<ELFT>::Elf_Shdr *
843ELFFile<ELFT>::getSection(uint32_t index) const {
844  if (index == 0)
845    return 0;
846  if (!SectionHeaderTable || index >= getNumSections())
847    // FIXME: Proper error handling.
848    report_fatal_error("Invalid section index!");
849
850  return reinterpret_cast<const Elf_Shdr *>(
851         reinterpret_cast<const char *>(SectionHeaderTable)
852         + (index * Header->e_shentsize));
853}
854
855template <class ELFT>
856const char *ELFFile<ELFT>::getString(uint32_t section,
857                                     ELF::Elf32_Word offset) const {
858  return getString(getSection(section), offset);
859}
860
861template <class ELFT>
862const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
863                                     ELF::Elf32_Word offset) const {
864  assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
865  if (offset >= section->sh_size)
866    // FIXME: Proper error handling.
867    report_fatal_error("Symbol name offset outside of string table!");
868  return (const char *)base() + section->sh_offset + offset;
869}
870
871template <class ELFT>
872const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
873  if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
874    return 0;
875  return (const char *)DynStrRegion.Addr + Offset;
876}
877
878template <class ELFT>
879ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
880  if (!Sym.isDynamic())
881    return getSymbolName(dot_symtab_sec, &*Sym);
882
883  if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
884    return object_error::parse_failed;
885  return StringRef(getDynamicString(Sym->st_name));
886}
887
888template <class ELFT>
889ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
890                                                const Elf_Sym *Symb) const {
891  if (Symb->st_name == 0) {
892    const Elf_Shdr *ContainingSec = getSection(Symb);
893    if (ContainingSec)
894      return getSectionName(ContainingSec);
895  }
896
897  const Elf_Shdr *StrTab = getSection(Section->sh_link);
898  if (Symb->st_name >= StrTab->sh_size)
899    return object_error::parse_failed;
900  return StringRef(getString(StrTab, Symb->st_name));
901}
902
903template <class ELFT>
904ErrorOr<StringRef>
905ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
906  if (Section->sh_name >= dot_shstrtab_sec->sh_size)
907    return object_error::parse_failed;
908  return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
909}
910
911template <class ELFT>
912ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
913                                                   const Elf_Sym *symb,
914                                                   bool &IsDefault) const {
915  // Handle non-dynamic symbols.
916  if (section != DynSymRegion.Addr && section != 0) {
917    // Non-dynamic symbols can have versions in their names
918    // A name of the form 'foo@V1' indicates version 'V1', non-default.
919    // A name of the form 'foo@@V2' indicates version 'V2', default version.
920    ErrorOr<StringRef> SymName = getSymbolName(section, symb);
921    if (!SymName)
922      return SymName;
923    StringRef Name = *SymName;
924    size_t atpos = Name.find('@');
925    if (atpos == StringRef::npos) {
926      IsDefault = false;
927      return StringRef("");
928    }
929    ++atpos;
930    if (atpos < Name.size() && Name[atpos] == '@') {
931      IsDefault = true;
932      ++atpos;
933    } else {
934      IsDefault = false;
935    }
936    return Name.substr(atpos);
937  }
938
939  // This is a dynamic symbol. Look in the GNU symbol version table.
940  if (dot_gnu_version_sec == NULL) {
941    // No version table.
942    IsDefault = false;
943    return StringRef("");
944  }
945
946  // Determine the position in the symbol table of this entry.
947  size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
948                       DynSymRegion.EntSize;
949
950  // Get the corresponding version index entry
951  const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
952  size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
953
954  // Special markers for unversioned symbols.
955  if (version_index == ELF::VER_NDX_LOCAL ||
956      version_index == ELF::VER_NDX_GLOBAL) {
957    IsDefault = false;
958    return StringRef("");
959  }
960
961  // Lookup this symbol in the version table
962  LoadVersionMap();
963  if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
964    return object_error::parse_failed;
965  const VersionMapEntry &entry = VersionMap[version_index];
966
967  // Get the version name string
968  size_t name_offset;
969  if (entry.isVerdef()) {
970    // The first Verdaux entry holds the name.
971    name_offset = entry.getVerdef()->getAux()->vda_name;
972  } else {
973    name_offset = entry.getVernaux()->vna_name;
974  }
975
976  // Set IsDefault
977  if (entry.isVerdef()) {
978    IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
979  } else {
980    IsDefault = false;
981  }
982
983  if (name_offset >= DynStrRegion.Size)
984    return object_error::parse_failed;
985  return StringRef(getDynamicString(name_offset));
986}
987
988/// This function returns the hash value for a symbol in the .dynsym section
989/// Name of the API remains consistent as specified in the libelf
990/// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
991static inline unsigned elf_hash(StringRef &symbolName) {
992  unsigned h = 0, g;
993  for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
994    h = (h << 4) + symbolName[i];
995    g = h & 0xf0000000L;
996    if (g != 0)
997      h ^= g >> 24;
998    h &= ~g;
999  }
1000  return h;
1001}
1002} // end namespace object
1003} // end namespace llvm
1004
1005#endif
1006