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