]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Object/ELF.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Object / ELF.h
1 //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the ELFFile template class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_OBJECT_ELF_H
15 #define LLVM_OBJECT_ELF_H
16
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"
25 #include <cassert>
26 #include <cstddef>
27 #include <cstdint>
28 #include <limits>
29 #include <utility>
30
31 namespace llvm {
32 namespace object {
33
34 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
35
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]);
44 }
45
46 static inline Error createError(StringRef Err) {
47   return make_error<StringError>(Err, object_error::parse_failed);
48 }
49
50 template <class ELFT>
51 class ELFFile {
52 public:
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;
75
76   const uint8_t *base() const {
77     return reinterpret_cast<const uint8_t *>(Buf.data());
78   }
79
80   size_t getBufSize() const { return Buf.size(); }
81
82 private:
83   StringRef Buf;
84
85 public:
86   const Elf_Ehdr *getHeader() const {
87     return reinterpret_cast<const Elf_Ehdr *>(base());
88   }
89
90   template <typename T>
91   Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
92   template <typename T>
93   Expected<const T *> getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
94
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;
99
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;
103
104   void VerifyStrTab(const Elf_Shdr *sh) const;
105
106   StringRef getRelocationTypeName(uint32_t Type) const;
107   void getRelocationTypeName(uint32_t Type,
108                              SmallVectorImpl<char> &Result) const;
109
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;
113
114   ELFFile(StringRef Object);
115
116   bool isMipsELF64() const {
117     return getHeader()->e_machine == ELF::EM_MIPS &&
118            getHeader()->getFileClass() == ELF::ELFCLASS64;
119   }
120
121   bool isMips64EL() const {
122     return isMipsELF64() &&
123            getHeader()->getDataEncoding() == ELF::ELFDATA2LSB;
124   }
125
126   Expected<Elf_Shdr_Range> sections() const;
127
128   Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
129     if (!Sec)
130       return makeArrayRef<Elf_Sym>(nullptr, nullptr);
131     return getSectionContentsAsArray<Elf_Sym>(Sec);
132   }
133
134   Expected<Elf_Rela_Range> relas(const Elf_Shdr *Sec) const {
135     return getSectionContentsAsArray<Elf_Rela>(Sec);
136   }
137
138   Expected<Elf_Rel_Range> rels(const Elf_Shdr *Sec) const {
139     return getSectionContentsAsArray<Elf_Rel>(Sec);
140   }
141
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");
146     auto *Begin =
147         reinterpret_cast<const Elf_Phdr *>(base() + getHeader()->e_phoff);
148     return makeArrayRef(Begin, Begin + getHeader()->e_phnum);
149   }
150
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;
161
162   Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
163                                       uint32_t Index) const;
164
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;
171 };
172
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>>;
177
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];
184 }
185
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");
195
196   // The size of the table was checked in getSHNDXTable.
197   return ShndxTable[Index];
198 }
199
200 template <class ELFT>
201 Expected<uint32_t>
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);
208     if (!ErrorOrIndex)
209       return ErrorOrIndex.takeError();
210     return *ErrorOrIndex;
211   }
212   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
213     return 0;
214   return Index;
215 }
216
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);
222   if (!SymsOrErr)
223     return SymsOrErr.takeError();
224   return getSection(Sym, *SymsOrErr, ShndxTable);
225 }
226
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);
232   if (!IndexOrErr)
233     return IndexOrErr.takeError();
234   uint32_t Index = *IndexOrErr;
235   if (Index == 0)
236     return nullptr;
237   auto SectionsOrErr = sections();
238   if (!SectionsOrErr)
239     return SectionsOrErr.takeError();
240   return object::getSection<ELFT>(*SectionsOrErr, Index);
241 }
242
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];
249 }
250
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);
255   if (!SymtabOrErr)
256     return SymtabOrErr.takeError();
257   return object::getSymbol<ELFT>(*SymtabOrErr, Index);
258 }
259
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");
266
267   uintX_t Offset = Sec->sh_offset;
268   uintX_t Size = Sec->sh_size;
269
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");
275
276   const T *Start = reinterpret_cast<const T *>(base() + Offset);
277   return makeArrayRef(Start, Size / sizeof(T));
278 }
279
280 template <class ELFT>
281 Expected<ArrayRef<uint8_t>>
282 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
283   return getSectionContentsAsArray<uint8_t>(Sec);
284 }
285
286 template <class ELFT>
287 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
288   return getELFRelocationTypeName(getHeader()->e_machine, Type);
289 }
290
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());
297   } else {
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;
307
308     // Concat all three relocation type names.
309     StringRef Name = getRelocationTypeName(Type1);
310     Result.append(Name.begin(), Name.end());
311
312     Name = getRelocationTypeName(Type2);
313     Result.append(1, '/');
314     Result.append(Name.begin(), Name.end());
315
316     Name = getRelocationTypeName(Type3);
317     Result.append(1, '/');
318     Result.append(Name.begin(), Name.end());
319   }
320 }
321
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());
327   if (Index == 0)
328     return nullptr;
329   return getEntry<Elf_Sym>(SymTab, Index);
330 }
331
332 template <class ELFT>
333 Expected<StringRef>
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;
338
339   if (!Index) // no section string table.
340     return "";
341   if (Index >= Sections.size())
342     return createError("invalid section index");
343   return getStringTable(&Sections[Index]);
344 }
345
346 template <class ELFT>
347 ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {
348   assert(sizeof(Elf_Ehdr) <= Buf.size() && "Invalid buffer");
349 }
350
351 template <class ELFT>
352 bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
353   return VAddr < Phdr->p_vaddr;
354 }
355
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>();
361
362   if (getHeader()->e_shentsize != sizeof(Elf_Shdr))
363     return createError(
364         "invalid section header entry size (e_shentsize) in ELF header");
365
366   const uint64_t FileSize = Buf.size();
367
368   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
369     return createError("section header table goes past the end of the file");
370
371   // Invalid address alignment of section headers
372   if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
373     return createError("invalid alignment of section headers");
374
375   const Elf_Shdr *First =
376       reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
377
378   uintX_t NumSections = getHeader()->e_shnum;
379   if (NumSections == 0)
380     NumSections = First->sh_size;
381
382   if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
383     return createError("section table goes past the end of file");
384
385   const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
386
387   // Section table goes past end of file!
388   if (SectionTableOffset + SectionTableSize > FileSize)
389     return createError("section table goes past the end of file");
390
391   return makeArrayRef(First, NumSections);
392 }
393
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);
399   if (!SecOrErr)
400     return SecOrErr.takeError();
401   return getEntry<T>(*SecOrErr, Entry);
402 }
403
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);
414 }
415
416 template <class ELFT>
417 Expected<const typename ELFT::Shdr *>
418 ELFFile<ELFT>::getSection(uint32_t Index) const {
419   auto TableOrErr = sections();
420   if (!TableOrErr)
421     return TableOrErr.takeError();
422   return object::getSection<ELFT>(*TableOrErr, Index);
423 }
424
425 template <class ELFT>
426 Expected<StringRef>
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);
431   if (!V)
432     return V.takeError();
433   ArrayRef<char> Data = *V;
434   if (Data.empty())
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());
439 }
440
441 template <class ELFT>
442 Expected<ArrayRef<typename ELFT::Word>>
443 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
444   auto SectionsOrErr = sections();
445   if (!SectionsOrErr)
446     return SectionsOrErr.takeError();
447   return getSHNDXTable(Section, *SectionsOrErr);
448 }
449
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);
456   if (!VOrErr)
457     return VOrErr.takeError();
458   ArrayRef<Elf_Word> V = *VOrErr;
459   auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
460   if (!SymTableOrErr)
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");
468   return V;
469 }
470
471 template <class ELFT>
472 Expected<StringRef>
473 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
474   auto SectionsOrErr = sections();
475   if (!SectionsOrErr)
476     return SectionsOrErr.takeError();
477   return getStringTableForSymtab(Sec, *SectionsOrErr);
478 }
479
480 template <class ELFT>
481 Expected<StringRef>
482 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
483                                        Elf_Shdr_Range Sections) const {
484
485   if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
486     return createError(
487         "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
488   auto SectionOrErr = object::getSection<ELFT>(Sections, Sec.sh_link);
489   if (!SectionOrErr)
490     return SectionOrErr.takeError();
491   return getStringTable(*SectionOrErr);
492 }
493
494 template <class ELFT>
495 Expected<StringRef>
496 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
497   auto SectionsOrErr = sections();
498   if (!SectionsOrErr)
499     return SectionsOrErr.takeError();
500   auto Table = getSectionStringTable(*SectionsOrErr);
501   if (!Table)
502     return Table.takeError();
503   return getSectionName(Section, *Table);
504 }
505
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;
510   if (Offset == 0)
511     return StringRef();
512   if (Offset >= DotShstrtab.size())
513     return createError("invalid string offset");
514   return StringRef(DotShstrtab.data() + Offset);
515 }
516
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) {
521   unsigned h = 0, g;
522   for (char C : SymbolName) {
523     h = (h << 4) + C;
524     g = h & 0xf0000000L;
525     if (g != 0)
526       h ^= g >> 24;
527     h &= ~g;
528   }
529   return h;
530 }
531
532 } // end namespace object
533 } // end namespace llvm
534
535 #endif // LLVM_OBJECT_ELF_H