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