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