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,(uint8_t)ELF::ELFDATANONE);
46 return std::make_pair((uint8_t)Object.begin()[ELF::EI_CLASS],
47 (uint8_t)Object.begin()[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 iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
137 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
138 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
139 typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
140 typedef iterator_range<Elf_Shdr_Iter> Elf_Shdr_Range;
142 /// \brief Archive files are 2 byte aligned, so we need this for
143 /// PointerIntPair to work.
144 template <typename T>
145 class ArchivePointerTypeTraits {
147 static inline const void *getAsVoidPointer(T *P) { return P; }
148 static inline T *getFromVoidPointer(const void *P) {
149 return static_cast<T *>(P);
151 enum { NumLowBitsAvailable = 1 };
156 typedef ptrdiff_t difference_type;
157 typedef const Elf_Sym value_type;
158 typedef std::random_access_iterator_tag iterator_category;
159 typedef value_type &reference;
160 typedef value_type *pointer;
162 /// \brief Default construct iterator.
163 Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
164 Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
165 : EntitySize(EntSize), Current(Start, IsDynamic) {}
167 reference operator*() {
168 assert(Current.getPointer() &&
169 "Attempted to dereference an invalid iterator!");
170 return *reinterpret_cast<pointer>(Current.getPointer());
173 pointer operator->() {
174 assert(Current.getPointer() &&
175 "Attempted to dereference an invalid iterator!");
176 return reinterpret_cast<pointer>(Current.getPointer());
179 bool operator==(const Elf_Sym_Iter &Other) {
180 return Current == Other.Current;
183 bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
185 Elf_Sym_Iter &operator++() {
186 assert(Current.getPointer() &&
187 "Attempted to increment an invalid iterator!");
188 Current.setPointer(Current.getPointer() + EntitySize);
192 Elf_Sym_Iter operator++(int) {
193 Elf_Sym_Iter Tmp = *this;
198 Elf_Sym_Iter operator+(difference_type Dist) {
199 assert(Current.getPointer() &&
200 "Attempted to increment an invalid iterator!");
201 Current.setPointer(Current.getPointer() + EntitySize * Dist);
205 Elf_Sym_Iter &operator=(const Elf_Sym_Iter &Other) {
206 EntitySize = Other.EntitySize;
207 Current = Other.Current;
211 difference_type operator-(const Elf_Sym_Iter &Other) const {
212 assert(EntitySize == Other.EntitySize &&
213 "Subtracting iterators of different EntitySize!");
214 return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
217 const char *get() const { return Current.getPointer(); }
219 bool isDynamic() const { return Current.getInt(); }
221 uintX_t getEntSize() const { return EntitySize; }
225 PointerIntPair<const char *, 1, bool,
226 ArchivePointerTypeTraits<const char> > Current;
230 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
231 typedef DenseMap<unsigned, unsigned> IndexMap_t;
235 const uint8_t *base() const {
236 return reinterpret_cast<const uint8_t *>(Buf.begin());
239 const Elf_Ehdr *Header;
240 const Elf_Shdr *SectionHeaderTable;
241 const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
242 const Elf_Shdr *dot_strtab_sec; // Symbol header string table.
243 const Elf_Shdr *dot_symtab_sec; // Symbol table section.
245 const Elf_Shdr *SymbolTableSectionHeaderIndex;
246 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
248 const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
249 const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
250 const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
252 /// \brief Represents a region described by entries in the .dynamic table.
253 struct DynRegionInfo {
254 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
255 /// \brief Address in current address space.
257 /// \brief Size in bytes of the region.
259 /// \brief Size of each entity in the region.
263 DynRegionInfo DynamicRegion;
264 DynRegionInfo DynHashRegion;
265 DynRegionInfo DynStrRegion;
266 DynRegionInfo DynSymRegion;
268 // Pointer to SONAME entry in dynamic string table
269 // This is set the first time getLoadName is called.
270 mutable const char *dt_soname;
272 // Records for each version index the corresponding Verdef or Vernaux entry.
273 // This is filled the first time LoadVersionMap() is called.
274 class VersionMapEntry : public PointerIntPair<const void*, 1> {
276 // If the integer is 0, this is an Elf_Verdef*.
277 // If the integer is 1, this is an Elf_Vernaux*.
278 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
279 VersionMapEntry(const Elf_Verdef *verdef)
280 : PointerIntPair<const void*, 1>(verdef, 0) { }
281 VersionMapEntry(const Elf_Vernaux *vernaux)
282 : PointerIntPair<const void*, 1>(vernaux, 1) { }
283 bool isNull() const { return getPointer() == nullptr; }
284 bool isVerdef() const { return !isNull() && getInt() == 0; }
285 bool isVernaux() const { return !isNull() && getInt() == 1; }
286 const Elf_Verdef *getVerdef() const {
287 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
289 const Elf_Vernaux *getVernaux() const {
290 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
293 mutable SmallVector<VersionMapEntry, 16> VersionMap;
294 void LoadVersionDefs(const Elf_Shdr *sec) const;
295 void LoadVersionNeeds(const Elf_Shdr *ec) const;
296 void LoadVersionMap() const;
300 const T *getEntry(uint32_t Section, uint32_t Entry) const;
301 template <typename T>
302 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
303 const char *getString(uint32_t section, uint32_t offset) const;
304 const char *getString(const Elf_Shdr *section, uint32_t offset) const;
305 const char *getDynamicString(uintX_t Offset) const;
306 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
308 bool &IsDefault) const;
309 void VerifyStrTab(const Elf_Shdr *sh) const;
311 StringRef getRelocationTypeName(uint32_t Type) const;
312 void getRelocationTypeName(uint32_t Type,
313 SmallVectorImpl<char> &Result) const;
315 /// \brief Get the symbol table section and symbol for a given relocation.
316 template <class RelT>
317 std::pair<const Elf_Shdr *, const Elf_Sym *>
318 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
320 ELFFile(StringRef Object, std::error_code &ec);
322 bool isMipsELF64() const {
323 return Header->e_machine == ELF::EM_MIPS &&
324 Header->getFileClass() == ELF::ELFCLASS64;
327 bool isMips64EL() const {
328 return Header->e_machine == ELF::EM_MIPS &&
329 Header->getFileClass() == ELF::ELFCLASS64 &&
330 Header->getDataEncoding() == ELF::ELFDATA2LSB;
333 Elf_Shdr_Iter begin_sections() const;
334 Elf_Shdr_Iter end_sections() const;
335 Elf_Shdr_Range sections() const {
336 return make_range(begin_sections(), end_sections());
339 Elf_Sym_Iter begin_symbols() const;
340 Elf_Sym_Iter end_symbols() const;
342 Elf_Dyn_Iter begin_dynamic_table() const;
343 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
344 /// the section size.
345 Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
346 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
347 return make_range(begin_dynamic_table(), end_dynamic_table(NULLEnd));
350 Elf_Sym_Iter begin_dynamic_symbols() const {
351 if (DynSymRegion.Addr)
352 return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
354 return Elf_Sym_Iter(0, nullptr, true);
357 Elf_Sym_Iter end_dynamic_symbols() const {
358 if (DynSymRegion.Addr)
359 return Elf_Sym_Iter(DynSymRegion.EntSize,
360 (const char *)DynSymRegion.Addr + DynSymRegion.Size,
362 return Elf_Sym_Iter(0, nullptr, true);
365 Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
366 return Elf_Rela_Iter(sec->sh_entsize,
367 (const char *)(base() + sec->sh_offset));
370 Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
371 return Elf_Rela_Iter(
373 (const char *)(base() + sec->sh_offset + sec->sh_size));
376 Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
377 return Elf_Rel_Iter(sec->sh_entsize,
378 (const char *)(base() + sec->sh_offset));
381 Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
382 return Elf_Rel_Iter(sec->sh_entsize,
383 (const char *)(base() + sec->sh_offset + sec->sh_size));
386 /// \brief Iterate over program header table.
387 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
389 Elf_Phdr_Iter begin_program_headers() const {
390 return Elf_Phdr_Iter(Header->e_phentsize,
391 (const char*)base() + Header->e_phoff);
394 Elf_Phdr_Iter end_program_headers() const {
395 return Elf_Phdr_Iter(Header->e_phentsize,
396 (const char*)base() +
398 (Header->e_phnum * Header->e_phentsize));
401 uint64_t getNumSections() const;
402 uintX_t getStringTableIndex() const;
403 ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
404 const Elf_Ehdr *getHeader() const { return Header; }
405 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
406 const Elf_Shdr *getSection(uint32_t Index) const;
407 const Elf_Sym *getSymbol(uint32_t index) const;
409 ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
411 /// \brief Get the name of \p Symb.
412 /// \param SymTab The symbol table section \p Symb is contained in.
413 /// \param Symb The symbol to get the name of.
415 /// \p SymTab is used to lookup the string table to use to get the symbol's
417 ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
418 const Elf_Sym *Symb) const;
419 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
420 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
421 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
422 StringRef getLoadName() const;
425 // Use an alignment of 2 for the typedefs since that is the worst case for
426 // ELF files in archives.
427 typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
428 typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
429 typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
430 typedef ELFFile<ELFType<support::big, 2, true> > ELF64BEFile;
432 // Iterate through the version definitions, and place each Elf_Verdef
433 // in the VersionMap according to its index.
434 template <class ELFT>
435 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
436 unsigned vd_size = sec->sh_size; // Size of section in bytes
437 unsigned vd_count = sec->sh_info; // Number of Verdef entries
438 const char *sec_start = (const char*)base() + sec->sh_offset;
439 const char *sec_end = sec_start + vd_size;
440 // The first Verdef entry is at the start of the section.
441 const char *p = sec_start;
442 for (unsigned i = 0; i < vd_count; i++) {
443 if (p + sizeof(Elf_Verdef) > sec_end)
444 report_fatal_error("Section ended unexpectedly while scanning "
445 "version definitions.");
446 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
447 if (vd->vd_version != ELF::VER_DEF_CURRENT)
448 report_fatal_error("Unexpected verdef version");
449 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
450 if (index >= VersionMap.size())
451 VersionMap.resize(index + 1);
452 VersionMap[index] = VersionMapEntry(vd);
457 // Iterate through the versions needed section, and place each Elf_Vernaux
458 // in the VersionMap according to its index.
459 template <class ELFT>
460 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
461 unsigned vn_size = sec->sh_size; // Size of section in bytes
462 unsigned vn_count = sec->sh_info; // Number of Verneed entries
463 const char *sec_start = (const char *)base() + sec->sh_offset;
464 const char *sec_end = sec_start + vn_size;
465 // The first Verneed entry is at the start of the section.
466 const char *p = sec_start;
467 for (unsigned i = 0; i < vn_count; i++) {
468 if (p + sizeof(Elf_Verneed) > sec_end)
469 report_fatal_error("Section ended unexpectedly while scanning "
470 "version needed records.");
471 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
472 if (vn->vn_version != ELF::VER_NEED_CURRENT)
473 report_fatal_error("Unexpected verneed version");
474 // Iterate through the Vernaux entries
475 const char *paux = p + vn->vn_aux;
476 for (unsigned j = 0; j < vn->vn_cnt; j++) {
477 if (paux + sizeof(Elf_Vernaux) > sec_end)
478 report_fatal_error("Section ended unexpected while scanning auxiliary "
479 "version needed records.");
480 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
481 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
482 if (index >= VersionMap.size())
483 VersionMap.resize(index + 1);
484 VersionMap[index] = VersionMapEntry(vna);
485 paux += vna->vna_next;
491 template <class ELFT>
492 void ELFFile<ELFT>::LoadVersionMap() const {
493 // If there is no dynamic symtab or version table, there is nothing to do.
494 if (!DynSymRegion.Addr || !dot_gnu_version_sec)
497 // Has the VersionMap already been loaded?
498 if (VersionMap.size() > 0)
501 // The first two version indexes are reserved.
502 // Index 0 is LOCAL, index 1 is GLOBAL.
503 VersionMap.push_back(VersionMapEntry());
504 VersionMap.push_back(VersionMapEntry());
506 if (dot_gnu_version_d_sec)
507 LoadVersionDefs(dot_gnu_version_d_sec);
509 if (dot_gnu_version_r_sec)
510 LoadVersionNeeds(dot_gnu_version_r_sec);
513 template <class ELFT>
514 ELF::Elf64_Word ELFFile<ELFT>::getSymbolTableIndex(const Elf_Sym *symb) const {
515 if (symb->st_shndx == ELF::SHN_XINDEX)
516 return ExtendedSymbolTable.lookup(symb);
517 return symb->st_shndx;
520 template <class ELFT>
521 const typename ELFFile<ELFT>::Elf_Shdr *
522 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
523 if (symb->st_shndx == ELF::SHN_XINDEX)
524 return getSection(ExtendedSymbolTable.lookup(symb));
525 if (symb->st_shndx >= ELF::SHN_LORESERVE)
527 return getSection(symb->st_shndx);
530 template <class ELFT>
531 const typename ELFFile<ELFT>::Elf_Sym *
532 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
533 return &*(begin_symbols() + Index);
536 template <class ELFT>
537 ErrorOr<ArrayRef<uint8_t> >
538 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
539 if (Sec->sh_offset + Sec->sh_size > Buf.size())
540 return object_error::parse_failed;
541 const uint8_t *Start = base() + Sec->sh_offset;
542 return ArrayRef<uint8_t>(Start, Sec->sh_size);
545 template <class ELFT>
546 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
547 return getELFRelocationTypeName(Header->e_machine, Type);
550 template <class ELFT>
551 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
552 SmallVectorImpl<char> &Result) const {
553 if (!isMipsELF64()) {
554 StringRef Name = getRelocationTypeName(Type);
555 Result.append(Name.begin(), Name.end());
557 // The Mips N64 ABI allows up to three operations to be specified per
558 // relocation record. Unfortunately there's no easy way to test for the
559 // presence of N64 ELFs as they have no special flag that identifies them
560 // as being N64. We can safely assume at the moment that all Mips
561 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
562 // information to disambiguate between old vs new ABIs.
563 uint8_t Type1 = (Type >> 0) & 0xFF;
564 uint8_t Type2 = (Type >> 8) & 0xFF;
565 uint8_t Type3 = (Type >> 16) & 0xFF;
567 // Concat all three relocation type names.
568 StringRef Name = getRelocationTypeName(Type1);
569 Result.append(Name.begin(), Name.end());
571 Name = getRelocationTypeName(Type2);
572 Result.append(1, '/');
573 Result.append(Name.begin(), Name.end());
575 Name = getRelocationTypeName(Type3);
576 Result.append(1, '/');
577 Result.append(Name.begin(), Name.end());
581 template <class ELFT>
582 template <class RelT>
583 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
584 const typename ELFFile<ELFT>::Elf_Sym *>
585 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
587 return std::make_pair(nullptr, nullptr);
588 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
589 return std::make_pair(
590 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
593 // Verify that the last byte in the string table in a null.
594 template <class ELFT>
595 void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
596 const char *strtab = (const char *)base() + sh->sh_offset;
597 if (strtab[sh->sh_size - 1] != 0)
598 // FIXME: Proper error handling.
599 report_fatal_error("String table must end with a null terminator!");
602 template <class ELFT>
603 uint64_t ELFFile<ELFT>::getNumSections() const {
604 assert(Header && "Header not initialized!");
605 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
606 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
607 return SectionHeaderTable->sh_size;
609 return Header->e_shnum;
612 template <class ELFT>
613 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
614 if (Header->e_shnum == ELF::SHN_UNDEF) {
615 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
616 return SectionHeaderTable->sh_link;
617 if (Header->e_shstrndx >= getNumSections())
620 return Header->e_shstrndx;
623 template <class ELFT>
624 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &ec)
625 : Buf(Object), SectionHeaderTable(nullptr), dot_shstrtab_sec(nullptr),
626 dot_strtab_sec(nullptr), dot_symtab_sec(nullptr),
627 SymbolTableSectionHeaderIndex(nullptr), dot_gnu_version_sec(nullptr),
628 dot_gnu_version_r_sec(nullptr), dot_gnu_version_d_sec(nullptr),
630 const uint64_t FileSize = Buf.size();
632 if (sizeof(Elf_Ehdr) > FileSize)
633 // FIXME: Proper error handling.
634 report_fatal_error("File too short!");
636 Header = reinterpret_cast<const Elf_Ehdr *>(base());
638 if (Header->e_shoff == 0)
641 const uint64_t SectionTableOffset = Header->e_shoff;
643 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
644 // FIXME: Proper error handling.
645 report_fatal_error("Section header table goes past end of file!");
647 // The getNumSections() call below depends on SectionHeaderTable being set.
649 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
650 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
652 if (SectionTableOffset + SectionTableSize > FileSize)
653 // FIXME: Proper error handling.
654 report_fatal_error("Section table goes past end of file!");
656 // Scan sections for special sections.
658 for (const Elf_Shdr &Sec : sections()) {
659 switch (Sec.sh_type) {
660 case ELF::SHT_SYMTAB_SHNDX:
661 if (SymbolTableSectionHeaderIndex)
662 // FIXME: Proper error handling.
663 report_fatal_error("More than one .symtab_shndx!");
664 SymbolTableSectionHeaderIndex = &Sec;
666 case ELF::SHT_SYMTAB:
668 // FIXME: Proper error handling.
669 report_fatal_error("More than one .symtab!");
670 dot_symtab_sec = &Sec;
671 dot_strtab_sec = getSection(Sec.sh_link);
673 case ELF::SHT_DYNSYM: {
674 if (DynSymRegion.Addr)
675 // FIXME: Proper error handling.
676 report_fatal_error("More than one .dynsym!");
677 DynSymRegion.Addr = base() + Sec.sh_offset;
678 DynSymRegion.Size = Sec.sh_size;
679 DynSymRegion.EntSize = Sec.sh_entsize;
680 const Elf_Shdr *DynStr = getSection(Sec.sh_link);
681 DynStrRegion.Addr = base() + DynStr->sh_offset;
682 DynStrRegion.Size = DynStr->sh_size;
683 DynStrRegion.EntSize = DynStr->sh_entsize;
686 case ELF::SHT_DYNAMIC:
687 if (DynamicRegion.Addr)
688 // FIXME: Proper error handling.
689 report_fatal_error("More than one .dynamic!");
690 DynamicRegion.Addr = base() + Sec.sh_offset;
691 DynamicRegion.Size = Sec.sh_size;
692 DynamicRegion.EntSize = Sec.sh_entsize;
694 case ELF::SHT_GNU_versym:
695 if (dot_gnu_version_sec != nullptr)
696 // FIXME: Proper error handling.
697 report_fatal_error("More than one .gnu.version section!");
698 dot_gnu_version_sec = &Sec;
700 case ELF::SHT_GNU_verdef:
701 if (dot_gnu_version_d_sec != nullptr)
702 // FIXME: Proper error handling.
703 report_fatal_error("More than one .gnu.version_d section!");
704 dot_gnu_version_d_sec = &Sec;
706 case ELF::SHT_GNU_verneed:
707 if (dot_gnu_version_r_sec != nullptr)
708 // FIXME: Proper error handling.
709 report_fatal_error("More than one .gnu.version_r section!");
710 dot_gnu_version_r_sec = &Sec;
715 // Get string table sections.
716 dot_shstrtab_sec = getSection(getStringTableIndex());
717 if (dot_shstrtab_sec) {
718 // Verify that the last byte in the string table in a null.
719 VerifyStrTab(dot_shstrtab_sec);
722 // Build symbol name side-mapping if there is one.
723 if (SymbolTableSectionHeaderIndex) {
724 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
725 SymbolTableSectionHeaderIndex->sh_offset);
726 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
728 if (*ShndxTable != ELF::SHN_UNDEF)
729 ExtendedSymbolTable[&*SI] = *ShndxTable;
734 // Scan program headers.
735 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
736 PhdrE = end_program_headers();
737 PhdrI != PhdrE; ++PhdrI) {
738 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
739 DynamicRegion.Addr = base() + PhdrI->p_offset;
740 DynamicRegion.Size = PhdrI->p_filesz;
741 DynamicRegion.EntSize = sizeof(Elf_Dyn);
746 ec = std::error_code();
749 // Get the symbol table index in the symtab section given a symbol
750 template <class ELFT>
751 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
752 uintptr_t SymLoc = uintptr_t(Sym);
753 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
754 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
755 uint64_t SymOffset = SymLoc - SymTabLoc;
756 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
757 "Symbol not multiple of symbol size!");
758 return SymOffset / dot_symtab_sec->sh_entsize;
761 template <class ELFT>
762 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
763 return Elf_Shdr_Iter(Header->e_shentsize,
764 (const char *)base() + Header->e_shoff);
767 template <class ELFT>
768 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
769 return Elf_Shdr_Iter(Header->e_shentsize,
770 (const char *)base() + Header->e_shoff +
771 (getNumSections() * Header->e_shentsize));
774 template <class ELFT>
775 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
777 return Elf_Sym_Iter(0, nullptr, false);
778 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
779 (const char *)base() + dot_symtab_sec->sh_offset, false);
782 template <class ELFT>
783 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
785 return Elf_Sym_Iter(0, nullptr, false);
786 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
787 (const char *)base() + dot_symtab_sec->sh_offset +
788 dot_symtab_sec->sh_size,
792 template <class ELFT>
793 typename ELFFile<ELFT>::Elf_Dyn_Iter
794 ELFFile<ELFT>::begin_dynamic_table() const {
795 if (DynamicRegion.Addr)
796 return Elf_Dyn_Iter(DynamicRegion.EntSize,
797 (const char *)DynamicRegion.Addr);
798 return Elf_Dyn_Iter(0, nullptr);
801 template <class ELFT>
802 typename ELFFile<ELFT>::Elf_Dyn_Iter
803 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
804 if (!DynamicRegion.Addr)
805 return Elf_Dyn_Iter(0, nullptr);
806 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
807 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
810 Elf_Dyn_Iter Start = begin_dynamic_table();
811 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
814 // Include the DT_NULL.
822 template <class ELFT>
823 StringRef ELFFile<ELFT>::getLoadName() const {
826 // Find the DT_SONAME entry
827 for (const auto &Entry : dynamic_table())
828 if (Entry.getTag() == ELF::DT_SONAME) {
829 dt_soname = getDynamicString(Entry.getVal());
836 template <class ELFT>
837 template <typename T>
838 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
839 return getEntry<T>(getSection(Section), Entry);
842 template <class ELFT>
843 template <typename T>
844 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
845 uint32_t Entry) const {
846 return reinterpret_cast<const T *>(base() + Section->sh_offset +
847 (Entry * Section->sh_entsize));
850 template <class ELFT>
851 const typename ELFFile<ELFT>::Elf_Shdr *
852 ELFFile<ELFT>::getSection(uint32_t index) const {
855 if (!SectionHeaderTable || index >= getNumSections())
856 // FIXME: Proper error handling.
857 report_fatal_error("Invalid section index!");
859 return reinterpret_cast<const Elf_Shdr *>(
860 reinterpret_cast<const char *>(SectionHeaderTable)
861 + (index * Header->e_shentsize));
864 template <class ELFT>
865 const char *ELFFile<ELFT>::getString(uint32_t section,
866 ELF::Elf32_Word offset) const {
867 return getString(getSection(section), offset);
870 template <class ELFT>
871 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
872 ELF::Elf32_Word offset) const {
873 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
874 if (offset >= section->sh_size)
875 // FIXME: Proper error handling.
876 report_fatal_error("Symbol name offset outside of string table!");
877 return (const char *)base() + section->sh_offset + offset;
880 template <class ELFT>
881 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
882 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
884 return (const char *)DynStrRegion.Addr + Offset;
887 template <class ELFT>
888 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
889 if (!Sym.isDynamic())
890 return getSymbolName(dot_symtab_sec, &*Sym);
892 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
893 return object_error::parse_failed;
894 return StringRef(getDynamicString(Sym->st_name));
897 template <class ELFT>
898 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
899 const Elf_Sym *Symb) const {
900 if (Symb->st_name == 0) {
901 const Elf_Shdr *ContainingSec = getSection(Symb);
903 return getSectionName(ContainingSec);
906 const Elf_Shdr *StrTab = getSection(Section->sh_link);
907 if (Symb->st_name >= StrTab->sh_size)
908 return object_error::parse_failed;
909 return StringRef(getString(StrTab, Symb->st_name));
912 template <class ELFT>
914 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
915 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
916 return object_error::parse_failed;
917 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
920 template <class ELFT>
921 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
923 bool &IsDefault) const {
924 // Handle non-dynamic symbols.
925 if (section != DynSymRegion.Addr && section != nullptr) {
926 // Non-dynamic symbols can have versions in their names
927 // A name of the form 'foo@V1' indicates version 'V1', non-default.
928 // A name of the form 'foo@@V2' indicates version 'V2', default version.
929 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
932 StringRef Name = *SymName;
933 size_t atpos = Name.find('@');
934 if (atpos == StringRef::npos) {
936 return StringRef("");
939 if (atpos < Name.size() && Name[atpos] == '@') {
945 return Name.substr(atpos);
948 // This is a dynamic symbol. Look in the GNU symbol version table.
949 if (!dot_gnu_version_sec) {
952 return StringRef("");
955 // Determine the position in the symbol table of this entry.
956 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
957 DynSymRegion.EntSize;
959 // Get the corresponding version index entry
960 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
961 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
963 // Special markers for unversioned symbols.
964 if (version_index == ELF::VER_NDX_LOCAL ||
965 version_index == ELF::VER_NDX_GLOBAL) {
967 return StringRef("");
970 // Lookup this symbol in the version table
972 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
973 return object_error::parse_failed;
974 const VersionMapEntry &entry = VersionMap[version_index];
976 // Get the version name string
978 if (entry.isVerdef()) {
979 // The first Verdaux entry holds the name.
980 name_offset = entry.getVerdef()->getAux()->vda_name;
982 name_offset = entry.getVernaux()->vna_name;
986 if (entry.isVerdef()) {
987 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
992 if (name_offset >= DynStrRegion.Size)
993 return object_error::parse_failed;
994 return StringRef(getDynamicString(name_offset));
997 /// This function returns the hash value for a symbol in the .dynsym section
998 /// Name of the API remains consistent as specified in the libelf
999 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1000 static inline unsigned elf_hash(StringRef &symbolName) {
1002 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1003 h = (h << 4) + symbolName[i];
1004 g = h & 0xf0000000L;
1011 } // end namespace object
1012 } // end namespace llvm