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