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