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