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