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 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
59 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
60 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
61 typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
62 typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
63 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
64 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
65 typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
66 typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
67 typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
68 typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
69 typedef Elf_Versym_Impl<ELFT> Elf_Versym;
70 typedef Elf_Hash_Impl<ELFT> Elf_Hash;
71 typedef iterator_range<const Elf_Dyn *> Elf_Dyn_Range;
72 typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
74 /// \brief Archive files are 2 byte aligned, so we need this for
75 /// PointerIntPair to work.
77 class ArchivePointerTypeTraits {
79 static inline const void *getAsVoidPointer(T *P) { return P; }
80 static inline T *getFromVoidPointer(const void *P) {
81 return static_cast<T *>(P);
83 enum { NumLowBitsAvailable = 1 };
86 typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
88 const uint8_t *base() const {
89 return reinterpret_cast<const uint8_t *>(Buf.data());
93 typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
97 const Elf_Ehdr *Header;
98 const Elf_Shdr *SectionHeaderTable = nullptr;
99 StringRef DotShstrtab; // Section header string table.
100 StringRef DotStrtab; // Symbol header string table.
101 const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
102 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
104 const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
105 DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
109 const T *getEntry(uint32_t Section, uint32_t Entry) const;
110 template <typename T>
111 const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
113 const Elf_Shdr *getDotSymtabSec() const { return dot_symtab_sec; }
114 const Elf_Shdr *getDotDynSymSec() const { return DotDynSymSec; }
116 ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
117 ErrorOr<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
119 void VerifyStrTab(const Elf_Shdr *sh) const;
121 StringRef getRelocationTypeName(uint32_t Type) const;
122 void getRelocationTypeName(uint32_t Type,
123 SmallVectorImpl<char> &Result) const;
125 /// \brief Get the symbol table section and symbol for a given relocation.
126 template <class RelT>
127 std::pair<const Elf_Shdr *, const Elf_Sym *>
128 getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
130 ELFFile(StringRef Object, std::error_code &EC);
132 bool isMipsELF64() const {
133 return Header->e_machine == ELF::EM_MIPS &&
134 Header->getFileClass() == ELF::ELFCLASS64;
137 bool isMips64EL() const {
138 return Header->e_machine == ELF::EM_MIPS &&
139 Header->getFileClass() == ELF::ELFCLASS64 &&
140 Header->getDataEncoding() == ELF::ELFDATA2LSB;
143 ErrorOr<const Elf_Dyn *> dynamic_table_begin(const Elf_Phdr *Phdr) const;
144 ErrorOr<const Elf_Dyn *> dynamic_table_end(const Elf_Phdr *Phdr) const;
145 ErrorOr<Elf_Dyn_Range> dynamic_table(const Elf_Phdr *Phdr) const {
146 ErrorOr<const Elf_Dyn *> Begin = dynamic_table_begin(Phdr);
147 if (std::error_code EC = Begin.getError())
149 ErrorOr<const Elf_Dyn *> End = dynamic_table_end(Phdr);
150 if (std::error_code EC = End.getError())
152 return make_range(*Begin, *End);
155 const Elf_Shdr *section_begin() const;
156 const Elf_Shdr *section_end() const;
157 Elf_Shdr_Range sections() const {
158 return make_range(section_begin(), section_end());
161 const Elf_Sym *symbol_begin(const Elf_Shdr *Sec) const {
164 if (Sec->sh_entsize != sizeof(Elf_Sym))
165 report_fatal_error("Invalid symbol size");
166 return reinterpret_cast<const Elf_Sym *>(base() + Sec->sh_offset);
168 const Elf_Sym *symbol_end(const Elf_Shdr *Sec) const {
171 uint64_t Size = Sec->sh_size;
172 if (Size % sizeof(Elf_Sym))
173 report_fatal_error("Invalid symbol table size");
174 return symbol_begin(Sec) + Size / sizeof(Elf_Sym);
176 Elf_Sym_Range symbols(const Elf_Shdr *Sec) const {
177 return make_range(symbol_begin(Sec), symbol_end(Sec));
180 const Elf_Sym *symbol_begin() const { return symbol_begin(dot_symtab_sec); }
181 const Elf_Sym *symbol_end() const { return symbol_end(dot_symtab_sec); }
182 Elf_Sym_Range symbols() const { return symbols(dot_symtab_sec); }
184 const Elf_Sym *dynamic_symbol_begin() const {
185 return symbol_begin(DotDynSymSec);
187 const Elf_Sym *dynamic_symbol_end() const { return symbol_end(DotDynSymSec); }
188 Elf_Sym_Range dynamic_symbols() const { return symbols(DotDynSymSec); }
190 typedef iterator_range<const Elf_Rela *> Elf_Rela_Range;
192 const Elf_Rela *rela_begin(const Elf_Shdr *sec) const {
193 if (sec->sh_entsize != sizeof(Elf_Rela))
194 report_fatal_error("Invalid relocation entry size");
195 return reinterpret_cast<const Elf_Rela *>(base() + sec->sh_offset);
198 const Elf_Rela *rela_end(const Elf_Shdr *sec) const {
199 uint64_t Size = sec->sh_size;
200 if (Size % sizeof(Elf_Rela))
201 report_fatal_error("Invalid relocation table size");
202 return rela_begin(sec) + Size / sizeof(Elf_Rela);
205 Elf_Rela_Range relas(const Elf_Shdr *Sec) const {
206 return make_range(rela_begin(Sec), rela_end(Sec));
209 const Elf_Rel *rel_begin(const Elf_Shdr *sec) const {
210 if (sec->sh_entsize != sizeof(Elf_Rel))
211 report_fatal_error("Invalid relocation entry size");
212 return reinterpret_cast<const Elf_Rel *>(base() + sec->sh_offset);
215 const Elf_Rel *rel_end(const Elf_Shdr *sec) const {
216 uint64_t Size = sec->sh_size;
217 if (Size % sizeof(Elf_Rel))
218 report_fatal_error("Invalid relocation table size");
219 return rel_begin(sec) + Size / sizeof(Elf_Rel);
222 typedef iterator_range<const Elf_Rel *> Elf_Rel_Range;
223 Elf_Rel_Range rels(const Elf_Shdr *Sec) const {
224 return make_range(rel_begin(Sec), rel_end(Sec));
227 /// \brief Iterate over program header table.
228 const Elf_Phdr *program_header_begin() const {
229 if (Header->e_phnum && Header->e_phentsize != sizeof(Elf_Phdr))
230 report_fatal_error("Invalid program header size");
231 return reinterpret_cast<const Elf_Phdr *>(base() + Header->e_phoff);
234 const Elf_Phdr *program_header_end() const {
235 return program_header_begin() + Header->e_phnum;
238 typedef iterator_range<const Elf_Phdr *> Elf_Phdr_Range;
240 const Elf_Phdr_Range program_headers() const {
241 return make_range(program_header_begin(), program_header_end());
244 uint64_t getNumSections() const;
245 uintX_t getStringTableIndex() const;
246 ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
247 const Elf_Ehdr *getHeader() const { return Header; }
248 ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
249 ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
251 const Elf_Sym *getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
252 return &*(symbol_begin(Sec) + Index);
255 ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
256 ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
259 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
260 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
261 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
262 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
264 template <class ELFT>
266 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
267 assert(symb->st_shndx == ELF::SHN_XINDEX);
268 return ExtendedSymbolTable.lookup(symb);
271 template <class ELFT>
272 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
273 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
274 uint32_t Index = symb->st_shndx;
275 if (Index == ELF::SHN_XINDEX)
276 return getSection(ExtendedSymbolTable.lookup(symb));
277 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
279 return getSection(symb->st_shndx);
282 template <class ELFT>
283 ErrorOr<ArrayRef<uint8_t> >
284 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
285 if (Sec->sh_offset + Sec->sh_size > Buf.size())
286 return object_error::parse_failed;
287 const uint8_t *Start = base() + Sec->sh_offset;
288 return makeArrayRef(Start, Sec->sh_size);
291 template <class ELFT>
292 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
293 return getELFRelocationTypeName(Header->e_machine, Type);
296 template <class ELFT>
297 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
298 SmallVectorImpl<char> &Result) const {
299 if (!isMipsELF64()) {
300 StringRef Name = getRelocationTypeName(Type);
301 Result.append(Name.begin(), Name.end());
303 // The Mips N64 ABI allows up to three operations to be specified per
304 // relocation record. Unfortunately there's no easy way to test for the
305 // presence of N64 ELFs as they have no special flag that identifies them
306 // as being N64. We can safely assume at the moment that all Mips
307 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
308 // information to disambiguate between old vs new ABIs.
309 uint8_t Type1 = (Type >> 0) & 0xFF;
310 uint8_t Type2 = (Type >> 8) & 0xFF;
311 uint8_t Type3 = (Type >> 16) & 0xFF;
313 // Concat all three relocation type names.
314 StringRef Name = getRelocationTypeName(Type1);
315 Result.append(Name.begin(), Name.end());
317 Name = getRelocationTypeName(Type2);
318 Result.append(1, '/');
319 Result.append(Name.begin(), Name.end());
321 Name = getRelocationTypeName(Type3);
322 Result.append(1, '/');
323 Result.append(Name.begin(), Name.end());
327 template <class ELFT>
328 template <class RelT>
329 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
330 const typename ELFFile<ELFT>::Elf_Sym *>
331 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
333 return std::make_pair(nullptr, nullptr);
334 ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
335 if (std::error_code EC = SymTableOrErr.getError())
336 report_fatal_error(EC.message());
337 const Elf_Shdr *SymTable = *SymTableOrErr;
338 return std::make_pair(
339 SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
342 template <class ELFT>
343 uint64_t ELFFile<ELFT>::getNumSections() const {
344 assert(Header && "Header not initialized!");
345 if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
346 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
347 return SectionHeaderTable->sh_size;
349 return Header->e_shnum;
352 template <class ELFT>
353 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
354 if (Header->e_shnum == ELF::SHN_UNDEF) {
355 if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
356 return SectionHeaderTable->sh_link;
357 if (Header->e_shstrndx >= getNumSections())
360 return Header->e_shstrndx;
363 template <class ELFT>
364 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
366 const uint64_t FileSize = Buf.size();
368 if (sizeof(Elf_Ehdr) > FileSize) {
370 EC = object_error::parse_failed;
374 Header = reinterpret_cast<const Elf_Ehdr *>(base());
376 if (Header->e_shoff == 0)
379 const uint64_t SectionTableOffset = Header->e_shoff;
381 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
382 // Section header table goes past end of file!
383 EC = object_error::parse_failed;
387 // The getNumSections() call below depends on SectionHeaderTable being set.
389 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
390 const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
392 if (SectionTableOffset + SectionTableSize > FileSize) {
393 // Section table goes past end of file!
394 EC = object_error::parse_failed;
398 // Scan sections for special sections.
400 for (const Elf_Shdr &Sec : sections()) {
401 switch (Sec.sh_type) {
402 case ELF::SHT_SYMTAB_SHNDX:
403 if (SymbolTableSectionHeaderIndex) {
404 // More than one .symtab_shndx!
405 EC = object_error::parse_failed;
408 SymbolTableSectionHeaderIndex = &Sec;
410 case ELF::SHT_SYMTAB: {
411 if (dot_symtab_sec) {
412 // More than one .symtab!
413 EC = object_error::parse_failed;
416 dot_symtab_sec = &Sec;
417 ErrorOr<StringRef> SymtabOrErr = getStringTableForSymtab(Sec);
418 if ((EC = SymtabOrErr.getError()))
420 DotStrtab = *SymtabOrErr;
422 case ELF::SHT_DYNSYM: {
424 // More than one .dynsym!
425 EC = object_error::parse_failed;
434 // Get string table sections.
435 uintX_t StringTableIndex = getStringTableIndex();
436 if (StringTableIndex) {
437 ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(StringTableIndex);
438 if ((EC = StrTabSecOrErr.getError()))
441 ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
442 if ((EC = SymtabOrErr.getError()))
444 DotShstrtab = *SymtabOrErr;
447 // Build symbol name side-mapping if there is one.
448 if (SymbolTableSectionHeaderIndex) {
449 const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
450 SymbolTableSectionHeaderIndex->sh_offset);
451 for (const Elf_Sym &S : symbols()) {
452 if (*ShndxTable != ELF::SHN_UNDEF)
453 ExtendedSymbolTable[&S] = *ShndxTable;
458 EC = std::error_code();
461 template <class ELFT>
462 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
463 return VAddr < Phdr->p_vaddr;
466 template <class ELFT>
467 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
468 if (Header->e_shentsize != sizeof(Elf_Shdr))
470 "Invalid section header entry size (e_shentsize) in ELF header");
471 return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
474 template <class ELFT>
475 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
476 return section_begin() + getNumSections();
479 template <class ELFT>
480 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
481 ELFFile<ELFT>::dynamic_table_begin(const Elf_Phdr *Phdr) const {
484 assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
485 uintX_t Offset = Phdr->p_offset;
486 if (Offset > Buf.size())
487 return object_error::parse_failed;
488 return reinterpret_cast<const Elf_Dyn *>(base() + Offset);
491 template <class ELFT>
492 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
493 ELFFile<ELFT>::dynamic_table_end(const Elf_Phdr *Phdr) const {
496 assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
497 uintX_t Size = Phdr->p_filesz;
498 if (Size % sizeof(Elf_Dyn))
499 return object_error::elf_invalid_dynamic_table_size;
500 // FIKME: Check for overflow?
501 uintX_t End = Phdr->p_offset + Size;
502 if (End > Buf.size())
503 return object_error::parse_failed;
504 return reinterpret_cast<const Elf_Dyn *>(base() + End);
507 template <class ELFT>
508 template <typename T>
509 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
510 ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
511 if (std::error_code EC = Sec.getError())
512 report_fatal_error(EC.message());
513 return getEntry<T>(*Sec, Entry);
516 template <class ELFT>
517 template <typename T>
518 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
519 uint32_t Entry) const {
520 return reinterpret_cast<const T *>(base() + Section->sh_offset +
521 (Entry * Section->sh_entsize));
524 template <class ELFT>
525 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
526 ELFFile<ELFT>::getSection(uint32_t Index) const {
527 assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
528 if (Index >= getNumSections())
529 return object_error::invalid_section_index;
531 return reinterpret_cast<const Elf_Shdr *>(
532 reinterpret_cast<const char *>(SectionHeaderTable) +
533 (Index * Header->e_shentsize));
536 template <class ELFT>
538 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
539 if (Section->sh_type != ELF::SHT_STRTAB)
540 return object_error::parse_failed;
541 uint64_t Offset = Section->sh_offset;
542 uint64_t Size = Section->sh_size;
543 if (Offset + Size > Buf.size())
544 return object_error::parse_failed;
545 StringRef Data((const char *)base() + Section->sh_offset, Size);
546 if (Data[Size - 1] != '\0')
547 return object_error::string_table_non_null_end;
551 template <class ELFT>
553 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
554 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
555 return object_error::parse_failed;
556 ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
557 if (std::error_code EC = SectionOrErr.getError())
559 return getStringTable(*SectionOrErr);
562 template <class ELFT>
564 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
565 uint32_t Offset = Section->sh_name;
568 if (Offset >= DotShstrtab.size())
569 return object_error::parse_failed;
570 return StringRef(DotShstrtab.data() + Offset);
573 /// This function returns the hash value for a symbol in the .dynsym section
574 /// Name of the API remains consistent as specified in the libelf
575 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
576 static inline unsigned elf_hash(StringRef &symbolName) {
578 for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
579 h = (h << 4) + symbolName[i];
587 } // end namespace object
588 } // end namespace llvm