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