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 };
163 typedef ptrdiff_t difference_type;
164 typedef const Elf_Sym value_type;
165 typedef std::random_access_iterator_tag iterator_category;
166 typedef value_type &reference;
167 typedef value_type *pointer;
169 /// \brief Default construct iterator.
170 Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
171 Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
172 : EntitySize(EntSize), Current(Start, IsDynamic) {}
174 reference operator*() {
175 assert(Current.getPointer() &&
176 "Attempted to dereference an invalid iterator!");
177 return *reinterpret_cast<pointer>(Current.getPointer());
180 pointer operator->() {
181 assert(Current.getPointer() &&
182 "Attempted to dereference an invalid iterator!");
183 return reinterpret_cast<pointer>(Current.getPointer());
186 bool operator==(const Elf_Sym_Iter &Other) {
187 return Current == Other.Current;
190 bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
192 Elf_Sym_Iter &operator++() {
193 assert(Current.getPointer() &&
194 "Attempted to increment an invalid iterator!");
195 Current.setPointer(Current.getPointer() + EntitySize);
199 Elf_Sym_Iter operator++(int) {
200 Elf_Sym_Iter Tmp = *this;
205 Elf_Sym_Iter operator+(difference_type Dist) {
206 assert(Current.getPointer() &&
207 "Attempted to increment an invalid iterator!");
208 Current.setPointer(Current.getPointer() + EntitySize * Dist);
212 difference_type operator-(const Elf_Sym_Iter &Other) const {
213 assert(EntitySize == Other.EntitySize &&
214 "Subtracting iterators of different EntitySize!");
215 return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
218 const char *get() const { return Current.getPointer(); }
220 bool isDynamic() const { return Current.getInt(); }
222 uintX_t getEntSize() const { return EntitySize; }
226 PointerIntPair<const char *, 1, bool,
227 ArchivePointerTypeTraits<const char> > Current;
231 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
232 typedef DenseMap<unsigned, unsigned> IndexMap_t;
236 const uint8_t *base() const {
237 return reinterpret_cast<const uint8_t *>(Buf.data());
240 const Elf_Ehdr *Header;
241 const Elf_Shdr *SectionHeaderTable;
242 const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
243 const Elf_Shdr *dot_strtab_sec; // Symbol header string table.
244 const Elf_Shdr *dot_symtab_sec; // Symbol table section.
246 const Elf_Shdr *SymbolTableSectionHeaderIndex;
247 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
249 const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
250 const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
251 const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
253 /// \brief Represents a region described by entries in the .dynamic table.
254 struct DynRegionInfo {
255 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
256 /// \brief Address in current address space.
258 /// \brief Size in bytes of the region.
260 /// \brief Size of each entity in the region.
264 DynRegionInfo DynamicRegion;
265 DynRegionInfo DynHashRegion;
266 DynRegionInfo DynStrRegion;
267 DynRegionInfo DynSymRegion;
269 // Pointer to SONAME entry in dynamic string table
270 // This is set the first time getLoadName is called.
271 mutable const char *dt_soname;
273 // Records for each version index the corresponding Verdef or Vernaux entry.
274 // This is filled the first time LoadVersionMap() is called.
275 class VersionMapEntry : public PointerIntPair<const void*, 1> {
277 // If the integer is 0, this is an Elf_Verdef*.
278 // If the integer is 1, this is an Elf_Vernaux*.
279 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
280 VersionMapEntry(const Elf_Verdef *verdef)
281 : PointerIntPair<const void*, 1>(verdef, 0) { }
282 VersionMapEntry(const Elf_Vernaux *vernaux)
283 : PointerIntPair<const void*, 1>(vernaux, 1) { }
284 bool isNull() const { return getPointer() == nullptr; }
285 bool isVerdef() const { return !isNull() && getInt() == 0; }
286 bool isVernaux() const { return !isNull() && getInt() == 1; }
287 const Elf_Verdef *getVerdef() const {
288 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
290 const Elf_Vernaux *getVernaux() const {
291 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
294 mutable SmallVector<VersionMapEntry, 16> VersionMap;
295 void LoadVersionDefs(const Elf_Shdr *sec) const;
296 void LoadVersionNeeds(const Elf_Shdr *ec) const;
297 void LoadVersionMap() const;
301 const T *getEntry(uint32_t Section, uint32_t Entry) const;
302 template <typename T>
303 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
304 const char *getString(uint32_t section, uint32_t offset) const;
305 const char *getString(const Elf_Shdr *section, uint32_t offset) const;
306 const char *getDynamicString(uintX_t Offset) const;
307 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
309 bool &IsDefault) const;
310 void VerifyStrTab(const Elf_Shdr *sh) const;
312 StringRef getRelocationTypeName(uint32_t Type) const;
313 void getRelocationTypeName(uint32_t Type,
314 SmallVectorImpl<char> &Result) const;
316 /// \brief Get the symbol table section and symbol for a given relocation.
317 template <class RelT>
318 std::pair<const Elf_Shdr *, const Elf_Sym *>
319 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
321 ELFFile(StringRef Object, std::error_code &EC);
323 bool isMipsELF64() const {
324 return Header->e_machine == ELF::EM_MIPS &&
325 Header->getFileClass() == ELF::ELFCLASS64;
328 bool isMips64EL() const {
329 return Header->e_machine == ELF::EM_MIPS &&
330 Header->getFileClass() == ELF::ELFCLASS64 &&
331 Header->getDataEncoding() == ELF::ELFDATA2LSB;
334 Elf_Shdr_Iter begin_sections() const;
335 Elf_Shdr_Iter end_sections() const;
336 Elf_Shdr_Range sections() const {
337 return make_range(begin_sections(), end_sections());
340 Elf_Sym_Iter begin_symbols() const;
341 Elf_Sym_Iter end_symbols() const;
343 Elf_Dyn_Iter begin_dynamic_table() const;
344 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
345 /// the section size.
346 Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
347 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
348 return make_range(begin_dynamic_table(), end_dynamic_table(NULLEnd));
351 Elf_Sym_Iter begin_dynamic_symbols() const {
352 if (DynSymRegion.Addr)
353 return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
355 return Elf_Sym_Iter(0, nullptr, true);
358 Elf_Sym_Iter end_dynamic_symbols() const {
359 if (DynSymRegion.Addr)
360 return Elf_Sym_Iter(DynSymRegion.EntSize,
361 (const char *)DynSymRegion.Addr + DynSymRegion.Size,
363 return Elf_Sym_Iter(0, nullptr, true);
366 Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
367 return Elf_Rela_Iter(sec->sh_entsize,
368 (const char *)(base() + sec->sh_offset));
371 Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
372 return Elf_Rela_Iter(
374 (const char *)(base() + sec->sh_offset + sec->sh_size));
377 Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
378 return Elf_Rel_Iter(sec->sh_entsize,
379 (const char *)(base() + sec->sh_offset));
382 Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
383 return Elf_Rel_Iter(sec->sh_entsize,
384 (const char *)(base() + sec->sh_offset + sec->sh_size));
387 /// \brief Iterate over program header table.
388 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
390 Elf_Phdr_Iter begin_program_headers() const {
391 return Elf_Phdr_Iter(Header->e_phentsize,
392 (const char*)base() + Header->e_phoff);
395 Elf_Phdr_Iter end_program_headers() const {
396 return Elf_Phdr_Iter(Header->e_phentsize,
397 (const char*)base() +
399 (Header->e_phnum * Header->e_phentsize));
402 uint64_t getNumSections() const;
403 uintX_t getStringTableIndex() const;
404 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
405 const Elf_Ehdr *getHeader() const { return Header; }
406 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
407 const Elf_Shdr *getSection(uint32_t Index) const;
408 const Elf_Sym *getSymbol(uint32_t index) const;
410 ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
412 /// \brief Get the name of \p Symb.
413 /// \param SymTab The symbol table section \p Symb is contained in.
414 /// \param Symb The symbol to get the name of.
416 /// \p SymTab is used to lookup the string table to use to get the symbol's
418 ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
419 const Elf_Sym *Symb) const;
420 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
421 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
422 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
423 StringRef getLoadName() const;
426 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
427 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
428 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
429 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
431 // Iterate through the version definitions, and place each Elf_Verdef
432 // in the VersionMap according to its index.
433 template <class ELFT>
434 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
435 unsigned vd_size = sec->sh_size; // Size of section in bytes
436 unsigned vd_count = sec->sh_info; // Number of Verdef entries
437 const char *sec_start = (const char*)base() + sec->sh_offset;
438 const char *sec_end = sec_start + vd_size;
439 // The first Verdef entry is at the start of the section.
440 const char *p = sec_start;
441 for (unsigned i = 0; i < vd_count; i++) {
442 if (p + sizeof(Elf_Verdef) > sec_end)
443 report_fatal_error("Section ended unexpectedly while scanning "
444 "version definitions.");
445 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
446 if (vd->vd_version != ELF::VER_DEF_CURRENT)
447 report_fatal_error("Unexpected verdef version");
448 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
449 if (index >= VersionMap.size())
450 VersionMap.resize(index + 1);
451 VersionMap[index] = VersionMapEntry(vd);
456 // Iterate through the versions needed section, and place each Elf_Vernaux
457 // in the VersionMap according to its index.
458 template <class ELFT>
459 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
460 unsigned vn_size = sec->sh_size; // Size of section in bytes
461 unsigned vn_count = sec->sh_info; // Number of Verneed entries
462 const char *sec_start = (const char *)base() + sec->sh_offset;
463 const char *sec_end = sec_start + vn_size;
464 // The first Verneed entry is at the start of the section.
465 const char *p = sec_start;
466 for (unsigned i = 0; i < vn_count; i++) {
467 if (p + sizeof(Elf_Verneed) > sec_end)
468 report_fatal_error("Section ended unexpectedly while scanning "
469 "version needed records.");
470 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
471 if (vn->vn_version != ELF::VER_NEED_CURRENT)
472 report_fatal_error("Unexpected verneed version");
473 // Iterate through the Vernaux entries
474 const char *paux = p + vn->vn_aux;
475 for (unsigned j = 0; j < vn->vn_cnt; j++) {
476 if (paux + sizeof(Elf_Vernaux) > sec_end)
477 report_fatal_error("Section ended unexpected while scanning auxiliary "
478 "version needed records.");
479 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
480 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
481 if (index >= VersionMap.size())
482 VersionMap.resize(index + 1);
483 VersionMap[index] = VersionMapEntry(vna);
484 paux += vna->vna_next;
490 template <class ELFT>
491 void ELFFile<ELFT>::LoadVersionMap() const {
492 // If there is no dynamic symtab or version table, there is nothing to do.
493 if (!DynSymRegion.Addr || !dot_gnu_version_sec)
496 // Has the VersionMap already been loaded?
497 if (VersionMap.size() > 0)
500 // The first two version indexes are reserved.
501 // Index 0 is LOCAL, index 1 is GLOBAL.
502 VersionMap.push_back(VersionMapEntry());
503 VersionMap.push_back(VersionMapEntry());
505 if (dot_gnu_version_d_sec)
506 LoadVersionDefs(dot_gnu_version_d_sec);
508 if (dot_gnu_version_r_sec)
509 LoadVersionNeeds(dot_gnu_version_r_sec);
512 template <class ELFT>
514 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
515 assert(symb->st_shndx == ELF::SHN_XINDEX);
516 return ExtendedSymbolTable.lookup(symb);
519 template <class ELFT>
520 const typename ELFFile<ELFT>::Elf_Shdr *
521 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
522 if (symb->st_shndx == ELF::SHN_XINDEX)
523 return getSection(ExtendedSymbolTable.lookup(symb));
524 if (symb->st_shndx >= ELF::SHN_LORESERVE)
526 return getSection(symb->st_shndx);
529 template <class ELFT>
530 const typename ELFFile<ELFT>::Elf_Sym *
531 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
532 return &*(begin_symbols() + Index);
535 template <class ELFT>
536 ErrorOr<ArrayRef<uint8_t> >
537 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
538 if (Sec->sh_offset + Sec->sh_size > Buf.size())
539 return object_error::parse_failed;
540 const uint8_t *Start = base() + Sec->sh_offset;
541 return makeArrayRef(Start, Sec->sh_size);
544 template <class ELFT>
545 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
546 return getELFRelocationTypeName(Header->e_machine, Type);
549 template <class ELFT>
550 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
551 SmallVectorImpl<char> &Result) const {
552 if (!isMipsELF64()) {
553 StringRef Name = getRelocationTypeName(Type);
554 Result.append(Name.begin(), Name.end());
556 // The Mips N64 ABI allows up to three operations to be specified per
557 // relocation record. Unfortunately there's no easy way to test for the
558 // presence of N64 ELFs as they have no special flag that identifies them
559 // as being N64. We can safely assume at the moment that all Mips
560 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
561 // information to disambiguate between old vs new ABIs.
562 uint8_t Type1 = (Type >> 0) & 0xFF;
563 uint8_t Type2 = (Type >> 8) & 0xFF;
564 uint8_t Type3 = (Type >> 16) & 0xFF;
566 // Concat all three relocation type names.
567 StringRef Name = getRelocationTypeName(Type1);
568 Result.append(Name.begin(), Name.end());
570 Name = getRelocationTypeName(Type2);
571 Result.append(1, '/');
572 Result.append(Name.begin(), Name.end());
574 Name = getRelocationTypeName(Type3);
575 Result.append(1, '/');
576 Result.append(Name.begin(), Name.end());
580 template <class ELFT>
581 template <class RelT>
582 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
583 const typename ELFFile<ELFT>::Elf_Sym *>
584 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
586 return std::make_pair(nullptr, nullptr);
587 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
588 return std::make_pair(
589 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
592 // Verify that the last byte in the string table in a null.
593 template <class ELFT>
594 void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
595 const char *strtab = (const char *)base() + sh->sh_offset;
596 if (strtab[sh->sh_size - 1] != 0)
597 // FIXME: Proper error handling.
598 report_fatal_error("String table must end with a null terminator!");
601 template <class ELFT>
602 uint64_t ELFFile<ELFT>::getNumSections() const {
603 assert(Header && "Header not initialized!");
604 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
605 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
606 return SectionHeaderTable->sh_size;
608 return Header->e_shnum;
611 template <class ELFT>
612 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
613 if (Header->e_shnum == ELF::SHN_UNDEF) {
614 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
615 return SectionHeaderTable->sh_link;
616 if (Header->e_shstrndx >= getNumSections())
619 return Header->e_shstrndx;
622 template <class ELFT>
623 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
624 : Buf(Object), SectionHeaderTable(nullptr), dot_shstrtab_sec(nullptr),
625 dot_strtab_sec(nullptr), dot_symtab_sec(nullptr),
626 SymbolTableSectionHeaderIndex(nullptr), dot_gnu_version_sec(nullptr),
627 dot_gnu_version_r_sec(nullptr), dot_gnu_version_d_sec(nullptr),
629 const uint64_t FileSize = Buf.size();
631 if (sizeof(Elf_Ehdr) > FileSize) {
633 EC = object_error::parse_failed;
637 Header = reinterpret_cast<const Elf_Ehdr *>(base());
639 if (Header->e_shoff == 0)
642 const uint64_t SectionTableOffset = Header->e_shoff;
644 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
645 // Section header table goes past end of file!
646 EC = object_error::parse_failed;
650 // The getNumSections() call below depends on SectionHeaderTable being set.
652 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
653 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
655 if (SectionTableOffset + SectionTableSize > FileSize) {
656 // Section table goes past end of file!
657 EC = object_error::parse_failed;
661 // Scan sections for special sections.
663 for (const Elf_Shdr &Sec : sections()) {
664 switch (Sec.sh_type) {
665 case ELF::SHT_SYMTAB_SHNDX:
666 if (SymbolTableSectionHeaderIndex) {
667 // More than one .symtab_shndx!
668 EC = object_error::parse_failed;
671 SymbolTableSectionHeaderIndex = &Sec;
673 case ELF::SHT_SYMTAB:
674 if (dot_symtab_sec) {
675 // More than one .symtab!
676 EC = object_error::parse_failed;
679 dot_symtab_sec = &Sec;
680 dot_strtab_sec = getSection(Sec.sh_link);
682 case ELF::SHT_DYNSYM: {
683 if (DynSymRegion.Addr) {
684 // More than one .dynsym!
685 EC = object_error::parse_failed;
688 DynSymRegion.Addr = base() + Sec.sh_offset;
689 DynSymRegion.Size = Sec.sh_size;
690 DynSymRegion.EntSize = Sec.sh_entsize;
691 const Elf_Shdr *DynStr = getSection(Sec.sh_link);
692 DynStrRegion.Addr = base() + DynStr->sh_offset;
693 DynStrRegion.Size = DynStr->sh_size;
694 DynStrRegion.EntSize = DynStr->sh_entsize;
697 case ELF::SHT_DYNAMIC:
698 if (DynamicRegion.Addr) {
699 // More than one .dynamic!
700 EC = object_error::parse_failed;
703 DynamicRegion.Addr = base() + Sec.sh_offset;
704 DynamicRegion.Size = Sec.sh_size;
705 DynamicRegion.EntSize = Sec.sh_entsize;
707 case ELF::SHT_GNU_versym:
708 if (dot_gnu_version_sec != nullptr) {
709 // More than one .gnu.version section!
710 EC = object_error::parse_failed;
713 dot_gnu_version_sec = &Sec;
715 case ELF::SHT_GNU_verdef:
716 if (dot_gnu_version_d_sec != nullptr) {
717 // More than one .gnu.version_d section!
718 EC = object_error::parse_failed;
721 dot_gnu_version_d_sec = &Sec;
723 case ELF::SHT_GNU_verneed:
724 if (dot_gnu_version_r_sec != nullptr) {
725 // More than one .gnu.version_r section!
726 EC = object_error::parse_failed;
729 dot_gnu_version_r_sec = &Sec;
734 // Get string table sections.
735 dot_shstrtab_sec = getSection(getStringTableIndex());
736 if (dot_shstrtab_sec) {
737 // Verify that the last byte in the string table in a null.
738 VerifyStrTab(dot_shstrtab_sec);
741 // Build symbol name side-mapping if there is one.
742 if (SymbolTableSectionHeaderIndex) {
743 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
744 SymbolTableSectionHeaderIndex->sh_offset);
745 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
747 if (*ShndxTable != ELF::SHN_UNDEF)
748 ExtendedSymbolTable[&*SI] = *ShndxTable;
753 // Scan program headers.
754 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
755 PhdrE = end_program_headers();
756 PhdrI != PhdrE; ++PhdrI) {
757 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
758 DynamicRegion.Addr = base() + PhdrI->p_offset;
759 DynamicRegion.Size = PhdrI->p_filesz;
760 DynamicRegion.EntSize = sizeof(Elf_Dyn);
765 EC = std::error_code();
768 // Get the symbol table index in the symtab section given a symbol
769 template <class ELFT>
770 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
771 uintptr_t SymLoc = uintptr_t(Sym);
772 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
773 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
774 uint64_t SymOffset = SymLoc - SymTabLoc;
775 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
776 "Symbol not multiple of symbol size!");
777 return SymOffset / dot_symtab_sec->sh_entsize;
780 template <class ELFT>
781 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
782 return Elf_Shdr_Iter(Header->e_shentsize,
783 (const char *)base() + Header->e_shoff);
786 template <class ELFT>
787 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
788 return Elf_Shdr_Iter(Header->e_shentsize,
789 (const char *)base() + Header->e_shoff +
790 (getNumSections() * Header->e_shentsize));
793 template <class ELFT>
794 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
796 return Elf_Sym_Iter(0, nullptr, false);
797 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
798 (const char *)base() + dot_symtab_sec->sh_offset, false);
801 template <class ELFT>
802 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
804 return Elf_Sym_Iter(0, nullptr, false);
805 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
806 (const char *)base() + dot_symtab_sec->sh_offset +
807 dot_symtab_sec->sh_size,
811 template <class ELFT>
812 typename ELFFile<ELFT>::Elf_Dyn_Iter
813 ELFFile<ELFT>::begin_dynamic_table() const {
814 if (DynamicRegion.Addr)
815 return Elf_Dyn_Iter(DynamicRegion.EntSize,
816 (const char *)DynamicRegion.Addr);
817 return Elf_Dyn_Iter(0, nullptr);
820 template <class ELFT>
821 typename ELFFile<ELFT>::Elf_Dyn_Iter
822 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
823 if (!DynamicRegion.Addr)
824 return Elf_Dyn_Iter(0, nullptr);
825 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
826 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
829 Elf_Dyn_Iter Start = begin_dynamic_table();
830 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
833 // Include the DT_NULL.
841 template <class ELFT>
842 StringRef ELFFile<ELFT>::getLoadName() const {
845 // Find the DT_SONAME entry
846 for (const auto &Entry : dynamic_table())
847 if (Entry.getTag() == ELF::DT_SONAME) {
848 dt_soname = getDynamicString(Entry.getVal());
855 template <class ELFT>
856 template <typename T>
857 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
858 return getEntry<T>(getSection(Section), Entry);
861 template <class ELFT>
862 template <typename T>
863 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
864 uint32_t Entry) const {
865 return reinterpret_cast<const T *>(base() + Section->sh_offset +
866 (Entry * Section->sh_entsize));
869 template <class ELFT>
870 const typename ELFFile<ELFT>::Elf_Shdr *
871 ELFFile<ELFT>::getSection(uint32_t index) const {
874 if (!SectionHeaderTable || index >= getNumSections())
875 // FIXME: Proper error handling.
876 report_fatal_error("Invalid section index!");
878 return reinterpret_cast<const Elf_Shdr *>(
879 reinterpret_cast<const char *>(SectionHeaderTable)
880 + (index * Header->e_shentsize));
883 template <class ELFT>
884 const char *ELFFile<ELFT>::getString(uint32_t section,
885 ELF::Elf32_Word offset) const {
886 return getString(getSection(section), offset);
889 template <class ELFT>
890 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
891 ELF::Elf32_Word offset) const {
892 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
893 if (offset >= section->sh_size)
894 // FIXME: Proper error handling.
895 report_fatal_error("Symbol name offset outside of string table!");
896 return (const char *)base() + section->sh_offset + offset;
899 template <class ELFT>
900 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
901 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
903 return (const char *)DynStrRegion.Addr + Offset;
906 template <class ELFT>
907 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
908 if (!Sym.isDynamic())
909 return getSymbolName(dot_symtab_sec, &*Sym);
911 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
912 return object_error::parse_failed;
913 return StringRef(getDynamicString(Sym->st_name));
916 template <class ELFT>
917 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
918 const Elf_Sym *Symb) const {
919 if (Symb->st_name == 0)
920 return StringRef("");
922 const Elf_Shdr *StrTab = getSection(Section->sh_link);
923 if (Symb->st_name >= StrTab->sh_size)
924 return object_error::parse_failed;
925 return StringRef(getString(StrTab, Symb->st_name));
928 template <class ELFT>
930 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
931 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
932 return object_error::parse_failed;
933 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
936 template <class ELFT>
937 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
939 bool &IsDefault) const {
940 // Handle non-dynamic symbols.
941 if (section != DynSymRegion.Addr && section != nullptr) {
942 // Non-dynamic symbols can have versions in their names
943 // A name of the form 'foo@V1' indicates version 'V1', non-default.
944 // A name of the form 'foo@@V2' indicates version 'V2', default version.
945 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
948 StringRef Name = *SymName;
949 size_t atpos = Name.find('@');
950 if (atpos == StringRef::npos) {
952 return StringRef("");
955 if (atpos < Name.size() && Name[atpos] == '@') {
961 return Name.substr(atpos);
964 // This is a dynamic symbol. Look in the GNU symbol version table.
965 if (!dot_gnu_version_sec) {
968 return StringRef("");
971 // Determine the position in the symbol table of this entry.
972 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
973 DynSymRegion.EntSize;
975 // Get the corresponding version index entry
976 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
977 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
979 // Special markers for unversioned symbols.
980 if (version_index == ELF::VER_NDX_LOCAL ||
981 version_index == ELF::VER_NDX_GLOBAL) {
983 return StringRef("");
986 // Lookup this symbol in the version table
988 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
989 return object_error::parse_failed;
990 const VersionMapEntry &entry = VersionMap[version_index];
992 // Get the version name string
994 if (entry.isVerdef()) {
995 // The first Verdaux entry holds the name.
996 name_offset = entry.getVerdef()->getAux()->vda_name;
998 name_offset = entry.getVernaux()->vna_name;
1002 if (entry.isVerdef()) {
1003 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
1008 if (name_offset >= DynStrRegion.Size)
1009 return object_error::parse_failed;
1010 return StringRef(getDynamicString(name_offset));
1013 /// This function returns the hash value for a symbol in the .dynsym section
1014 /// Name of the API remains consistent as specified in the libelf
1015 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1016 static inline unsigned elf_hash(StringRef &symbolName) {
1018 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1019 h = (h << 4) + symbolName[i];
1020 g = h & 0xf0000000L;
1027 } // end namespace object
1028 } // end namespace llvm