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