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