Delete dead code.
[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   typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
59   typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
60   typedef Elf_Sym_Impl<ELFT> Elf_Sym;
61   typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
62   typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
63   typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
64   typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
65   typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
66   typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
67   typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
68   typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
69   typedef Elf_Versym_Impl<ELFT> Elf_Versym;
70   typedef Elf_Hash_Impl<ELFT> Elf_Hash;
71   typedef iterator_range<const Elf_Dyn *> Elf_Dyn_Range;
72   typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
73
74   /// \brief Archive files are 2 byte aligned, so we need this for
75   ///     PointerIntPair to work.
76   template <typename T>
77   class ArchivePointerTypeTraits {
78   public:
79     static inline const void *getAsVoidPointer(T *P) { return P; }
80     static inline T *getFromVoidPointer(const void *P) {
81       return static_cast<T *>(P);
82     }
83     enum { NumLowBitsAvailable = 1 };
84   };
85
86   typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
87
88   const uint8_t *base() const {
89     return reinterpret_cast<const uint8_t *>(Buf.data());
90   }
91
92 private:
93   typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
94   typedef DenseMap<unsigned, unsigned> IndexMap_t;
95
96   StringRef Buf;
97
98   const Elf_Ehdr *Header;
99   const Elf_Shdr *SectionHeaderTable = nullptr;
100   StringRef DotShstrtab;                    // Section header string table.
101   StringRef DotStrtab;                      // Symbol header string table.
102   const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
103   const Elf_Shdr *DotDynSymSec = nullptr;   // Dynamic symbol table section.
104
105   const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
106   DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
107
108   const Elf_Shdr *dot_gnu_version_sec = nullptr;   // .gnu.version
109   const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
110   const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
111
112   // Records for each version index the corresponding Verdef or Vernaux entry.
113   // This is filled the first time LoadVersionMap() is called.
114   class VersionMapEntry : public PointerIntPair<const void*, 1> {
115     public:
116     // If the integer is 0, this is an Elf_Verdef*.
117     // If the integer is 1, this is an Elf_Vernaux*.
118     VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
119     VersionMapEntry(const Elf_Verdef *verdef)
120         : PointerIntPair<const void*, 1>(verdef, 0) { }
121     VersionMapEntry(const Elf_Vernaux *vernaux)
122         : PointerIntPair<const void*, 1>(vernaux, 1) { }
123     bool isNull() const { return getPointer() == nullptr; }
124     bool isVerdef() const { return !isNull() && getInt() == 0; }
125     bool isVernaux() const { return !isNull() && getInt() == 1; }
126     const Elf_Verdef *getVerdef() const {
127       return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
128     }
129     const Elf_Vernaux *getVernaux() const {
130       return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
131     }
132   };
133   mutable SmallVector<VersionMapEntry, 16> VersionMap;
134   void LoadVersionDefs(const Elf_Shdr *sec) const;
135   void LoadVersionNeeds(const Elf_Shdr *ec) const;
136   void LoadVersionMap() const;
137
138 public:
139   template<typename T>
140   const T        *getEntry(uint32_t Section, uint32_t Entry) const;
141   template <typename T>
142   const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
143
144   const Elf_Shdr *getDotSymtabSec() const { return dot_symtab_sec; }
145   const Elf_Shdr *getDotDynSymSec() const { return DotDynSymSec; }
146
147   ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
148   ErrorOr<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
149
150   ErrorOr<StringRef> getSymbolVersion(StringRef StrTab, const Elf_Sym *Symb,
151                                       bool &IsDefault) const;
152   void VerifyStrTab(const Elf_Shdr *sh) const;
153
154   StringRef getRelocationTypeName(uint32_t Type) const;
155   void getRelocationTypeName(uint32_t Type,
156                              SmallVectorImpl<char> &Result) const;
157
158   /// \brief Get the symbol table section and symbol for a given relocation.
159   template <class RelT>
160   std::pair<const Elf_Shdr *, const Elf_Sym *>
161   getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
162
163   ELFFile(StringRef Object, std::error_code &EC);
164
165   bool isMipsELF64() const {
166     return Header->e_machine == ELF::EM_MIPS &&
167       Header->getFileClass() == ELF::ELFCLASS64;
168   }
169
170   bool isMips64EL() const {
171     return Header->e_machine == ELF::EM_MIPS &&
172       Header->getFileClass() == ELF::ELFCLASS64 &&
173       Header->getDataEncoding() == ELF::ELFDATA2LSB;
174   }
175
176   const Elf_Shdr *section_begin() const;
177   const Elf_Shdr *section_end() const;
178   Elf_Shdr_Range sections() const {
179     return make_range(section_begin(), section_end());
180   }
181
182   const Elf_Sym *symbol_begin(const Elf_Shdr *Sec) const {
183     if (!Sec)
184       return nullptr;
185     if (Sec->sh_entsize != sizeof(Elf_Sym))
186       report_fatal_error("Invalid symbol size");
187     return reinterpret_cast<const Elf_Sym *>(base() + Sec->sh_offset);
188   }
189   const Elf_Sym *symbol_end(const Elf_Shdr *Sec) const {
190     if (!Sec)
191       return nullptr;
192     uint64_t Size = Sec->sh_size;
193     if (Size % sizeof(Elf_Sym))
194       report_fatal_error("Invalid symbol table size");
195     return symbol_begin(Sec) + Size / sizeof(Elf_Sym);
196   }
197   Elf_Sym_Range symbols(const Elf_Shdr *Sec) const {
198     return make_range(symbol_begin(Sec), symbol_end(Sec));
199   }
200
201   const Elf_Sym *symbol_begin() const { return symbol_begin(dot_symtab_sec); }
202   const Elf_Sym *symbol_end() const { return symbol_end(dot_symtab_sec); }
203   Elf_Sym_Range symbols() const { return symbols(dot_symtab_sec); }
204
205   const Elf_Sym *dynamic_symbol_begin() const {
206     return symbol_begin(DotDynSymSec);
207   }
208   const Elf_Sym *dynamic_symbol_end() const { return symbol_end(DotDynSymSec); }
209   Elf_Sym_Range dynamic_symbols() const { return symbols(DotDynSymSec); }
210
211   typedef iterator_range<const Elf_Rela *> Elf_Rela_Range;
212
213   const Elf_Rela *rela_begin(const Elf_Shdr *sec) const {
214     if (sec->sh_entsize != sizeof(Elf_Rela))
215       report_fatal_error("Invalid relocation entry size");
216     return reinterpret_cast<const Elf_Rela *>(base() + sec->sh_offset);
217   }
218
219   const Elf_Rela *rela_end(const Elf_Shdr *sec) const {
220     uint64_t Size = sec->sh_size;
221     if (Size % sizeof(Elf_Rela))
222       report_fatal_error("Invalid relocation table size");
223     return rela_begin(sec) + Size / sizeof(Elf_Rela);
224   }
225
226   Elf_Rela_Range relas(const Elf_Shdr *Sec) const {
227     return make_range(rela_begin(Sec), rela_end(Sec));
228   }
229
230   const Elf_Rel *rel_begin(const Elf_Shdr *sec) const {
231     if (sec->sh_entsize != sizeof(Elf_Rel))
232       report_fatal_error("Invalid relocation entry size");
233     return reinterpret_cast<const Elf_Rel *>(base() + sec->sh_offset);
234   }
235
236   const Elf_Rel *rel_end(const Elf_Shdr *sec) const {
237     uint64_t Size = sec->sh_size;
238     if (Size % sizeof(Elf_Rel))
239       report_fatal_error("Invalid relocation table size");
240     return rel_begin(sec) + Size / sizeof(Elf_Rel);
241   }
242
243   typedef iterator_range<const Elf_Rel *> Elf_Rel_Range;
244   Elf_Rel_Range rels(const Elf_Shdr *Sec) const {
245     return make_range(rel_begin(Sec), rel_end(Sec));
246   }
247
248   /// \brief Iterate over program header table.
249   const Elf_Phdr *program_header_begin() const {
250     if (Header->e_phnum && Header->e_phentsize != sizeof(Elf_Phdr))
251       report_fatal_error("Invalid program header size");
252     return reinterpret_cast<const Elf_Phdr *>(base() + Header->e_phoff);
253   }
254
255   const Elf_Phdr *program_header_end() const {
256     return program_header_begin() + Header->e_phnum;
257   }
258
259   typedef iterator_range<const Elf_Phdr *> Elf_Phdr_Range;
260
261   const Elf_Phdr_Range program_headers() const {
262     return make_range(program_header_begin(), program_header_end());
263   }
264
265   uint64_t getNumSections() const;
266   uintX_t getStringTableIndex() const;
267   ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
268   const Elf_Ehdr *getHeader() const { return Header; }
269   ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
270   ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
271
272   const Elf_Sym *getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
273     return &*(symbol_begin(Sec) + Index);
274   }
275
276   ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
277   ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
278 };
279
280 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
281 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
282 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
283 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
284
285 // Iterate through the version definitions, and place each Elf_Verdef
286 // in the VersionMap according to its index.
287 template <class ELFT>
288 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
289   unsigned vd_size = sec->sh_size;  // Size of section in bytes
290   unsigned vd_count = sec->sh_info; // Number of Verdef entries
291   const char *sec_start = (const char*)base() + sec->sh_offset;
292   const char *sec_end = sec_start + vd_size;
293   // The first Verdef entry is at the start of the section.
294   const char *p = sec_start;
295   for (unsigned i = 0; i < vd_count; i++) {
296     if (p + sizeof(Elf_Verdef) > sec_end)
297       report_fatal_error("Section ended unexpectedly while scanning "
298                          "version definitions.");
299     const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
300     if (vd->vd_version != ELF::VER_DEF_CURRENT)
301       report_fatal_error("Unexpected verdef version");
302     size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
303     if (index >= VersionMap.size())
304       VersionMap.resize(index + 1);
305     VersionMap[index] = VersionMapEntry(vd);
306     p += vd->vd_next;
307   }
308 }
309
310 // Iterate through the versions needed section, and place each Elf_Vernaux
311 // in the VersionMap according to its index.
312 template <class ELFT>
313 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
314   unsigned vn_size = sec->sh_size;  // Size of section in bytes
315   unsigned vn_count = sec->sh_info; // Number of Verneed entries
316   const char *sec_start = (const char *)base() + sec->sh_offset;
317   const char *sec_end = sec_start + vn_size;
318   // The first Verneed entry is at the start of the section.
319   const char *p = sec_start;
320   for (unsigned i = 0; i < vn_count; i++) {
321     if (p + sizeof(Elf_Verneed) > sec_end)
322       report_fatal_error("Section ended unexpectedly while scanning "
323                          "version needed records.");
324     const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
325     if (vn->vn_version != ELF::VER_NEED_CURRENT)
326       report_fatal_error("Unexpected verneed version");
327     // Iterate through the Vernaux entries
328     const char *paux = p + vn->vn_aux;
329     for (unsigned j = 0; j < vn->vn_cnt; j++) {
330       if (paux + sizeof(Elf_Vernaux) > sec_end)
331         report_fatal_error("Section ended unexpected while scanning auxiliary "
332                            "version needed records.");
333       const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
334       size_t index = vna->vna_other & ELF::VERSYM_VERSION;
335       if (index >= VersionMap.size())
336         VersionMap.resize(index + 1);
337       VersionMap[index] = VersionMapEntry(vna);
338       paux += vna->vna_next;
339     }
340     p += vn->vn_next;
341   }
342 }
343
344 template <class ELFT>
345 void ELFFile<ELFT>::LoadVersionMap() const {
346   // If there is no dynamic symtab or version table, there is nothing to do.
347   if (!DotDynSymSec || !dot_gnu_version_sec)
348     return;
349
350   // Has the VersionMap already been loaded?
351   if (VersionMap.size() > 0)
352     return;
353
354   // The first two version indexes are reserved.
355   // Index 0 is LOCAL, index 1 is GLOBAL.
356   VersionMap.push_back(VersionMapEntry());
357   VersionMap.push_back(VersionMapEntry());
358
359   if (dot_gnu_version_d_sec)
360     LoadVersionDefs(dot_gnu_version_d_sec);
361
362   if (dot_gnu_version_r_sec)
363     LoadVersionNeeds(dot_gnu_version_r_sec);
364 }
365
366 template <class ELFT>
367 ELF::Elf64_Word
368 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
369   assert(symb->st_shndx == ELF::SHN_XINDEX);
370   return ExtendedSymbolTable.lookup(symb);
371 }
372
373 template <class ELFT>
374 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
375 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
376   uint32_t Index = symb->st_shndx;
377   if (Index == ELF::SHN_XINDEX)
378     return getSection(ExtendedSymbolTable.lookup(symb));
379   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
380     return nullptr;
381   return getSection(symb->st_shndx);
382 }
383
384 template <class ELFT>
385 ErrorOr<ArrayRef<uint8_t> >
386 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
387   if (Sec->sh_offset + Sec->sh_size > Buf.size())
388     return object_error::parse_failed;
389   const uint8_t *Start = base() + Sec->sh_offset;
390   return makeArrayRef(Start, Sec->sh_size);
391 }
392
393 template <class ELFT>
394 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
395   return getELFRelocationTypeName(Header->e_machine, Type);
396 }
397
398 template <class ELFT>
399 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
400                                           SmallVectorImpl<char> &Result) const {
401   if (!isMipsELF64()) {
402     StringRef Name = getRelocationTypeName(Type);
403     Result.append(Name.begin(), Name.end());
404   } else {
405     // The Mips N64 ABI allows up to three operations to be specified per
406     // relocation record. Unfortunately there's no easy way to test for the
407     // presence of N64 ELFs as they have no special flag that identifies them
408     // as being N64. We can safely assume at the moment that all Mips
409     // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
410     // information to disambiguate between old vs new ABIs.
411     uint8_t Type1 = (Type >> 0) & 0xFF;
412     uint8_t Type2 = (Type >> 8) & 0xFF;
413     uint8_t Type3 = (Type >> 16) & 0xFF;
414
415     // Concat all three relocation type names.
416     StringRef Name = getRelocationTypeName(Type1);
417     Result.append(Name.begin(), Name.end());
418
419     Name = getRelocationTypeName(Type2);
420     Result.append(1, '/');
421     Result.append(Name.begin(), Name.end());
422
423     Name = getRelocationTypeName(Type3);
424     Result.append(1, '/');
425     Result.append(Name.begin(), Name.end());
426   }
427 }
428
429 template <class ELFT>
430 template <class RelT>
431 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
432           const typename ELFFile<ELFT>::Elf_Sym *>
433 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
434   if (!Sec->sh_link)
435     return std::make_pair(nullptr, nullptr);
436   ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
437   if (std::error_code EC = SymTableOrErr.getError())
438     report_fatal_error(EC.message());
439   const Elf_Shdr *SymTable = *SymTableOrErr;
440   return std::make_pair(
441       SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
442 }
443
444 template <class ELFT>
445 uint64_t ELFFile<ELFT>::getNumSections() const {
446   assert(Header && "Header not initialized!");
447   if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
448     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
449     return SectionHeaderTable->sh_size;
450   }
451   return Header->e_shnum;
452 }
453
454 template <class ELFT>
455 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
456   if (Header->e_shnum == ELF::SHN_UNDEF) {
457     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
458       return SectionHeaderTable->sh_link;
459     if (Header->e_shstrndx >= getNumSections())
460       return 0;
461   }
462   return Header->e_shstrndx;
463 }
464
465 template <class ELFT>
466 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
467     : Buf(Object) {
468   const uint64_t FileSize = Buf.size();
469
470   if (sizeof(Elf_Ehdr) > FileSize) {
471     // File too short!
472     EC = object_error::parse_failed;
473     return;
474   }
475
476   Header = reinterpret_cast<const Elf_Ehdr *>(base());
477
478   if (Header->e_shoff == 0)
479     return;
480
481   const uint64_t SectionTableOffset = Header->e_shoff;
482
483   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
484     // Section header table goes past end of file!
485     EC = object_error::parse_failed;
486     return;
487   }
488
489   // The getNumSections() call below depends on SectionHeaderTable being set.
490   SectionHeaderTable =
491     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
492   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
493
494   if (SectionTableOffset + SectionTableSize > FileSize) {
495     // Section table goes past end of file!
496     EC = object_error::parse_failed;
497     return;
498   }
499
500   // Scan sections for special sections.
501
502   for (const Elf_Shdr &Sec : sections()) {
503     switch (Sec.sh_type) {
504     case ELF::SHT_SYMTAB_SHNDX:
505       if (SymbolTableSectionHeaderIndex) {
506         // More than one .symtab_shndx!
507         EC = object_error::parse_failed;
508         return;
509       }
510       SymbolTableSectionHeaderIndex = &Sec;
511       break;
512     case ELF::SHT_SYMTAB: {
513       if (dot_symtab_sec) {
514         // More than one .symtab!
515         EC = object_error::parse_failed;
516         return;
517       }
518       dot_symtab_sec = &Sec;
519       ErrorOr<StringRef> SymtabOrErr = getStringTableForSymtab(Sec);
520       if ((EC = SymtabOrErr.getError()))
521         return;
522       DotStrtab = *SymtabOrErr;
523     } break;
524     case ELF::SHT_DYNSYM: {
525       if (DotDynSymSec) {
526         // More than one .dynsym!
527         EC = object_error::parse_failed;
528         return;
529       }
530       DotDynSymSec = &Sec;
531       break;
532     }
533     case ELF::SHT_GNU_versym:
534       if (dot_gnu_version_sec != nullptr) {
535         // More than one .gnu.version section!
536         EC = object_error::parse_failed;
537         return;
538       }
539       dot_gnu_version_sec = &Sec;
540       break;
541     case ELF::SHT_GNU_verdef:
542       if (dot_gnu_version_d_sec != nullptr) {
543         // More than one .gnu.version_d section!
544         EC = object_error::parse_failed;
545         return;
546       }
547       dot_gnu_version_d_sec = &Sec;
548       break;
549     case ELF::SHT_GNU_verneed:
550       if (dot_gnu_version_r_sec != nullptr) {
551         // More than one .gnu.version_r section!
552         EC = object_error::parse_failed;
553         return;
554       }
555       dot_gnu_version_r_sec = &Sec;
556       break;
557     }
558   }
559
560   // Get string table sections.
561   uintX_t StringTableIndex = getStringTableIndex();
562   if (StringTableIndex) {
563     ErrorOr<const Elf_Shdr *> StrTabSecOrErr =
564         getSection(getStringTableIndex());
565     if ((EC = StrTabSecOrErr.getError()))
566       return;
567
568     ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
569     if ((EC = SymtabOrErr.getError()))
570       return;
571     DotShstrtab = *SymtabOrErr;
572   }
573
574   // Build symbol name side-mapping if there is one.
575   if (SymbolTableSectionHeaderIndex) {
576     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
577                                       SymbolTableSectionHeaderIndex->sh_offset);
578     for (const Elf_Sym &S : symbols()) {
579       if (*ShndxTable != ELF::SHN_UNDEF)
580         ExtendedSymbolTable[&S] = *ShndxTable;
581       ++ShndxTable;
582     }
583   }
584
585   EC = std::error_code();
586 }
587
588 template <class ELFT>
589 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
590   return VAddr < Phdr->p_vaddr;
591 }
592
593 template <class ELFT>
594 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
595   if (Header->e_shentsize != sizeof(Elf_Shdr))
596     report_fatal_error(
597         "Invalid section header entry size (e_shentsize) in ELF header");
598   return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
599 }
600
601 template <class ELFT>
602 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
603   return section_begin() + getNumSections();
604 }
605
606 template <class ELFT>
607 template <typename T>
608 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
609   ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
610   if (std::error_code EC = Sec.getError())
611     report_fatal_error(EC.message());
612   return getEntry<T>(*Sec, Entry);
613 }
614
615 template <class ELFT>
616 template <typename T>
617 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
618                                  uint32_t Entry) const {
619   return reinterpret_cast<const T *>(base() + Section->sh_offset +
620                                      (Entry * Section->sh_entsize));
621 }
622
623 template <class ELFT>
624 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
625 ELFFile<ELFT>::getSection(uint32_t Index) const {
626   assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
627   if (Index >= getNumSections())
628     return object_error::invalid_section_index;
629
630   return reinterpret_cast<const Elf_Shdr *>(
631       reinterpret_cast<const char *>(SectionHeaderTable) +
632       (Index * Header->e_shentsize));
633 }
634
635 template <class ELFT>
636 ErrorOr<StringRef>
637 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
638   if (Section->sh_type != ELF::SHT_STRTAB)
639     return object_error::parse_failed;
640   uint64_t Offset = Section->sh_offset;
641   uint64_t Size = Section->sh_size;
642   if (Offset + Size > Buf.size())
643     return object_error::parse_failed;
644   StringRef Data((const char *)base() + Section->sh_offset, Size);
645   if (Data[Size - 1] != '\0')
646     return object_error::string_table_non_null_end;
647   return Data;
648 }
649
650 template <class ELFT>
651 ErrorOr<StringRef>
652 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
653   if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
654     return object_error::parse_failed;
655   ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
656   if (std::error_code EC = SectionOrErr.getError())
657     return EC;
658   return getStringTable(*SectionOrErr);
659 }
660
661 template <class ELFT>
662 ErrorOr<StringRef>
663 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
664   uint32_t Offset = Section->sh_name;
665   if (Offset == 0)
666     return StringRef();
667   if (Offset >= DotShstrtab.size())
668     return object_error::parse_failed;
669   return StringRef(DotShstrtab.data() + Offset);
670 }
671
672 template <class ELFT>
673 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(StringRef StrTab,
674                                                    const Elf_Sym *symb,
675                                                    bool &IsDefault) const {
676   // This is a dynamic symbol. Look in the GNU symbol version table.
677   if (!dot_gnu_version_sec) {
678     // No version table.
679     IsDefault = false;
680     return StringRef("");
681   }
682
683   // Determine the position in the symbol table of this entry.
684   size_t entry_index =
685       (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
686        reinterpret_cast<uintptr_t>(base())) /
687       sizeof(Elf_Sym);
688
689   // Get the corresponding version index entry
690   const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
691   size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
692
693   // Special markers for unversioned symbols.
694   if (version_index == ELF::VER_NDX_LOCAL ||
695       version_index == ELF::VER_NDX_GLOBAL) {
696     IsDefault = false;
697     return StringRef("");
698   }
699
700   // Lookup this symbol in the version table
701   LoadVersionMap();
702   if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
703     return object_error::parse_failed;
704   const VersionMapEntry &entry = VersionMap[version_index];
705
706   // Get the version name string
707   size_t name_offset;
708   if (entry.isVerdef()) {
709     // The first Verdaux entry holds the name.
710     name_offset = entry.getVerdef()->getAux()->vda_name;
711   } else {
712     name_offset = entry.getVernaux()->vna_name;
713   }
714
715   // Set IsDefault
716   if (entry.isVerdef()) {
717     IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
718   } else {
719     IsDefault = false;
720   }
721
722   if (name_offset >= StrTab.size())
723     return object_error::parse_failed;
724   return StringRef(StrTab.data() + name_offset);
725 }
726
727 /// This function returns the hash value for a symbol in the .dynsym section
728 /// Name of the API remains consistent as specified in the libelf
729 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
730 static inline unsigned elf_hash(StringRef &symbolName) {
731   unsigned h = 0, g;
732   for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
733     h = (h << 4) + symbolName[i];
734     g = h & 0xf0000000L;
735     if (g != 0)
736       h ^= g >> 24;
737     h &= ~g;
738   }
739   return h;
740 }
741 } // end namespace object
742 } // end namespace llvm
743
744 #endif