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