Fix the build with MSVC 2013 by explicitly requesting llvm::make_unique
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldELF.cpp
1 //===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- 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 // Implementation of ELF support for the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "RuntimeDyldELF.h"
15 #include "JITRegistrar.h"
16 #include "ObjectImageCommon.h"
17 #include "llvm/ADT/IntervalMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/ObjectBuffer.h"
22 #include "llvm/ExecutionEngine/ObjectImage.h"
23 #include "llvm/Object/ELFObjectFile.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/ELF.h"
26 #include "llvm/Support/MemoryBuffer.h"
27
28 using namespace llvm;
29 using namespace llvm::object;
30
31 #define DEBUG_TYPE "dyld"
32
33 namespace {
34
35 static inline error_code check(error_code Err) {
36   if (Err) {
37     report_fatal_error(Err.message());
38   }
39   return Err;
40 }
41
42 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
43   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
44
45   typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
46   typedef Elf_Sym_Impl<ELFT> Elf_Sym;
47   typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
48   typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
49
50   typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
51
52   typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
53
54   std::unique_ptr<ObjectFile> UnderlyingFile;
55
56 public:
57   DyldELFObject(std::unique_ptr<ObjectFile> UnderlyingFile,
58                 MemoryBuffer *Wrapper, error_code &ec);
59
60   DyldELFObject(MemoryBuffer *Wrapper, error_code &ec);
61
62   void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
63   void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
64
65   // Methods for type inquiry through isa, cast and dyn_cast
66   static inline bool classof(const Binary *v) {
67     return (isa<ELFObjectFile<ELFT>>(v) &&
68             classof(cast<ELFObjectFile<ELFT>>(v)));
69   }
70   static inline bool classof(const ELFObjectFile<ELFT> *v) {
71     return v->isDyldType();
72   }
73 };
74
75 template <class ELFT> class ELFObjectImage : public ObjectImageCommon {
76   bool Registered;
77
78 public:
79   ELFObjectImage(ObjectBuffer *Input, std::unique_ptr<DyldELFObject<ELFT>> Obj)
80       : ObjectImageCommon(Input, std::move(Obj)), Registered(false) {}
81
82   virtual ~ELFObjectImage() {
83     if (Registered)
84       deregisterWithDebugger();
85   }
86
87   // Subclasses can override these methods to update the image with loaded
88   // addresses for sections and common symbols
89   void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) override {
90     static_cast<DyldELFObject<ELFT>*>(getObjectFile())
91         ->updateSectionAddress(Sec, Addr);
92   }
93
94   void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) override {
95     static_cast<DyldELFObject<ELFT>*>(getObjectFile())
96         ->updateSymbolAddress(Sym, Addr);
97   }
98
99   void registerWithDebugger() override {
100     JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
101     Registered = true;
102   }
103   void deregisterWithDebugger() override {
104     JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
105   }
106 };
107
108 // The MemoryBuffer passed into this constructor is just a wrapper around the
109 // actual memory.  Ultimately, the Binary parent class will take ownership of
110 // this MemoryBuffer object but not the underlying memory.
111 template <class ELFT>
112 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
113     : ELFObjectFile<ELFT>(Wrapper, ec) {
114   this->isDyldELFObject = true;
115 }
116
117 template <class ELFT>
118 DyldELFObject<ELFT>::DyldELFObject(std::unique_ptr<ObjectFile> UnderlyingFile,
119                                    MemoryBuffer *Wrapper, error_code &ec)
120     : ELFObjectFile<ELFT>(Wrapper, ec),
121       UnderlyingFile(std::move(UnderlyingFile)) {
122   this->isDyldELFObject = true;
123 }
124
125 template <class ELFT>
126 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
127                                                uint64_t Addr) {
128   DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
129   Elf_Shdr *shdr =
130       const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
131
132   // This assumes the address passed in matches the target address bitness
133   // The template-based type cast handles everything else.
134   shdr->sh_addr = static_cast<addr_type>(Addr);
135 }
136
137 template <class ELFT>
138 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
139                                               uint64_t Addr) {
140
141   Elf_Sym *sym = const_cast<Elf_Sym *>(
142       ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
143
144   // This assumes the address passed in matches the target address bitness
145   // The template-based type cast handles everything else.
146   sym->st_value = static_cast<addr_type>(Addr);
147 }
148
149 } // namespace
150
151 namespace llvm {
152
153 void RuntimeDyldELF::registerEHFrames() {
154   if (!MemMgr)
155     return;
156   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
157     SID EHFrameSID = UnregisteredEHFrameSections[i];
158     uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
159     uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
160     size_t EHFrameSize = Sections[EHFrameSID].Size;
161     MemMgr->registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
162     RegisteredEHFrameSections.push_back(EHFrameSID);
163   }
164   UnregisteredEHFrameSections.clear();
165 }
166
167 void RuntimeDyldELF::deregisterEHFrames() {
168   if (!MemMgr)
169     return;
170   for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) {
171     SID EHFrameSID = RegisteredEHFrameSections[i];
172     uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
173     uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
174     size_t EHFrameSize = Sections[EHFrameSID].Size;
175     MemMgr->deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
176   }
177   RegisteredEHFrameSections.clear();
178 }
179
180 ObjectImage *
181 RuntimeDyldELF::createObjectImageFromFile(std::unique_ptr<object::ObjectFile> ObjFile) {
182   if (!ObjFile)
183     return nullptr;
184
185   error_code ec;
186   MemoryBuffer *Buffer =
187       MemoryBuffer::getMemBuffer(ObjFile->getData(), "", false);
188
189   if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
190     auto Obj =
191         llvm::make_unique<DyldELFObject<ELFType<support::little, 2, false>>>(
192             std::move(ObjFile), Buffer, ec);
193     return new ELFObjectImage<ELFType<support::little, 2, false>>(
194         nullptr, std::move(Obj));
195   } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
196     auto Obj =
197         llvm::make_unique<DyldELFObject<ELFType<support::big, 2, false>>>(
198             std::move(ObjFile), Buffer, ec);
199     return new ELFObjectImage<ELFType<support::big, 2, false>>(nullptr, std::move(Obj));
200   } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
201     auto Obj = llvm::make_unique<DyldELFObject<ELFType<support::big, 2, true>>>(
202         std::move(ObjFile), Buffer, ec);
203     return new ELFObjectImage<ELFType<support::big, 2, true>>(nullptr,
204                                                               std::move(Obj));
205   } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
206     auto Obj =
207         llvm::make_unique<DyldELFObject<ELFType<support::little, 2, true>>>(
208             std::move(ObjFile), Buffer, ec);
209     return new ELFObjectImage<ELFType<support::little, 2, true>>(
210         nullptr, std::move(Obj));
211   } else
212     llvm_unreachable("Unexpected ELF format");
213 }
214
215 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
216   if (Buffer->getBufferSize() < ELF::EI_NIDENT)
217     llvm_unreachable("Unexpected ELF object size");
218   std::pair<unsigned char, unsigned char> Ident =
219       std::make_pair((uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
220                      (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
221   error_code ec;
222
223   if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
224     auto Obj =
225         llvm::make_unique<DyldELFObject<ELFType<support::little, 4, false>>>(
226             Buffer->getMemBuffer(), ec);
227     return new ELFObjectImage<ELFType<support::little, 4, false>>(
228         Buffer, std::move(Obj));
229   } else if (Ident.first == ELF::ELFCLASS32 &&
230              Ident.second == ELF::ELFDATA2MSB) {
231     auto Obj =
232         llvm::make_unique<DyldELFObject<ELFType<support::big, 4, false>>>(
233             Buffer->getMemBuffer(), ec);
234     return new ELFObjectImage<ELFType<support::big, 4, false>>(Buffer,
235                                                                std::move(Obj));
236   } else if (Ident.first == ELF::ELFCLASS64 &&
237              Ident.second == ELF::ELFDATA2MSB) {
238     auto Obj = llvm::make_unique<DyldELFObject<ELFType<support::big, 8, true>>>(
239         Buffer->getMemBuffer(), ec);
240     return new ELFObjectImage<ELFType<support::big, 8, true>>(Buffer, std::move(Obj));
241   } else if (Ident.first == ELF::ELFCLASS64 &&
242              Ident.second == ELF::ELFDATA2LSB) {
243     auto Obj =
244         llvm::make_unique<DyldELFObject<ELFType<support::little, 8, true>>>(
245             Buffer->getMemBuffer(), ec);
246     return new ELFObjectImage<ELFType<support::little, 8, true>>(Buffer, std::move(Obj));
247   } else
248     llvm_unreachable("Unexpected ELF format");
249 }
250
251 RuntimeDyldELF::~RuntimeDyldELF() {}
252
253 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
254                                              uint64_t Offset, uint64_t Value,
255                                              uint32_t Type, int64_t Addend,
256                                              uint64_t SymOffset) {
257   switch (Type) {
258   default:
259     llvm_unreachable("Relocation type not implemented yet!");
260     break;
261   case ELF::R_X86_64_64: {
262     uint64_t *Target = reinterpret_cast<uint64_t *>(Section.Address + Offset);
263     *Target = Value + Addend;
264     DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
265                  << format("%p\n", Target));
266     break;
267   }
268   case ELF::R_X86_64_32:
269   case ELF::R_X86_64_32S: {
270     Value += Addend;
271     assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
272            (Type == ELF::R_X86_64_32S &&
273             ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
274     uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
275     uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
276     *Target = TruncatedAddr;
277     DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
278                  << format("%p\n", Target));
279     break;
280   }
281   case ELF::R_X86_64_GOTPCREL: {
282     // findGOTEntry returns the 'G + GOT' part of the relocation calculation
283     // based on the load/target address of the GOT (not the current/local addr).
284     uint64_t GOTAddr = findGOTEntry(Value, SymOffset);
285     uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
286     uint64_t FinalAddress = Section.LoadAddress + Offset;
287     // The processRelocationRef method combines the symbol offset and the addend
288     // and in most cases that's what we want.  For this relocation type, we need
289     // the raw addend, so we subtract the symbol offset to get it.
290     int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress;
291     assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
292     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
293     *Target = TruncOffset;
294     break;
295   }
296   case ELF::R_X86_64_PC32: {
297     // Get the placeholder value from the generated object since
298     // a previous relocation attempt may have overwritten the loaded version
299     uint32_t *Placeholder =
300         reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
301     uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
302     uint64_t FinalAddress = Section.LoadAddress + Offset;
303     int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
304     assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
305     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
306     *Target = TruncOffset;
307     break;
308   }
309   case ELF::R_X86_64_PC64: {
310     // Get the placeholder value from the generated object since
311     // a previous relocation attempt may have overwritten the loaded version
312     uint64_t *Placeholder =
313         reinterpret_cast<uint64_t *>(Section.ObjAddress + Offset);
314     uint64_t *Target = reinterpret_cast<uint64_t *>(Section.Address + Offset);
315     uint64_t FinalAddress = Section.LoadAddress + Offset;
316     *Target = *Placeholder + Value + Addend - FinalAddress;
317     break;
318   }
319   }
320 }
321
322 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
323                                           uint64_t Offset, uint32_t Value,
324                                           uint32_t Type, int32_t Addend) {
325   switch (Type) {
326   case ELF::R_386_32: {
327     // Get the placeholder value from the generated object since
328     // a previous relocation attempt may have overwritten the loaded version
329     uint32_t *Placeholder =
330         reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
331     uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
332     *Target = *Placeholder + Value + Addend;
333     break;
334   }
335   case ELF::R_386_PC32: {
336     // Get the placeholder value from the generated object since
337     // a previous relocation attempt may have overwritten the loaded version
338     uint32_t *Placeholder =
339         reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
340     uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
341     uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
342     uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
343     *Target = RealOffset;
344     break;
345   }
346   default:
347     // There are other relocation types, but it appears these are the
348     // only ones currently used by the LLVM ELF object writer
349     llvm_unreachable("Relocation type not implemented yet!");
350     break;
351   }
352 }
353
354 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
355                                               uint64_t Offset, uint64_t Value,
356                                               uint32_t Type, int64_t Addend) {
357   uint32_t *TargetPtr = reinterpret_cast<uint32_t *>(Section.Address + Offset);
358   uint64_t FinalAddress = Section.LoadAddress + Offset;
359
360   DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
361                << format("%llx", Section.Address + Offset)
362                << " FinalAddress: 0x" << format("%llx", FinalAddress)
363                << " Value: 0x" << format("%llx", Value) << " Type: 0x"
364                << format("%x", Type) << " Addend: 0x" << format("%llx", Addend)
365                << "\n");
366
367   switch (Type) {
368   default:
369     llvm_unreachable("Relocation type not implemented yet!");
370     break;
371   case ELF::R_AARCH64_ABS64: {
372     uint64_t *TargetPtr =
373         reinterpret_cast<uint64_t *>(Section.Address + Offset);
374     *TargetPtr = Value + Addend;
375     break;
376   }
377   case ELF::R_AARCH64_PREL32: {
378     uint64_t Result = Value + Addend - FinalAddress;
379     assert(static_cast<int64_t>(Result) >= INT32_MIN &&
380            static_cast<int64_t>(Result) <= UINT32_MAX);
381     *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
382     break;
383   }
384   case ELF::R_AARCH64_CALL26: // fallthrough
385   case ELF::R_AARCH64_JUMP26: {
386     // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
387     // calculation.
388     uint64_t BranchImm = Value + Addend - FinalAddress;
389
390     // "Check that -2^27 <= result < 2^27".
391     assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
392            static_cast<int64_t>(BranchImm) < (1LL << 27));
393
394     // AArch64 code is emitted with .rela relocations. The data already in any
395     // bits affected by the relocation on entry is garbage.
396     *TargetPtr &= 0xfc000000U;
397     // Immediate goes in bits 25:0 of B and BL.
398     *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
399     break;
400   }
401   case ELF::R_AARCH64_MOVW_UABS_G3: {
402     uint64_t Result = Value + Addend;
403
404     // AArch64 code is emitted with .rela relocations. The data already in any
405     // bits affected by the relocation on entry is garbage.
406     *TargetPtr &= 0xffe0001fU;
407     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
408     *TargetPtr |= Result >> (48 - 5);
409     // Shift must be "lsl #48", in bits 22:21
410     assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
411     break;
412   }
413   case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
414     uint64_t Result = Value + Addend;
415
416     // AArch64 code is emitted with .rela relocations. The data already in any
417     // bits affected by the relocation on entry is garbage.
418     *TargetPtr &= 0xffe0001fU;
419     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
420     *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
421     // Shift must be "lsl #32", in bits 22:21
422     assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
423     break;
424   }
425   case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
426     uint64_t Result = Value + Addend;
427
428     // AArch64 code is emitted with .rela relocations. The data already in any
429     // bits affected by the relocation on entry is garbage.
430     *TargetPtr &= 0xffe0001fU;
431     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
432     *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
433     // Shift must be "lsl #16", in bits 22:2
434     assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
435     break;
436   }
437   case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
438     uint64_t Result = Value + Addend;
439
440     // AArch64 code is emitted with .rela relocations. The data already in any
441     // bits affected by the relocation on entry is garbage.
442     *TargetPtr &= 0xffe0001fU;
443     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
444     *TargetPtr |= ((Result & 0xffffU) << 5);
445     // Shift must be "lsl #0", in bits 22:21.
446     assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
447     break;
448   }
449   case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
450     // Operation: Page(S+A) - Page(P)
451     uint64_t Result =
452         ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
453
454     // Check that -2^32 <= X < 2^32
455     assert(static_cast<int64_t>(Result) >= (-1LL << 32) &&
456            static_cast<int64_t>(Result) < (1LL << 32) &&
457            "overflow check failed for relocation");
458
459     // AArch64 code is emitted with .rela relocations. The data already in any
460     // bits affected by the relocation on entry is garbage.
461     *TargetPtr &= 0x9f00001fU;
462     // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
463     // from bits 32:12 of X.
464     *TargetPtr |= ((Result & 0x3000U) << (29 - 12));
465     *TargetPtr |= ((Result & 0x1ffffc000ULL) >> (14 - 5));
466     break;
467   }
468   case ELF::R_AARCH64_LDST32_ABS_LO12_NC: {
469     // Operation: S + A
470     uint64_t Result = Value + Addend;
471
472     // AArch64 code is emitted with .rela relocations. The data already in any
473     // bits affected by the relocation on entry is garbage.
474     *TargetPtr &= 0xffc003ffU;
475     // Immediate goes in bits 21:10 of LD/ST instruction, taken
476     // from bits 11:2 of X
477     *TargetPtr |= ((Result & 0xffc) << (10 - 2));
478     break;
479   }
480   case ELF::R_AARCH64_LDST64_ABS_LO12_NC: {
481     // Operation: S + A
482     uint64_t Result = Value + Addend;
483
484     // AArch64 code is emitted with .rela relocations. The data already in any
485     // bits affected by the relocation on entry is garbage.
486     *TargetPtr &= 0xffc003ffU;
487     // Immediate goes in bits 21:10 of LD/ST instruction, taken
488     // from bits 11:3 of X
489     *TargetPtr |= ((Result & 0xff8) << (10 - 3));
490     break;
491   }
492   }
493 }
494
495 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
496                                           uint64_t Offset, uint32_t Value,
497                                           uint32_t Type, int32_t Addend) {
498   // TODO: Add Thumb relocations.
499   uint32_t *Placeholder =
500       reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
501   uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
502   uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
503   Value += Addend;
504
505   DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
506                << Section.Address + Offset
507                << " FinalAddress: " << format("%p", FinalAddress) << " Value: "
508                << format("%x", Value) << " Type: " << format("%x", Type)
509                << " Addend: " << format("%x", Addend) << "\n");
510
511   switch (Type) {
512   default:
513     llvm_unreachable("Not implemented relocation type!");
514
515   case ELF::R_ARM_NONE:
516     break;
517   // Write a 32bit value to relocation address, taking into account the
518   // implicit addend encoded in the target.
519   case ELF::R_ARM_PREL31:
520   case ELF::R_ARM_TARGET1:
521   case ELF::R_ARM_ABS32:
522     *TargetPtr = *Placeholder + Value;
523     break;
524   // Write first 16 bit of 32 bit value to the mov instruction.
525   // Last 4 bit should be shifted.
526   case ELF::R_ARM_MOVW_ABS_NC:
527     // We are not expecting any other addend in the relocation address.
528     // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
529     // non-contiguous fields.
530     assert((*Placeholder & 0x000F0FFF) == 0);
531     Value = Value & 0xFFFF;
532     *TargetPtr = *Placeholder | (Value & 0xFFF);
533     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
534     break;
535   // Write last 16 bit of 32 bit value to the mov instruction.
536   // Last 4 bit should be shifted.
537   case ELF::R_ARM_MOVT_ABS:
538     // We are not expecting any other addend in the relocation address.
539     // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
540     assert((*Placeholder & 0x000F0FFF) == 0);
541
542     Value = (Value >> 16) & 0xFFFF;
543     *TargetPtr = *Placeholder | (Value & 0xFFF);
544     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
545     break;
546   // Write 24 bit relative value to the branch instruction.
547   case ELF::R_ARM_PC24: // Fall through.
548   case ELF::R_ARM_CALL: // Fall through.
549   case ELF::R_ARM_JUMP24: {
550     int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
551     RelValue = (RelValue & 0x03FFFFFC) >> 2;
552     assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
553     *TargetPtr &= 0xFF000000;
554     *TargetPtr |= RelValue;
555     break;
556   }
557   case ELF::R_ARM_PRIVATE_0:
558     // This relocation is reserved by the ARM ELF ABI for internal use. We
559     // appropriate it here to act as an R_ARM_ABS32 without any addend for use
560     // in the stubs created during JIT (which can't put an addend into the
561     // original object file).
562     *TargetPtr = Value;
563     break;
564   }
565 }
566
567 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
568                                            uint64_t Offset, uint32_t Value,
569                                            uint32_t Type, int32_t Addend) {
570   uint32_t *Placeholder =
571       reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
572   uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
573   Value += Addend;
574
575   DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
576                << Section.Address + Offset << " FinalAddress: "
577                << format("%p", Section.LoadAddress + Offset) << " Value: "
578                << format("%x", Value) << " Type: " << format("%x", Type)
579                << " Addend: " << format("%x", Addend) << "\n");
580
581   switch (Type) {
582   default:
583     llvm_unreachable("Not implemented relocation type!");
584     break;
585   case ELF::R_MIPS_32:
586     *TargetPtr = Value + (*Placeholder);
587     break;
588   case ELF::R_MIPS_26:
589     *TargetPtr = ((*Placeholder) & 0xfc000000) | ((Value & 0x0fffffff) >> 2);
590     break;
591   case ELF::R_MIPS_HI16:
592     // Get the higher 16-bits. Also add 1 if bit 15 is 1.
593     Value += ((*Placeholder) & 0x0000ffff) << 16;
594     *TargetPtr =
595         ((*Placeholder) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
596     break;
597   case ELF::R_MIPS_LO16:
598     Value += ((*Placeholder) & 0x0000ffff);
599     *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
600     break;
601   case ELF::R_MIPS_UNUSED1:
602     // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
603     // are used for internal JIT purpose. These relocations are similar to
604     // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
605     // account.
606     *TargetPtr =
607         ((*TargetPtr) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
608     break;
609   case ELF::R_MIPS_UNUSED2:
610     *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
611     break;
612   }
613 }
614
615 // Return the .TOC. section address to R_PPC64_TOC relocations.
616 uint64_t RuntimeDyldELF::findPPC64TOC() const {
617   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
618   // order. The TOC starts where the first of these sections starts.
619   SectionList::const_iterator it = Sections.begin();
620   SectionList::const_iterator ite = Sections.end();
621   for (; it != ite; ++it) {
622     if (it->Name == ".got" || it->Name == ".toc" || it->Name == ".tocbss" ||
623         it->Name == ".plt")
624       break;
625   }
626   if (it == ite) {
627     // This may happen for
628     // * references to TOC base base (sym@toc, .odp relocation) without
629     // a .toc directive.
630     // In this case just use the first section (which is usually
631     // the .odp) since the code won't reference the .toc base
632     // directly.
633     it = Sections.begin();
634   }
635   assert(it != ite);
636   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
637   // thus permitting a full 64 Kbytes segment.
638   return it->LoadAddress + 0x8000;
639 }
640
641 // Returns the sections and offset associated with the ODP entry referenced
642 // by Symbol.
643 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
644                                          ObjSectionToIDMap &LocalSections,
645                                          RelocationValueRef &Rel) {
646   // Get the ELF symbol value (st_value) to compare with Relocation offset in
647   // .opd entries
648   for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
649        si != se; ++si) {
650     section_iterator RelSecI = si->getRelocatedSection();
651     if (RelSecI == Obj.end_sections())
652       continue;
653
654     StringRef RelSectionName;
655     check(RelSecI->getName(RelSectionName));
656     if (RelSectionName != ".opd")
657       continue;
658
659     for (relocation_iterator i = si->relocation_begin(),
660                              e = si->relocation_end();
661          i != e;) {
662       // The R_PPC64_ADDR64 relocation indicates the first field
663       // of a .opd entry
664       uint64_t TypeFunc;
665       check(i->getType(TypeFunc));
666       if (TypeFunc != ELF::R_PPC64_ADDR64) {
667         ++i;
668         continue;
669       }
670
671       uint64_t TargetSymbolOffset;
672       symbol_iterator TargetSymbol = i->getSymbol();
673       check(i->getOffset(TargetSymbolOffset));
674       int64_t Addend;
675       check(getELFRelocationAddend(*i, Addend));
676
677       ++i;
678       if (i == e)
679         break;
680
681       // Just check if following relocation is a R_PPC64_TOC
682       uint64_t TypeTOC;
683       check(i->getType(TypeTOC));
684       if (TypeTOC != ELF::R_PPC64_TOC)
685         continue;
686
687       // Finally compares the Symbol value and the target symbol offset
688       // to check if this .opd entry refers to the symbol the relocation
689       // points to.
690       if (Rel.Addend != (int64_t)TargetSymbolOffset)
691         continue;
692
693       section_iterator tsi(Obj.end_sections());
694       check(TargetSymbol->getSection(tsi));
695       bool IsCode = false;
696       tsi->isText(IsCode);
697       Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
698       Rel.Addend = (intptr_t)Addend;
699       return;
700     }
701   }
702   llvm_unreachable("Attempting to get address of ODP entry!");
703 }
704
705 // Relocation masks following the #lo(value), #hi(value), #higher(value),
706 // and #highest(value) macros defined in section 4.5.1. Relocation Types
707 // in PPC-elf64abi document.
708 //
709 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
710
711 static inline uint16_t applyPPChi(uint64_t value) {
712   return (value >> 16) & 0xffff;
713 }
714
715 static inline uint16_t applyPPChigher(uint64_t value) {
716   return (value >> 32) & 0xffff;
717 }
718
719 static inline uint16_t applyPPChighest(uint64_t value) {
720   return (value >> 48) & 0xffff;
721 }
722
723 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
724                                             uint64_t Offset, uint64_t Value,
725                                             uint32_t Type, int64_t Addend) {
726   uint8_t *LocalAddress = Section.Address + Offset;
727   switch (Type) {
728   default:
729     llvm_unreachable("Relocation type not implemented yet!");
730     break;
731   case ELF::R_PPC64_ADDR16_LO:
732     writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
733     break;
734   case ELF::R_PPC64_ADDR16_HI:
735     writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
736     break;
737   case ELF::R_PPC64_ADDR16_HIGHER:
738     writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
739     break;
740   case ELF::R_PPC64_ADDR16_HIGHEST:
741     writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
742     break;
743   case ELF::R_PPC64_ADDR14: {
744     assert(((Value + Addend) & 3) == 0);
745     // Preserve the AA/LK bits in the branch instruction
746     uint8_t aalk = *(LocalAddress + 3);
747     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
748   } break;
749   case ELF::R_PPC64_ADDR32: {
750     int32_t Result = static_cast<int32_t>(Value + Addend);
751     if (SignExtend32<32>(Result) != Result)
752       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
753     writeInt32BE(LocalAddress, Result);
754   } break;
755   case ELF::R_PPC64_REL24: {
756     uint64_t FinalAddress = (Section.LoadAddress + Offset);
757     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
758     if (SignExtend32<24>(delta) != delta)
759       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
760     // Generates a 'bl <address>' instruction
761     writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
762   } break;
763   case ELF::R_PPC64_REL32: {
764     uint64_t FinalAddress = (Section.LoadAddress + Offset);
765     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
766     if (SignExtend32<32>(delta) != delta)
767       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
768     writeInt32BE(LocalAddress, delta);
769   } break;
770   case ELF::R_PPC64_REL64: {
771     uint64_t FinalAddress = (Section.LoadAddress + Offset);
772     uint64_t Delta = Value - FinalAddress + Addend;
773     writeInt64BE(LocalAddress, Delta);
774   } break;
775   case ELF::R_PPC64_ADDR64:
776     writeInt64BE(LocalAddress, Value + Addend);
777     break;
778   case ELF::R_PPC64_TOC:
779     writeInt64BE(LocalAddress, findPPC64TOC());
780     break;
781   case ELF::R_PPC64_TOC16: {
782     uint64_t TOCStart = findPPC64TOC();
783     Value = applyPPClo((Value + Addend) - TOCStart);
784     writeInt16BE(LocalAddress, applyPPClo(Value));
785   } break;
786   case ELF::R_PPC64_TOC16_DS: {
787     uint64_t TOCStart = findPPC64TOC();
788     Value = ((Value + Addend) - TOCStart);
789     writeInt16BE(LocalAddress, applyPPClo(Value));
790   } break;
791   }
792 }
793
794 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
795                                               uint64_t Offset, uint64_t Value,
796                                               uint32_t Type, int64_t Addend) {
797   uint8_t *LocalAddress = Section.Address + Offset;
798   switch (Type) {
799   default:
800     llvm_unreachable("Relocation type not implemented yet!");
801     break;
802   case ELF::R_390_PC16DBL:
803   case ELF::R_390_PLT16DBL: {
804     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
805     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
806     writeInt16BE(LocalAddress, Delta / 2);
807     break;
808   }
809   case ELF::R_390_PC32DBL:
810   case ELF::R_390_PLT32DBL: {
811     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
812     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
813     writeInt32BE(LocalAddress, Delta / 2);
814     break;
815   }
816   case ELF::R_390_PC32: {
817     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
818     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
819     writeInt32BE(LocalAddress, Delta);
820     break;
821   }
822   case ELF::R_390_64:
823     writeInt64BE(LocalAddress, Value + Addend);
824     break;
825   }
826 }
827
828 // The target location for the relocation is described by RE.SectionID and
829 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
830 // SectionEntry has three members describing its location.
831 // SectionEntry::Address is the address at which the section has been loaded
832 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
833 // address that the section will have in the target process.
834 // SectionEntry::ObjAddress is the address of the bits for this section in the
835 // original emitted object image (also in the current address space).
836 //
837 // Relocations will be applied as if the section were loaded at
838 // SectionEntry::LoadAddress, but they will be applied at an address based
839 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
840 // Target memory contents if they are required for value calculations.
841 //
842 // The Value parameter here is the load address of the symbol for the
843 // relocation to be applied.  For relocations which refer to symbols in the
844 // current object Value will be the LoadAddress of the section in which
845 // the symbol resides (RE.Addend provides additional information about the
846 // symbol location).  For external symbols, Value will be the address of the
847 // symbol in the target address space.
848 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
849                                        uint64_t Value) {
850   const SectionEntry &Section = Sections[RE.SectionID];
851   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
852                            RE.SymOffset);
853 }
854
855 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
856                                        uint64_t Offset, uint64_t Value,
857                                        uint32_t Type, int64_t Addend,
858                                        uint64_t SymOffset) {
859   switch (Arch) {
860   case Triple::x86_64:
861     resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
862     break;
863   case Triple::x86:
864     resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
865                          (uint32_t)(Addend & 0xffffffffL));
866     break;
867   case Triple::aarch64:
868   case Triple::aarch64_be:
869     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
870     break;
871   case Triple::arm: // Fall through.
872   case Triple::armeb:
873   case Triple::thumb:
874   case Triple::thumbeb:
875     resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
876                          (uint32_t)(Addend & 0xffffffffL));
877     break;
878   case Triple::mips: // Fall through.
879   case Triple::mipsel:
880     resolveMIPSRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL),
881                           Type, (uint32_t)(Addend & 0xffffffffL));
882     break;
883   case Triple::ppc64: // Fall through.
884   case Triple::ppc64le:
885     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
886     break;
887   case Triple::systemz:
888     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
889     break;
890   default:
891     llvm_unreachable("Unsupported CPU type!");
892   }
893 }
894
895 relocation_iterator RuntimeDyldELF::processRelocationRef(
896     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
897     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
898     StubMap &Stubs) {
899   uint64_t RelType;
900   Check(RelI->getType(RelType));
901   int64_t Addend;
902   Check(getELFRelocationAddend(*RelI, Addend));
903   symbol_iterator Symbol = RelI->getSymbol();
904
905   // Obtain the symbol name which is referenced in the relocation
906   StringRef TargetName;
907   if (Symbol != Obj.end_symbols())
908     Symbol->getName(TargetName);
909   DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
910                << " TargetName: " << TargetName << "\n");
911   RelocationValueRef Value;
912   // First search for the symbol in the local symbol table
913   SymbolTableMap::const_iterator lsi = Symbols.end();
914   SymbolRef::Type SymType = SymbolRef::ST_Unknown;
915   if (Symbol != Obj.end_symbols()) {
916     lsi = Symbols.find(TargetName.data());
917     Symbol->getType(SymType);
918   }
919   if (lsi != Symbols.end()) {
920     Value.SectionID = lsi->second.first;
921     Value.Offset = lsi->second.second;
922     Value.Addend = lsi->second.second + Addend;
923   } else {
924     // Search for the symbol in the global symbol table
925     SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
926     if (Symbol != Obj.end_symbols())
927       gsi = GlobalSymbolTable.find(TargetName.data());
928     if (gsi != GlobalSymbolTable.end()) {
929       Value.SectionID = gsi->second.first;
930       Value.Offset = gsi->second.second;
931       Value.Addend = gsi->second.second + Addend;
932     } else {
933       switch (SymType) {
934       case SymbolRef::ST_Debug: {
935         // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
936         // and can be changed by another developers. Maybe best way is add
937         // a new symbol type ST_Section to SymbolRef and use it.
938         section_iterator si(Obj.end_sections());
939         Symbol->getSection(si);
940         if (si == Obj.end_sections())
941           llvm_unreachable("Symbol section not found, bad object file format!");
942         DEBUG(dbgs() << "\t\tThis is section symbol\n");
943         // Default to 'true' in case isText fails (though it never does).
944         bool isCode = true;
945         si->isText(isCode);
946         Value.SectionID = findOrEmitSection(Obj, (*si), isCode, ObjSectionToID);
947         Value.Addend = Addend;
948         break;
949       }
950       case SymbolRef::ST_Data:
951       case SymbolRef::ST_Unknown: {
952         Value.SymbolName = TargetName.data();
953         Value.Addend = Addend;
954
955         // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
956         // will manifest here as a NULL symbol name.
957         // We can set this as a valid (but empty) symbol name, and rely
958         // on addRelocationForSymbol to handle this.
959         if (!Value.SymbolName)
960           Value.SymbolName = "";
961         break;
962       }
963       default:
964         llvm_unreachable("Unresolved symbol type!");
965         break;
966       }
967     }
968   }
969   uint64_t Offset;
970   Check(RelI->getOffset(Offset));
971
972   DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
973                << "\n");
974   if (Arch == Triple::aarch64 &&
975       (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26)) {
976     // This is an AArch64 branch relocation, need to use a stub function.
977     DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
978     SectionEntry &Section = Sections[SectionID];
979
980     // Look for an existing stub.
981     StubMap::const_iterator i = Stubs.find(Value);
982     if (i != Stubs.end()) {
983       resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
984                         RelType, 0);
985       DEBUG(dbgs() << " Stub function found\n");
986     } else {
987       // Create a new stub function.
988       DEBUG(dbgs() << " Create a new stub function\n");
989       Stubs[Value] = Section.StubOffset;
990       uint8_t *StubTargetAddr =
991           createStubFunction(Section.Address + Section.StubOffset);
992
993       RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.Address,
994                                 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
995       RelocationEntry REmovk_g2(SectionID, StubTargetAddr - Section.Address + 4,
996                                 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
997       RelocationEntry REmovk_g1(SectionID, StubTargetAddr - Section.Address + 8,
998                                 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
999       RelocationEntry REmovk_g0(SectionID,
1000                                 StubTargetAddr - Section.Address + 12,
1001                                 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1002
1003       if (Value.SymbolName) {
1004         addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1005         addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1006         addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1007         addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1008       } else {
1009         addRelocationForSection(REmovz_g3, Value.SectionID);
1010         addRelocationForSection(REmovk_g2, Value.SectionID);
1011         addRelocationForSection(REmovk_g1, Value.SectionID);
1012         addRelocationForSection(REmovk_g0, Value.SectionID);
1013       }
1014       resolveRelocation(Section, Offset,
1015                         (uint64_t)Section.Address + Section.StubOffset, RelType,
1016                         0);
1017       Section.StubOffset += getMaxStubSize();
1018     }
1019   } else if (Arch == Triple::arm &&
1020              (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1021               RelType == ELF::R_ARM_JUMP24)) {
1022     // This is an ARM branch relocation, need to use a stub function.
1023     DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
1024     SectionEntry &Section = Sections[SectionID];
1025
1026     // Look for an existing stub.
1027     StubMap::const_iterator i = Stubs.find(Value);
1028     if (i != Stubs.end()) {
1029       resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
1030                         RelType, 0);
1031       DEBUG(dbgs() << " Stub function found\n");
1032     } else {
1033       // Create a new stub function.
1034       DEBUG(dbgs() << " Create a new stub function\n");
1035       Stubs[Value] = Section.StubOffset;
1036       uint8_t *StubTargetAddr =
1037           createStubFunction(Section.Address + Section.StubOffset);
1038       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1039                          ELF::R_ARM_PRIVATE_0, Value.Addend);
1040       if (Value.SymbolName)
1041         addRelocationForSymbol(RE, Value.SymbolName);
1042       else
1043         addRelocationForSection(RE, Value.SectionID);
1044
1045       resolveRelocation(Section, Offset,
1046                         (uint64_t)Section.Address + Section.StubOffset, RelType,
1047                         0);
1048       Section.StubOffset += getMaxStubSize();
1049     }
1050   } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1051              RelType == ELF::R_MIPS_26) {
1052     // This is an Mips branch relocation, need to use a stub function.
1053     DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1054     SectionEntry &Section = Sections[SectionID];
1055     uint8_t *Target = Section.Address + Offset;
1056     uint32_t *TargetAddress = (uint32_t *)Target;
1057
1058     // Extract the addend from the instruction.
1059     uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1060
1061     Value.Addend += Addend;
1062
1063     //  Look up for existing stub.
1064     StubMap::const_iterator i = Stubs.find(Value);
1065     if (i != Stubs.end()) {
1066       RelocationEntry RE(SectionID, Offset, RelType, i->second);
1067       addRelocationForSection(RE, SectionID);
1068       DEBUG(dbgs() << " Stub function found\n");
1069     } else {
1070       // Create a new stub function.
1071       DEBUG(dbgs() << " Create a new stub function\n");
1072       Stubs[Value] = Section.StubOffset;
1073       uint8_t *StubTargetAddr =
1074           createStubFunction(Section.Address + Section.StubOffset);
1075
1076       // Creating Hi and Lo relocations for the filled stub instructions.
1077       RelocationEntry REHi(SectionID, StubTargetAddr - Section.Address,
1078                            ELF::R_MIPS_UNUSED1, Value.Addend);
1079       RelocationEntry RELo(SectionID, StubTargetAddr - Section.Address + 4,
1080                            ELF::R_MIPS_UNUSED2, Value.Addend);
1081
1082       if (Value.SymbolName) {
1083         addRelocationForSymbol(REHi, Value.SymbolName);
1084         addRelocationForSymbol(RELo, Value.SymbolName);
1085       } else {
1086         addRelocationForSection(REHi, Value.SectionID);
1087         addRelocationForSection(RELo, Value.SectionID);
1088       }
1089
1090       RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset);
1091       addRelocationForSection(RE, SectionID);
1092       Section.StubOffset += getMaxStubSize();
1093     }
1094   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1095     if (RelType == ELF::R_PPC64_REL24) {
1096       // A PPC branch relocation will need a stub function if the target is
1097       // an external symbol (Symbol::ST_Unknown) or if the target address
1098       // is not within the signed 24-bits branch address.
1099       SectionEntry &Section = Sections[SectionID];
1100       uint8_t *Target = Section.Address + Offset;
1101       bool RangeOverflow = false;
1102       if (SymType != SymbolRef::ST_Unknown) {
1103         // A function call may points to the .opd entry, so the final symbol
1104         // value
1105         // in calculated based in the relocation values in .opd section.
1106         findOPDEntrySection(Obj, ObjSectionToID, Value);
1107         uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1108         int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1109         // If it is within 24-bits branch range, just set the branch target
1110         if (SignExtend32<24>(delta) == delta) {
1111           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1112           if (Value.SymbolName)
1113             addRelocationForSymbol(RE, Value.SymbolName);
1114           else
1115             addRelocationForSection(RE, Value.SectionID);
1116         } else {
1117           RangeOverflow = true;
1118         }
1119       }
1120       if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1121         // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1122         // larger than 24-bits.
1123         StubMap::const_iterator i = Stubs.find(Value);
1124         if (i != Stubs.end()) {
1125           // Symbol function stub already created, just relocate to it
1126           resolveRelocation(Section, Offset,
1127                             (uint64_t)Section.Address + i->second, RelType, 0);
1128           DEBUG(dbgs() << " Stub function found\n");
1129         } else {
1130           // Create a new stub function.
1131           DEBUG(dbgs() << " Create a new stub function\n");
1132           Stubs[Value] = Section.StubOffset;
1133           uint8_t *StubTargetAddr =
1134               createStubFunction(Section.Address + Section.StubOffset);
1135           RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1136                              ELF::R_PPC64_ADDR64, Value.Addend);
1137
1138           // Generates the 64-bits address loads as exemplified in section
1139           // 4.5.1 in PPC64 ELF ABI.
1140           RelocationEntry REhst(SectionID, StubTargetAddr - Section.Address + 2,
1141                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1142           RelocationEntry REhr(SectionID, StubTargetAddr - Section.Address + 6,
1143                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1144           RelocationEntry REh(SectionID, StubTargetAddr - Section.Address + 14,
1145                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
1146           RelocationEntry REl(SectionID, StubTargetAddr - Section.Address + 18,
1147                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
1148
1149           if (Value.SymbolName) {
1150             addRelocationForSymbol(REhst, Value.SymbolName);
1151             addRelocationForSymbol(REhr, Value.SymbolName);
1152             addRelocationForSymbol(REh, Value.SymbolName);
1153             addRelocationForSymbol(REl, Value.SymbolName);
1154           } else {
1155             addRelocationForSection(REhst, Value.SectionID);
1156             addRelocationForSection(REhr, Value.SectionID);
1157             addRelocationForSection(REh, Value.SectionID);
1158             addRelocationForSection(REl, Value.SectionID);
1159           }
1160
1161           resolveRelocation(Section, Offset,
1162                             (uint64_t)Section.Address + Section.StubOffset,
1163                             RelType, 0);
1164           Section.StubOffset += getMaxStubSize();
1165         }
1166         if (SymType == SymbolRef::ST_Unknown)
1167           // Restore the TOC for external calls
1168           writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1169       }
1170     } else {
1171       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1172       // Extra check to avoid relocation againt empty symbols (usually
1173       // the R_PPC64_TOC).
1174       if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1175         Value.SymbolName = nullptr;
1176
1177       if (Value.SymbolName)
1178         addRelocationForSymbol(RE, Value.SymbolName);
1179       else
1180         addRelocationForSection(RE, Value.SectionID);
1181     }
1182   } else if (Arch == Triple::systemz &&
1183              (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1184     // Create function stubs for both PLT and GOT references, regardless of
1185     // whether the GOT reference is to data or code.  The stub contains the
1186     // full address of the symbol, as needed by GOT references, and the
1187     // executable part only adds an overhead of 8 bytes.
1188     //
1189     // We could try to conserve space by allocating the code and data
1190     // parts of the stub separately.  However, as things stand, we allocate
1191     // a stub for every relocation, so using a GOT in JIT code should be
1192     // no less space efficient than using an explicit constant pool.
1193     DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1194     SectionEntry &Section = Sections[SectionID];
1195
1196     // Look for an existing stub.
1197     StubMap::const_iterator i = Stubs.find(Value);
1198     uintptr_t StubAddress;
1199     if (i != Stubs.end()) {
1200       StubAddress = uintptr_t(Section.Address) + i->second;
1201       DEBUG(dbgs() << " Stub function found\n");
1202     } else {
1203       // Create a new stub function.
1204       DEBUG(dbgs() << " Create a new stub function\n");
1205
1206       uintptr_t BaseAddress = uintptr_t(Section.Address);
1207       uintptr_t StubAlignment = getStubAlignment();
1208       StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1209                     -StubAlignment;
1210       unsigned StubOffset = StubAddress - BaseAddress;
1211
1212       Stubs[Value] = StubOffset;
1213       createStubFunction((uint8_t *)StubAddress);
1214       RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1215                          Value.Addend - Addend);
1216       if (Value.SymbolName)
1217         addRelocationForSymbol(RE, Value.SymbolName);
1218       else
1219         addRelocationForSection(RE, Value.SectionID);
1220       Section.StubOffset = StubOffset + getMaxStubSize();
1221     }
1222
1223     if (RelType == ELF::R_390_GOTENT)
1224       resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1225                         Addend);
1226     else
1227       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1228   } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1229     // The way the PLT relocations normally work is that the linker allocates
1230     // the
1231     // PLT and this relocation makes a PC-relative call into the PLT.  The PLT
1232     // entry will then jump to an address provided by the GOT.  On first call,
1233     // the
1234     // GOT address will point back into PLT code that resolves the symbol. After
1235     // the first call, the GOT entry points to the actual function.
1236     //
1237     // For local functions we're ignoring all of that here and just replacing
1238     // the PLT32 relocation type with PC32, which will translate the relocation
1239     // into a PC-relative call directly to the function. For external symbols we
1240     // can't be sure the function will be within 2^32 bytes of the call site, so
1241     // we need to create a stub, which calls into the GOT.  This case is
1242     // equivalent to the usual PLT implementation except that we use the stub
1243     // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1244     // rather than allocating a PLT section.
1245     if (Value.SymbolName) {
1246       // This is a call to an external function.
1247       // Look for an existing stub.
1248       SectionEntry &Section = Sections[SectionID];
1249       StubMap::const_iterator i = Stubs.find(Value);
1250       uintptr_t StubAddress;
1251       if (i != Stubs.end()) {
1252         StubAddress = uintptr_t(Section.Address) + i->second;
1253         DEBUG(dbgs() << " Stub function found\n");
1254       } else {
1255         // Create a new stub function (equivalent to a PLT entry).
1256         DEBUG(dbgs() << " Create a new stub function\n");
1257
1258         uintptr_t BaseAddress = uintptr_t(Section.Address);
1259         uintptr_t StubAlignment = getStubAlignment();
1260         StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1261                       -StubAlignment;
1262         unsigned StubOffset = StubAddress - BaseAddress;
1263         Stubs[Value] = StubOffset;
1264         createStubFunction((uint8_t *)StubAddress);
1265
1266         // Create a GOT entry for the external function.
1267         GOTEntries.push_back(Value);
1268
1269         // Make our stub function a relative call to the GOT entry.
1270         RelocationEntry RE(SectionID, StubOffset + 2, ELF::R_X86_64_GOTPCREL,
1271                            -4);
1272         addRelocationForSymbol(RE, Value.SymbolName);
1273
1274         // Bump our stub offset counter
1275         Section.StubOffset = StubOffset + getMaxStubSize();
1276       }
1277
1278       // Make the target call a call into the stub table.
1279       resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1280                         Addend);
1281     } else {
1282       RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1283                          Value.Offset);
1284       addRelocationForSection(RE, Value.SectionID);
1285     }
1286   } else {
1287     if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1288       GOTEntries.push_back(Value);
1289     }
1290     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1291     if (Value.SymbolName)
1292       addRelocationForSymbol(RE, Value.SymbolName);
1293     else
1294       addRelocationForSection(RE, Value.SectionID);
1295   }
1296   return ++RelI;
1297 }
1298
1299 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1300
1301   SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator it;
1302   SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator end = GOTs.end();
1303
1304   for (it = GOTs.begin(); it != end; ++it) {
1305     GOTRelocations &GOTEntries = it->second;
1306     for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1307       if (GOTEntries[i].SymbolName != nullptr &&
1308           GOTEntries[i].SymbolName == Name) {
1309         GOTEntries[i].Offset = Addr;
1310       }
1311     }
1312   }
1313 }
1314
1315 size_t RuntimeDyldELF::getGOTEntrySize() {
1316   // We don't use the GOT in all of these cases, but it's essentially free
1317   // to put them all here.
1318   size_t Result = 0;
1319   switch (Arch) {
1320   case Triple::x86_64:
1321   case Triple::aarch64:
1322   case Triple::ppc64:
1323   case Triple::ppc64le:
1324   case Triple::systemz:
1325     Result = sizeof(uint64_t);
1326     break;
1327   case Triple::x86:
1328   case Triple::arm:
1329   case Triple::thumb:
1330   case Triple::mips:
1331   case Triple::mipsel:
1332     Result = sizeof(uint32_t);
1333     break;
1334   default:
1335     llvm_unreachable("Unsupported CPU type!");
1336   }
1337   return Result;
1338 }
1339
1340 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress, uint64_t Offset) {
1341
1342   const size_t GOTEntrySize = getGOTEntrySize();
1343
1344   SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator it;
1345   SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator end =
1346       GOTs.end();
1347
1348   int GOTIndex = -1;
1349   for (it = GOTs.begin(); it != end; ++it) {
1350     SID GOTSectionID = it->first;
1351     const GOTRelocations &GOTEntries = it->second;
1352
1353     // Find the matching entry in our vector.
1354     uint64_t SymbolOffset = 0;
1355     for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1356       if (!GOTEntries[i].SymbolName) {
1357         if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1358             GOTEntries[i].Offset == Offset) {
1359           GOTIndex = i;
1360           SymbolOffset = GOTEntries[i].Offset;
1361           break;
1362         }
1363       } else {
1364         // GOT entries for external symbols use the addend as the address when
1365         // the external symbol has been resolved.
1366         if (GOTEntries[i].Offset == LoadAddress) {
1367           GOTIndex = i;
1368           // Don't use the Addend here.  The relocation handler will use it.
1369           break;
1370         }
1371       }
1372     }
1373
1374     if (GOTIndex != -1) {
1375       if (GOTEntrySize == sizeof(uint64_t)) {
1376         uint64_t *LocalGOTAddr = (uint64_t *)getSectionAddress(GOTSectionID);
1377         // Fill in this entry with the address of the symbol being referenced.
1378         LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1379       } else {
1380         uint32_t *LocalGOTAddr = (uint32_t *)getSectionAddress(GOTSectionID);
1381         // Fill in this entry with the address of the symbol being referenced.
1382         LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1383       }
1384
1385       // Calculate the load address of this entry
1386       return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1387     }
1388   }
1389
1390   assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1391   return 0;
1392 }
1393
1394 void RuntimeDyldELF::finalizeLoad(ObjSectionToIDMap &SectionMap) {
1395   // If necessary, allocate the global offset table
1396   if (MemMgr) {
1397     // Allocate the GOT if necessary
1398     size_t numGOTEntries = GOTEntries.size();
1399     if (numGOTEntries != 0) {
1400       // Allocate memory for the section
1401       unsigned SectionID = Sections.size();
1402       size_t TotalSize = numGOTEntries * getGOTEntrySize();
1403       uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, getGOTEntrySize(),
1404                                                   SectionID, ".got", false);
1405       if (!Addr)
1406         report_fatal_error("Unable to allocate memory for GOT!");
1407
1408       GOTs.push_back(std::make_pair(SectionID, GOTEntries));
1409       Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1410       // For now, initialize all GOT entries to zero.  We'll fill them in as
1411       // needed when GOT-based relocations are applied.
1412       memset(Addr, 0, TotalSize);
1413     }
1414   } else {
1415     report_fatal_error("Unable to allocate memory for GOT!");
1416   }
1417
1418   // Look for and record the EH frame section.
1419   ObjSectionToIDMap::iterator i, e;
1420   for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1421     const SectionRef &Section = i->first;
1422     StringRef Name;
1423     Section.getName(Name);
1424     if (Name == ".eh_frame") {
1425       UnregisteredEHFrameSections.push_back(i->second);
1426       break;
1427     }
1428   }
1429 }
1430
1431 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1432   if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1433     return false;
1434   return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic,
1435                  strlen(ELF::ElfMagic))) == 0;
1436 }
1437
1438 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const {
1439   return Obj->isELF();
1440 }
1441
1442 } // namespace llvm