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