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