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