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