Use makeArrayRef or None to avoid unnecessarily mentioning the ArrayRef type extra...
[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
72 public:
73   template<typename T>
74   const T        *getEntry(uint32_t Section, uint32_t Entry) const;
75   template <typename T>
76   const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
77
78   ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
79   ErrorOr<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
80
81   ErrorOr<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
82
83   void VerifyStrTab(const Elf_Shdr *sh) const;
84
85   StringRef getRelocationTypeName(uint32_t Type) const;
86   void getRelocationTypeName(uint32_t Type,
87                              SmallVectorImpl<char> &Result) const;
88
89   /// \brief Get the symbol for a given relocation.
90   const Elf_Sym *getRelocationSymbol(const Elf_Rel *Rel,
91                                      const Elf_Shdr *SymTab) const;
92
93   ELFFile(StringRef Object, std::error_code &EC);
94
95   bool isMipsELF64() const {
96     return Header->e_machine == ELF::EM_MIPS &&
97       Header->getFileClass() == ELF::ELFCLASS64;
98   }
99
100   bool isMips64EL() const {
101     return Header->e_machine == ELF::EM_MIPS &&
102       Header->getFileClass() == ELF::ELFCLASS64 &&
103       Header->getDataEncoding() == ELF::ELFDATA2LSB;
104   }
105
106   ErrorOr<const Elf_Dyn *> dynamic_table_begin(const Elf_Phdr *Phdr) const;
107   ErrorOr<const Elf_Dyn *> dynamic_table_end(const Elf_Phdr *Phdr) const;
108   ErrorOr<Elf_Dyn_Range> dynamic_table(const Elf_Phdr *Phdr) const {
109     ErrorOr<const Elf_Dyn *> Begin = dynamic_table_begin(Phdr);
110     if (std::error_code EC = Begin.getError())
111       return EC;
112     ErrorOr<const Elf_Dyn *> End = dynamic_table_end(Phdr);
113     if (std::error_code EC = End.getError())
114       return EC;
115     return make_range(*Begin, *End);
116   }
117
118   const Elf_Shdr *section_begin() const;
119   const Elf_Shdr *section_end() const;
120   Elf_Shdr_Range sections() const {
121     return make_range(section_begin(), section_end());
122   }
123
124   const Elf_Sym *symbol_begin(const Elf_Shdr *Sec) const {
125     if (!Sec)
126       return nullptr;
127     if (Sec->sh_entsize != sizeof(Elf_Sym))
128       report_fatal_error("Invalid symbol size");
129     return reinterpret_cast<const Elf_Sym *>(base() + Sec->sh_offset);
130   }
131   const Elf_Sym *symbol_end(const Elf_Shdr *Sec) const {
132     if (!Sec)
133       return nullptr;
134     uint64_t Size = Sec->sh_size;
135     if (Size % sizeof(Elf_Sym))
136       report_fatal_error("Invalid symbol table size");
137     return symbol_begin(Sec) + Size / sizeof(Elf_Sym);
138   }
139   Elf_Sym_Range symbols(const Elf_Shdr *Sec) const {
140     return make_range(symbol_begin(Sec), symbol_end(Sec));
141   }
142
143   typedef iterator_range<const Elf_Rela *> Elf_Rela_Range;
144
145   const Elf_Rela *rela_begin(const Elf_Shdr *sec) const {
146     if (sec->sh_entsize != sizeof(Elf_Rela))
147       report_fatal_error("Invalid relocation entry size");
148     return reinterpret_cast<const Elf_Rela *>(base() + sec->sh_offset);
149   }
150
151   const Elf_Rela *rela_end(const Elf_Shdr *sec) const {
152     uint64_t Size = sec->sh_size;
153     if (Size % sizeof(Elf_Rela))
154       report_fatal_error("Invalid relocation table size");
155     return rela_begin(sec) + Size / sizeof(Elf_Rela);
156   }
157
158   Elf_Rela_Range relas(const Elf_Shdr *Sec) const {
159     return make_range(rela_begin(Sec), rela_end(Sec));
160   }
161
162   const Elf_Rel *rel_begin(const Elf_Shdr *sec) const {
163     if (sec->sh_entsize != sizeof(Elf_Rel))
164       report_fatal_error("Invalid relocation entry size");
165     return reinterpret_cast<const Elf_Rel *>(base() + sec->sh_offset);
166   }
167
168   const Elf_Rel *rel_end(const Elf_Shdr *sec) const {
169     uint64_t Size = sec->sh_size;
170     if (Size % sizeof(Elf_Rel))
171       report_fatal_error("Invalid relocation table size");
172     return rel_begin(sec) + Size / sizeof(Elf_Rel);
173   }
174
175   typedef iterator_range<const Elf_Rel *> Elf_Rel_Range;
176   Elf_Rel_Range rels(const Elf_Shdr *Sec) const {
177     return make_range(rel_begin(Sec), rel_end(Sec));
178   }
179
180   /// \brief Iterate over program header table.
181   const Elf_Phdr *program_header_begin() const {
182     if (Header->e_phnum && Header->e_phentsize != sizeof(Elf_Phdr))
183       report_fatal_error("Invalid program header size");
184     return reinterpret_cast<const Elf_Phdr *>(base() + Header->e_phoff);
185   }
186
187   const Elf_Phdr *program_header_end() const {
188     return program_header_begin() + Header->e_phnum;
189   }
190
191   typedef iterator_range<const Elf_Phdr *> Elf_Phdr_Range;
192
193   const Elf_Phdr_Range program_headers() const {
194     return make_range(program_header_begin(), program_header_end());
195   }
196
197   uint64_t getNumSections() const;
198   uintX_t getStringTableIndex() const;
199   uint32_t getExtendedSymbolTableIndex(const Elf_Sym *Sym,
200                                        const Elf_Shdr *SymTab,
201                                        ArrayRef<Elf_Word> ShndxTable) const;
202   const Elf_Ehdr *getHeader() const { return Header; }
203   ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
204                                        const Elf_Shdr *SymTab,
205                                        ArrayRef<Elf_Word> ShndxTable) 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 uint32_t ELFFile<ELFT>::getExtendedSymbolTableIndex(
223     const Elf_Sym *Sym, const Elf_Shdr *SymTab,
224     ArrayRef<Elf_Word> ShndxTable) const {
225   assert(Sym->st_shndx == ELF::SHN_XINDEX);
226   unsigned Index = Sym - symbol_begin(SymTab);
227
228   // The size of the table was checked in getSHNDXTable.
229   return ShndxTable[Index];
230 }
231
232 template <class ELFT>
233 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
234 ELFFile<ELFT>::getSection(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
235                           ArrayRef<Elf_Word> ShndxTable) const {
236   uint32_t Index = Sym->st_shndx;
237   if (Index == ELF::SHN_XINDEX)
238     return getSection(getExtendedSymbolTableIndex(Sym, SymTab, ShndxTable));
239
240   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
241     return nullptr;
242   return getSection(Sym->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 const typename ELFFile<ELFT>::Elf_Sym *
292 ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
293                                    const Elf_Shdr *SymTab) const {
294   uint32_t Index = Rel->getSymbol(isMips64EL());
295   if (Index == 0)
296     return nullptr;
297   return getEntry<Elf_Sym>(SymTab, Index);
298 }
299
300 template <class ELFT>
301 uint64_t ELFFile<ELFT>::getNumSections() const {
302   assert(Header && "Header not initialized!");
303   if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
304     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
305     return SectionHeaderTable->sh_size;
306   }
307   return Header->e_shnum;
308 }
309
310 template <class ELFT>
311 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
312   if (Header->e_shnum == ELF::SHN_UNDEF) {
313     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
314       return SectionHeaderTable->sh_link;
315     if (Header->e_shstrndx >= getNumSections())
316       return 0;
317   }
318   return Header->e_shstrndx;
319 }
320
321 template <class ELFT>
322 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
323     : Buf(Object) {
324   const uint64_t FileSize = Buf.size();
325
326   if (sizeof(Elf_Ehdr) > FileSize) {
327     // File too short!
328     EC = object_error::parse_failed;
329     return;
330   }
331
332   Header = reinterpret_cast<const Elf_Ehdr *>(base());
333
334   if (Header->e_shoff == 0)
335     return;
336
337   const uint64_t SectionTableOffset = Header->e_shoff;
338
339   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
340     // Section header table goes past end of file!
341     EC = object_error::parse_failed;
342     return;
343   }
344
345   // The getNumSections() call below depends on SectionHeaderTable being set.
346   SectionHeaderTable =
347     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
348   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
349
350   if (SectionTableOffset + SectionTableSize > FileSize) {
351     // Section table goes past end of file!
352     EC = object_error::parse_failed;
353     return;
354   }
355
356   // Get string table sections.
357   uintX_t StringTableIndex = getStringTableIndex();
358   if (StringTableIndex) {
359     ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(StringTableIndex);
360     if ((EC = StrTabSecOrErr.getError()))
361       return;
362
363     ErrorOr<StringRef> StringTableOrErr = getStringTable(*StrTabSecOrErr);
364     if ((EC = StringTableOrErr.getError()))
365       return;
366     DotShstrtab = *StringTableOrErr;
367   }
368
369   EC = std::error_code();
370 }
371
372 template <class ELFT>
373 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
374   return VAddr < Phdr->p_vaddr;
375 }
376
377 template <class ELFT>
378 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
379   if (Header->e_shentsize != sizeof(Elf_Shdr))
380     report_fatal_error(
381         "Invalid section header entry size (e_shentsize) in ELF header");
382   return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
383 }
384
385 template <class ELFT>
386 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
387   return section_begin() + getNumSections();
388 }
389
390 template <class ELFT>
391 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
392 ELFFile<ELFT>::dynamic_table_begin(const Elf_Phdr *Phdr) const {
393   if (!Phdr)
394     return nullptr;
395   assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
396   uintX_t Offset = Phdr->p_offset;
397   if (Offset > Buf.size())
398     return object_error::parse_failed;
399   return reinterpret_cast<const Elf_Dyn *>(base() + Offset);
400 }
401
402 template <class ELFT>
403 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
404 ELFFile<ELFT>::dynamic_table_end(const Elf_Phdr *Phdr) const {
405   if (!Phdr)
406     return nullptr;
407   assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
408   uintX_t Size = Phdr->p_filesz;
409   if (Size % sizeof(Elf_Dyn))
410     return object_error::elf_invalid_dynamic_table_size;
411   // FIKME: Check for overflow?
412   uintX_t End = Phdr->p_offset + Size;
413   if (End > Buf.size())
414     return object_error::parse_failed;
415   return reinterpret_cast<const Elf_Dyn *>(base() + End);
416 }
417
418 template <class ELFT>
419 template <typename T>
420 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
421   ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
422   if (std::error_code EC = Sec.getError())
423     report_fatal_error(EC.message());
424   return getEntry<T>(*Sec, Entry);
425 }
426
427 template <class ELFT>
428 template <typename T>
429 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
430                                  uint32_t Entry) const {
431   return reinterpret_cast<const T *>(base() + Section->sh_offset +
432                                      (Entry * Section->sh_entsize));
433 }
434
435 template <class ELFT>
436 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
437 ELFFile<ELFT>::getSection(uint32_t Index) const {
438   assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
439   if (Index >= getNumSections())
440     return object_error::invalid_section_index;
441
442   return reinterpret_cast<const Elf_Shdr *>(
443       reinterpret_cast<const char *>(SectionHeaderTable) +
444       (Index * Header->e_shentsize));
445 }
446
447 template <class ELFT>
448 ErrorOr<StringRef>
449 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
450   if (Section->sh_type != ELF::SHT_STRTAB)
451     return object_error::parse_failed;
452   uint64_t Offset = Section->sh_offset;
453   uint64_t Size = Section->sh_size;
454   if (Offset + Size > Buf.size())
455     return object_error::parse_failed;
456   StringRef Data((const char *)base() + Section->sh_offset, Size);
457   if (Data[Size - 1] != '\0')
458     return object_error::string_table_non_null_end;
459   return Data;
460 }
461
462 template <class ELFT>
463 ErrorOr<ArrayRef<typename ELFFile<ELFT>::Elf_Word>>
464 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
465   assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
466   const Elf_Word *ShndxTableBegin =
467       reinterpret_cast<const Elf_Word *>(base() + Section.sh_offset);
468   uintX_t Size = Section.sh_size;
469   if (Size % sizeof(uint32_t))
470     return object_error::parse_failed;
471   uintX_t NumSymbols = Size / sizeof(uint32_t);
472   const Elf_Word *ShndxTableEnd = ShndxTableBegin + NumSymbols;
473   if (reinterpret_cast<const char *>(ShndxTableEnd) > Buf.end())
474     return object_error::parse_failed;
475   ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Section.sh_link);
476   if (std::error_code EC = SymTableOrErr.getError())
477     return EC;
478   const Elf_Shdr &SymTable = **SymTableOrErr;
479   if (SymTable.sh_type != ELF::SHT_SYMTAB &&
480       SymTable.sh_type != ELF::SHT_DYNSYM)
481     return object_error::parse_failed;
482   if (NumSymbols != (SymTable.sh_size / sizeof(Elf_Sym)))
483     return object_error::parse_failed;
484   return makeArrayRef(ShndxTableBegin, ShndxTableEnd);
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