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