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