Rename improperly named variable. NFC.
[oota-llvm.git] / 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/SmallVector.h"
18 #include "llvm/Object/ELFTypes.h"
19 #include "llvm/Support/MemoryBuffer.h"
20
21 namespace llvm {
22 namespace object {
23
24 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
25
26 // Subclasses of ELFFile may need this for template instantiation
27 inline std::pair<unsigned char, unsigned char>
28 getElfArchType(StringRef Object) {
29   if (Object.size() < ELF::EI_NIDENT)
30     return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
31                           (uint8_t)ELF::ELFDATANONE);
32   return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
33                         (uint8_t)Object[ELF::EI_DATA]);
34 }
35
36 template <class ELFT>
37 class ELFFile {
38 public:
39   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
40   typedef typename std::conditional<ELFT::Is64Bits,
41                                     uint64_t, uint32_t>::type uintX_t;
42
43   typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
44   typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
45   typedef Elf_Sym_Impl<ELFT> Elf_Sym;
46   typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
47   typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
48   typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
49   typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
50   typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
51   typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
52   typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
53   typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
54   typedef Elf_Versym_Impl<ELFT> Elf_Versym;
55   typedef Elf_Hash_Impl<ELFT> Elf_Hash;
56   typedef iterator_range<const Elf_Dyn *> Elf_Dyn_Range;
57   typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
58   typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
59
60   const uint8_t *base() const {
61     return reinterpret_cast<const uint8_t *>(Buf.data());
62   }
63
64 private:
65
66   StringRef Buf;
67
68   const Elf_Ehdr *Header;
69   const Elf_Shdr *SectionHeaderTable = nullptr;
70   StringRef DotShstrtab;                    // Section header string table.
71   const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
72
73   const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
74
75 public:
76   template<typename T>
77   const T        *getEntry(uint32_t Section, uint32_t Entry) const;
78   template <typename T>
79   const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
80
81   ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
82   ErrorOr<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
83
84   void VerifyStrTab(const Elf_Shdr *sh) const;
85
86   StringRef getRelocationTypeName(uint32_t Type) const;
87   void getRelocationTypeName(uint32_t Type,
88                              SmallVectorImpl<char> &Result) const;
89
90   /// \brief Get the symbol table section and symbol for a given relocation.
91   template <class RelT>
92   std::pair<const Elf_Shdr *, const Elf_Sym *>
93   getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
94
95   ELFFile(StringRef Object, std::error_code &EC);
96
97   bool isMipsELF64() const {
98     return Header->e_machine == ELF::EM_MIPS &&
99       Header->getFileClass() == ELF::ELFCLASS64;
100   }
101
102   bool isMips64EL() const {
103     return Header->e_machine == ELF::EM_MIPS &&
104       Header->getFileClass() == ELF::ELFCLASS64 &&
105       Header->getDataEncoding() == ELF::ELFDATA2LSB;
106   }
107
108   ErrorOr<const Elf_Dyn *> dynamic_table_begin(const Elf_Phdr *Phdr) const;
109   ErrorOr<const Elf_Dyn *> dynamic_table_end(const Elf_Phdr *Phdr) const;
110   ErrorOr<Elf_Dyn_Range> dynamic_table(const Elf_Phdr *Phdr) const {
111     ErrorOr<const Elf_Dyn *> Begin = dynamic_table_begin(Phdr);
112     if (std::error_code EC = Begin.getError())
113       return EC;
114     ErrorOr<const Elf_Dyn *> End = dynamic_table_end(Phdr);
115     if (std::error_code EC = End.getError())
116       return EC;
117     return make_range(*Begin, *End);
118   }
119
120   const Elf_Shdr *section_begin() const;
121   const Elf_Shdr *section_end() const;
122   Elf_Shdr_Range sections() const {
123     return make_range(section_begin(), section_end());
124   }
125
126   const Elf_Sym *symbol_begin(const Elf_Shdr *Sec) const {
127     if (!Sec)
128       return nullptr;
129     if (Sec->sh_entsize != sizeof(Elf_Sym))
130       report_fatal_error("Invalid symbol size");
131     return reinterpret_cast<const Elf_Sym *>(base() + Sec->sh_offset);
132   }
133   const Elf_Sym *symbol_end(const Elf_Shdr *Sec) const {
134     if (!Sec)
135       return nullptr;
136     uint64_t Size = Sec->sh_size;
137     if (Size % sizeof(Elf_Sym))
138       report_fatal_error("Invalid symbol table size");
139     return symbol_begin(Sec) + Size / sizeof(Elf_Sym);
140   }
141   Elf_Sym_Range symbols(const Elf_Shdr *Sec) const {
142     return make_range(symbol_begin(Sec), symbol_end(Sec));
143   }
144
145   typedef iterator_range<const Elf_Rela *> Elf_Rela_Range;
146
147   const Elf_Rela *rela_begin(const Elf_Shdr *sec) const {
148     if (sec->sh_entsize != sizeof(Elf_Rela))
149       report_fatal_error("Invalid relocation entry size");
150     return reinterpret_cast<const Elf_Rela *>(base() + sec->sh_offset);
151   }
152
153   const Elf_Rela *rela_end(const Elf_Shdr *sec) const {
154     uint64_t Size = sec->sh_size;
155     if (Size % sizeof(Elf_Rela))
156       report_fatal_error("Invalid relocation table size");
157     return rela_begin(sec) + Size / sizeof(Elf_Rela);
158   }
159
160   Elf_Rela_Range relas(const Elf_Shdr *Sec) const {
161     return make_range(rela_begin(Sec), rela_end(Sec));
162   }
163
164   const Elf_Rel *rel_begin(const Elf_Shdr *sec) const {
165     if (sec->sh_entsize != sizeof(Elf_Rel))
166       report_fatal_error("Invalid relocation entry size");
167     return reinterpret_cast<const Elf_Rel *>(base() + sec->sh_offset);
168   }
169
170   const Elf_Rel *rel_end(const Elf_Shdr *sec) const {
171     uint64_t Size = sec->sh_size;
172     if (Size % sizeof(Elf_Rel))
173       report_fatal_error("Invalid relocation table size");
174     return rel_begin(sec) + Size / sizeof(Elf_Rel);
175   }
176
177   typedef iterator_range<const Elf_Rel *> Elf_Rel_Range;
178   Elf_Rel_Range rels(const Elf_Shdr *Sec) const {
179     return make_range(rel_begin(Sec), rel_end(Sec));
180   }
181
182   /// \brief Iterate over program header table.
183   const Elf_Phdr *program_header_begin() const {
184     if (Header->e_phnum && Header->e_phentsize != sizeof(Elf_Phdr))
185       report_fatal_error("Invalid program header size");
186     return reinterpret_cast<const Elf_Phdr *>(base() + Header->e_phoff);
187   }
188
189   const Elf_Phdr *program_header_end() const {
190     return program_header_begin() + Header->e_phnum;
191   }
192
193   typedef iterator_range<const Elf_Phdr *> Elf_Phdr_Range;
194
195   const Elf_Phdr_Range program_headers() const {
196     return make_range(program_header_begin(), program_header_end());
197   }
198
199   uint64_t getNumSections() const;
200   uintX_t getStringTableIndex() const;
201   ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
202   const Elf_Ehdr *getHeader() const { return Header; }
203   ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
204   ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
205
206   const Elf_Sym *getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
207     return &*(symbol_begin(Sec) + Index);
208   }
209
210   ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
211   ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
212 };
213
214 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
215 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
216 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
217 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
218
219 template <class ELFT>
220 ELF::Elf64_Word
221 ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *Sym) const {
222   assert(Sym->st_shndx == ELF::SHN_XINDEX);
223   unsigned Index = Sym - symbol_begin(dot_symtab_sec);
224
225   // FIXME: error checking
226   const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word *>(
227       base() + SymbolTableSectionHeaderIndex->sh_offset);
228   return ShndxTable[Index];
229 }
230
231 template <class ELFT>
232 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
233 ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
234   uint32_t Index = symb->st_shndx;
235   if (Index == ELF::SHN_XINDEX)
236     return getSection(getExtendedSymbolTableIndex(symb));
237   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
238     return nullptr;
239   return getSection(symb->st_shndx);
240 }
241
242 template <class ELFT>
243 ErrorOr<ArrayRef<uint8_t> >
244 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
245   if (Sec->sh_offset + Sec->sh_size > Buf.size())
246     return object_error::parse_failed;
247   const uint8_t *Start = base() + Sec->sh_offset;
248   return makeArrayRef(Start, Sec->sh_size);
249 }
250
251 template <class ELFT>
252 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
253   return getELFRelocationTypeName(Header->e_machine, Type);
254 }
255
256 template <class ELFT>
257 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
258                                           SmallVectorImpl<char> &Result) const {
259   if (!isMipsELF64()) {
260     StringRef Name = getRelocationTypeName(Type);
261     Result.append(Name.begin(), Name.end());
262   } else {
263     // The Mips N64 ABI allows up to three operations to be specified per
264     // relocation record. Unfortunately there's no easy way to test for the
265     // presence of N64 ELFs as they have no special flag that identifies them
266     // as being N64. We can safely assume at the moment that all Mips
267     // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
268     // information to disambiguate between old vs new ABIs.
269     uint8_t Type1 = (Type >> 0) & 0xFF;
270     uint8_t Type2 = (Type >> 8) & 0xFF;
271     uint8_t Type3 = (Type >> 16) & 0xFF;
272
273     // Concat all three relocation type names.
274     StringRef Name = getRelocationTypeName(Type1);
275     Result.append(Name.begin(), Name.end());
276
277     Name = getRelocationTypeName(Type2);
278     Result.append(1, '/');
279     Result.append(Name.begin(), Name.end());
280
281     Name = getRelocationTypeName(Type3);
282     Result.append(1, '/');
283     Result.append(Name.begin(), Name.end());
284   }
285 }
286
287 template <class ELFT>
288 template <class RelT>
289 std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
290           const typename ELFFile<ELFT>::Elf_Sym *>
291 ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
292   if (!Sec->sh_link)
293     return std::make_pair(nullptr, nullptr);
294   ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
295   if (std::error_code EC = SymTableOrErr.getError())
296     report_fatal_error(EC.message());
297   const Elf_Shdr *SymTable = *SymTableOrErr;
298   return std::make_pair(
299       SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
300 }
301
302 template <class ELFT>
303 uint64_t ELFFile<ELFT>::getNumSections() const {
304   assert(Header && "Header not initialized!");
305   if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
306     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
307     return SectionHeaderTable->sh_size;
308   }
309   return Header->e_shnum;
310 }
311
312 template <class ELFT>
313 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
314   if (Header->e_shnum == ELF::SHN_UNDEF) {
315     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
316       return SectionHeaderTable->sh_link;
317     if (Header->e_shstrndx >= getNumSections())
318       return 0;
319   }
320   return Header->e_shstrndx;
321 }
322
323 template <class ELFT>
324 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
325     : Buf(Object) {
326   const uint64_t FileSize = Buf.size();
327
328   if (sizeof(Elf_Ehdr) > FileSize) {
329     // File too short!
330     EC = object_error::parse_failed;
331     return;
332   }
333
334   Header = reinterpret_cast<const Elf_Ehdr *>(base());
335
336   if (Header->e_shoff == 0)
337     return;
338
339   const uint64_t SectionTableOffset = Header->e_shoff;
340
341   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
342     // Section header table goes past end of file!
343     EC = object_error::parse_failed;
344     return;
345   }
346
347   // The getNumSections() call below depends on SectionHeaderTable being set.
348   SectionHeaderTable =
349     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
350   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
351
352   if (SectionTableOffset + SectionTableSize > FileSize) {
353     // Section table goes past end of file!
354     EC = object_error::parse_failed;
355     return;
356   }
357
358   // Scan sections for special sections.
359
360   for (const Elf_Shdr &Sec : sections()) {
361     switch (Sec.sh_type) {
362     case ELF::SHT_SYMTAB_SHNDX:
363       if (SymbolTableSectionHeaderIndex) {
364         // More than one .symtab_shndx!
365         EC = object_error::parse_failed;
366         return;
367       }
368       SymbolTableSectionHeaderIndex = &Sec;
369       break;
370     case ELF::SHT_SYMTAB: {
371       if (dot_symtab_sec) {
372         // More than one .symtab!
373         EC = object_error::parse_failed;
374         return;
375       }
376       dot_symtab_sec = &Sec;
377     } break;
378     }
379   }
380
381   // Get string table sections.
382   uintX_t StringTableIndex = getStringTableIndex();
383   if (StringTableIndex) {
384     ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(StringTableIndex);
385     if ((EC = StrTabSecOrErr.getError()))
386       return;
387
388     ErrorOr<StringRef> StringTableOrErr = getStringTable(*StrTabSecOrErr);
389     if ((EC = StringTableOrErr.getError()))
390       return;
391     DotShstrtab = *StringTableOrErr;
392   }
393
394   EC = std::error_code();
395 }
396
397 template <class ELFT>
398 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
399   return VAddr < Phdr->p_vaddr;
400 }
401
402 template <class ELFT>
403 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
404   if (Header->e_shentsize != sizeof(Elf_Shdr))
405     report_fatal_error(
406         "Invalid section header entry size (e_shentsize) in ELF header");
407   return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
408 }
409
410 template <class ELFT>
411 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
412   return section_begin() + getNumSections();
413 }
414
415 template <class ELFT>
416 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
417 ELFFile<ELFT>::dynamic_table_begin(const Elf_Phdr *Phdr) const {
418   if (!Phdr)
419     return nullptr;
420   assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
421   uintX_t Offset = Phdr->p_offset;
422   if (Offset > Buf.size())
423     return object_error::parse_failed;
424   return reinterpret_cast<const Elf_Dyn *>(base() + Offset);
425 }
426
427 template <class ELFT>
428 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
429 ELFFile<ELFT>::dynamic_table_end(const Elf_Phdr *Phdr) const {
430   if (!Phdr)
431     return nullptr;
432   assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
433   uintX_t Size = Phdr->p_filesz;
434   if (Size % sizeof(Elf_Dyn))
435     return object_error::elf_invalid_dynamic_table_size;
436   // FIKME: Check for overflow?
437   uintX_t End = Phdr->p_offset + Size;
438   if (End > Buf.size())
439     return object_error::parse_failed;
440   return reinterpret_cast<const Elf_Dyn *>(base() + End);
441 }
442
443 template <class ELFT>
444 template <typename T>
445 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
446   ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
447   if (std::error_code EC = Sec.getError())
448     report_fatal_error(EC.message());
449   return getEntry<T>(*Sec, Entry);
450 }
451
452 template <class ELFT>
453 template <typename T>
454 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
455                                  uint32_t Entry) const {
456   return reinterpret_cast<const T *>(base() + Section->sh_offset +
457                                      (Entry * Section->sh_entsize));
458 }
459
460 template <class ELFT>
461 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
462 ELFFile<ELFT>::getSection(uint32_t Index) const {
463   assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
464   if (Index >= getNumSections())
465     return object_error::invalid_section_index;
466
467   return reinterpret_cast<const Elf_Shdr *>(
468       reinterpret_cast<const char *>(SectionHeaderTable) +
469       (Index * Header->e_shentsize));
470 }
471
472 template <class ELFT>
473 ErrorOr<StringRef>
474 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
475   if (Section->sh_type != ELF::SHT_STRTAB)
476     return object_error::parse_failed;
477   uint64_t Offset = Section->sh_offset;
478   uint64_t Size = Section->sh_size;
479   if (Offset + Size > Buf.size())
480     return object_error::parse_failed;
481   StringRef Data((const char *)base() + Section->sh_offset, Size);
482   if (Data[Size - 1] != '\0')
483     return object_error::string_table_non_null_end;
484   return Data;
485 }
486
487 template <class ELFT>
488 ErrorOr<StringRef>
489 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
490   if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
491     return object_error::parse_failed;
492   ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
493   if (std::error_code EC = SectionOrErr.getError())
494     return EC;
495   return getStringTable(*SectionOrErr);
496 }
497
498 template <class ELFT>
499 ErrorOr<StringRef>
500 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
501   uint32_t Offset = Section->sh_name;
502   if (Offset == 0)
503     return StringRef();
504   if (Offset >= DotShstrtab.size())
505     return object_error::parse_failed;
506   return StringRef(DotShstrtab.data() + Offset);
507 }
508
509 /// This function returns the hash value for a symbol in the .dynsym section
510 /// Name of the API remains consistent as specified in the libelf
511 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
512 static inline unsigned elf_hash(StringRef &symbolName) {
513   unsigned h = 0, g;
514   for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
515     h = (h << 4) + symbolName[i];
516     g = h & 0xf0000000L;
517     if (g != 0)
518       h ^= g >> 24;
519     h &= ~g;
520   }
521   return h;
522 }
523 } // end namespace object
524 } // end namespace llvm
525
526 #endif