Don't use StringRef iterator functions for data access
[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(ELF::ELFCLASSNONE, ELF::ELFDATANONE);
46   return std::make_pair(Object[ELF::EI_CLASS], Object[ELF::EI_DATA]);
47 }
48
49 template <class ELFT>
50 class ELFFile {
51 public:
52   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
53   typedef typename std::conditional<ELFT::Is64Bits,
54                                     uint64_t, uint32_t>::type uintX_t;
55
56   /// \brief Iterate over constant sized entities.
57   template <class EntT>
58   class ELFEntityIterator {
59   public:
60     typedef ptrdiff_t difference_type;
61     typedef EntT value_type;
62     typedef std::forward_iterator_tag iterator_category;
63     typedef value_type &reference;
64     typedef value_type *pointer;
65
66     /// \brief Default construct iterator.
67     ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
68     ELFEntityIterator(uintX_t EntSize, const char *Start)
69         : EntitySize(EntSize), Current(Start) {}
70
71     reference operator *() {
72       assert(Current && "Attempted to dereference an invalid iterator!");
73       return *reinterpret_cast<pointer>(Current);
74     }
75
76     pointer operator ->() {
77       assert(Current && "Attempted to dereference an invalid iterator!");
78       return reinterpret_cast<pointer>(Current);
79     }
80
81     bool operator ==(const ELFEntityIterator &Other) {
82       return Current == Other.Current;
83     }
84
85     bool operator !=(const ELFEntityIterator &Other) {
86       return !(*this == Other);
87     }
88
89     ELFEntityIterator &operator ++() {
90       assert(Current && "Attempted to increment an invalid iterator!");
91       Current += EntitySize;
92       return *this;
93     }
94
95     ELFEntityIterator operator ++(int) {
96       ELFEntityIterator Tmp = *this;
97       ++*this;
98       return Tmp;
99     }
100
101     ELFEntityIterator &operator =(const ELFEntityIterator &Other) {
102       EntitySize = Other.EntitySize;
103       Current = Other.Current;
104       return *this;
105     }
106
107     difference_type operator -(const ELFEntityIterator &Other) const {
108       assert(EntitySize == Other.EntitySize &&
109              "Subtracting iterators of different EntitySize!");
110       return (Current - Other.Current) / EntitySize;
111     }
112
113     const char *get() const { return Current; }
114
115     uintX_t getEntSize() const { return EntitySize; }
116
117   private:
118     uintX_t EntitySize;
119     const char *Current;
120   };
121
122   typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
123   typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
124   typedef Elf_Sym_Impl<ELFT> Elf_Sym;
125   typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
126   typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
127   typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
128   typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
129   typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
130   typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
131   typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
132   typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
133   typedef Elf_Versym_Impl<ELFT> Elf_Versym;
134   typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
135   typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
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   typedef iterator_range<Elf_Shdr_Iter> Elf_Shdr_Range;
140
141   /// \brief Archive files are 2 byte aligned, so we need this for
142   ///     PointerIntPair to work.
143   template <typename T>
144   class ArchivePointerTypeTraits {
145   public:
146     static inline const void *getAsVoidPointer(T *P) { return P; }
147     static inline T *getFromVoidPointer(const void *P) {
148       return static_cast<T *>(P);
149     }
150     enum { NumLowBitsAvailable = 1 };
151   };
152
153   class Elf_Sym_Iter {
154   public:
155     typedef ptrdiff_t difference_type;
156     typedef const Elf_Sym value_type;
157     typedef std::random_access_iterator_tag iterator_category;
158     typedef value_type &reference;
159     typedef value_type *pointer;
160
161     /// \brief Default construct iterator.
162     Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
163     Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
164         : EntitySize(EntSize), Current(Start, IsDynamic) {}
165
166     reference operator*() {
167       assert(Current.getPointer() &&
168              "Attempted to dereference an invalid iterator!");
169       return *reinterpret_cast<pointer>(Current.getPointer());
170     }
171
172     pointer operator->() {
173       assert(Current.getPointer() &&
174              "Attempted to dereference an invalid iterator!");
175       return reinterpret_cast<pointer>(Current.getPointer());
176     }
177
178     bool operator==(const Elf_Sym_Iter &Other) {
179       return Current == Other.Current;
180     }
181
182     bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
183
184     Elf_Sym_Iter &operator++() {
185       assert(Current.getPointer() &&
186              "Attempted to increment an invalid iterator!");
187       Current.setPointer(Current.getPointer() + EntitySize);
188       return *this;
189     }
190
191     Elf_Sym_Iter operator++(int) {
192       Elf_Sym_Iter Tmp = *this;
193       ++*this;
194       return Tmp;
195     }
196
197     Elf_Sym_Iter operator+(difference_type Dist) {
198       assert(Current.getPointer() &&
199              "Attempted to increment an invalid iterator!");
200       Current.setPointer(Current.getPointer() + EntitySize * Dist);
201       return *this;
202     }
203
204     Elf_Sym_Iter &operator=(const Elf_Sym_Iter &Other) {
205       EntitySize = Other.EntitySize;
206       Current = Other.Current;
207       return *this;
208     }
209
210     difference_type operator-(const Elf_Sym_Iter &Other) const {
211       assert(EntitySize == Other.EntitySize &&
212              "Subtracting iterators of different EntitySize!");
213       return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
214     }
215
216     const char *get() const { return Current.getPointer(); }
217
218     bool isDynamic() const { return Current.getInt(); }
219
220     uintX_t getEntSize() const { return EntitySize; }
221
222   private:
223     uintX_t EntitySize;
224     PointerIntPair<const char *, 1, bool,
225                    ArchivePointerTypeTraits<const char> > Current;
226   };
227
228 private:
229   typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
230   typedef DenseMap<unsigned, unsigned> IndexMap_t;
231
232   StringRef Buf;
233
234   const uint8_t *base() const {
235     return reinterpret_cast<const uint8_t *>(Buf.data());
236   }
237
238   const Elf_Ehdr *Header;
239   const Elf_Shdr *SectionHeaderTable;
240   const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
241   const Elf_Shdr *dot_strtab_sec;   // Symbol header string table.
242   const Elf_Shdr *dot_symtab_sec;   // Symbol table section.
243
244   const Elf_Shdr *SymbolTableSectionHeaderIndex;
245   DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
246
247   const Elf_Shdr *dot_gnu_version_sec;   // .gnu.version
248   const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
249   const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
250
251   /// \brief Represents a region described by entries in the .dynamic table.
252   struct DynRegionInfo {
253     DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
254     /// \brief Address in current address space.
255     const void *Addr;
256     /// \brief Size in bytes of the region.
257     uintX_t Size;
258     /// \brief Size of each entity in the region.
259     uintX_t EntSize;
260   };
261
262   DynRegionInfo DynamicRegion;
263   DynRegionInfo DynHashRegion;
264   DynRegionInfo DynStrRegion;
265   DynRegionInfo DynSymRegion;
266
267   // Pointer to SONAME entry in dynamic string table
268   // This is set the first time getLoadName is called.
269   mutable const char *dt_soname;
270
271   // Records for each version index the corresponding Verdef or Vernaux entry.
272   // This is filled the first time LoadVersionMap() is called.
273   class VersionMapEntry : public PointerIntPair<const void*, 1> {
274     public:
275     // If the integer is 0, this is an Elf_Verdef*.
276     // If the integer is 1, this is an Elf_Vernaux*.
277     VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
278     VersionMapEntry(const Elf_Verdef *verdef)
279         : PointerIntPair<const void*, 1>(verdef, 0) { }
280     VersionMapEntry(const Elf_Vernaux *vernaux)
281         : PointerIntPair<const void*, 1>(vernaux, 1) { }
282     bool isNull() const { return getPointer() == nullptr; }
283     bool isVerdef() const { return !isNull() && getInt() == 0; }
284     bool isVernaux() const { return !isNull() && getInt() == 1; }
285     const Elf_Verdef *getVerdef() const {
286       return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
287     }
288     const Elf_Vernaux *getVernaux() const {
289       return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
290     }
291   };
292   mutable SmallVector<VersionMapEntry, 16> VersionMap;
293   void LoadVersionDefs(const Elf_Shdr *sec) const;
294   void LoadVersionNeeds(const Elf_Shdr *ec) const;
295   void LoadVersionMap() const;
296
297 public:
298   template<typename T>
299   const T        *getEntry(uint32_t Section, uint32_t Entry) const;
300   template <typename T>
301   const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
302   const char     *getString(uint32_t section, uint32_t offset) const;
303   const char     *getString(const Elf_Shdr *section, uint32_t offset) const;
304   const char *getDynamicString(uintX_t Offset) const;
305   ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
306                                       const Elf_Sym *Symb,
307                                       bool &IsDefault) const;
308   void VerifyStrTab(const Elf_Shdr *sh) const;
309
310   StringRef getRelocationTypeName(uint32_t Type) const;
311   void getRelocationTypeName(uint32_t Type,
312                              SmallVectorImpl<char> &Result) const;
313
314   /// \brief Get the symbol table section and symbol for a given relocation.
315   template <class RelT>
316   std::pair<const Elf_Shdr *, const Elf_Sym *>
317   getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
318
319   ELFFile(StringRef Object, std::error_code &ec);
320
321   bool isMipsELF64() const {
322     return Header->e_machine == ELF::EM_MIPS &&
323       Header->getFileClass() == ELF::ELFCLASS64;
324   }
325
326   bool isMips64EL() const {
327     return Header->e_machine == ELF::EM_MIPS &&
328       Header->getFileClass() == ELF::ELFCLASS64 &&
329       Header->getDataEncoding() == ELF::ELFDATA2LSB;
330   }
331
332   Elf_Shdr_Iter begin_sections() const;
333   Elf_Shdr_Iter end_sections() const;
334   Elf_Shdr_Range sections() const {
335     return make_range(begin_sections(), end_sections());
336   }
337
338   Elf_Sym_Iter begin_symbols() const;
339   Elf_Sym_Iter end_symbols() const;
340
341   Elf_Dyn_Iter begin_dynamic_table() const;
342   /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
343   /// the section size.
344   Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
345   Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
346     return make_range(begin_dynamic_table(), end_dynamic_table(NULLEnd));
347   }
348
349   Elf_Sym_Iter begin_dynamic_symbols() const {
350     if (DynSymRegion.Addr)
351       return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
352                           true);
353     return Elf_Sym_Iter(0, nullptr, true);
354   }
355
356   Elf_Sym_Iter end_dynamic_symbols() const {
357     if (DynSymRegion.Addr)
358       return Elf_Sym_Iter(DynSymRegion.EntSize,
359                           (const char *)DynSymRegion.Addr + DynSymRegion.Size,
360                           true);
361     return Elf_Sym_Iter(0, nullptr, true);
362   }
363
364   Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
365     return Elf_Rela_Iter(sec->sh_entsize,
366                          (const char *)(base() + sec->sh_offset));
367   }
368
369   Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
370     return Elf_Rela_Iter(
371         sec->sh_entsize,
372         (const char *)(base() + sec->sh_offset + sec->sh_size));
373   }
374
375   Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
376     return Elf_Rel_Iter(sec->sh_entsize,
377                         (const char *)(base() + sec->sh_offset));
378   }
379
380   Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
381     return Elf_Rel_Iter(sec->sh_entsize,
382                         (const char *)(base() + sec->sh_offset + sec->sh_size));
383   }
384
385   /// \brief Iterate over program header table.
386   typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
387
388   Elf_Phdr_Iter begin_program_headers() const {
389     return Elf_Phdr_Iter(Header->e_phentsize,
390                          (const char*)base() + Header->e_phoff);
391   }
392
393   Elf_Phdr_Iter end_program_headers() const {
394     return Elf_Phdr_Iter(Header->e_phentsize,
395                          (const char*)base() +
396                            Header->e_phoff +
397                            (Header->e_phnum * Header->e_phentsize));
398   }
399
400   uint64_t getNumSections() const;
401   uintX_t getStringTableIndex() const;
402   ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
403   const Elf_Ehdr *getHeader() const { return Header; }
404   const Elf_Shdr *getSection(const Elf_Sym *symb) const;
405   const Elf_Shdr *getSection(uint32_t Index) const;
406   const Elf_Sym *getSymbol(uint32_t index) const;
407
408   ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
409
410   /// \brief Get the name of \p Symb.
411   /// \param SymTab The symbol table section \p Symb is contained in.
412   /// \param Symb The symbol to get the name of.
413   ///
414   /// \p SymTab is used to lookup the string table to use to get the symbol's
415   /// name.
416   ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
417                                    const Elf_Sym *Symb) const;
418   ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
419   uint64_t getSymbolIndex(const Elf_Sym *sym) const;
420   ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
421   StringRef getLoadName() const;
422 };
423
424 // Use an alignment of 2 for the typedefs since that is the worst case for
425 // ELF files in archives.
426 typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
427 typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
428 typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
429 typedef ELFFile<ELFType<support::big, 2, 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 ArrayRef<uint8_t>(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     // FIXME: Proper error handling.
633     report_fatal_error("File too short!");
634
635   Header = reinterpret_cast<const Elf_Ehdr *>(base());
636
637   if (Header->e_shoff == 0)
638     return;
639
640   const uint64_t SectionTableOffset = Header->e_shoff;
641
642   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
643     // FIXME: Proper error handling.
644     report_fatal_error("Section header table goes past end of file!");
645
646   // The getNumSections() call below depends on SectionHeaderTable being set.
647   SectionHeaderTable =
648     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
649   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
650
651   if (SectionTableOffset + SectionTableSize > FileSize)
652     // FIXME: Proper error handling.
653     report_fatal_error("Section table goes past end of file!");
654
655   // Scan sections for special sections.
656
657   for (const Elf_Shdr &Sec : sections()) {
658     switch (Sec.sh_type) {
659     case ELF::SHT_SYMTAB_SHNDX:
660       if (SymbolTableSectionHeaderIndex)
661         // FIXME: Proper error handling.
662         report_fatal_error("More than one .symtab_shndx!");
663       SymbolTableSectionHeaderIndex = &Sec;
664       break;
665     case ELF::SHT_SYMTAB:
666       if (dot_symtab_sec)
667         // FIXME: Proper error handling.
668         report_fatal_error("More than one .symtab!");
669       dot_symtab_sec = &Sec;
670       dot_strtab_sec = getSection(Sec.sh_link);
671       break;
672     case ELF::SHT_DYNSYM: {
673       if (DynSymRegion.Addr)
674         // FIXME: Proper error handling.
675         report_fatal_error("More than one .dynsym!");
676       DynSymRegion.Addr = base() + Sec.sh_offset;
677       DynSymRegion.Size = Sec.sh_size;
678       DynSymRegion.EntSize = Sec.sh_entsize;
679       const Elf_Shdr *DynStr = getSection(Sec.sh_link);
680       DynStrRegion.Addr = base() + DynStr->sh_offset;
681       DynStrRegion.Size = DynStr->sh_size;
682       DynStrRegion.EntSize = DynStr->sh_entsize;
683       break;
684     }
685     case ELF::SHT_DYNAMIC:
686       if (DynamicRegion.Addr)
687         // FIXME: Proper error handling.
688         report_fatal_error("More than one .dynamic!");
689       DynamicRegion.Addr = base() + Sec.sh_offset;
690       DynamicRegion.Size = Sec.sh_size;
691       DynamicRegion.EntSize = Sec.sh_entsize;
692       break;
693     case ELF::SHT_GNU_versym:
694       if (dot_gnu_version_sec != nullptr)
695         // FIXME: Proper error handling.
696         report_fatal_error("More than one .gnu.version section!");
697       dot_gnu_version_sec = &Sec;
698       break;
699     case ELF::SHT_GNU_verdef:
700       if (dot_gnu_version_d_sec != nullptr)
701         // FIXME: Proper error handling.
702         report_fatal_error("More than one .gnu.version_d section!");
703       dot_gnu_version_d_sec = &Sec;
704       break;
705     case ELF::SHT_GNU_verneed:
706       if (dot_gnu_version_r_sec != nullptr)
707         // FIXME: Proper error handling.
708         report_fatal_error("More than one .gnu.version_r section!");
709       dot_gnu_version_r_sec = &Sec;
710       break;
711     }
712   }
713
714   // Get string table sections.
715   dot_shstrtab_sec = getSection(getStringTableIndex());
716   if (dot_shstrtab_sec) {
717     // Verify that the last byte in the string table in a null.
718     VerifyStrTab(dot_shstrtab_sec);
719   }
720
721   // Build symbol name side-mapping if there is one.
722   if (SymbolTableSectionHeaderIndex) {
723     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
724                                       SymbolTableSectionHeaderIndex->sh_offset);
725     for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
726          ++SI) {
727       if (*ShndxTable != ELF::SHN_UNDEF)
728         ExtendedSymbolTable[&*SI] = *ShndxTable;
729       ++ShndxTable;
730     }
731   }
732
733   // Scan program headers.
734   for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
735                      PhdrE = end_program_headers();
736        PhdrI != PhdrE; ++PhdrI) {
737     if (PhdrI->p_type == ELF::PT_DYNAMIC) {
738       DynamicRegion.Addr = base() + PhdrI->p_offset;
739       DynamicRegion.Size = PhdrI->p_filesz;
740       DynamicRegion.EntSize = sizeof(Elf_Dyn);
741       break;
742     }
743   }
744
745   ec = std::error_code();
746 }
747
748 // Get the symbol table index in the symtab section given a symbol
749 template <class ELFT>
750 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
751   uintptr_t SymLoc = uintptr_t(Sym);
752   uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
753   assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
754   uint64_t SymOffset = SymLoc - SymTabLoc;
755   assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
756          "Symbol not multiple of symbol size!");
757   return SymOffset / dot_symtab_sec->sh_entsize;
758 }
759
760 template <class ELFT>
761 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
762   return Elf_Shdr_Iter(Header->e_shentsize,
763                        (const char *)base() + Header->e_shoff);
764 }
765
766 template <class ELFT>
767 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
768   return Elf_Shdr_Iter(Header->e_shentsize,
769                        (const char *)base() + Header->e_shoff +
770                            (getNumSections() * Header->e_shentsize));
771 }
772
773 template <class ELFT>
774 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
775   if (!dot_symtab_sec)
776     return Elf_Sym_Iter(0, nullptr, false);
777   return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
778                       (const char *)base() + dot_symtab_sec->sh_offset, false);
779 }
780
781 template <class ELFT>
782 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
783   if (!dot_symtab_sec)
784     return Elf_Sym_Iter(0, nullptr, false);
785   return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
786                       (const char *)base() + dot_symtab_sec->sh_offset +
787                           dot_symtab_sec->sh_size,
788                       false);
789 }
790
791 template <class ELFT>
792 typename ELFFile<ELFT>::Elf_Dyn_Iter
793 ELFFile<ELFT>::begin_dynamic_table() const {
794   if (DynamicRegion.Addr)
795     return Elf_Dyn_Iter(DynamicRegion.EntSize,
796                         (const char *)DynamicRegion.Addr);
797   return Elf_Dyn_Iter(0, nullptr);
798 }
799
800 template <class ELFT>
801 typename ELFFile<ELFT>::Elf_Dyn_Iter
802 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
803   if (!DynamicRegion.Addr)
804     return Elf_Dyn_Iter(0, nullptr);
805   Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
806                     (const char *)DynamicRegion.Addr + DynamicRegion.Size);
807
808   if (NULLEnd) {
809     Elf_Dyn_Iter Start = begin_dynamic_table();
810     while (Start != Ret && Start->getTag() != ELF::DT_NULL)
811       ++Start;
812
813     // Include the DT_NULL.
814     if (Start != Ret)
815       ++Start;
816     Ret = Start;
817   }
818   return Ret;
819 }
820
821 template <class ELFT>
822 StringRef ELFFile<ELFT>::getLoadName() const {
823   if (!dt_soname) {
824     dt_soname = "";
825     // Find the DT_SONAME entry
826     for (const auto &Entry : dynamic_table())
827       if (Entry.getTag() == ELF::DT_SONAME) {
828         dt_soname = getDynamicString(Entry.getVal());
829         break;
830       }
831   }
832   return dt_soname;
833 }
834
835 template <class ELFT>
836 template <typename T>
837 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
838   return getEntry<T>(getSection(Section), Entry);
839 }
840
841 template <class ELFT>
842 template <typename T>
843 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
844                                  uint32_t Entry) const {
845   return reinterpret_cast<const T *>(base() + Section->sh_offset +
846                                      (Entry * Section->sh_entsize));
847 }
848
849 template <class ELFT>
850 const typename ELFFile<ELFT>::Elf_Shdr *
851 ELFFile<ELFT>::getSection(uint32_t index) const {
852   if (index == 0)
853     return nullptr;
854   if (!SectionHeaderTable || index >= getNumSections())
855     // FIXME: Proper error handling.
856     report_fatal_error("Invalid section index!");
857
858   return reinterpret_cast<const Elf_Shdr *>(
859          reinterpret_cast<const char *>(SectionHeaderTable)
860          + (index * Header->e_shentsize));
861 }
862
863 template <class ELFT>
864 const char *ELFFile<ELFT>::getString(uint32_t section,
865                                      ELF::Elf32_Word offset) const {
866   return getString(getSection(section), offset);
867 }
868
869 template <class ELFT>
870 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
871                                      ELF::Elf32_Word offset) const {
872   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
873   if (offset >= section->sh_size)
874     // FIXME: Proper error handling.
875     report_fatal_error("Symbol name offset outside of string table!");
876   return (const char *)base() + section->sh_offset + offset;
877 }
878
879 template <class ELFT>
880 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
881   if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
882     return nullptr;
883   return (const char *)DynStrRegion.Addr + Offset;
884 }
885
886 template <class ELFT>
887 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
888   if (!Sym.isDynamic())
889     return getSymbolName(dot_symtab_sec, &*Sym);
890
891   if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
892     return object_error::parse_failed;
893   return StringRef(getDynamicString(Sym->st_name));
894 }
895
896 template <class ELFT>
897 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
898                                                 const Elf_Sym *Symb) const {
899   if (Symb->st_name == 0) {
900     const Elf_Shdr *ContainingSec = getSection(Symb);
901     if (ContainingSec)
902       return getSectionName(ContainingSec);
903   }
904
905   const Elf_Shdr *StrTab = getSection(Section->sh_link);
906   if (Symb->st_name >= StrTab->sh_size)
907     return object_error::parse_failed;
908   return StringRef(getString(StrTab, Symb->st_name));
909 }
910
911 template <class ELFT>
912 ErrorOr<StringRef>
913 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
914   if (Section->sh_name >= dot_shstrtab_sec->sh_size)
915     return object_error::parse_failed;
916   return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
917 }
918
919 template <class ELFT>
920 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
921                                                    const Elf_Sym *symb,
922                                                    bool &IsDefault) const {
923   // Handle non-dynamic symbols.
924   if (section != DynSymRegion.Addr && section != nullptr) {
925     // Non-dynamic symbols can have versions in their names
926     // A name of the form 'foo@V1' indicates version 'V1', non-default.
927     // A name of the form 'foo@@V2' indicates version 'V2', default version.
928     ErrorOr<StringRef> SymName = getSymbolName(section, symb);
929     if (!SymName)
930       return SymName;
931     StringRef Name = *SymName;
932     size_t atpos = Name.find('@');
933     if (atpos == StringRef::npos) {
934       IsDefault = false;
935       return StringRef("");
936     }
937     ++atpos;
938     if (atpos < Name.size() && Name[atpos] == '@') {
939       IsDefault = true;
940       ++atpos;
941     } else {
942       IsDefault = false;
943     }
944     return Name.substr(atpos);
945   }
946
947   // This is a dynamic symbol. Look in the GNU symbol version table.
948   if (!dot_gnu_version_sec) {
949     // No version table.
950     IsDefault = false;
951     return StringRef("");
952   }
953
954   // Determine the position in the symbol table of this entry.
955   size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
956                        DynSymRegion.EntSize;
957
958   // Get the corresponding version index entry
959   const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
960   size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
961
962   // Special markers for unversioned symbols.
963   if (version_index == ELF::VER_NDX_LOCAL ||
964       version_index == ELF::VER_NDX_GLOBAL) {
965     IsDefault = false;
966     return StringRef("");
967   }
968
969   // Lookup this symbol in the version table
970   LoadVersionMap();
971   if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
972     return object_error::parse_failed;
973   const VersionMapEntry &entry = VersionMap[version_index];
974
975   // Get the version name string
976   size_t name_offset;
977   if (entry.isVerdef()) {
978     // The first Verdaux entry holds the name.
979     name_offset = entry.getVerdef()->getAux()->vda_name;
980   } else {
981     name_offset = entry.getVernaux()->vna_name;
982   }
983
984   // Set IsDefault
985   if (entry.isVerdef()) {
986     IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
987   } else {
988     IsDefault = false;
989   }
990
991   if (name_offset >= DynStrRegion.Size)
992     return object_error::parse_failed;
993   return StringRef(getDynamicString(name_offset));
994 }
995
996 /// This function returns the hash value for a symbol in the .dynsym section
997 /// Name of the API remains consistent as specified in the libelf
998 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
999 static inline unsigned elf_hash(StringRef &symbolName) {
1000   unsigned h = 0, g;
1001   for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1002     h = (h << 4) + symbolName[i];
1003     g = h & 0xf0000000L;
1004     if (g != 0)
1005       h ^= g >> 24;
1006     h &= ~g;
1007   }
1008   return h;
1009 }
1010 } // end namespace object
1011 } // end namespace llvm
1012
1013 #endif