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