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