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