Simplify another 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   uint64_t getSymbolSize(DataRefImpl Symb) 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 uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Symb) const {
337   return toELFSymIter(Symb)->st_size;
338 }
339
340 template <class ELFT>
341 std::error_code ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb,
342                                                     uint8_t &Result) const {
343   Result = toELFSymIter(Symb)->st_other;
344   return object_error::success;
345 }
346
347 template <class ELFT>
348 std::error_code
349 ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb,
350                                    SymbolRef::Type &Result) const {
351   const Elf_Sym *ESym = getSymbol(Symb);
352
353   switch (ESym->getType()) {
354   case ELF::STT_NOTYPE:
355     Result = SymbolRef::ST_Unknown;
356     break;
357   case ELF::STT_SECTION:
358     Result = SymbolRef::ST_Debug;
359     break;
360   case ELF::STT_FILE:
361     Result = SymbolRef::ST_File;
362     break;
363   case ELF::STT_FUNC:
364     Result = SymbolRef::ST_Function;
365     break;
366   case ELF::STT_OBJECT:
367   case ELF::STT_COMMON:
368   case ELF::STT_TLS:
369     Result = SymbolRef::ST_Data;
370     break;
371   default:
372     Result = SymbolRef::ST_Other;
373     break;
374   }
375   return object_error::success;
376 }
377
378 template <class ELFT>
379 uint32_t ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Symb) const {
380   Elf_Sym_Iter EIter = toELFSymIter(Symb);
381   const Elf_Sym *ESym = &*EIter;
382
383   uint32_t Result = SymbolRef::SF_None;
384
385   if (ESym->getBinding() != ELF::STB_LOCAL)
386     Result |= SymbolRef::SF_Global;
387
388   if (ESym->getBinding() == ELF::STB_WEAK)
389     Result |= SymbolRef::SF_Weak;
390
391   if (ESym->st_shndx == ELF::SHN_ABS)
392     Result |= SymbolRef::SF_Absolute;
393
394   if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION ||
395       EIter == EF.begin_symbols() || EIter == EF.begin_dynamic_symbols())
396     Result |= SymbolRef::SF_FormatSpecific;
397
398   if (EF.getSymbolTableIndex(ESym) == ELF::SHN_UNDEF)
399     Result |= SymbolRef::SF_Undefined;
400
401   if (ESym->getType() == ELF::STT_COMMON ||
402       EF.getSymbolTableIndex(ESym) == ELF::SHN_COMMON)
403     Result |= SymbolRef::SF_Common;
404
405   if (isExportedToOtherDSO(ESym))
406     Result |= SymbolRef::SF_Exported;
407
408   if (ESym->getVisibility() == ELF::STV_HIDDEN)
409     Result |= SymbolRef::SF_Hidden;
410
411   return Result;
412 }
413
414 template <class ELFT>
415 section_iterator
416 ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym) const {
417   const Elf_Shdr *ESec = EF.getSection(ESym);
418   if (!ESec)
419     return section_end();
420   else {
421     DataRefImpl Sec;
422     Sec.p = reinterpret_cast<intptr_t>(ESec);
423     return section_iterator(SectionRef(Sec, this));
424   }
425 }
426
427 template <class ELFT>
428 std::error_code
429 ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb,
430                                       section_iterator &Res) const {
431   Res = getSymbolSection(getSymbol(Symb));
432   return object_error::success;
433 }
434
435 template <class ELFT>
436 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
437   Sec = toDRI(++toELFShdrIter(Sec));
438 }
439
440 template <class ELFT>
441 std::error_code ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec,
442                                                     StringRef &Result) const {
443   ErrorOr<StringRef> Name = EF.getSectionName(&*toELFShdrIter(Sec));
444   if (!Name)
445     return Name.getError();
446   Result = *Name;
447   return object_error::success;
448 }
449
450 template <class ELFT>
451 uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
452   return toELFShdrIter(Sec)->sh_addr;
453 }
454
455 template <class ELFT>
456 uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
457   return toELFShdrIter(Sec)->sh_size;
458 }
459
460 template <class ELFT>
461 std::error_code
462 ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec,
463                                         StringRef &Result) const {
464   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
465   Result = StringRef((const char *)base() + EShdr->sh_offset, EShdr->sh_size);
466   return object_error::success;
467 }
468
469 template <class ELFT>
470 uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
471   return toELFShdrIter(Sec)->sh_addralign;
472 }
473
474 template <class ELFT>
475 bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
476   return toELFShdrIter(Sec)->sh_flags & ELF::SHF_EXECINSTR;
477 }
478
479 template <class ELFT>
480 bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
481   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
482   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
483          EShdr->sh_type == ELF::SHT_PROGBITS;
484 }
485
486 template <class ELFT>
487 bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
488   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
489   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
490          EShdr->sh_type == ELF::SHT_NOBITS;
491 }
492
493 template <class ELFT>
494 bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
495   return toELFShdrIter(Sec)->sh_type == ELF::SHT_NOBITS;
496 }
497
498 template <class ELFT>
499 bool ELFObjectFile<ELFT>::sectionContainsSymbol(DataRefImpl Sec,
500                                                 DataRefImpl Symb) const {
501   Elf_Sym_Iter ESym = toELFSymIter(Symb);
502
503   uintX_t Index = ESym->st_shndx;
504   bool Reserved = Index >= ELF::SHN_LORESERVE && Index <= ELF::SHN_HIRESERVE;
505
506   return !Reserved && (&*toELFShdrIter(Sec) == EF.getSection(ESym->st_shndx));
507 }
508
509 template <class ELFT>
510 relocation_iterator
511 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
512   DataRefImpl RelData;
513   uintptr_t SHT = reinterpret_cast<uintptr_t>(EF.begin_sections().get());
514   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
515   RelData.d.b = 0;
516   return relocation_iterator(RelocationRef(RelData, this));
517 }
518
519 template <class ELFT>
520 relocation_iterator
521 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
522   DataRefImpl RelData;
523   uintptr_t SHT = reinterpret_cast<uintptr_t>(EF.begin_sections().get());
524   const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
525   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
526   if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
527     RelData.d.b = 0;
528   else
529     RelData.d.b = S->sh_size / S->sh_entsize;
530
531   return relocation_iterator(RelocationRef(RelData, this));
532 }
533
534 template <class ELFT>
535 section_iterator
536 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
537   if (EF.getHeader()->e_type != ELF::ET_REL)
538     return section_end();
539
540   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
541   uintX_t Type = EShdr->sh_type;
542   if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
543     return section_end();
544
545   const Elf_Shdr *R = EF.getSection(EShdr->sh_info);
546   return section_iterator(SectionRef(toDRI(R), this));
547 }
548
549 // Relocations
550 template <class ELFT>
551 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
552   ++Rel.d.b;
553 }
554
555 template <class ELFT>
556 symbol_iterator
557 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
558   uint32_t symbolIdx;
559   const Elf_Shdr *sec = getRelSection(Rel);
560   switch (sec->sh_type) {
561   default:
562     report_fatal_error("Invalid section type in Rel!");
563   case ELF::SHT_REL: {
564     symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
565     break;
566   }
567   case ELF::SHT_RELA: {
568     symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
569     break;
570   }
571   }
572   if (!symbolIdx)
573     return symbol_end();
574
575   const Elf_Shdr *SymSec = EF.getSection(sec->sh_link);
576
577   DataRefImpl SymbolData;
578   switch (SymSec->sh_type) {
579   default:
580     report_fatal_error("Invalid symbol table section type!");
581   case ELF::SHT_SYMTAB:
582     SymbolData = toDRI(EF.begin_symbols() + symbolIdx);
583     break;
584   case ELF::SHT_DYNSYM:
585     SymbolData = toDRI(EF.begin_dynamic_symbols() + symbolIdx);
586     break;
587   }
588
589   return symbol_iterator(SymbolRef(SymbolData, this));
590 }
591
592 // ELF relocations can target sections, by targetting a symbol of type
593 // STT_SECTION
594 template <class ELFT>
595 section_iterator
596 ELFObjectFile<ELFT>::getRelocationSection(DataRefImpl Rel) const {
597   symbol_iterator Sym = getRelocationSymbol(Rel);
598   if (Sym == symbol_end())
599     return section_end();
600   const Elf_Sym *ESym = getSymbol(Sym->getRawDataRefImpl());
601   if (ESym->getType() != ELF::STT_SECTION)
602     return section_end();
603   return getSymbolSection(ESym);
604 }
605
606 template <class ELFT>
607 std::error_code
608 ELFObjectFile<ELFT>::getRelocationAddress(DataRefImpl Rel,
609                                           uint64_t &Result) const {
610   uint64_t ROffset = getROffset(Rel);
611   const Elf_Ehdr *Header = EF.getHeader();
612
613   if (Header->e_type == ELF::ET_REL) {
614     const Elf_Shdr *RelocationSec = getRelSection(Rel);
615     const Elf_Shdr *RelocatedSec = EF.getSection(RelocationSec->sh_info);
616     Result = ROffset + RelocatedSec->sh_addr;
617   } else {
618     Result = ROffset;
619   }
620
621   return object_error::success;
622 }
623
624 template <class ELFT>
625 std::error_code
626 ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel,
627                                          uint64_t &Result) const {
628   assert(EF.getHeader()->e_type == ELF::ET_REL &&
629          "Only relocatable object files have relocation offsets");
630   Result = getROffset(Rel);
631   return object_error::success;
632 }
633
634 template <class ELFT>
635 uint64_t ELFObjectFile<ELFT>::getROffset(DataRefImpl Rel) const {
636   const Elf_Shdr *sec = getRelSection(Rel);
637   switch (sec->sh_type) {
638   default:
639     report_fatal_error("Invalid section type in Rel!");
640   case ELF::SHT_REL:
641     return getRel(Rel)->r_offset;
642   case ELF::SHT_RELA:
643     return getRela(Rel)->r_offset;
644   }
645 }
646
647 template <class ELFT>
648 std::error_code ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel,
649                                                        uint64_t &Result) const {
650   const Elf_Shdr *sec = getRelSection(Rel);
651   switch (sec->sh_type) {
652   default:
653     report_fatal_error("Invalid section type in Rel!");
654   case ELF::SHT_REL: {
655     Result = getRel(Rel)->getType(EF.isMips64EL());
656     break;
657   }
658   case ELF::SHT_RELA: {
659     Result = getRela(Rel)->getType(EF.isMips64EL());
660     break;
661   }
662   }
663   return object_error::success;
664 }
665
666 template <class ELFT>
667 StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
668   return getELFRelocationTypeName(EF.getHeader()->e_machine, Type);
669 }
670
671 template <class ELFT>
672 std::error_code ELFObjectFile<ELFT>::getRelocationTypeName(
673     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
674   const Elf_Shdr *sec = getRelSection(Rel);
675   uint32_t type;
676   switch (sec->sh_type) {
677   default:
678     return object_error::parse_failed;
679   case ELF::SHT_REL: {
680     type = getRel(Rel)->getType(EF.isMips64EL());
681     break;
682   }
683   case ELF::SHT_RELA: {
684     type = getRela(Rel)->getType(EF.isMips64EL());
685     break;
686   }
687   }
688
689   EF.getRelocationTypeName(type, Result);
690   return object_error::success;
691 }
692
693 template <class ELFT>
694 std::error_code
695 ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel,
696                                          int64_t &Result) const {
697   const Elf_Shdr *sec = getRelSection(Rel);
698   switch (sec->sh_type) {
699   default:
700     report_fatal_error("Invalid section type in Rel!");
701   case ELF::SHT_REL: {
702     Result = 0;
703     return object_error::success;
704   }
705   case ELF::SHT_RELA: {
706     Result = getRela(Rel)->r_addend;
707     return object_error::success;
708   }
709   }
710 }
711
712 template <class ELFT>
713 std::error_code ELFObjectFile<ELFT>::getRelocationValueString(
714     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
715   const Elf_Shdr *sec = getRelSection(Rel);
716   uint8_t type;
717   StringRef res;
718   int64_t addend = 0;
719   uint16_t symbol_index = 0;
720   switch (sec->sh_type) {
721   default:
722     return object_error::parse_failed;
723   case ELF::SHT_REL: {
724     type = getRel(Rel)->getType(EF.isMips64EL());
725     symbol_index = getRel(Rel)->getSymbol(EF.isMips64EL());
726     // TODO: Read implicit addend from section data.
727     break;
728   }
729   case ELF::SHT_RELA: {
730     type = getRela(Rel)->getType(EF.isMips64EL());
731     symbol_index = getRela(Rel)->getSymbol(EF.isMips64EL());
732     addend = getRela(Rel)->r_addend;
733     break;
734   }
735   }
736   const Elf_Sym *symb =
737       EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
738   ErrorOr<StringRef> SymName =
739       EF.getSymbolName(EF.getSection(sec->sh_link), symb);
740   if (!SymName)
741     return SymName.getError();
742   switch (EF.getHeader()->e_machine) {
743   case ELF::EM_X86_64:
744     switch (type) {
745     case ELF::R_X86_64_PC8:
746     case ELF::R_X86_64_PC16:
747     case ELF::R_X86_64_PC32: {
748       std::string fmtbuf;
749       raw_string_ostream fmt(fmtbuf);
750       fmt << *SymName << (addend < 0 ? "" : "+") << addend << "-P";
751       fmt.flush();
752       Result.append(fmtbuf.begin(), fmtbuf.end());
753     } break;
754     case ELF::R_X86_64_8:
755     case ELF::R_X86_64_16:
756     case ELF::R_X86_64_32:
757     case ELF::R_X86_64_32S:
758     case ELF::R_X86_64_64: {
759       std::string fmtbuf;
760       raw_string_ostream fmt(fmtbuf);
761       fmt << *SymName << (addend < 0 ? "" : "+") << addend;
762       fmt.flush();
763       Result.append(fmtbuf.begin(), fmtbuf.end());
764     } break;
765     default:
766       res = "Unknown";
767     }
768     break;
769   case ELF::EM_AARCH64: {
770     std::string fmtbuf;
771     raw_string_ostream fmt(fmtbuf);
772     fmt << *SymName;
773     if (addend != 0)
774       fmt << (addend < 0 ? "" : "+") << addend;
775     fmt.flush();
776     Result.append(fmtbuf.begin(), fmtbuf.end());
777     break;
778   }
779   case ELF::EM_386:
780   case ELF::EM_ARM:
781   case ELF::EM_HEXAGON:
782   case ELF::EM_MIPS:
783     res = *SymName;
784     break;
785   default:
786     res = "Unknown";
787   }
788   if (Result.empty())
789     Result.append(res.begin(), res.end());
790   return object_error::success;
791 }
792
793 template <class ELFT>
794 const typename ELFFile<ELFT>::Elf_Sym *
795 ELFObjectFile<ELFT>::getSymbol(DataRefImpl Symb) const {
796   return &*toELFSymIter(Symb);
797 }
798
799 template <class ELFT>
800 const typename ELFObjectFile<ELFT>::Elf_Rel *
801 ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
802   return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
803 }
804
805 template <class ELFT>
806 const typename ELFObjectFile<ELFT>::Elf_Rela *
807 ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
808   return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
809 }
810
811 template <class ELFT>
812 ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, std::error_code &EC)
813     : ELFObjectFileBase(
814           getELFType(static_cast<endianness>(ELFT::TargetEndianness) ==
815                          support::little,
816                      ELFT::Is64Bits),
817           Object),
818       EF(Data.getBuffer(), EC) {}
819
820 template <class ELFT>
821 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin_impl() const {
822   return basic_symbol_iterator(SymbolRef(toDRI(EF.begin_symbols()), this));
823 }
824
825 template <class ELFT>
826 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end_impl() const {
827   return basic_symbol_iterator(SymbolRef(toDRI(EF.end_symbols()), this));
828 }
829
830 template <class ELFT>
831 symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
832   return symbol_iterator(SymbolRef(toDRI(EF.begin_dynamic_symbols()), this));
833 }
834
835 template <class ELFT>
836 symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
837   return symbol_iterator(SymbolRef(toDRI(EF.end_dynamic_symbols()), this));
838 }
839
840 template <class ELFT>
841 section_iterator ELFObjectFile<ELFT>::section_begin() const {
842   return section_iterator(SectionRef(toDRI(EF.begin_sections()), this));
843 }
844
845 template <class ELFT>
846 section_iterator ELFObjectFile<ELFT>::section_end() const {
847   return section_iterator(SectionRef(toDRI(EF.end_sections()), this));
848 }
849
850 template <class ELFT>
851 StringRef ELFObjectFile<ELFT>::getLoadName() const {
852   Elf_Dyn_Iter DI = EF.begin_dynamic_table();
853   Elf_Dyn_Iter DE = EF.end_dynamic_table();
854
855   while (DI != DE && DI->getTag() != ELF::DT_SONAME)
856     ++DI;
857
858   if (DI != DE)
859     return EF.getDynamicString(DI->getVal());
860   return "";
861 }
862
863 template <class ELFT>
864 uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
865   return ELFT::Is64Bits ? 8 : 4;
866 }
867
868 template <class ELFT>
869 StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
870   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
871   switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
872   case ELF::ELFCLASS32:
873     switch (EF.getHeader()->e_machine) {
874     case ELF::EM_386:
875       return "ELF32-i386";
876     case ELF::EM_X86_64:
877       return "ELF32-x86-64";
878     case ELF::EM_ARM:
879       return (IsLittleEndian ? "ELF32-arm-little" : "ELF32-arm-big");
880     case ELF::EM_HEXAGON:
881       return "ELF32-hexagon";
882     case ELF::EM_MIPS:
883       return "ELF32-mips";
884     case ELF::EM_PPC:
885       return "ELF32-ppc";
886     case ELF::EM_SPARC:
887     case ELF::EM_SPARC32PLUS:
888       return "ELF32-sparc";
889     default:
890       return "ELF32-unknown";
891     }
892   case ELF::ELFCLASS64:
893     switch (EF.getHeader()->e_machine) {
894     case ELF::EM_386:
895       return "ELF64-i386";
896     case ELF::EM_X86_64:
897       return "ELF64-x86-64";
898     case ELF::EM_AARCH64:
899       return (IsLittleEndian ? "ELF64-aarch64-little" : "ELF64-aarch64-big");
900     case ELF::EM_PPC64:
901       return "ELF64-ppc64";
902     case ELF::EM_S390:
903       return "ELF64-s390";
904     case ELF::EM_SPARCV9:
905       return "ELF64-sparc";
906     case ELF::EM_MIPS:
907       return "ELF64-mips";
908     default:
909       return "ELF64-unknown";
910     }
911   default:
912     // FIXME: Proper error handling.
913     report_fatal_error("Invalid ELFCLASS!");
914   }
915 }
916
917 template <class ELFT>
918 unsigned ELFObjectFile<ELFT>::getArch() const {
919   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
920   switch (EF.getHeader()->e_machine) {
921   case ELF::EM_386:
922     return Triple::x86;
923   case ELF::EM_X86_64:
924     return Triple::x86_64;
925   case ELF::EM_AARCH64:
926     return Triple::aarch64;
927   case ELF::EM_ARM:
928     return Triple::arm;
929   case ELF::EM_HEXAGON:
930     return Triple::hexagon;
931   case ELF::EM_MIPS:
932     switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
933     case ELF::ELFCLASS32:
934       return IsLittleEndian ? Triple::mipsel : Triple::mips;
935     case ELF::ELFCLASS64:
936       return IsLittleEndian ? Triple::mips64el : Triple::mips64;
937     default:
938       report_fatal_error("Invalid ELFCLASS!");
939     }
940   case ELF::EM_PPC:
941     return Triple::ppc;
942   case ELF::EM_PPC64:
943     return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
944   case ELF::EM_S390:
945     return Triple::systemz;
946
947   case ELF::EM_SPARC:
948   case ELF::EM_SPARC32PLUS:
949     return IsLittleEndian ? Triple::sparcel : Triple::sparc;
950   case ELF::EM_SPARCV9:
951     return Triple::sparcv9;
952
953   default:
954     return Triple::UnknownArch;
955   }
956 }
957
958 template <class ELFT>
959 std::pair<symbol_iterator, symbol_iterator>
960 ELFObjectFile<ELFT>::getELFDynamicSymbolIterators() const {
961   return std::make_pair(dynamic_symbol_begin(), dynamic_symbol_end());
962 }
963
964 template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
965   return EF.getHeader()->e_type == ELF::ET_REL;
966 }
967
968 inline std::error_code getELFRelocationAddend(const RelocationRef R,
969                                               int64_t &Addend) {
970   const ObjectFile *Obj = R.getObjectFile();
971   DataRefImpl DRI = R.getRawDataRefImpl();
972   return cast<ELFObjectFileBase>(Obj)->getRelocationAddend(DRI, Addend);
973 }
974
975 inline std::pair<symbol_iterator, symbol_iterator>
976 getELFDynamicSymbolIterators(const SymbolicFile *Obj) {
977   return cast<ELFObjectFileBase>(Obj)->getELFDynamicSymbolIterators();
978 }
979
980 inline std::error_code GetELFSymbolVersion(const ObjectFile *Obj,
981                                            const SymbolRef &Sym,
982                                            StringRef &Version,
983                                            bool &IsDefault) {
984   return cast<ELFObjectFileBase>(Obj)
985       ->getSymbolVersion(Sym, Version, IsDefault);
986 }
987 }
988 }
989
990 #endif