llvm-objdump: don't assert if ELF file has no sections
[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, std::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 && Header->e_shoff > 0) {
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, std::error_code &ec)
625     : Buf(Object), SectionHeaderTable(nullptr), dot_shstrtab_sec(nullptr),
626       dot_strtab_sec(nullptr), dot_symtab_sec(nullptr),
627       SymbolTableSectionHeaderIndex(nullptr), dot_gnu_version_sec(nullptr),
628       dot_gnu_version_r_sec(nullptr), dot_gnu_version_d_sec(nullptr),
629       dt_soname(nullptr) {
630   const uint64_t FileSize = Buf->getBufferSize();
631
632   if (sizeof(Elf_Ehdr) > FileSize)
633     // FIXME: Proper error handling.
634     report_fatal_error("File too short!");
635
636   Header = reinterpret_cast<const Elf_Ehdr *>(base());
637
638   if (Header->e_shoff == 0)
639     return;
640
641   const uint64_t SectionTableOffset = Header->e_shoff;
642
643   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
644     // FIXME: Proper error handling.
645     report_fatal_error("Section header table goes past end of file!");
646
647   // The getNumSections() call below depends on SectionHeaderTable being set.
648   SectionHeaderTable =
649     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
650   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
651
652   if (SectionTableOffset + SectionTableSize > FileSize)
653     // FIXME: Proper error handling.
654     report_fatal_error("Section table goes past end of file!");
655
656   // Scan sections for special sections.
657
658   for (const Elf_Shdr &Sec : sections()) {
659     switch (Sec.sh_type) {
660     case ELF::SHT_SYMTAB_SHNDX:
661       if (SymbolTableSectionHeaderIndex)
662         // FIXME: Proper error handling.
663         report_fatal_error("More than one .symtab_shndx!");
664       SymbolTableSectionHeaderIndex = &Sec;
665       break;
666     case ELF::SHT_SYMTAB:
667       if (dot_symtab_sec)
668         // FIXME: Proper error handling.
669         report_fatal_error("More than one .symtab!");
670       dot_symtab_sec = &Sec;
671       dot_strtab_sec = getSection(Sec.sh_link);
672       break;
673     case ELF::SHT_DYNSYM: {
674       if (DynSymRegion.Addr)
675         // FIXME: Proper error handling.
676         report_fatal_error("More than one .dynsym!");
677       DynSymRegion.Addr = base() + Sec.sh_offset;
678       DynSymRegion.Size = Sec.sh_size;
679       DynSymRegion.EntSize = Sec.sh_entsize;
680       const Elf_Shdr *DynStr = getSection(Sec.sh_link);
681       DynStrRegion.Addr = base() + DynStr->sh_offset;
682       DynStrRegion.Size = DynStr->sh_size;
683       DynStrRegion.EntSize = DynStr->sh_entsize;
684       break;
685     }
686     case ELF::SHT_DYNAMIC:
687       if (DynamicRegion.Addr)
688         // FIXME: Proper error handling.
689         report_fatal_error("More than one .dynamic!");
690       DynamicRegion.Addr = base() + Sec.sh_offset;
691       DynamicRegion.Size = Sec.sh_size;
692       DynamicRegion.EntSize = Sec.sh_entsize;
693       break;
694     case ELF::SHT_GNU_versym:
695       if (dot_gnu_version_sec != nullptr)
696         // FIXME: Proper error handling.
697         report_fatal_error("More than one .gnu.version section!");
698       dot_gnu_version_sec = &Sec;
699       break;
700     case ELF::SHT_GNU_verdef:
701       if (dot_gnu_version_d_sec != nullptr)
702         // FIXME: Proper error handling.
703         report_fatal_error("More than one .gnu.version_d section!");
704       dot_gnu_version_d_sec = &Sec;
705       break;
706     case ELF::SHT_GNU_verneed:
707       if (dot_gnu_version_r_sec != nullptr)
708         // FIXME: Proper error handling.
709         report_fatal_error("More than one .gnu.version_r section!");
710       dot_gnu_version_r_sec = &Sec;
711       break;
712     }
713   }
714
715   // Get string table sections.
716   dot_shstrtab_sec = getSection(getStringTableIndex());
717   if (dot_shstrtab_sec) {
718     // Verify that the last byte in the string table in a null.
719     VerifyStrTab(dot_shstrtab_sec);
720   }
721
722   // Build symbol name side-mapping if there is one.
723   if (SymbolTableSectionHeaderIndex) {
724     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
725                                       SymbolTableSectionHeaderIndex->sh_offset);
726     for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
727          ++SI) {
728       if (*ShndxTable != ELF::SHN_UNDEF)
729         ExtendedSymbolTable[&*SI] = *ShndxTable;
730       ++ShndxTable;
731     }
732   }
733
734   // Scan program headers.
735   for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
736                      PhdrE = end_program_headers();
737        PhdrI != PhdrE; ++PhdrI) {
738     if (PhdrI->p_type == ELF::PT_DYNAMIC) {
739       DynamicRegion.Addr = base() + PhdrI->p_offset;
740       DynamicRegion.Size = PhdrI->p_filesz;
741       DynamicRegion.EntSize = sizeof(Elf_Dyn);
742       break;
743     }
744   }
745
746   ec = std::error_code();
747 }
748
749 // Get the symbol table index in the symtab section given a symbol
750 template <class ELFT>
751 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
752   uintptr_t SymLoc = uintptr_t(Sym);
753   uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
754   assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
755   uint64_t SymOffset = SymLoc - SymTabLoc;
756   assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
757          "Symbol not multiple of symbol size!");
758   return SymOffset / dot_symtab_sec->sh_entsize;
759 }
760
761 template <class ELFT>
762 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
763   return Elf_Shdr_Iter(Header->e_shentsize,
764                        (const char *)base() + Header->e_shoff);
765 }
766
767 template <class ELFT>
768 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
769   return Elf_Shdr_Iter(Header->e_shentsize,
770                        (const char *)base() + Header->e_shoff +
771                            (getNumSections() * Header->e_shentsize));
772 }
773
774 template <class ELFT>
775 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
776   if (!dot_symtab_sec)
777     return Elf_Sym_Iter(0, nullptr, false);
778   return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
779                       (const char *)base() + dot_symtab_sec->sh_offset, false);
780 }
781
782 template <class ELFT>
783 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
784   if (!dot_symtab_sec)
785     return Elf_Sym_Iter(0, nullptr, false);
786   return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
787                       (const char *)base() + dot_symtab_sec->sh_offset +
788                           dot_symtab_sec->sh_size,
789                       false);
790 }
791
792 template <class ELFT>
793 typename ELFFile<ELFT>::Elf_Dyn_Iter
794 ELFFile<ELFT>::begin_dynamic_table() const {
795   if (DynamicRegion.Addr)
796     return Elf_Dyn_Iter(DynamicRegion.EntSize,
797                         (const char *)DynamicRegion.Addr);
798   return Elf_Dyn_Iter(0, nullptr);
799 }
800
801 template <class ELFT>
802 typename ELFFile<ELFT>::Elf_Dyn_Iter
803 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
804   if (!DynamicRegion.Addr)
805     return Elf_Dyn_Iter(0, nullptr);
806   Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
807                     (const char *)DynamicRegion.Addr + DynamicRegion.Size);
808
809   if (NULLEnd) {
810     Elf_Dyn_Iter Start = begin_dynamic_table();
811     while (Start != Ret && Start->getTag() != ELF::DT_NULL)
812       ++Start;
813
814     // Include the DT_NULL.
815     if (Start != Ret)
816       ++Start;
817     Ret = Start;
818   }
819   return Ret;
820 }
821
822 template <class ELFT>
823 StringRef ELFFile<ELFT>::getLoadName() const {
824   if (!dt_soname) {
825     dt_soname = "";
826     // Find the DT_SONAME entry
827     for (const auto &Entry : dynamic_table())
828       if (Entry.getTag() == ELF::DT_SONAME) {
829         dt_soname = getDynamicString(Entry.getVal());
830         break;
831       }
832   }
833   return dt_soname;
834 }
835
836 template <class ELFT>
837 template <typename T>
838 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
839   return getEntry<T>(getSection(Section), Entry);
840 }
841
842 template <class ELFT>
843 template <typename T>
844 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
845                                  uint32_t Entry) const {
846   return reinterpret_cast<const T *>(base() + Section->sh_offset +
847                                      (Entry * Section->sh_entsize));
848 }
849
850 template <class ELFT>
851 const typename ELFFile<ELFT>::Elf_Shdr *
852 ELFFile<ELFT>::getSection(uint32_t index) const {
853   if (index == 0)
854     return nullptr;
855   if (!SectionHeaderTable || index >= getNumSections())
856     // FIXME: Proper error handling.
857     report_fatal_error("Invalid section index!");
858
859   return reinterpret_cast<const Elf_Shdr *>(
860          reinterpret_cast<const char *>(SectionHeaderTable)
861          + (index * Header->e_shentsize));
862 }
863
864 template <class ELFT>
865 const char *ELFFile<ELFT>::getString(uint32_t section,
866                                      ELF::Elf32_Word offset) const {
867   return getString(getSection(section), offset);
868 }
869
870 template <class ELFT>
871 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
872                                      ELF::Elf32_Word offset) const {
873   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
874   if (offset >= section->sh_size)
875     // FIXME: Proper error handling.
876     report_fatal_error("Symbol name offset outside of string table!");
877   return (const char *)base() + section->sh_offset + offset;
878 }
879
880 template <class ELFT>
881 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
882   if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
883     return nullptr;
884   return (const char *)DynStrRegion.Addr + Offset;
885 }
886
887 template <class ELFT>
888 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
889   if (!Sym.isDynamic())
890     return getSymbolName(dot_symtab_sec, &*Sym);
891
892   if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
893     return object_error::parse_failed;
894   return StringRef(getDynamicString(Sym->st_name));
895 }
896
897 template <class ELFT>
898 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
899                                                 const Elf_Sym *Symb) const {
900   if (Symb->st_name == 0) {
901     const Elf_Shdr *ContainingSec = getSection(Symb);
902     if (ContainingSec)
903       return getSectionName(ContainingSec);
904   }
905
906   const Elf_Shdr *StrTab = getSection(Section->sh_link);
907   if (Symb->st_name >= StrTab->sh_size)
908     return object_error::parse_failed;
909   return StringRef(getString(StrTab, Symb->st_name));
910 }
911
912 template <class ELFT>
913 ErrorOr<StringRef>
914 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
915   if (Section->sh_name >= dot_shstrtab_sec->sh_size)
916     return object_error::parse_failed;
917   return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
918 }
919
920 template <class ELFT>
921 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
922                                                    const Elf_Sym *symb,
923                                                    bool &IsDefault) const {
924   // Handle non-dynamic symbols.
925   if (section != DynSymRegion.Addr && section != nullptr) {
926     // Non-dynamic symbols can have versions in their names
927     // A name of the form 'foo@V1' indicates version 'V1', non-default.
928     // A name of the form 'foo@@V2' indicates version 'V2', default version.
929     ErrorOr<StringRef> SymName = getSymbolName(section, symb);
930     if (!SymName)
931       return SymName;
932     StringRef Name = *SymName;
933     size_t atpos = Name.find('@');
934     if (atpos == StringRef::npos) {
935       IsDefault = false;
936       return StringRef("");
937     }
938     ++atpos;
939     if (atpos < Name.size() && Name[atpos] == '@') {
940       IsDefault = true;
941       ++atpos;
942     } else {
943       IsDefault = false;
944     }
945     return Name.substr(atpos);
946   }
947
948   // This is a dynamic symbol. Look in the GNU symbol version table.
949   if (!dot_gnu_version_sec) {
950     // No version table.
951     IsDefault = false;
952     return StringRef("");
953   }
954
955   // Determine the position in the symbol table of this entry.
956   size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
957                        DynSymRegion.EntSize;
958
959   // Get the corresponding version index entry
960   const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
961   size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
962
963   // Special markers for unversioned symbols.
964   if (version_index == ELF::VER_NDX_LOCAL ||
965       version_index == ELF::VER_NDX_GLOBAL) {
966     IsDefault = false;
967     return StringRef("");
968   }
969
970   // Lookup this symbol in the version table
971   LoadVersionMap();
972   if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
973     return object_error::parse_failed;
974   const VersionMapEntry &entry = VersionMap[version_index];
975
976   // Get the version name string
977   size_t name_offset;
978   if (entry.isVerdef()) {
979     // The first Verdaux entry holds the name.
980     name_offset = entry.getVerdef()->getAux()->vda_name;
981   } else {
982     name_offset = entry.getVernaux()->vna_name;
983   }
984
985   // Set IsDefault
986   if (entry.isVerdef()) {
987     IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
988   } else {
989     IsDefault = false;
990   }
991
992   if (name_offset >= DynStrRegion.Size)
993     return object_error::parse_failed;
994   return StringRef(getDynamicString(name_offset));
995 }
996
997 /// This function returns the hash value for a symbol in the .dynsym section
998 /// Name of the API remains consistent as specified in the libelf
999 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1000 static inline unsigned elf_hash(StringRef &symbolName) {
1001   unsigned h = 0, g;
1002   for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1003     h = (h << 4) + symbolName[i];
1004     g = h & 0xf0000000L;
1005     if (g != 0)
1006       h ^= g >> 24;
1007     h &= ~g;
1008   }
1009   return h;
1010 }
1011 } // end namespace object
1012 } // end namespace llvm
1013
1014 #endif