Simplify now that we always use an alignment of 2 for ELF files.
[oota-llvm.git] / include / llvm / Object / ELFObjectFile.h
1 //===- ELFObjectFile.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 ELFObjectFile template class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_OBJECT_ELFOBJECTFILE_H
15 #define LLVM_OBJECT_ELFOBJECTFILE_H
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Object/ELF.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ELF.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cctype>
32 #include <limits>
33 #include <utility>
34
35 namespace llvm {
36 namespace object {
37
38 class ELFObjectFileBase : public ObjectFile {
39 protected:
40   ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
41
42 public:
43   virtual std::error_code getRelocationAddend(DataRefImpl Rel,
44                                               int64_t &Res) const = 0;
45   virtual std::pair<symbol_iterator, symbol_iterator>
46   getELFDynamicSymbolIterators() const = 0;
47
48   virtual std::error_code getSymbolVersion(SymbolRef Symb, StringRef &Version,
49                                            bool &IsDefault) const = 0;
50
51   virtual uint64_t getSectionFlags(SectionRef Sec) const = 0;
52   virtual uint32_t getSectionType(SectionRef Sec) const = 0;
53
54   static inline bool classof(const Binary *v) { return v->isELF(); }
55 };
56
57 template <class ELFT> class ELFObjectFile : public ELFObjectFileBase {
58 public:
59   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
60
61   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
62
63   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
64   typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
65   typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
66   typedef typename ELFFile<ELFT>::Elf_Rel Elf_Rel;
67   typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
68   typedef typename ELFFile<ELFT>::Elf_Dyn Elf_Dyn;
69
70   typedef typename ELFFile<ELFT>::Elf_Sym_Iter Elf_Sym_Iter;
71   typedef typename ELFFile<ELFT>::Elf_Shdr_Iter Elf_Shdr_Iter;
72   typedef typename ELFFile<ELFT>::Elf_Dyn_Iter Elf_Dyn_Iter;
73
74 protected:
75   ELFFile<ELFT> EF;
76
77   void moveSymbolNext(DataRefImpl &Symb) const override;
78   std::error_code getSymbolName(DataRefImpl Symb,
79                                 StringRef &Res) const override;
80   std::error_code getSymbolAddress(DataRefImpl Symb,
81                                    uint64_t &Res) const override;
82   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
83   uint64_t getSymbolSize(DataRefImpl Symb) const override;
84   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
85   std::error_code getSymbolOther(DataRefImpl Symb, uint8_t &Res) const override;
86   std::error_code getSymbolType(DataRefImpl Symb,
87                                 SymbolRef::Type &Res) const override;
88   section_iterator getSymbolSection(const Elf_Sym *Symb) const;
89   std::error_code getSymbolSection(DataRefImpl Symb,
90                                    section_iterator &Res) const override;
91
92   void moveSectionNext(DataRefImpl &Sec) const override;
93   std::error_code getSectionName(DataRefImpl Sec,
94                                  StringRef &Res) const override;
95   uint64_t getSectionAddress(DataRefImpl Sec) const override;
96   uint64_t getSectionSize(DataRefImpl Sec) const override;
97   std::error_code getSectionContents(DataRefImpl Sec,
98                                      StringRef &Res) const override;
99   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
100   bool isSectionText(DataRefImpl Sec) const override;
101   bool isSectionData(DataRefImpl Sec) const override;
102   bool isSectionBSS(DataRefImpl Sec) const override;
103   bool isSectionVirtual(DataRefImpl Sec) const override;
104   bool sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb) const override;
105   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
106   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
107   section_iterator getRelocatedSection(DataRefImpl Sec) const override;
108
109   void moveRelocationNext(DataRefImpl &Rel) const override;
110   std::error_code getRelocationAddress(DataRefImpl Rel,
111                                        uint64_t &Res) const override;
112   std::error_code getRelocationOffset(DataRefImpl Rel,
113                                       uint64_t &Res) const override;
114   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
115   section_iterator getRelocationSection(DataRefImpl Rel) const override;
116   std::error_code getRelocationType(DataRefImpl Rel,
117                                     uint64_t &Res) const override;
118   std::error_code
119   getRelocationTypeName(DataRefImpl Rel,
120                         SmallVectorImpl<char> &Result) const override;
121   std::error_code
122   getRelocationValueString(DataRefImpl Rel,
123                            SmallVectorImpl<char> &Result) const override;
124
125   uint64_t getROffset(DataRefImpl Rel) const;
126   StringRef getRelocationTypeName(uint32_t Type) const;
127
128   /// \brief Get the relocation section that contains \a Rel.
129   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
130     return EF.getSection(Rel.d.a);
131   }
132
133   const Elf_Rel *getRel(DataRefImpl Rel) const;
134   const Elf_Rela *getRela(DataRefImpl Rela) const;
135
136   Elf_Sym_Iter toELFSymIter(DataRefImpl Symb) const {
137     bool IsDynamic = Symb.p & 1;
138     if (IsDynamic)
139       return Elf_Sym_Iter(
140           EF.begin_dynamic_symbols().getEntSize(),
141           reinterpret_cast<const char *>(Symb.p & ~uintptr_t(1)), IsDynamic);
142     return Elf_Sym_Iter(EF.begin_symbols().getEntSize(),
143                         reinterpret_cast<const char *>(Symb.p), IsDynamic);
144   }
145
146   DataRefImpl toDRI(Elf_Sym_Iter Symb) const {
147     DataRefImpl DRI;
148     DRI.p = reinterpret_cast<uintptr_t>(Symb.get()) |
149       static_cast<uintptr_t>(Symb.isDynamic());
150     return DRI;
151   }
152
153   Elf_Shdr_Iter toELFShdrIter(DataRefImpl Sec) const {
154     return Elf_Shdr_Iter(EF.getHeader()->e_shentsize,
155                          reinterpret_cast<const char *>(Sec.p));
156   }
157
158   DataRefImpl toDRI(Elf_Shdr_Iter Sec) const {
159     DataRefImpl DRI;
160     DRI.p = reinterpret_cast<uintptr_t>(Sec.get());
161     return DRI;
162   }
163
164   DataRefImpl toDRI(const Elf_Shdr *Sec) const {
165     DataRefImpl DRI;
166     DRI.p = reinterpret_cast<uintptr_t>(Sec);
167     return DRI;
168   }
169
170   Elf_Dyn_Iter toELFDynIter(DataRefImpl Dyn) const {
171     return Elf_Dyn_Iter(EF.begin_dynamic_table().getEntSize(),
172                         reinterpret_cast<const char *>(Dyn.p));
173   }
174
175   DataRefImpl toDRI(Elf_Dyn_Iter Dyn) const {
176     DataRefImpl DRI;
177     DRI.p = reinterpret_cast<uintptr_t>(Dyn.get());
178     return DRI;
179   }
180
181   bool isExportedToOtherDSO(const Elf_Sym *ESym) const {
182     unsigned char Binding = ESym->getBinding();
183     unsigned char Visibility = ESym->getVisibility();
184
185     // A symbol is exported if its binding is either GLOBAL or WEAK, and its
186     // visibility is either DEFAULT or PROTECTED. All other symbols are not
187     // exported.
188     if ((Binding == ELF::STB_GLOBAL || Binding == ELF::STB_WEAK) &&
189         (Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_PROTECTED))
190       return true;
191
192     return false;
193   }
194
195   // This flag is used for classof, to distinguish ELFObjectFile from
196   // its subclass. If more subclasses will be created, this flag will
197   // have to become an enum.
198   bool isDyldELFObject;
199
200 public:
201   ELFObjectFile(MemoryBufferRef Object, std::error_code &EC);
202
203   const Elf_Sym *getSymbol(DataRefImpl Symb) const;
204
205   basic_symbol_iterator symbol_begin_impl() const override;
206   basic_symbol_iterator symbol_end_impl() const override;
207
208   symbol_iterator dynamic_symbol_begin() const;
209   symbol_iterator dynamic_symbol_end() const;
210
211   section_iterator section_begin() const override;
212   section_iterator section_end() const override;
213
214   std::error_code getRelocationAddend(DataRefImpl Rel,
215                                       int64_t &Res) const override;
216   std::error_code getSymbolVersion(SymbolRef Symb, StringRef &Version,
217                                    bool &IsDefault) const override;
218
219   uint64_t getSectionFlags(SectionRef Sec) const override;
220   uint32_t getSectionType(SectionRef Sec) const override;
221
222   uint8_t getBytesInAddress() const override;
223   StringRef getFileFormatName() const override;
224   unsigned getArch() const override;
225   StringRef getLoadName() const;
226
227   std::error_code getPlatformFlags(unsigned &Result) const override {
228     Result = EF.getHeader()->e_flags;
229     return object_error::success;
230   }
231
232   const ELFFile<ELFT> *getELFFile() const { return &EF; }
233
234   bool isDyldType() const { return isDyldELFObject; }
235   static inline bool classof(const Binary *v) {
236     return v->getType() == getELFType(ELFT::TargetEndianness == support::little,
237                                       ELFT::Is64Bits);
238   }
239
240   std::pair<symbol_iterator, symbol_iterator>
241   getELFDynamicSymbolIterators() const override;
242
243   bool isRelocatableObject() const override;
244 };
245
246 typedef ELFObjectFile<ELFType<support::little, false>> ELF32LEObjectFile;
247 typedef ELFObjectFile<ELFType<support::little, true>> ELF64LEObjectFile;
248 typedef ELFObjectFile<ELFType<support::big, false>> ELF32BEObjectFile;
249 typedef ELFObjectFile<ELFType<support::big, true>> ELF64BEObjectFile;
250
251 template <class ELFT>
252 void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Symb) const {
253   Symb = toDRI(++toELFSymIter(Symb));
254 }
255
256 template <class ELFT>
257 std::error_code ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Symb,
258                                                    StringRef &Result) const {
259   ErrorOr<StringRef> Name = EF.getSymbolName(toELFSymIter(Symb));
260   if (!Name)
261     return Name.getError();
262   Result = *Name;
263   return object_error::success;
264 }
265
266 template <class ELFT>
267 std::error_code ELFObjectFile<ELFT>::getSymbolVersion(SymbolRef SymRef,
268                                                       StringRef &Version,
269                                                       bool &IsDefault) const {
270   DataRefImpl Symb = SymRef.getRawDataRefImpl();
271   const Elf_Sym *symb = getSymbol(Symb);
272   ErrorOr<StringRef> Ver =
273       EF.getSymbolVersion(EF.getSection(Symb.d.b), symb, IsDefault);
274   if (!Ver)
275     return Ver.getError();
276   Version = *Ver;
277   return object_error::success;
278 }
279
280 template <class ELFT>
281 uint64_t ELFObjectFile<ELFT>::getSectionFlags(SectionRef Sec) const {
282   DataRefImpl DRI = Sec.getRawDataRefImpl();
283   return toELFShdrIter(DRI)->sh_flags;
284 }
285
286 template <class ELFT>
287 uint32_t ELFObjectFile<ELFT>::getSectionType(SectionRef Sec) const {
288   DataRefImpl DRI = Sec.getRawDataRefImpl();
289   return toELFShdrIter(DRI)->sh_type;
290 }
291
292 template <class ELFT>
293 std::error_code ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb,
294                                                       uint64_t &Result) const {
295   const Elf_Sym *ESym = getSymbol(Symb);
296   switch (EF.getSymbolTableIndex(ESym)) {
297   case ELF::SHN_COMMON:
298   case ELF::SHN_UNDEF:
299     Result = UnknownAddressOrSize;
300     return object_error::success;
301   case ELF::SHN_ABS:
302     Result = ESym->st_value;
303     return object_error::success;
304   default:
305     break;
306   }
307
308   const Elf_Ehdr *Header = EF.getHeader();
309   Result = ESym->st_value;
310
311   // Clear the ARM/Thumb or microMIPS indicator flag.
312   if ((Header->e_machine == ELF::EM_ARM || Header->e_machine == ELF::EM_MIPS) &&
313       ESym->getType() == ELF::STT_FUNC)
314     Result &= ~1;
315
316   if (Header->e_type == ELF::ET_REL) {
317     const typename ELFFile<ELFT>::Elf_Shdr * Section = EF.getSection(ESym);
318     if (Section != nullptr)
319       Result += Section->sh_addr;
320   }
321
322   return object_error::success;
323 }
324
325 template <class ELFT>
326 uint32_t ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb) const {
327   Elf_Sym_Iter Sym = toELFSymIter(Symb);
328   if (Sym->st_shndx == ELF::SHN_COMMON)
329     return Sym->st_value;
330   return 0;
331 }
332
333 template <class ELFT>
334 uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Symb) const {
335   return toELFSymIter(Symb)->st_size;
336 }
337
338 template <class ELFT>
339 std::error_code ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb,
340                                                     uint8_t &Result) const {
341   Result = toELFSymIter(Symb)->st_other;
342   return object_error::success;
343 }
344
345 template <class ELFT>
346 std::error_code
347 ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb,
348                                    SymbolRef::Type &Result) const {
349   const Elf_Sym *ESym = getSymbol(Symb);
350
351   switch (ESym->getType()) {
352   case ELF::STT_NOTYPE:
353     Result = SymbolRef::ST_Unknown;
354     break;
355   case ELF::STT_SECTION:
356     Result = SymbolRef::ST_Debug;
357     break;
358   case ELF::STT_FILE:
359     Result = SymbolRef::ST_File;
360     break;
361   case ELF::STT_FUNC:
362     Result = SymbolRef::ST_Function;
363     break;
364   case ELF::STT_OBJECT:
365   case ELF::STT_COMMON:
366   case ELF::STT_TLS:
367     Result = SymbolRef::ST_Data;
368     break;
369   default:
370     Result = SymbolRef::ST_Other;
371     break;
372   }
373   return object_error::success;
374 }
375
376 template <class ELFT>
377 uint32_t ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Symb) const {
378   Elf_Sym_Iter EIter = toELFSymIter(Symb);
379   const Elf_Sym *ESym = &*EIter;
380
381   uint32_t Result = SymbolRef::SF_None;
382
383   if (ESym->getBinding() != ELF::STB_LOCAL)
384     Result |= SymbolRef::SF_Global;
385
386   if (ESym->getBinding() == ELF::STB_WEAK)
387     Result |= SymbolRef::SF_Weak;
388
389   if (ESym->st_shndx == ELF::SHN_ABS)
390     Result |= SymbolRef::SF_Absolute;
391
392   if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION ||
393       EIter == EF.begin_symbols() || EIter == EF.begin_dynamic_symbols())
394     Result |= SymbolRef::SF_FormatSpecific;
395
396   if (EF.getSymbolTableIndex(ESym) == ELF::SHN_UNDEF)
397     Result |= SymbolRef::SF_Undefined;
398
399   if (ESym->getType() == ELF::STT_COMMON ||
400       EF.getSymbolTableIndex(ESym) == ELF::SHN_COMMON)
401     Result |= SymbolRef::SF_Common;
402
403   if (isExportedToOtherDSO(ESym))
404     Result |= SymbolRef::SF_Exported;
405
406   if (ESym->getVisibility() == ELF::STV_HIDDEN)
407     Result |= SymbolRef::SF_Hidden;
408
409   return Result;
410 }
411
412 template <class ELFT>
413 section_iterator
414 ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym) const {
415   const Elf_Shdr *ESec = EF.getSection(ESym);
416   if (!ESec)
417     return section_end();
418   else {
419     DataRefImpl Sec;
420     Sec.p = reinterpret_cast<intptr_t>(ESec);
421     return section_iterator(SectionRef(Sec, this));
422   }
423 }
424
425 template <class ELFT>
426 std::error_code
427 ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb,
428                                       section_iterator &Res) const {
429   Res = getSymbolSection(getSymbol(Symb));
430   return object_error::success;
431 }
432
433 template <class ELFT>
434 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
435   Sec = toDRI(++toELFShdrIter(Sec));
436 }
437
438 template <class ELFT>
439 std::error_code ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec,
440                                                     StringRef &Result) const {
441   ErrorOr<StringRef> Name = EF.getSectionName(&*toELFShdrIter(Sec));
442   if (!Name)
443     return Name.getError();
444   Result = *Name;
445   return object_error::success;
446 }
447
448 template <class ELFT>
449 uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
450   return toELFShdrIter(Sec)->sh_addr;
451 }
452
453 template <class ELFT>
454 uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
455   return toELFShdrIter(Sec)->sh_size;
456 }
457
458 template <class ELFT>
459 std::error_code
460 ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec,
461                                         StringRef &Result) const {
462   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
463   Result = StringRef((const char *)base() + EShdr->sh_offset, EShdr->sh_size);
464   return object_error::success;
465 }
466
467 template <class ELFT>
468 uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
469   return toELFShdrIter(Sec)->sh_addralign;
470 }
471
472 template <class ELFT>
473 bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
474   return toELFShdrIter(Sec)->sh_flags & ELF::SHF_EXECINSTR;
475 }
476
477 template <class ELFT>
478 bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
479   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
480   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
481          EShdr->sh_type == ELF::SHT_PROGBITS;
482 }
483
484 template <class ELFT>
485 bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
486   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
487   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
488          EShdr->sh_type == ELF::SHT_NOBITS;
489 }
490
491 template <class ELFT>
492 bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
493   return toELFShdrIter(Sec)->sh_type == ELF::SHT_NOBITS;
494 }
495
496 template <class ELFT>
497 bool ELFObjectFile<ELFT>::sectionContainsSymbol(DataRefImpl Sec,
498                                                 DataRefImpl Symb) const {
499   Elf_Sym_Iter ESym = toELFSymIter(Symb);
500
501   uintX_t Index = ESym->st_shndx;
502   bool Reserved = Index >= ELF::SHN_LORESERVE && Index <= ELF::SHN_HIRESERVE;
503
504   return !Reserved && (&*toELFShdrIter(Sec) == EF.getSection(ESym->st_shndx));
505 }
506
507 template <class ELFT>
508 relocation_iterator
509 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
510   DataRefImpl RelData;
511   uintptr_t SHT = reinterpret_cast<uintptr_t>(EF.begin_sections().get());
512   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
513   RelData.d.b = 0;
514   return relocation_iterator(RelocationRef(RelData, this));
515 }
516
517 template <class ELFT>
518 relocation_iterator
519 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
520   DataRefImpl RelData;
521   uintptr_t SHT = reinterpret_cast<uintptr_t>(EF.begin_sections().get());
522   const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
523   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
524   if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
525     RelData.d.b = 0;
526   else
527     RelData.d.b = S->sh_size / S->sh_entsize;
528
529   return relocation_iterator(RelocationRef(RelData, this));
530 }
531
532 template <class ELFT>
533 section_iterator
534 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
535   if (EF.getHeader()->e_type != ELF::ET_REL)
536     return section_end();
537
538   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
539   uintX_t Type = EShdr->sh_type;
540   if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
541     return section_end();
542
543   const Elf_Shdr *R = EF.getSection(EShdr->sh_info);
544   return section_iterator(SectionRef(toDRI(R), this));
545 }
546
547 // Relocations
548 template <class ELFT>
549 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
550   ++Rel.d.b;
551 }
552
553 template <class ELFT>
554 symbol_iterator
555 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
556   uint32_t symbolIdx;
557   const Elf_Shdr *sec = getRelSection(Rel);
558   switch (sec->sh_type) {
559   default:
560     report_fatal_error("Invalid section type in Rel!");
561   case ELF::SHT_REL: {
562     symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
563     break;
564   }
565   case ELF::SHT_RELA: {
566     symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
567     break;
568   }
569   }
570   if (!symbolIdx)
571     return symbol_end();
572
573   const Elf_Shdr *SymSec = EF.getSection(sec->sh_link);
574
575   DataRefImpl SymbolData;
576   switch (SymSec->sh_type) {
577   default:
578     report_fatal_error("Invalid symbol table section type!");
579   case ELF::SHT_SYMTAB:
580     SymbolData = toDRI(EF.begin_symbols() + symbolIdx);
581     break;
582   case ELF::SHT_DYNSYM:
583     SymbolData = toDRI(EF.begin_dynamic_symbols() + symbolIdx);
584     break;
585   }
586
587   return symbol_iterator(SymbolRef(SymbolData, this));
588 }
589
590 // ELF relocations can target sections, by targetting a symbol of type
591 // STT_SECTION
592 template <class ELFT>
593 section_iterator
594 ELFObjectFile<ELFT>::getRelocationSection(DataRefImpl Rel) const {
595   symbol_iterator Sym = getRelocationSymbol(Rel);
596   if (Sym == symbol_end())
597     return section_end();
598   const Elf_Sym *ESym = getSymbol(Sym->getRawDataRefImpl());
599   if (ESym->getType() != ELF::STT_SECTION)
600     return section_end();
601   return getSymbolSection(ESym);
602 }
603
604 template <class ELFT>
605 std::error_code
606 ELFObjectFile<ELFT>::getRelocationAddress(DataRefImpl Rel,
607                                           uint64_t &Result) const {
608   uint64_t ROffset = getROffset(Rel);
609   const Elf_Ehdr *Header = EF.getHeader();
610
611   if (Header->e_type == ELF::ET_REL) {
612     const Elf_Shdr *RelocationSec = getRelSection(Rel);
613     const Elf_Shdr *RelocatedSec = EF.getSection(RelocationSec->sh_info);
614     Result = ROffset + RelocatedSec->sh_addr;
615   } else {
616     Result = ROffset;
617   }
618
619   return object_error::success;
620 }
621
622 template <class ELFT>
623 std::error_code
624 ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel,
625                                          uint64_t &Result) const {
626   assert(EF.getHeader()->e_type == ELF::ET_REL &&
627          "Only relocatable object files have relocation offsets");
628   Result = getROffset(Rel);
629   return object_error::success;
630 }
631
632 template <class ELFT>
633 uint64_t ELFObjectFile<ELFT>::getROffset(DataRefImpl Rel) const {
634   const Elf_Shdr *sec = getRelSection(Rel);
635   switch (sec->sh_type) {
636   default:
637     report_fatal_error("Invalid section type in Rel!");
638   case ELF::SHT_REL:
639     return getRel(Rel)->r_offset;
640   case ELF::SHT_RELA:
641     return getRela(Rel)->r_offset;
642   }
643 }
644
645 template <class ELFT>
646 std::error_code ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel,
647                                                        uint64_t &Result) const {
648   const Elf_Shdr *sec = getRelSection(Rel);
649   switch (sec->sh_type) {
650   default:
651     report_fatal_error("Invalid section type in Rel!");
652   case ELF::SHT_REL: {
653     Result = getRel(Rel)->getType(EF.isMips64EL());
654     break;
655   }
656   case ELF::SHT_RELA: {
657     Result = getRela(Rel)->getType(EF.isMips64EL());
658     break;
659   }
660   }
661   return object_error::success;
662 }
663
664 template <class ELFT>
665 StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
666   return getELFRelocationTypeName(EF.getHeader()->e_machine, Type);
667 }
668
669 template <class ELFT>
670 std::error_code ELFObjectFile<ELFT>::getRelocationTypeName(
671     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
672   const Elf_Shdr *sec = getRelSection(Rel);
673   uint32_t type;
674   switch (sec->sh_type) {
675   default:
676     return object_error::parse_failed;
677   case ELF::SHT_REL: {
678     type = getRel(Rel)->getType(EF.isMips64EL());
679     break;
680   }
681   case ELF::SHT_RELA: {
682     type = getRela(Rel)->getType(EF.isMips64EL());
683     break;
684   }
685   }
686
687   EF.getRelocationTypeName(type, Result);
688   return object_error::success;
689 }
690
691 template <class ELFT>
692 std::error_code
693 ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel,
694                                          int64_t &Result) const {
695   const Elf_Shdr *sec = getRelSection(Rel);
696   switch (sec->sh_type) {
697   default:
698     report_fatal_error("Invalid section type in Rel!");
699   case ELF::SHT_REL: {
700     Result = 0;
701     return object_error::success;
702   }
703   case ELF::SHT_RELA: {
704     Result = getRela(Rel)->r_addend;
705     return object_error::success;
706   }
707   }
708 }
709
710 template <class ELFT>
711 std::error_code ELFObjectFile<ELFT>::getRelocationValueString(
712     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
713   const Elf_Shdr *sec = getRelSection(Rel);
714   uint8_t type;
715   StringRef res;
716   int64_t addend = 0;
717   uint16_t symbol_index = 0;
718   switch (sec->sh_type) {
719   default:
720     return object_error::parse_failed;
721   case ELF::SHT_REL: {
722     type = getRel(Rel)->getType(EF.isMips64EL());
723     symbol_index = getRel(Rel)->getSymbol(EF.isMips64EL());
724     // TODO: Read implicit addend from section data.
725     break;
726   }
727   case ELF::SHT_RELA: {
728     type = getRela(Rel)->getType(EF.isMips64EL());
729     symbol_index = getRela(Rel)->getSymbol(EF.isMips64EL());
730     addend = getRela(Rel)->r_addend;
731     break;
732   }
733   }
734   const Elf_Sym *symb =
735       EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
736   ErrorOr<StringRef> SymName =
737       EF.getSymbolName(EF.getSection(sec->sh_link), symb);
738   if (!SymName)
739     return SymName.getError();
740   switch (EF.getHeader()->e_machine) {
741   case ELF::EM_X86_64:
742     switch (type) {
743     case ELF::R_X86_64_PC8:
744     case ELF::R_X86_64_PC16:
745     case ELF::R_X86_64_PC32: {
746       std::string fmtbuf;
747       raw_string_ostream fmt(fmtbuf);
748       fmt << *SymName << (addend < 0 ? "" : "+") << addend << "-P";
749       fmt.flush();
750       Result.append(fmtbuf.begin(), fmtbuf.end());
751     } break;
752     case ELF::R_X86_64_8:
753     case ELF::R_X86_64_16:
754     case ELF::R_X86_64_32:
755     case ELF::R_X86_64_32S:
756     case ELF::R_X86_64_64: {
757       std::string fmtbuf;
758       raw_string_ostream fmt(fmtbuf);
759       fmt << *SymName << (addend < 0 ? "" : "+") << addend;
760       fmt.flush();
761       Result.append(fmtbuf.begin(), fmtbuf.end());
762     } break;
763     default:
764       res = "Unknown";
765     }
766     break;
767   case ELF::EM_AARCH64: {
768     std::string fmtbuf;
769     raw_string_ostream fmt(fmtbuf);
770     fmt << *SymName;
771     if (addend != 0)
772       fmt << (addend < 0 ? "" : "+") << addend;
773     fmt.flush();
774     Result.append(fmtbuf.begin(), fmtbuf.end());
775     break;
776   }
777   case ELF::EM_386:
778   case ELF::EM_ARM:
779   case ELF::EM_HEXAGON:
780   case ELF::EM_MIPS:
781     res = *SymName;
782     break;
783   default:
784     res = "Unknown";
785   }
786   if (Result.empty())
787     Result.append(res.begin(), res.end());
788   return object_error::success;
789 }
790
791 template <class ELFT>
792 const typename ELFFile<ELFT>::Elf_Sym *
793 ELFObjectFile<ELFT>::getSymbol(DataRefImpl Symb) const {
794   return &*toELFSymIter(Symb);
795 }
796
797 template <class ELFT>
798 const typename ELFObjectFile<ELFT>::Elf_Rel *
799 ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
800   return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
801 }
802
803 template <class ELFT>
804 const typename ELFObjectFile<ELFT>::Elf_Rela *
805 ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
806   return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
807 }
808
809 template <class ELFT>
810 ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, std::error_code &EC)
811     : ELFObjectFileBase(
812           getELFType(static_cast<endianness>(ELFT::TargetEndianness) ==
813                          support::little,
814                      ELFT::Is64Bits),
815           Object),
816       EF(Data.getBuffer(), EC) {}
817
818 template <class ELFT>
819 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin_impl() const {
820   return basic_symbol_iterator(SymbolRef(toDRI(EF.begin_symbols()), this));
821 }
822
823 template <class ELFT>
824 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end_impl() const {
825   return basic_symbol_iterator(SymbolRef(toDRI(EF.end_symbols()), this));
826 }
827
828 template <class ELFT>
829 symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
830   return symbol_iterator(SymbolRef(toDRI(EF.begin_dynamic_symbols()), this));
831 }
832
833 template <class ELFT>
834 symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
835   return symbol_iterator(SymbolRef(toDRI(EF.end_dynamic_symbols()), this));
836 }
837
838 template <class ELFT>
839 section_iterator ELFObjectFile<ELFT>::section_begin() const {
840   return section_iterator(SectionRef(toDRI(EF.begin_sections()), this));
841 }
842
843 template <class ELFT>
844 section_iterator ELFObjectFile<ELFT>::section_end() const {
845   return section_iterator(SectionRef(toDRI(EF.end_sections()), this));
846 }
847
848 template <class ELFT>
849 StringRef ELFObjectFile<ELFT>::getLoadName() const {
850   Elf_Dyn_Iter DI = EF.begin_dynamic_table();
851   Elf_Dyn_Iter DE = EF.end_dynamic_table();
852
853   while (DI != DE && DI->getTag() != ELF::DT_SONAME)
854     ++DI;
855
856   if (DI != DE)
857     return EF.getDynamicString(DI->getVal());
858   return "";
859 }
860
861 template <class ELFT>
862 uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
863   return ELFT::Is64Bits ? 8 : 4;
864 }
865
866 template <class ELFT>
867 StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
868   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
869   switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
870   case ELF::ELFCLASS32:
871     switch (EF.getHeader()->e_machine) {
872     case ELF::EM_386:
873       return "ELF32-i386";
874     case ELF::EM_X86_64:
875       return "ELF32-x86-64";
876     case ELF::EM_ARM:
877       return (IsLittleEndian ? "ELF32-arm-little" : "ELF32-arm-big");
878     case ELF::EM_HEXAGON:
879       return "ELF32-hexagon";
880     case ELF::EM_MIPS:
881       return "ELF32-mips";
882     case ELF::EM_PPC:
883       return "ELF32-ppc";
884     case ELF::EM_SPARC:
885     case ELF::EM_SPARC32PLUS:
886       return "ELF32-sparc";
887     default:
888       return "ELF32-unknown";
889     }
890   case ELF::ELFCLASS64:
891     switch (EF.getHeader()->e_machine) {
892     case ELF::EM_386:
893       return "ELF64-i386";
894     case ELF::EM_X86_64:
895       return "ELF64-x86-64";
896     case ELF::EM_AARCH64:
897       return (IsLittleEndian ? "ELF64-aarch64-little" : "ELF64-aarch64-big");
898     case ELF::EM_PPC64:
899       return "ELF64-ppc64";
900     case ELF::EM_S390:
901       return "ELF64-s390";
902     case ELF::EM_SPARCV9:
903       return "ELF64-sparc";
904     case ELF::EM_MIPS:
905       return "ELF64-mips";
906     default:
907       return "ELF64-unknown";
908     }
909   default:
910     // FIXME: Proper error handling.
911     report_fatal_error("Invalid ELFCLASS!");
912   }
913 }
914
915 template <class ELFT>
916 unsigned ELFObjectFile<ELFT>::getArch() const {
917   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
918   switch (EF.getHeader()->e_machine) {
919   case ELF::EM_386:
920     return Triple::x86;
921   case ELF::EM_X86_64:
922     return Triple::x86_64;
923   case ELF::EM_AARCH64:
924     return Triple::aarch64;
925   case ELF::EM_ARM:
926     return Triple::arm;
927   case ELF::EM_HEXAGON:
928     return Triple::hexagon;
929   case ELF::EM_MIPS:
930     switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
931     case ELF::ELFCLASS32:
932       return IsLittleEndian ? Triple::mipsel : Triple::mips;
933     case ELF::ELFCLASS64:
934       return IsLittleEndian ? Triple::mips64el : Triple::mips64;
935     default:
936       report_fatal_error("Invalid ELFCLASS!");
937     }
938   case ELF::EM_PPC:
939     return Triple::ppc;
940   case ELF::EM_PPC64:
941     return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
942   case ELF::EM_S390:
943     return Triple::systemz;
944
945   case ELF::EM_SPARC:
946   case ELF::EM_SPARC32PLUS:
947     return IsLittleEndian ? Triple::sparcel : Triple::sparc;
948   case ELF::EM_SPARCV9:
949     return Triple::sparcv9;
950
951   default:
952     return Triple::UnknownArch;
953   }
954 }
955
956 template <class ELFT>
957 std::pair<symbol_iterator, symbol_iterator>
958 ELFObjectFile<ELFT>::getELFDynamicSymbolIterators() const {
959   return std::make_pair(dynamic_symbol_begin(), dynamic_symbol_end());
960 }
961
962 template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
963   return EF.getHeader()->e_type == ELF::ET_REL;
964 }
965
966 inline std::error_code getELFRelocationAddend(const RelocationRef R,
967                                               int64_t &Addend) {
968   const ObjectFile *Obj = R.getObjectFile();
969   DataRefImpl DRI = R.getRawDataRefImpl();
970   return cast<ELFObjectFileBase>(Obj)->getRelocationAddend(DRI, Addend);
971 }
972
973 inline std::pair<symbol_iterator, symbol_iterator>
974 getELFDynamicSymbolIterators(const SymbolicFile *Obj) {
975   return cast<ELFObjectFileBase>(Obj)->getELFDynamicSymbolIterators();
976 }
977
978 inline std::error_code GetELFSymbolVersion(const ObjectFile *Obj,
979                                            const SymbolRef &Sym,
980                                            StringRef &Version,
981                                            bool &IsDefault) {
982   return cast<ELFObjectFileBase>(Obj)
983       ->getSymbolVersion(Sym, Version, IsDefault);
984 }
985 }
986 }
987
988 #endif