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