1 //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the ELFFile template class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_OBJECT_ELF_H
15 #define LLVM_OBJECT_ELF_H
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Object/ELFTypes.h"
24 #include "llvm/Object/Error.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/Endian.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
39 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
41 // Subclasses of ELFFile may need this for template instantiation
42 inline std::pair<unsigned char, unsigned char>
43 getElfArchType(StringRef Object) {
44 if (Object.size() < ELF::EI_NIDENT)
45 return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
46 (uint8_t)ELF::ELFDATANONE);
47 return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
48 (uint8_t)Object[ELF::EI_DATA]);
54 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
55 typedef typename std::conditional<ELFT::Is64Bits,
56 uint64_t, uint32_t>::type uintX_t;
58 /// \brief Iterate over constant sized entities.
60 class ELFEntityIterator {
62 typedef ptrdiff_t difference_type;
63 typedef EntT value_type;
64 typedef std::forward_iterator_tag iterator_category;
65 typedef value_type &reference;
66 typedef value_type *pointer;
68 /// \brief Default construct iterator.
69 ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
70 ELFEntityIterator(uintX_t EntSize, const char *Start)
71 : EntitySize(EntSize), Current(Start) {}
73 reference operator *() {
74 assert(Current && "Attempted to dereference an invalid iterator!");
75 return *reinterpret_cast<pointer>(Current);
78 pointer operator ->() {
79 assert(Current && "Attempted to dereference an invalid iterator!");
80 return reinterpret_cast<pointer>(Current);
83 bool operator ==(const ELFEntityIterator &Other) {
84 return Current == Other.Current;
87 bool operator !=(const ELFEntityIterator &Other) {
88 return !(*this == Other);
91 ELFEntityIterator &operator ++() {
92 assert(Current && "Attempted to increment an invalid iterator!");
93 Current += EntitySize;
97 ELFEntityIterator operator ++(int) {
98 ELFEntityIterator Tmp = *this;
103 difference_type operator -(const ELFEntityIterator &Other) const {
104 assert(EntitySize == Other.EntitySize &&
105 "Subtracting iterators of different EntitySize!");
106 return (Current - Other.Current) / EntitySize;
109 const char *get() const { return Current; }
111 uintX_t getEntSize() const { return EntitySize; }
118 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
119 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
120 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
121 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
122 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
123 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
124 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
125 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
126 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
127 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
128 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
129 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
130 typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
131 typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
132 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
133 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
134 typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
135 typedef iterator_range<Elf_Shdr_Iter> Elf_Shdr_Range;
137 /// \brief Archive files are 2 byte aligned, so we need this for
138 /// PointerIntPair to work.
139 template <typename T>
140 class ArchivePointerTypeTraits {
142 static inline const void *getAsVoidPointer(T *P) { return P; }
143 static inline T *getFromVoidPointer(const void *P) {
144 return static_cast<T *>(P);
146 enum { NumLowBitsAvailable = 1 };
151 typedef ptrdiff_t difference_type;
152 typedef const Elf_Sym value_type;
153 typedef std::random_access_iterator_tag iterator_category;
154 typedef value_type &reference;
155 typedef value_type *pointer;
157 /// \brief Default construct iterator.
158 Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
159 Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
160 : EntitySize(EntSize), Current(Start, IsDynamic) {}
162 reference operator*() {
163 assert(Current.getPointer() &&
164 "Attempted to dereference an invalid iterator!");
165 return *reinterpret_cast<pointer>(Current.getPointer());
168 pointer operator->() {
169 assert(Current.getPointer() &&
170 "Attempted to dereference an invalid iterator!");
171 return reinterpret_cast<pointer>(Current.getPointer());
174 bool operator==(const Elf_Sym_Iter &Other) {
175 return Current == Other.Current;
178 bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
180 Elf_Sym_Iter &operator++() {
181 assert(Current.getPointer() &&
182 "Attempted to increment an invalid iterator!");
183 Current.setPointer(Current.getPointer() + EntitySize);
187 Elf_Sym_Iter operator++(int) {
188 Elf_Sym_Iter Tmp = *this;
193 Elf_Sym_Iter operator+(difference_type Dist) {
194 assert(Current.getPointer() &&
195 "Attempted to increment an invalid iterator!");
196 Current.setPointer(Current.getPointer() + EntitySize * Dist);
200 difference_type operator-(const Elf_Sym_Iter &Other) const {
201 assert(EntitySize == Other.EntitySize &&
202 "Subtracting iterators of different EntitySize!");
203 return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
206 const char *get() const { return Current.getPointer(); }
208 bool isDynamic() const { return Current.getInt(); }
210 uintX_t getEntSize() const { return EntitySize; }
214 PointerIntPair<const char *, 1, bool,
215 ArchivePointerTypeTraits<const char> > Current;
219 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
220 typedef DenseMap<unsigned, unsigned> IndexMap_t;
224 const uint8_t *base() const {
225 return reinterpret_cast<const uint8_t *>(Buf.data());
228 const Elf_Ehdr *Header;
229 const Elf_Shdr *SectionHeaderTable;
230 const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
231 const Elf_Shdr *dot_strtab_sec; // Symbol header string table.
232 const Elf_Shdr *dot_symtab_sec; // Symbol table section.
234 const Elf_Shdr *SymbolTableSectionHeaderIndex;
235 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
237 const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
238 const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
239 const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
241 /// \brief Represents a region described by entries in the .dynamic table.
242 struct DynRegionInfo {
243 DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
244 /// \brief Address in current address space.
246 /// \brief Size in bytes of the region.
248 /// \brief Size of each entity in the region.
252 DynRegionInfo DynamicRegion;
253 DynRegionInfo DynHashRegion;
254 DynRegionInfo DynStrRegion;
255 DynRegionInfo DynSymRegion;
257 // Pointer to SONAME entry in dynamic string table
258 // This is set the first time getLoadName is called.
259 mutable const char *dt_soname;
261 // Records for each version index the corresponding Verdef or Vernaux entry.
262 // This is filled the first time LoadVersionMap() is called.
263 class VersionMapEntry : public PointerIntPair<const void*, 1> {
265 // If the integer is 0, this is an Elf_Verdef*.
266 // If the integer is 1, this is an Elf_Vernaux*.
267 VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
268 VersionMapEntry(const Elf_Verdef *verdef)
269 : PointerIntPair<const void*, 1>(verdef, 0) { }
270 VersionMapEntry(const Elf_Vernaux *vernaux)
271 : PointerIntPair<const void*, 1>(vernaux, 1) { }
272 bool isNull() const { return getPointer() == nullptr; }
273 bool isVerdef() const { return !isNull() && getInt() == 0; }
274 bool isVernaux() const { return !isNull() && getInt() == 1; }
275 const Elf_Verdef *getVerdef() const {
276 return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
278 const Elf_Vernaux *getVernaux() const {
279 return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
282 mutable SmallVector<VersionMapEntry, 16> VersionMap;
283 void LoadVersionDefs(const Elf_Shdr *sec) const;
284 void LoadVersionNeeds(const Elf_Shdr *ec) const;
285 void LoadVersionMap() const;
289 const T *getEntry(uint32_t Section, uint32_t Entry) const;
290 template <typename T>
291 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
292 const char *getString(uint32_t section, uint32_t offset) const;
293 const char *getString(const Elf_Shdr *section, uint32_t offset) const;
294 const char *getDynamicString(uintX_t Offset) const;
295 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
297 bool &IsDefault) const;
298 void VerifyStrTab(const Elf_Shdr *sh) const;
300 StringRef getRelocationTypeName(uint32_t Type) const;
301 void getRelocationTypeName(uint32_t Type,
302 SmallVectorImpl<char> &Result) const;
304 /// \brief Get the symbol table section and symbol for a given relocation.
305 template <class RelT>
306 std::pair<const Elf_Shdr *, const Elf_Sym *>
307 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
309 ELFFile(StringRef Object, std::error_code &ec);
311 bool isMipsELF64() const {
312 return Header->e_machine == ELF::EM_MIPS &&
313 Header->getFileClass() == ELF::ELFCLASS64;
316 bool isMips64EL() const {
317 return Header->e_machine == ELF::EM_MIPS &&
318 Header->getFileClass() == ELF::ELFCLASS64 &&
319 Header->getDataEncoding() == ELF::ELFDATA2LSB;
322 Elf_Shdr_Iter begin_sections() const;
323 Elf_Shdr_Iter end_sections() const;
324 Elf_Shdr_Range sections() const {
325 return make_range(begin_sections(), end_sections());
328 Elf_Sym_Iter begin_symbols() const;
329 Elf_Sym_Iter end_symbols() const;
331 Elf_Dyn_Iter begin_dynamic_table() const;
332 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
333 /// the section size.
334 Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
335 Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
336 return make_range(begin_dynamic_table(), end_dynamic_table(NULLEnd));
339 Elf_Sym_Iter begin_dynamic_symbols() const {
340 if (DynSymRegion.Addr)
341 return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
343 return Elf_Sym_Iter(0, nullptr, true);
346 Elf_Sym_Iter end_dynamic_symbols() const {
347 if (DynSymRegion.Addr)
348 return Elf_Sym_Iter(DynSymRegion.EntSize,
349 (const char *)DynSymRegion.Addr + DynSymRegion.Size,
351 return Elf_Sym_Iter(0, nullptr, true);
354 Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
355 return Elf_Rela_Iter(sec->sh_entsize,
356 (const char *)(base() + sec->sh_offset));
359 Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
360 return Elf_Rela_Iter(
362 (const char *)(base() + sec->sh_offset + sec->sh_size));
365 Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
366 return Elf_Rel_Iter(sec->sh_entsize,
367 (const char *)(base() + sec->sh_offset));
370 Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
371 return Elf_Rel_Iter(sec->sh_entsize,
372 (const char *)(base() + sec->sh_offset + sec->sh_size));
375 /// \brief Iterate over program header table.
376 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
378 Elf_Phdr_Iter begin_program_headers() const {
379 return Elf_Phdr_Iter(Header->e_phentsize,
380 (const char*)base() + Header->e_phoff);
383 Elf_Phdr_Iter end_program_headers() const {
384 return Elf_Phdr_Iter(Header->e_phentsize,
385 (const char*)base() +
387 (Header->e_phnum * Header->e_phentsize));
390 uint64_t getNumSections() const;
391 uintX_t getStringTableIndex() const;
392 ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
393 const Elf_Ehdr *getHeader() const { return Header; }
394 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
395 const Elf_Shdr *getSection(uint32_t Index) const;
396 const Elf_Sym *getSymbol(uint32_t index) const;
398 ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
400 /// \brief Get the name of \p Symb.
401 /// \param SymTab The symbol table section \p Symb is contained in.
402 /// \param Symb The symbol to get the name of.
404 /// \p SymTab is used to lookup the string table to use to get the symbol's
406 ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
407 const Elf_Sym *Symb) const;
408 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
409 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
410 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
411 StringRef getLoadName() const;
414 // Use an alignment of 2 for the typedefs since that is the worst case for
415 // ELF files in archives.
416 typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
417 typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
418 typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
419 typedef ELFFile<ELFType<support::big, 2, true> > ELF64BEFile;
421 // Iterate through the version definitions, and place each Elf_Verdef
422 // in the VersionMap according to its index.
423 template <class ELFT>
424 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
425 unsigned vd_size = sec->sh_size; // Size of section in bytes
426 unsigned vd_count = sec->sh_info; // Number of Verdef entries
427 const char *sec_start = (const char*)base() + sec->sh_offset;
428 const char *sec_end = sec_start + vd_size;
429 // The first Verdef entry is at the start of the section.
430 const char *p = sec_start;
431 for (unsigned i = 0; i < vd_count; i++) {
432 if (p + sizeof(Elf_Verdef) > sec_end)
433 report_fatal_error("Section ended unexpectedly while scanning "
434 "version definitions.");
435 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
436 if (vd->vd_version != ELF::VER_DEF_CURRENT)
437 report_fatal_error("Unexpected verdef version");
438 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
439 if (index >= VersionMap.size())
440 VersionMap.resize(index + 1);
441 VersionMap[index] = VersionMapEntry(vd);
446 // Iterate through the versions needed section, and place each Elf_Vernaux
447 // in the VersionMap according to its index.
448 template <class ELFT>
449 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
450 unsigned vn_size = sec->sh_size; // Size of section in bytes
451 unsigned vn_count = sec->sh_info; // Number of Verneed entries
452 const char *sec_start = (const char *)base() + sec->sh_offset;
453 const char *sec_end = sec_start + vn_size;
454 // The first Verneed entry is at the start of the section.
455 const char *p = sec_start;
456 for (unsigned i = 0; i < vn_count; i++) {
457 if (p + sizeof(Elf_Verneed) > sec_end)
458 report_fatal_error("Section ended unexpectedly while scanning "
459 "version needed records.");
460 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
461 if (vn->vn_version != ELF::VER_NEED_CURRENT)
462 report_fatal_error("Unexpected verneed version");
463 // Iterate through the Vernaux entries
464 const char *paux = p + vn->vn_aux;
465 for (unsigned j = 0; j < vn->vn_cnt; j++) {
466 if (paux + sizeof(Elf_Vernaux) > sec_end)
467 report_fatal_error("Section ended unexpected while scanning auxiliary "
468 "version needed records.");
469 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
470 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
471 if (index >= VersionMap.size())
472 VersionMap.resize(index + 1);
473 VersionMap[index] = VersionMapEntry(vna);
474 paux += vna->vna_next;
480 template <class ELFT>
481 void ELFFile<ELFT>::LoadVersionMap() const {
482 // If there is no dynamic symtab or version table, there is nothing to do.
483 if (!DynSymRegion.Addr || !dot_gnu_version_sec)
486 // Has the VersionMap already been loaded?
487 if (VersionMap.size() > 0)
490 // The first two version indexes are reserved.
491 // Index 0 is LOCAL, index 1 is GLOBAL.
492 VersionMap.push_back(VersionMapEntry());
493 VersionMap.push_back(VersionMapEntry());
495 if (dot_gnu_version_d_sec)
496 LoadVersionDefs(dot_gnu_version_d_sec);
498 if (dot_gnu_version_r_sec)
499 LoadVersionNeeds(dot_gnu_version_r_sec);
502 template <class ELFT>
503 ELF::Elf64_Word ELFFile<ELFT>::getSymbolTableIndex(const Elf_Sym *symb) const {
504 if (symb->st_shndx == ELF::SHN_XINDEX)
505 return ExtendedSymbolTable.lookup(symb);
506 return symb->st_shndx;
509 template <class ELFT>
510 const typename ELFFile<ELFT>::Elf_Shdr *
511 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
512 if (symb->st_shndx == ELF::SHN_XINDEX)
513 return getSection(ExtendedSymbolTable.lookup(symb));
514 if (symb->st_shndx >= ELF::SHN_LORESERVE)
516 return getSection(symb->st_shndx);
519 template <class ELFT>
520 const typename ELFFile<ELFT>::Elf_Sym *
521 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
522 return &*(begin_symbols() + Index);
525 template <class ELFT>
526 ErrorOr<ArrayRef<uint8_t> >
527 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
528 if (Sec->sh_offset + Sec->sh_size > Buf.size())
529 return object_error::parse_failed;
530 const uint8_t *Start = base() + Sec->sh_offset;
531 return makeArrayRef(Start, Sec->sh_size);
534 template <class ELFT>
535 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
536 return getELFRelocationTypeName(Header->e_machine, Type);
539 template <class ELFT>
540 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
541 SmallVectorImpl<char> &Result) const {
542 if (!isMipsELF64()) {
543 StringRef Name = getRelocationTypeName(Type);
544 Result.append(Name.begin(), Name.end());
546 // The Mips N64 ABI allows up to three operations to be specified per
547 // relocation record. Unfortunately there's no easy way to test for the
548 // presence of N64 ELFs as they have no special flag that identifies them
549 // as being N64. We can safely assume at the moment that all Mips
550 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
551 // information to disambiguate between old vs new ABIs.
552 uint8_t Type1 = (Type >> 0) & 0xFF;
553 uint8_t Type2 = (Type >> 8) & 0xFF;
554 uint8_t Type3 = (Type >> 16) & 0xFF;
556 // Concat all three relocation type names.
557 StringRef Name = getRelocationTypeName(Type1);
558 Result.append(Name.begin(), Name.end());
560 Name = getRelocationTypeName(Type2);
561 Result.append(1, '/');
562 Result.append(Name.begin(), Name.end());
564 Name = getRelocationTypeName(Type3);
565 Result.append(1, '/');
566 Result.append(Name.begin(), Name.end());
570 template <class ELFT>
571 template <class RelT>
572 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
573 const typename ELFFile<ELFT>::Elf_Sym *>
574 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
576 return std::make_pair(nullptr, nullptr);
577 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
578 return std::make_pair(
579 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
582 // Verify that the last byte in the string table in a null.
583 template <class ELFT>
584 void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
585 const char *strtab = (const char *)base() + sh->sh_offset;
586 if (strtab[sh->sh_size - 1] != 0)
587 // FIXME: Proper error handling.
588 report_fatal_error("String table must end with a null terminator!");
591 template <class ELFT>
592 uint64_t ELFFile<ELFT>::getNumSections() const {
593 assert(Header && "Header not initialized!");
594 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
595 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
596 return SectionHeaderTable->sh_size;
598 return Header->e_shnum;
601 template <class ELFT>
602 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
603 if (Header->e_shnum == ELF::SHN_UNDEF) {
604 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
605 return SectionHeaderTable->sh_link;
606 if (Header->e_shstrndx >= getNumSections())
609 return Header->e_shstrndx;
612 template <class ELFT>
613 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &ec)
614 : Buf(Object), SectionHeaderTable(nullptr), dot_shstrtab_sec(nullptr),
615 dot_strtab_sec(nullptr), dot_symtab_sec(nullptr),
616 SymbolTableSectionHeaderIndex(nullptr), dot_gnu_version_sec(nullptr),
617 dot_gnu_version_r_sec(nullptr), dot_gnu_version_d_sec(nullptr),
619 const uint64_t FileSize = Buf.size();
621 if (sizeof(Elf_Ehdr) > FileSize)
622 // FIXME: Proper error handling.
623 report_fatal_error("File too short!");
625 Header = reinterpret_cast<const Elf_Ehdr *>(base());
627 if (Header->e_shoff == 0)
630 const uint64_t SectionTableOffset = Header->e_shoff;
632 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
633 // FIXME: Proper error handling.
634 report_fatal_error("Section header table goes past end of file!");
636 // The getNumSections() call below depends on SectionHeaderTable being set.
638 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
639 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
641 if (SectionTableOffset + SectionTableSize > FileSize)
642 // FIXME: Proper error handling.
643 report_fatal_error("Section table goes past end of file!");
645 // Scan sections for special sections.
647 for (const Elf_Shdr &Sec : sections()) {
648 switch (Sec.sh_type) {
649 case ELF::SHT_SYMTAB_SHNDX:
650 if (SymbolTableSectionHeaderIndex)
651 // FIXME: Proper error handling.
652 report_fatal_error("More than one .symtab_shndx!");
653 SymbolTableSectionHeaderIndex = &Sec;
655 case ELF::SHT_SYMTAB:
657 // FIXME: Proper error handling.
658 report_fatal_error("More than one .symtab!");
659 dot_symtab_sec = &Sec;
660 dot_strtab_sec = getSection(Sec.sh_link);
662 case ELF::SHT_DYNSYM: {
663 if (DynSymRegion.Addr)
664 // FIXME: Proper error handling.
665 report_fatal_error("More than one .dynsym!");
666 DynSymRegion.Addr = base() + Sec.sh_offset;
667 DynSymRegion.Size = Sec.sh_size;
668 DynSymRegion.EntSize = Sec.sh_entsize;
669 const Elf_Shdr *DynStr = getSection(Sec.sh_link);
670 DynStrRegion.Addr = base() + DynStr->sh_offset;
671 DynStrRegion.Size = DynStr->sh_size;
672 DynStrRegion.EntSize = DynStr->sh_entsize;
675 case ELF::SHT_DYNAMIC:
676 if (DynamicRegion.Addr)
677 // FIXME: Proper error handling.
678 report_fatal_error("More than one .dynamic!");
679 DynamicRegion.Addr = base() + Sec.sh_offset;
680 DynamicRegion.Size = Sec.sh_size;
681 DynamicRegion.EntSize = Sec.sh_entsize;
683 case ELF::SHT_GNU_versym:
684 if (dot_gnu_version_sec != nullptr)
685 // FIXME: Proper error handling.
686 report_fatal_error("More than one .gnu.version section!");
687 dot_gnu_version_sec = &Sec;
689 case ELF::SHT_GNU_verdef:
690 if (dot_gnu_version_d_sec != nullptr)
691 // FIXME: Proper error handling.
692 report_fatal_error("More than one .gnu.version_d section!");
693 dot_gnu_version_d_sec = &Sec;
695 case ELF::SHT_GNU_verneed:
696 if (dot_gnu_version_r_sec != nullptr)
697 // FIXME: Proper error handling.
698 report_fatal_error("More than one .gnu.version_r section!");
699 dot_gnu_version_r_sec = &Sec;
704 // Get string table sections.
705 dot_shstrtab_sec = getSection(getStringTableIndex());
706 if (dot_shstrtab_sec) {
707 // Verify that the last byte in the string table in a null.
708 VerifyStrTab(dot_shstrtab_sec);
711 // Build symbol name side-mapping if there is one.
712 if (SymbolTableSectionHeaderIndex) {
713 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
714 SymbolTableSectionHeaderIndex->sh_offset);
715 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
717 if (*ShndxTable != ELF::SHN_UNDEF)
718 ExtendedSymbolTable[&*SI] = *ShndxTable;
723 // Scan program headers.
724 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
725 PhdrE = end_program_headers();
726 PhdrI != PhdrE; ++PhdrI) {
727 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
728 DynamicRegion.Addr = base() + PhdrI->p_offset;
729 DynamicRegion.Size = PhdrI->p_filesz;
730 DynamicRegion.EntSize = sizeof(Elf_Dyn);
735 ec = std::error_code();
738 // Get the symbol table index in the symtab section given a symbol
739 template <class ELFT>
740 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
741 uintptr_t SymLoc = uintptr_t(Sym);
742 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
743 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
744 uint64_t SymOffset = SymLoc - SymTabLoc;
745 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
746 "Symbol not multiple of symbol size!");
747 return SymOffset / dot_symtab_sec->sh_entsize;
750 template <class ELFT>
751 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
752 return Elf_Shdr_Iter(Header->e_shentsize,
753 (const char *)base() + Header->e_shoff);
756 template <class ELFT>
757 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
758 return Elf_Shdr_Iter(Header->e_shentsize,
759 (const char *)base() + Header->e_shoff +
760 (getNumSections() * Header->e_shentsize));
763 template <class ELFT>
764 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
766 return Elf_Sym_Iter(0, nullptr, false);
767 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
768 (const char *)base() + dot_symtab_sec->sh_offset, false);
771 template <class ELFT>
772 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
774 return Elf_Sym_Iter(0, nullptr, false);
775 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
776 (const char *)base() + dot_symtab_sec->sh_offset +
777 dot_symtab_sec->sh_size,
781 template <class ELFT>
782 typename ELFFile<ELFT>::Elf_Dyn_Iter
783 ELFFile<ELFT>::begin_dynamic_table() const {
784 if (DynamicRegion.Addr)
785 return Elf_Dyn_Iter(DynamicRegion.EntSize,
786 (const char *)DynamicRegion.Addr);
787 return Elf_Dyn_Iter(0, nullptr);
790 template <class ELFT>
791 typename ELFFile<ELFT>::Elf_Dyn_Iter
792 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
793 if (!DynamicRegion.Addr)
794 return Elf_Dyn_Iter(0, nullptr);
795 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
796 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
799 Elf_Dyn_Iter Start = begin_dynamic_table();
800 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
803 // Include the DT_NULL.
811 template <class ELFT>
812 StringRef ELFFile<ELFT>::getLoadName() const {
815 // Find the DT_SONAME entry
816 for (const auto &Entry : dynamic_table())
817 if (Entry.getTag() == ELF::DT_SONAME) {
818 dt_soname = getDynamicString(Entry.getVal());
825 template <class ELFT>
826 template <typename T>
827 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
828 return getEntry<T>(getSection(Section), Entry);
831 template <class ELFT>
832 template <typename T>
833 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
834 uint32_t Entry) const {
835 return reinterpret_cast<const T *>(base() + Section->sh_offset +
836 (Entry * Section->sh_entsize));
839 template <class ELFT>
840 const typename ELFFile<ELFT>::Elf_Shdr *
841 ELFFile<ELFT>::getSection(uint32_t index) const {
844 if (!SectionHeaderTable || index >= getNumSections())
845 // FIXME: Proper error handling.
846 report_fatal_error("Invalid section index!");
848 return reinterpret_cast<const Elf_Shdr *>(
849 reinterpret_cast<const char *>(SectionHeaderTable)
850 + (index * Header->e_shentsize));
853 template <class ELFT>
854 const char *ELFFile<ELFT>::getString(uint32_t section,
855 ELF::Elf32_Word offset) const {
856 return getString(getSection(section), offset);
859 template <class ELFT>
860 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
861 ELF::Elf32_Word offset) const {
862 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
863 if (offset >= section->sh_size)
864 // FIXME: Proper error handling.
865 report_fatal_error("Symbol name offset outside of string table!");
866 return (const char *)base() + section->sh_offset + offset;
869 template <class ELFT>
870 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
871 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
873 return (const char *)DynStrRegion.Addr + Offset;
876 template <class ELFT>
877 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
878 if (!Sym.isDynamic())
879 return getSymbolName(dot_symtab_sec, &*Sym);
881 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
882 return object_error::parse_failed;
883 return StringRef(getDynamicString(Sym->st_name));
886 template <class ELFT>
887 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
888 const Elf_Sym *Symb) const {
889 if (Symb->st_name == 0) {
890 const Elf_Shdr *ContainingSec = getSection(Symb);
892 return getSectionName(ContainingSec);
895 const Elf_Shdr *StrTab = getSection(Section->sh_link);
896 if (Symb->st_name >= StrTab->sh_size)
897 return object_error::parse_failed;
898 return StringRef(getString(StrTab, Symb->st_name));
901 template <class ELFT>
903 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
904 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
905 return object_error::parse_failed;
906 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
909 template <class ELFT>
910 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
912 bool &IsDefault) const {
913 // Handle non-dynamic symbols.
914 if (section != DynSymRegion.Addr && section != nullptr) {
915 // Non-dynamic symbols can have versions in their names
916 // A name of the form 'foo@V1' indicates version 'V1', non-default.
917 // A name of the form 'foo@@V2' indicates version 'V2', default version.
918 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
921 StringRef Name = *SymName;
922 size_t atpos = Name.find('@');
923 if (atpos == StringRef::npos) {
925 return StringRef("");
928 if (atpos < Name.size() && Name[atpos] == '@') {
934 return Name.substr(atpos);
937 // This is a dynamic symbol. Look in the GNU symbol version table.
938 if (!dot_gnu_version_sec) {
941 return StringRef("");
944 // Determine the position in the symbol table of this entry.
945 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
946 DynSymRegion.EntSize;
948 // Get the corresponding version index entry
949 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
950 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
952 // Special markers for unversioned symbols.
953 if (version_index == ELF::VER_NDX_LOCAL ||
954 version_index == ELF::VER_NDX_GLOBAL) {
956 return StringRef("");
959 // Lookup this symbol in the version table
961 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
962 return object_error::parse_failed;
963 const VersionMapEntry &entry = VersionMap[version_index];
965 // Get the version name string
967 if (entry.isVerdef()) {
968 // The first Verdaux entry holds the name.
969 name_offset = entry.getVerdef()->getAux()->vda_name;
971 name_offset = entry.getVernaux()->vna_name;
975 if (entry.isVerdef()) {
976 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
981 if (name_offset >= DynStrRegion.Size)
982 return object_error::parse_failed;
983 return StringRef(getDynamicString(name_offset));
986 /// This function returns the hash value for a symbol in the .dynsym section
987 /// Name of the API remains consistent as specified in the libelf
988 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
989 static inline unsigned elf_hash(StringRef &symbolName) {
991 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
992 h = (h << 4) + symbolName[i];
1000 } // end namespace object
1001 } // end namespace llvm