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