1 //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the ELFFile template class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_OBJECT_ELF_H
15 #define LLVM_OBJECT_ELF_H
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"
39 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
41 // Subclasses of ELFFile may need this for template instantiation
42 inline std::pair<unsigned char, unsigned char>
43 getElfArchType(StringRef Object) {
44 if (Object.size() < ELF::EI_NIDENT)
45 return std::make_pair(ELF::ELFCLASSNONE, ELF::ELFDATANONE);
46 return std::make_pair(Object[ELF::EI_CLASS], Object[ELF::EI_DATA]);
52 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
53 typedef typename std::conditional<ELFT::Is64Bits,
54 uint64_t, uint32_t>::type uintX_t;
56 /// \brief Iterate over constant sized entities.
58 class ELFEntityIterator {
60 typedef ptrdiff_t difference_type;
61 typedef EntT value_type;
62 typedef std::forward_iterator_tag iterator_category;
63 typedef value_type &reference;
64 typedef value_type *pointer;
66 /// \brief Default construct iterator.
67 ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
68 ELFEntityIterator(uintX_t EntSize, const char *Start)
69 : EntitySize(EntSize), Current(Start) {}
71 reference operator *() {
72 assert(Current && "Attempted to dereference an invalid iterator!");
73 return *reinterpret_cast<pointer>(Current);
76 pointer operator ->() {
77 assert(Current && "Attempted to dereference an invalid iterator!");
78 return reinterpret_cast<pointer>(Current);
81 bool operator ==(const ELFEntityIterator &Other) {
82 return Current == Other.Current;
85 bool operator !=(const ELFEntityIterator &Other) {
86 return !(*this == Other);
89 ELFEntityIterator &operator ++() {
90 assert(Current && "Attempted to increment an invalid iterator!");
91 Current += EntitySize;
95 ELFEntityIterator operator ++(int) {
96 ELFEntityIterator Tmp = *this;
101 ELFEntityIterator &operator =(const ELFEntityIterator &Other) {
102 EntitySize = Other.EntitySize;
103 Current = Other.Current;
107 difference_type operator -(const ELFEntityIterator &Other) const {
108 assert(EntitySize == Other.EntitySize &&
109 "Subtracting iterators of different EntitySize!");
110 return (Current - Other.Current) / EntitySize;
113 const char *get() const { return Current; }
115 uintX_t getEntSize() const { return EntitySize; }
122 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
123 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
124 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
125 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
126 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
127 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
128 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
129 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
130 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
131 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
132 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
133 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
134 typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
135 typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
136 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
137 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
138 typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
139 typedef iterator_range<Elf_Shdr_Iter> Elf_Shdr_Range;
141 /// \brief Archive files are 2 byte aligned, so we need this for
142 /// PointerIntPair to work.
143 template <typename T>
144 class ArchivePointerTypeTraits {
146 static inline const void *getAsVoidPointer(T *P) { return P; }
147 static inline T *getFromVoidPointer(const void *P) {
148 return static_cast<T *>(P);
150 enum { NumLowBitsAvailable = 1 };
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;
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) {}
166 reference operator*() {
167 assert(Current.getPointer() &&
168 "Attempted to dereference an invalid iterator!");
169 return *reinterpret_cast<pointer>(Current.getPointer());
172 pointer operator->() {
173 assert(Current.getPointer() &&
174 "Attempted to dereference an invalid iterator!");
175 return reinterpret_cast<pointer>(Current.getPointer());
178 bool operator==(const Elf_Sym_Iter &Other) {
179 return Current == Other.Current;
182 bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
184 Elf_Sym_Iter &operator++() {
185 assert(Current.getPointer() &&
186 "Attempted to increment an invalid iterator!");
187 Current.setPointer(Current.getPointer() + EntitySize);
191 Elf_Sym_Iter operator++(int) {
192 Elf_Sym_Iter Tmp = *this;
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);
204 Elf_Sym_Iter &operator=(const Elf_Sym_Iter &Other) {
205 EntitySize = Other.EntitySize;
206 Current = Other.Current;
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;
216 const char *get() const { return Current.getPointer(); }
218 bool isDynamic() const { return Current.getInt(); }
220 uintX_t getEntSize() const { return EntitySize; }
224 PointerIntPair<const char *, 1, bool,
225 ArchivePointerTypeTraits<const char> > Current;
229 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
230 typedef DenseMap<unsigned, unsigned> IndexMap_t;
234 const uint8_t *base() const {
235 return reinterpret_cast<const uint8_t *>(Buf.data());
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.
244 const Elf_Shdr *SymbolTableSectionHeaderIndex;
245 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
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
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.
256 /// \brief Size in bytes of the region.
258 /// \brief Size of each entity in the region.
262 DynRegionInfo DynamicRegion;
263 DynRegionInfo DynHashRegion;
264 DynRegionInfo DynStrRegion;
265 DynRegionInfo DynSymRegion;
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;
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> {
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;
288 const Elf_Vernaux *getVernaux() const {
289 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
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;
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,
307 bool &IsDefault) const;
308 void VerifyStrTab(const Elf_Shdr *sh) const;
310 StringRef getRelocationTypeName(uint32_t Type) const;
311 void getRelocationTypeName(uint32_t Type,
312 SmallVectorImpl<char> &Result) const;
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;
319 ELFFile(StringRef Object, std::error_code &ec);
321 bool isMipsELF64() const {
322 return Header->e_machine == ELF::EM_MIPS &&
323 Header->getFileClass() == ELF::ELFCLASS64;
326 bool isMips64EL() const {
327 return Header->e_machine == ELF::EM_MIPS &&
328 Header->getFileClass() == ELF::ELFCLASS64 &&
329 Header->getDataEncoding() == ELF::ELFDATA2LSB;
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());
338 Elf_Sym_Iter begin_symbols() const;
339 Elf_Sym_Iter end_symbols() const;
341 Elf_Dyn_Iter begin_dynamic_table() const;
342 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
343 /// the section size.
344 Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
345 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
346 return make_range(begin_dynamic_table(), end_dynamic_table(NULLEnd));
349 Elf_Sym_Iter begin_dynamic_symbols() const {
350 if (DynSymRegion.Addr)
351 return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
353 return Elf_Sym_Iter(0, nullptr, true);
356 Elf_Sym_Iter end_dynamic_symbols() const {
357 if (DynSymRegion.Addr)
358 return Elf_Sym_Iter(DynSymRegion.EntSize,
359 (const char *)DynSymRegion.Addr + DynSymRegion.Size,
361 return Elf_Sym_Iter(0, nullptr, true);
364 Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
365 return Elf_Rela_Iter(sec->sh_entsize,
366 (const char *)(base() + sec->sh_offset));
369 Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
370 return Elf_Rela_Iter(
372 (const char *)(base() + sec->sh_offset + sec->sh_size));
375 Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
376 return Elf_Rel_Iter(sec->sh_entsize,
377 (const char *)(base() + sec->sh_offset));
380 Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
381 return Elf_Rel_Iter(sec->sh_entsize,
382 (const char *)(base() + sec->sh_offset + sec->sh_size));
385 /// \brief Iterate over program header table.
386 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
388 Elf_Phdr_Iter begin_program_headers() const {
389 return Elf_Phdr_Iter(Header->e_phentsize,
390 (const char*)base() + Header->e_phoff);
393 Elf_Phdr_Iter end_program_headers() const {
394 return Elf_Phdr_Iter(Header->e_phentsize,
395 (const char*)base() +
397 (Header->e_phnum * Header->e_phentsize));
400 uint64_t getNumSections() const;
401 uintX_t getStringTableIndex() const;
402 ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
403 const Elf_Ehdr *getHeader() const { return Header; }
404 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
405 const Elf_Shdr *getSection(uint32_t Index) const;
406 const Elf_Sym *getSymbol(uint32_t index) const;
408 ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
410 /// \brief Get the name of \p Symb.
411 /// \param SymTab The symbol table section \p Symb is contained in.
412 /// \param Symb The symbol to get the name of.
414 /// \p SymTab is used to lookup the string table to use to get the symbol's
416 ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
417 const Elf_Sym *Symb) const;
418 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
419 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
420 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
421 StringRef getLoadName() const;
424 // Use an alignment of 2 for the typedefs since that is the worst case for
425 // ELF files in archives.
426 typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
427 typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
428 typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
429 typedef ELFFile<ELFType<support::big, 2, true> > ELF64BEFile;
431 // Iterate through the version definitions, and place each Elf_Verdef
432 // in the VersionMap according to its index.
433 template <class ELFT>
434 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
435 unsigned vd_size = sec->sh_size; // Size of section in bytes
436 unsigned vd_count = sec->sh_info; // Number of Verdef entries
437 const char *sec_start = (const char*)base() + sec->sh_offset;
438 const char *sec_end = sec_start + vd_size;
439 // The first Verdef entry is at the start of the section.
440 const char *p = sec_start;
441 for (unsigned i = 0; i < vd_count; i++) {
442 if (p + sizeof(Elf_Verdef) > sec_end)
443 report_fatal_error("Section ended unexpectedly while scanning "
444 "version definitions.");
445 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
446 if (vd->vd_version != ELF::VER_DEF_CURRENT)
447 report_fatal_error("Unexpected verdef version");
448 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
449 if (index >= VersionMap.size())
450 VersionMap.resize(index + 1);
451 VersionMap[index] = VersionMapEntry(vd);
456 // Iterate through the versions needed section, and place each Elf_Vernaux
457 // in the VersionMap according to its index.
458 template <class ELFT>
459 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
460 unsigned vn_size = sec->sh_size; // Size of section in bytes
461 unsigned vn_count = sec->sh_info; // Number of Verneed entries
462 const char *sec_start = (const char *)base() + sec->sh_offset;
463 const char *sec_end = sec_start + vn_size;
464 // The first Verneed entry is at the start of the section.
465 const char *p = sec_start;
466 for (unsigned i = 0; i < vn_count; i++) {
467 if (p + sizeof(Elf_Verneed) > sec_end)
468 report_fatal_error("Section ended unexpectedly while scanning "
469 "version needed records.");
470 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
471 if (vn->vn_version != ELF::VER_NEED_CURRENT)
472 report_fatal_error("Unexpected verneed version");
473 // Iterate through the Vernaux entries
474 const char *paux = p + vn->vn_aux;
475 for (unsigned j = 0; j < vn->vn_cnt; j++) {
476 if (paux + sizeof(Elf_Vernaux) > sec_end)
477 report_fatal_error("Section ended unexpected while scanning auxiliary "
478 "version needed records.");
479 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
480 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
481 if (index >= VersionMap.size())
482 VersionMap.resize(index + 1);
483 VersionMap[index] = VersionMapEntry(vna);
484 paux += vna->vna_next;
490 template <class ELFT>
491 void ELFFile<ELFT>::LoadVersionMap() const {
492 // If there is no dynamic symtab or version table, there is nothing to do.
493 if (!DynSymRegion.Addr || !dot_gnu_version_sec)
496 // Has the VersionMap already been loaded?
497 if (VersionMap.size() > 0)
500 // The first two version indexes are reserved.
501 // Index 0 is LOCAL, index 1 is GLOBAL.
502 VersionMap.push_back(VersionMapEntry());
503 VersionMap.push_back(VersionMapEntry());
505 if (dot_gnu_version_d_sec)
506 LoadVersionDefs(dot_gnu_version_d_sec);
508 if (dot_gnu_version_r_sec)
509 LoadVersionNeeds(dot_gnu_version_r_sec);
512 template <class ELFT>
513 ELF::Elf64_Word ELFFile<ELFT>::getSymbolTableIndex(const Elf_Sym *symb) const {
514 if (symb->st_shndx == ELF::SHN_XINDEX)
515 return ExtendedSymbolTable.lookup(symb);
516 return symb->st_shndx;
519 template <class ELFT>
520 const typename ELFFile<ELFT>::Elf_Shdr *
521 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
522 if (symb->st_shndx == ELF::SHN_XINDEX)
523 return getSection(ExtendedSymbolTable.lookup(symb));
524 if (symb->st_shndx >= ELF::SHN_LORESERVE)
526 return getSection(symb->st_shndx);
529 template <class ELFT>
530 const typename ELFFile<ELFT>::Elf_Sym *
531 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
532 return &*(begin_symbols() + Index);
535 template <class ELFT>
536 ErrorOr<ArrayRef<uint8_t> >
537 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
538 if (Sec->sh_offset + Sec->sh_size > Buf.size())
539 return object_error::parse_failed;
540 const uint8_t *Start = base() + Sec->sh_offset;
541 return ArrayRef<uint8_t>(Start, Sec->sh_size);
544 template <class ELFT>
545 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
546 return getELFRelocationTypeName(Header->e_machine, Type);
549 template <class ELFT>
550 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
551 SmallVectorImpl<char> &Result) const {
552 if (!isMipsELF64()) {
553 StringRef Name = getRelocationTypeName(Type);
554 Result.append(Name.begin(), Name.end());
556 // The Mips N64 ABI allows up to three operations to be specified per
557 // relocation record. Unfortunately there's no easy way to test for the
558 // presence of N64 ELFs as they have no special flag that identifies them
559 // as being N64. We can safely assume at the moment that all Mips
560 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
561 // information to disambiguate between old vs new ABIs.
562 uint8_t Type1 = (Type >> 0) & 0xFF;
563 uint8_t Type2 = (Type >> 8) & 0xFF;
564 uint8_t Type3 = (Type >> 16) & 0xFF;
566 // Concat all three relocation type names.
567 StringRef Name = getRelocationTypeName(Type1);
568 Result.append(Name.begin(), Name.end());
570 Name = getRelocationTypeName(Type2);
571 Result.append(1, '/');
572 Result.append(Name.begin(), Name.end());
574 Name = getRelocationTypeName(Type3);
575 Result.append(1, '/');
576 Result.append(Name.begin(), Name.end());
580 template <class ELFT>
581 template <class RelT>
582 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
583 const typename ELFFile<ELFT>::Elf_Sym *>
584 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
586 return std::make_pair(nullptr, nullptr);
587 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
588 return std::make_pair(
589 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
592 // Verify that the last byte in the string table in a null.
593 template <class ELFT>
594 void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
595 const char *strtab = (const char *)base() + sh->sh_offset;
596 if (strtab[sh->sh_size - 1] != 0)
597 // FIXME: Proper error handling.
598 report_fatal_error("String table must end with a null terminator!");
601 template <class ELFT>
602 uint64_t ELFFile<ELFT>::getNumSections() const {
603 assert(Header && "Header not initialized!");
604 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
605 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
606 return SectionHeaderTable->sh_size;
608 return Header->e_shnum;
611 template <class ELFT>
612 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
613 if (Header->e_shnum == ELF::SHN_UNDEF) {
614 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
615 return SectionHeaderTable->sh_link;
616 if (Header->e_shstrndx >= getNumSections())
619 return Header->e_shstrndx;
622 template <class ELFT>
623 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &ec)
624 : Buf(Object), SectionHeaderTable(nullptr), dot_shstrtab_sec(nullptr),
625 dot_strtab_sec(nullptr), dot_symtab_sec(nullptr),
626 SymbolTableSectionHeaderIndex(nullptr), dot_gnu_version_sec(nullptr),
627 dot_gnu_version_r_sec(nullptr), dot_gnu_version_d_sec(nullptr),
629 const uint64_t FileSize = Buf.size();
631 if (sizeof(Elf_Ehdr) > FileSize)
632 // FIXME: Proper error handling.
633 report_fatal_error("File too short!");
635 Header = reinterpret_cast<const Elf_Ehdr *>(base());
637 if (Header->e_shoff == 0)
640 const uint64_t SectionTableOffset = Header->e_shoff;
642 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
643 // FIXME: Proper error handling.
644 report_fatal_error("Section header table goes past end of file!");
646 // The getNumSections() call below depends on SectionHeaderTable being set.
648 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
649 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
651 if (SectionTableOffset + SectionTableSize > FileSize)
652 // FIXME: Proper error handling.
653 report_fatal_error("Section table goes past end of file!");
655 // Scan sections for special sections.
657 for (const Elf_Shdr &Sec : sections()) {
658 switch (Sec.sh_type) {
659 case ELF::SHT_SYMTAB_SHNDX:
660 if (SymbolTableSectionHeaderIndex)
661 // FIXME: Proper error handling.
662 report_fatal_error("More than one .symtab_shndx!");
663 SymbolTableSectionHeaderIndex = &Sec;
665 case ELF::SHT_SYMTAB:
667 // FIXME: Proper error handling.
668 report_fatal_error("More than one .symtab!");
669 dot_symtab_sec = &Sec;
670 dot_strtab_sec = getSection(Sec.sh_link);
672 case ELF::SHT_DYNSYM: {
673 if (DynSymRegion.Addr)
674 // FIXME: Proper error handling.
675 report_fatal_error("More than one .dynsym!");
676 DynSymRegion.Addr = base() + Sec.sh_offset;
677 DynSymRegion.Size = Sec.sh_size;
678 DynSymRegion.EntSize = Sec.sh_entsize;
679 const Elf_Shdr *DynStr = getSection(Sec.sh_link);
680 DynStrRegion.Addr = base() + DynStr->sh_offset;
681 DynStrRegion.Size = DynStr->sh_size;
682 DynStrRegion.EntSize = DynStr->sh_entsize;
685 case ELF::SHT_DYNAMIC:
686 if (DynamicRegion.Addr)
687 // FIXME: Proper error handling.
688 report_fatal_error("More than one .dynamic!");
689 DynamicRegion.Addr = base() + Sec.sh_offset;
690 DynamicRegion.Size = Sec.sh_size;
691 DynamicRegion.EntSize = Sec.sh_entsize;
693 case ELF::SHT_GNU_versym:
694 if (dot_gnu_version_sec != nullptr)
695 // FIXME: Proper error handling.
696 report_fatal_error("More than one .gnu.version section!");
697 dot_gnu_version_sec = &Sec;
699 case ELF::SHT_GNU_verdef:
700 if (dot_gnu_version_d_sec != nullptr)
701 // FIXME: Proper error handling.
702 report_fatal_error("More than one .gnu.version_d section!");
703 dot_gnu_version_d_sec = &Sec;
705 case ELF::SHT_GNU_verneed:
706 if (dot_gnu_version_r_sec != nullptr)
707 // FIXME: Proper error handling.
708 report_fatal_error("More than one .gnu.version_r section!");
709 dot_gnu_version_r_sec = &Sec;
714 // Get string table sections.
715 dot_shstrtab_sec = getSection(getStringTableIndex());
716 if (dot_shstrtab_sec) {
717 // Verify that the last byte in the string table in a null.
718 VerifyStrTab(dot_shstrtab_sec);
721 // Build symbol name side-mapping if there is one.
722 if (SymbolTableSectionHeaderIndex) {
723 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
724 SymbolTableSectionHeaderIndex->sh_offset);
725 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
727 if (*ShndxTable != ELF::SHN_UNDEF)
728 ExtendedSymbolTable[&*SI] = *ShndxTable;
733 // Scan program headers.
734 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
735 PhdrE = end_program_headers();
736 PhdrI != PhdrE; ++PhdrI) {
737 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
738 DynamicRegion.Addr = base() + PhdrI->p_offset;
739 DynamicRegion.Size = PhdrI->p_filesz;
740 DynamicRegion.EntSize = sizeof(Elf_Dyn);
745 ec = std::error_code();
748 // Get the symbol table index in the symtab section given a symbol
749 template <class ELFT>
750 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
751 uintptr_t SymLoc = uintptr_t(Sym);
752 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
753 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
754 uint64_t SymOffset = SymLoc - SymTabLoc;
755 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
756 "Symbol not multiple of symbol size!");
757 return SymOffset / dot_symtab_sec->sh_entsize;
760 template <class ELFT>
761 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
762 return Elf_Shdr_Iter(Header->e_shentsize,
763 (const char *)base() + Header->e_shoff);
766 template <class ELFT>
767 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
768 return Elf_Shdr_Iter(Header->e_shentsize,
769 (const char *)base() + Header->e_shoff +
770 (getNumSections() * Header->e_shentsize));
773 template <class ELFT>
774 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
776 return Elf_Sym_Iter(0, nullptr, false);
777 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
778 (const char *)base() + dot_symtab_sec->sh_offset, false);
781 template <class ELFT>
782 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
784 return Elf_Sym_Iter(0, nullptr, false);
785 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
786 (const char *)base() + dot_symtab_sec->sh_offset +
787 dot_symtab_sec->sh_size,
791 template <class ELFT>
792 typename ELFFile<ELFT>::Elf_Dyn_Iter
793 ELFFile<ELFT>::begin_dynamic_table() const {
794 if (DynamicRegion.Addr)
795 return Elf_Dyn_Iter(DynamicRegion.EntSize,
796 (const char *)DynamicRegion.Addr);
797 return Elf_Dyn_Iter(0, nullptr);
800 template <class ELFT>
801 typename ELFFile<ELFT>::Elf_Dyn_Iter
802 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
803 if (!DynamicRegion.Addr)
804 return Elf_Dyn_Iter(0, nullptr);
805 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
806 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
809 Elf_Dyn_Iter Start = begin_dynamic_table();
810 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
813 // Include the DT_NULL.
821 template <class ELFT>
822 StringRef ELFFile<ELFT>::getLoadName() const {
825 // Find the DT_SONAME entry
826 for (const auto &Entry : dynamic_table())
827 if (Entry.getTag() == ELF::DT_SONAME) {
828 dt_soname = getDynamicString(Entry.getVal());
835 template <class ELFT>
836 template <typename T>
837 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
838 return getEntry<T>(getSection(Section), Entry);
841 template <class ELFT>
842 template <typename T>
843 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
844 uint32_t Entry) const {
845 return reinterpret_cast<const T *>(base() + Section->sh_offset +
846 (Entry * Section->sh_entsize));
849 template <class ELFT>
850 const typename ELFFile<ELFT>::Elf_Shdr *
851 ELFFile<ELFT>::getSection(uint32_t index) const {
854 if (!SectionHeaderTable || index >= getNumSections())
855 // FIXME: Proper error handling.
856 report_fatal_error("Invalid section index!");
858 return reinterpret_cast<const Elf_Shdr *>(
859 reinterpret_cast<const char *>(SectionHeaderTable)
860 + (index * Header->e_shentsize));
863 template <class ELFT>
864 const char *ELFFile<ELFT>::getString(uint32_t section,
865 ELF::Elf32_Word offset) const {
866 return getString(getSection(section), offset);
869 template <class ELFT>
870 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
871 ELF::Elf32_Word offset) const {
872 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
873 if (offset >= section->sh_size)
874 // FIXME: Proper error handling.
875 report_fatal_error("Symbol name offset outside of string table!");
876 return (const char *)base() + section->sh_offset + offset;
879 template <class ELFT>
880 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
881 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
883 return (const char *)DynStrRegion.Addr + Offset;
886 template <class ELFT>
887 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
888 if (!Sym.isDynamic())
889 return getSymbolName(dot_symtab_sec, &*Sym);
891 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
892 return object_error::parse_failed;
893 return StringRef(getDynamicString(Sym->st_name));
896 template <class ELFT>
897 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
898 const Elf_Sym *Symb) const {
899 if (Symb->st_name == 0) {
900 const Elf_Shdr *ContainingSec = getSection(Symb);
902 return getSectionName(ContainingSec);
905 const Elf_Shdr *StrTab = getSection(Section->sh_link);
906 if (Symb->st_name >= StrTab->sh_size)
907 return object_error::parse_failed;
908 return StringRef(getString(StrTab, Symb->st_name));
911 template <class ELFT>
913 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
914 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
915 return object_error::parse_failed;
916 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
919 template <class ELFT>
920 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
922 bool &IsDefault) const {
923 // Handle non-dynamic symbols.
924 if (section != DynSymRegion.Addr && section != nullptr) {
925 // Non-dynamic symbols can have versions in their names
926 // A name of the form 'foo@V1' indicates version 'V1', non-default.
927 // A name of the form 'foo@@V2' indicates version 'V2', default version.
928 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
931 StringRef Name = *SymName;
932 size_t atpos = Name.find('@');
933 if (atpos == StringRef::npos) {
935 return StringRef("");
938 if (atpos < Name.size() && Name[atpos] == '@') {
944 return Name.substr(atpos);
947 // This is a dynamic symbol. Look in the GNU symbol version table.
948 if (!dot_gnu_version_sec) {
951 return StringRef("");
954 // Determine the position in the symbol table of this entry.
955 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
956 DynSymRegion.EntSize;
958 // Get the corresponding version index entry
959 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
960 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
962 // Special markers for unversioned symbols.
963 if (version_index == ELF::VER_NDX_LOCAL ||
964 version_index == ELF::VER_NDX_GLOBAL) {
966 return StringRef("");
969 // Lookup this symbol in the version table
971 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
972 return object_error::parse_failed;
973 const VersionMapEntry &entry = VersionMap[version_index];
975 // Get the version name string
977 if (entry.isVerdef()) {
978 // The first Verdaux entry holds the name.
979 name_offset = entry.getVerdef()->getAux()->vda_name;
981 name_offset = entry.getVernaux()->vna_name;
985 if (entry.isVerdef()) {
986 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
991 if (name_offset >= DynStrRegion.Size)
992 return object_error::parse_failed;
993 return StringRef(getDynamicString(name_offset));
996 /// This function returns the hash value for a symbol in the .dynsym section
997 /// Name of the API remains consistent as specified in the libelf
998 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
999 static inline unsigned elf_hash(StringRef &symbolName) {
1001 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1002 h = (h << 4) + symbolName[i];
1003 g = h & 0xf0000000L;
1010 } // end namespace object
1011 } // end namespace llvm