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