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