Fixed bugs in llvm-obdump while parsing Mach-O files from malformed archives
[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   template <typename T>
214   ErrorOr<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr *Sec) const;
215   ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
216 };
217
218 typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
219 typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
220 typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
221 typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
222
223 template <class ELFT>
224 uint32_t ELFFile<ELFT>::getExtendedSymbolTableIndex(
225     const Elf_Sym *Sym, const Elf_Shdr *SymTab,
226     ArrayRef<Elf_Word> ShndxTable) const {
227   assert(Sym->st_shndx == ELF::SHN_XINDEX);
228   unsigned Index = Sym - symbol_begin(SymTab);
229
230   // The size of the table was checked in getSHNDXTable.
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 *Sym, const Elf_Shdr *SymTab,
237                           ArrayRef<Elf_Word> ShndxTable) const {
238   uint32_t Index = Sym->st_shndx;
239   if (Index == ELF::SHN_XINDEX)
240     return getSection(getExtendedSymbolTableIndex(Sym, SymTab, ShndxTable));
241
242   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
243     return nullptr;
244   return getSection(Sym->st_shndx);
245 }
246
247 template <class ELFT>
248 template <typename T>
249 ErrorOr<ArrayRef<T>>
250 ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr *Sec) const {
251   uintX_t Offset = Sec->sh_offset;
252   uintX_t Size = Sec->sh_size;
253
254   if (Size % sizeof(T))
255     return object_error::parse_failed;
256   if (Offset + Size > Buf.size())
257     return object_error::parse_failed;
258
259   const T *Start = reinterpret_cast<const T *>(base() + Offset);
260   return makeArrayRef(Start, Size / sizeof(T));
261 }
262
263 template <class ELFT>
264 ErrorOr<ArrayRef<uint8_t>>
265 ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
266   return getSectionContentsAsArray<uint8_t>(Sec);
267 }
268
269 template <class ELFT>
270 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
271   return getELFRelocationTypeName(Header->e_machine, Type);
272 }
273
274 template <class ELFT>
275 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
276                                           SmallVectorImpl<char> &Result) const {
277   if (!isMipsELF64()) {
278     StringRef Name = getRelocationTypeName(Type);
279     Result.append(Name.begin(), Name.end());
280   } else {
281     // The Mips N64 ABI allows up to three operations to be specified per
282     // relocation record. Unfortunately there's no easy way to test for the
283     // presence of N64 ELFs as they have no special flag that identifies them
284     // as being N64. We can safely assume at the moment that all Mips
285     // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
286     // information to disambiguate between old vs new ABIs.
287     uint8_t Type1 = (Type >> 0) & 0xFF;
288     uint8_t Type2 = (Type >> 8) & 0xFF;
289     uint8_t Type3 = (Type >> 16) & 0xFF;
290
291     // Concat all three relocation type names.
292     StringRef Name = getRelocationTypeName(Type1);
293     Result.append(Name.begin(), Name.end());
294
295     Name = getRelocationTypeName(Type2);
296     Result.append(1, '/');
297     Result.append(Name.begin(), Name.end());
298
299     Name = getRelocationTypeName(Type3);
300     Result.append(1, '/');
301     Result.append(Name.begin(), Name.end());
302   }
303 }
304
305 template <class ELFT>
306 const typename ELFFile<ELFT>::Elf_Sym *
307 ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
308                                    const Elf_Shdr *SymTab) const {
309   uint32_t Index = Rel->getSymbol(isMips64EL());
310   if (Index == 0)
311     return nullptr;
312   return getEntry<Elf_Sym>(SymTab, Index);
313 }
314
315 template <class ELFT>
316 uint64_t ELFFile<ELFT>::getNumSections() const {
317   assert(Header && "Header not initialized!");
318   if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
319     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
320     return SectionHeaderTable->sh_size;
321   }
322   return Header->e_shnum;
323 }
324
325 template <class ELFT>
326 typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
327   if (Header->e_shnum == ELF::SHN_UNDEF) {
328     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
329       return SectionHeaderTable->sh_link;
330     if (Header->e_shstrndx >= getNumSections())
331       return 0;
332   }
333   return Header->e_shstrndx;
334 }
335
336 template <class ELFT>
337 ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
338     : Buf(Object) {
339   const uint64_t FileSize = Buf.size();
340
341   if (sizeof(Elf_Ehdr) > FileSize) {
342     // File too short!
343     EC = object_error::parse_failed;
344     return;
345   }
346
347   Header = reinterpret_cast<const Elf_Ehdr *>(base());
348
349   if (Header->e_shoff == 0)
350     return;
351
352   const uint64_t SectionTableOffset = Header->e_shoff;
353
354   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
355     // Section header table goes past end of file!
356     EC = object_error::parse_failed;
357     return;
358   }
359
360   // The getNumSections() call below depends on SectionHeaderTable being set.
361   SectionHeaderTable =
362     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
363   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
364
365   if (SectionTableOffset + SectionTableSize > FileSize) {
366     // Section table goes past end of file!
367     EC = object_error::parse_failed;
368     return;
369   }
370
371   // Get string table sections.
372   uintX_t StringTableIndex = getStringTableIndex();
373   if (StringTableIndex) {
374     ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(StringTableIndex);
375     if ((EC = StrTabSecOrErr.getError()))
376       return;
377
378     ErrorOr<StringRef> StringTableOrErr = getStringTable(*StrTabSecOrErr);
379     if ((EC = StringTableOrErr.getError()))
380       return;
381     DotShstrtab = *StringTableOrErr;
382   }
383
384   EC = std::error_code();
385 }
386
387 template <class ELFT>
388 static bool compareAddr(uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) {
389   return VAddr < Phdr->p_vaddr;
390 }
391
392 template <class ELFT>
393 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
394   if (Header->e_shentsize != sizeof(Elf_Shdr))
395     report_fatal_error(
396         "Invalid section header entry size (e_shentsize) in ELF header");
397   return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
398 }
399
400 template <class ELFT>
401 const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
402   return section_begin() + getNumSections();
403 }
404
405 template <class ELFT>
406 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
407 ELFFile<ELFT>::dynamic_table_begin(const Elf_Phdr *Phdr) const {
408   if (!Phdr)
409     return nullptr;
410   assert(Phdr->p_type == ELF::PT_DYNAMIC && "Got the wrong program header");
411   uintX_t Offset = Phdr->p_offset;
412   if (Offset > Buf.size())
413     return object_error::parse_failed;
414   return reinterpret_cast<const Elf_Dyn *>(base() + Offset);
415 }
416
417 template <class ELFT>
418 ErrorOr<const typename ELFFile<ELFT>::Elf_Dyn *>
419 ELFFile<ELFT>::dynamic_table_end(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 Size = Phdr->p_filesz;
424   if (Size % sizeof(Elf_Dyn))
425     return object_error::elf_invalid_dynamic_table_size;
426   // FIKME: Check for overflow?
427   uintX_t End = Phdr->p_offset + Size;
428   if (End > Buf.size())
429     return object_error::parse_failed;
430   return reinterpret_cast<const Elf_Dyn *>(base() + End);
431 }
432
433 template <class ELFT>
434 template <typename T>
435 const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
436   ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
437   if (std::error_code EC = Sec.getError())
438     report_fatal_error(EC.message());
439   return getEntry<T>(*Sec, Entry);
440 }
441
442 template <class ELFT>
443 template <typename T>
444 const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
445                                  uint32_t Entry) const {
446   return reinterpret_cast<const T *>(base() + Section->sh_offset +
447                                      (Entry * Section->sh_entsize));
448 }
449
450 template <class ELFT>
451 ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
452 ELFFile<ELFT>::getSection(uint32_t Index) const {
453   assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
454   if (Index >= getNumSections())
455     return object_error::invalid_section_index;
456
457   return reinterpret_cast<const Elf_Shdr *>(
458       reinterpret_cast<const char *>(SectionHeaderTable) +
459       (Index * Header->e_shentsize));
460 }
461
462 template <class ELFT>
463 ErrorOr<StringRef>
464 ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
465   if (Section->sh_type != ELF::SHT_STRTAB)
466     return object_error::parse_failed;
467   uint64_t Offset = Section->sh_offset;
468   uint64_t Size = Section->sh_size;
469   if (Offset + Size > Buf.size())
470     return object_error::parse_failed;
471   StringRef Data((const char *)base() + Section->sh_offset, Size);
472   if (Data[Size - 1] != '\0')
473     return object_error::string_table_non_null_end;
474   return Data;
475 }
476
477 template <class ELFT>
478 ErrorOr<ArrayRef<typename ELFFile<ELFT>::Elf_Word>>
479 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
480   assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
481   const Elf_Word *ShndxTableBegin =
482       reinterpret_cast<const Elf_Word *>(base() + Section.sh_offset);
483   uintX_t Size = Section.sh_size;
484   if (Size % sizeof(uint32_t))
485     return object_error::parse_failed;
486   uintX_t NumSymbols = Size / sizeof(uint32_t);
487   const Elf_Word *ShndxTableEnd = ShndxTableBegin + NumSymbols;
488   if (reinterpret_cast<const char *>(ShndxTableEnd) > Buf.end())
489     return object_error::parse_failed;
490   ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Section.sh_link);
491   if (std::error_code EC = SymTableOrErr.getError())
492     return EC;
493   const Elf_Shdr &SymTable = **SymTableOrErr;
494   if (SymTable.sh_type != ELF::SHT_SYMTAB &&
495       SymTable.sh_type != ELF::SHT_DYNSYM)
496     return object_error::parse_failed;
497   if (NumSymbols != (SymTable.sh_size / sizeof(Elf_Sym)))
498     return object_error::parse_failed;
499   return makeArrayRef(ShndxTableBegin, ShndxTableEnd);
500 }
501
502 template <class ELFT>
503 ErrorOr<StringRef>
504 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
505   if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
506     return object_error::parse_failed;
507   ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
508   if (std::error_code EC = SectionOrErr.getError())
509     return EC;
510   return getStringTable(*SectionOrErr);
511 }
512
513 template <class ELFT>
514 ErrorOr<StringRef>
515 ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
516   uint32_t Offset = Section->sh_name;
517   if (Offset == 0)
518     return StringRef();
519   if (Offset >= DotShstrtab.size())
520     return object_error::parse_failed;
521   return StringRef(DotShstrtab.data() + Offset);
522 }
523
524 /// This function returns the hash value for a symbol in the .dynsym section
525 /// Name of the API remains consistent as specified in the libelf
526 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
527 static inline unsigned elf_hash(StringRef &symbolName) {
528   unsigned h = 0, g;
529   for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
530     h = (h << 4) + symbolName[i];
531     g = h & 0xf0000000L;
532     if (g != 0)
533       h ^= g >> 24;
534     h &= ~g;
535   }
536   return h;
537 }
538 } // end namespace object
539 } // end namespace llvm
540
541 #endif