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