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