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/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Object/ELFTypes.h"
21 #include "llvm/Object/Error.h"
22 #include "llvm/Support/ELF.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/Error.h"
34 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
36 // Subclasses of ELFFile may need this for template instantiation
37 inline std::pair<unsigned char, unsigned char>
38 getElfArchType(StringRef Object) {
39 if (Object.size() < ELF::EI_NIDENT)
40 return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
41 (uint8_t)ELF::ELFDATANONE);
42 return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
43 (uint8_t)Object[ELF::EI_DATA]);
46 static inline Error createError(StringRef Err) {
47 return make_error<StringError>(Err, object_error::parse_failed);
53 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
54 using uintX_t = typename ELFT::uint;
55 using Elf_Ehdr = typename ELFT::Ehdr;
56 using Elf_Shdr = typename ELFT::Shdr;
57 using Elf_Sym = typename ELFT::Sym;
58 using Elf_Dyn = typename ELFT::Dyn;
59 using Elf_Phdr = typename ELFT::Phdr;
60 using Elf_Rel = typename ELFT::Rel;
61 using Elf_Rela = typename ELFT::Rela;
62 using Elf_Verdef = typename ELFT::Verdef;
63 using Elf_Verdaux = typename ELFT::Verdaux;
64 using Elf_Verneed = typename ELFT::Verneed;
65 using Elf_Vernaux = typename ELFT::Vernaux;
66 using Elf_Versym = typename ELFT::Versym;
67 using Elf_Hash = typename ELFT::Hash;
68 using Elf_GnuHash = typename ELFT::GnuHash;
69 using Elf_Dyn_Range = typename ELFT::DynRange;
70 using Elf_Shdr_Range = typename ELFT::ShdrRange;
71 using Elf_Sym_Range = typename ELFT::SymRange;
72 using Elf_Rel_Range = typename ELFT::RelRange;
73 using Elf_Rela_Range = typename ELFT::RelaRange;
74 using Elf_Phdr_Range = typename ELFT::PhdrRange;
76 const uint8_t *base() const {
77 return reinterpret_cast<const uint8_t *>(Buf.data());
80 size_t getBufSize() const { return Buf.size(); }
86 const Elf_Ehdr *getHeader() const {
87 return reinterpret_cast<const Elf_Ehdr *>(base());
91 Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
93 Expected<const T *> getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
95 Expected<StringRef> getStringTable(const Elf_Shdr *Section) const;
96 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
97 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
98 Elf_Shdr_Range Sections) const;
100 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
101 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
102 Elf_Shdr_Range Sections) const;
104 void VerifyStrTab(const Elf_Shdr *sh) const;
106 StringRef getRelocationTypeName(uint32_t Type) const;
107 void getRelocationTypeName(uint32_t Type,
108 SmallVectorImpl<char> &Result) const;
110 /// \brief Get the symbol for a given relocation.
111 Expected<const Elf_Sym *> getRelocationSymbol(const Elf_Rel *Rel,
112 const Elf_Shdr *SymTab) const;
114 ELFFile(StringRef Object);
116 bool isMipsELF64() const {
117 return getHeader()->e_machine == ELF::EM_MIPS &&
118 getHeader()->getFileClass() == ELF::ELFCLASS64;
121 bool isMips64EL() const {
122 return isMipsELF64() &&
123 getHeader()->getDataEncoding() == ELF::ELFDATA2LSB;
126 Expected<Elf_Shdr_Range> sections() const;
128 Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
130 return makeArrayRef<Elf_Sym>(nullptr, nullptr);
131 return getSectionContentsAsArray<Elf_Sym>(Sec);
134 Expected<Elf_Rela_Range> relas(const Elf_Shdr *Sec) const {
135 return getSectionContentsAsArray<Elf_Rela>(Sec);
138 Expected<Elf_Rel_Range> rels(const Elf_Shdr *Sec) const {
139 return getSectionContentsAsArray<Elf_Rel>(Sec);
142 /// \brief Iterate over program header table.
143 Expected<Elf_Phdr_Range> program_headers() const {
144 if (getHeader()->e_phnum && getHeader()->e_phentsize != sizeof(Elf_Phdr))
145 return createError("invalid e_phentsize");
147 reinterpret_cast<const Elf_Phdr *>(base() + getHeader()->e_phoff);
148 return makeArrayRef(Begin, Begin + getHeader()->e_phnum);
151 Expected<StringRef> getSectionStringTable(Elf_Shdr_Range Sections) const;
152 Expected<uint32_t> getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
153 ArrayRef<Elf_Word> ShndxTable) const;
154 Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
155 const Elf_Shdr *SymTab,
156 ArrayRef<Elf_Word> ShndxTable) const;
157 Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
158 Elf_Sym_Range Symtab,
159 ArrayRef<Elf_Word> ShndxTable) const;
160 Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
162 Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
163 uint32_t Index) const;
165 Expected<StringRef> getSectionName(const Elf_Shdr *Section) const;
166 Expected<StringRef> getSectionName(const Elf_Shdr *Section,
167 StringRef DotShstrtab) const;
168 template <typename T>
169 Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr *Sec) const;
170 Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr *Sec) const;
173 using ELF32LEFile = ELFFile<ELFType<support::little, false>>;
174 using ELF64LEFile = ELFFile<ELFType<support::little, true>>;
175 using ELF32BEFile = ELFFile<ELFType<support::big, false>>;
176 using ELF64BEFile = ELFFile<ELFType<support::big, true>>;
178 template <class ELFT>
179 inline Expected<const typename ELFT::Shdr *>
180 getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
181 if (Index >= Sections.size())
182 return createError("invalid section index");
183 return &Sections[Index];
186 template <class ELFT>
187 inline Expected<uint32_t>
188 getExtendedSymbolTableIndex(const typename ELFT::Sym *Sym,
189 const typename ELFT::Sym *FirstSym,
190 ArrayRef<typename ELFT::Word> ShndxTable) {
191 assert(Sym->st_shndx == ELF::SHN_XINDEX);
192 unsigned Index = Sym - FirstSym;
193 if (Index >= ShndxTable.size())
194 return createError("index past the end of the symbol table");
196 // The size of the table was checked in getSHNDXTable.
197 return ShndxTable[Index];
200 template <class ELFT>
202 ELFFile<ELFT>::getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
203 ArrayRef<Elf_Word> ShndxTable) const {
204 uint32_t Index = Sym->st_shndx;
205 if (Index == ELF::SHN_XINDEX) {
206 auto ErrorOrIndex = getExtendedSymbolTableIndex<ELFT>(
207 Sym, Syms.begin(), ShndxTable);
209 return ErrorOrIndex.takeError();
210 return *ErrorOrIndex;
212 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
217 template <class ELFT>
218 Expected<const typename ELFT::Shdr *>
219 ELFFile<ELFT>::getSection(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
220 ArrayRef<Elf_Word> ShndxTable) const {
221 auto SymsOrErr = symbols(SymTab);
223 return SymsOrErr.takeError();
224 return getSection(Sym, *SymsOrErr, ShndxTable);
227 template <class ELFT>
228 Expected<const typename ELFT::Shdr *>
229 ELFFile<ELFT>::getSection(const Elf_Sym *Sym, Elf_Sym_Range Symbols,
230 ArrayRef<Elf_Word> ShndxTable) const {
231 auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
233 return IndexOrErr.takeError();
234 uint32_t Index = *IndexOrErr;
237 auto SectionsOrErr = sections();
239 return SectionsOrErr.takeError();
240 return object::getSection<ELFT>(*SectionsOrErr, Index);
243 template <class ELFT>
244 inline Expected<const typename ELFT::Sym *>
245 getSymbol(typename ELFT::SymRange Symbols, uint32_t Index) {
246 if (Index >= Symbols.size())
247 return createError("invalid symbol index");
248 return &Symbols[Index];
251 template <class ELFT>
252 Expected<const typename ELFT::Sym *>
253 ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
254 auto SymtabOrErr = symbols(Sec);
256 return SymtabOrErr.takeError();
257 return object::getSymbol<ELFT>(*SymtabOrErr, Index);
260 template <class ELFT>
261 template <typename T>
262 Expected<ArrayRef<T>>
263 ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr *Sec) const {
264 if (Sec->sh_entsize != sizeof(T) && sizeof(T) != 1)
265 return createError("invalid sh_entsize");
267 uintX_t Offset = Sec->sh_offset;
268 uintX_t Size = Sec->sh_size;
270 if (Size % sizeof(T))
271 return createError("size is not a multiple of sh_entsize");
272 if ((std::numeric_limits<uintX_t>::max() - Offset < Size) ||
273 Offset + Size > Buf.size())
274 return createError("invalid section offset");
276 const T *Start = reinterpret_cast<const T *>(base() + Offset);
277 return makeArrayRef(Start, Size / sizeof(T));
280 template <class ELFT>
281 Expected<ArrayRef<uint8_t>>
282 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
283 return getSectionContentsAsArray<uint8_t>(Sec);
286 template <class ELFT>
287 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
288 return getELFRelocationTypeName(getHeader()->e_machine, Type);
291 template <class ELFT>
292 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
293 SmallVectorImpl<char> &Result) const {
294 if (!isMipsELF64()) {
295 StringRef Name = getRelocationTypeName(Type);
296 Result.append(Name.begin(), Name.end());
298 // The Mips N64 ABI allows up to three operations to be specified per
299 // relocation record. Unfortunately there's no easy way to test for the
300 // presence of N64 ELFs as they have no special flag that identifies them
301 // as being N64. We can safely assume at the moment that all Mips
302 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
303 // information to disambiguate between old vs new ABIs.
304 uint8_t Type1 = (Type >> 0) & 0xFF;
305 uint8_t Type2 = (Type >> 8) & 0xFF;
306 uint8_t Type3 = (Type >> 16) & 0xFF;
308 // Concat all three relocation type names.
309 StringRef Name = getRelocationTypeName(Type1);
310 Result.append(Name.begin(), Name.end());
312 Name = getRelocationTypeName(Type2);
313 Result.append(1, '/');
314 Result.append(Name.begin(), Name.end());
316 Name = getRelocationTypeName(Type3);
317 Result.append(1, '/');
318 Result.append(Name.begin(), Name.end());
322 template <class ELFT>
323 Expected<const typename ELFT::Sym *>
324 ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
325 const Elf_Shdr *SymTab) const {
326 uint32_t Index = Rel->getSymbol(isMips64EL());
329 return getEntry<Elf_Sym>(SymTab, Index);
332 template <class ELFT>
334 ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections) const {
335 uint32_t Index = getHeader()->e_shstrndx;
336 if (Index == ELF::SHN_XINDEX)
337 Index = Sections[0].sh_link;
339 if (!Index) // no section string table.
341 if (Index >= Sections.size())
342 return createError("invalid section index");
343 return getStringTable(&Sections[Index]);
346 template <class ELFT>
347 ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {
348 assert(sizeof(Elf_Ehdr) <= Buf.size() && "Invalid buffer");
351 template <class ELFT>
352 bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
353 return VAddr < Phdr->p_vaddr;
356 template <class ELFT>
357 Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
358 const uintX_t SectionTableOffset = getHeader()->e_shoff;
359 if (SectionTableOffset == 0)
360 return ArrayRef<Elf_Shdr>();
362 if (getHeader()->e_shentsize != sizeof(Elf_Shdr))
364 "invalid section header entry size (e_shentsize) in ELF header");
366 const uint64_t FileSize = Buf.size();
368 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
369 return createError("section header table goes past the end of the file");
371 // Invalid address alignment of section headers
372 if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
373 return createError("invalid alignment of section headers");
375 const Elf_Shdr *First =
376 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
378 uintX_t NumSections = getHeader()->e_shnum;
379 if (NumSections == 0)
380 NumSections = First->sh_size;
382 if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
383 return createError("section table goes past the end of file");
385 const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
387 // Section table goes past end of file!
388 if (SectionTableOffset + SectionTableSize > FileSize)
389 return createError("section table goes past the end of file");
391 return makeArrayRef(First, NumSections);
394 template <class ELFT>
395 template <typename T>
396 Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
397 uint32_t Entry) const {
398 auto SecOrErr = getSection(Section);
400 return SecOrErr.takeError();
401 return getEntry<T>(*SecOrErr, Entry);
404 template <class ELFT>
405 template <typename T>
406 Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
407 uint32_t Entry) const {
408 if (sizeof(T) != Section->sh_entsize)
409 return createError("invalid sh_entsize");
410 size_t Pos = Section->sh_offset + Entry * sizeof(T);
411 if (Pos + sizeof(T) > Buf.size())
412 return createError("invalid section offset");
413 return reinterpret_cast<const T *>(base() + Pos);
416 template <class ELFT>
417 Expected<const typename ELFT::Shdr *>
418 ELFFile<ELFT>::getSection(uint32_t Index) const {
419 auto TableOrErr = sections();
421 return TableOrErr.takeError();
422 return object::getSection<ELFT>(*TableOrErr, Index);
425 template <class ELFT>
427 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
428 if (Section->sh_type != ELF::SHT_STRTAB)
429 return createError("invalid sh_type for string table, expected SHT_STRTAB");
430 auto V = getSectionContentsAsArray<char>(Section);
432 return V.takeError();
433 ArrayRef<char> Data = *V;
435 return createError("empty string table");
436 if (Data.back() != '\0')
437 return createError("string table non-null terminated");
438 return StringRef(Data.begin(), Data.size());
441 template <class ELFT>
442 Expected<ArrayRef<typename ELFT::Word>>
443 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
444 auto SectionsOrErr = sections();
446 return SectionsOrErr.takeError();
447 return getSHNDXTable(Section, *SectionsOrErr);
450 template <class ELFT>
451 Expected<ArrayRef<typename ELFT::Word>>
452 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
453 Elf_Shdr_Range Sections) const {
454 assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
455 auto VOrErr = getSectionContentsAsArray<Elf_Word>(&Section);
457 return VOrErr.takeError();
458 ArrayRef<Elf_Word> V = *VOrErr;
459 auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
461 return SymTableOrErr.takeError();
462 const Elf_Shdr &SymTable = **SymTableOrErr;
463 if (SymTable.sh_type != ELF::SHT_SYMTAB &&
464 SymTable.sh_type != ELF::SHT_DYNSYM)
465 return createError("invalid sh_type");
466 if (V.size() != (SymTable.sh_size / sizeof(Elf_Sym)))
467 return createError("invalid section contents size");
471 template <class ELFT>
473 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
474 auto SectionsOrErr = sections();
476 return SectionsOrErr.takeError();
477 return getStringTableForSymtab(Sec, *SectionsOrErr);
480 template <class ELFT>
482 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
483 Elf_Shdr_Range Sections) const {
485 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
487 "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
488 auto SectionOrErr = object::getSection<ELFT>(Sections, Sec.sh_link);
490 return SectionOrErr.takeError();
491 return getStringTable(*SectionOrErr);
494 template <class ELFT>
496 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
497 auto SectionsOrErr = sections();
499 return SectionsOrErr.takeError();
500 auto Table = getSectionStringTable(*SectionsOrErr);
502 return Table.takeError();
503 return getSectionName(Section, *Table);
506 template <class ELFT>
507 Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section,
508 StringRef DotShstrtab) const {
509 uint32_t Offset = Section->sh_name;
512 if (Offset >= DotShstrtab.size())
513 return createError("invalid string offset");
514 return StringRef(DotShstrtab.data() + Offset);
517 /// This function returns the hash value for a symbol in the .dynsym section
518 /// Name of the API remains consistent as specified in the libelf
519 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
520 inline unsigned hashSysV(StringRef SymbolName) {
522 for (char C : SymbolName) {
532 } // end namespace object
533 } // end namespace llvm
535 #endif // LLVM_OBJECT_ELF_H