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