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