1 //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the ELFFile template class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_OBJECT_ELF_H
15 #define LLVM_OBJECT_ELF_H
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Object/ELFTypes.h"
24 #include "llvm/Object/Error.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/Endian.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
39 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
41 // Subclasses of ELFFile may need this for template instantiation
42 inline std::pair<unsigned char, unsigned char>
43 getElfArchType(StringRef Object) {
44 if (Object.size() < ELF::EI_NIDENT)
45 return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
46 (uint8_t)ELF::ELFDATANONE);
47 return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
48 (uint8_t)Object[ELF::EI_DATA]);
54 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
55 typedef typename std::conditional<ELFT::Is64Bits,
56 uint64_t, uint32_t>::type uintX_t;
58 /// \brief Iterate over constant sized entities.
60 class ELFEntityIterator {
62 typedef ptrdiff_t difference_type;
63 typedef EntT value_type;
64 typedef std::forward_iterator_tag iterator_category;
65 typedef value_type &reference;
66 typedef value_type *pointer;
68 /// \brief Default construct iterator.
69 ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
70 ELFEntityIterator(uintX_t EntSize, const char *Start)
71 : EntitySize(EntSize), Current(Start) {}
73 reference operator *() {
74 assert(Current && "Attempted to dereference an invalid iterator!");
75 return *reinterpret_cast<pointer>(Current);
78 pointer operator ->() {
79 assert(Current && "Attempted to dereference an invalid iterator!");
80 return reinterpret_cast<pointer>(Current);
83 bool operator ==(const ELFEntityIterator &Other) {
84 return Current == Other.Current;
87 bool operator !=(const ELFEntityIterator &Other) {
88 return !(*this == Other);
91 ELFEntityIterator &operator ++() {
92 assert(Current && "Attempted to increment an invalid iterator!");
93 Current += EntitySize;
97 ELFEntityIterator &operator+(difference_type n) {
98 assert(Current && "Attempted to increment an invalid iterator!");
99 Current += (n * EntitySize);
103 ELFEntityIterator &operator-(difference_type n) {
104 assert(Current && "Attempted to subtract an invalid iterator!");
105 Current -= (n * EntitySize);
109 ELFEntityIterator operator ++(int) {
110 ELFEntityIterator Tmp = *this;
115 difference_type operator -(const ELFEntityIterator &Other) const {
116 assert(EntitySize == Other.EntitySize &&
117 "Subtracting iterators of different EntitySize!");
118 return (Current - Other.Current) / EntitySize;
121 const char *get() const { return Current; }
123 uintX_t getEntSize() const { return EntitySize; }
130 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
131 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
132 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
133 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
134 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
135 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
136 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
137 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
138 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
139 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
140 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
141 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
142 typedef Elf_Hash_Impl<ELFT> Elf_Hash;
143 typedef iterator_range<const Elf_Dyn *> Elf_Dyn_Range;
144 typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
146 /// \brief Archive files are 2 byte aligned, so we need this for
147 /// PointerIntPair to work.
148 template <typename T>
149 class ArchivePointerTypeTraits {
151 static inline const void *getAsVoidPointer(T *P) { return P; }
152 static inline T *getFromVoidPointer(const void *P) {
153 return static_cast<T *>(P);
155 enum { NumLowBitsAvailable = 1 };
158 typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
161 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
162 typedef DenseMap<unsigned, unsigned> IndexMap_t;
166 const uint8_t *base() const {
167 return reinterpret_cast<const uint8_t *>(Buf.data());
170 const Elf_Ehdr *Header;
171 const Elf_Shdr *SectionHeaderTable = nullptr;
172 StringRef DotShstrtab; // Section header string table.
173 StringRef DotStrtab; // Symbol header string table.
174 const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
175 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
176 const Elf_Hash *HashTable = nullptr;
178 const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
179 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
181 const Elf_Shdr *dot_gnu_version_sec = nullptr; // .gnu.version
182 const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
183 const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
185 /// \brief Represents a region described by entries in the .dynamic table.
186 struct DynRegionInfo {
187 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
188 /// \brief Address in current address space.
190 /// \brief Size in bytes of the region.
192 /// \brief Size of each entity in the region.
196 DynRegionInfo DynamicRegion;
197 DynRegionInfo DynStrRegion;
198 DynRegionInfo DynRelaRegion;
200 // SONAME entry in dynamic string table
203 // Records for each version index the corresponding Verdef or Vernaux entry.
204 // This is filled the first time LoadVersionMap() is called.
205 class VersionMapEntry : public PointerIntPair<const void*, 1> {
207 // If the integer is 0, this is an Elf_Verdef*.
208 // If the integer is 1, this is an Elf_Vernaux*.
209 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
210 VersionMapEntry(const Elf_Verdef *verdef)
211 : PointerIntPair<const void*, 1>(verdef, 0) { }
212 VersionMapEntry(const Elf_Vernaux *vernaux)
213 : PointerIntPair<const void*, 1>(vernaux, 1) { }
214 bool isNull() const { return getPointer() == nullptr; }
215 bool isVerdef() const { return !isNull() && getInt() == 0; }
216 bool isVernaux() const { return !isNull() && getInt() == 1; }
217 const Elf_Verdef *getVerdef() const {
218 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
220 const Elf_Vernaux *getVernaux() const {
221 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
224 mutable SmallVector<VersionMapEntry, 16> VersionMap;
225 void LoadVersionDefs(const Elf_Shdr *sec) const;
226 void LoadVersionNeeds(const Elf_Shdr *ec) const;
227 void LoadVersionMap() const;
229 void scanDynamicTable();
233 const T *getEntry(uint32_t Section, uint32_t Entry) const;
234 template <typename T>
235 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
237 const Elf_Shdr *getDotSymtabSec() const { return dot_symtab_sec; }
238 const Elf_Shdr *getDotDynSymSec() const { return DotDynSymSec; }
239 const Elf_Hash *getHashTable() const { return HashTable; }
240 StringRef getDynamicStringTable() const {
241 return StringRef((const char *)DynStrRegion.Addr, DynStrRegion.Size);
244 ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
245 ErrorOr<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
247 const char *getDynamicString(uintX_t Offset) const;
248 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
250 bool &IsDefault) const;
251 void VerifyStrTab(const Elf_Shdr *sh) const;
253 StringRef getRelocationTypeName(uint32_t Type) const;
254 void getRelocationTypeName(uint32_t Type,
255 SmallVectorImpl<char> &Result) const;
257 /// \brief Get the symbol table section and symbol for a given relocation.
258 template <class RelT>
259 std::pair<const Elf_Shdr *, const Elf_Sym *>
260 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
262 ELFFile(StringRef Object, std::error_code &EC);
264 bool isMipsELF64() const {
265 return Header->e_machine == ELF::EM_MIPS &&
266 Header->getFileClass() == ELF::ELFCLASS64;
269 bool isMips64EL() const {
270 return Header->e_machine == ELF::EM_MIPS &&
271 Header->getFileClass() == ELF::ELFCLASS64 &&
272 Header->getDataEncoding() == ELF::ELFDATA2LSB;
275 const Elf_Shdr *section_begin() const;
276 const Elf_Shdr *section_end() const;
277 Elf_Shdr_Range sections() const {
278 return make_range(section_begin(), section_end());
281 const Elf_Sym *symbol_begin() const;
282 const Elf_Sym *symbol_end() const;
283 Elf_Sym_Range symbols() const {
284 return make_range(symbol_begin(), symbol_end());
287 const Elf_Dyn *dynamic_table_begin() const;
288 const Elf_Dyn *dynamic_table_end() const;
289 Elf_Dyn_Range dynamic_table() const {
290 return make_range(dynamic_table_begin(), dynamic_table_end());
293 const Elf_Sym *dynamic_symbol_begin() const {
296 if (DotDynSymSec->sh_entsize != sizeof(Elf_Sym))
297 report_fatal_error("Invalid symbol size");
298 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset);
301 const Elf_Sym *dynamic_symbol_end() const {
304 return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset +
305 DotDynSymSec->sh_size);
308 Elf_Sym_Range dynamic_symbols() const {
309 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
312 const Elf_Rela *dyn_rela_begin() const {
313 if (DynRelaRegion.Size && DynRelaRegion.EntSize != sizeof(Elf_Rela))
314 report_fatal_error("Invalid relocation entry size");
315 return reinterpret_cast<const Elf_Rela *>(DynRelaRegion.Addr);
318 const Elf_Rela *dyn_rela_end() const {
319 uint64_t Size = DynRelaRegion.Size;
320 if (Size % sizeof(Elf_Rela))
321 report_fatal_error("Invalid relocation table size");
322 return dyn_rela_begin() + Size / sizeof(Elf_Rela);
325 typedef iterator_range<const Elf_Rela *> Elf_Rela_Range;
327 Elf_Rela_Range dyn_relas() const {
328 return make_range(dyn_rela_begin(), dyn_rela_end());
331 const Elf_Rela *rela_begin(const Elf_Shdr *sec) const {
332 if (sec->sh_entsize != sizeof(Elf_Rela))
333 report_fatal_error("Invalid relocation entry size");
334 return reinterpret_cast<const Elf_Rela *>(base() + sec->sh_offset);
337 const Elf_Rela *rela_end(const Elf_Shdr *sec) const {
338 uint64_t Size = sec->sh_size;
339 if (Size % sizeof(Elf_Rela))
340 report_fatal_error("Invalid relocation table size");
341 return rela_begin(sec) + Size / sizeof(Elf_Rela);
344 Elf_Rela_Range relas(const Elf_Shdr *Sec) const {
345 return make_range(rela_begin(Sec), rela_end(Sec));
348 const Elf_Rel *rel_begin(const Elf_Shdr *sec) const {
349 if (sec->sh_entsize != sizeof(Elf_Rel))
350 report_fatal_error("Invalid relocation entry size");
351 return reinterpret_cast<const Elf_Rel *>(base() + sec->sh_offset);
354 const Elf_Rel *rel_end(const Elf_Shdr *sec) const {
355 uint64_t Size = sec->sh_size;
356 if (Size % sizeof(Elf_Rel))
357 report_fatal_error("Invalid relocation table size");
358 return rel_begin(sec) + Size / sizeof(Elf_Rel);
361 typedef iterator_range<const Elf_Rel *> Elf_Rel_Range;
362 Elf_Rel_Range rels(const Elf_Shdr *Sec) const {
363 return make_range(rel_begin(Sec), rel_end(Sec));
366 /// \brief Iterate over program header table.
367 const Elf_Phdr *program_header_begin() const {
368 if (Header->e_phnum && Header->e_phentsize != sizeof(Elf_Phdr))
369 report_fatal_error("Invalid program header size");
370 return reinterpret_cast<const Elf_Phdr *>(base() + Header->e_phoff);
373 const Elf_Phdr *program_header_end() const {
374 return program_header_begin() + Header->e_phnum;
377 typedef iterator_range<const Elf_Phdr *> Elf_Phdr_Range;
379 const Elf_Phdr_Range program_headers() const {
380 return make_range(program_header_begin(), program_header_end());
383 uint64_t getNumSections() const;
384 uintX_t getStringTableIndex() const;
385 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
386 const Elf_Ehdr *getHeader() const { return Header; }
387 ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
388 ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
389 const Elf_Sym *getSymbol(uint32_t index) const;
391 ErrorOr<StringRef> getStaticSymbolName(const Elf_Sym *Symb) const;
392 ErrorOr<StringRef> getDynamicSymbolName(const Elf_Sym *Symb) const;
394 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
395 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
396 StringRef getLoadName() const;
399 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
400 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
401 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
402 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
404 // Iterate through the version definitions, and place each Elf_Verdef
405 // in the VersionMap according to its index.
406 template <class ELFT>
407 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
408 unsigned vd_size = sec->sh_size; // Size of section in bytes
409 unsigned vd_count = sec->sh_info; // Number of Verdef entries
410 const char *sec_start = (const char*)base() + sec->sh_offset;
411 const char *sec_end = sec_start + vd_size;
412 // The first Verdef entry is at the start of the section.
413 const char *p = sec_start;
414 for (unsigned i = 0; i < vd_count; i++) {
415 if (p + sizeof(Elf_Verdef) > sec_end)
416 report_fatal_error("Section ended unexpectedly while scanning "
417 "version definitions.");
418 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
419 if (vd->vd_version != ELF::VER_DEF_CURRENT)
420 report_fatal_error("Unexpected verdef version");
421 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
422 if (index >= VersionMap.size())
423 VersionMap.resize(index + 1);
424 VersionMap[index] = VersionMapEntry(vd);
429 // Iterate through the versions needed section, and place each Elf_Vernaux
430 // in the VersionMap according to its index.
431 template <class ELFT>
432 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
433 unsigned vn_size = sec->sh_size; // Size of section in bytes
434 unsigned vn_count = sec->sh_info; // Number of Verneed entries
435 const char *sec_start = (const char *)base() + sec->sh_offset;
436 const char *sec_end = sec_start + vn_size;
437 // The first Verneed entry is at the start of the section.
438 const char *p = sec_start;
439 for (unsigned i = 0; i < vn_count; i++) {
440 if (p + sizeof(Elf_Verneed) > sec_end)
441 report_fatal_error("Section ended unexpectedly while scanning "
442 "version needed records.");
443 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
444 if (vn->vn_version != ELF::VER_NEED_CURRENT)
445 report_fatal_error("Unexpected verneed version");
446 // Iterate through the Vernaux entries
447 const char *paux = p + vn->vn_aux;
448 for (unsigned j = 0; j < vn->vn_cnt; j++) {
449 if (paux + sizeof(Elf_Vernaux) > sec_end)
450 report_fatal_error("Section ended unexpected while scanning auxiliary "
451 "version needed records.");
452 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
453 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
454 if (index >= VersionMap.size())
455 VersionMap.resize(index + 1);
456 VersionMap[index] = VersionMapEntry(vna);
457 paux += vna->vna_next;
463 template <class ELFT>
464 void ELFFile<ELFT>::LoadVersionMap() const {
465 // If there is no dynamic symtab or version table, there is nothing to do.
466 if (!DotDynSymSec || !dot_gnu_version_sec)
469 // Has the VersionMap already been loaded?
470 if (VersionMap.size() > 0)
473 // The first two version indexes are reserved.
474 // Index 0 is LOCAL, index 1 is GLOBAL.
475 VersionMap.push_back(VersionMapEntry());
476 VersionMap.push_back(VersionMapEntry());
478 if (dot_gnu_version_d_sec)
479 LoadVersionDefs(dot_gnu_version_d_sec);
481 if (dot_gnu_version_r_sec)
482 LoadVersionNeeds(dot_gnu_version_r_sec);
485 template <class ELFT>
487 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
488 assert(symb->st_shndx == ELF::SHN_XINDEX);
489 return ExtendedSymbolTable.lookup(symb);
492 template <class ELFT>
493 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
494 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
495 uint32_t Index = symb->st_shndx;
496 if (Index == ELF::SHN_XINDEX)
497 return getSection(ExtendedSymbolTable.lookup(symb));
498 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
500 return getSection(symb->st_shndx);
503 template <class ELFT>
504 const typename ELFFile<ELFT>::Elf_Sym *
505 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
506 return &*(symbol_begin() + Index);
509 template <class ELFT>
510 ErrorOr<ArrayRef<uint8_t> >
511 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
512 if (Sec->sh_offset + Sec->sh_size > Buf.size())
513 return object_error::parse_failed;
514 const uint8_t *Start = base() + Sec->sh_offset;
515 return makeArrayRef(Start, Sec->sh_size);
518 template <class ELFT>
519 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
520 return getELFRelocationTypeName(Header->e_machine, Type);
523 template <class ELFT>
524 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
525 SmallVectorImpl<char> &Result) const {
526 if (!isMipsELF64()) {
527 StringRef Name = getRelocationTypeName(Type);
528 Result.append(Name.begin(), Name.end());
530 // The Mips N64 ABI allows up to three operations to be specified per
531 // relocation record. Unfortunately there's no easy way to test for the
532 // presence of N64 ELFs as they have no special flag that identifies them
533 // as being N64. We can safely assume at the moment that all Mips
534 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
535 // information to disambiguate between old vs new ABIs.
536 uint8_t Type1 = (Type >> 0) & 0xFF;
537 uint8_t Type2 = (Type >> 8) & 0xFF;
538 uint8_t Type3 = (Type >> 16) & 0xFF;
540 // Concat all three relocation type names.
541 StringRef Name = getRelocationTypeName(Type1);
542 Result.append(Name.begin(), Name.end());
544 Name = getRelocationTypeName(Type2);
545 Result.append(1, '/');
546 Result.append(Name.begin(), Name.end());
548 Name = getRelocationTypeName(Type3);
549 Result.append(1, '/');
550 Result.append(Name.begin(), Name.end());
554 template <class ELFT>
555 template <class RelT>
556 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
557 const typename ELFFile<ELFT>::Elf_Sym *>
558 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
560 return std::make_pair(nullptr, nullptr);
561 ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
562 if (std::error_code EC = SymTableOrErr.getError())
563 report_fatal_error(EC.message());
564 const Elf_Shdr *SymTable = *SymTableOrErr;
565 return std::make_pair(
566 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
569 template <class ELFT>
570 uint64_t ELFFile<ELFT>::getNumSections() const {
571 assert(Header && "Header not initialized!");
572 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
573 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
574 return SectionHeaderTable->sh_size;
576 return Header->e_shnum;
579 template <class ELFT>
580 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
581 if (Header->e_shnum == ELF::SHN_UNDEF) {
582 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
583 return SectionHeaderTable->sh_link;
584 if (Header->e_shstrndx >= getNumSections())
587 return Header->e_shstrndx;
590 template <class ELFT>
591 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
593 const uint64_t FileSize = Buf.size();
595 if (sizeof(Elf_Ehdr) > FileSize) {
597 EC = object_error::parse_failed;
601 Header = reinterpret_cast<const Elf_Ehdr *>(base());
603 if (Header->e_shoff == 0) {
608 const uint64_t SectionTableOffset = Header->e_shoff;
610 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
611 // Section header table goes past end of file!
612 EC = object_error::parse_failed;
616 // The getNumSections() call below depends on SectionHeaderTable being set.
618 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
619 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
621 if (SectionTableOffset + SectionTableSize > FileSize) {
622 // Section table goes past end of file!
623 EC = object_error::parse_failed;
627 // Scan sections for special sections.
629 for (const Elf_Shdr &Sec : sections()) {
630 switch (Sec.sh_type) {
633 EC = object_error::parse_failed;
636 HashTable = reinterpret_cast<const Elf_Hash *>(base() + Sec.sh_offset);
638 case ELF::SHT_SYMTAB_SHNDX:
639 if (SymbolTableSectionHeaderIndex) {
640 // More than one .symtab_shndx!
641 EC = object_error::parse_failed;
644 SymbolTableSectionHeaderIndex = &Sec;
646 case ELF::SHT_SYMTAB: {
647 if (dot_symtab_sec) {
648 // More than one .symtab!
649 EC = object_error::parse_failed;
652 dot_symtab_sec = &Sec;
653 ErrorOr<StringRef> SymtabOrErr = getStringTableForSymtab(Sec);
654 if ((EC = SymtabOrErr.getError()))
656 DotStrtab = *SymtabOrErr;
658 case ELF::SHT_DYNSYM: {
660 // More than one .dynsym!
661 EC = object_error::parse_failed;
667 case ELF::SHT_GNU_versym:
668 if (dot_gnu_version_sec != nullptr) {
669 // More than one .gnu.version section!
670 EC = object_error::parse_failed;
673 dot_gnu_version_sec = &Sec;
675 case ELF::SHT_GNU_verdef:
676 if (dot_gnu_version_d_sec != nullptr) {
677 // More than one .gnu.version_d section!
678 EC = object_error::parse_failed;
681 dot_gnu_version_d_sec = &Sec;
683 case ELF::SHT_GNU_verneed:
684 if (dot_gnu_version_r_sec != nullptr) {
685 // More than one .gnu.version_r section!
686 EC = object_error::parse_failed;
689 dot_gnu_version_r_sec = &Sec;
694 // Get string table sections.
695 ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(getStringTableIndex());
696 if ((EC = StrTabSecOrErr.getError()))
699 ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
700 if ((EC = SymtabOrErr.getError()))
702 DotShstrtab = *SymtabOrErr;
704 // Build symbol name side-mapping if there is one.
705 if (SymbolTableSectionHeaderIndex) {
706 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
707 SymbolTableSectionHeaderIndex->sh_offset);
708 for (const Elf_Sym &S : symbols()) {
709 if (*ShndxTable != ELF::SHN_UNDEF)
710 ExtendedSymbolTable[&S] = *ShndxTable;
717 EC = std::error_code();
720 template <class ELFT>
721 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
722 return VAddr < Phdr->p_vaddr;
725 template <class ELFT> void ELFFile<ELFT>::scanDynamicTable() {
726 SmallVector<const Elf_Phdr *, 4> LoadSegments;
727 for (const Elf_Phdr &Phdr : program_headers()) {
728 if (Phdr.p_type == ELF::PT_DYNAMIC) {
729 DynamicRegion.Addr = base() + Phdr.p_offset;
730 DynamicRegion.Size = Phdr.p_filesz;
733 if (Phdr.p_type != ELF::PT_LOAD || Phdr.p_filesz == 0)
735 LoadSegments.push_back(&Phdr);
738 auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t * {
739 const Elf_Phdr **I = std::upper_bound(
740 LoadSegments.begin(), LoadSegments.end(), VAddr, compareAddr<ELFT>);
741 if (I == LoadSegments.begin())
742 report_fatal_error("Virtual address is not in any segment");
744 const Elf_Phdr &Phdr = **I;
745 uint64_t Delta = VAddr - Phdr.p_vaddr;
746 if (Delta >= Phdr.p_filesz)
747 report_fatal_error("Virtual address is not in any segment");
748 return this->base() + Phdr.p_offset + Delta;
751 uint64_t SONameOffset = 0;
752 for (const Elf_Dyn &Dyn : dynamic_table()) {
758 reinterpret_cast<const Elf_Hash *>(toMappedAddr(Dyn.getPtr()));
761 if (!DynStrRegion.Addr)
762 DynStrRegion.Addr = toMappedAddr(Dyn.getPtr());
765 if (!DynStrRegion.Size)
766 DynStrRegion.Size = Dyn.getVal();
769 if (!DynRelaRegion.Addr)
770 DynRelaRegion.Addr = toMappedAddr(Dyn.getPtr());
773 DynRelaRegion.Size = Dyn.getVal();
775 case ELF::DT_RELAENT:
776 DynRelaRegion.EntSize = Dyn.getVal();
779 SONameOffset = Dyn.getVal();
784 DTSoname = getDynamicString(SONameOffset);
787 template <class ELFT>
788 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
789 if (Header->e_shentsize != sizeof(Elf_Shdr))
791 "Invalid section header entry size (e_shentsize) in ELF header");
792 return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
795 template <class ELFT>
796 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
797 return section_begin() + getNumSections();
800 template <class ELFT>
801 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
804 if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
805 report_fatal_error("Invalid symbol size");
806 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
809 template <class ELFT>
810 const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
813 return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
814 dot_symtab_sec->sh_size);
817 template <class ELFT>
818 const typename ELFFile<ELFT>::Elf_Dyn *
819 ELFFile<ELFT>::dynamic_table_begin() const {
820 return reinterpret_cast<const Elf_Dyn *>(DynamicRegion.Addr);
823 template <class ELFT>
824 const typename ELFFile<ELFT>::Elf_Dyn *
825 ELFFile<ELFT>::dynamic_table_end() const {
826 uint64_t Size = DynamicRegion.Size;
827 if (Size % sizeof(Elf_Dyn))
828 report_fatal_error("Invalid dynamic table size");
830 return dynamic_table_begin() + Size / sizeof(Elf_Dyn);
833 template <class ELFT>
834 StringRef ELFFile<ELFT>::getLoadName() const {
838 template <class ELFT>
839 template <typename T>
840 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
841 ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
842 if (std::error_code EC = Sec.getError())
843 report_fatal_error(EC.message());
844 return getEntry<T>(*Sec, Entry);
847 template <class ELFT>
848 template <typename T>
849 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
850 uint32_t Entry) const {
851 return reinterpret_cast<const T *>(base() + Section->sh_offset +
852 (Entry * Section->sh_entsize));
855 template <class ELFT>
856 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
857 ELFFile<ELFT>::getSection(uint32_t Index) const {
858 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
859 if (Index >= getNumSections())
860 return object_error::invalid_section_index;
862 return reinterpret_cast<const Elf_Shdr *>(
863 reinterpret_cast<const char *>(SectionHeaderTable) +
864 (Index * Header->e_shentsize));
867 template <class ELFT>
869 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
870 if (Section->sh_type != ELF::SHT_STRTAB)
871 return object_error::parse_failed;
872 uint64_t Offset = Section->sh_offset;
873 uint64_t Size = Section->sh_size;
874 if (Offset + Size > Buf.size())
875 return object_error::parse_failed;
876 StringRef Data((const char *)base() + Section->sh_offset, Size);
877 if (Data[Size - 1] != '\0')
878 return object_error::string_table_non_null_end;
882 template <class ELFT>
884 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
885 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
886 return object_error::parse_failed;
887 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
888 if (std::error_code EC = SectionOrErr.getError())
890 return getStringTable(*SectionOrErr);
893 template <class ELFT>
894 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
895 if (Offset >= DynStrRegion.Size)
897 return (const char *)DynStrRegion.Addr + Offset;
900 template <class ELFT>
902 ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
903 return Symb->getName(DotStrtab);
906 template <class ELFT>
908 ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
909 return StringRef(getDynamicString(Symb->st_name));
912 template <class ELFT>
914 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
915 uint32_t Offset = Section->sh_name;
916 if (Offset >= DotShstrtab.size())
917 return object_error::parse_failed;
918 return StringRef(DotShstrtab.data() + Offset);
921 template <class ELFT>
922 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
924 bool &IsDefault) const {
927 ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
928 if (std::error_code EC = StrTabOrErr.getError())
930 StrTab = *StrTabOrErr;
932 // Handle non-dynamic symbols.
933 if (section != DotDynSymSec && section != nullptr) {
934 // Non-dynamic symbols can have versions in their names
935 // A name of the form 'foo@V1' indicates version 'V1', non-default.
936 // A name of the form 'foo@@V2' indicates version 'V2', default version.
937 ErrorOr<StringRef> SymName = symb->getName(StrTab);
940 StringRef Name = *SymName;
941 size_t atpos = Name.find('@');
942 if (atpos == StringRef::npos) {
944 return StringRef("");
947 if (atpos < Name.size() && Name[atpos] == '@') {
953 return Name.substr(atpos);
956 // This is a dynamic symbol. Look in the GNU symbol version table.
957 if (!dot_gnu_version_sec) {
960 return StringRef("");
963 // Determine the position in the symbol table of this entry.
965 (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
966 reinterpret_cast<uintptr_t>(base())) /
969 // Get the corresponding version index entry
970 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
971 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
973 // Special markers for unversioned symbols.
974 if (version_index == ELF::VER_NDX_LOCAL ||
975 version_index == ELF::VER_NDX_GLOBAL) {
977 return StringRef("");
980 // Lookup this symbol in the version table
982 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
983 return object_error::parse_failed;
984 const VersionMapEntry &entry = VersionMap[version_index];
986 // Get the version name string
988 if (entry.isVerdef()) {
989 // The first Verdaux entry holds the name.
990 name_offset = entry.getVerdef()->getAux()->vda_name;
992 name_offset = entry.getVernaux()->vna_name;
996 if (entry.isVerdef()) {
997 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
1002 if (name_offset >= DynStrRegion.Size)
1003 return object_error::parse_failed;
1004 return StringRef(getDynamicString(name_offset));
1007 /// This function returns the hash value for a symbol in the .dynsym section
1008 /// Name of the API remains consistent as specified in the libelf
1009 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1010 static inline unsigned elf_hash(StringRef &symbolName) {
1012 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1013 h = (h << 4) + symbolName[i];
1014 g = h & 0xf0000000L;
1021 } // end namespace object
1022 } // end namespace llvm