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(MemoryBuffer *Object) {
44 if (Object->getBufferSize() < ELF::EI_NIDENT)
45 return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATANONE);
46 return std::make_pair((uint8_t) Object->getBufferStart()[ELF::EI_CLASS],
47 (uint8_t) Object->getBufferStart()[ELF::EI_DATA]);
53 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
54 typedef typename std::conditional<ELFT::Is64Bits,
55 uint64_t, uint32_t>::type uintX_t;
57 /// \brief Iterate over constant sized entities.
59 class ELFEntityIterator {
61 typedef ptrdiff_t difference_type;
62 typedef EntT value_type;
63 typedef std::forward_iterator_tag iterator_category;
64 typedef value_type &reference;
65 typedef value_type *pointer;
67 /// \brief Default construct iterator.
68 ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
69 ELFEntityIterator(uintX_t EntSize, const char *Start)
70 : EntitySize(EntSize), Current(Start) {}
72 reference operator *() {
73 assert(Current && "Attempted to dereference an invalid iterator!");
74 return *reinterpret_cast<pointer>(Current);
77 pointer operator ->() {
78 assert(Current && "Attempted to dereference an invalid iterator!");
79 return reinterpret_cast<pointer>(Current);
82 bool operator ==(const ELFEntityIterator &Other) {
83 return Current == Other.Current;
86 bool operator !=(const ELFEntityIterator &Other) {
87 return !(*this == Other);
90 ELFEntityIterator &operator ++() {
91 assert(Current && "Attempted to increment an invalid iterator!");
92 Current += EntitySize;
96 ELFEntityIterator operator ++(int) {
97 ELFEntityIterator Tmp = *this;
102 ELFEntityIterator &operator =(const ELFEntityIterator &Other) {
103 EntitySize = Other.EntitySize;
104 Current = Other.Current;
108 difference_type operator -(const ELFEntityIterator &Other) const {
109 assert(EntitySize == Other.EntitySize &&
110 "Subtracting iterators of different EntitySize!");
111 return (Current - Other.Current) / EntitySize;
114 const char *get() const { return Current; }
116 uintX_t getEntSize() const { return EntitySize; }
123 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
124 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
125 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
126 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
127 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
128 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
129 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
130 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
131 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
132 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
133 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
134 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
135 typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
136 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
137 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
138 typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
140 /// \brief Archive files are 2 byte aligned, so we need this for
141 /// PointerIntPair to work.
142 template <typename T>
143 class ArchivePointerTypeTraits {
145 static inline const void *getAsVoidPointer(T *P) { return P; }
146 static inline T *getFromVoidPointer(const void *P) {
147 return static_cast<T *>(P);
149 enum { NumLowBitsAvailable = 1 };
154 typedef ptrdiff_t difference_type;
155 typedef const Elf_Sym value_type;
156 typedef std::random_access_iterator_tag iterator_category;
157 typedef value_type &reference;
158 typedef value_type *pointer;
160 /// \brief Default construct iterator.
161 Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
162 Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
163 : EntitySize(EntSize), Current(Start, IsDynamic) {}
165 reference operator*() {
166 assert(Current.getPointer() &&
167 "Attempted to dereference an invalid iterator!");
168 return *reinterpret_cast<pointer>(Current.getPointer());
171 pointer operator->() {
172 assert(Current.getPointer() &&
173 "Attempted to dereference an invalid iterator!");
174 return reinterpret_cast<pointer>(Current.getPointer());
177 bool operator==(const Elf_Sym_Iter &Other) {
178 return Current == Other.Current;
181 bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
183 Elf_Sym_Iter &operator++() {
184 assert(Current.getPointer() &&
185 "Attempted to increment an invalid iterator!");
186 Current.setPointer(Current.getPointer() + EntitySize);
190 Elf_Sym_Iter operator++(int) {
191 Elf_Sym_Iter Tmp = *this;
196 Elf_Sym_Iter operator+(difference_type Dist) {
197 assert(Current.getPointer() &&
198 "Attempted to increment an invalid iterator!");
199 Current.setPointer(Current.getPointer() + EntitySize * Dist);
203 Elf_Sym_Iter &operator=(const Elf_Sym_Iter &Other) {
204 EntitySize = Other.EntitySize;
205 Current = Other.Current;
209 difference_type operator-(const Elf_Sym_Iter &Other) const {
210 assert(EntitySize == Other.EntitySize &&
211 "Subtracting iterators of different EntitySize!");
212 return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
215 const char *get() const { return Current.getPointer(); }
217 bool isDynamic() const { return Current.getInt(); }
219 uintX_t getEntSize() const { return EntitySize; }
223 PointerIntPair<const char *, 1, bool,
224 ArchivePointerTypeTraits<const char> > Current;
228 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
229 typedef DenseMap<unsigned, unsigned> IndexMap_t;
233 const uint8_t *base() const {
234 return reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
237 const Elf_Ehdr *Header;
238 const Elf_Shdr *SectionHeaderTable;
239 const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
240 const Elf_Shdr *dot_strtab_sec; // Symbol header string table.
241 const Elf_Shdr *dot_symtab_sec; // Symbol table section.
243 const Elf_Shdr *SymbolTableSectionHeaderIndex;
244 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
246 const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
247 const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
248 const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
250 /// \brief Represents a region described by entries in the .dynamic table.
251 struct DynRegionInfo {
252 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
253 /// \brief Address in current address space.
255 /// \brief Size in bytes of the region.
257 /// \brief Size of each entity in the region.
261 DynRegionInfo DynamicRegion;
262 DynRegionInfo DynHashRegion;
263 DynRegionInfo DynStrRegion;
264 DynRegionInfo DynSymRegion;
266 // Pointer to SONAME entry in dynamic string table
267 // This is set the first time getLoadName is called.
268 mutable const char *dt_soname;
270 // Records for each version index the corresponding Verdef or Vernaux entry.
271 // This is filled the first time LoadVersionMap() is called.
272 class VersionMapEntry : public PointerIntPair<const void*, 1> {
274 // If the integer is 0, this is an Elf_Verdef*.
275 // If the integer is 1, this is an Elf_Vernaux*.
276 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
277 VersionMapEntry(const Elf_Verdef *verdef)
278 : PointerIntPair<const void*, 1>(verdef, 0) { }
279 VersionMapEntry(const Elf_Vernaux *vernaux)
280 : PointerIntPair<const void*, 1>(vernaux, 1) { }
281 bool isNull() const { return getPointer() == nullptr; }
282 bool isVerdef() const { return !isNull() && getInt() == 0; }
283 bool isVernaux() const { return !isNull() && getInt() == 1; }
284 const Elf_Verdef *getVerdef() const {
285 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
287 const Elf_Vernaux *getVernaux() const {
288 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
291 mutable SmallVector<VersionMapEntry, 16> VersionMap;
292 void LoadVersionDefs(const Elf_Shdr *sec) const;
293 void LoadVersionNeeds(const Elf_Shdr *ec) const;
294 void LoadVersionMap() const;
298 const T *getEntry(uint32_t Section, uint32_t Entry) const;
299 template <typename T>
300 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
301 const char *getString(uint32_t section, uint32_t offset) const;
302 const char *getString(const Elf_Shdr *section, uint32_t offset) const;
303 const char *getDynamicString(uintX_t Offset) const;
304 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
306 bool &IsDefault) const;
307 void VerifyStrTab(const Elf_Shdr *sh) const;
309 StringRef getRelocationTypeName(uint32_t Type) const;
310 void getRelocationTypeName(uint32_t Type,
311 SmallVectorImpl<char> &Result) const;
313 /// \brief Get the symbol table section and symbol for a given relocation.
314 template <class RelT>
315 std::pair<const Elf_Shdr *, const Elf_Sym *>
316 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
318 ELFFile(MemoryBuffer *Object, error_code &ec);
320 bool isMipsELF64() const {
321 return Header->e_machine == ELF::EM_MIPS &&
322 Header->getFileClass() == ELF::ELFCLASS64;
325 bool isMips64EL() const {
326 return Header->e_machine == ELF::EM_MIPS &&
327 Header->getFileClass() == ELF::ELFCLASS64 &&
328 Header->getDataEncoding() == ELF::ELFDATA2LSB;
331 Elf_Shdr_Iter begin_sections() const;
332 Elf_Shdr_Iter end_sections() const;
334 Elf_Sym_Iter begin_symbols() const;
335 Elf_Sym_Iter end_symbols() const;
337 Elf_Dyn_Iter begin_dynamic_table() const;
338 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
339 /// the section size.
340 Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
342 Elf_Sym_Iter begin_dynamic_symbols() const {
343 if (DynSymRegion.Addr)
344 return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
346 return Elf_Sym_Iter(0, nullptr, true);
349 Elf_Sym_Iter end_dynamic_symbols() const {
350 if (DynSymRegion.Addr)
351 return Elf_Sym_Iter(DynSymRegion.EntSize,
352 (const char *)DynSymRegion.Addr + DynSymRegion.Size,
354 return Elf_Sym_Iter(0, nullptr, true);
357 Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
358 return Elf_Rela_Iter(sec->sh_entsize,
359 (const char *)(base() + sec->sh_offset));
362 Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
363 return Elf_Rela_Iter(
365 (const char *)(base() + sec->sh_offset + sec->sh_size));
368 Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
369 return Elf_Rel_Iter(sec->sh_entsize,
370 (const char *)(base() + sec->sh_offset));
373 Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
374 return Elf_Rel_Iter(sec->sh_entsize,
375 (const char *)(base() + sec->sh_offset + sec->sh_size));
378 /// \brief Iterate over program header table.
379 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
381 Elf_Phdr_Iter begin_program_headers() const {
382 return Elf_Phdr_Iter(Header->e_phentsize,
383 (const char*)base() + Header->e_phoff);
386 Elf_Phdr_Iter end_program_headers() const {
387 return Elf_Phdr_Iter(Header->e_phentsize,
388 (const char*)base() +
390 (Header->e_phnum * Header->e_phentsize));
393 uint64_t getNumSections() const;
394 uintX_t getStringTableIndex() const;
395 ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
396 const Elf_Ehdr *getHeader() const { return Header; }
397 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
398 const Elf_Shdr *getSection(uint32_t Index) const;
399 const Elf_Sym *getSymbol(uint32_t index) const;
401 ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
403 /// \brief Get the name of \p Symb.
404 /// \param SymTab The symbol table section \p Symb is contained in.
405 /// \param Symb The symbol to get the name of.
407 /// \p SymTab is used to lookup the string table to use to get the symbol's
409 ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
410 const Elf_Sym *Symb) const;
411 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
412 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
413 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
414 StringRef getLoadName() const;
417 // Use an alignment of 2 for the typedefs since that is the worst case for
418 // ELF files in archives.
419 typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
420 typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
421 typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
422 typedef ELFFile<ELFType<support::big, 2, true> > ELF64BEFile;
424 // Iterate through the version definitions, and place each Elf_Verdef
425 // in the VersionMap according to its index.
426 template <class ELFT>
427 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
428 unsigned vd_size = sec->sh_size; // Size of section in bytes
429 unsigned vd_count = sec->sh_info; // Number of Verdef entries
430 const char *sec_start = (const char*)base() + sec->sh_offset;
431 const char *sec_end = sec_start + vd_size;
432 // The first Verdef entry is at the start of the section.
433 const char *p = sec_start;
434 for (unsigned i = 0; i < vd_count; i++) {
435 if (p + sizeof(Elf_Verdef) > sec_end)
436 report_fatal_error("Section ended unexpectedly while scanning "
437 "version definitions.");
438 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
439 if (vd->vd_version != ELF::VER_DEF_CURRENT)
440 report_fatal_error("Unexpected verdef version");
441 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
442 if (index >= VersionMap.size())
443 VersionMap.resize(index + 1);
444 VersionMap[index] = VersionMapEntry(vd);
449 // Iterate through the versions needed section, and place each Elf_Vernaux
450 // in the VersionMap according to its index.
451 template <class ELFT>
452 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
453 unsigned vn_size = sec->sh_size; // Size of section in bytes
454 unsigned vn_count = sec->sh_info; // Number of Verneed entries
455 const char *sec_start = (const char *)base() + sec->sh_offset;
456 const char *sec_end = sec_start + vn_size;
457 // The first Verneed entry is at the start of the section.
458 const char *p = sec_start;
459 for (unsigned i = 0; i < vn_count; i++) {
460 if (p + sizeof(Elf_Verneed) > sec_end)
461 report_fatal_error("Section ended unexpectedly while scanning "
462 "version needed records.");
463 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
464 if (vn->vn_version != ELF::VER_NEED_CURRENT)
465 report_fatal_error("Unexpected verneed version");
466 // Iterate through the Vernaux entries
467 const char *paux = p + vn->vn_aux;
468 for (unsigned j = 0; j < vn->vn_cnt; j++) {
469 if (paux + sizeof(Elf_Vernaux) > sec_end)
470 report_fatal_error("Section ended unexpected while scanning auxiliary "
471 "version needed records.");
472 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
473 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
474 if (index >= VersionMap.size())
475 VersionMap.resize(index + 1);
476 VersionMap[index] = VersionMapEntry(vna);
477 paux += vna->vna_next;
483 template <class ELFT>
484 void ELFFile<ELFT>::LoadVersionMap() const {
485 // If there is no dynamic symtab or version table, there is nothing to do.
486 if (!DynSymRegion.Addr || !dot_gnu_version_sec)
489 // Has the VersionMap already been loaded?
490 if (VersionMap.size() > 0)
493 // The first two version indexes are reserved.
494 // Index 0 is LOCAL, index 1 is GLOBAL.
495 VersionMap.push_back(VersionMapEntry());
496 VersionMap.push_back(VersionMapEntry());
498 if (dot_gnu_version_d_sec)
499 LoadVersionDefs(dot_gnu_version_d_sec);
501 if (dot_gnu_version_r_sec)
502 LoadVersionNeeds(dot_gnu_version_r_sec);
505 template <class ELFT>
506 ELF::Elf64_Word ELFFile<ELFT>::getSymbolTableIndex(const Elf_Sym *symb) const {
507 if (symb->st_shndx == ELF::SHN_XINDEX)
508 return ExtendedSymbolTable.lookup(symb);
509 return symb->st_shndx;
512 template <class ELFT>
513 const typename ELFFile<ELFT>::Elf_Shdr *
514 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
515 if (symb->st_shndx == ELF::SHN_XINDEX)
516 return getSection(ExtendedSymbolTable.lookup(symb));
517 if (symb->st_shndx >= ELF::SHN_LORESERVE)
519 return getSection(symb->st_shndx);
522 template <class ELFT>
523 const typename ELFFile<ELFT>::Elf_Sym *
524 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
525 return &*(begin_symbols() + Index);
528 template <class ELFT>
529 ErrorOr<ArrayRef<uint8_t> >
530 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
531 if (Sec->sh_offset + Sec->sh_size > Buf->getBufferSize())
532 return object_error::parse_failed;
533 const uint8_t *Start = base() + Sec->sh_offset;
534 return ArrayRef<uint8_t>(Start, Sec->sh_size);
537 template <class ELFT>
538 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
539 return getELFRelocationTypeName(Header->e_machine, Type);
542 template <class ELFT>
543 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
544 SmallVectorImpl<char> &Result) const {
545 if (!isMipsELF64()) {
546 StringRef Name = getRelocationTypeName(Type);
547 Result.append(Name.begin(), Name.end());
549 // The Mips N64 ABI allows up to three operations to be specified per
550 // relocation record. Unfortunately there's no easy way to test for the
551 // presence of N64 ELFs as they have no special flag that identifies them
552 // as being N64. We can safely assume at the moment that all Mips
553 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
554 // information to disambiguate between old vs new ABIs.
555 uint8_t Type1 = (Type >> 0) & 0xFF;
556 uint8_t Type2 = (Type >> 8) & 0xFF;
557 uint8_t Type3 = (Type >> 16) & 0xFF;
559 // Concat all three relocation type names.
560 StringRef Name = getRelocationTypeName(Type1);
561 Result.append(Name.begin(), Name.end());
563 Name = getRelocationTypeName(Type2);
564 Result.append(1, '/');
565 Result.append(Name.begin(), Name.end());
567 Name = getRelocationTypeName(Type3);
568 Result.append(1, '/');
569 Result.append(Name.begin(), Name.end());
573 template <class ELFT>
574 template <class RelT>
575 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
576 const typename ELFFile<ELFT>::Elf_Sym *>
577 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
579 return std::make_pair(nullptr, nullptr);
580 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
581 return std::make_pair(
582 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
585 // Verify that the last byte in the string table in a null.
586 template <class ELFT>
587 void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
588 const char *strtab = (const char *)base() + sh->sh_offset;
589 if (strtab[sh->sh_size - 1] != 0)
590 // FIXME: Proper error handling.
591 report_fatal_error("String table must end with a null terminator!");
594 template <class ELFT>
595 uint64_t ELFFile<ELFT>::getNumSections() const {
596 assert(Header && "Header not initialized!");
597 if (Header->e_shnum == ELF::SHN_UNDEF) {
598 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
599 return SectionHeaderTable->sh_size;
601 return Header->e_shnum;
604 template <class ELFT>
605 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
606 if (Header->e_shnum == ELF::SHN_UNDEF) {
607 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
608 return SectionHeaderTable->sh_link;
609 if (Header->e_shstrndx >= getNumSections())
612 return Header->e_shstrndx;
615 template <class ELFT>
616 ELFFile<ELFT>::ELFFile(MemoryBuffer *Object, error_code &ec)
618 SectionHeaderTable(nullptr),
619 dot_shstrtab_sec(nullptr),
620 dot_strtab_sec(nullptr),
621 dot_symtab_sec(nullptr),
622 SymbolTableSectionHeaderIndex(nullptr),
623 dot_gnu_version_sec(nullptr),
624 dot_gnu_version_r_sec(nullptr),
625 dot_gnu_version_d_sec(nullptr),
627 const uint64_t FileSize = Buf->getBufferSize();
629 if (sizeof(Elf_Ehdr) > FileSize)
630 // FIXME: Proper error handling.
631 report_fatal_error("File too short!");
633 Header = reinterpret_cast<const Elf_Ehdr *>(base());
635 if (Header->e_shoff == 0)
638 const uint64_t SectionTableOffset = Header->e_shoff;
640 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
641 // FIXME: Proper error handling.
642 report_fatal_error("Section header table goes past end of file!");
644 // The getNumSections() call below depends on SectionHeaderTable being set.
646 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
647 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
649 if (SectionTableOffset + SectionTableSize > FileSize)
650 // FIXME: Proper error handling.
651 report_fatal_error("Section table goes past end of file!");
653 // Scan sections for special sections.
655 for (Elf_Shdr_Iter SecI = begin_sections(), SecE = end_sections();
656 SecI != SecE; ++SecI) {
657 switch (SecI->sh_type) {
658 case ELF::SHT_SYMTAB_SHNDX:
659 if (SymbolTableSectionHeaderIndex)
660 // FIXME: Proper error handling.
661 report_fatal_error("More than one .symtab_shndx!");
662 SymbolTableSectionHeaderIndex = &*SecI;
664 case ELF::SHT_SYMTAB:
666 // FIXME: Proper error handling.
667 report_fatal_error("More than one .symtab!");
668 dot_symtab_sec = &*SecI;
669 dot_strtab_sec = getSection(SecI->sh_link);
671 case ELF::SHT_DYNSYM: {
672 if (DynSymRegion.Addr)
673 // FIXME: Proper error handling.
674 report_fatal_error("More than one .dynsym!");
675 DynSymRegion.Addr = base() + SecI->sh_offset;
676 DynSymRegion.Size = SecI->sh_size;
677 DynSymRegion.EntSize = SecI->sh_entsize;
678 const Elf_Shdr *DynStr = getSection(SecI->sh_link);
679 DynStrRegion.Addr = base() + DynStr->sh_offset;
680 DynStrRegion.Size = DynStr->sh_size;
681 DynStrRegion.EntSize = DynStr->sh_entsize;
684 case ELF::SHT_DYNAMIC:
685 if (DynamicRegion.Addr)
686 // FIXME: Proper error handling.
687 report_fatal_error("More than one .dynamic!");
688 DynamicRegion.Addr = base() + SecI->sh_offset;
689 DynamicRegion.Size = SecI->sh_size;
690 DynamicRegion.EntSize = SecI->sh_entsize;
692 case ELF::SHT_GNU_versym:
693 if (dot_gnu_version_sec != nullptr)
694 // FIXME: Proper error handling.
695 report_fatal_error("More than one .gnu.version section!");
696 dot_gnu_version_sec = &*SecI;
698 case ELF::SHT_GNU_verdef:
699 if (dot_gnu_version_d_sec != nullptr)
700 // FIXME: Proper error handling.
701 report_fatal_error("More than one .gnu.version_d section!");
702 dot_gnu_version_d_sec = &*SecI;
704 case ELF::SHT_GNU_verneed:
705 if (dot_gnu_version_r_sec != nullptr)
706 // FIXME: Proper error handling.
707 report_fatal_error("More than one .gnu.version_r section!");
708 dot_gnu_version_r_sec = &*SecI;
713 // Get string table sections.
714 dot_shstrtab_sec = getSection(getStringTableIndex());
715 if (dot_shstrtab_sec) {
716 // Verify that the last byte in the string table in a null.
717 VerifyStrTab(dot_shstrtab_sec);
720 // Build symbol name side-mapping if there is one.
721 if (SymbolTableSectionHeaderIndex) {
722 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
723 SymbolTableSectionHeaderIndex->sh_offset);
724 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
726 if (*ShndxTable != ELF::SHN_UNDEF)
727 ExtendedSymbolTable[&*SI] = *ShndxTable;
732 // Scan program headers.
733 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
734 PhdrE = end_program_headers();
735 PhdrI != PhdrE; ++PhdrI) {
736 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
737 DynamicRegion.Addr = base() + PhdrI->p_offset;
738 DynamicRegion.Size = PhdrI->p_filesz;
739 DynamicRegion.EntSize = sizeof(Elf_Dyn);
744 ec = error_code::success();
747 // Get the symbol table index in the symtab section given a symbol
748 template <class ELFT>
749 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
750 uintptr_t SymLoc = uintptr_t(Sym);
751 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
752 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
753 uint64_t SymOffset = SymLoc - SymTabLoc;
754 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
755 "Symbol not multiple of symbol size!");
756 return SymOffset / dot_symtab_sec->sh_entsize;
759 template <class ELFT>
760 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
761 return Elf_Shdr_Iter(Header->e_shentsize,
762 (const char *)base() + Header->e_shoff);
765 template <class ELFT>
766 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
767 return Elf_Shdr_Iter(Header->e_shentsize,
768 (const char *)base() + Header->e_shoff +
769 (getNumSections() * Header->e_shentsize));
772 template <class ELFT>
773 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
775 return Elf_Sym_Iter(0, nullptr, false);
776 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
777 (const char *)base() + dot_symtab_sec->sh_offset, false);
780 template <class ELFT>
781 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
783 return Elf_Sym_Iter(0, nullptr, false);
784 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
785 (const char *)base() + dot_symtab_sec->sh_offset +
786 dot_symtab_sec->sh_size,
790 template <class ELFT>
791 typename ELFFile<ELFT>::Elf_Dyn_Iter
792 ELFFile<ELFT>::begin_dynamic_table() const {
793 if (DynamicRegion.Addr)
794 return Elf_Dyn_Iter(DynamicRegion.EntSize,
795 (const char *)DynamicRegion.Addr);
796 return Elf_Dyn_Iter(0, nullptr);
799 template <class ELFT>
800 typename ELFFile<ELFT>::Elf_Dyn_Iter
801 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
802 if (!DynamicRegion.Addr)
803 return Elf_Dyn_Iter(0, nullptr);
804 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
805 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
808 Elf_Dyn_Iter Start = begin_dynamic_table();
809 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
812 // Include the DT_NULL.
820 template <class ELFT>
821 StringRef ELFFile<ELFT>::getLoadName() const {
823 // Find the DT_SONAME entry
824 Elf_Dyn_Iter it = begin_dynamic_table();
825 Elf_Dyn_Iter ie = end_dynamic_table();
826 while (it != ie && it->getTag() != ELF::DT_SONAME)
830 dt_soname = getDynamicString(it->getVal());
838 template <class ELFT>
839 template <typename T>
840 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
841 return getEntry<T>(getSection(Section), Entry);
844 template <class ELFT>
845 template <typename T>
846 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
847 uint32_t Entry) const {
848 return reinterpret_cast<const T *>(base() + Section->sh_offset +
849 (Entry * Section->sh_entsize));
852 template <class ELFT>
853 const typename ELFFile<ELFT>::Elf_Shdr *
854 ELFFile<ELFT>::getSection(uint32_t index) const {
857 if (!SectionHeaderTable || index >= getNumSections())
858 // FIXME: Proper error handling.
859 report_fatal_error("Invalid section index!");
861 return reinterpret_cast<const Elf_Shdr *>(
862 reinterpret_cast<const char *>(SectionHeaderTable)
863 + (index * Header->e_shentsize));
866 template <class ELFT>
867 const char *ELFFile<ELFT>::getString(uint32_t section,
868 ELF::Elf32_Word offset) const {
869 return getString(getSection(section), offset);
872 template <class ELFT>
873 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
874 ELF::Elf32_Word offset) const {
875 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
876 if (offset >= section->sh_size)
877 // FIXME: Proper error handling.
878 report_fatal_error("Symbol name offset outside of string table!");
879 return (const char *)base() + section->sh_offset + offset;
882 template <class ELFT>
883 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
884 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
886 return (const char *)DynStrRegion.Addr + Offset;
889 template <class ELFT>
890 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
891 if (!Sym.isDynamic())
892 return getSymbolName(dot_symtab_sec, &*Sym);
894 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
895 return object_error::parse_failed;
896 return StringRef(getDynamicString(Sym->st_name));
899 template <class ELFT>
900 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
901 const Elf_Sym *Symb) const {
902 if (Symb->st_name == 0) {
903 const Elf_Shdr *ContainingSec = getSection(Symb);
905 return getSectionName(ContainingSec);
908 const Elf_Shdr *StrTab = getSection(Section->sh_link);
909 if (Symb->st_name >= StrTab->sh_size)
910 return object_error::parse_failed;
911 return StringRef(getString(StrTab, Symb->st_name));
914 template <class ELFT>
916 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
917 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
918 return object_error::parse_failed;
919 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
922 template <class ELFT>
923 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
925 bool &IsDefault) const {
926 // Handle non-dynamic symbols.
927 if (section != DynSymRegion.Addr && section != nullptr) {
928 // Non-dynamic symbols can have versions in their names
929 // A name of the form 'foo@V1' indicates version 'V1', non-default.
930 // A name of the form 'foo@@V2' indicates version 'V2', default version.
931 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
934 StringRef Name = *SymName;
935 size_t atpos = Name.find('@');
936 if (atpos == StringRef::npos) {
938 return StringRef("");
941 if (atpos < Name.size() && Name[atpos] == '@') {
947 return Name.substr(atpos);
950 // This is a dynamic symbol. Look in the GNU symbol version table.
951 if (!dot_gnu_version_sec) {
954 return StringRef("");
957 // Determine the position in the symbol table of this entry.
958 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
959 DynSymRegion.EntSize;
961 // Get the corresponding version index entry
962 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
963 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
965 // Special markers for unversioned symbols.
966 if (version_index == ELF::VER_NDX_LOCAL ||
967 version_index == ELF::VER_NDX_GLOBAL) {
969 return StringRef("");
972 // Lookup this symbol in the version table
974 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
975 return object_error::parse_failed;
976 const VersionMapEntry &entry = VersionMap[version_index];
978 // Get the version name string
980 if (entry.isVerdef()) {
981 // The first Verdaux entry holds the name.
982 name_offset = entry.getVerdef()->getAux()->vda_name;
984 name_offset = entry.getVernaux()->vna_name;
988 if (entry.isVerdef()) {
989 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
994 if (name_offset >= DynStrRegion.Size)
995 return object_error::parse_failed;
996 return StringRef(getDynamicString(name_offset));
999 /// This function returns the hash value for a symbol in the .dynsym section
1000 /// Name of the API remains consistent as specified in the libelf
1001 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1002 static inline unsigned elf_hash(StringRef &symbolName) {
1004 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1005 h = (h << 4) + symbolName[i];
1006 g = h & 0xf0000000L;
1013 } // end namespace object
1014 } // end namespace llvm