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 ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
143 typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
144 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
145 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
146 typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
147 typedef iterator_range<Elf_Shdr_Iter> 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;
175 StringRef DotShstrtab; // Section header string table.
176 StringRef DotStrtab; // Symbol header string table.
177 const Elf_Shdr *dot_symtab_sec; // Symbol table section.
179 const Elf_Shdr *SymbolTableSectionHeaderIndex;
180 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
182 const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
183 const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
184 const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
186 /// \brief Represents a region described by entries in the .dynamic table.
187 struct DynRegionInfo {
188 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
189 /// \brief Address in current address space.
191 /// \brief Size in bytes of the region.
193 /// \brief Size of each entity in the region.
197 DynRegionInfo DynamicRegion;
198 DynRegionInfo DynHashRegion;
199 DynRegionInfo DynStrRegion;
200 DynRegionInfo DynSymRegion;
201 DynRegionInfo DynRelaRegion;
203 // Pointer to SONAME entry in dynamic string table
204 // This is set the first time getLoadName is called.
205 mutable const char *dt_soname;
207 // Records for each version index the corresponding Verdef or Vernaux entry.
208 // This is filled the first time LoadVersionMap() is called.
209 class VersionMapEntry : public PointerIntPair<const void*, 1> {
211 // If the integer is 0, this is an Elf_Verdef*.
212 // If the integer is 1, this is an Elf_Vernaux*.
213 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
214 VersionMapEntry(const Elf_Verdef *verdef)
215 : PointerIntPair<const void*, 1>(verdef, 0) { }
216 VersionMapEntry(const Elf_Vernaux *vernaux)
217 : PointerIntPair<const void*, 1>(vernaux, 1) { }
218 bool isNull() const { return getPointer() == nullptr; }
219 bool isVerdef() const { return !isNull() && getInt() == 0; }
220 bool isVernaux() const { return !isNull() && getInt() == 1; }
221 const Elf_Verdef *getVerdef() const {
222 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
224 const Elf_Vernaux *getVernaux() const {
225 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
228 mutable SmallVector<VersionMapEntry, 16> VersionMap;
229 void LoadVersionDefs(const Elf_Shdr *sec) const;
230 void LoadVersionNeeds(const Elf_Shdr *ec) const;
231 void LoadVersionMap() const;
235 const T *getEntry(uint32_t Section, uint32_t Entry) const;
236 template <typename T>
237 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
238 ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
239 const char *getDynamicString(uintX_t Offset) const;
240 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
242 bool &IsDefault) const;
243 void VerifyStrTab(const Elf_Shdr *sh) const;
245 StringRef getRelocationTypeName(uint32_t Type) const;
246 void getRelocationTypeName(uint32_t Type,
247 SmallVectorImpl<char> &Result) const;
249 /// \brief Get the symbol table section and symbol for a given relocation.
250 template <class RelT>
251 std::pair<const Elf_Shdr *, const Elf_Sym *>
252 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
254 ELFFile(StringRef Object, std::error_code &EC);
256 bool isMipsELF64() const {
257 return Header->e_machine == ELF::EM_MIPS &&
258 Header->getFileClass() == ELF::ELFCLASS64;
261 bool isMips64EL() const {
262 return Header->e_machine == ELF::EM_MIPS &&
263 Header->getFileClass() == ELF::ELFCLASS64 &&
264 Header->getDataEncoding() == ELF::ELFDATA2LSB;
267 Elf_Shdr_Iter section_begin() const;
268 Elf_Shdr_Iter section_end() const;
269 Elf_Shdr_Range sections() const {
270 return make_range(section_begin(), section_end());
273 const Elf_Sym *symbol_begin() const;
274 const Elf_Sym *symbol_end() const;
275 Elf_Sym_Range symbols() const {
276 return make_range(symbol_begin(), symbol_end());
279 Elf_Dyn_Iter dynamic_table_begin() const;
280 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
281 /// the section size.
282 Elf_Dyn_Iter dynamic_table_end(bool NULLEnd = false) const;
283 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
284 return make_range(dynamic_table_begin(), dynamic_table_end(NULLEnd));
287 const Elf_Sym *dynamic_symbol_begin() const {
288 if (!DynSymRegion.Addr)
290 if (DynSymRegion.EntSize != sizeof(Elf_Sym))
291 report_fatal_error("Invalid symbol size");
292 return reinterpret_cast<const Elf_Sym *>(DynSymRegion.Addr);
295 const Elf_Sym *dynamic_symbol_end() const {
296 if (!DynSymRegion.Addr)
298 return reinterpret_cast<const Elf_Sym *>(
299 ((const char *)DynSymRegion.Addr + DynSymRegion.Size));
302 Elf_Sym_Range dynamic_symbols() const {
303 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
306 Elf_Rela_Iter dyn_rela_begin() const {
307 if (DynRelaRegion.Addr)
308 return Elf_Rela_Iter(DynRelaRegion.EntSize,
309 (const char *)DynRelaRegion.Addr);
310 return Elf_Rela_Iter(0, nullptr);
313 Elf_Rela_Iter dyn_rela_end() const {
314 if (DynRelaRegion.Addr)
315 return Elf_Rela_Iter(
316 DynRelaRegion.EntSize,
317 (const char *)DynRelaRegion.Addr + DynRelaRegion.Size);
318 return Elf_Rela_Iter(0, nullptr);
321 Elf_Rela_Iter rela_begin(const Elf_Shdr *sec) const {
322 return Elf_Rela_Iter(sec->sh_entsize,
323 (const char *)(base() + sec->sh_offset));
326 Elf_Rela_Iter rela_end(const Elf_Shdr *sec) const {
327 return Elf_Rela_Iter(
329 (const char *)(base() + sec->sh_offset + sec->sh_size));
332 Elf_Rel_Iter rel_begin(const Elf_Shdr *sec) const {
333 return Elf_Rel_Iter(sec->sh_entsize,
334 (const char *)(base() + sec->sh_offset));
337 Elf_Rel_Iter rel_end(const Elf_Shdr *sec) const {
338 return Elf_Rel_Iter(sec->sh_entsize,
339 (const char *)(base() + sec->sh_offset + sec->sh_size));
342 /// \brief Iterate over program header table.
343 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
345 Elf_Phdr_Iter program_header_begin() const {
346 return Elf_Phdr_Iter(Header->e_phentsize,
347 (const char*)base() + Header->e_phoff);
350 Elf_Phdr_Iter program_header_end() const {
351 return Elf_Phdr_Iter(Header->e_phentsize,
352 (const char*)base() +
354 (Header->e_phnum * Header->e_phentsize));
357 uint64_t getNumSections() const;
358 uintX_t getStringTableIndex() const;
359 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
360 const Elf_Ehdr *getHeader() const { return Header; }
361 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
362 const Elf_Shdr *getSection(uint32_t Index) const;
363 const Elf_Sym *getSymbol(uint32_t index) const;
365 ErrorOr<StringRef> getStaticSymbolName(const Elf_Sym *Symb) const;
366 ErrorOr<StringRef> getDynamicSymbolName(const Elf_Sym *Symb) const;
367 ErrorOr<StringRef> getSymbolName(const Elf_Sym *Symb, bool IsDynamic) const;
369 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
370 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
371 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
372 StringRef getLoadName() const;
375 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
376 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
377 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
378 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
380 // Iterate through the version definitions, and place each Elf_Verdef
381 // in the VersionMap according to its index.
382 template <class ELFT>
383 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
384 unsigned vd_size = sec->sh_size; // Size of section in bytes
385 unsigned vd_count = sec->sh_info; // Number of Verdef entries
386 const char *sec_start = (const char*)base() + sec->sh_offset;
387 const char *sec_end = sec_start + vd_size;
388 // The first Verdef entry is at the start of the section.
389 const char *p = sec_start;
390 for (unsigned i = 0; i < vd_count; i++) {
391 if (p + sizeof(Elf_Verdef) > sec_end)
392 report_fatal_error("Section ended unexpectedly while scanning "
393 "version definitions.");
394 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
395 if (vd->vd_version != ELF::VER_DEF_CURRENT)
396 report_fatal_error("Unexpected verdef version");
397 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
398 if (index >= VersionMap.size())
399 VersionMap.resize(index + 1);
400 VersionMap[index] = VersionMapEntry(vd);
405 // Iterate through the versions needed section, and place each Elf_Vernaux
406 // in the VersionMap according to its index.
407 template <class ELFT>
408 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
409 unsigned vn_size = sec->sh_size; // Size of section in bytes
410 unsigned vn_count = sec->sh_info; // Number of Verneed entries
411 const char *sec_start = (const char *)base() + sec->sh_offset;
412 const char *sec_end = sec_start + vn_size;
413 // The first Verneed entry is at the start of the section.
414 const char *p = sec_start;
415 for (unsigned i = 0; i < vn_count; i++) {
416 if (p + sizeof(Elf_Verneed) > sec_end)
417 report_fatal_error("Section ended unexpectedly while scanning "
418 "version needed records.");
419 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
420 if (vn->vn_version != ELF::VER_NEED_CURRENT)
421 report_fatal_error("Unexpected verneed version");
422 // Iterate through the Vernaux entries
423 const char *paux = p + vn->vn_aux;
424 for (unsigned j = 0; j < vn->vn_cnt; j++) {
425 if (paux + sizeof(Elf_Vernaux) > sec_end)
426 report_fatal_error("Section ended unexpected while scanning auxiliary "
427 "version needed records.");
428 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
429 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
430 if (index >= VersionMap.size())
431 VersionMap.resize(index + 1);
432 VersionMap[index] = VersionMapEntry(vna);
433 paux += vna->vna_next;
439 template <class ELFT>
440 void ELFFile<ELFT>::LoadVersionMap() const {
441 // If there is no dynamic symtab or version table, there is nothing to do.
442 if (!DynSymRegion.Addr || !dot_gnu_version_sec)
445 // Has the VersionMap already been loaded?
446 if (VersionMap.size() > 0)
449 // The first two version indexes are reserved.
450 // Index 0 is LOCAL, index 1 is GLOBAL.
451 VersionMap.push_back(VersionMapEntry());
452 VersionMap.push_back(VersionMapEntry());
454 if (dot_gnu_version_d_sec)
455 LoadVersionDefs(dot_gnu_version_d_sec);
457 if (dot_gnu_version_r_sec)
458 LoadVersionNeeds(dot_gnu_version_r_sec);
461 template <class ELFT>
463 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
464 assert(symb->st_shndx == ELF::SHN_XINDEX);
465 return ExtendedSymbolTable.lookup(symb);
468 template <class ELFT>
469 const typename ELFFile<ELFT>::Elf_Shdr *
470 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
471 if (symb->st_shndx == ELF::SHN_XINDEX)
472 return getSection(ExtendedSymbolTable.lookup(symb));
473 if (symb->st_shndx >= ELF::SHN_LORESERVE)
475 return getSection(symb->st_shndx);
478 template <class ELFT>
479 const typename ELFFile<ELFT>::Elf_Sym *
480 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
481 return &*(symbol_begin() + Index);
484 template <class ELFT>
485 ErrorOr<ArrayRef<uint8_t> >
486 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
487 if (Sec->sh_offset + Sec->sh_size > Buf.size())
488 return object_error::parse_failed;
489 const uint8_t *Start = base() + Sec->sh_offset;
490 return makeArrayRef(Start, Sec->sh_size);
493 template <class ELFT>
494 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
495 return getELFRelocationTypeName(Header->e_machine, Type);
498 template <class ELFT>
499 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
500 SmallVectorImpl<char> &Result) const {
501 if (!isMipsELF64()) {
502 StringRef Name = getRelocationTypeName(Type);
503 Result.append(Name.begin(), Name.end());
505 // The Mips N64 ABI allows up to three operations to be specified per
506 // relocation record. Unfortunately there's no easy way to test for the
507 // presence of N64 ELFs as they have no special flag that identifies them
508 // as being N64. We can safely assume at the moment that all Mips
509 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
510 // information to disambiguate between old vs new ABIs.
511 uint8_t Type1 = (Type >> 0) & 0xFF;
512 uint8_t Type2 = (Type >> 8) & 0xFF;
513 uint8_t Type3 = (Type >> 16) & 0xFF;
515 // Concat all three relocation type names.
516 StringRef Name = getRelocationTypeName(Type1);
517 Result.append(Name.begin(), Name.end());
519 Name = getRelocationTypeName(Type2);
520 Result.append(1, '/');
521 Result.append(Name.begin(), Name.end());
523 Name = getRelocationTypeName(Type3);
524 Result.append(1, '/');
525 Result.append(Name.begin(), Name.end());
529 template <class ELFT>
530 template <class RelT>
531 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
532 const typename ELFFile<ELFT>::Elf_Sym *>
533 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
535 return std::make_pair(nullptr, nullptr);
536 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
537 return std::make_pair(
538 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
541 template <class ELFT>
542 uint64_t ELFFile<ELFT>::getNumSections() const {
543 assert(Header && "Header not initialized!");
544 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
545 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
546 return SectionHeaderTable->sh_size;
548 return Header->e_shnum;
551 template <class ELFT>
552 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
553 if (Header->e_shnum == ELF::SHN_UNDEF) {
554 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
555 return SectionHeaderTable->sh_link;
556 if (Header->e_shstrndx >= getNumSections())
559 return Header->e_shstrndx;
562 template <class ELFT>
563 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
564 : Buf(Object), SectionHeaderTable(nullptr), dot_symtab_sec(nullptr),
565 SymbolTableSectionHeaderIndex(nullptr), dot_gnu_version_sec(nullptr),
566 dot_gnu_version_r_sec(nullptr), dot_gnu_version_d_sec(nullptr),
568 const uint64_t FileSize = Buf.size();
570 if (sizeof(Elf_Ehdr) > FileSize) {
572 EC = object_error::parse_failed;
576 Header = reinterpret_cast<const Elf_Ehdr *>(base());
578 if (Header->e_shoff == 0)
581 const uint64_t SectionTableOffset = Header->e_shoff;
583 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
584 // Section header table goes past end of file!
585 EC = object_error::parse_failed;
589 // The getNumSections() call below depends on SectionHeaderTable being set.
591 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
592 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
594 if (SectionTableOffset + SectionTableSize > FileSize) {
595 // Section table goes past end of file!
596 EC = object_error::parse_failed;
600 // Scan sections for special sections.
602 for (const Elf_Shdr &Sec : sections()) {
603 switch (Sec.sh_type) {
604 case ELF::SHT_SYMTAB_SHNDX:
605 if (SymbolTableSectionHeaderIndex) {
606 // More than one .symtab_shndx!
607 EC = object_error::parse_failed;
610 SymbolTableSectionHeaderIndex = &Sec;
612 case ELF::SHT_SYMTAB: {
613 if (dot_symtab_sec) {
614 // More than one .symtab!
615 EC = object_error::parse_failed;
618 dot_symtab_sec = &Sec;
619 ErrorOr<StringRef> SymtabOrErr = getStringTable(getSection(Sec.sh_link));
620 if ((EC = SymtabOrErr.getError()))
622 DotStrtab = *SymtabOrErr;
624 case ELF::SHT_DYNSYM: {
625 if (DynSymRegion.Addr) {
626 // More than one .dynsym!
627 EC = object_error::parse_failed;
630 DynSymRegion.Addr = base() + Sec.sh_offset;
631 DynSymRegion.Size = Sec.sh_size;
632 DynSymRegion.EntSize = Sec.sh_entsize;
633 const Elf_Shdr *DynStr = getSection(Sec.sh_link);
634 DynStrRegion.Addr = base() + DynStr->sh_offset;
635 DynStrRegion.Size = DynStr->sh_size;
636 DynStrRegion.EntSize = DynStr->sh_entsize;
639 case ELF::SHT_DYNAMIC:
640 if (DynamicRegion.Addr) {
641 // More than one .dynamic!
642 EC = object_error::parse_failed;
645 DynamicRegion.Addr = base() + Sec.sh_offset;
646 DynamicRegion.Size = Sec.sh_size;
647 DynamicRegion.EntSize = Sec.sh_entsize;
649 case ELF::SHT_GNU_versym:
650 if (dot_gnu_version_sec != nullptr) {
651 // More than one .gnu.version section!
652 EC = object_error::parse_failed;
655 dot_gnu_version_sec = &Sec;
657 case ELF::SHT_GNU_verdef:
658 if (dot_gnu_version_d_sec != nullptr) {
659 // More than one .gnu.version_d section!
660 EC = object_error::parse_failed;
663 dot_gnu_version_d_sec = &Sec;
665 case ELF::SHT_GNU_verneed:
666 if (dot_gnu_version_r_sec != nullptr) {
667 // More than one .gnu.version_r section!
668 EC = object_error::parse_failed;
671 dot_gnu_version_r_sec = &Sec;
676 // Get string table sections.
677 ErrorOr<StringRef> SymtabOrErr =
678 getStringTable(getSection(getStringTableIndex()));
679 if ((EC = SymtabOrErr.getError()))
681 DotShstrtab = *SymtabOrErr;
683 // Build symbol name side-mapping if there is one.
684 if (SymbolTableSectionHeaderIndex) {
685 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
686 SymbolTableSectionHeaderIndex->sh_offset);
687 for (const Elf_Sym &S : symbols()) {
688 if (*ShndxTable != ELF::SHN_UNDEF)
689 ExtendedSymbolTable[&S] = *ShndxTable;
694 // Scan program headers.
695 for (Elf_Phdr_Iter PhdrI = program_header_begin(),
696 PhdrE = program_header_end();
697 PhdrI != PhdrE; ++PhdrI) {
698 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
699 DynamicRegion.Addr = base() + PhdrI->p_offset;
700 DynamicRegion.Size = PhdrI->p_filesz;
701 DynamicRegion.EntSize = sizeof(Elf_Dyn);
706 // Scan dynamic table.
707 for (Elf_Dyn_Iter DynI = dynamic_table_begin(), DynE = dynamic_table_end();
708 DynI != DynE; ++DynI) {
709 switch (DynI->d_tag) {
712 const uint8_t *FBase = nullptr;
713 for (Elf_Phdr_Iter PhdrI = program_header_begin(),
714 PhdrE = program_header_end();
715 PhdrI != PhdrE; ++PhdrI) {
716 if (PhdrI->p_type != ELF::PT_LOAD)
718 if (DynI->getPtr() >= PhdrI->p_vaddr &&
719 DynI->getPtr() < PhdrI->p_vaddr + PhdrI->p_memsz) {
720 VBase = PhdrI->p_vaddr;
721 FBase = base() + PhdrI->p_offset;
727 DynRelaRegion.Addr = FBase + DynI->getPtr() - VBase;
731 DynRelaRegion.Size = DynI->getVal();
733 case ELF::DT_RELAENT:
734 DynRelaRegion.EntSize = DynI->getVal();
738 EC = std::error_code();
741 // Get the symbol table index in the symtab section given a symbol
742 template <class ELFT>
743 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
744 uintptr_t SymLoc = uintptr_t(Sym);
745 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
746 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
747 uint64_t SymOffset = SymLoc - SymTabLoc;
748 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
749 "Symbol not multiple of symbol size!");
750 return SymOffset / dot_symtab_sec->sh_entsize;
753 template <class ELFT>
754 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::section_begin() const {
755 return Elf_Shdr_Iter(Header->e_shentsize,
756 (const char *)base() + Header->e_shoff);
759 template <class ELFT>
760 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::section_end() const {
761 return Elf_Shdr_Iter(Header->e_shentsize,
762 (const char *)base() + Header->e_shoff +
763 (getNumSections() * Header->e_shentsize));
766 template <class ELFT>
767 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
770 if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
771 report_fatal_error("Invalid symbol size");
772 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
775 template <class ELFT>
776 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
779 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
780 dot_symtab_sec->sh_size);
783 template <class ELFT>
784 typename ELFFile<ELFT>::Elf_Dyn_Iter
785 ELFFile<ELFT>::dynamic_table_begin() const {
786 if (DynamicRegion.Addr)
787 return Elf_Dyn_Iter(DynamicRegion.EntSize,
788 (const char *)DynamicRegion.Addr);
789 return Elf_Dyn_Iter(0, nullptr);
792 template <class ELFT>
793 typename ELFFile<ELFT>::Elf_Dyn_Iter
794 ELFFile<ELFT>::dynamic_table_end(bool NULLEnd) const {
795 if (!DynamicRegion.Addr)
796 return Elf_Dyn_Iter(0, nullptr);
797 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
798 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
801 Elf_Dyn_Iter Start = dynamic_table_begin();
802 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
805 // Include the DT_NULL.
813 template <class ELFT>
814 StringRef ELFFile<ELFT>::getLoadName() const {
817 // Find the DT_SONAME entry
818 for (const auto &Entry : dynamic_table())
819 if (Entry.getTag() == ELF::DT_SONAME) {
820 dt_soname = getDynamicString(Entry.getVal());
827 template <class ELFT>
828 template <typename T>
829 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
830 return getEntry<T>(getSection(Section), Entry);
833 template <class ELFT>
834 template <typename T>
835 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
836 uint32_t Entry) const {
837 return reinterpret_cast<const T *>(base() + Section->sh_offset +
838 (Entry * Section->sh_entsize));
841 template <class ELFT>
842 const typename ELFFile<ELFT>::Elf_Shdr *
843 ELFFile<ELFT>::getSection(uint32_t index) const {
846 if (!SectionHeaderTable || index >= getNumSections())
847 // FIXME: Proper error handling.
848 report_fatal_error("Invalid section index!");
850 return reinterpret_cast<const Elf_Shdr *>(
851 reinterpret_cast<const char *>(SectionHeaderTable)
852 + (index * Header->e_shentsize));
855 template <class ELFT>
857 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
858 if (Section->sh_type != ELF::SHT_STRTAB)
859 return object_error::parse_failed;
860 uint64_t Offset = Section->sh_offset;
861 uint64_t Size = Section->sh_size;
862 if (Offset + Size > Buf.size())
863 return object_error::parse_failed;
864 StringRef Data((const char *)base() + Section->sh_offset, Size);
865 if (Data[Size - 1] != '\0')
866 return object_error::string_table_non_null_end;
870 template <class ELFT>
871 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
872 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
874 return (const char *)DynStrRegion.Addr + Offset;
877 template <class ELFT>
879 ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
880 return Symb->getName(DotStrtab);
883 template <class ELFT>
885 ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
886 return StringRef(getDynamicString(Symb->st_name));
889 template <class ELFT>
890 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Sym *Symb,
891 bool IsDynamic) const {
893 return getDynamicSymbolName(Symb);
894 return getStaticSymbolName(Symb);
897 template <class ELFT>
899 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
900 uint32_t Offset = Section->sh_name;
901 if (Offset >= DotShstrtab.size())
902 return object_error::parse_failed;
903 return StringRef(DotShstrtab.data() + Offset);
906 template <class ELFT>
907 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
909 bool &IsDefault) const {
912 ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
913 if (std::error_code EC = StrTabOrErr.getError())
915 StrTab = *StrTabOrErr;
917 // Handle non-dynamic symbols.
918 if (section != DynSymRegion.Addr && section != nullptr) {
919 // Non-dynamic symbols can have versions in their names
920 // A name of the form 'foo@V1' indicates version 'V1', non-default.
921 // A name of the form 'foo@@V2' indicates version 'V2', default version.
922 ErrorOr<StringRef> SymName = symb->getName(StrTab);
925 StringRef Name = *SymName;
926 size_t atpos = Name.find('@');
927 if (atpos == StringRef::npos) {
929 return StringRef("");
932 if (atpos < Name.size() && Name[atpos] == '@') {
938 return Name.substr(atpos);
941 // This is a dynamic symbol. Look in the GNU symbol version table.
942 if (!dot_gnu_version_sec) {
945 return StringRef("");
948 // Determine the position in the symbol table of this entry.
949 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
950 DynSymRegion.EntSize;
952 // Get the corresponding version index entry
953 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
954 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
956 // Special markers for unversioned symbols.
957 if (version_index == ELF::VER_NDX_LOCAL ||
958 version_index == ELF::VER_NDX_GLOBAL) {
960 return StringRef("");
963 // Lookup this symbol in the version table
965 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
966 return object_error::parse_failed;
967 const VersionMapEntry &entry = VersionMap[version_index];
969 // Get the version name string
971 if (entry.isVerdef()) {
972 // The first Verdaux entry holds the name.
973 name_offset = entry.getVerdef()->getAux()->vda_name;
975 name_offset = entry.getVernaux()->vna_name;
979 if (entry.isVerdef()) {
980 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
985 if (name_offset >= DynStrRegion.Size)
986 return object_error::parse_failed;
987 return StringRef(getDynamicString(name_offset));
990 /// This function returns the hash value for a symbol in the .dynsym section
991 /// Name of the API remains consistent as specified in the libelf
992 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
993 static inline unsigned elf_hash(StringRef &symbolName) {
995 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
996 h = (h << 4) + symbolName[i];
1004 } // end namespace object
1005 } // end namespace llvm