Remove all uses of 'using std::error_code' from headers.
[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 using std::error_code;
31
32 #define DEBUG_TYPE "dyld"
33
34 namespace {
35
36 static inline error_code check(error_code Err) {
37   if (Err) {
38     report_fatal_error(Err.message());
39   }
40   return Err;
41 }
42
43 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
44   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
45
46   typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
47   typedef Elf_Sym_Impl<ELFT> Elf_Sym;
48   typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
49   typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
50
51   typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
52
53   typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
54
55   std::unique_ptr<ObjectFile> UnderlyingFile;
56
57 public:
58   DyldELFObject(std::unique_ptr<ObjectFile> UnderlyingFile,
59                 MemoryBuffer *Wrapper, error_code &ec);
60
61   DyldELFObject(MemoryBuffer *Wrapper, error_code &ec);
62
63   void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
64   void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
65
66   // Methods for type inquiry through isa, cast and dyn_cast
67   static inline bool classof(const Binary *v) {
68     return (isa<ELFObjectFile<ELFT>>(v) &&
69             classof(cast<ELFObjectFile<ELFT>>(v)));
70   }
71   static inline bool classof(const ELFObjectFile<ELFT> *v) {
72     return v->isDyldType();
73   }
74 };
75
76 template <class ELFT> class ELFObjectImage : public ObjectImageCommon {
77   bool Registered;
78
79 public:
80   ELFObjectImage(ObjectBuffer *Input, std::unique_ptr<DyldELFObject<ELFT>> Obj)
81       : ObjectImageCommon(Input, std::move(Obj)), Registered(false) {}
82
83   virtual ~ELFObjectImage() {
84     if (Registered)
85       deregisterWithDebugger();
86   }
87
88   // Subclasses can override these methods to update the image with loaded
89   // addresses for sections and common symbols
90   void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) override {
91     static_cast<DyldELFObject<ELFT>*>(getObjectFile())
92         ->updateSectionAddress(Sec, Addr);
93   }
94
95   void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) override {
96     static_cast<DyldELFObject<ELFT>*>(getObjectFile())
97         ->updateSymbolAddress(Sym, Addr);
98   }
99
100   void registerWithDebugger() override {
101     JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
102     Registered = true;
103   }
104   void deregisterWithDebugger() override {
105     JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
106   }
107 };
108
109 // The MemoryBuffer passed into this constructor is just a wrapper around the
110 // actual memory.  Ultimately, the Binary parent class will take ownership of
111 // this MemoryBuffer object but not the underlying memory.
112 template <class ELFT>
113 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
114     : ELFObjectFile<ELFT>(Wrapper, ec) {
115   this->isDyldELFObject = true;
116 }
117
118 template <class ELFT>
119 DyldELFObject<ELFT>::DyldELFObject(std::unique_ptr<ObjectFile> UnderlyingFile,
120                                    MemoryBuffer *Wrapper, error_code &ec)
121     : ELFObjectFile<ELFT>(Wrapper, ec),
122       UnderlyingFile(std::move(UnderlyingFile)) {
123   this->isDyldELFObject = true;
124 }
125
126 template <class ELFT>
127 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
128                                                uint64_t Addr) {
129   DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
130   Elf_Shdr *shdr =
131       const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
132
133   // This assumes the address passed in matches the target address bitness
134   // The template-based type cast handles everything else.
135   shdr->sh_addr = static_cast<addr_type>(Addr);
136 }
137
138 template <class ELFT>
139 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
140                                               uint64_t Addr) {
141
142   Elf_Sym *sym = const_cast<Elf_Sym *>(
143       ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
144
145   // This assumes the address passed in matches the target address bitness
146   // The template-based type cast handles everything else.
147   sym->st_value = static_cast<addr_type>(Addr);
148 }
149
150 } // namespace
151
152 namespace llvm {
153
154 void RuntimeDyldELF::registerEHFrames() {
155   if (!MemMgr)
156     return;
157   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
158     SID EHFrameSID = UnregisteredEHFrameSections[i];
159     uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
160     uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
161     size_t EHFrameSize = Sections[EHFrameSID].Size;
162     MemMgr->registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
163     RegisteredEHFrameSections.push_back(EHFrameSID);
164   }
165   UnregisteredEHFrameSections.clear();
166 }
167
168 void RuntimeDyldELF::deregisterEHFrames() {
169   if (!MemMgr)
170     return;
171   for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) {
172     SID EHFrameSID = RegisteredEHFrameSections[i];
173     uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
174     uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
175     size_t EHFrameSize = Sections[EHFrameSID].Size;
176     MemMgr->deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
177   }
178   RegisteredEHFrameSections.clear();
179 }
180
181 ObjectImage *
182 RuntimeDyldELF::createObjectImageFromFile(std::unique_ptr<object::ObjectFile> ObjFile) {
183   if (!ObjFile)
184     return nullptr;
185
186   error_code ec;
187   MemoryBuffer *Buffer =
188       MemoryBuffer::getMemBuffer(ObjFile->getData(), "", false);
189
190   if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
191     auto Obj =
192         llvm::make_unique<DyldELFObject<ELFType<support::little, 2, false>>>(
193             std::move(ObjFile), Buffer, ec);
194     return new ELFObjectImage<ELFType<support::little, 2, false>>(
195         nullptr, std::move(Obj));
196   } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
197     auto Obj =
198         llvm::make_unique<DyldELFObject<ELFType<support::big, 2, false>>>(
199             std::move(ObjFile), Buffer, ec);
200     return new ELFObjectImage<ELFType<support::big, 2, false>>(nullptr, std::move(Obj));
201   } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
202     auto Obj = llvm::make_unique<DyldELFObject<ELFType<support::big, 2, true>>>(
203         std::move(ObjFile), Buffer, ec);
204     return new ELFObjectImage<ELFType<support::big, 2, true>>(nullptr,
205                                                               std::move(Obj));
206   } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
207     auto Obj =
208         llvm::make_unique<DyldELFObject<ELFType<support::little, 2, true>>>(
209             std::move(ObjFile), Buffer, ec);
210     return new ELFObjectImage<ELFType<support::little, 2, true>>(
211         nullptr, std::move(Obj));
212   } else
213     llvm_unreachable("Unexpected ELF format");
214 }
215
216 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
217   if (Buffer->getBufferSize() < ELF::EI_NIDENT)
218     llvm_unreachable("Unexpected ELF object size");
219   std::pair<unsigned char, unsigned char> Ident =
220       std::make_pair((uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
221                      (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
222   error_code ec;
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             Buffer->getMemBuffer(), 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>>>(
234             Buffer->getMemBuffer(), 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         Buffer->getMemBuffer(), 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>>>(
246             Buffer->getMemBuffer(), 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 address to R_PPC64_TOC relocations.
617 uint64_t RuntimeDyldELF::findPPC64TOC() const {
618   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
619   // order. The TOC starts where the first of these sections starts.
620   SectionList::const_iterator it = Sections.begin();
621   SectionList::const_iterator ite = Sections.end();
622   for (; it != ite; ++it) {
623     if (it->Name == ".got" || it->Name == ".toc" || it->Name == ".tocbss" ||
624         it->Name == ".plt")
625       break;
626   }
627   if (it == ite) {
628     // This may happen for
629     // * references to TOC base base (sym@toc, .odp relocation) without
630     // a .toc directive.
631     // In this case just use the first section (which is usually
632     // the .odp) since the code won't reference the .toc base
633     // directly.
634     it = Sections.begin();
635   }
636   assert(it != ite);
637   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
638   // thus permitting a full 64 Kbytes segment.
639   return it->LoadAddress + 0x8000;
640 }
641
642 // Returns the sections and offset associated with the ODP entry referenced
643 // by Symbol.
644 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
645                                          ObjSectionToIDMap &LocalSections,
646                                          RelocationValueRef &Rel) {
647   // Get the ELF symbol value (st_value) to compare with Relocation offset in
648   // .opd entries
649   for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
650        si != se; ++si) {
651     section_iterator RelSecI = si->getRelocatedSection();
652     if (RelSecI == Obj.end_sections())
653       continue;
654
655     StringRef RelSectionName;
656     check(RelSecI->getName(RelSectionName));
657     if (RelSectionName != ".opd")
658       continue;
659
660     for (relocation_iterator i = si->relocation_begin(),
661                              e = si->relocation_end();
662          i != e;) {
663       // The R_PPC64_ADDR64 relocation indicates the first field
664       // of a .opd entry
665       uint64_t TypeFunc;
666       check(i->getType(TypeFunc));
667       if (TypeFunc != ELF::R_PPC64_ADDR64) {
668         ++i;
669         continue;
670       }
671
672       uint64_t TargetSymbolOffset;
673       symbol_iterator TargetSymbol = i->getSymbol();
674       check(i->getOffset(TargetSymbolOffset));
675       int64_t Addend;
676       check(getELFRelocationAddend(*i, Addend));
677
678       ++i;
679       if (i == e)
680         break;
681
682       // Just check if following relocation is a R_PPC64_TOC
683       uint64_t TypeTOC;
684       check(i->getType(TypeTOC));
685       if (TypeTOC != ELF::R_PPC64_TOC)
686         continue;
687
688       // Finally compares the Symbol value and the target symbol offset
689       // to check if this .opd entry refers to the symbol the relocation
690       // points to.
691       if (Rel.Addend != (int64_t)TargetSymbolOffset)
692         continue;
693
694       section_iterator tsi(Obj.end_sections());
695       check(TargetSymbol->getSection(tsi));
696       bool IsCode = false;
697       tsi->isText(IsCode);
698       Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
699       Rel.Addend = (intptr_t)Addend;
700       return;
701     }
702   }
703   llvm_unreachable("Attempting to get address of ODP entry!");
704 }
705
706 // Relocation masks following the #lo(value), #hi(value), #higher(value),
707 // and #highest(value) macros defined in section 4.5.1. Relocation Types
708 // in PPC-elf64abi document.
709 //
710 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
711
712 static inline uint16_t applyPPChi(uint64_t value) {
713   return (value >> 16) & 0xffff;
714 }
715
716 static inline uint16_t applyPPChigher(uint64_t value) {
717   return (value >> 32) & 0xffff;
718 }
719
720 static inline uint16_t applyPPChighest(uint64_t value) {
721   return (value >> 48) & 0xffff;
722 }
723
724 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
725                                             uint64_t Offset, uint64_t Value,
726                                             uint32_t Type, int64_t Addend) {
727   uint8_t *LocalAddress = Section.Address + Offset;
728   switch (Type) {
729   default:
730     llvm_unreachable("Relocation type not implemented yet!");
731     break;
732   case ELF::R_PPC64_ADDR16_LO:
733     writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
734     break;
735   case ELF::R_PPC64_ADDR16_HI:
736     writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
737     break;
738   case ELF::R_PPC64_ADDR16_HIGHER:
739     writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
740     break;
741   case ELF::R_PPC64_ADDR16_HIGHEST:
742     writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
743     break;
744   case ELF::R_PPC64_ADDR14: {
745     assert(((Value + Addend) & 3) == 0);
746     // Preserve the AA/LK bits in the branch instruction
747     uint8_t aalk = *(LocalAddress + 3);
748     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
749   } break;
750   case ELF::R_PPC64_ADDR32: {
751     int32_t Result = static_cast<int32_t>(Value + Addend);
752     if (SignExtend32<32>(Result) != Result)
753       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
754     writeInt32BE(LocalAddress, Result);
755   } break;
756   case ELF::R_PPC64_REL24: {
757     uint64_t FinalAddress = (Section.LoadAddress + Offset);
758     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
759     if (SignExtend32<24>(delta) != delta)
760       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
761     // Generates a 'bl <address>' instruction
762     writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
763   } break;
764   case ELF::R_PPC64_REL32: {
765     uint64_t FinalAddress = (Section.LoadAddress + Offset);
766     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
767     if (SignExtend32<32>(delta) != delta)
768       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
769     writeInt32BE(LocalAddress, delta);
770   } break;
771   case ELF::R_PPC64_REL64: {
772     uint64_t FinalAddress = (Section.LoadAddress + Offset);
773     uint64_t Delta = Value - FinalAddress + Addend;
774     writeInt64BE(LocalAddress, Delta);
775   } break;
776   case ELF::R_PPC64_ADDR64:
777     writeInt64BE(LocalAddress, Value + Addend);
778     break;
779   case ELF::R_PPC64_TOC:
780     writeInt64BE(LocalAddress, findPPC64TOC());
781     break;
782   case ELF::R_PPC64_TOC16: {
783     uint64_t TOCStart = findPPC64TOC();
784     Value = applyPPClo((Value + Addend) - TOCStart);
785     writeInt16BE(LocalAddress, applyPPClo(Value));
786   } break;
787   case ELF::R_PPC64_TOC16_DS: {
788     uint64_t TOCStart = findPPC64TOC();
789     Value = ((Value + Addend) - TOCStart);
790     writeInt16BE(LocalAddress, applyPPClo(Value));
791   } break;
792   }
793 }
794
795 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
796                                               uint64_t Offset, uint64_t Value,
797                                               uint32_t Type, int64_t Addend) {
798   uint8_t *LocalAddress = Section.Address + Offset;
799   switch (Type) {
800   default:
801     llvm_unreachable("Relocation type not implemented yet!");
802     break;
803   case ELF::R_390_PC16DBL:
804   case ELF::R_390_PLT16DBL: {
805     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
806     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
807     writeInt16BE(LocalAddress, Delta / 2);
808     break;
809   }
810   case ELF::R_390_PC32DBL:
811   case ELF::R_390_PLT32DBL: {
812     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
813     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
814     writeInt32BE(LocalAddress, Delta / 2);
815     break;
816   }
817   case ELF::R_390_PC32: {
818     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
819     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
820     writeInt32BE(LocalAddress, Delta);
821     break;
822   }
823   case ELF::R_390_64:
824     writeInt64BE(LocalAddress, Value + Addend);
825     break;
826   }
827 }
828
829 // The target location for the relocation is described by RE.SectionID and
830 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
831 // SectionEntry has three members describing its location.
832 // SectionEntry::Address is the address at which the section has been loaded
833 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
834 // address that the section will have in the target process.
835 // SectionEntry::ObjAddress is the address of the bits for this section in the
836 // original emitted object image (also in the current address space).
837 //
838 // Relocations will be applied as if the section were loaded at
839 // SectionEntry::LoadAddress, but they will be applied at an address based
840 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
841 // Target memory contents if they are required for value calculations.
842 //
843 // The Value parameter here is the load address of the symbol for the
844 // relocation to be applied.  For relocations which refer to symbols in the
845 // current object Value will be the LoadAddress of the section in which
846 // the symbol resides (RE.Addend provides additional information about the
847 // symbol location).  For external symbols, Value will be the address of the
848 // symbol in the target address space.
849 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
850                                        uint64_t Value) {
851   const SectionEntry &Section = Sections[RE.SectionID];
852   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
853                            RE.SymOffset);
854 }
855
856 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
857                                        uint64_t Offset, uint64_t Value,
858                                        uint32_t Type, int64_t Addend,
859                                        uint64_t SymOffset) {
860   switch (Arch) {
861   case Triple::x86_64:
862     resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
863     break;
864   case Triple::x86:
865     resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
866                          (uint32_t)(Addend & 0xffffffffL));
867     break;
868   case Triple::aarch64:
869   case Triple::aarch64_be:
870   case Triple::arm64:
871   case Triple::arm64_be:
872     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
873     break;
874   case Triple::arm: // Fall through.
875   case Triple::armeb:
876   case Triple::thumb:
877   case Triple::thumbeb:
878     resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
879                          (uint32_t)(Addend & 0xffffffffL));
880     break;
881   case Triple::mips: // Fall through.
882   case Triple::mipsel:
883     resolveMIPSRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL),
884                           Type, (uint32_t)(Addend & 0xffffffffL));
885     break;
886   case Triple::ppc64: // Fall through.
887   case Triple::ppc64le:
888     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
889     break;
890   case Triple::systemz:
891     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
892     break;
893   default:
894     llvm_unreachable("Unsupported CPU type!");
895   }
896 }
897
898 relocation_iterator RuntimeDyldELF::processRelocationRef(
899     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
900     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
901     StubMap &Stubs) {
902   uint64_t RelType;
903   Check(RelI->getType(RelType));
904   int64_t Addend;
905   Check(getELFRelocationAddend(*RelI, Addend));
906   symbol_iterator Symbol = RelI->getSymbol();
907
908   // Obtain the symbol name which is referenced in the relocation
909   StringRef TargetName;
910   if (Symbol != Obj.end_symbols())
911     Symbol->getName(TargetName);
912   DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
913                << " TargetName: " << TargetName << "\n");
914   RelocationValueRef Value;
915   // First search for the symbol in the local symbol table
916   SymbolTableMap::const_iterator lsi = Symbols.end();
917   SymbolRef::Type SymType = SymbolRef::ST_Unknown;
918   if (Symbol != Obj.end_symbols()) {
919     lsi = Symbols.find(TargetName.data());
920     Symbol->getType(SymType);
921   }
922   if (lsi != Symbols.end()) {
923     Value.SectionID = lsi->second.first;
924     Value.Offset = lsi->second.second;
925     Value.Addend = lsi->second.second + Addend;
926   } else {
927     // Search for the symbol in the global symbol table
928     SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
929     if (Symbol != Obj.end_symbols())
930       gsi = GlobalSymbolTable.find(TargetName.data());
931     if (gsi != GlobalSymbolTable.end()) {
932       Value.SectionID = gsi->second.first;
933       Value.Offset = gsi->second.second;
934       Value.Addend = gsi->second.second + Addend;
935     } else {
936       switch (SymType) {
937       case SymbolRef::ST_Debug: {
938         // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
939         // and can be changed by another developers. Maybe best way is add
940         // a new symbol type ST_Section to SymbolRef and use it.
941         section_iterator si(Obj.end_sections());
942         Symbol->getSection(si);
943         if (si == Obj.end_sections())
944           llvm_unreachable("Symbol section not found, bad object file format!");
945         DEBUG(dbgs() << "\t\tThis is section symbol\n");
946         // Default to 'true' in case isText fails (though it never does).
947         bool isCode = true;
948         si->isText(isCode);
949         Value.SectionID = findOrEmitSection(Obj, (*si), isCode, ObjSectionToID);
950         Value.Addend = Addend;
951         break;
952       }
953       case SymbolRef::ST_Data:
954       case SymbolRef::ST_Unknown: {
955         Value.SymbolName = TargetName.data();
956         Value.Addend = Addend;
957
958         // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
959         // will manifest here as a NULL symbol name.
960         // We can set this as a valid (but empty) symbol name, and rely
961         // on addRelocationForSymbol to handle this.
962         if (!Value.SymbolName)
963           Value.SymbolName = "";
964         break;
965       }
966       default:
967         llvm_unreachable("Unresolved symbol type!");
968         break;
969       }
970     }
971   }
972   uint64_t Offset;
973   Check(RelI->getOffset(Offset));
974
975   DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
976                << "\n");
977   if ((Arch == Triple::aarch64 || Arch == Triple::aarch64_be ||
978        Arch == Triple::arm64 || Arch == Triple::arm64_be) &&
979       (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26)) {
980     // This is an AArch64 branch relocation, need to use a stub function.
981     DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
982     SectionEntry &Section = Sections[SectionID];
983
984     // Look for an existing stub.
985     StubMap::const_iterator i = Stubs.find(Value);
986     if (i != Stubs.end()) {
987       resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
988                         RelType, 0);
989       DEBUG(dbgs() << " Stub function found\n");
990     } else {
991       // Create a new stub function.
992       DEBUG(dbgs() << " Create a new stub function\n");
993       Stubs[Value] = Section.StubOffset;
994       uint8_t *StubTargetAddr =
995           createStubFunction(Section.Address + Section.StubOffset);
996
997       RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.Address,
998                                 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
999       RelocationEntry REmovk_g2(SectionID, StubTargetAddr - Section.Address + 4,
1000                                 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
1001       RelocationEntry REmovk_g1(SectionID, StubTargetAddr - Section.Address + 8,
1002                                 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
1003       RelocationEntry REmovk_g0(SectionID,
1004                                 StubTargetAddr - Section.Address + 12,
1005                                 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1006
1007       if (Value.SymbolName) {
1008         addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1009         addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1010         addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1011         addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1012       } else {
1013         addRelocationForSection(REmovz_g3, Value.SectionID);
1014         addRelocationForSection(REmovk_g2, Value.SectionID);
1015         addRelocationForSection(REmovk_g1, Value.SectionID);
1016         addRelocationForSection(REmovk_g0, Value.SectionID);
1017       }
1018       resolveRelocation(Section, Offset,
1019                         (uint64_t)Section.Address + Section.StubOffset, RelType,
1020                         0);
1021       Section.StubOffset += getMaxStubSize();
1022     }
1023   } else if (Arch == Triple::arm &&
1024              (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1025               RelType == ELF::R_ARM_JUMP24)) {
1026     // This is an ARM branch relocation, need to use a stub function.
1027     DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
1028     SectionEntry &Section = Sections[SectionID];
1029
1030     // Look for an existing stub.
1031     StubMap::const_iterator i = Stubs.find(Value);
1032     if (i != Stubs.end()) {
1033       resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
1034                         RelType, 0);
1035       DEBUG(dbgs() << " Stub function found\n");
1036     } else {
1037       // Create a new stub function.
1038       DEBUG(dbgs() << " Create a new stub function\n");
1039       Stubs[Value] = Section.StubOffset;
1040       uint8_t *StubTargetAddr =
1041           createStubFunction(Section.Address + Section.StubOffset);
1042       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1043                          ELF::R_ARM_PRIVATE_0, Value.Addend);
1044       if (Value.SymbolName)
1045         addRelocationForSymbol(RE, Value.SymbolName);
1046       else
1047         addRelocationForSection(RE, Value.SectionID);
1048
1049       resolveRelocation(Section, Offset,
1050                         (uint64_t)Section.Address + Section.StubOffset, RelType,
1051                         0);
1052       Section.StubOffset += getMaxStubSize();
1053     }
1054   } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1055              RelType == ELF::R_MIPS_26) {
1056     // This is an Mips branch relocation, need to use a stub function.
1057     DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1058     SectionEntry &Section = Sections[SectionID];
1059     uint8_t *Target = Section.Address + Offset;
1060     uint32_t *TargetAddress = (uint32_t *)Target;
1061
1062     // Extract the addend from the instruction.
1063     uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1064
1065     Value.Addend += Addend;
1066
1067     //  Look up for existing stub.
1068     StubMap::const_iterator i = Stubs.find(Value);
1069     if (i != Stubs.end()) {
1070       RelocationEntry RE(SectionID, Offset, RelType, i->second);
1071       addRelocationForSection(RE, SectionID);
1072       DEBUG(dbgs() << " Stub function found\n");
1073     } else {
1074       // Create a new stub function.
1075       DEBUG(dbgs() << " Create a new stub function\n");
1076       Stubs[Value] = Section.StubOffset;
1077       uint8_t *StubTargetAddr =
1078           createStubFunction(Section.Address + Section.StubOffset);
1079
1080       // Creating Hi and Lo relocations for the filled stub instructions.
1081       RelocationEntry REHi(SectionID, StubTargetAddr - Section.Address,
1082                            ELF::R_MIPS_UNUSED1, Value.Addend);
1083       RelocationEntry RELo(SectionID, StubTargetAddr - Section.Address + 4,
1084                            ELF::R_MIPS_UNUSED2, Value.Addend);
1085
1086       if (Value.SymbolName) {
1087         addRelocationForSymbol(REHi, Value.SymbolName);
1088         addRelocationForSymbol(RELo, Value.SymbolName);
1089       } else {
1090         addRelocationForSection(REHi, Value.SectionID);
1091         addRelocationForSection(RELo, Value.SectionID);
1092       }
1093
1094       RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset);
1095       addRelocationForSection(RE, SectionID);
1096       Section.StubOffset += getMaxStubSize();
1097     }
1098   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1099     if (RelType == ELF::R_PPC64_REL24) {
1100       // A PPC branch relocation will need a stub function if the target is
1101       // an external symbol (Symbol::ST_Unknown) or if the target address
1102       // is not within the signed 24-bits branch address.
1103       SectionEntry &Section = Sections[SectionID];
1104       uint8_t *Target = Section.Address + Offset;
1105       bool RangeOverflow = false;
1106       if (SymType != SymbolRef::ST_Unknown) {
1107         // A function call may points to the .opd entry, so the final symbol
1108         // value
1109         // in calculated based in the relocation values in .opd section.
1110         findOPDEntrySection(Obj, ObjSectionToID, Value);
1111         uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1112         int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1113         // If it is within 24-bits branch range, just set the branch target
1114         if (SignExtend32<24>(delta) == delta) {
1115           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1116           if (Value.SymbolName)
1117             addRelocationForSymbol(RE, Value.SymbolName);
1118           else
1119             addRelocationForSection(RE, Value.SectionID);
1120         } else {
1121           RangeOverflow = true;
1122         }
1123       }
1124       if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1125         // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1126         // larger than 24-bits.
1127         StubMap::const_iterator i = Stubs.find(Value);
1128         if (i != Stubs.end()) {
1129           // Symbol function stub already created, just relocate to it
1130           resolveRelocation(Section, Offset,
1131                             (uint64_t)Section.Address + i->second, RelType, 0);
1132           DEBUG(dbgs() << " Stub function found\n");
1133         } else {
1134           // Create a new stub function.
1135           DEBUG(dbgs() << " Create a new stub function\n");
1136           Stubs[Value] = Section.StubOffset;
1137           uint8_t *StubTargetAddr =
1138               createStubFunction(Section.Address + Section.StubOffset);
1139           RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1140                              ELF::R_PPC64_ADDR64, Value.Addend);
1141
1142           // Generates the 64-bits address loads as exemplified in section
1143           // 4.5.1 in PPC64 ELF ABI.
1144           RelocationEntry REhst(SectionID, StubTargetAddr - Section.Address + 2,
1145                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1146           RelocationEntry REhr(SectionID, StubTargetAddr - Section.Address + 6,
1147                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1148           RelocationEntry REh(SectionID, StubTargetAddr - Section.Address + 14,
1149                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
1150           RelocationEntry REl(SectionID, StubTargetAddr - Section.Address + 18,
1151                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
1152
1153           if (Value.SymbolName) {
1154             addRelocationForSymbol(REhst, Value.SymbolName);
1155             addRelocationForSymbol(REhr, Value.SymbolName);
1156             addRelocationForSymbol(REh, Value.SymbolName);
1157             addRelocationForSymbol(REl, Value.SymbolName);
1158           } else {
1159             addRelocationForSection(REhst, Value.SectionID);
1160             addRelocationForSection(REhr, Value.SectionID);
1161             addRelocationForSection(REh, Value.SectionID);
1162             addRelocationForSection(REl, Value.SectionID);
1163           }
1164
1165           resolveRelocation(Section, Offset,
1166                             (uint64_t)Section.Address + Section.StubOffset,
1167                             RelType, 0);
1168           Section.StubOffset += getMaxStubSize();
1169         }
1170         if (SymType == SymbolRef::ST_Unknown)
1171           // Restore the TOC for external calls
1172           writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1173       }
1174     } else {
1175       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1176       // Extra check to avoid relocation againt empty symbols (usually
1177       // the R_PPC64_TOC).
1178       if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1179         Value.SymbolName = nullptr;
1180
1181       if (Value.SymbolName)
1182         addRelocationForSymbol(RE, Value.SymbolName);
1183       else
1184         addRelocationForSection(RE, Value.SectionID);
1185     }
1186   } else if (Arch == Triple::systemz &&
1187              (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1188     // Create function stubs for both PLT and GOT references, regardless of
1189     // whether the GOT reference is to data or code.  The stub contains the
1190     // full address of the symbol, as needed by GOT references, and the
1191     // executable part only adds an overhead of 8 bytes.
1192     //
1193     // We could try to conserve space by allocating the code and data
1194     // parts of the stub separately.  However, as things stand, we allocate
1195     // a stub for every relocation, so using a GOT in JIT code should be
1196     // no less space efficient than using an explicit constant pool.
1197     DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1198     SectionEntry &Section = Sections[SectionID];
1199
1200     // Look for an existing stub.
1201     StubMap::const_iterator i = Stubs.find(Value);
1202     uintptr_t StubAddress;
1203     if (i != Stubs.end()) {
1204       StubAddress = uintptr_t(Section.Address) + i->second;
1205       DEBUG(dbgs() << " Stub function found\n");
1206     } else {
1207       // Create a new stub function.
1208       DEBUG(dbgs() << " Create a new stub function\n");
1209
1210       uintptr_t BaseAddress = uintptr_t(Section.Address);
1211       uintptr_t StubAlignment = getStubAlignment();
1212       StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1213                     -StubAlignment;
1214       unsigned StubOffset = StubAddress - BaseAddress;
1215
1216       Stubs[Value] = StubOffset;
1217       createStubFunction((uint8_t *)StubAddress);
1218       RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1219                          Value.Addend - Addend);
1220       if (Value.SymbolName)
1221         addRelocationForSymbol(RE, Value.SymbolName);
1222       else
1223         addRelocationForSection(RE, Value.SectionID);
1224       Section.StubOffset = StubOffset + getMaxStubSize();
1225     }
1226
1227     if (RelType == ELF::R_390_GOTENT)
1228       resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1229                         Addend);
1230     else
1231       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1232   } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1233     // The way the PLT relocations normally work is that the linker allocates
1234     // the
1235     // PLT and this relocation makes a PC-relative call into the PLT.  The PLT
1236     // entry will then jump to an address provided by the GOT.  On first call,
1237     // the
1238     // GOT address will point back into PLT code that resolves the symbol. After
1239     // the first call, the GOT entry points to the actual function.
1240     //
1241     // For local functions we're ignoring all of that here and just replacing
1242     // the PLT32 relocation type with PC32, which will translate the relocation
1243     // into a PC-relative call directly to the function. For external symbols we
1244     // can't be sure the function will be within 2^32 bytes of the call site, so
1245     // we need to create a stub, which calls into the GOT.  This case is
1246     // equivalent to the usual PLT implementation except that we use the stub
1247     // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1248     // rather than allocating a PLT section.
1249     if (Value.SymbolName) {
1250       // This is a call to an external function.
1251       // Look for an existing stub.
1252       SectionEntry &Section = Sections[SectionID];
1253       StubMap::const_iterator i = Stubs.find(Value);
1254       uintptr_t StubAddress;
1255       if (i != Stubs.end()) {
1256         StubAddress = uintptr_t(Section.Address) + i->second;
1257         DEBUG(dbgs() << " Stub function found\n");
1258       } else {
1259         // Create a new stub function (equivalent to a PLT entry).
1260         DEBUG(dbgs() << " Create a new stub function\n");
1261
1262         uintptr_t BaseAddress = uintptr_t(Section.Address);
1263         uintptr_t StubAlignment = getStubAlignment();
1264         StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1265                       -StubAlignment;
1266         unsigned StubOffset = StubAddress - BaseAddress;
1267         Stubs[Value] = StubOffset;
1268         createStubFunction((uint8_t *)StubAddress);
1269
1270         // Create a GOT entry for the external function.
1271         GOTEntries.push_back(Value);
1272
1273         // Make our stub function a relative call to the GOT entry.
1274         RelocationEntry RE(SectionID, StubOffset + 2, ELF::R_X86_64_GOTPCREL,
1275                            -4);
1276         addRelocationForSymbol(RE, Value.SymbolName);
1277
1278         // Bump our stub offset counter
1279         Section.StubOffset = StubOffset + getMaxStubSize();
1280       }
1281
1282       // Make the target call a call into the stub table.
1283       resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1284                         Addend);
1285     } else {
1286       RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1287                          Value.Offset);
1288       addRelocationForSection(RE, Value.SectionID);
1289     }
1290   } else {
1291     if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1292       GOTEntries.push_back(Value);
1293     }
1294     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1295     if (Value.SymbolName)
1296       addRelocationForSymbol(RE, Value.SymbolName);
1297     else
1298       addRelocationForSection(RE, Value.SectionID);
1299   }
1300   return ++RelI;
1301 }
1302
1303 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1304
1305   SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator it;
1306   SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator end = GOTs.end();
1307
1308   for (it = GOTs.begin(); it != end; ++it) {
1309     GOTRelocations &GOTEntries = it->second;
1310     for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1311       if (GOTEntries[i].SymbolName != nullptr &&
1312           GOTEntries[i].SymbolName == Name) {
1313         GOTEntries[i].Offset = Addr;
1314       }
1315     }
1316   }
1317 }
1318
1319 size_t RuntimeDyldELF::getGOTEntrySize() {
1320   // We don't use the GOT in all of these cases, but it's essentially free
1321   // to put them all here.
1322   size_t Result = 0;
1323   switch (Arch) {
1324   case Triple::x86_64:
1325   case Triple::aarch64:
1326   case Triple::aarch64_be:
1327   case Triple::arm64:
1328   case Triple::arm64_be:
1329   case Triple::ppc64:
1330   case Triple::ppc64le:
1331   case Triple::systemz:
1332     Result = sizeof(uint64_t);
1333     break;
1334   case Triple::x86:
1335   case Triple::arm:
1336   case Triple::thumb:
1337   case Triple::mips:
1338   case Triple::mipsel:
1339     Result = sizeof(uint32_t);
1340     break;
1341   default:
1342     llvm_unreachable("Unsupported CPU type!");
1343   }
1344   return Result;
1345 }
1346
1347 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress, uint64_t Offset) {
1348
1349   const size_t GOTEntrySize = getGOTEntrySize();
1350
1351   SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator it;
1352   SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator end =
1353       GOTs.end();
1354
1355   int GOTIndex = -1;
1356   for (it = GOTs.begin(); it != end; ++it) {
1357     SID GOTSectionID = it->first;
1358     const GOTRelocations &GOTEntries = it->second;
1359
1360     // Find the matching entry in our vector.
1361     uint64_t SymbolOffset = 0;
1362     for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1363       if (!GOTEntries[i].SymbolName) {
1364         if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1365             GOTEntries[i].Offset == Offset) {
1366           GOTIndex = i;
1367           SymbolOffset = GOTEntries[i].Offset;
1368           break;
1369         }
1370       } else {
1371         // GOT entries for external symbols use the addend as the address when
1372         // the external symbol has been resolved.
1373         if (GOTEntries[i].Offset == LoadAddress) {
1374           GOTIndex = i;
1375           // Don't use the Addend here.  The relocation handler will use it.
1376           break;
1377         }
1378       }
1379     }
1380
1381     if (GOTIndex != -1) {
1382       if (GOTEntrySize == sizeof(uint64_t)) {
1383         uint64_t *LocalGOTAddr = (uint64_t *)getSectionAddress(GOTSectionID);
1384         // Fill in this entry with the address of the symbol being referenced.
1385         LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1386       } else {
1387         uint32_t *LocalGOTAddr = (uint32_t *)getSectionAddress(GOTSectionID);
1388         // Fill in this entry with the address of the symbol being referenced.
1389         LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1390       }
1391
1392       // Calculate the load address of this entry
1393       return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1394     }
1395   }
1396
1397   assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1398   return 0;
1399 }
1400
1401 void RuntimeDyldELF::finalizeLoad(ObjectImage &ObjImg,
1402                                   ObjSectionToIDMap &SectionMap) {
1403   // If necessary, allocate the global offset table
1404   if (MemMgr) {
1405     // Allocate the GOT if necessary
1406     size_t numGOTEntries = GOTEntries.size();
1407     if (numGOTEntries != 0) {
1408       // Allocate memory for the section
1409       unsigned SectionID = Sections.size();
1410       size_t TotalSize = numGOTEntries * getGOTEntrySize();
1411       uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, getGOTEntrySize(),
1412                                                   SectionID, ".got", false);
1413       if (!Addr)
1414         report_fatal_error("Unable to allocate memory for GOT!");
1415
1416       GOTs.push_back(std::make_pair(SectionID, GOTEntries));
1417       Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1418       // For now, initialize all GOT entries to zero.  We'll fill them in as
1419       // needed when GOT-based relocations are applied.
1420       memset(Addr, 0, TotalSize);
1421     }
1422   } else {
1423     report_fatal_error("Unable to allocate memory for GOT!");
1424   }
1425
1426   // Look for and record the EH frame section.
1427   ObjSectionToIDMap::iterator i, e;
1428   for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1429     const SectionRef &Section = i->first;
1430     StringRef Name;
1431     Section.getName(Name);
1432     if (Name == ".eh_frame") {
1433       UnregisteredEHFrameSections.push_back(i->second);
1434       break;
1435     }
1436   }
1437 }
1438
1439 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1440   if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1441     return false;
1442   return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic,
1443                  strlen(ELF::ElfMagic))) == 0;
1444 }
1445
1446 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const {
1447   return Obj->isELF();
1448 }
1449
1450 } // namespace llvm