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