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