Teach llvm-nm to know about fat archives (aka MachOUniversal files
[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   section_iterator getRelocatedSection(DataRefImpl Sec) const override;
93
94   void moveRelocationNext(DataRefImpl &Rel) const override;
95   error_code getRelocationAddress(DataRefImpl Rel,
96                                   uint64_t &Res) const override;
97   error_code getRelocationOffset(DataRefImpl Rel, uint64_t &Res) const override;
98   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
99   error_code getRelocationType(DataRefImpl Rel, uint64_t &Res) const override;
100   error_code getRelocationTypeName(DataRefImpl Rel,
101                                   SmallVectorImpl<char> &Result) const override;
102   error_code getRelocationValueString(DataRefImpl Rel,
103                                   SmallVectorImpl<char> &Result) const override;
104
105   uint64_t getROffset(DataRefImpl Rel) const;
106   StringRef getRelocationTypeName(uint32_t Type) const;
107
108   /// \brief Get the relocation section that contains \a Rel.
109   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
110     return EF.getSection(Rel.d.a);
111   }
112
113   const Elf_Rel *getRel(DataRefImpl Rel) const;
114   const Elf_Rela *getRela(DataRefImpl Rela) const;
115
116   Elf_Sym_Iter toELFSymIter(DataRefImpl Symb) const {
117     bool IsDynamic = Symb.p & 1;
118     if (IsDynamic)
119       return Elf_Sym_Iter(
120           EF.begin_dynamic_symbols().getEntSize(),
121           reinterpret_cast<const char *>(Symb.p & ~uintptr_t(1)), IsDynamic);
122     return Elf_Sym_Iter(EF.begin_symbols().getEntSize(),
123                         reinterpret_cast<const char *>(Symb.p), IsDynamic);
124   }
125
126   DataRefImpl toDRI(Elf_Sym_Iter Symb) const {
127     DataRefImpl DRI;
128     DRI.p = reinterpret_cast<uintptr_t>(Symb.get()) |
129       static_cast<uintptr_t>(Symb.isDynamic());
130     return DRI;
131   }
132
133   Elf_Shdr_Iter toELFShdrIter(DataRefImpl Sec) const {
134     return Elf_Shdr_Iter(EF.getHeader()->e_shentsize,
135                          reinterpret_cast<const char *>(Sec.p));
136   }
137
138   DataRefImpl toDRI(Elf_Shdr_Iter Sec) const {
139     DataRefImpl DRI;
140     DRI.p = reinterpret_cast<uintptr_t>(Sec.get());
141     return DRI;
142   }
143
144   DataRefImpl toDRI(const Elf_Shdr *Sec) const {
145     DataRefImpl DRI;
146     DRI.p = reinterpret_cast<uintptr_t>(Sec);
147     return DRI;
148   }
149
150   Elf_Dyn_Iter toELFDynIter(DataRefImpl Dyn) const {
151     return Elf_Dyn_Iter(EF.begin_dynamic_table().getEntSize(),
152                         reinterpret_cast<const char *>(Dyn.p));
153   }
154
155   DataRefImpl toDRI(Elf_Dyn_Iter Dyn) const {
156     DataRefImpl DRI;
157     DRI.p = reinterpret_cast<uintptr_t>(Dyn.get());
158     return DRI;
159   }
160
161   // This flag is used for classof, to distinguish ELFObjectFile from
162   // its subclass. If more subclasses will be created, this flag will
163   // have to become an enum.
164   bool isDyldELFObject;
165
166 public:
167   ELFObjectFile(MemoryBuffer *Object, error_code &EC, bool BufferOwned = true);
168
169   const Elf_Sym *getSymbol(DataRefImpl Symb) const;
170
171   basic_symbol_iterator symbol_begin_impl() const override;
172   basic_symbol_iterator symbol_end_impl() const override;
173
174   symbol_iterator dynamic_symbol_begin() const;
175   symbol_iterator dynamic_symbol_end() const;
176
177   section_iterator section_begin() const override;
178   section_iterator section_end() const override;
179
180   library_iterator needed_library_begin() const override;
181   library_iterator needed_library_end() const override;
182
183   error_code getRelocationAddend(DataRefImpl Rel, int64_t &Res) const;
184   error_code getSymbolVersion(SymbolRef Symb, StringRef &Version,
185                               bool &IsDefault) const;
186
187
188   uint8_t getBytesInAddress() const override;
189   StringRef getFileFormatName() const override;
190   unsigned getArch() const override;
191   StringRef getLoadName() const override;
192
193   const ELFFile<ELFT> *getELFFile() const { return &EF; }
194
195   bool isDyldType() const { return isDyldELFObject; }
196   static inline bool classof(const Binary *v) {
197     return v->getType() == getELFType(ELFT::TargetEndianness == support::little,
198                                       ELFT::Is64Bits);
199   }
200 };
201
202 // Use an alignment of 2 for the typedefs since that is the worst case for
203 // ELF files in archives.
204 typedef ELFObjectFile<ELFType<support::little, 2, false> > ELF32LEObjectFile;
205 typedef ELFObjectFile<ELFType<support::little, 2, true> > ELF64LEObjectFile;
206 typedef ELFObjectFile<ELFType<support::big, 2, false> > ELF32BEObjectFile;
207 typedef ELFObjectFile<ELFType<support::big, 2, true> > ELF64BEObjectFile;
208
209 template <class ELFT>
210 void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Symb) const {
211   Symb = toDRI(++toELFSymIter(Symb));
212 }
213
214 template <class ELFT>
215 error_code ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Symb,
216                                               StringRef &Result) const {
217   ErrorOr<StringRef> Name = EF.getSymbolName(toELFSymIter(Symb));
218   if (!Name)
219     return Name.getError();
220   Result = *Name;
221   return object_error::success;
222 }
223
224 template <class ELFT>
225 error_code ELFObjectFile<ELFT>::getSymbolVersion(SymbolRef SymRef,
226                                                  StringRef &Version,
227                                                  bool &IsDefault) const {
228   DataRefImpl Symb = SymRef.getRawDataRefImpl();
229   const Elf_Sym *symb = getSymbol(Symb);
230   ErrorOr<StringRef> Ver =
231       EF.getSymbolVersion(EF.getSection(Symb.d.b), symb, IsDefault);
232   if (!Ver)
233     return Ver.getError();
234   Version = *Ver;
235   return object_error::success;
236 }
237
238 template <class ELFT>
239 error_code ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb,
240                                                  uint64_t &Result) const {
241   const Elf_Sym *ESym = getSymbol(Symb);
242   switch (EF.getSymbolTableIndex(ESym)) {
243   case ELF::SHN_COMMON:
244   case ELF::SHN_UNDEF:
245     Result = UnknownAddressOrSize;
246     return object_error::success;
247   case ELF::SHN_ABS:
248     Result = ESym->st_value;
249     return object_error::success;
250   default:
251     break;
252   }
253
254   const Elf_Ehdr *Header = EF.getHeader();
255   Result = ESym->st_value;
256
257   // Clear the ARM/Thumb indicator flag.
258   if (Header->e_machine == ELF::EM_ARM && ESym->getType() == ELF::STT_FUNC)
259     Result &= ~1;
260
261   if (Header->e_type == ELF::ET_REL)
262     Result += EF.getSection(ESym)->sh_addr;
263
264   return object_error::success;
265 }
266
267 template <class ELFT>
268 error_code ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb,
269                                                    uint32_t &Res) const {
270   Elf_Sym_Iter Sym = toELFSymIter(Symb);
271   if (Sym->st_shndx == ELF::SHN_COMMON)
272     Res = Sym->st_value;
273   else
274     Res = 0;
275   return object_error::success;
276 }
277
278 template <class ELFT>
279 error_code ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Symb,
280                                               uint64_t &Result) const {
281   Result = toELFSymIter(Symb)->st_size;
282   return object_error::success;
283 }
284
285 template <class ELFT>
286 error_code ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb,
287                                               SymbolRef::Type &Result) const {
288   const Elf_Sym *ESym = getSymbol(Symb);
289
290   switch (ESym->getType()) {
291   case ELF::STT_NOTYPE:
292     Result = SymbolRef::ST_Unknown;
293     break;
294   case ELF::STT_SECTION:
295     Result = SymbolRef::ST_Debug;
296     break;
297   case ELF::STT_FILE:
298     Result = SymbolRef::ST_File;
299     break;
300   case ELF::STT_FUNC:
301     Result = SymbolRef::ST_Function;
302     break;
303   case ELF::STT_OBJECT:
304   case ELF::STT_COMMON:
305   case ELF::STT_TLS:
306     Result = SymbolRef::ST_Data;
307     break;
308   default:
309     Result = SymbolRef::ST_Other;
310     break;
311   }
312   return object_error::success;
313 }
314
315 template <class ELFT>
316 uint32_t ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Symb) const {
317   Elf_Sym_Iter EIter = toELFSymIter(Symb);
318   const Elf_Sym *ESym = &*EIter;
319
320   uint32_t Result = SymbolRef::SF_None;
321
322   if (ESym->getBinding() != ELF::STB_LOCAL)
323     Result |= SymbolRef::SF_Global;
324
325   if (ESym->getBinding() == ELF::STB_WEAK)
326     Result |= SymbolRef::SF_Weak;
327
328   if (ESym->st_shndx == ELF::SHN_ABS)
329     Result |= SymbolRef::SF_Absolute;
330
331   if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION ||
332       EIter == EF.begin_symbols() || EIter == EF.begin_dynamic_symbols())
333     Result |= SymbolRef::SF_FormatSpecific;
334
335   if (EF.getSymbolTableIndex(ESym) == ELF::SHN_UNDEF)
336     Result |= SymbolRef::SF_Undefined;
337
338   if (ESym->getType() == ELF::STT_COMMON ||
339       EF.getSymbolTableIndex(ESym) == ELF::SHN_COMMON)
340     Result |= SymbolRef::SF_Common;
341
342   return Result;
343 }
344
345 template <class ELFT>
346 error_code ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb,
347                                                  section_iterator &Res) const {
348   const Elf_Sym *ESym = getSymbol(Symb);
349   const Elf_Shdr *ESec = EF.getSection(ESym);
350   if (!ESec)
351     Res = section_end();
352   else {
353     DataRefImpl Sec;
354     Sec.p = reinterpret_cast<intptr_t>(ESec);
355     Res = section_iterator(SectionRef(Sec, this));
356   }
357   return object_error::success;
358 }
359
360 template <class ELFT>
361 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
362   Sec = toDRI(++toELFShdrIter(Sec));
363 }
364
365 template <class ELFT>
366 error_code ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec,
367                                                StringRef &Result) const {
368   ErrorOr<StringRef> Name = EF.getSectionName(&*toELFShdrIter(Sec));
369   if (!Name)
370     return Name.getError();
371   Result = *Name;
372   return object_error::success;
373 }
374
375 template <class ELFT>
376 error_code ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec,
377                                                   uint64_t &Result) const {
378   Result = toELFShdrIter(Sec)->sh_addr;
379   return object_error::success;
380 }
381
382 template <class ELFT>
383 error_code ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec,
384                                                uint64_t &Result) const {
385   Result = toELFShdrIter(Sec)->sh_size;
386   return object_error::success;
387 }
388
389 template <class ELFT>
390 error_code ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec,
391                                                    StringRef &Result) const {
392   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
393   Result = StringRef((const char *)base() + EShdr->sh_offset, EShdr->sh_size);
394   return object_error::success;
395 }
396
397 template <class ELFT>
398 error_code ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec,
399                                                     uint64_t &Result) const {
400   Result = toELFShdrIter(Sec)->sh_addralign;
401   return object_error::success;
402 }
403
404 template <class ELFT>
405 error_code ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec,
406                                               bool &Result) const {
407   Result = toELFShdrIter(Sec)->sh_flags & ELF::SHF_EXECINSTR;
408   return object_error::success;
409 }
410
411 template <class ELFT>
412 error_code ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec,
413                                               bool &Result) const {
414   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
415   Result = EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
416            EShdr->sh_type == ELF::SHT_PROGBITS;
417   return object_error::success;
418 }
419
420 template <class ELFT>
421 error_code ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec,
422                                              bool &Result) const {
423   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
424   Result = EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
425            EShdr->sh_type == ELF::SHT_NOBITS;
426   return object_error::success;
427 }
428
429 template <class ELFT>
430 error_code
431 ELFObjectFile<ELFT>::isSectionRequiredForExecution(DataRefImpl Sec,
432                                                    bool &Result) const {
433   Result = toELFShdrIter(Sec)->sh_flags & ELF::SHF_ALLOC;
434   return object_error::success;
435 }
436
437 template <class ELFT>
438 error_code ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec,
439                                                  bool &Result) const {
440   Result = toELFShdrIter(Sec)->sh_type == ELF::SHT_NOBITS;
441   return object_error::success;
442 }
443
444 template <class ELFT>
445 error_code ELFObjectFile<ELFT>::isSectionZeroInit(DataRefImpl Sec,
446                                                   bool &Result) const {
447   Result = toELFShdrIter(Sec)->sh_type == ELF::SHT_NOBITS;
448   return object_error::success;
449 }
450
451 template <class ELFT>
452 error_code ELFObjectFile<ELFT>::isSectionReadOnlyData(DataRefImpl Sec,
453                                                       bool &Result) const {
454   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
455   Result = !(EShdr->sh_flags & (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
456   return object_error::success;
457 }
458
459 template <class ELFT>
460 error_code ELFObjectFile<ELFT>::sectionContainsSymbol(DataRefImpl Sec,
461                                                       DataRefImpl Symb,
462                                                       bool &Result) const {
463   Elf_Sym_Iter ESym = toELFSymIter(Symb);
464
465   uintX_t Index = ESym->st_shndx;
466   bool Reserved = Index >= ELF::SHN_LORESERVE && Index <= ELF::SHN_HIRESERVE;
467
468   Result = !Reserved && (&*toELFShdrIter(Sec) == EF.getSection(ESym->st_shndx));
469   return object_error::success;
470 }
471
472 template <class ELFT>
473 relocation_iterator
474 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
475   DataRefImpl RelData;
476   uintptr_t SHT = reinterpret_cast<uintptr_t>(EF.begin_sections().get());
477   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
478   RelData.d.b = 0;
479   return relocation_iterator(RelocationRef(RelData, this));
480 }
481
482 template <class ELFT>
483 relocation_iterator
484 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
485   DataRefImpl RelData;
486   uintptr_t SHT = reinterpret_cast<uintptr_t>(EF.begin_sections().get());
487   const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
488   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
489   if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
490     RelData.d.b = 0;
491   else
492     RelData.d.b = S->sh_size / S->sh_entsize;
493
494   return relocation_iterator(RelocationRef(RelData, this));
495 }
496
497 template <class ELFT>
498 section_iterator
499 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
500   if (EF.getHeader()->e_type != ELF::ET_REL)
501     return section_end();
502
503   Elf_Shdr_Iter EShdr = toELFShdrIter(Sec);
504   uintX_t Type = EShdr->sh_type;
505   if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
506     return section_end();
507
508   const Elf_Shdr *R = EF.getSection(EShdr->sh_info);
509   return section_iterator(SectionRef(toDRI(R), this));
510 }
511
512 // Relocations
513 template <class ELFT>
514 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
515   ++Rel.d.b;
516 }
517
518 template <class ELFT>
519 symbol_iterator
520 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
521   uint32_t symbolIdx;
522   const Elf_Shdr *sec = getRelSection(Rel);
523   switch (sec->sh_type) {
524   default:
525     report_fatal_error("Invalid section type in Rel!");
526   case ELF::SHT_REL: {
527     symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
528     break;
529   }
530   case ELF::SHT_RELA: {
531     symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
532     break;
533   }
534   }
535   if (!symbolIdx)
536     return symbol_end();
537
538   const Elf_Shdr *SymSec = EF.getSection(sec->sh_link);
539
540   DataRefImpl SymbolData;
541   switch (SymSec->sh_type) {
542   default:
543     report_fatal_error("Invalid symbol table section type!");
544   case ELF::SHT_SYMTAB:
545     SymbolData = toDRI(EF.begin_symbols() + symbolIdx);
546     break;
547   case ELF::SHT_DYNSYM:
548     SymbolData = toDRI(EF.begin_dynamic_symbols() + symbolIdx);
549     break;
550   }
551
552   return symbol_iterator(SymbolRef(SymbolData, this));
553 }
554
555 template <class ELFT>
556 error_code ELFObjectFile<ELFT>::getRelocationAddress(DataRefImpl Rel,
557                                                      uint64_t &Result) const {
558   uint64_t ROffset = getROffset(Rel);
559   const Elf_Ehdr *Header = EF.getHeader();
560
561   if (Header->e_type == ELF::ET_REL) {
562     const Elf_Shdr *RelocationSec = getRelSection(Rel);
563     const Elf_Shdr *RelocatedSec = EF.getSection(RelocationSec->sh_info);
564     Result = ROffset + RelocatedSec->sh_addr;
565   } else {
566     Result = ROffset;
567   }
568
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