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((uint8_t)ELF::ELFCLASSNONE,
46 (uint8_t)ELF::ELFDATANONE);
47 return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
48 (uint8_t)Object[ELF::EI_DATA]);
54 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
55 typedef typename std::conditional<ELFT::Is64Bits,
56 uint64_t, uint32_t>::type uintX_t;
58 /// \brief Iterate over constant sized entities.
60 class ELFEntityIterator {
62 typedef ptrdiff_t difference_type;
63 typedef EntT value_type;
64 typedef std::forward_iterator_tag iterator_category;
65 typedef value_type &reference;
66 typedef value_type *pointer;
68 /// \brief Default construct iterator.
69 ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
70 ELFEntityIterator(uintX_t EntSize, const char *Start)
71 : EntitySize(EntSize), Current(Start) {}
73 reference operator *() {
74 assert(Current && "Attempted to dereference an invalid iterator!");
75 return *reinterpret_cast<pointer>(Current);
78 pointer operator ->() {
79 assert(Current && "Attempted to dereference an invalid iterator!");
80 return reinterpret_cast<pointer>(Current);
83 bool operator ==(const ELFEntityIterator &Other) {
84 return Current == Other.Current;
87 bool operator !=(const ELFEntityIterator &Other) {
88 return !(*this == Other);
91 ELFEntityIterator &operator ++() {
92 assert(Current && "Attempted to increment an invalid iterator!");
93 Current += EntitySize;
97 ELFEntityIterator &operator+(difference_type n) {
98 assert(Current && "Attempted to increment an invalid iterator!");
99 Current += (n * EntitySize);
103 ELFEntityIterator &operator-(difference_type n) {
104 assert(Current && "Attempted to subtract an invalid iterator!");
105 Current -= (n * EntitySize);
109 ELFEntityIterator operator ++(int) {
110 ELFEntityIterator Tmp = *this;
115 difference_type operator -(const ELFEntityIterator &Other) const {
116 assert(EntitySize == Other.EntitySize &&
117 "Subtracting iterators of different EntitySize!");
118 return (Current - Other.Current) / EntitySize;
121 const char *get() const { return Current; }
123 uintX_t getEntSize() const { return EntitySize; }
130 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
131 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
132 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
133 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
134 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
135 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
136 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
137 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
138 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
139 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
140 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
141 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
142 typedef Elf_Hash_Impl<ELFT> Elf_Hash;
143 typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
144 typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
145 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
146 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
147 typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
149 /// \brief Archive files are 2 byte aligned, so we need this for
150 /// PointerIntPair to work.
151 template <typename T>
152 class ArchivePointerTypeTraits {
154 static inline const void *getAsVoidPointer(T *P) { return P; }
155 static inline T *getFromVoidPointer(const void *P) {
156 return static_cast<T *>(P);
158 enum { NumLowBitsAvailable = 1 };
161 typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
164 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
165 typedef DenseMap<unsigned, unsigned> IndexMap_t;
169 const uint8_t *base() const {
170 return reinterpret_cast<const uint8_t *>(Buf.data());
173 const Elf_Ehdr *Header;
174 const Elf_Shdr *SectionHeaderTable = nullptr;
175 StringRef DotShstrtab; // Section header string table.
176 StringRef DotStrtab; // Symbol header string table.
177 const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
178 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
179 const Elf_Hash *HashTable = nullptr;
181 const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
182 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
184 const Elf_Shdr *dot_gnu_version_sec = nullptr; // .gnu.version
185 const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
186 const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
188 /// \brief Represents a region described by entries in the .dynamic table.
189 struct DynRegionInfo {
190 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
191 /// \brief Address in current address space.
193 /// \brief Size in bytes of the region.
195 /// \brief Size of each entity in the region.
199 DynRegionInfo DynamicRegion;
200 DynRegionInfo DynHashRegion;
201 DynRegionInfo DynStrRegion;
202 DynRegionInfo DynRelaRegion;
204 // Pointer to SONAME entry in dynamic string table
205 // This is set the first time getLoadName is called.
206 mutable const char *dt_soname = nullptr;
208 // Records for each version index the corresponding Verdef or Vernaux entry.
209 // This is filled the first time LoadVersionMap() is called.
210 class VersionMapEntry : public PointerIntPair<const void*, 1> {
212 // If the integer is 0, this is an Elf_Verdef*.
213 // If the integer is 1, this is an Elf_Vernaux*.
214 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
215 VersionMapEntry(const Elf_Verdef *verdef)
216 : PointerIntPair<const void*, 1>(verdef, 0) { }
217 VersionMapEntry(const Elf_Vernaux *vernaux)
218 : PointerIntPair<const void*, 1>(vernaux, 1) { }
219 bool isNull() const { return getPointer() == nullptr; }
220 bool isVerdef() const { return !isNull() && getInt() == 0; }
221 bool isVernaux() const { return !isNull() && getInt() == 1; }
222 const Elf_Verdef *getVerdef() const {
223 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
225 const Elf_Vernaux *getVernaux() const {
226 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
229 mutable SmallVector<VersionMapEntry, 16> VersionMap;
230 void LoadVersionDefs(const Elf_Shdr *sec) const;
231 void LoadVersionNeeds(const Elf_Shdr *ec) const;
232 void LoadVersionMap() const;
234 void scanDynamicTable();
238 const T *getEntry(uint32_t Section, uint32_t Entry) const;
239 template <typename T>
240 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
242 const Elf_Shdr *getDotSymtabSec() const { return dot_symtab_sec; }
243 const Elf_Shdr *getDotDynSymSec() const { return DotDynSymSec; }
244 const Elf_Hash *getHashTable() const { return HashTable; }
246 ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
247 const char *getDynamicString(uintX_t Offset) const;
248 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
250 bool &IsDefault) const;
251 void VerifyStrTab(const Elf_Shdr *sh) const;
253 StringRef getRelocationTypeName(uint32_t Type) const;
254 void getRelocationTypeName(uint32_t Type,
255 SmallVectorImpl<char> &Result) const;
257 /// \brief Get the symbol table section and symbol for a given relocation.
258 template <class RelT>
259 std::pair<const Elf_Shdr *, const Elf_Sym *>
260 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
262 ELFFile(StringRef Object, std::error_code &EC);
264 bool isMipsELF64() const {
265 return Header->e_machine == ELF::EM_MIPS &&
266 Header->getFileClass() == ELF::ELFCLASS64;
269 bool isMips64EL() const {
270 return Header->e_machine == ELF::EM_MIPS &&
271 Header->getFileClass() == ELF::ELFCLASS64 &&
272 Header->getDataEncoding() == ELF::ELFDATA2LSB;
275 const Elf_Shdr *section_begin() const;
276 const Elf_Shdr *section_end() const;
277 Elf_Shdr_Range sections() const {
278 return make_range(section_begin(), section_end());
281 const Elf_Sym *symbol_begin() const;
282 const Elf_Sym *symbol_end() const;
283 Elf_Sym_Range symbols() const {
284 return make_range(symbol_begin(), symbol_end());
287 Elf_Dyn_Iter dynamic_table_begin() const;
288 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
289 /// the section size.
290 Elf_Dyn_Iter dynamic_table_end(bool NULLEnd = false) const;
291 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
292 return make_range(dynamic_table_begin(), dynamic_table_end(NULLEnd));
295 const Elf_Sym *dynamic_symbol_begin() const {
298 if (DotDynSymSec->sh_entsize != sizeof(Elf_Sym))
299 report_fatal_error("Invalid symbol size");
300 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset);
303 const Elf_Sym *dynamic_symbol_end() const {
306 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset +
307 DotDynSymSec->sh_size);
310 Elf_Sym_Range dynamic_symbols() const {
311 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
314 Elf_Rela_Iter dyn_rela_begin() const {
315 if (DynRelaRegion.Addr)
316 return Elf_Rela_Iter(DynRelaRegion.EntSize,
317 (const char *)DynRelaRegion.Addr);
318 return Elf_Rela_Iter(0, nullptr);
321 Elf_Rela_Iter dyn_rela_end() const {
322 if (DynRelaRegion.Addr)
323 return Elf_Rela_Iter(
324 DynRelaRegion.EntSize,
325 (const char *)DynRelaRegion.Addr + DynRelaRegion.Size);
326 return Elf_Rela_Iter(0, nullptr);
329 Elf_Rela_Iter rela_begin(const Elf_Shdr *sec) const {
330 return Elf_Rela_Iter(sec->sh_entsize,
331 (const char *)(base() + sec->sh_offset));
334 Elf_Rela_Iter rela_end(const Elf_Shdr *sec) const {
335 return Elf_Rela_Iter(
337 (const char *)(base() + sec->sh_offset + sec->sh_size));
340 Elf_Rel_Iter rel_begin(const Elf_Shdr *sec) const {
341 return Elf_Rel_Iter(sec->sh_entsize,
342 (const char *)(base() + sec->sh_offset));
345 Elf_Rel_Iter rel_end(const Elf_Shdr *sec) const {
346 return Elf_Rel_Iter(sec->sh_entsize,
347 (const char *)(base() + sec->sh_offset + sec->sh_size));
350 /// \brief Iterate over program header table.
351 const Elf_Phdr *program_header_begin() const {
352 if (Header->e_phnum && Header->e_phentsize != sizeof(Elf_Phdr))
353 report_fatal_error("Invalid program header size");
354 return reinterpret_cast<const Elf_Phdr *>(base() + Header->e_phoff);
357 const Elf_Phdr *program_header_end() const {
358 return program_header_begin() + Header->e_phnum;
361 typedef iterator_range<const Elf_Phdr *> Elf_Phdr_Range;
363 const Elf_Phdr_Range program_headers() const {
364 return make_range(program_header_begin(), program_header_end());
367 uint64_t getNumSections() const;
368 uintX_t getStringTableIndex() const;
369 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
370 const Elf_Ehdr *getHeader() const { return Header; }
371 ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
372 ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
373 const Elf_Sym *getSymbol(uint32_t index) const;
375 ErrorOr<StringRef> getStaticSymbolName(const Elf_Sym *Symb) const;
376 ErrorOr<StringRef> getDynamicSymbolName(const Elf_Sym *Symb) const;
377 ErrorOr<StringRef> getSymbolName(const Elf_Sym *Symb, bool IsDynamic) const;
379 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
380 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
381 StringRef getLoadName() const;
384 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
385 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
386 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
387 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
389 // Iterate through the version definitions, and place each Elf_Verdef
390 // in the VersionMap according to its index.
391 template <class ELFT>
392 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
393 unsigned vd_size = sec->sh_size; // Size of section in bytes
394 unsigned vd_count = sec->sh_info; // Number of Verdef entries
395 const char *sec_start = (const char*)base() + sec->sh_offset;
396 const char *sec_end = sec_start + vd_size;
397 // The first Verdef entry is at the start of the section.
398 const char *p = sec_start;
399 for (unsigned i = 0; i < vd_count; i++) {
400 if (p + sizeof(Elf_Verdef) > sec_end)
401 report_fatal_error("Section ended unexpectedly while scanning "
402 "version definitions.");
403 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
404 if (vd->vd_version != ELF::VER_DEF_CURRENT)
405 report_fatal_error("Unexpected verdef version");
406 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
407 if (index >= VersionMap.size())
408 VersionMap.resize(index + 1);
409 VersionMap[index] = VersionMapEntry(vd);
414 // Iterate through the versions needed section, and place each Elf_Vernaux
415 // in the VersionMap according to its index.
416 template <class ELFT>
417 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
418 unsigned vn_size = sec->sh_size; // Size of section in bytes
419 unsigned vn_count = sec->sh_info; // Number of Verneed entries
420 const char *sec_start = (const char *)base() + sec->sh_offset;
421 const char *sec_end = sec_start + vn_size;
422 // The first Verneed entry is at the start of the section.
423 const char *p = sec_start;
424 for (unsigned i = 0; i < vn_count; i++) {
425 if (p + sizeof(Elf_Verneed) > sec_end)
426 report_fatal_error("Section ended unexpectedly while scanning "
427 "version needed records.");
428 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
429 if (vn->vn_version != ELF::VER_NEED_CURRENT)
430 report_fatal_error("Unexpected verneed version");
431 // Iterate through the Vernaux entries
432 const char *paux = p + vn->vn_aux;
433 for (unsigned j = 0; j < vn->vn_cnt; j++) {
434 if (paux + sizeof(Elf_Vernaux) > sec_end)
435 report_fatal_error("Section ended unexpected while scanning auxiliary "
436 "version needed records.");
437 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
438 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
439 if (index >= VersionMap.size())
440 VersionMap.resize(index + 1);
441 VersionMap[index] = VersionMapEntry(vna);
442 paux += vna->vna_next;
448 template <class ELFT>
449 void ELFFile<ELFT>::LoadVersionMap() const {
450 // If there is no dynamic symtab or version table, there is nothing to do.
451 if (!DotDynSymSec || !dot_gnu_version_sec)
454 // Has the VersionMap already been loaded?
455 if (VersionMap.size() > 0)
458 // The first two version indexes are reserved.
459 // Index 0 is LOCAL, index 1 is GLOBAL.
460 VersionMap.push_back(VersionMapEntry());
461 VersionMap.push_back(VersionMapEntry());
463 if (dot_gnu_version_d_sec)
464 LoadVersionDefs(dot_gnu_version_d_sec);
466 if (dot_gnu_version_r_sec)
467 LoadVersionNeeds(dot_gnu_version_r_sec);
470 template <class ELFT>
472 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
473 assert(symb->st_shndx == ELF::SHN_XINDEX);
474 return ExtendedSymbolTable.lookup(symb);
477 template <class ELFT>
478 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
479 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
480 uint32_t Index = symb->st_shndx;
481 if (Index == ELF::SHN_XINDEX)
482 return getSection(ExtendedSymbolTable.lookup(symb));
483 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
485 return getSection(symb->st_shndx);
488 template <class ELFT>
489 const typename ELFFile<ELFT>::Elf_Sym *
490 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
491 return &*(symbol_begin() + Index);
494 template <class ELFT>
495 ErrorOr<ArrayRef<uint8_t> >
496 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
497 if (Sec->sh_offset + Sec->sh_size > Buf.size())
498 return object_error::parse_failed;
499 const uint8_t *Start = base() + Sec->sh_offset;
500 return makeArrayRef(Start, Sec->sh_size);
503 template <class ELFT>
504 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
505 return getELFRelocationTypeName(Header->e_machine, Type);
508 template <class ELFT>
509 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
510 SmallVectorImpl<char> &Result) const {
511 if (!isMipsELF64()) {
512 StringRef Name = getRelocationTypeName(Type);
513 Result.append(Name.begin(), Name.end());
515 // The Mips N64 ABI allows up to three operations to be specified per
516 // relocation record. Unfortunately there's no easy way to test for the
517 // presence of N64 ELFs as they have no special flag that identifies them
518 // as being N64. We can safely assume at the moment that all Mips
519 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
520 // information to disambiguate between old vs new ABIs.
521 uint8_t Type1 = (Type >> 0) & 0xFF;
522 uint8_t Type2 = (Type >> 8) & 0xFF;
523 uint8_t Type3 = (Type >> 16) & 0xFF;
525 // Concat all three relocation type names.
526 StringRef Name = getRelocationTypeName(Type1);
527 Result.append(Name.begin(), Name.end());
529 Name = getRelocationTypeName(Type2);
530 Result.append(1, '/');
531 Result.append(Name.begin(), Name.end());
533 Name = getRelocationTypeName(Type3);
534 Result.append(1, '/');
535 Result.append(Name.begin(), Name.end());
539 template <class ELFT>
540 template <class RelT>
541 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
542 const typename ELFFile<ELFT>::Elf_Sym *>
543 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
545 return std::make_pair(nullptr, nullptr);
546 ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
547 if (std::error_code EC = SymTableOrErr.getError())
548 report_fatal_error(EC.message());
549 const Elf_Shdr *SymTable = *SymTableOrErr;
550 return std::make_pair(
551 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
554 template <class ELFT>
555 uint64_t ELFFile<ELFT>::getNumSections() const {
556 assert(Header && "Header not initialized!");
557 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
558 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
559 return SectionHeaderTable->sh_size;
561 return Header->e_shnum;
564 template <class ELFT>
565 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
566 if (Header->e_shnum == ELF::SHN_UNDEF) {
567 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
568 return SectionHeaderTable->sh_link;
569 if (Header->e_shstrndx >= getNumSections())
572 return Header->e_shstrndx;
575 template <class ELFT>
576 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
578 const uint64_t FileSize = Buf.size();
580 if (sizeof(Elf_Ehdr) > FileSize) {
582 EC = object_error::parse_failed;
586 Header = reinterpret_cast<const Elf_Ehdr *>(base());
588 if (Header->e_shoff == 0) {
593 const uint64_t SectionTableOffset = Header->e_shoff;
595 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
596 // Section header table goes past end of file!
597 EC = object_error::parse_failed;
601 // The getNumSections() call below depends on SectionHeaderTable being set.
603 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
604 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
606 if (SectionTableOffset + SectionTableSize > FileSize) {
607 // Section table goes past end of file!
608 EC = object_error::parse_failed;
612 // Scan sections for special sections.
614 for (const Elf_Shdr &Sec : sections()) {
615 switch (Sec.sh_type) {
618 EC = object_error::parse_failed;
621 HashTable = reinterpret_cast<const Elf_Hash *>(base() + Sec.sh_offset);
623 case ELF::SHT_SYMTAB_SHNDX:
624 if (SymbolTableSectionHeaderIndex) {
625 // More than one .symtab_shndx!
626 EC = object_error::parse_failed;
629 SymbolTableSectionHeaderIndex = &Sec;
631 case ELF::SHT_SYMTAB: {
632 if (dot_symtab_sec) {
633 // More than one .symtab!
634 EC = object_error::parse_failed;
637 dot_symtab_sec = &Sec;
638 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
639 if ((EC = SectionOrErr.getError()))
641 ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
642 if ((EC = SymtabOrErr.getError()))
644 DotStrtab = *SymtabOrErr;
646 case ELF::SHT_DYNSYM: {
648 // More than one .dynsym!
649 EC = object_error::parse_failed;
653 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
654 if ((EC = SectionOrErr.getError()))
656 ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
657 if ((EC = SymtabOrErr.getError()))
659 DynStrRegion.Addr = SymtabOrErr->data();
660 DynStrRegion.Size = SymtabOrErr->size();
661 DynStrRegion.EntSize = 1;
664 case ELF::SHT_DYNAMIC:
665 if (DynamicRegion.Addr) {
666 // More than one .dynamic!
667 EC = object_error::parse_failed;
670 DynamicRegion.Addr = base() + Sec.sh_offset;
671 DynamicRegion.Size = Sec.sh_size;
672 DynamicRegion.EntSize = Sec.sh_entsize;
674 case ELF::SHT_GNU_versym:
675 if (dot_gnu_version_sec != nullptr) {
676 // More than one .gnu.version section!
677 EC = object_error::parse_failed;
680 dot_gnu_version_sec = &Sec;
682 case ELF::SHT_GNU_verdef:
683 if (dot_gnu_version_d_sec != nullptr) {
684 // More than one .gnu.version_d section!
685 EC = object_error::parse_failed;
688 dot_gnu_version_d_sec = &Sec;
690 case ELF::SHT_GNU_verneed:
691 if (dot_gnu_version_r_sec != nullptr) {
692 // More than one .gnu.version_r section!
693 EC = object_error::parse_failed;
696 dot_gnu_version_r_sec = &Sec;
701 // Get string table sections.
702 ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(getStringTableIndex());
703 if ((EC = StrTabSecOrErr.getError()))
706 ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
707 if ((EC = SymtabOrErr.getError()))
709 DotShstrtab = *SymtabOrErr;
711 // Build symbol name side-mapping if there is one.
712 if (SymbolTableSectionHeaderIndex) {
713 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
714 SymbolTableSectionHeaderIndex->sh_offset);
715 for (const Elf_Sym &S : symbols()) {
716 if (*ShndxTable != ELF::SHN_UNDEF)
717 ExtendedSymbolTable[&S] = *ShndxTable;
724 EC = std::error_code();
727 template <class ELFT>
728 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
729 return VAddr < Phdr->p_vaddr;
732 template <class ELFT> void ELFFile<ELFT>::scanDynamicTable() {
733 SmallVector<const Elf_Phdr *, 4> LoadSegments;
734 for (const Elf_Phdr &Phdr : program_headers()) {
735 if (Phdr.p_type == ELF::PT_DYNAMIC) {
736 DynamicRegion.Addr = base() + Phdr.p_offset;
737 DynamicRegion.Size = Phdr.p_filesz;
738 DynamicRegion.EntSize = sizeof(Elf_Dyn);
741 if (Phdr.p_type != ELF::PT_LOAD || Phdr.p_filesz == 0)
743 LoadSegments.push_back(&Phdr);
746 auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t * {
747 const Elf_Phdr **I = std::upper_bound(
748 LoadSegments.begin(), LoadSegments.end(), VAddr, compareAddr<ELFT>);
749 if (I == LoadSegments.begin())
752 return this->base() + (*I)->p_offset + (VAddr - (*I)->p_vaddr);
755 for (Elf_Dyn_Iter DynI = dynamic_table_begin(), DynE = dynamic_table_end();
756 DynI != DynE; ++DynI) {
757 switch (DynI->d_tag) {
762 reinterpret_cast<const Elf_Hash *>(toMappedAddr(DynI->getPtr()));
765 if (!DynStrRegion.Addr)
766 DynStrRegion.Addr = toMappedAddr(DynI->getPtr());
769 if (!DynStrRegion.Size)
770 DynStrRegion.Size = DynI->getVal();
773 if (!DynRelaRegion.Addr)
774 DynRelaRegion.Addr = toMappedAddr(DynI->getPtr());
777 DynRelaRegion.Size = DynI->getVal();
779 case ELF::DT_RELAENT:
780 DynRelaRegion.EntSize = DynI->getVal();
785 template <class ELFT>
786 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
787 if (Header->e_shentsize != sizeof(Elf_Shdr))
789 "Invalid section header entry size (e_shentsize) in ELF header");
790 return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
793 template <class ELFT>
794 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
795 return section_begin() + getNumSections();
798 template <class ELFT>
799 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
802 if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
803 report_fatal_error("Invalid symbol size");
804 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
807 template <class ELFT>
808 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
811 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
812 dot_symtab_sec->sh_size);
815 template <class ELFT>
816 typename ELFFile<ELFT>::Elf_Dyn_Iter
817 ELFFile<ELFT>::dynamic_table_begin() const {
818 if (DynamicRegion.Addr)
819 return Elf_Dyn_Iter(DynamicRegion.EntSize,
820 (const char *)DynamicRegion.Addr);
821 return Elf_Dyn_Iter(0, nullptr);
824 template <class ELFT>
825 typename ELFFile<ELFT>::Elf_Dyn_Iter
826 ELFFile<ELFT>::dynamic_table_end(bool NULLEnd) const {
827 if (!DynamicRegion.Addr)
828 return Elf_Dyn_Iter(0, nullptr);
829 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
830 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
833 Elf_Dyn_Iter Start = dynamic_table_begin();
834 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
837 // Include the DT_NULL.
845 template <class ELFT>
846 StringRef ELFFile<ELFT>::getLoadName() const {
849 // Find the DT_SONAME entry
850 for (const auto &Entry : dynamic_table())
851 if (Entry.getTag() == ELF::DT_SONAME) {
852 dt_soname = getDynamicString(Entry.getVal());
859 template <class ELFT>
860 template <typename T>
861 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
862 ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
863 if (std::error_code EC = Sec.getError())
864 report_fatal_error(EC.message());
865 return getEntry<T>(*Sec, Entry);
868 template <class ELFT>
869 template <typename T>
870 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
871 uint32_t Entry) const {
872 return reinterpret_cast<const T *>(base() + Section->sh_offset +
873 (Entry * Section->sh_entsize));
876 template <class ELFT>
877 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
878 ELFFile<ELFT>::getSection(uint32_t Index) const {
879 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
880 if (Index >= getNumSections())
881 return object_error::invalid_section_index;
883 return reinterpret_cast<const Elf_Shdr *>(
884 reinterpret_cast<const char *>(SectionHeaderTable) +
885 (Index * Header->e_shentsize));
888 template <class ELFT>
890 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
891 if (Section->sh_type != ELF::SHT_STRTAB)
892 return object_error::parse_failed;
893 uint64_t Offset = Section->sh_offset;
894 uint64_t Size = Section->sh_size;
895 if (Offset + Size > Buf.size())
896 return object_error::parse_failed;
897 StringRef Data((const char *)base() + Section->sh_offset, Size);
898 if (Data[Size - 1] != '\0')
899 return object_error::string_table_non_null_end;
903 template <class ELFT>
904 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
905 if (Offset >= DynStrRegion.Size)
907 return (const char *)DynStrRegion.Addr + Offset;
910 template <class ELFT>
912 ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
913 return Symb->getName(DotStrtab);
916 template <class ELFT>
918 ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
919 return StringRef(getDynamicString(Symb->st_name));
922 template <class ELFT>
923 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Sym *Symb,
924 bool IsDynamic) const {
926 return getDynamicSymbolName(Symb);
927 return getStaticSymbolName(Symb);
930 template <class ELFT>
932 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
933 uint32_t Offset = Section->sh_name;
934 if (Offset >= DotShstrtab.size())
935 return object_error::parse_failed;
936 return StringRef(DotShstrtab.data() + Offset);
939 template <class ELFT>
940 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
942 bool &IsDefault) const {
945 ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
946 if (std::error_code EC = StrTabOrErr.getError())
948 StrTab = *StrTabOrErr;
950 // Handle non-dynamic symbols.
951 if (section != DotDynSymSec && section != nullptr) {
952 // Non-dynamic symbols can have versions in their names
953 // A name of the form 'foo@V1' indicates version 'V1', non-default.
954 // A name of the form 'foo@@V2' indicates version 'V2', default version.
955 ErrorOr<StringRef> SymName = symb->getName(StrTab);
958 StringRef Name = *SymName;
959 size_t atpos = Name.find('@');
960 if (atpos == StringRef::npos) {
962 return StringRef("");
965 if (atpos < Name.size() && Name[atpos] == '@') {
971 return Name.substr(atpos);
974 // This is a dynamic symbol. Look in the GNU symbol version table.
975 if (!dot_gnu_version_sec) {
978 return StringRef("");
981 // Determine the position in the symbol table of this entry.
983 (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
984 reinterpret_cast<uintptr_t>(base())) /
987 // Get the corresponding version index entry
988 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
989 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
991 // Special markers for unversioned symbols.
992 if (version_index == ELF::VER_NDX_LOCAL ||
993 version_index == ELF::VER_NDX_GLOBAL) {
995 return StringRef("");
998 // Lookup this symbol in the version table
1000 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
1001 return object_error::parse_failed;
1002 const VersionMapEntry &entry = VersionMap[version_index];
1004 // Get the version name string
1006 if (entry.isVerdef()) {
1007 // The first Verdaux entry holds the name.
1008 name_offset = entry.getVerdef()->getAux()->vda_name;
1010 name_offset = entry.getVernaux()->vna_name;
1014 if (entry.isVerdef()) {
1015 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
1020 if (name_offset >= DynStrRegion.Size)
1021 return object_error::parse_failed;
1022 return StringRef(getDynamicString(name_offset));
1025 /// This function returns the hash value for a symbol in the .dynsym section
1026 /// Name of the API remains consistent as specified in the libelf
1027 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1028 static inline unsigned elf_hash(StringRef &symbolName) {
1030 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1031 h = (h << 4) + symbolName[i];
1032 g = h & 0xf0000000L;
1039 } // end namespace object
1040 } // end namespace llvm