]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Object/ELF.h
Merge ^/head r317971 through r318379.
[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 StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type);
36
37 // Subclasses of ELFFile may need this for template instantiation
38 inline std::pair<unsigned char, unsigned char>
39 getElfArchType(StringRef Object) {
40   if (Object.size() < ELF::EI_NIDENT)
41     return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
42                           (uint8_t)ELF::ELFDATANONE);
43   return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
44                         (uint8_t)Object[ELF::EI_DATA]);
45 }
46
47 static inline Error createError(StringRef Err) {
48   return make_error<StringError>(Err, object_error::parse_failed);
49 }
50
51 template <class ELFT>
52 class ELFFile {
53 public:
54   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
55   using uintX_t = typename ELFT::uint;
56   using Elf_Ehdr = typename ELFT::Ehdr;
57   using Elf_Shdr = typename ELFT::Shdr;
58   using Elf_Sym = typename ELFT::Sym;
59   using Elf_Dyn = typename ELFT::Dyn;
60   using Elf_Phdr = typename ELFT::Phdr;
61   using Elf_Rel = typename ELFT::Rel;
62   using Elf_Rela = typename ELFT::Rela;
63   using Elf_Verdef = typename ELFT::Verdef;
64   using Elf_Verdaux = typename ELFT::Verdaux;
65   using Elf_Verneed = typename ELFT::Verneed;
66   using Elf_Vernaux = typename ELFT::Vernaux;
67   using Elf_Versym = typename ELFT::Versym;
68   using Elf_Hash = typename ELFT::Hash;
69   using Elf_GnuHash = typename ELFT::GnuHash;
70   using Elf_Dyn_Range = typename ELFT::DynRange;
71   using Elf_Shdr_Range = typename ELFT::ShdrRange;
72   using Elf_Sym_Range = typename ELFT::SymRange;
73   using Elf_Rel_Range = typename ELFT::RelRange;
74   using Elf_Rela_Range = typename ELFT::RelaRange;
75   using Elf_Phdr_Range = typename ELFT::PhdrRange;
76
77   const uint8_t *base() const {
78     return reinterpret_cast<const uint8_t *>(Buf.data());
79   }
80
81   size_t getBufSize() const { return Buf.size(); }
82
83 private:
84   StringRef Buf;
85
86 public:
87   const Elf_Ehdr *getHeader() const {
88     return reinterpret_cast<const Elf_Ehdr *>(base());
89   }
90
91   template <typename T>
92   Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
93   template <typename T>
94   Expected<const T *> getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
95
96   Expected<StringRef> getStringTable(const Elf_Shdr *Section) const;
97   Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
98   Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
99                                               Elf_Shdr_Range Sections) const;
100
101   Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
102   Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
103                                              Elf_Shdr_Range Sections) const;
104
105   void VerifyStrTab(const Elf_Shdr *sh) const;
106
107   StringRef getRelocationTypeName(uint32_t Type) const;
108   void getRelocationTypeName(uint32_t Type,
109                              SmallVectorImpl<char> &Result) const;
110
111   /// \brief Get the symbol for a given relocation.
112   Expected<const Elf_Sym *> getRelocationSymbol(const Elf_Rel *Rel,
113                                                 const Elf_Shdr *SymTab) const;
114
115   ELFFile(StringRef Object);
116
117   bool isMipsELF64() const {
118     return getHeader()->e_machine == ELF::EM_MIPS &&
119            getHeader()->getFileClass() == ELF::ELFCLASS64;
120   }
121
122   bool isMips64EL() const {
123     return isMipsELF64() &&
124            getHeader()->getDataEncoding() == ELF::ELFDATA2LSB;
125   }
126
127   Expected<Elf_Shdr_Range> sections() const;
128
129   Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
130     if (!Sec)
131       return makeArrayRef<Elf_Sym>(nullptr, nullptr);
132     return getSectionContentsAsArray<Elf_Sym>(Sec);
133   }
134
135   Expected<Elf_Rela_Range> relas(const Elf_Shdr *Sec) const {
136     return getSectionContentsAsArray<Elf_Rela>(Sec);
137   }
138
139   Expected<Elf_Rel_Range> rels(const Elf_Shdr *Sec) const {
140     return getSectionContentsAsArray<Elf_Rel>(Sec);
141   }
142
143   /// \brief Iterate over program header table.
144   Expected<Elf_Phdr_Range> program_headers() const {
145     if (getHeader()->e_phnum && getHeader()->e_phentsize != sizeof(Elf_Phdr))
146       return createError("invalid e_phentsize");
147     auto *Begin =
148         reinterpret_cast<const Elf_Phdr *>(base() + getHeader()->e_phoff);
149     return makeArrayRef(Begin, Begin + getHeader()->e_phnum);
150   }
151
152   Expected<StringRef> getSectionStringTable(Elf_Shdr_Range Sections) const;
153   Expected<uint32_t> getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
154                                      ArrayRef<Elf_Word> ShndxTable) const;
155   Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
156                                         const Elf_Shdr *SymTab,
157                                         ArrayRef<Elf_Word> ShndxTable) const;
158   Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
159                                         Elf_Sym_Range Symtab,
160                                         ArrayRef<Elf_Word> ShndxTable) const;
161   Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
162
163   Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
164                                       uint32_t Index) const;
165
166   Expected<StringRef> getSectionName(const Elf_Shdr *Section) const;
167   Expected<StringRef> getSectionName(const Elf_Shdr *Section,
168                                      StringRef DotShstrtab) const;
169   template <typename T>
170   Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr *Sec) const;
171   Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr *Sec) const;
172 };
173
174 using ELF32LEFile = ELFFile<ELFType<support::little, false>>;
175 using ELF64LEFile = ELFFile<ELFType<support::little, true>>;
176 using ELF32BEFile = ELFFile<ELFType<support::big, false>>;
177 using ELF64BEFile = ELFFile<ELFType<support::big, true>>;
178
179 template <class ELFT>
180 inline Expected<const typename ELFT::Shdr *>
181 getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
182   if (Index >= Sections.size())
183     return createError("invalid section index");
184   return &Sections[Index];
185 }
186
187 template <class ELFT>
188 inline Expected<uint32_t>
189 getExtendedSymbolTableIndex(const typename ELFT::Sym *Sym,
190                             const typename ELFT::Sym *FirstSym,
191                             ArrayRef<typename ELFT::Word> ShndxTable) {
192   assert(Sym->st_shndx == ELF::SHN_XINDEX);
193   unsigned Index = Sym - FirstSym;
194   if (Index >= ShndxTable.size())
195     return createError("index past the end of the symbol table");
196
197   // The size of the table was checked in getSHNDXTable.
198   return ShndxTable[Index];
199 }
200
201 template <class ELFT>
202 Expected<uint32_t>
203 ELFFile<ELFT>::getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
204                                ArrayRef<Elf_Word> ShndxTable) const {
205   uint32_t Index = Sym->st_shndx;
206   if (Index == ELF::SHN_XINDEX) {
207     auto ErrorOrIndex = getExtendedSymbolTableIndex<ELFT>(
208         Sym, Syms.begin(), ShndxTable);
209     if (!ErrorOrIndex)
210       return ErrorOrIndex.takeError();
211     return *ErrorOrIndex;
212   }
213   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
214     return 0;
215   return Index;
216 }
217
218 template <class ELFT>
219 Expected<const typename ELFT::Shdr *>
220 ELFFile<ELFT>::getSection(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
221                           ArrayRef<Elf_Word> ShndxTable) const {
222   auto SymsOrErr = symbols(SymTab);
223   if (!SymsOrErr)
224     return SymsOrErr.takeError();
225   return getSection(Sym, *SymsOrErr, ShndxTable);
226 }
227
228 template <class ELFT>
229 Expected<const typename ELFT::Shdr *>
230 ELFFile<ELFT>::getSection(const Elf_Sym *Sym, Elf_Sym_Range Symbols,
231                           ArrayRef<Elf_Word> ShndxTable) const {
232   auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
233   if (!IndexOrErr)
234     return IndexOrErr.takeError();
235   uint32_t Index = *IndexOrErr;
236   if (Index == 0)
237     return nullptr;
238   auto SectionsOrErr = sections();
239   if (!SectionsOrErr)
240     return SectionsOrErr.takeError();
241   return object::getSection<ELFT>(*SectionsOrErr, Index);
242 }
243
244 template <class ELFT>
245 inline Expected<const typename ELFT::Sym *>
246 getSymbol(typename ELFT::SymRange Symbols, uint32_t Index) {
247   if (Index >= Symbols.size())
248     return createError("invalid symbol index");
249   return &Symbols[Index];
250 }
251
252 template <class ELFT>
253 Expected<const typename ELFT::Sym *>
254 ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
255   auto SymtabOrErr = symbols(Sec);
256   if (!SymtabOrErr)
257     return SymtabOrErr.takeError();
258   return object::getSymbol<ELFT>(*SymtabOrErr, Index);
259 }
260
261 template <class ELFT>
262 template <typename T>
263 Expected<ArrayRef<T>>
264 ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr *Sec) const {
265   if (Sec->sh_entsize != sizeof(T) && sizeof(T) != 1)
266     return createError("invalid sh_entsize");
267
268   uintX_t Offset = Sec->sh_offset;
269   uintX_t Size = Sec->sh_size;
270
271   if (Size % sizeof(T))
272     return createError("size is not a multiple of sh_entsize");
273   if ((std::numeric_limits<uintX_t>::max() - Offset < Size) ||
274       Offset + Size > Buf.size())
275     return createError("invalid section offset");
276
277   const T *Start = reinterpret_cast<const T *>(base() + Offset);
278   return makeArrayRef(Start, Size / sizeof(T));
279 }
280
281 template <class ELFT>
282 Expected<ArrayRef<uint8_t>>
283 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
284   return getSectionContentsAsArray<uint8_t>(Sec);
285 }
286
287 template <class ELFT>
288 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
289   return getELFRelocationTypeName(getHeader()->e_machine, Type);
290 }
291
292 template <class ELFT>
293 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
294                                           SmallVectorImpl<char> &Result) const {
295   if (!isMipsELF64()) {
296     StringRef Name = getRelocationTypeName(Type);
297     Result.append(Name.begin(), Name.end());
298   } else {
299     // The Mips N64 ABI allows up to three operations to be specified per
300     // relocation record. Unfortunately there's no easy way to test for the
301     // presence of N64 ELFs as they have no special flag that identifies them
302     // as being N64. We can safely assume at the moment that all Mips
303     // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
304     // information to disambiguate between old vs new ABIs.
305     uint8_t Type1 = (Type >> 0) & 0xFF;
306     uint8_t Type2 = (Type >> 8) & 0xFF;
307     uint8_t Type3 = (Type >> 16) & 0xFF;
308
309     // Concat all three relocation type names.
310     StringRef Name = getRelocationTypeName(Type1);
311     Result.append(Name.begin(), Name.end());
312
313     Name = getRelocationTypeName(Type2);
314     Result.append(1, '/');
315     Result.append(Name.begin(), Name.end());
316
317     Name = getRelocationTypeName(Type3);
318     Result.append(1, '/');
319     Result.append(Name.begin(), Name.end());
320   }
321 }
322
323 template <class ELFT>
324 Expected<const typename ELFT::Sym *>
325 ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
326                                    const Elf_Shdr *SymTab) const {
327   uint32_t Index = Rel->getSymbol(isMips64EL());
328   if (Index == 0)
329     return nullptr;
330   return getEntry<Elf_Sym>(SymTab, Index);
331 }
332
333 template <class ELFT>
334 Expected<StringRef>
335 ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections) const {
336   uint32_t Index = getHeader()->e_shstrndx;
337   if (Index == ELF::SHN_XINDEX)
338     Index = Sections[0].sh_link;
339
340   if (!Index) // no section string table.
341     return "";
342   if (Index >= Sections.size())
343     return createError("invalid section index");
344   return getStringTable(&Sections[Index]);
345 }
346
347 template <class ELFT>
348 ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {
349   assert(sizeof(Elf_Ehdr) <= Buf.size() && "Invalid buffer");
350 }
351
352 template <class ELFT>
353 bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
354   return VAddr < Phdr->p_vaddr;
355 }
356
357 template <class ELFT>
358 Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
359   const uintX_t SectionTableOffset = getHeader()->e_shoff;
360   if (SectionTableOffset == 0)
361     return ArrayRef<Elf_Shdr>();
362
363   if (getHeader()->e_shentsize != sizeof(Elf_Shdr))
364     return createError(
365         "invalid section header entry size (e_shentsize) in ELF header");
366
367   const uint64_t FileSize = Buf.size();
368
369   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
370     return createError("section header table goes past the end of the file");
371
372   // Invalid address alignment of section headers
373   if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
374     return createError("invalid alignment of section headers");
375
376   const Elf_Shdr *First =
377       reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
378
379   uintX_t NumSections = getHeader()->e_shnum;
380   if (NumSections == 0)
381     NumSections = First->sh_size;
382
383   if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
384     return createError("section table goes past the end of file");
385
386   const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
387
388   // Section table goes past end of file!
389   if (SectionTableOffset + SectionTableSize > FileSize)
390     return createError("section table goes past the end of file");
391
392   return makeArrayRef(First, NumSections);
393 }
394
395 template <class ELFT>
396 template <typename T>
397 Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
398                                             uint32_t Entry) const {
399   auto SecOrErr = getSection(Section);
400   if (!SecOrErr)
401     return SecOrErr.takeError();
402   return getEntry<T>(*SecOrErr, Entry);
403 }
404
405 template <class ELFT>
406 template <typename T>
407 Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
408                                             uint32_t Entry) const {
409   if (sizeof(T) != Section->sh_entsize)
410     return createError("invalid sh_entsize");
411   size_t Pos = Section->sh_offset + Entry * sizeof(T);
412   if (Pos + sizeof(T) > Buf.size())
413     return createError("invalid section offset");
414   return reinterpret_cast<const T *>(base() + Pos);
415 }
416
417 template <class ELFT>
418 Expected<const typename ELFT::Shdr *>
419 ELFFile<ELFT>::getSection(uint32_t Index) const {
420   auto TableOrErr = sections();
421   if (!TableOrErr)
422     return TableOrErr.takeError();
423   return object::getSection<ELFT>(*TableOrErr, Index);
424 }
425
426 template <class ELFT>
427 Expected<StringRef>
428 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
429   if (Section->sh_type != ELF::SHT_STRTAB)
430     return createError("invalid sh_type for string table, expected SHT_STRTAB");
431   auto V = getSectionContentsAsArray<char>(Section);
432   if (!V)
433     return V.takeError();
434   ArrayRef<char> Data = *V;
435   if (Data.empty())
436     return createError("empty string table");
437   if (Data.back() != '\0')
438     return createError("string table non-null terminated");
439   return StringRef(Data.begin(), Data.size());
440 }
441
442 template <class ELFT>
443 Expected<ArrayRef<typename ELFT::Word>>
444 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
445   auto SectionsOrErr = sections();
446   if (!SectionsOrErr)
447     return SectionsOrErr.takeError();
448   return getSHNDXTable(Section, *SectionsOrErr);
449 }
450
451 template <class ELFT>
452 Expected<ArrayRef<typename ELFT::Word>>
453 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
454                              Elf_Shdr_Range Sections) const {
455   assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
456   auto VOrErr = getSectionContentsAsArray<Elf_Word>(&Section);
457   if (!VOrErr)
458     return VOrErr.takeError();
459   ArrayRef<Elf_Word> V = *VOrErr;
460   auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
461   if (!SymTableOrErr)
462     return SymTableOrErr.takeError();
463   const Elf_Shdr &SymTable = **SymTableOrErr;
464   if (SymTable.sh_type != ELF::SHT_SYMTAB &&
465       SymTable.sh_type != ELF::SHT_DYNSYM)
466     return createError("invalid sh_type");
467   if (V.size() != (SymTable.sh_size / sizeof(Elf_Sym)))
468     return createError("invalid section contents size");
469   return V;
470 }
471
472 template <class ELFT>
473 Expected<StringRef>
474 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
475   auto SectionsOrErr = sections();
476   if (!SectionsOrErr)
477     return SectionsOrErr.takeError();
478   return getStringTableForSymtab(Sec, *SectionsOrErr);
479 }
480
481 template <class ELFT>
482 Expected<StringRef>
483 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
484                                        Elf_Shdr_Range Sections) const {
485
486   if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
487     return createError(
488         "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
489   auto SectionOrErr = object::getSection<ELFT>(Sections, Sec.sh_link);
490   if (!SectionOrErr)
491     return SectionOrErr.takeError();
492   return getStringTable(*SectionOrErr);
493 }
494
495 template <class ELFT>
496 Expected<StringRef>
497 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
498   auto SectionsOrErr = sections();
499   if (!SectionsOrErr)
500     return SectionsOrErr.takeError();
501   auto Table = getSectionStringTable(*SectionsOrErr);
502   if (!Table)
503     return Table.takeError();
504   return getSectionName(Section, *Table);
505 }
506
507 template <class ELFT>
508 Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section,
509                                                   StringRef DotShstrtab) const {
510   uint32_t Offset = Section->sh_name;
511   if (Offset == 0)
512     return StringRef();
513   if (Offset >= DotShstrtab.size())
514     return createError("invalid string offset");
515   return StringRef(DotShstrtab.data() + Offset);
516 }
517
518 /// This function returns the hash value for a symbol in the .dynsym section
519 /// Name of the API remains consistent as specified in the libelf
520 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
521 inline unsigned hashSysV(StringRef SymbolName) {
522   unsigned h = 0, g;
523   for (char C : SymbolName) {
524     h = (h << 4) + C;
525     g = h & 0xf0000000L;
526     if (g != 0)
527       h ^= g >> 24;
528     h &= ~g;
529   }
530   return h;
531 }
532
533 } // end namespace object
534 } // end namespace llvm
535
536 #endif // LLVM_OBJECT_ELF_H