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