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