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