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 iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
148 /// \brief Archive files are 2 byte aligned, so we need this for
149 /// PointerIntPair to work.
150 template <typename T>
151 class ArchivePointerTypeTraits {
153 static inline const void *getAsVoidPointer(T *P) { return P; }
154 static inline T *getFromVoidPointer(const void *P) {
155 return static_cast<T *>(P);
157 enum { NumLowBitsAvailable = 1 };
160 typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
163 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
164 typedef DenseMap<unsigned, unsigned> IndexMap_t;
168 const uint8_t *base() const {
169 return reinterpret_cast<const uint8_t *>(Buf.data());
172 const Elf_Ehdr *Header;
173 const Elf_Shdr *SectionHeaderTable = nullptr;
174 StringRef DotShstrtab; // Section header string table.
175 StringRef DotStrtab; // Symbol header string table.
176 const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
177 StringRef DynSymStrTab; // Dynnamic symbol string table.
178 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
180 const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
181 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
183 const Elf_Shdr *dot_gnu_version_sec = nullptr; // .gnu.version
184 const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
185 const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
187 /// \brief Represents a region described by entries in the .dynamic table.
188 struct DynRegionInfo {
189 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
190 /// \brief Address in current address space.
192 /// \brief Size in bytes of the region.
194 /// \brief Size of each entity in the region.
198 DynRegionInfo DynamicRegion;
199 DynRegionInfo DynHashRegion;
200 DynRegionInfo DynRelaRegion;
202 // Pointer to SONAME entry in dynamic string table
203 // This is set the first time getLoadName is called.
204 mutable const char *dt_soname = nullptr;
206 // Records for each version index the corresponding Verdef or Vernaux entry.
207 // This is filled the first time LoadVersionMap() is called.
208 class VersionMapEntry : public PointerIntPair<const void*, 1> {
210 // If the integer is 0, this is an Elf_Verdef*.
211 // If the integer is 1, this is an Elf_Vernaux*.
212 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
213 VersionMapEntry(const Elf_Verdef *verdef)
214 : PointerIntPair<const void*, 1>(verdef, 0) { }
215 VersionMapEntry(const Elf_Vernaux *vernaux)
216 : PointerIntPair<const void*, 1>(vernaux, 1) { }
217 bool isNull() const { return getPointer() == nullptr; }
218 bool isVerdef() const { return !isNull() && getInt() == 0; }
219 bool isVernaux() const { return !isNull() && getInt() == 1; }
220 const Elf_Verdef *getVerdef() const {
221 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
223 const Elf_Vernaux *getVernaux() const {
224 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
227 mutable SmallVector<VersionMapEntry, 16> VersionMap;
228 void LoadVersionDefs(const Elf_Shdr *sec) const;
229 void LoadVersionNeeds(const Elf_Shdr *ec) const;
230 void LoadVersionMap() const;
234 const T *getEntry(uint32_t Section, uint32_t Entry) const;
235 template <typename T>
236 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
238 const Elf_Shdr *getDotSymtabSec() const { return dot_symtab_sec; }
239 const Elf_Shdr *getDotDynSymSec() const { return DotDynSymSec; }
241 ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
242 const char *getDynamicString(uintX_t Offset) const;
243 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
245 bool &IsDefault) const;
246 void VerifyStrTab(const Elf_Shdr *sh) const;
248 StringRef getRelocationTypeName(uint32_t Type) const;
249 void getRelocationTypeName(uint32_t Type,
250 SmallVectorImpl<char> &Result) const;
252 /// \brief Get the symbol table section and symbol for a given relocation.
253 template <class RelT>
254 std::pair<const Elf_Shdr *, const Elf_Sym *>
255 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
257 ELFFile(StringRef Object, std::error_code &EC);
259 bool isMipsELF64() const {
260 return Header->e_machine == ELF::EM_MIPS &&
261 Header->getFileClass() == ELF::ELFCLASS64;
264 bool isMips64EL() const {
265 return Header->e_machine == ELF::EM_MIPS &&
266 Header->getFileClass() == ELF::ELFCLASS64 &&
267 Header->getDataEncoding() == ELF::ELFDATA2LSB;
270 const Elf_Shdr *section_begin() const;
271 const Elf_Shdr *section_end() const;
272 Elf_Shdr_Range sections() const {
273 return make_range(section_begin(), section_end());
276 const Elf_Sym *symbol_begin() const;
277 const Elf_Sym *symbol_end() const;
278 Elf_Sym_Range symbols() const {
279 return make_range(symbol_begin(), symbol_end());
282 Elf_Dyn_Iter dynamic_table_begin() const;
283 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
284 /// the section size.
285 Elf_Dyn_Iter dynamic_table_end(bool NULLEnd = false) const;
286 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
287 return make_range(dynamic_table_begin(), dynamic_table_end(NULLEnd));
290 const Elf_Sym *dynamic_symbol_begin() const {
293 if (DotDynSymSec->sh_entsize != sizeof(Elf_Sym))
294 report_fatal_error("Invalid symbol size");
295 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset);
298 const Elf_Sym *dynamic_symbol_end() const {
301 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset +
302 DotDynSymSec->sh_size);
305 Elf_Sym_Range dynamic_symbols() const {
306 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
309 Elf_Rela_Iter dyn_rela_begin() const {
310 if (DynRelaRegion.Addr)
311 return Elf_Rela_Iter(DynRelaRegion.EntSize,
312 (const char *)DynRelaRegion.Addr);
313 return Elf_Rela_Iter(0, nullptr);
316 Elf_Rela_Iter dyn_rela_end() const {
317 if (DynRelaRegion.Addr)
318 return Elf_Rela_Iter(
319 DynRelaRegion.EntSize,
320 (const char *)DynRelaRegion.Addr + DynRelaRegion.Size);
321 return Elf_Rela_Iter(0, nullptr);
324 Elf_Rela_Iter rela_begin(const Elf_Shdr *sec) const {
325 return Elf_Rela_Iter(sec->sh_entsize,
326 (const char *)(base() + sec->sh_offset));
329 Elf_Rela_Iter rela_end(const Elf_Shdr *sec) const {
330 return Elf_Rela_Iter(
332 (const char *)(base() + sec->sh_offset + sec->sh_size));
335 Elf_Rel_Iter rel_begin(const Elf_Shdr *sec) const {
336 return Elf_Rel_Iter(sec->sh_entsize,
337 (const char *)(base() + sec->sh_offset));
340 Elf_Rel_Iter rel_end(const Elf_Shdr *sec) const {
341 return Elf_Rel_Iter(sec->sh_entsize,
342 (const char *)(base() + sec->sh_offset + sec->sh_size));
345 /// \brief Iterate over program header table.
346 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
348 Elf_Phdr_Iter program_header_begin() const {
349 return Elf_Phdr_Iter(Header->e_phentsize,
350 (const char*)base() + Header->e_phoff);
353 Elf_Phdr_Iter program_header_end() const {
354 return Elf_Phdr_Iter(Header->e_phentsize,
355 (const char*)base() +
357 (Header->e_phnum * Header->e_phentsize));
360 uint64_t getNumSections() const;
361 uintX_t getStringTableIndex() const;
362 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
363 const Elf_Ehdr *getHeader() const { return Header; }
364 ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
365 ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
366 const Elf_Sym *getSymbol(uint32_t index) const;
368 ErrorOr<StringRef> getStaticSymbolName(const Elf_Sym *Symb) const;
369 ErrorOr<StringRef> getDynamicSymbolName(const Elf_Sym *Symb) const;
370 ErrorOr<StringRef> getSymbolName(const Elf_Sym *Symb, bool IsDynamic) const;
372 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
373 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
374 StringRef getLoadName() const;
377 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
378 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
379 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
380 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
382 // Iterate through the version definitions, and place each Elf_Verdef
383 // in the VersionMap according to its index.
384 template <class ELFT>
385 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
386 unsigned vd_size = sec->sh_size; // Size of section in bytes
387 unsigned vd_count = sec->sh_info; // Number of Verdef entries
388 const char *sec_start = (const char*)base() + sec->sh_offset;
389 const char *sec_end = sec_start + vd_size;
390 // The first Verdef entry is at the start of the section.
391 const char *p = sec_start;
392 for (unsigned i = 0; i < vd_count; i++) {
393 if (p + sizeof(Elf_Verdef) > sec_end)
394 report_fatal_error("Section ended unexpectedly while scanning "
395 "version definitions.");
396 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
397 if (vd->vd_version != ELF::VER_DEF_CURRENT)
398 report_fatal_error("Unexpected verdef version");
399 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
400 if (index >= VersionMap.size())
401 VersionMap.resize(index + 1);
402 VersionMap[index] = VersionMapEntry(vd);
407 // Iterate through the versions needed section, and place each Elf_Vernaux
408 // in the VersionMap according to its index.
409 template <class ELFT>
410 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
411 unsigned vn_size = sec->sh_size; // Size of section in bytes
412 unsigned vn_count = sec->sh_info; // Number of Verneed entries
413 const char *sec_start = (const char *)base() + sec->sh_offset;
414 const char *sec_end = sec_start + vn_size;
415 // The first Verneed entry is at the start of the section.
416 const char *p = sec_start;
417 for (unsigned i = 0; i < vn_count; i++) {
418 if (p + sizeof(Elf_Verneed) > sec_end)
419 report_fatal_error("Section ended unexpectedly while scanning "
420 "version needed records.");
421 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
422 if (vn->vn_version != ELF::VER_NEED_CURRENT)
423 report_fatal_error("Unexpected verneed version");
424 // Iterate through the Vernaux entries
425 const char *paux = p + vn->vn_aux;
426 for (unsigned j = 0; j < vn->vn_cnt; j++) {
427 if (paux + sizeof(Elf_Vernaux) > sec_end)
428 report_fatal_error("Section ended unexpected while scanning auxiliary "
429 "version needed records.");
430 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
431 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
432 if (index >= VersionMap.size())
433 VersionMap.resize(index + 1);
434 VersionMap[index] = VersionMapEntry(vna);
435 paux += vna->vna_next;
441 template <class ELFT>
442 void ELFFile<ELFT>::LoadVersionMap() const {
443 // If there is no dynamic symtab or version table, there is nothing to do.
444 if (!DotDynSymSec || !dot_gnu_version_sec)
447 // Has the VersionMap already been loaded?
448 if (VersionMap.size() > 0)
451 // The first two version indexes are reserved.
452 // Index 0 is LOCAL, index 1 is GLOBAL.
453 VersionMap.push_back(VersionMapEntry());
454 VersionMap.push_back(VersionMapEntry());
456 if (dot_gnu_version_d_sec)
457 LoadVersionDefs(dot_gnu_version_d_sec);
459 if (dot_gnu_version_r_sec)
460 LoadVersionNeeds(dot_gnu_version_r_sec);
463 template <class ELFT>
465 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
466 assert(symb->st_shndx == ELF::SHN_XINDEX);
467 return ExtendedSymbolTable.lookup(symb);
470 template <class ELFT>
471 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
472 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
473 uint32_t Index = symb->st_shndx;
474 if (Index == ELF::SHN_XINDEX)
475 return getSection(ExtendedSymbolTable.lookup(symb));
476 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
478 return getSection(symb->st_shndx);
481 template <class ELFT>
482 const typename ELFFile<ELFT>::Elf_Sym *
483 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
484 return &*(symbol_begin() + Index);
487 template <class ELFT>
488 ErrorOr<ArrayRef<uint8_t> >
489 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
490 if (Sec->sh_offset + Sec->sh_size > Buf.size())
491 return object_error::parse_failed;
492 const uint8_t *Start = base() + Sec->sh_offset;
493 return makeArrayRef(Start, Sec->sh_size);
496 template <class ELFT>
497 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
498 return getELFRelocationTypeName(Header->e_machine, Type);
501 template <class ELFT>
502 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
503 SmallVectorImpl<char> &Result) const {
504 if (!isMipsELF64()) {
505 StringRef Name = getRelocationTypeName(Type);
506 Result.append(Name.begin(), Name.end());
508 // The Mips N64 ABI allows up to three operations to be specified per
509 // relocation record. Unfortunately there's no easy way to test for the
510 // presence of N64 ELFs as they have no special flag that identifies them
511 // as being N64. We can safely assume at the moment that all Mips
512 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
513 // information to disambiguate between old vs new ABIs.
514 uint8_t Type1 = (Type >> 0) & 0xFF;
515 uint8_t Type2 = (Type >> 8) & 0xFF;
516 uint8_t Type3 = (Type >> 16) & 0xFF;
518 // Concat all three relocation type names.
519 StringRef Name = getRelocationTypeName(Type1);
520 Result.append(Name.begin(), Name.end());
522 Name = getRelocationTypeName(Type2);
523 Result.append(1, '/');
524 Result.append(Name.begin(), Name.end());
526 Name = getRelocationTypeName(Type3);
527 Result.append(1, '/');
528 Result.append(Name.begin(), Name.end());
532 template <class ELFT>
533 template <class RelT>
534 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
535 const typename ELFFile<ELFT>::Elf_Sym *>
536 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
538 return std::make_pair(nullptr, nullptr);
539 ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
540 if (std::error_code EC = SymTableOrErr.getError())
541 report_fatal_error(EC.message());
542 const Elf_Shdr *SymTable = *SymTableOrErr;
543 return std::make_pair(
544 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
547 template <class ELFT>
548 uint64_t ELFFile<ELFT>::getNumSections() const {
549 assert(Header && "Header not initialized!");
550 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
551 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
552 return SectionHeaderTable->sh_size;
554 return Header->e_shnum;
557 template <class ELFT>
558 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
559 if (Header->e_shnum == ELF::SHN_UNDEF) {
560 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
561 return SectionHeaderTable->sh_link;
562 if (Header->e_shstrndx >= getNumSections())
565 return Header->e_shstrndx;
568 template <class ELFT>
569 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
571 const uint64_t FileSize = Buf.size();
573 if (sizeof(Elf_Ehdr) > FileSize) {
575 EC = object_error::parse_failed;
579 Header = reinterpret_cast<const Elf_Ehdr *>(base());
581 if (Header->e_shoff == 0)
584 const uint64_t SectionTableOffset = Header->e_shoff;
586 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
587 // Section header table goes past end of file!
588 EC = object_error::parse_failed;
592 // The getNumSections() call below depends on SectionHeaderTable being set.
594 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
595 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
597 if (SectionTableOffset + SectionTableSize > FileSize) {
598 // Section table goes past end of file!
599 EC = object_error::parse_failed;
603 // Scan sections for special sections.
605 for (const Elf_Shdr &Sec : sections()) {
606 switch (Sec.sh_type) {
607 case ELF::SHT_SYMTAB_SHNDX:
608 if (SymbolTableSectionHeaderIndex) {
609 // More than one .symtab_shndx!
610 EC = object_error::parse_failed;
613 SymbolTableSectionHeaderIndex = &Sec;
615 case ELF::SHT_SYMTAB: {
616 if (dot_symtab_sec) {
617 // More than one .symtab!
618 EC = object_error::parse_failed;
621 dot_symtab_sec = &Sec;
622 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
623 if ((EC = SectionOrErr.getError()))
625 ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
626 if ((EC = SymtabOrErr.getError()))
628 DotStrtab = *SymtabOrErr;
630 case ELF::SHT_DYNSYM: {
632 // More than one .dynsym!
633 EC = object_error::parse_failed;
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 DynSymStrTab = *SymtabOrErr;
646 case ELF::SHT_DYNAMIC:
647 if (DynamicRegion.Addr) {
648 // More than one .dynamic!
649 EC = object_error::parse_failed;
652 DynamicRegion.Addr = base() + Sec.sh_offset;
653 DynamicRegion.Size = Sec.sh_size;
654 DynamicRegion.EntSize = Sec.sh_entsize;
656 case ELF::SHT_GNU_versym:
657 if (dot_gnu_version_sec != nullptr) {
658 // More than one .gnu.version section!
659 EC = object_error::parse_failed;
662 dot_gnu_version_sec = &Sec;
664 case ELF::SHT_GNU_verdef:
665 if (dot_gnu_version_d_sec != nullptr) {
666 // More than one .gnu.version_d section!
667 EC = object_error::parse_failed;
670 dot_gnu_version_d_sec = &Sec;
672 case ELF::SHT_GNU_verneed:
673 if (dot_gnu_version_r_sec != nullptr) {
674 // More than one .gnu.version_r section!
675 EC = object_error::parse_failed;
678 dot_gnu_version_r_sec = &Sec;
683 // Get string table sections.
684 ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(getStringTableIndex());
685 if ((EC = StrTabSecOrErr.getError()))
688 ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
689 if ((EC = SymtabOrErr.getError()))
691 DotShstrtab = *SymtabOrErr;
693 // Build symbol name side-mapping if there is one.
694 if (SymbolTableSectionHeaderIndex) {
695 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
696 SymbolTableSectionHeaderIndex->sh_offset);
697 for (const Elf_Sym &S : symbols()) {
698 if (*ShndxTable != ELF::SHN_UNDEF)
699 ExtendedSymbolTable[&S] = *ShndxTable;
704 // Scan program headers.
705 for (Elf_Phdr_Iter PhdrI = program_header_begin(),
706 PhdrE = program_header_end();
707 PhdrI != PhdrE; ++PhdrI) {
708 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
709 DynamicRegion.Addr = base() + PhdrI->p_offset;
710 DynamicRegion.Size = PhdrI->p_filesz;
711 DynamicRegion.EntSize = sizeof(Elf_Dyn);
716 // Scan dynamic table.
717 for (Elf_Dyn_Iter DynI = dynamic_table_begin(), DynE = dynamic_table_end();
718 DynI != DynE; ++DynI) {
719 switch (DynI->d_tag) {
722 const uint8_t *FBase = nullptr;
723 for (Elf_Phdr_Iter PhdrI = program_header_begin(),
724 PhdrE = program_header_end();
725 PhdrI != PhdrE; ++PhdrI) {
726 if (PhdrI->p_type != ELF::PT_LOAD)
728 if (DynI->getPtr() >= PhdrI->p_vaddr &&
729 DynI->getPtr() < PhdrI->p_vaddr + PhdrI->p_memsz) {
730 VBase = PhdrI->p_vaddr;
731 FBase = base() + PhdrI->p_offset;
737 DynRelaRegion.Addr = FBase + DynI->getPtr() - VBase;
741 DynRelaRegion.Size = DynI->getVal();
743 case ELF::DT_RELAENT:
744 DynRelaRegion.EntSize = DynI->getVal();
748 EC = std::error_code();
751 template <class ELFT>
752 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
753 if (Header->e_shentsize != sizeof(Elf_Shdr))
755 "Invalid section header entry size (e_shentsize) in ELF header");
756 return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
759 template <class ELFT>
760 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
761 return section_begin() + getNumSections();
764 template <class ELFT>
765 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
768 if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
769 report_fatal_error("Invalid symbol size");
770 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
773 template <class ELFT>
774 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
777 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
778 dot_symtab_sec->sh_size);
781 template <class ELFT>
782 typename ELFFile<ELFT>::Elf_Dyn_Iter
783 ELFFile<ELFT>::dynamic_table_begin() const {
784 if (DynamicRegion.Addr)
785 return Elf_Dyn_Iter(DynamicRegion.EntSize,
786 (const char *)DynamicRegion.Addr);
787 return Elf_Dyn_Iter(0, nullptr);
790 template <class ELFT>
791 typename ELFFile<ELFT>::Elf_Dyn_Iter
792 ELFFile<ELFT>::dynamic_table_end(bool NULLEnd) const {
793 if (!DynamicRegion.Addr)
794 return Elf_Dyn_Iter(0, nullptr);
795 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
796 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
799 Elf_Dyn_Iter Start = dynamic_table_begin();
800 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
803 // Include the DT_NULL.
811 template <class ELFT>
812 StringRef ELFFile<ELFT>::getLoadName() const {
815 // Find the DT_SONAME entry
816 for (const auto &Entry : dynamic_table())
817 if (Entry.getTag() == ELF::DT_SONAME) {
818 dt_soname = getDynamicString(Entry.getVal());
825 template <class ELFT>
826 template <typename T>
827 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
828 ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
829 if (std::error_code EC = Sec.getError())
830 report_fatal_error(EC.message());
831 return getEntry<T>(*Sec, Entry);
834 template <class ELFT>
835 template <typename T>
836 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
837 uint32_t Entry) const {
838 return reinterpret_cast<const T *>(base() + Section->sh_offset +
839 (Entry * Section->sh_entsize));
842 template <class ELFT>
843 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
844 ELFFile<ELFT>::getSection(uint32_t Index) const {
845 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
846 if (Index >= getNumSections())
847 return object_error::invalid_section_index;
849 return reinterpret_cast<const Elf_Shdr *>(
850 reinterpret_cast<const char *>(SectionHeaderTable) +
851 (Index * Header->e_shentsize));
854 template <class ELFT>
856 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
857 if (Section->sh_type != ELF::SHT_STRTAB)
858 return object_error::parse_failed;
859 uint64_t Offset = Section->sh_offset;
860 uint64_t Size = Section->sh_size;
861 if (Offset + Size > Buf.size())
862 return object_error::parse_failed;
863 StringRef Data((const char *)base() + Section->sh_offset, Size);
864 if (Data[Size - 1] != '\0')
865 return object_error::string_table_non_null_end;
869 template <class ELFT>
870 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
871 if (!DotDynSymSec || Offset >= DynSymStrTab.size())
873 return (const char *)DynSymStrTab.begin() + Offset;
876 template <class ELFT>
878 ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
879 return Symb->getName(DotStrtab);
882 template <class ELFT>
884 ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
885 return StringRef(getDynamicString(Symb->st_name));
888 template <class ELFT>
889 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Sym *Symb,
890 bool IsDynamic) const {
892 return getDynamicSymbolName(Symb);
893 return getStaticSymbolName(Symb);
896 template <class ELFT>
898 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
899 uint32_t Offset = Section->sh_name;
900 if (Offset >= DotShstrtab.size())
901 return object_error::parse_failed;
902 return StringRef(DotShstrtab.data() + Offset);
905 template <class ELFT>
906 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
908 bool &IsDefault) const {
911 ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
912 if (std::error_code EC = StrTabOrErr.getError())
914 StrTab = *StrTabOrErr;
916 // Handle non-dynamic symbols.
917 if (section != DotDynSymSec && section != nullptr) {
918 // Non-dynamic symbols can have versions in their names
919 // A name of the form 'foo@V1' indicates version 'V1', non-default.
920 // A name of the form 'foo@@V2' indicates version 'V2', default version.
921 ErrorOr<StringRef> SymName = symb->getName(StrTab);
924 StringRef Name = *SymName;
925 size_t atpos = Name.find('@');
926 if (atpos == StringRef::npos) {
928 return StringRef("");
931 if (atpos < Name.size() && Name[atpos] == '@') {
937 return Name.substr(atpos);
940 // This is a dynamic symbol. Look in the GNU symbol version table.
941 if (!dot_gnu_version_sec) {
944 return StringRef("");
947 // Determine the position in the symbol table of this entry.
949 (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
950 reinterpret_cast<uintptr_t>(base())) /
953 // Get the corresponding version index entry
954 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
955 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
957 // Special markers for unversioned symbols.
958 if (version_index == ELF::VER_NDX_LOCAL ||
959 version_index == ELF::VER_NDX_GLOBAL) {
961 return StringRef("");
964 // Lookup this symbol in the version table
966 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
967 return object_error::parse_failed;
968 const VersionMapEntry &entry = VersionMap[version_index];
970 // Get the version name string
972 if (entry.isVerdef()) {
973 // The first Verdaux entry holds the name.
974 name_offset = entry.getVerdef()->getAux()->vda_name;
976 name_offset = entry.getVernaux()->vna_name;
980 if (entry.isVerdef()) {
981 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
986 if (name_offset >= DynSymStrTab.size())
987 return object_error::parse_failed;
988 return StringRef(getDynamicString(name_offset));
991 /// This function returns the hash value for a symbol in the .dynsym section
992 /// Name of the API remains consistent as specified in the libelf
993 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
994 static inline unsigned elf_hash(StringRef &symbolName) {
996 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
997 h = (h << 4) + symbolName[i];
1005 } // end namespace object
1006 } // end namespace llvm