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