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