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