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