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