llvm/test/CodeGen/ARM/fnattr-trap.ll: Add -mtriple, to appease targeting *-win32.
[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 = nullptr;
174   StringRef DotShstrtab;                    // Section header string table.
175   StringRef DotStrtab;                      // Symbol header string table.
176   const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
177   StringRef DynSymStrTab;                   // Dynnamic symbol string table.
178   const Elf_Shdr *DotDynSymSec = nullptr;   // Dynamic symbol table section.
179
180   const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
181   DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
182
183   const Elf_Shdr *dot_gnu_version_sec = nullptr;   // .gnu.version
184   const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
185   const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
186
187   /// \brief Represents a region described by entries in the .dynamic table.
188   struct DynRegionInfo {
189     DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
190     /// \brief Address in current address space.
191     const void *Addr;
192     /// \brief Size in bytes of the region.
193     uintX_t Size;
194     /// \brief Size of each entity in the region.
195     uintX_t EntSize;
196   };
197
198   DynRegionInfo DynamicRegion;
199   DynRegionInfo DynHashRegion;
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 = nullptr;
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 (!DotDynSymSec)
288       return nullptr;
289     if (DotDynSymSec->sh_entsize != sizeof(Elf_Sym))
290       report_fatal_error("Invalid symbol size");
291     return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset);
292   }
293
294   const Elf_Sym *dynamic_symbol_end() const {
295     if (!DotDynSymSec)
296       return nullptr;
297     return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset +
298                                              DotDynSymSec->sh_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 (!DotDynSymSec || !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) {
568   const uint64_t FileSize = Buf.size();
569
570   if (sizeof(Elf_Ehdr) > FileSize) {
571     // File too short!
572     EC = object_error::parse_failed;
573     return;
574   }
575
576   Header = reinterpret_cast<const Elf_Ehdr *>(base());
577
578   if (Header->e_shoff == 0)
579     return;
580
581   const uint64_t SectionTableOffset = Header->e_shoff;
582
583   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
584     // Section header table goes past end of file!
585     EC = object_error::parse_failed;
586     return;
587   }
588
589   // The getNumSections() call below depends on SectionHeaderTable being set.
590   SectionHeaderTable =
591     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
592   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
593
594   if (SectionTableOffset + SectionTableSize > FileSize) {
595     // Section table goes past end of file!
596     EC = object_error::parse_failed;
597     return;
598   }
599
600   // Scan sections for special sections.
601
602   for (const Elf_Shdr &Sec : sections()) {
603     switch (Sec.sh_type) {
604     case ELF::SHT_SYMTAB_SHNDX:
605       if (SymbolTableSectionHeaderIndex) {
606         // More than one .symtab_shndx!
607         EC = object_error::parse_failed;
608         return;
609       }
610       SymbolTableSectionHeaderIndex = &Sec;
611       break;
612     case ELF::SHT_SYMTAB: {
613       if (dot_symtab_sec) {
614         // More than one .symtab!
615         EC = object_error::parse_failed;
616         return;
617       }
618       dot_symtab_sec = &Sec;
619       ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
620       if ((EC = SectionOrErr.getError()))
621         return;
622       ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
623       if ((EC = SymtabOrErr.getError()))
624         return;
625       DotStrtab = *SymtabOrErr;
626     } break;
627     case ELF::SHT_DYNSYM: {
628       if (DotDynSymSec) {
629         // More than one .dynsym!
630         EC = object_error::parse_failed;
631         return;
632       }
633       DotDynSymSec = &Sec;
634       ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
635       if ((EC = SectionOrErr.getError()))
636         return;
637       ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
638       if ((EC = SymtabOrErr.getError()))
639         return;
640       DynSymStrTab = *SymtabOrErr;
641       break;
642     }
643     case ELF::SHT_DYNAMIC:
644       if (DynamicRegion.Addr) {
645         // More than one .dynamic!
646         EC = object_error::parse_failed;
647         return;
648       }
649       DynamicRegion.Addr = base() + Sec.sh_offset;
650       DynamicRegion.Size = Sec.sh_size;
651       DynamicRegion.EntSize = Sec.sh_entsize;
652       break;
653     case ELF::SHT_GNU_versym:
654       if (dot_gnu_version_sec != nullptr) {
655         // More than one .gnu.version section!
656         EC = object_error::parse_failed;
657         return;
658       }
659       dot_gnu_version_sec = &Sec;
660       break;
661     case ELF::SHT_GNU_verdef:
662       if (dot_gnu_version_d_sec != nullptr) {
663         // More than one .gnu.version_d section!
664         EC = object_error::parse_failed;
665         return;
666       }
667       dot_gnu_version_d_sec = &Sec;
668       break;
669     case ELF::SHT_GNU_verneed:
670       if (dot_gnu_version_r_sec != nullptr) {
671         // More than one .gnu.version_r section!
672         EC = object_error::parse_failed;
673         return;
674       }
675       dot_gnu_version_r_sec = &Sec;
676       break;
677     }
678   }
679
680   // Get string table sections.
681   ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(getStringTableIndex());
682   if ((EC = StrTabSecOrErr.getError()))
683     return;
684
685   ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
686   if ((EC = SymtabOrErr.getError()))
687     return;
688   DotShstrtab = *SymtabOrErr;
689
690   // Build symbol name side-mapping if there is one.
691   if (SymbolTableSectionHeaderIndex) {
692     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
693                                       SymbolTableSectionHeaderIndex->sh_offset);
694     for (const Elf_Sym &S : symbols()) {
695       if (*ShndxTable != ELF::SHN_UNDEF)
696         ExtendedSymbolTable[&S] = *ShndxTable;
697       ++ShndxTable;
698     }
699   }
700
701   // Scan program headers.
702   for (Elf_Phdr_Iter PhdrI = program_header_begin(),
703                      PhdrE = program_header_end();
704        PhdrI != PhdrE; ++PhdrI) {
705     if (PhdrI->p_type == ELF::PT_DYNAMIC) {
706       DynamicRegion.Addr = base() + PhdrI->p_offset;
707       DynamicRegion.Size = PhdrI->p_filesz;
708       DynamicRegion.EntSize = sizeof(Elf_Dyn);
709       break;
710     }
711   }
712
713   // Scan dynamic table.
714   for (Elf_Dyn_Iter DynI = dynamic_table_begin(), DynE = dynamic_table_end();
715        DynI != DynE; ++DynI) {
716     switch (DynI->d_tag) {
717     case ELF::DT_RELA: {
718       uint64_t VBase = 0;
719       const uint8_t *FBase = nullptr;
720       for (Elf_Phdr_Iter PhdrI = program_header_begin(),
721                          PhdrE = program_header_end();
722            PhdrI != PhdrE; ++PhdrI) {
723         if (PhdrI->p_type != ELF::PT_LOAD)
724           continue;
725         if (DynI->getPtr() >= PhdrI->p_vaddr &&
726             DynI->getPtr() < PhdrI->p_vaddr + PhdrI->p_memsz) {
727           VBase = PhdrI->p_vaddr;
728           FBase = base() + PhdrI->p_offset;
729           break;
730         }
731       }
732       if (!VBase)
733         return;
734       DynRelaRegion.Addr = FBase + DynI->getPtr() - VBase;
735       break;
736     }
737     case ELF::DT_RELASZ:
738       DynRelaRegion.Size = DynI->getVal();
739       break;
740     case ELF::DT_RELAENT:
741       DynRelaRegion.EntSize = DynI->getVal();
742     }
743   }
744
745   EC = std::error_code();
746 }
747
748 // Get the symbol table index in the symtab section given a symbol
749 template <class ELFT>
750 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
751   uintptr_t SymLoc = uintptr_t(Sym);
752   uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
753   assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
754   uint64_t SymOffset = SymLoc - SymTabLoc;
755   assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
756          "Symbol not multiple of symbol size!");
757   return SymOffset / dot_symtab_sec->sh_entsize;
758 }
759
760 template <class ELFT>
761 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
762   if (Header->e_shentsize != sizeof(Elf_Shdr))
763     report_fatal_error(
764         "Invalid section header entry size (e_shentsize) in ELF header");
765   return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
766 }
767
768 template <class ELFT>
769 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
770   return section_begin() + getNumSections();
771 }
772
773 template <class ELFT>
774 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
775   if (!dot_symtab_sec)
776     return nullptr;
777   if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
778     report_fatal_error("Invalid symbol size");
779   return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
780 }
781
782 template <class ELFT>
783 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
784   if (!dot_symtab_sec)
785     return nullptr;
786   return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
787                                            dot_symtab_sec->sh_size);
788 }
789
790 template <class ELFT>
791 typename ELFFile<ELFT>::Elf_Dyn_Iter
792 ELFFile<ELFT>::dynamic_table_begin() const {
793   if (DynamicRegion.Addr)
794     return Elf_Dyn_Iter(DynamicRegion.EntSize,
795                         (const char *)DynamicRegion.Addr);
796   return Elf_Dyn_Iter(0, nullptr);
797 }
798
799 template <class ELFT>
800 typename ELFFile<ELFT>::Elf_Dyn_Iter
801 ELFFile<ELFT>::dynamic_table_end(bool NULLEnd) const {
802   if (!DynamicRegion.Addr)
803     return Elf_Dyn_Iter(0, nullptr);
804   Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
805                     (const char *)DynamicRegion.Addr + DynamicRegion.Size);
806
807   if (NULLEnd) {
808     Elf_Dyn_Iter Start = dynamic_table_begin();
809     while (Start != Ret && Start->getTag() != ELF::DT_NULL)
810       ++Start;
811
812     // Include the DT_NULL.
813     if (Start != Ret)
814       ++Start;
815     Ret = Start;
816   }
817   return Ret;
818 }
819
820 template <class ELFT>
821 StringRef ELFFile<ELFT>::getLoadName() const {
822   if (!dt_soname) {
823     dt_soname = "";
824     // Find the DT_SONAME entry
825     for (const auto &Entry : dynamic_table())
826       if (Entry.getTag() == ELF::DT_SONAME) {
827         dt_soname = getDynamicString(Entry.getVal());
828         break;
829       }
830   }
831   return dt_soname;
832 }
833
834 template <class ELFT>
835 template <typename T>
836 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
837   ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
838   if (std::error_code EC = Sec.getError())
839     report_fatal_error(EC.message());
840   return getEntry<T>(*Sec, Entry);
841 }
842
843 template <class ELFT>
844 template <typename T>
845 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
846                                  uint32_t Entry) const {
847   return reinterpret_cast<const T *>(base() + Section->sh_offset +
848                                      (Entry * Section->sh_entsize));
849 }
850
851 template <class ELFT>
852 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
853 ELFFile<ELFT>::getSection(uint32_t Index) const {
854   assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
855   if (Index >= getNumSections())
856     return object_error::invalid_section_index;
857
858   return reinterpret_cast<const Elf_Shdr *>(
859       reinterpret_cast<const char *>(SectionHeaderTable) +
860       (Index * Header->e_shentsize));
861 }
862
863 template <class ELFT>
864 ErrorOr<StringRef>
865 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
866   if (Section->sh_type != ELF::SHT_STRTAB)
867     return object_error::parse_failed;
868   uint64_t Offset = Section->sh_offset;
869   uint64_t Size = Section->sh_size;
870   if (Offset + Size > Buf.size())
871     return object_error::parse_failed;
872   StringRef Data((const char *)base() + Section->sh_offset, Size);
873   if (Data[Size - 1] != '\0')
874     return object_error::string_table_non_null_end;
875   return Data;
876 }
877
878 template <class ELFT>
879 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
880   if (!DotDynSymSec || Offset >= DynSymStrTab.size())
881     return nullptr;
882   return (const char *)DynSymStrTab.begin() + Offset;
883 }
884
885 template <class ELFT>
886 ErrorOr<StringRef>
887 ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
888   return Symb->getName(DotStrtab);
889 }
890
891 template <class ELFT>
892 ErrorOr<StringRef>
893 ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
894   return StringRef(getDynamicString(Symb->st_name));
895 }
896
897 template <class ELFT>
898 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Sym *Symb,
899                                                 bool IsDynamic) const {
900   if (IsDynamic)
901     return getDynamicSymbolName(Symb);
902   return getStaticSymbolName(Symb);
903 }
904
905 template <class ELFT>
906 ErrorOr<StringRef>
907 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
908   uint32_t Offset = Section->sh_name;
909   if (Offset >= DotShstrtab.size())
910     return object_error::parse_failed;
911   return StringRef(DotShstrtab.data() + Offset);
912 }
913
914 template <class ELFT>
915 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
916                                                    const Elf_Sym *symb,
917                                                    bool &IsDefault) const {
918   StringRef StrTab;
919   if (section) {
920     ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
921     if (std::error_code EC = StrTabOrErr.getError())
922       return EC;
923     StrTab = *StrTabOrErr;
924   }
925   // Handle non-dynamic symbols.
926   if (section != DotDynSymSec && section != nullptr) {
927     // Non-dynamic symbols can have versions in their names
928     // A name of the form 'foo@V1' indicates version 'V1', non-default.
929     // A name of the form 'foo@@V2' indicates version 'V2', default version.
930     ErrorOr<StringRef> SymName = symb->getName(StrTab);
931     if (!SymName)
932       return SymName;
933     StringRef Name = *SymName;
934     size_t atpos = Name.find('@');
935     if (atpos == StringRef::npos) {
936       IsDefault = false;
937       return StringRef("");
938     }
939     ++atpos;
940     if (atpos < Name.size() && Name[atpos] == '@') {
941       IsDefault = true;
942       ++atpos;
943     } else {
944       IsDefault = false;
945     }
946     return Name.substr(atpos);
947   }
948
949   // This is a dynamic symbol. Look in the GNU symbol version table.
950   if (!dot_gnu_version_sec) {
951     // No version table.
952     IsDefault = false;
953     return StringRef("");
954   }
955
956   // Determine the position in the symbol table of this entry.
957   size_t entry_index =
958       (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
959        reinterpret_cast<uintptr_t>(base())) /
960       sizeof(Elf_Sym);
961
962   // Get the corresponding version index entry
963   const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
964   size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
965
966   // Special markers for unversioned symbols.
967   if (version_index == ELF::VER_NDX_LOCAL ||
968       version_index == ELF::VER_NDX_GLOBAL) {
969     IsDefault = false;
970     return StringRef("");
971   }
972
973   // Lookup this symbol in the version table
974   LoadVersionMap();
975   if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
976     return object_error::parse_failed;
977   const VersionMapEntry &entry = VersionMap[version_index];
978
979   // Get the version name string
980   size_t name_offset;
981   if (entry.isVerdef()) {
982     // The first Verdaux entry holds the name.
983     name_offset = entry.getVerdef()->getAux()->vda_name;
984   } else {
985     name_offset = entry.getVernaux()->vna_name;
986   }
987
988   // Set IsDefault
989   if (entry.isVerdef()) {
990     IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
991   } else {
992     IsDefault = false;
993   }
994
995   if (name_offset >= DynSymStrTab.size())
996     return object_error::parse_failed;
997   return StringRef(getDynamicString(name_offset));
998 }
999
1000 /// This function returns the hash value for a symbol in the .dynsym section
1001 /// Name of the API remains consistent as specified in the libelf
1002 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1003 static inline unsigned elf_hash(StringRef &symbolName) {
1004   unsigned h = 0, g;
1005   for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1006     h = (h << 4) + symbolName[i];
1007     g = h & 0xf0000000L;
1008     if (g != 0)
1009       h ^= g >> 24;
1010     h &= ~g;
1011   }
1012   return h;
1013 }
1014 } // end namespace object
1015 } // end namespace llvm
1016
1017 #endif