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