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