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