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