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 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->getBufferStart());
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(MemoryBuffer *Object, 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->getBufferSize())
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) {
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(MemoryBuffer *Object, error_code &ec)
626 SectionHeaderTable(nullptr),
627 dot_shstrtab_sec(nullptr),
628 dot_strtab_sec(nullptr),
629 dot_symtab_sec(nullptr),
630 SymbolTableSectionHeaderIndex(nullptr),
631 dot_gnu_version_sec(nullptr),
632 dot_gnu_version_r_sec(nullptr),
633 dot_gnu_version_d_sec(nullptr),
635 const uint64_t FileSize = Buf->getBufferSize();
637 if (sizeof(Elf_Ehdr) > FileSize)
638 // FIXME: Proper error handling.
639 report_fatal_error("File too short!");
641 Header = reinterpret_cast<const Elf_Ehdr *>(base());
643 if (Header->e_shoff == 0)
646 const uint64_t SectionTableOffset = Header->e_shoff;
648 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
649 // FIXME: Proper error handling.
650 report_fatal_error("Section header table goes past end of file!");
652 // The getNumSections() call below depends on SectionHeaderTable being set.
654 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
655 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
657 if (SectionTableOffset + SectionTableSize > FileSize)
658 // FIXME: Proper error handling.
659 report_fatal_error("Section table goes past end of file!");
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 // FIXME: Proper error handling.
668 report_fatal_error("More than one .symtab_shndx!");
669 SymbolTableSectionHeaderIndex = &Sec;
671 case ELF::SHT_SYMTAB:
673 // FIXME: Proper error handling.
674 report_fatal_error("More than one .symtab!");
675 dot_symtab_sec = &Sec;
676 dot_strtab_sec = getSection(Sec.sh_link);
678 case ELF::SHT_DYNSYM: {
679 if (DynSymRegion.Addr)
680 // FIXME: Proper error handling.
681 report_fatal_error("More than one .dynsym!");
682 DynSymRegion.Addr = base() + Sec.sh_offset;
683 DynSymRegion.Size = Sec.sh_size;
684 DynSymRegion.EntSize = Sec.sh_entsize;
685 const Elf_Shdr *DynStr = getSection(Sec.sh_link);
686 DynStrRegion.Addr = base() + DynStr->sh_offset;
687 DynStrRegion.Size = DynStr->sh_size;
688 DynStrRegion.EntSize = DynStr->sh_entsize;
691 case ELF::SHT_DYNAMIC:
692 if (DynamicRegion.Addr)
693 // FIXME: Proper error handling.
694 report_fatal_error("More than one .dynamic!");
695 DynamicRegion.Addr = base() + Sec.sh_offset;
696 DynamicRegion.Size = Sec.sh_size;
697 DynamicRegion.EntSize = Sec.sh_entsize;
699 case ELF::SHT_GNU_versym:
700 if (dot_gnu_version_sec != nullptr)
701 // FIXME: Proper error handling.
702 report_fatal_error("More than one .gnu.version section!");
703 dot_gnu_version_sec = &Sec;
705 case ELF::SHT_GNU_verdef:
706 if (dot_gnu_version_d_sec != nullptr)
707 // FIXME: Proper error handling.
708 report_fatal_error("More than one .gnu.version_d section!");
709 dot_gnu_version_d_sec = &Sec;
711 case ELF::SHT_GNU_verneed:
712 if (dot_gnu_version_r_sec != nullptr)
713 // FIXME: Proper error handling.
714 report_fatal_error("More than one .gnu.version_r section!");
715 dot_gnu_version_r_sec = &Sec;
720 // Get string table sections.
721 dot_shstrtab_sec = getSection(getStringTableIndex());
722 if (dot_shstrtab_sec) {
723 // Verify that the last byte in the string table in a null.
724 VerifyStrTab(dot_shstrtab_sec);
727 // Build symbol name side-mapping if there is one.
728 if (SymbolTableSectionHeaderIndex) {
729 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
730 SymbolTableSectionHeaderIndex->sh_offset);
731 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
733 if (*ShndxTable != ELF::SHN_UNDEF)
734 ExtendedSymbolTable[&*SI] = *ShndxTable;
739 // Scan program headers.
740 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
741 PhdrE = end_program_headers();
742 PhdrI != PhdrE; ++PhdrI) {
743 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
744 DynamicRegion.Addr = base() + PhdrI->p_offset;
745 DynamicRegion.Size = PhdrI->p_filesz;
746 DynamicRegion.EntSize = sizeof(Elf_Dyn);
754 // Get the symbol table index in the symtab section given a symbol
755 template <class ELFT>
756 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
757 uintptr_t SymLoc = uintptr_t(Sym);
758 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
759 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
760 uint64_t SymOffset = SymLoc - SymTabLoc;
761 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
762 "Symbol not multiple of symbol size!");
763 return SymOffset / dot_symtab_sec->sh_entsize;
766 template <class ELFT>
767 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
768 return Elf_Shdr_Iter(Header->e_shentsize,
769 (const char *)base() + Header->e_shoff);
772 template <class ELFT>
773 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
774 return Elf_Shdr_Iter(Header->e_shentsize,
775 (const char *)base() + Header->e_shoff +
776 (getNumSections() * Header->e_shentsize));
779 template <class ELFT>
780 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
782 return Elf_Sym_Iter(0, nullptr, false);
783 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
784 (const char *)base() + dot_symtab_sec->sh_offset, false);
787 template <class ELFT>
788 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
790 return Elf_Sym_Iter(0, nullptr, false);
791 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
792 (const char *)base() + dot_symtab_sec->sh_offset +
793 dot_symtab_sec->sh_size,
797 template <class ELFT>
798 typename ELFFile<ELFT>::Elf_Dyn_Iter
799 ELFFile<ELFT>::begin_dynamic_table() const {
800 if (DynamicRegion.Addr)
801 return Elf_Dyn_Iter(DynamicRegion.EntSize,
802 (const char *)DynamicRegion.Addr);
803 return Elf_Dyn_Iter(0, nullptr);
806 template <class ELFT>
807 typename ELFFile<ELFT>::Elf_Dyn_Iter
808 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
809 if (!DynamicRegion.Addr)
810 return Elf_Dyn_Iter(0, nullptr);
811 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
812 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
815 Elf_Dyn_Iter Start = begin_dynamic_table();
816 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
819 // Include the DT_NULL.
827 template <class ELFT>
828 StringRef ELFFile<ELFT>::getLoadName() const {
831 // Find the DT_SONAME entry
832 for (const auto &Entry : dynamic_table())
833 if (Entry.getTag() == ELF::DT_SONAME) {
834 dt_soname = getDynamicString(Entry.getVal());
841 template <class ELFT>
842 template <typename T>
843 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
844 return getEntry<T>(getSection(Section), Entry);
847 template <class ELFT>
848 template <typename T>
849 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
850 uint32_t Entry) const {
851 return reinterpret_cast<const T *>(base() + Section->sh_offset +
852 (Entry * Section->sh_entsize));
855 template <class ELFT>
856 const typename ELFFile<ELFT>::Elf_Shdr *
857 ELFFile<ELFT>::getSection(uint32_t index) const {
860 if (!SectionHeaderTable || index >= getNumSections())
861 // FIXME: Proper error handling.
862 report_fatal_error("Invalid section index!");
864 return reinterpret_cast<const Elf_Shdr *>(
865 reinterpret_cast<const char *>(SectionHeaderTable)
866 + (index * Header->e_shentsize));
869 template <class ELFT>
870 const char *ELFFile<ELFT>::getString(uint32_t section,
871 ELF::Elf32_Word offset) const {
872 return getString(getSection(section), offset);
875 template <class ELFT>
876 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
877 ELF::Elf32_Word offset) const {
878 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
879 if (offset >= section->sh_size)
880 // FIXME: Proper error handling.
881 report_fatal_error("Symbol name offset outside of string table!");
882 return (const char *)base() + section->sh_offset + offset;
885 template <class ELFT>
886 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
887 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
889 return (const char *)DynStrRegion.Addr + Offset;
892 template <class ELFT>
893 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
894 if (!Sym.isDynamic())
895 return getSymbolName(dot_symtab_sec, &*Sym);
897 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
898 return object_error::parse_failed;
899 return StringRef(getDynamicString(Sym->st_name));
902 template <class ELFT>
903 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
904 const Elf_Sym *Symb) const {
905 if (Symb->st_name == 0) {
906 const Elf_Shdr *ContainingSec = getSection(Symb);
908 return getSectionName(ContainingSec);
911 const Elf_Shdr *StrTab = getSection(Section->sh_link);
912 if (Symb->st_name >= StrTab->sh_size)
913 return object_error::parse_failed;
914 return StringRef(getString(StrTab, Symb->st_name));
917 template <class ELFT>
919 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
920 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
921 return object_error::parse_failed;
922 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
925 template <class ELFT>
926 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
928 bool &IsDefault) const {
929 // Handle non-dynamic symbols.
930 if (section != DynSymRegion.Addr && section != nullptr) {
931 // Non-dynamic symbols can have versions in their names
932 // A name of the form 'foo@V1' indicates version 'V1', non-default.
933 // A name of the form 'foo@@V2' indicates version 'V2', default version.
934 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
937 StringRef Name = *SymName;
938 size_t atpos = Name.find('@');
939 if (atpos == StringRef::npos) {
941 return StringRef("");
944 if (atpos < Name.size() && Name[atpos] == '@') {
950 return Name.substr(atpos);
953 // This is a dynamic symbol. Look in the GNU symbol version table.
954 if (!dot_gnu_version_sec) {
957 return StringRef("");
960 // Determine the position in the symbol table of this entry.
961 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
962 DynSymRegion.EntSize;
964 // Get the corresponding version index entry
965 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
966 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
968 // Special markers for unversioned symbols.
969 if (version_index == ELF::VER_NDX_LOCAL ||
970 version_index == ELF::VER_NDX_GLOBAL) {
972 return StringRef("");
975 // Lookup this symbol in the version table
977 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
978 return object_error::parse_failed;
979 const VersionMapEntry &entry = VersionMap[version_index];
981 // Get the version name string
983 if (entry.isVerdef()) {
984 // The first Verdaux entry holds the name.
985 name_offset = entry.getVerdef()->getAux()->vda_name;
987 name_offset = entry.getVernaux()->vna_name;
991 if (entry.isVerdef()) {
992 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
997 if (name_offset >= DynStrRegion.Size)
998 return object_error::parse_failed;
999 return StringRef(getDynamicString(name_offset));
1002 /// This function returns the hash value for a symbol in the .dynsym section
1003 /// Name of the API remains consistent as specified in the libelf
1004 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1005 static inline unsigned elf_hash(StringRef &symbolName) {
1007 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
1008 h = (h << 4) + symbolName[i];
1009 g = h & 0xf0000000L;
1016 } // end namespace object
1017 } // end namespace llvm