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