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/IntervalMap.h"
20 #include "llvm/ADT/PointerIntPair.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"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ErrorOr.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/raw_ostream.h"
40 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
42 // Subclasses of ELFFile may need this for template instantiation
43 inline std::pair<unsigned char, unsigned char>
44 getElfArchType(StringRef Object) {
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]);
55 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
56 typedef typename std::conditional<ELFT::Is64Bits,
57 uint64_t, uint32_t>::type uintX_t;
59 /// \brief Iterate over constant sized entities.
61 class ELFEntityIterator {
63 typedef ptrdiff_t difference_type;
64 typedef EntT value_type;
65 typedef std::forward_iterator_tag iterator_category;
66 typedef value_type &reference;
67 typedef value_type *pointer;
69 /// \brief Default construct iterator.
70 ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
71 ELFEntityIterator(uintX_t EntSize, const char *Start)
72 : EntitySize(EntSize), Current(Start) {}
74 reference operator *() {
75 assert(Current && "Attempted to dereference an invalid iterator!");
76 return *reinterpret_cast<pointer>(Current);
79 pointer operator ->() {
80 assert(Current && "Attempted to dereference an invalid iterator!");
81 return reinterpret_cast<pointer>(Current);
84 bool operator ==(const ELFEntityIterator &Other) {
85 return Current == Other.Current;
88 bool operator !=(const ELFEntityIterator &Other) {
89 return !(*this == Other);
92 ELFEntityIterator &operator ++() {
93 assert(Current && "Attempted to increment an invalid iterator!");
94 Current += EntitySize;
98 ELFEntityIterator &operator+(difference_type n) {
99 assert(Current && "Attempted to increment an invalid iterator!");
100 Current += (n * EntitySize);
104 ELFEntityIterator &operator-(difference_type n) {
105 assert(Current && "Attempted to subtract an invalid iterator!");
106 Current -= (n * EntitySize);
110 ELFEntityIterator operator ++(int) {
111 ELFEntityIterator Tmp = *this;
116 difference_type operator -(const ELFEntityIterator &Other) const {
117 assert(EntitySize == Other.EntitySize &&
118 "Subtracting iterators of different EntitySize!");
119 return (Current - Other.Current) / EntitySize;
122 const char *get() const { return Current; }
124 uintX_t getEntSize() const { return EntitySize; }
131 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
132 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
133 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
134 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
135 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
136 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
137 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
138 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
139 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
140 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
141 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
142 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
143 typedef Elf_Hash<ELFT> Elf_Hash;
144 typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
145 typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
146 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
147 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
148 typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
150 /// \brief Archive files are 2 byte aligned, so we need this for
151 /// PointerIntPair to work.
152 template <typename T>
153 class ArchivePointerTypeTraits {
155 static inline const void *getAsVoidPointer(T *P) { return P; }
156 static inline T *getFromVoidPointer(const void *P) {
157 return static_cast<T *>(P);
159 enum { NumLowBitsAvailable = 1 };
162 typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
165 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
166 typedef DenseMap<unsigned, unsigned> IndexMap_t;
170 const uint8_t *base() const {
171 return reinterpret_cast<const uint8_t *>(Buf.data());
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 StringRef DynSymStrTab; // Dynnamic symbol string table.
180 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
181 const Elf_Hash *HashTable = nullptr;
183 const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
184 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
186 const Elf_Shdr *dot_gnu_version_sec = nullptr; // .gnu.version
187 const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
188 const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
190 /// \brief Represents a region described by entries in the .dynamic table.
191 struct DynRegionInfo {
192 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
193 /// \brief Address in current address space.
195 /// \brief Size in bytes of the region.
197 /// \brief Size of each entity in the region.
201 DynRegionInfo DynamicRegion;
202 DynRegionInfo DynHashRegion;
203 DynRegionInfo DynRelaRegion;
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;
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> {
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;
226 const Elf_Vernaux *getVernaux() const {
227 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
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;
235 void scanDynamicTable();
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;
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; }
247 ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
248 const char *getDynamicString(uintX_t Offset) const;
249 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
251 bool &IsDefault) const;
252 void VerifyStrTab(const Elf_Shdr *sh) const;
254 StringRef getRelocationTypeName(uint32_t Type) const;
255 void getRelocationTypeName(uint32_t Type,
256 SmallVectorImpl<char> &Result) const;
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;
263 ELFFile(StringRef Object, std::error_code &EC);
265 bool isMipsELF64() const {
266 return Header->e_machine == ELF::EM_MIPS &&
267 Header->getFileClass() == ELF::ELFCLASS64;
270 bool isMips64EL() const {
271 return Header->e_machine == ELF::EM_MIPS &&
272 Header->getFileClass() == ELF::ELFCLASS64 &&
273 Header->getDataEncoding() == ELF::ELFDATA2LSB;
276 const Elf_Shdr *section_begin() const;
277 const Elf_Shdr *section_end() const;
278 Elf_Shdr_Range sections() const {
279 return make_range(section_begin(), section_end());
282 const Elf_Sym *symbol_begin() const;
283 const Elf_Sym *symbol_end() const;
284 Elf_Sym_Range symbols() const {
285 return make_range(symbol_begin(), symbol_end());
288 Elf_Dyn_Iter dynamic_table_begin() const;
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 {
293 return make_range(dynamic_table_begin(), dynamic_table_end(NULLEnd));
296 const Elf_Sym *dynamic_symbol_begin() const {
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);
304 const Elf_Sym *dynamic_symbol_end() const {
307 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset +
308 DotDynSymSec->sh_size);
311 Elf_Sym_Range dynamic_symbols() const {
312 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
315 Elf_Rela_Iter dyn_rela_begin() const {
316 if (DynRelaRegion.Addr)
317 return Elf_Rela_Iter(DynRelaRegion.EntSize,
318 (const char *)DynRelaRegion.Addr);
319 return Elf_Rela_Iter(0, nullptr);
322 Elf_Rela_Iter dyn_rela_end() const {
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);
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));
335 Elf_Rela_Iter rela_end(const Elf_Shdr *sec) const {
336 return Elf_Rela_Iter(
338 (const char *)(base() + sec->sh_offset + sec->sh_size));
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));
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));
351 /// \brief Iterate over program header table.
352 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
354 Elf_Phdr_Iter program_header_begin() const {
355 return Elf_Phdr_Iter(Header->e_phentsize,
356 (const char*)base() + Header->e_phoff);
359 Elf_Phdr_Iter program_header_end() const {
360 return Elf_Phdr_Iter(Header->e_phentsize,
361 (const char*)base() +
363 (Header->e_phnum * Header->e_phentsize));
366 uint64_t getNumSections() const;
367 uintX_t getStringTableIndex() const;
368 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) 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;
374 ErrorOr<StringRef> getStaticSymbolName(const Elf_Sym *Symb) const;
375 ErrorOr<StringRef> getDynamicSymbolName(const Elf_Sym *Symb) const;
376 ErrorOr<StringRef> getSymbolName(const Elf_Sym *Symb, bool IsDynamic) const;
378 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
379 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
380 StringRef getLoadName() const;
383 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
384 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
385 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
386 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
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);
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;
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)
453 // Has the VersionMap already been loaded?
454 if (VersionMap.size() > 0)
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());
462 if (dot_gnu_version_d_sec)
463 LoadVersionDefs(dot_gnu_version_d_sec);
465 if (dot_gnu_version_r_sec)
466 LoadVersionNeeds(dot_gnu_version_r_sec);
469 template <class ELFT>
471 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
472 assert(symb->st_shndx == ELF::SHN_XINDEX);
473 return ExtendedSymbolTable.lookup(symb);
476 template <class ELFT>
477 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
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)
484 return getSection(symb->st_shndx);
487 template <class ELFT>
488 const typename ELFFile<ELFT>::Elf_Sym *
489 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
490 return &*(symbol_begin() + Index);
493 template <class ELFT>
494 ErrorOr<ArrayRef<uint8_t> >
495 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
496 if (Sec->sh_offset + Sec->sh_size > Buf.size())
497 return object_error::parse_failed;
498 const uint8_t *Start = base() + Sec->sh_offset;
499 return makeArrayRef(Start, Sec->sh_size);
502 template <class ELFT>
503 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
504 return getELFRelocationTypeName(Header->e_machine, Type);
507 template <class ELFT>
508 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
509 SmallVectorImpl<char> &Result) const {
510 if (!isMipsELF64()) {
511 StringRef Name = getRelocationTypeName(Type);
512 Result.append(Name.begin(), Name.end());
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;
524 // Concat all three relocation type names.
525 StringRef Name = getRelocationTypeName(Type1);
526 Result.append(Name.begin(), Name.end());
528 Name = getRelocationTypeName(Type2);
529 Result.append(1, '/');
530 Result.append(Name.begin(), Name.end());
532 Name = getRelocationTypeName(Type3);
533 Result.append(1, '/');
534 Result.append(Name.begin(), Name.end());
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 {
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())));
553 template <class ELFT>
554 uint64_t ELFFile<ELFT>::getNumSections() const {
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;
560 return Header->e_shnum;
563 template <class ELFT>
564 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
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())
571 return Header->e_shstrndx;
574 template <class ELFT>
575 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
577 const uint64_t FileSize = Buf.size();
579 if (sizeof(Elf_Ehdr) > FileSize) {
581 EC = object_error::parse_failed;
585 Header = reinterpret_cast<const Elf_Ehdr *>(base());
587 if (Header->e_shoff == 0) {
592 const uint64_t SectionTableOffset = Header->e_shoff;
594 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
595 // Section header table goes past end of file!
596 EC = object_error::parse_failed;
600 // The getNumSections() call below depends on SectionHeaderTable being set.
602 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
603 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
605 if (SectionTableOffset + SectionTableSize > FileSize) {
606 // Section table goes past end of file!
607 EC = object_error::parse_failed;
611 // Scan sections for special sections.
613 for (const Elf_Shdr &Sec : sections()) {
614 switch (Sec.sh_type) {
617 EC = object_error::parse_failed;
620 HashTable = reinterpret_cast<const Elf_Hash *>(base() + Sec.sh_offset);
622 case ELF::SHT_SYMTAB_SHNDX:
623 if (SymbolTableSectionHeaderIndex) {
624 // More than one .symtab_shndx!
625 EC = object_error::parse_failed;
628 SymbolTableSectionHeaderIndex = &Sec;
630 case ELF::SHT_SYMTAB: {
631 if (dot_symtab_sec) {
632 // More than one .symtab!
633 EC = object_error::parse_failed;
636 dot_symtab_sec = &Sec;
637 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
638 if ((EC = SectionOrErr.getError()))
640 ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
641 if ((EC = SymtabOrErr.getError()))
643 DotStrtab = *SymtabOrErr;
645 case ELF::SHT_DYNSYM: {
647 // More than one .dynsym!
648 EC = object_error::parse_failed;
652 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
653 if ((EC = SectionOrErr.getError()))
655 ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
656 if ((EC = SymtabOrErr.getError()))
658 DynSymStrTab = *SymtabOrErr;
661 case ELF::SHT_DYNAMIC:
662 if (DynamicRegion.Addr) {
663 // More than one .dynamic!
664 EC = object_error::parse_failed;
667 DynamicRegion.Addr = base() + Sec.sh_offset;
668 DynamicRegion.Size = Sec.sh_size;
669 DynamicRegion.EntSize = Sec.sh_entsize;
671 case ELF::SHT_GNU_versym:
672 if (dot_gnu_version_sec != nullptr) {
673 // More than one .gnu.version section!
674 EC = object_error::parse_failed;
677 dot_gnu_version_sec = &Sec;
679 case ELF::SHT_GNU_verdef:
680 if (dot_gnu_version_d_sec != nullptr) {
681 // More than one .gnu.version_d section!
682 EC = object_error::parse_failed;
685 dot_gnu_version_d_sec = &Sec;
687 case ELF::SHT_GNU_verneed:
688 if (dot_gnu_version_r_sec != nullptr) {
689 // More than one .gnu.version_r section!
690 EC = object_error::parse_failed;
693 dot_gnu_version_r_sec = &Sec;
698 // Get string table sections.
699 ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(getStringTableIndex());
700 if ((EC = StrTabSecOrErr.getError()))
703 ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
704 if ((EC = SymtabOrErr.getError()))
706 DotShstrtab = *SymtabOrErr;
708 // Build symbol name side-mapping if there is one.
709 if (SymbolTableSectionHeaderIndex) {
710 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
711 SymbolTableSectionHeaderIndex->sh_offset);
712 for (const Elf_Sym &S : symbols()) {
713 if (*ShndxTable != ELF::SHN_UNDEF)
714 ExtendedSymbolTable[&S] = *ShndxTable;
721 EC = std::error_code();
724 template <class ELFT>
725 void ELFFile<ELFT>::scanDynamicTable() {
726 // Build load-address to file-offset map.
727 typedef typename IntervalMap<
729 IntervalMapImpl::NodeSizer<uintX_t, uintptr_t>::LeafSize,
730 IntervalMapHalfOpenInfo<uintX_t>> LoadMapT;
731 LoadMapT::Allocator Alloc;
732 LoadMapT LoadMap(Alloc);
734 for (Elf_Phdr_Iter PhdrI = program_header_begin(),
735 PhdrE = program_header_end();
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);
743 if (PhdrI->p_type != ELF::PT_LOAD)
745 if (PhdrI->p_filesz == 0)
747 LoadMap.insert(PhdrI->p_vaddr, PhdrI->p_vaddr + PhdrI->p_filesz,
751 auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t * {
752 auto I = LoadMap.find(VAddr);
753 if (I == LoadMap.end())
755 return base() + I.value() + (VAddr - I.start());
758 for (Elf_Dyn_Iter DynI = dynamic_table_begin(), DynE = dynamic_table_end();
759 DynI != DynE; ++DynI) {
760 switch (DynI->d_tag) {
765 reinterpret_cast<const Elf_Hash *>(toMappedAddr(DynI->getPtr()));
768 if (!DynRelaRegion.Addr)
769 DynRelaRegion.Addr = toMappedAddr(DynI->getPtr());
772 DynRelaRegion.Size = DynI->getVal();
774 case ELF::DT_RELAENT:
775 DynRelaRegion.EntSize = DynI->getVal();
780 template <class ELFT>
781 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
782 if (Header->e_shentsize != sizeof(Elf_Shdr))
784 "Invalid section header entry size (e_shentsize) in ELF header");
785 return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
788 template <class ELFT>
789 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
790 return section_begin() + getNumSections();
793 template <class ELFT>
794 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
797 if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
798 report_fatal_error("Invalid symbol size");
799 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
802 template <class ELFT>
803 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
806 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
807 dot_symtab_sec->sh_size);
810 template <class ELFT>
811 typename ELFFile<ELFT>::Elf_Dyn_Iter
812 ELFFile<ELFT>::dynamic_table_begin() const {
813 if (DynamicRegion.Addr)
814 return Elf_Dyn_Iter(DynamicRegion.EntSize,
815 (const char *)DynamicRegion.Addr);
816 return Elf_Dyn_Iter(0, nullptr);
819 template <class ELFT>
820 typename ELFFile<ELFT>::Elf_Dyn_Iter
821 ELFFile<ELFT>::dynamic_table_end(bool NULLEnd) const {
822 if (!DynamicRegion.Addr)
823 return Elf_Dyn_Iter(0, nullptr);
824 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
825 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
828 Elf_Dyn_Iter Start = dynamic_table_begin();
829 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
832 // Include the DT_NULL.
840 template <class ELFT>
841 StringRef ELFFile<ELFT>::getLoadName() const {
844 // Find the DT_SONAME entry
845 for (const auto &Entry : dynamic_table())
846 if (Entry.getTag() == ELF::DT_SONAME) {
847 dt_soname = getDynamicString(Entry.getVal());
854 template <class ELFT>
855 template <typename T>
856 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
857 ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
858 if (std::error_code EC = Sec.getError())
859 report_fatal_error(EC.message());
860 return getEntry<T>(*Sec, Entry);
863 template <class ELFT>
864 template <typename T>
865 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
866 uint32_t Entry) const {
867 return reinterpret_cast<const T *>(base() + Section->sh_offset +
868 (Entry * Section->sh_entsize));
871 template <class ELFT>
872 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
873 ELFFile<ELFT>::getSection(uint32_t Index) const {
874 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
875 if (Index >= getNumSections())
876 return object_error::invalid_section_index;
878 return reinterpret_cast<const Elf_Shdr *>(
879 reinterpret_cast<const char *>(SectionHeaderTable) +
880 (Index * Header->e_shentsize));
883 template <class ELFT>
885 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
886 if (Section->sh_type != ELF::SHT_STRTAB)
887 return object_error::parse_failed;
888 uint64_t Offset = Section->sh_offset;
889 uint64_t Size = Section->sh_size;
890 if (Offset + Size > Buf.size())
891 return object_error::parse_failed;
892 StringRef Data((const char *)base() + Section->sh_offset, Size);
893 if (Data[Size - 1] != '\0')
894 return object_error::string_table_non_null_end;
898 template <class ELFT>
899 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
900 if (!DotDynSymSec || Offset >= DynSymStrTab.size())
902 return (const char *)DynSymStrTab.begin() + Offset;
905 template <class ELFT>
907 ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
908 return Symb->getName(DotStrtab);
911 template <class ELFT>
913 ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
914 return StringRef(getDynamicString(Symb->st_name));
917 template <class ELFT>
918 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Sym *Symb,
919 bool IsDynamic) const {
921 return getDynamicSymbolName(Symb);
922 return getStaticSymbolName(Symb);
925 template <class ELFT>
927 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
928 uint32_t Offset = Section->sh_name;
929 if (Offset >= DotShstrtab.size())
930 return object_error::parse_failed;
931 return StringRef(DotShstrtab.data() + Offset);
934 template <class ELFT>
935 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
937 bool &IsDefault) const {
940 ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
941 if (std::error_code EC = StrTabOrErr.getError())
943 StrTab = *StrTabOrErr;
945 // Handle non-dynamic symbols.
946 if (section != DotDynSymSec && section != nullptr) {
947 // Non-dynamic symbols can have versions in their names
948 // A name of the form 'foo@V1' indicates version 'V1', non-default.
949 // A name of the form 'foo@@V2' indicates version 'V2', default version.
950 ErrorOr<StringRef> SymName = symb->getName(StrTab);
953 StringRef Name = *SymName;
954 size_t atpos = Name.find('@');
955 if (atpos == StringRef::npos) {
957 return StringRef("");
960 if (atpos < Name.size() && Name[atpos] == '@') {
966 return Name.substr(atpos);
969 // This is a dynamic symbol. Look in the GNU symbol version table.
970 if (!dot_gnu_version_sec) {
973 return StringRef("");
976 // Determine the position in the symbol table of this entry.
978 (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
979 reinterpret_cast<uintptr_t>(base())) /
982 // Get the corresponding version index entry
983 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
984 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
986 // Special markers for unversioned symbols.
987 if (version_index == ELF::VER_NDX_LOCAL ||
988 version_index == ELF::VER_NDX_GLOBAL) {
990 return StringRef("");
993 // Lookup this symbol in the version table
995 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
996 return object_error::parse_failed;
997 const VersionMapEntry &entry = VersionMap[version_index];
999 // Get the version name string
1001 if (entry.isVerdef()) {
1002 // The first Verdaux entry holds the name.
1003 name_offset = entry.getVerdef()->getAux()->vda_name;
1005 name_offset = entry.getVernaux()->vna_name;
1009 if (entry.isVerdef()) {
1010 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
1015 if (name_offset >= DynSymStrTab.size())
1016 return object_error::parse_failed;
1017 return StringRef(getDynamicString(name_offset));
1020 /// This function returns the hash value for a symbol in the .dynsym section
1021 /// Name of the API remains consistent as specified in the libelf
1022 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1023 static inline unsigned elf_hash(StringRef &symbolName) {
1025 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1026 h = (h << 4) + symbolName[i];
1027 g = h & 0xf0000000L;
1034 } // end namespace object
1035 } // end namespace llvm