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 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::random_access_iterator_tag iterator_category;
64 typedef value_type &reference;
65 typedef value_type *pointer;
67 /// \brief Default construct iterator.
68 ELFEntityIterator() : EntitySize(0), Current(0) {}
69 ELFEntityIterator(uintX_t EntSize, const char *Start)
70 : EntitySize(EntSize), Current(Start) {}
72 reference operator *() {
73 assert(Current && "Attempted to dereference an invalid iterator!");
74 return *reinterpret_cast<pointer>(Current);
77 pointer operator ->() {
78 assert(Current && "Attempted to dereference an invalid iterator!");
79 return reinterpret_cast<pointer>(Current);
82 bool operator ==(const ELFEntityIterator &Other) {
83 return Current == Other.Current;
86 bool operator !=(const ELFEntityIterator &Other) {
87 return !(*this == Other);
90 ELFEntityIterator &operator ++() {
91 assert(Current && "Attempted to increment an invalid iterator!");
92 Current += EntitySize;
96 ELFEntityIterator operator ++(int) {
97 ELFEntityIterator Tmp = *this;
102 ELFEntityIterator &operator =(const ELFEntityIterator &Other) {
103 EntitySize = Other.EntitySize;
104 Current = Other.Current;
108 difference_type operator -(const ELFEntityIterator &Other) const {
109 assert(EntitySize == Other.EntitySize &&
110 "Subtracting iterators of different EntitySize!");
111 return (Current - Other.Current) / EntitySize;
114 const char *get() const { return Current; }
116 uintX_t getEntSize() const { return EntitySize; }
123 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
124 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
125 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
126 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
127 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
128 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
129 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
130 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
131 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
132 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
133 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
134 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
135 typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
136 typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
137 typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
138 typedef ELFEntityIterator<const Elf_Shdr> Elf_Shdr_Iter;
140 /// \brief Archive files are 2 byte aligned, so we need this for
141 /// PointerIntPair to work.
142 template <typename T>
143 class ArchivePointerTypeTraits {
145 static inline const void *getAsVoidPointer(T *P) { return P; }
146 static inline T *getFromVoidPointer(const void *P) {
147 return static_cast<T *>(P);
149 enum { NumLowBitsAvailable = 1 };
154 typedef ptrdiff_t difference_type;
155 typedef const Elf_Sym value_type;
156 typedef std::random_access_iterator_tag iterator_category;
157 typedef value_type &reference;
158 typedef value_type *pointer;
160 /// \brief Default construct iterator.
161 Elf_Sym_Iter() : EntitySize(0), Current(0, false) {}
162 Elf_Sym_Iter(uintX_t EntSize, const char *Start, bool IsDynamic)
163 : EntitySize(EntSize), Current(Start, IsDynamic) {}
165 reference operator*() {
166 assert(Current.getPointer() &&
167 "Attempted to dereference an invalid iterator!");
168 return *reinterpret_cast<pointer>(Current.getPointer());
171 pointer operator->() {
172 assert(Current.getPointer() &&
173 "Attempted to dereference an invalid iterator!");
174 return reinterpret_cast<pointer>(Current.getPointer());
177 bool operator==(const Elf_Sym_Iter &Other) {
178 return Current == Other.Current;
181 bool operator!=(const Elf_Sym_Iter &Other) { return !(*this == Other); }
183 Elf_Sym_Iter &operator++() {
184 assert(Current.getPointer() &&
185 "Attempted to increment an invalid iterator!");
186 Current.setPointer(Current.getPointer() + EntitySize);
190 Elf_Sym_Iter operator++(int) {
191 Elf_Sym_Iter Tmp = *this;
196 Elf_Sym_Iter operator+(difference_type Dist) {
197 assert(Current.getPointer() &&
198 "Attempted to increment an invalid iterator!");
199 Current.setPointer(Current.getPointer() + EntitySize * Dist);
203 Elf_Sym_Iter &operator=(const Elf_Sym_Iter &Other) {
204 EntitySize = Other.EntitySize;
205 Current = Other.Current;
209 difference_type operator-(const Elf_Sym_Iter &Other) const {
210 assert(EntitySize == Other.EntitySize &&
211 "Subtracting iterators of different EntitySize!");
212 return (Current.getPointer() - Other.Current.getPointer()) / EntitySize;
215 const char *get() const { return Current.getPointer(); }
217 bool isDynamic() const { return Current.getInt(); }
219 uintX_t getEntSize() const { return EntitySize; }
223 PointerIntPair<const char *, 1, bool,
224 ArchivePointerTypeTraits<const char> > Current;
228 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
229 typedef DenseMap<unsigned, unsigned> IndexMap_t;
233 const uint8_t *base() const {
234 return reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
237 const Elf_Ehdr *Header;
238 const Elf_Shdr *SectionHeaderTable;
239 const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
240 const Elf_Shdr *dot_strtab_sec; // Symbol header string table.
241 const Elf_Shdr *dot_symtab_sec; // Symbol table section.
243 const Elf_Shdr *SymbolTableSectionHeaderIndex;
244 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
246 const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
247 const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
248 const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
250 /// \brief Represents a region described by entries in the .dynamic table.
251 struct DynRegionInfo {
252 DynRegionInfo() : Addr(0), Size(0), EntSize(0) {}
253 /// \brief Address in current address space.
255 /// \brief Size in bytes of the region.
257 /// \brief Size of each entity in the region.
261 DynRegionInfo DynamicRegion;
262 DynRegionInfo DynHashRegion;
263 DynRegionInfo DynStrRegion;
264 DynRegionInfo DynSymRegion;
266 // Pointer to SONAME entry in dynamic string table
267 // This is set the first time getLoadName is called.
268 mutable const char *dt_soname;
270 // Records for each version index the corresponding Verdef or Vernaux entry.
271 // This is filled the first time LoadVersionMap() is called.
272 class VersionMapEntry : public PointerIntPair<const void*, 1> {
274 // If the integer is 0, this is an Elf_Verdef*.
275 // If the integer is 1, this is an Elf_Vernaux*.
276 VersionMapEntry() : PointerIntPair<const void*, 1>(NULL, 0) { }
277 VersionMapEntry(const Elf_Verdef *verdef)
278 : PointerIntPair<const void*, 1>(verdef, 0) { }
279 VersionMapEntry(const Elf_Vernaux *vernaux)
280 : PointerIntPair<const void*, 1>(vernaux, 1) { }
281 bool isNull() const { return getPointer() == NULL; }
282 bool isVerdef() const { return !isNull() && getInt() == 0; }
283 bool isVernaux() const { return !isNull() && getInt() == 1; }
284 const Elf_Verdef *getVerdef() const {
285 return isVerdef() ? (const Elf_Verdef*)getPointer() : NULL;
287 const Elf_Vernaux *getVernaux() const {
288 return isVernaux() ? (const Elf_Vernaux*)getPointer() : NULL;
291 mutable SmallVector<VersionMapEntry, 16> VersionMap;
292 void LoadVersionDefs(const Elf_Shdr *sec) const;
293 void LoadVersionNeeds(const Elf_Shdr *ec) const;
294 void LoadVersionMap() const;
298 const T *getEntry(uint32_t Section, uint32_t Entry) const;
299 template <typename T>
300 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
301 const char *getString(uint32_t section, uint32_t offset) const;
302 const char *getString(const Elf_Shdr *section, uint32_t offset) const;
303 const char *getDynamicString(uintX_t Offset) const;
304 ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
306 bool &IsDefault) const;
307 void VerifyStrTab(const Elf_Shdr *sh) const;
309 StringRef getRelocationTypeName(uint32_t Type) const;
310 void getRelocationTypeName(uint32_t Type,
311 SmallVectorImpl<char> &Result) const;
313 /// \brief Get the symbol table section and symbol for a given relocation.
314 template <class RelT>
315 std::pair<const Elf_Shdr *, const Elf_Sym *>
316 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
318 ELFFile(MemoryBuffer *Object, error_code &ec);
320 bool isMips64EL() const {
321 return Header->e_machine == ELF::EM_MIPS &&
322 Header->getFileClass() == ELF::ELFCLASS64 &&
323 Header->getDataEncoding() == ELF::ELFDATA2LSB;
326 Elf_Shdr_Iter begin_sections() const;
327 Elf_Shdr_Iter end_sections() const;
329 Elf_Sym_Iter begin_symbols() const;
330 Elf_Sym_Iter end_symbols() const;
332 Elf_Dyn_Iter begin_dynamic_table() const;
333 /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
334 /// the section size.
335 Elf_Dyn_Iter end_dynamic_table(bool NULLEnd = false) const;
337 Elf_Sym_Iter begin_dynamic_symbols() const {
338 if (DynSymRegion.Addr)
339 return Elf_Sym_Iter(DynSymRegion.EntSize, (const char *)DynSymRegion.Addr,
341 return Elf_Sym_Iter(0, 0, true);
344 Elf_Sym_Iter end_dynamic_symbols() const {
345 if (DynSymRegion.Addr)
346 return Elf_Sym_Iter(DynSymRegion.EntSize,
347 (const char *)DynSymRegion.Addr + DynSymRegion.Size,
349 return Elf_Sym_Iter(0, 0, true);
352 Elf_Rela_Iter begin_rela(const Elf_Shdr *sec) const {
353 return Elf_Rela_Iter(sec->sh_entsize,
354 (const char *)(base() + sec->sh_offset));
357 Elf_Rela_Iter end_rela(const Elf_Shdr *sec) const {
358 return Elf_Rela_Iter(
360 (const char *)(base() + sec->sh_offset + sec->sh_size));
363 Elf_Rel_Iter begin_rel(const Elf_Shdr *sec) const {
364 return Elf_Rel_Iter(sec->sh_entsize,
365 (const char *)(base() + sec->sh_offset));
368 Elf_Rel_Iter end_rel(const Elf_Shdr *sec) const {
369 return Elf_Rel_Iter(sec->sh_entsize,
370 (const char *)(base() + sec->sh_offset + sec->sh_size));
373 /// \brief Iterate over program header table.
374 typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
376 Elf_Phdr_Iter begin_program_headers() const {
377 return Elf_Phdr_Iter(Header->e_phentsize,
378 (const char*)base() + Header->e_phoff);
381 Elf_Phdr_Iter end_program_headers() const {
382 return Elf_Phdr_Iter(Header->e_phentsize,
383 (const char*)base() +
385 (Header->e_phnum * Header->e_phentsize));
388 uint64_t getNumSections() const;
389 uintX_t getStringTableIndex() const;
390 ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
391 const Elf_Ehdr *getHeader() const { return Header; }
392 const Elf_Shdr *getSection(const Elf_Sym *symb) const;
393 const Elf_Shdr *getSection(uint32_t Index) const;
394 const Elf_Sym *getSymbol(uint32_t index) const;
396 ErrorOr<StringRef> getSymbolName(Elf_Sym_Iter Sym) const;
398 /// \brief Get the name of \p Symb.
399 /// \param SymTab The symbol table section \p Symb is contained in.
400 /// \param Symb The symbol to get the name of.
402 /// \p SymTab is used to lookup the string table to use to get the symbol's
404 ErrorOr<StringRef> getSymbolName(const Elf_Shdr *SymTab,
405 const Elf_Sym *Symb) const;
406 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
407 uint64_t getSymbolIndex(const Elf_Sym *sym) const;
408 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
409 StringRef getLoadName() const;
412 // Use an alignment of 2 for the typedefs since that is the worst case for
413 // ELF files in archives.
414 typedef ELFFile<ELFType<support::little, 2, false> > ELF32LEFile;
415 typedef ELFFile<ELFType<support::little, 2, true> > ELF64LEFile;
416 typedef ELFFile<ELFType<support::big, 2, false> > ELF32BEFile;
417 typedef ELFFile<ELFType<support::big, 2, true> > ELF64BEFile;
419 // Iterate through the version definitions, and place each Elf_Verdef
420 // in the VersionMap according to its index.
421 template <class ELFT>
422 void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
423 unsigned vd_size = sec->sh_size; // Size of section in bytes
424 unsigned vd_count = sec->sh_info; // Number of Verdef entries
425 const char *sec_start = (const char*)base() + sec->sh_offset;
426 const char *sec_end = sec_start + vd_size;
427 // The first Verdef entry is at the start of the section.
428 const char *p = sec_start;
429 for (unsigned i = 0; i < vd_count; i++) {
430 if (p + sizeof(Elf_Verdef) > sec_end)
431 report_fatal_error("Section ended unexpectedly while scanning "
432 "version definitions.");
433 const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
434 if (vd->vd_version != ELF::VER_DEF_CURRENT)
435 report_fatal_error("Unexpected verdef version");
436 size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
437 if (index >= VersionMap.size())
438 VersionMap.resize(index + 1);
439 VersionMap[index] = VersionMapEntry(vd);
444 // Iterate through the versions needed section, and place each Elf_Vernaux
445 // in the VersionMap according to its index.
446 template <class ELFT>
447 void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
448 unsigned vn_size = sec->sh_size; // Size of section in bytes
449 unsigned vn_count = sec->sh_info; // Number of Verneed entries
450 const char *sec_start = (const char *)base() + sec->sh_offset;
451 const char *sec_end = sec_start + vn_size;
452 // The first Verneed entry is at the start of the section.
453 const char *p = sec_start;
454 for (unsigned i = 0; i < vn_count; i++) {
455 if (p + sizeof(Elf_Verneed) > sec_end)
456 report_fatal_error("Section ended unexpectedly while scanning "
457 "version needed records.");
458 const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
459 if (vn->vn_version != ELF::VER_NEED_CURRENT)
460 report_fatal_error("Unexpected verneed version");
461 // Iterate through the Vernaux entries
462 const char *paux = p + vn->vn_aux;
463 for (unsigned j = 0; j < vn->vn_cnt; j++) {
464 if (paux + sizeof(Elf_Vernaux) > sec_end)
465 report_fatal_error("Section ended unexpected while scanning auxiliary "
466 "version needed records.");
467 const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
468 size_t index = vna->vna_other & ELF::VERSYM_VERSION;
469 if (index >= VersionMap.size())
470 VersionMap.resize(index + 1);
471 VersionMap[index] = VersionMapEntry(vna);
472 paux += vna->vna_next;
478 template <class ELFT>
479 void ELFFile<ELFT>::LoadVersionMap() const {
480 // If there is no dynamic symtab or version table, there is nothing to do.
481 if (DynSymRegion.Addr == NULL || dot_gnu_version_sec == NULL)
484 // Has the VersionMap already been loaded?
485 if (VersionMap.size() > 0)
488 // The first two version indexes are reserved.
489 // Index 0 is LOCAL, index 1 is GLOBAL.
490 VersionMap.push_back(VersionMapEntry());
491 VersionMap.push_back(VersionMapEntry());
493 if (dot_gnu_version_d_sec)
494 LoadVersionDefs(dot_gnu_version_d_sec);
496 if (dot_gnu_version_r_sec)
497 LoadVersionNeeds(dot_gnu_version_r_sec);
500 template <class ELFT>
501 ELF::Elf64_Word ELFFile<ELFT>::getSymbolTableIndex(const Elf_Sym *symb) const {
502 if (symb->st_shndx == ELF::SHN_XINDEX)
503 return ExtendedSymbolTable.lookup(symb);
504 return symb->st_shndx;
507 template <class ELFT>
508 const typename ELFFile<ELFT>::Elf_Shdr *
509 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
510 if (symb->st_shndx == ELF::SHN_XINDEX)
511 return getSection(ExtendedSymbolTable.lookup(symb));
512 if (symb->st_shndx >= ELF::SHN_LORESERVE)
514 return getSection(symb->st_shndx);
517 template <class ELFT>
518 const typename ELFFile<ELFT>::Elf_Sym *
519 ELFFile<ELFT>::getSymbol(uint32_t Index) const {
520 return &*(begin_symbols() + Index);
523 template <class ELFT>
524 ErrorOr<ArrayRef<uint8_t> >
525 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
526 if (Sec->sh_offset + Sec->sh_size > Buf->getBufferSize())
527 return object_error::parse_failed;
528 const uint8_t *Start = base() + Sec->sh_offset;
529 return ArrayRef<uint8_t>(Start, Sec->sh_size);
532 template <class ELFT>
533 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
534 return getELFRelocationTypeName(Header->e_machine, Type);
537 template <class ELFT>
538 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
539 SmallVectorImpl<char> &Result) const {
541 StringRef Name = getRelocationTypeName(Type);
542 Result.append(Name.begin(), Name.end());
544 uint8_t Type1 = (Type >> 0) & 0xFF;
545 uint8_t Type2 = (Type >> 8) & 0xFF;
546 uint8_t Type3 = (Type >> 16) & 0xFF;
548 // Concat all three relocation type names.
549 StringRef Name = getRelocationTypeName(Type1);
550 Result.append(Name.begin(), Name.end());
552 Name = getRelocationTypeName(Type2);
553 Result.append(1, '/');
554 Result.append(Name.begin(), Name.end());
556 Name = getRelocationTypeName(Type3);
557 Result.append(1, '/');
558 Result.append(Name.begin(), Name.end());
562 template <class ELFT>
563 template <class RelT>
564 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
565 const typename ELFFile<ELFT>::Elf_Sym *>
566 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
568 return std::make_pair((const Elf_Shdr *)0, (const Elf_Sym *)0);
569 const Elf_Shdr *SymTable = getSection(Sec->sh_link);
570 return std::make_pair(
571 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
574 // Verify that the last byte in the string table in a null.
575 template <class ELFT>
576 void ELFFile<ELFT>::VerifyStrTab(const Elf_Shdr *sh) const {
577 const char *strtab = (const char *)base() + sh->sh_offset;
578 if (strtab[sh->sh_size - 1] != 0)
579 // FIXME: Proper error handling.
580 report_fatal_error("String table must end with a null terminator!");
583 template <class ELFT>
584 uint64_t ELFFile<ELFT>::getNumSections() const {
585 assert(Header && "Header not initialized!");
586 if (Header->e_shnum == ELF::SHN_UNDEF) {
587 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
588 return SectionHeaderTable->sh_size;
590 return Header->e_shnum;
593 template <class ELFT>
594 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
595 if (Header->e_shnum == ELF::SHN_UNDEF) {
596 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
597 return SectionHeaderTable->sh_link;
598 if (Header->e_shstrndx >= getNumSections())
601 return Header->e_shstrndx;
604 template <class ELFT>
605 ELFFile<ELFT>::ELFFile(MemoryBuffer *Object, error_code &ec)
607 SectionHeaderTable(0),
611 SymbolTableSectionHeaderIndex(0),
612 dot_gnu_version_sec(0),
613 dot_gnu_version_r_sec(0),
614 dot_gnu_version_d_sec(0),
616 const uint64_t FileSize = Buf->getBufferSize();
618 if (sizeof(Elf_Ehdr) > FileSize)
619 // FIXME: Proper error handling.
620 report_fatal_error("File too short!");
622 Header = reinterpret_cast<const Elf_Ehdr *>(base());
624 if (Header->e_shoff == 0)
627 const uint64_t SectionTableOffset = Header->e_shoff;
629 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
630 // FIXME: Proper error handling.
631 report_fatal_error("Section header table goes past end of file!");
633 // The getNumSections() call below depends on SectionHeaderTable being set.
635 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
636 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
638 if (SectionTableOffset + SectionTableSize > FileSize)
639 // FIXME: Proper error handling.
640 report_fatal_error("Section table goes past end of file!");
642 // Scan sections for special sections.
644 for (Elf_Shdr_Iter SecI = begin_sections(), SecE = end_sections();
645 SecI != SecE; ++SecI) {
646 switch (SecI->sh_type) {
647 case ELF::SHT_SYMTAB_SHNDX:
648 if (SymbolTableSectionHeaderIndex)
649 // FIXME: Proper error handling.
650 report_fatal_error("More than one .symtab_shndx!");
651 SymbolTableSectionHeaderIndex = &*SecI;
653 case ELF::SHT_SYMTAB:
655 // FIXME: Proper error handling.
656 report_fatal_error("More than one .symtab!");
657 dot_symtab_sec = &*SecI;
658 dot_strtab_sec = getSection(SecI->sh_link);
660 case ELF::SHT_DYNSYM: {
661 if (DynSymRegion.Addr)
662 // FIXME: Proper error handling.
663 report_fatal_error("More than one .dynsym!");
664 DynSymRegion.Addr = base() + SecI->sh_offset;
665 DynSymRegion.Size = SecI->sh_size;
666 DynSymRegion.EntSize = SecI->sh_entsize;
667 const Elf_Shdr *DynStr = getSection(SecI->sh_link);
668 DynStrRegion.Addr = base() + DynStr->sh_offset;
669 DynStrRegion.Size = DynStr->sh_size;
670 DynStrRegion.EntSize = DynStr->sh_entsize;
673 case ELF::SHT_DYNAMIC:
674 if (DynamicRegion.Addr)
675 // FIXME: Proper error handling.
676 report_fatal_error("More than one .dynamic!");
677 DynamicRegion.Addr = base() + SecI->sh_offset;
678 DynamicRegion.Size = SecI->sh_size;
679 DynamicRegion.EntSize = SecI->sh_entsize;
681 case ELF::SHT_GNU_versym:
682 if (dot_gnu_version_sec != NULL)
683 // FIXME: Proper error handling.
684 report_fatal_error("More than one .gnu.version section!");
685 dot_gnu_version_sec = &*SecI;
687 case ELF::SHT_GNU_verdef:
688 if (dot_gnu_version_d_sec != NULL)
689 // FIXME: Proper error handling.
690 report_fatal_error("More than one .gnu.version_d section!");
691 dot_gnu_version_d_sec = &*SecI;
693 case ELF::SHT_GNU_verneed:
694 if (dot_gnu_version_r_sec != NULL)
695 // FIXME: Proper error handling.
696 report_fatal_error("More than one .gnu.version_r section!");
697 dot_gnu_version_r_sec = &*SecI;
702 // Get string table sections.
703 dot_shstrtab_sec = getSection(getStringTableIndex());
704 if (dot_shstrtab_sec) {
705 // Verify that the last byte in the string table in a null.
706 VerifyStrTab(dot_shstrtab_sec);
709 // Build symbol name side-mapping if there is one.
710 if (SymbolTableSectionHeaderIndex) {
711 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
712 SymbolTableSectionHeaderIndex->sh_offset);
713 for (Elf_Sym_Iter SI = begin_symbols(), SE = end_symbols(); SI != SE;
715 if (*ShndxTable != ELF::SHN_UNDEF)
716 ExtendedSymbolTable[&*SI] = *ShndxTable;
721 // Scan program headers.
722 for (Elf_Phdr_Iter PhdrI = begin_program_headers(),
723 PhdrE = end_program_headers();
724 PhdrI != PhdrE; ++PhdrI) {
725 if (PhdrI->p_type == ELF::PT_DYNAMIC) {
726 DynamicRegion.Addr = base() + PhdrI->p_offset;
727 DynamicRegion.Size = PhdrI->p_filesz;
728 DynamicRegion.EntSize = sizeof(Elf_Dyn);
733 ec = error_code::success();
736 // Get the symbol table index in the symtab section given a symbol
737 template <class ELFT>
738 uint64_t ELFFile<ELFT>::getSymbolIndex(const Elf_Sym *Sym) const {
739 uintptr_t SymLoc = uintptr_t(Sym);
740 uintptr_t SymTabLoc = uintptr_t(base() + dot_symtab_sec->sh_offset);
741 assert(SymLoc > SymTabLoc && "Symbol not in symbol table!");
742 uint64_t SymOffset = SymLoc - SymTabLoc;
743 assert(SymOffset % dot_symtab_sec->sh_entsize == 0 &&
744 "Symbol not multiple of symbol size!");
745 return SymOffset / dot_symtab_sec->sh_entsize;
748 template <class ELFT>
749 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::begin_sections() const {
750 return Elf_Shdr_Iter(Header->e_shentsize,
751 (const char *)base() + Header->e_shoff);
754 template <class ELFT>
755 typename ELFFile<ELFT>::Elf_Shdr_Iter ELFFile<ELFT>::end_sections() const {
756 return Elf_Shdr_Iter(Header->e_shentsize,
757 (const char *)base() + Header->e_shoff +
758 (getNumSections() * Header->e_shentsize));
761 template <class ELFT>
762 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::begin_symbols() const {
764 return Elf_Sym_Iter(0, 0, false);
765 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
766 (const char *)base() + dot_symtab_sec->sh_offset, false);
769 template <class ELFT>
770 typename ELFFile<ELFT>::Elf_Sym_Iter ELFFile<ELFT>::end_symbols() const {
772 return Elf_Sym_Iter(0, 0, false);
773 return Elf_Sym_Iter(dot_symtab_sec->sh_entsize,
774 (const char *)base() + dot_symtab_sec->sh_offset +
775 dot_symtab_sec->sh_size,
779 template <class ELFT>
780 typename ELFFile<ELFT>::Elf_Dyn_Iter
781 ELFFile<ELFT>::begin_dynamic_table() const {
782 if (DynamicRegion.Addr)
783 return Elf_Dyn_Iter(DynamicRegion.EntSize,
784 (const char *)DynamicRegion.Addr);
785 return Elf_Dyn_Iter(0, 0);
788 template <class ELFT>
789 typename ELFFile<ELFT>::Elf_Dyn_Iter
790 ELFFile<ELFT>::end_dynamic_table(bool NULLEnd) const {
791 if (!DynamicRegion.Addr)
792 return Elf_Dyn_Iter(0, 0);
793 Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
794 (const char *)DynamicRegion.Addr + DynamicRegion.Size);
797 Elf_Dyn_Iter Start = begin_dynamic_table();
798 while (Start != Ret && Start->getTag() != ELF::DT_NULL)
801 // Include the DT_NULL.
809 template <class ELFT>
810 StringRef ELFFile<ELFT>::getLoadName() const {
812 // Find the DT_SONAME entry
813 Elf_Dyn_Iter it = begin_dynamic_table();
814 Elf_Dyn_Iter ie = end_dynamic_table();
815 while (it != ie && it->getTag() != ELF::DT_SONAME)
819 dt_soname = getDynamicString(it->getVal());
827 template <class ELFT>
828 template <typename T>
829 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
830 return getEntry<T>(getSection(Section), Entry);
833 template <class ELFT>
834 template <typename T>
835 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
836 uint32_t Entry) const {
837 return reinterpret_cast<const T *>(base() + Section->sh_offset +
838 (Entry * Section->sh_entsize));
841 template <class ELFT>
842 const typename ELFFile<ELFT>::Elf_Shdr *
843 ELFFile<ELFT>::getSection(uint32_t index) const {
846 if (!SectionHeaderTable || index >= getNumSections())
847 // FIXME: Proper error handling.
848 report_fatal_error("Invalid section index!");
850 return reinterpret_cast<const Elf_Shdr *>(
851 reinterpret_cast<const char *>(SectionHeaderTable)
852 + (index * Header->e_shentsize));
855 template <class ELFT>
856 const char *ELFFile<ELFT>::getString(uint32_t section,
857 ELF::Elf32_Word offset) const {
858 return getString(getSection(section), offset);
861 template <class ELFT>
862 const char *ELFFile<ELFT>::getString(const Elf_Shdr *section,
863 ELF::Elf32_Word offset) const {
864 assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
865 if (offset >= section->sh_size)
866 // FIXME: Proper error handling.
867 report_fatal_error("Symbol name offset outside of string table!");
868 return (const char *)base() + section->sh_offset + offset;
871 template <class ELFT>
872 const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
873 if (!DynStrRegion.Addr || Offset >= DynStrRegion.Size)
875 return (const char *)DynStrRegion.Addr + Offset;
878 template <class ELFT>
879 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(Elf_Sym_Iter Sym) const {
880 if (!Sym.isDynamic())
881 return getSymbolName(dot_symtab_sec, &*Sym);
883 if (!DynStrRegion.Addr || Sym->st_name >= DynStrRegion.Size)
884 return object_error::parse_failed;
885 return StringRef(getDynamicString(Sym->st_name));
888 template <class ELFT>
889 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Shdr *Section,
890 const Elf_Sym *Symb) const {
891 if (Symb->st_name == 0) {
892 const Elf_Shdr *ContainingSec = getSection(Symb);
894 return getSectionName(ContainingSec);
897 const Elf_Shdr *StrTab = getSection(Section->sh_link);
898 if (Symb->st_name >= StrTab->sh_size)
899 return object_error::parse_failed;
900 return StringRef(getString(StrTab, Symb->st_name));
903 template <class ELFT>
905 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
906 if (Section->sh_name >= dot_shstrtab_sec->sh_size)
907 return object_error::parse_failed;
908 return StringRef(getString(dot_shstrtab_sec, Section->sh_name));
911 template <class ELFT>
912 ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
914 bool &IsDefault) const {
915 // Handle non-dynamic symbols.
916 if (section != DynSymRegion.Addr && section != 0) {
917 // Non-dynamic symbols can have versions in their names
918 // A name of the form 'foo@V1' indicates version 'V1', non-default.
919 // A name of the form 'foo@@V2' indicates version 'V2', default version.
920 ErrorOr<StringRef> SymName = getSymbolName(section, symb);
923 StringRef Name = *SymName;
924 size_t atpos = Name.find('@');
925 if (atpos == StringRef::npos) {
927 return StringRef("");
930 if (atpos < Name.size() && Name[atpos] == '@') {
936 return Name.substr(atpos);
939 // This is a dynamic symbol. Look in the GNU symbol version table.
940 if (dot_gnu_version_sec == NULL) {
943 return StringRef("");
946 // Determine the position in the symbol table of this entry.
947 size_t entry_index = ((const char *)symb - (const char *)DynSymRegion.Addr) /
948 DynSymRegion.EntSize;
950 // Get the corresponding version index entry
951 const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
952 size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
954 // Special markers for unversioned symbols.
955 if (version_index == ELF::VER_NDX_LOCAL ||
956 version_index == ELF::VER_NDX_GLOBAL) {
958 return StringRef("");
961 // Lookup this symbol in the version table
963 if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
964 return object_error::parse_failed;
965 const VersionMapEntry &entry = VersionMap[version_index];
967 // Get the version name string
969 if (entry.isVerdef()) {
970 // The first Verdaux entry holds the name.
971 name_offset = entry.getVerdef()->getAux()->vda_name;
973 name_offset = entry.getVernaux()->vna_name;
977 if (entry.isVerdef()) {
978 IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
983 if (name_offset >= DynStrRegion.Size)
984 return object_error::parse_failed;
985 return StringRef(getDynamicString(name_offset));
988 /// This function returns the hash value for a symbol in the .dynsym section
989 /// Name of the API remains consistent as specified in the libelf
990 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
991 static inline unsigned elf_hash(StringRef &symbolName) {
993 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
994 h = (h << 4) + symbolName[i];
1002 } // end namespace object
1003 } // end namespace llvm