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