AArch64: add stubs to support long function calls on MCJIT
[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/ELF.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Support/ELF.h"
28 using namespace llvm;
29 using namespace llvm::object;
30
31 namespace {
32
33 static inline
34 error_code check(error_code Err) {
35   if (Err) {
36     report_fatal_error(Err.message());
37   }
38   return Err;
39 }
40
41 template<class ELFT>
42 class DyldELFObject
43   : public ELFObjectFile<ELFT> {
44   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
45
46   typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
47   typedef Elf_Sym_Impl<ELFT> Elf_Sym;
48   typedef
49     Elf_Rel_Impl<ELFT, false> Elf_Rel;
50   typedef
51     Elf_Rel_Impl<ELFT, true> Elf_Rela;
52
53   typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
54
55   typedef typename ELFDataTypeTypedefHelper<
56           ELFT>::value_type addr_type;
57
58 public:
59   DyldELFObject(MemoryBuffer *Wrapper, error_code &ec);
60
61   void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
62   void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
63
64   // Methods for type inquiry through isa, cast and dyn_cast
65   static inline bool classof(const Binary *v) {
66     return (isa<ELFObjectFile<ELFT> >(v)
67             && classof(cast<ELFObjectFile
68                 <ELFT> >(v)));
69   }
70   static inline bool classof(
71       const ELFObjectFile<ELFT> *v) {
72     return v->isDyldType();
73   }
74 };
75
76 template<class ELFT>
77 class ELFObjectImage : public ObjectImageCommon {
78   protected:
79     DyldELFObject<ELFT> *DyldObj;
80     bool Registered;
81
82   public:
83     ELFObjectImage(ObjectBuffer *Input,
84                  DyldELFObject<ELFT> *Obj)
85     : ObjectImageCommon(Input, Obj),
86       DyldObj(Obj),
87       Registered(false) {}
88
89     virtual ~ELFObjectImage() {
90       if (Registered)
91         deregisterWithDebugger();
92     }
93
94     // Subclasses can override these methods to update the image with loaded
95     // addresses for sections and common symbols
96     virtual void updateSectionAddress(const SectionRef &Sec, uint64_t Addr)
97     {
98       DyldObj->updateSectionAddress(Sec, Addr);
99     }
100
101     virtual void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr)
102     {
103       DyldObj->updateSymbolAddress(Sym, Addr);
104     }
105
106     virtual void registerWithDebugger()
107     {
108       JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
109       Registered = true;
110     }
111     virtual void deregisterWithDebugger()
112     {
113       JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
114     }
115 };
116
117 // The MemoryBuffer passed into this constructor is just a wrapper around the
118 // actual memory.  Ultimately, the Binary parent class will take ownership of
119 // this MemoryBuffer object but not the underlying memory.
120 template<class ELFT>
121 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
122   : ELFObjectFile<ELFT>(Wrapper, ec) {
123   this->isDyldELFObject = true;
124 }
125
126 template<class ELFT>
127 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
128                                                uint64_t Addr) {
129   DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
130   Elf_Shdr *shdr = const_cast<Elf_Shdr*>(
131                           reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
132
133   // This assumes the address passed in matches the target address bitness
134   // The template-based type cast handles everything else.
135   shdr->sh_addr = static_cast<addr_type>(Addr);
136 }
137
138 template<class ELFT>
139 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
140                                               uint64_t Addr) {
141
142   Elf_Sym *sym = const_cast<Elf_Sym*>(
143     ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
144
145   // This assumes the address passed in matches the target address bitness
146   // The template-based type cast handles everything else.
147   sym->st_value = static_cast<addr_type>(Addr);
148 }
149
150 } // namespace
151
152 namespace llvm {
153
154 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
155   if (Buffer->getBufferSize() < ELF::EI_NIDENT)
156     llvm_unreachable("Unexpected ELF object size");
157   std::pair<unsigned char, unsigned char> Ident = std::make_pair(
158                          (uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
159                          (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
160   error_code ec;
161
162   if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
163     DyldELFObject<ELFType<support::little, 4, false> > *Obj =
164       new DyldELFObject<ELFType<support::little, 4, false> >(
165         Buffer->getMemBuffer(), ec);
166     return new ELFObjectImage<ELFType<support::little, 4, false> >(Buffer, Obj);
167   }
168   else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB) {
169     DyldELFObject<ELFType<support::big, 4, false> > *Obj =
170       new DyldELFObject<ELFType<support::big, 4, false> >(
171         Buffer->getMemBuffer(), ec);
172     return new ELFObjectImage<ELFType<support::big, 4, false> >(Buffer, Obj);
173   }
174   else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB) {
175     DyldELFObject<ELFType<support::big, 8, true> > *Obj =
176       new DyldELFObject<ELFType<support::big, 8, true> >(
177         Buffer->getMemBuffer(), ec);
178     return new ELFObjectImage<ELFType<support::big, 8, true> >(Buffer, Obj);
179   }
180   else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB) {
181     DyldELFObject<ELFType<support::little, 8, true> > *Obj =
182       new DyldELFObject<ELFType<support::little, 8, true> >(
183         Buffer->getMemBuffer(), ec);
184     return new ELFObjectImage<ELFType<support::little, 8, true> >(Buffer, Obj);
185   }
186   else
187     llvm_unreachable("Unexpected ELF format");
188 }
189
190 RuntimeDyldELF::~RuntimeDyldELF() {
191 }
192
193 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
194                                              uint64_t Offset,
195                                              uint64_t Value,
196                                              uint32_t Type,
197                                              int64_t Addend) {
198   switch (Type) {
199   default:
200     llvm_unreachable("Relocation type not implemented yet!");
201   break;
202   case ELF::R_X86_64_64: {
203     uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
204     *Target = Value + Addend;
205     DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend))
206                  << " at " << format("%p\n",Target));
207     break;
208   }
209   case ELF::R_X86_64_32:
210   case ELF::R_X86_64_32S: {
211     Value += Addend;
212     assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
213            (Type == ELF::R_X86_64_32S &&
214              ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
215     uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
216     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
217     *Target = TruncatedAddr;
218     DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr)
219                  << " at " << format("%p\n",Target));
220     break;
221   }
222   case ELF::R_X86_64_PC32: {
223     // Get the placeholder value from the generated object since
224     // a previous relocation attempt may have overwritten the loaded version
225     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
226                                                                    + Offset);
227     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
228     uint64_t  FinalAddress = Section.LoadAddress + Offset;
229     int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
230     assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
231     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
232     *Target = TruncOffset;
233     break;
234   }
235   }
236 }
237
238 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
239                                           uint64_t Offset,
240                                           uint32_t Value,
241                                           uint32_t Type,
242                                           int32_t Addend) {
243   switch (Type) {
244   case ELF::R_386_32: {
245     // Get the placeholder value from the generated object since
246     // a previous relocation attempt may have overwritten the loaded version
247     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
248                                                                    + Offset);
249     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
250     *Target = *Placeholder + Value + Addend;
251     break;
252   }
253   case ELF::R_386_PC32: {
254     // Get the placeholder value from the generated object since
255     // a previous relocation attempt may have overwritten the loaded version
256     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
257                                                                    + Offset);
258     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
259     uint32_t  FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
260     uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
261     *Target = RealOffset;
262     break;
263     }
264     default:
265       // There are other relocation types, but it appears these are the
266       // only ones currently used by the LLVM ELF object writer
267       llvm_unreachable("Relocation type not implemented yet!");
268       break;
269   }
270 }
271
272 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
273                                               uint64_t Offset,
274                                               uint64_t Value,
275                                               uint32_t Type,
276                                               int64_t Addend) {
277   uint32_t *TargetPtr = reinterpret_cast<uint32_t*>(Section.Address + Offset);
278   uint64_t FinalAddress = Section.LoadAddress + Offset;
279
280   DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
281                << format("%llx", Section.Address + Offset)
282                << " FinalAddress: 0x" << format("%llx",FinalAddress)
283                << " Value: 0x" << format("%llx",Value)
284                << " Type: 0x" << format("%x",Type)
285                << " Addend: 0x" << format("%llx",Addend)
286                << "\n");
287
288   switch (Type) {
289   default:
290     llvm_unreachable("Relocation type not implemented yet!");
291     break;
292   case ELF::R_AARCH64_PREL32: { // test-shift.ll (.eh_frame)
293     uint64_t Result = Value + Addend - FinalAddress;
294     assert(static_cast<int64_t>(Result) >= INT32_MIN && 
295            static_cast<int64_t>(Result) <= UINT32_MAX);
296     *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
297     break;
298   }
299   case ELF::R_AARCH64_CALL26: // fallthrough
300   case ELF::R_AARCH64_JUMP26: {
301     // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
302     // calculation.
303     uint64_t BranchImm = Value + Addend - FinalAddress;
304
305     // "Check that -2^27 <= result < 2^27".
306     assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) && 
307            static_cast<int64_t>(BranchImm) < (1LL << 27));
308     // Immediate goes in bits 25:0 of B and BL.
309     *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
310     break;
311   }
312   case ELF::R_AARCH64_MOVW_UABS_G3: {
313     uint64_t Result = Value + Addend;
314     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
315     *TargetPtr |= Result >> (48 - 5);
316     // Shift is "lsl #48", in bits 22:21
317     *TargetPtr |= 3 << 21;
318     break;
319   }
320   case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
321     uint64_t Result = Value + Addend;
322     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
323     *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
324     // Shift is "lsl #32", in bits 22:21
325     *TargetPtr |= 2 << 21;
326     break;
327   }
328   case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
329     uint64_t Result = Value + Addend;
330     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
331     *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
332     // Shift is "lsl #16", in bits 22:21
333     *TargetPtr |= 1 << 21;
334     break;
335   }
336   case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
337     uint64_t Result = Value + Addend;
338     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
339     *TargetPtr |= ((Result & 0xffffU) << 5);
340     // Shift is "lsl #0", in bits 22:21. No action needed.
341     break;
342   }
343   }
344 }
345
346 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
347                                           uint64_t Offset,
348                                           uint32_t Value,
349                                           uint32_t Type,
350                                           int32_t Addend) {
351   // TODO: Add Thumb relocations.
352   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
353   uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
354   Value += Addend;
355
356   DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
357                << Section.Address + Offset
358                << " FinalAddress: " << format("%p",FinalAddress)
359                << " Value: " << format("%x",Value)
360                << " Type: " << format("%x",Type)
361                << " Addend: " << format("%x",Addend)
362                << "\n");
363
364   switch(Type) {
365   default:
366     llvm_unreachable("Not implemented relocation type!");
367
368   // Write a 32bit value to relocation address, taking into account the
369   // implicit addend encoded in the target.
370   case ELF::R_ARM_TARGET1 :
371   case ELF::R_ARM_ABS32 :
372     *TargetPtr += Value;
373     break;
374
375   // Write first 16 bit of 32 bit value to the mov instruction.
376   // Last 4 bit should be shifted.
377   case ELF::R_ARM_MOVW_ABS_NC :
378     // We are not expecting any other addend in the relocation address.
379     // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
380     // non-contiguous fields.
381     assert((*TargetPtr & 0x000F0FFF) == 0);
382     Value = Value & 0xFFFF;
383     *TargetPtr |= Value & 0xFFF;
384     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
385     break;
386
387   // Write last 16 bit of 32 bit value to the mov instruction.
388   // Last 4 bit should be shifted.
389   case ELF::R_ARM_MOVT_ABS :
390     // We are not expecting any other addend in the relocation address.
391     // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
392     assert((*TargetPtr & 0x000F0FFF) == 0);
393     Value = (Value >> 16) & 0xFFFF;
394     *TargetPtr |= Value & 0xFFF;
395     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
396     break;
397
398   // Write 24 bit relative value to the branch instruction.
399   case ELF::R_ARM_PC24 :    // Fall through.
400   case ELF::R_ARM_CALL :    // Fall through.
401   case ELF::R_ARM_JUMP24 :
402     int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
403     RelValue = (RelValue & 0x03FFFFFC) >> 2;
404     *TargetPtr &= 0xFF000000;
405     *TargetPtr |= RelValue;
406     break;
407   }
408 }
409
410 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
411                                            uint64_t Offset,
412                                            uint32_t Value,
413                                            uint32_t Type,
414                                            int32_t Addend) {
415   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
416   Value += Addend;
417
418   DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
419                << Section.Address + Offset
420                << " FinalAddress: "
421                << format("%p",Section.LoadAddress + Offset)
422                << " Value: " << format("%x",Value)
423                << " Type: " << format("%x",Type)
424                << " Addend: " << format("%x",Addend)
425                << "\n");
426
427   switch(Type) {
428   default:
429     llvm_unreachable("Not implemented relocation type!");
430     break;
431   case ELF::R_MIPS_32:
432     *TargetPtr = Value + (*TargetPtr);
433     break;
434   case ELF::R_MIPS_26:
435     *TargetPtr = ((*TargetPtr) & 0xfc000000) | (( Value & 0x0fffffff) >> 2);
436     break;
437   case ELF::R_MIPS_HI16:
438     // Get the higher 16-bits. Also add 1 if bit 15 is 1.
439     Value += ((*TargetPtr) & 0x0000ffff) << 16;
440     *TargetPtr = ((*TargetPtr) & 0xffff0000) |
441                  (((Value + 0x8000) >> 16) & 0xffff);
442     break;
443    case ELF::R_MIPS_LO16:
444     Value += ((*TargetPtr) & 0x0000ffff);
445     *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
446     break;
447    }
448 }
449
450 // Return the .TOC. section address to R_PPC64_TOC relocations.
451 uint64_t RuntimeDyldELF::findPPC64TOC() const {
452   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
453   // order. The TOC starts where the first of these sections starts.
454   SectionList::const_iterator it = Sections.begin();
455   SectionList::const_iterator ite = Sections.end();
456   for (; it != ite; ++it) {
457     if (it->Name == ".got" ||
458         it->Name == ".toc" ||
459         it->Name == ".tocbss" ||
460         it->Name == ".plt")
461       break;
462   }
463   if (it == ite) {
464     // This may happen for
465     // * references to TOC base base (sym@toc, .odp relocation) without
466     // a .toc directive.
467     // In this case just use the first section (which is usually
468     // the .odp) since the code won't reference the .toc base
469     // directly.
470     it = Sections.begin();
471   }
472   assert (it != ite);
473   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
474   // thus permitting a full 64 Kbytes segment.
475   return it->LoadAddress + 0x8000;
476 }
477
478 // Returns the sections and offset associated with the ODP entry referenced
479 // by Symbol.
480 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
481                                          ObjSectionToIDMap &LocalSections,
482                                          RelocationValueRef &Rel) {
483   // Get the ELF symbol value (st_value) to compare with Relocation offset in
484   // .opd entries
485
486   error_code err;
487   for (section_iterator si = Obj.begin_sections(),
488      se = Obj.end_sections(); si != se; si.increment(err)) {
489     StringRef SectionName;
490     check(si->getName(SectionName));
491     if (SectionName != ".opd")
492       continue;
493
494     for (relocation_iterator i = si->begin_relocations(),
495          e = si->end_relocations(); i != e;) {
496       check(err);
497
498       // The R_PPC64_ADDR64 relocation indicates the first field
499       // of a .opd entry
500       uint64_t TypeFunc;
501       check(i->getType(TypeFunc));
502       if (TypeFunc != ELF::R_PPC64_ADDR64) {
503         i.increment(err);
504         continue;
505       }
506
507       SymbolRef TargetSymbol;
508       uint64_t TargetSymbolOffset;
509       int64_t TargetAdditionalInfo;
510       check(i->getSymbol(TargetSymbol));
511       check(i->getOffset(TargetSymbolOffset));
512       check(i->getAdditionalInfo(TargetAdditionalInfo));
513
514       i = i.increment(err);
515       if (i == e)
516         break;
517       check(err);
518
519       // Just check if following relocation is a R_PPC64_TOC
520       uint64_t TypeTOC;
521       check(i->getType(TypeTOC));
522       if (TypeTOC != ELF::R_PPC64_TOC)
523         continue;
524
525       // Finally compares the Symbol value and the target symbol offset
526       // to check if this .opd entry refers to the symbol the relocation
527       // points to.
528       if (Rel.Addend != (intptr_t)TargetSymbolOffset)
529         continue;
530
531       section_iterator tsi(Obj.end_sections());
532       check(TargetSymbol.getSection(tsi));
533       Rel.SectionID = findOrEmitSection(Obj, (*tsi), true, LocalSections);
534       Rel.Addend = (intptr_t)TargetAdditionalInfo;
535       return;
536     }
537   }
538   llvm_unreachable("Attempting to get address of ODP entry!");
539 }
540
541 // Relocation masks following the #lo(value), #hi(value), #higher(value),
542 // and #highest(value) macros defined in section 4.5.1. Relocation Types
543 // in PPC-elf64abi document.
544 //
545 static inline
546 uint16_t applyPPClo (uint64_t value)
547 {
548   return value & 0xffff;
549 }
550
551 static inline
552 uint16_t applyPPChi (uint64_t value)
553 {
554   return (value >> 16) & 0xffff;
555 }
556
557 static inline
558 uint16_t applyPPChigher (uint64_t value)
559 {
560   return (value >> 32) & 0xffff;
561 }
562
563 static inline
564 uint16_t applyPPChighest (uint64_t value)
565 {
566   return (value >> 48) & 0xffff;
567 }
568
569 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
570                                             uint64_t Offset,
571                                             uint64_t Value,
572                                             uint32_t Type,
573                                             int64_t Addend) {
574   uint8_t* LocalAddress = Section.Address + Offset;
575   switch (Type) {
576   default:
577     llvm_unreachable("Relocation type not implemented yet!");
578   break;
579   case ELF::R_PPC64_ADDR16_LO :
580     writeInt16BE(LocalAddress, applyPPClo (Value + Addend));
581     break;
582   case ELF::R_PPC64_ADDR16_HI :
583     writeInt16BE(LocalAddress, applyPPChi (Value + Addend));
584     break;
585   case ELF::R_PPC64_ADDR16_HIGHER :
586     writeInt16BE(LocalAddress, applyPPChigher (Value + Addend));
587     break;
588   case ELF::R_PPC64_ADDR16_HIGHEST :
589     writeInt16BE(LocalAddress, applyPPChighest (Value + Addend));
590     break;
591   case ELF::R_PPC64_ADDR14 : {
592     assert(((Value + Addend) & 3) == 0);
593     // Preserve the AA/LK bits in the branch instruction
594     uint8_t aalk = *(LocalAddress+3);
595     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
596   } break;
597   case ELF::R_PPC64_ADDR32 : {
598     int32_t Result = static_cast<int32_t>(Value + Addend);
599     if (SignExtend32<32>(Result) != Result)
600       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
601     writeInt32BE(LocalAddress, Result);
602   } break;
603   case ELF::R_PPC64_REL24 : {
604     uint64_t FinalAddress = (Section.LoadAddress + Offset);
605     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
606     if (SignExtend32<24>(delta) != delta)
607       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
608     // Generates a 'bl <address>' instruction
609     writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
610   } break;
611   case ELF::R_PPC64_REL32 : {
612     uint64_t FinalAddress = (Section.LoadAddress + Offset);
613     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
614     if (SignExtend32<32>(delta) != delta)
615       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
616     writeInt32BE(LocalAddress, delta);
617   } break;
618   case ELF::R_PPC64_ADDR64 :
619     writeInt64BE(LocalAddress, Value + Addend);
620     break;
621   case ELF::R_PPC64_TOC :
622     writeInt64BE(LocalAddress, findPPC64TOC());
623     break;
624   case ELF::R_PPC64_TOC16 : {
625     uint64_t TOCStart = findPPC64TOC();
626     Value = applyPPClo((Value + Addend) - TOCStart);
627     writeInt16BE(LocalAddress, applyPPClo(Value));
628   } break;
629   case ELF::R_PPC64_TOC16_DS : {
630     uint64_t TOCStart = findPPC64TOC();
631     Value = ((Value + Addend) - TOCStart);
632     writeInt16BE(LocalAddress, applyPPClo(Value));
633   } break;
634   }
635 }
636
637 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
638                                               uint64_t Offset,
639                                               uint64_t Value,
640                                               uint32_t Type,
641                                               int64_t Addend) {
642   uint8_t *LocalAddress = Section.Address + Offset;
643   switch (Type) {
644   default:
645     llvm_unreachable("Relocation type not implemented yet!");
646     break;
647   case ELF::R_390_PC16DBL:
648   case ELF::R_390_PLT16DBL: {
649     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
650     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
651     writeInt16BE(LocalAddress, Delta / 2);
652     break;
653   }
654   case ELF::R_390_PC32DBL:
655   case ELF::R_390_PLT32DBL: {
656     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
657     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
658     writeInt32BE(LocalAddress, Delta / 2);
659     break;
660   }
661   case ELF::R_390_PC32: {
662     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
663     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
664     writeInt32BE(LocalAddress, Delta);
665     break;
666   }
667   case ELF::R_390_64:
668     writeInt64BE(LocalAddress, Value + Addend);
669     break;
670   }
671 }
672
673 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
674                                        uint64_t Value) {
675   const SectionEntry &Section = Sections[RE.SectionID];
676   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend);
677 }
678
679 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
680                                        uint64_t Offset,
681                                        uint64_t Value,
682                                        uint32_t Type,
683                                        int64_t Addend) {
684   switch (Arch) {
685   case Triple::x86_64:
686     resolveX86_64Relocation(Section, Offset, Value, Type, Addend);
687     break;
688   case Triple::x86:
689     resolveX86Relocation(Section, Offset,
690                          (uint32_t)(Value & 0xffffffffL), Type,
691                          (uint32_t)(Addend & 0xffffffffL));
692     break;
693   case Triple::aarch64:
694     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
695     break;
696   case Triple::arm:    // Fall through.
697   case Triple::thumb:
698     resolveARMRelocation(Section, Offset,
699                          (uint32_t)(Value & 0xffffffffL), Type,
700                          (uint32_t)(Addend & 0xffffffffL));
701     break;
702   case Triple::mips:    // Fall through.
703   case Triple::mipsel:
704     resolveMIPSRelocation(Section, Offset,
705                           (uint32_t)(Value & 0xffffffffL), Type,
706                           (uint32_t)(Addend & 0xffffffffL));
707     break;
708   case Triple::ppc64:
709     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
710     break;
711   case Triple::systemz:
712     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
713     break;
714   default: llvm_unreachable("Unsupported CPU type!");
715   }
716 }
717
718 void RuntimeDyldELF::processRelocationRef(unsigned SectionID,
719                                           RelocationRef RelI,
720                                           ObjectImage &Obj,
721                                           ObjSectionToIDMap &ObjSectionToID,
722                                           const SymbolTableMap &Symbols,
723                                           StubMap &Stubs) {
724   uint64_t RelType;
725   Check(RelI.getType(RelType));
726   int64_t Addend;
727   Check(RelI.getAdditionalInfo(Addend));
728   SymbolRef Symbol;
729   Check(RelI.getSymbol(Symbol));
730
731   // Obtain the symbol name which is referenced in the relocation
732   StringRef TargetName;
733   Symbol.getName(TargetName);
734   DEBUG(dbgs() << "\t\tRelType: " << RelType
735                << " Addend: " << Addend
736                << " TargetName: " << TargetName
737                << "\n");
738   RelocationValueRef Value;
739   // First search for the symbol in the local symbol table
740   SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
741   SymbolRef::Type SymType;
742   Symbol.getType(SymType);
743   if (lsi != Symbols.end()) {
744     Value.SectionID = lsi->second.first;
745     Value.Addend = lsi->second.second + Addend;
746   } else {
747     // Search for the symbol in the global symbol table
748     SymbolTableMap::const_iterator gsi =
749         GlobalSymbolTable.find(TargetName.data());
750     if (gsi != GlobalSymbolTable.end()) {
751       Value.SectionID = gsi->second.first;
752       Value.Addend = gsi->second.second + Addend;
753     } else {
754       switch (SymType) {
755         case SymbolRef::ST_Debug: {
756           // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
757           // and can be changed by another developers. Maybe best way is add
758           // a new symbol type ST_Section to SymbolRef and use it.
759           section_iterator si(Obj.end_sections());
760           Symbol.getSection(si);
761           if (si == Obj.end_sections())
762             llvm_unreachable("Symbol section not found, bad object file format!");
763           DEBUG(dbgs() << "\t\tThis is section symbol\n");
764           // Default to 'true' in case isText fails (though it never does).
765           bool isCode = true;
766           si->isText(isCode);
767           Value.SectionID = findOrEmitSection(Obj,
768                                               (*si),
769                                               isCode,
770                                               ObjSectionToID);
771           Value.Addend = Addend;
772           break;
773         }
774         case SymbolRef::ST_Unknown: {
775           Value.SymbolName = TargetName.data();
776           Value.Addend = Addend;
777           break;
778         }
779         default:
780           llvm_unreachable("Unresolved symbol type!");
781           break;
782       }
783     }
784   }
785   uint64_t Offset;
786   Check(RelI.getOffset(Offset));
787
788   DEBUG(dbgs() << "\t\tSectionID: " << SectionID
789                << " Offset: " << Offset
790                << "\n");
791   if (Arch == Triple::aarch64 &&
792       (RelType == ELF::R_AARCH64_CALL26 ||
793        RelType == ELF::R_AARCH64_JUMP26)) {
794     // This is an AArch64 branch relocation, need to use a stub function.
795     DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
796     SectionEntry &Section = Sections[SectionID];
797
798     // Look for an existing stub.
799     StubMap::const_iterator i = Stubs.find(Value);
800     if (i != Stubs.end()) {
801         resolveRelocation(Section, Offset,
802                           (uint64_t)Section.Address + i->second, RelType, 0);
803       DEBUG(dbgs() << " Stub function found\n");
804     } else {
805       // Create a new stub function.
806       DEBUG(dbgs() << " Create a new stub function\n");
807       Stubs[Value] = Section.StubOffset;
808       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
809                                                    Section.StubOffset);
810
811       RelocationEntry REmovz_g3(SectionID,
812                                 StubTargetAddr - Section.Address,
813                                 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
814       RelocationEntry REmovk_g2(SectionID,
815                                 StubTargetAddr - Section.Address + 4,
816                                 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
817       RelocationEntry REmovk_g1(SectionID,
818                                 StubTargetAddr - Section.Address + 8,
819                                 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
820       RelocationEntry REmovk_g0(SectionID,
821                                 StubTargetAddr - Section.Address + 12,
822                                 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
823
824       if (Value.SymbolName) {
825         addRelocationForSymbol(REmovz_g3, Value.SymbolName);
826         addRelocationForSymbol(REmovk_g2, Value.SymbolName);
827         addRelocationForSymbol(REmovk_g1, Value.SymbolName);
828         addRelocationForSymbol(REmovk_g0, Value.SymbolName);
829       } else {
830         addRelocationForSection(REmovz_g3, Value.SectionID);
831         addRelocationForSection(REmovk_g2, Value.SectionID);
832         addRelocationForSection(REmovk_g1, Value.SectionID);
833         addRelocationForSection(REmovk_g0, Value.SectionID);
834       }
835       resolveRelocation(Section, Offset,
836                         (uint64_t)Section.Address + Section.StubOffset,
837                         RelType, 0);
838       Section.StubOffset += getMaxStubSize();
839     }
840   } else if (Arch == Triple::arm &&
841       (RelType == ELF::R_ARM_PC24 ||
842        RelType == ELF::R_ARM_CALL ||
843        RelType == ELF::R_ARM_JUMP24)) {
844     // This is an ARM branch relocation, need to use a stub function.
845     DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
846     SectionEntry &Section = Sections[SectionID];
847
848     // Look for an existing stub.
849     StubMap::const_iterator i = Stubs.find(Value);
850     if (i != Stubs.end()) {
851         resolveRelocation(Section, Offset,
852                           (uint64_t)Section.Address + i->second, RelType, 0);
853       DEBUG(dbgs() << " Stub function found\n");
854     } else {
855       // Create a new stub function.
856       DEBUG(dbgs() << " Create a new stub function\n");
857       Stubs[Value] = Section.StubOffset;
858       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
859                                                    Section.StubOffset);
860       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
861                          ELF::R_ARM_ABS32, Value.Addend);
862       if (Value.SymbolName)
863         addRelocationForSymbol(RE, Value.SymbolName);
864       else
865         addRelocationForSection(RE, Value.SectionID);
866
867       resolveRelocation(Section, Offset,
868                         (uint64_t)Section.Address + Section.StubOffset,
869                         RelType, 0);
870       Section.StubOffset += getMaxStubSize();
871     }
872   } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
873              RelType == ELF::R_MIPS_26) {
874     // This is an Mips branch relocation, need to use a stub function.
875     DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
876     SectionEntry &Section = Sections[SectionID];
877     uint8_t *Target = Section.Address + Offset;
878     uint32_t *TargetAddress = (uint32_t *)Target;
879
880     // Extract the addend from the instruction.
881     uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
882
883     Value.Addend += Addend;
884
885     //  Look up for existing stub.
886     StubMap::const_iterator i = Stubs.find(Value);
887     if (i != Stubs.end()) {
888       resolveRelocation(Section, Offset,
889                         (uint64_t)Section.Address + i->second, RelType, 0);
890       DEBUG(dbgs() << " Stub function found\n");
891     } else {
892       // Create a new stub function.
893       DEBUG(dbgs() << " Create a new stub function\n");
894       Stubs[Value] = Section.StubOffset;
895       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
896                                                    Section.StubOffset);
897
898       // Creating Hi and Lo relocations for the filled stub instructions.
899       RelocationEntry REHi(SectionID,
900                            StubTargetAddr - Section.Address,
901                            ELF::R_MIPS_HI16, Value.Addend);
902       RelocationEntry RELo(SectionID,
903                            StubTargetAddr - Section.Address + 4,
904                            ELF::R_MIPS_LO16, Value.Addend);
905
906       if (Value.SymbolName) {
907         addRelocationForSymbol(REHi, Value.SymbolName);
908         addRelocationForSymbol(RELo, Value.SymbolName);
909       } else {
910         addRelocationForSection(REHi, Value.SectionID);
911         addRelocationForSection(RELo, Value.SectionID);
912       }
913
914       resolveRelocation(Section, Offset,
915                         (uint64_t)Section.Address + Section.StubOffset,
916                         RelType, 0);
917       Section.StubOffset += getMaxStubSize();
918     }
919   } else if (Arch == Triple::ppc64) {
920     if (RelType == ELF::R_PPC64_REL24) {
921       // A PPC branch relocation will need a stub function if the target is
922       // an external symbol (Symbol::ST_Unknown) or if the target address
923       // is not within the signed 24-bits branch address.
924       SectionEntry &Section = Sections[SectionID];
925       uint8_t *Target = Section.Address + Offset;
926       bool RangeOverflow = false;
927       if (SymType != SymbolRef::ST_Unknown) {
928         // A function call may points to the .opd entry, so the final symbol value
929         // in calculated based in the relocation values in .opd section.
930         findOPDEntrySection(Obj, ObjSectionToID, Value);
931         uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
932         int32_t delta = static_cast<int32_t>(Target - RelocTarget);
933         // If it is within 24-bits branch range, just set the branch target
934         if (SignExtend32<24>(delta) == delta) {
935           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
936           if (Value.SymbolName)
937             addRelocationForSymbol(RE, Value.SymbolName);
938           else
939             addRelocationForSection(RE, Value.SectionID);
940         } else {
941           RangeOverflow = true;
942         }
943       }
944       if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
945         // It is an external symbol (SymbolRef::ST_Unknown) or within a range
946         // larger than 24-bits.
947         StubMap::const_iterator i = Stubs.find(Value);
948         if (i != Stubs.end()) {
949           // Symbol function stub already created, just relocate to it
950           resolveRelocation(Section, Offset,
951                             (uint64_t)Section.Address + i->second, RelType, 0);
952           DEBUG(dbgs() << " Stub function found\n");
953         } else {
954           // Create a new stub function.
955           DEBUG(dbgs() << " Create a new stub function\n");
956           Stubs[Value] = Section.StubOffset;
957           uint8_t *StubTargetAddr = createStubFunction(Section.Address +
958                                                        Section.StubOffset);
959           RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
960                              ELF::R_PPC64_ADDR64, Value.Addend);
961
962           // Generates the 64-bits address loads as exemplified in section
963           // 4.5.1 in PPC64 ELF ABI.
964           RelocationEntry REhst(SectionID,
965                                 StubTargetAddr - Section.Address + 2,
966                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
967           RelocationEntry REhr(SectionID,
968                                StubTargetAddr - Section.Address + 6,
969                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
970           RelocationEntry REh(SectionID,
971                               StubTargetAddr - Section.Address + 14,
972                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
973           RelocationEntry REl(SectionID,
974                               StubTargetAddr - Section.Address + 18,
975                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
976
977           if (Value.SymbolName) {
978             addRelocationForSymbol(REhst, Value.SymbolName);
979             addRelocationForSymbol(REhr,  Value.SymbolName);
980             addRelocationForSymbol(REh,   Value.SymbolName);
981             addRelocationForSymbol(REl,   Value.SymbolName);
982           } else {
983             addRelocationForSection(REhst, Value.SectionID);
984             addRelocationForSection(REhr,  Value.SectionID);
985             addRelocationForSection(REh,   Value.SectionID);
986             addRelocationForSection(REl,   Value.SectionID);
987           }
988
989           resolveRelocation(Section, Offset,
990                             (uint64_t)Section.Address + Section.StubOffset,
991                             RelType, 0);
992           if (SymType == SymbolRef::ST_Unknown)
993             // Restore the TOC for external calls
994             writeInt32BE(Target+4, 0xE8410028); // ld r2,40(r1)
995           Section.StubOffset += getMaxStubSize();
996         }
997       }
998     } else {
999       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1000       // Extra check to avoid relocation againt empty symbols (usually
1001       // the R_PPC64_TOC).
1002       if (Value.SymbolName && !TargetName.empty())
1003         addRelocationForSymbol(RE, Value.SymbolName);
1004       else
1005         addRelocationForSection(RE, Value.SectionID);
1006     }
1007   } else if (Arch == Triple::systemz &&
1008              (RelType == ELF::R_390_PLT32DBL ||
1009               RelType == ELF::R_390_GOTENT)) {
1010     // Create function stubs for both PLT and GOT references, regardless of
1011     // whether the GOT reference is to data or code.  The stub contains the
1012     // full address of the symbol, as needed by GOT references, and the
1013     // executable part only adds an overhead of 8 bytes.
1014     //
1015     // We could try to conserve space by allocating the code and data
1016     // parts of the stub separately.  However, as things stand, we allocate
1017     // a stub for every relocation, so using a GOT in JIT code should be
1018     // no less space efficient than using an explicit constant pool.
1019     DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1020     SectionEntry &Section = Sections[SectionID];
1021
1022     // Look for an existing stub.
1023     StubMap::const_iterator i = Stubs.find(Value);
1024     uintptr_t StubAddress;
1025     if (i != Stubs.end()) {
1026       StubAddress = uintptr_t(Section.Address) + i->second;
1027       DEBUG(dbgs() << " Stub function found\n");
1028     } else {
1029       // Create a new stub function.
1030       DEBUG(dbgs() << " Create a new stub function\n");
1031
1032       uintptr_t BaseAddress = uintptr_t(Section.Address);
1033       uintptr_t StubAlignment = getStubAlignment();
1034       StubAddress = (BaseAddress + Section.StubOffset +
1035                      StubAlignment - 1) & -StubAlignment;
1036       unsigned StubOffset = StubAddress - BaseAddress;
1037
1038       Stubs[Value] = StubOffset;
1039       createStubFunction((uint8_t *)StubAddress);
1040       RelocationEntry RE(SectionID, StubOffset + 8,
1041                          ELF::R_390_64, Value.Addend - Addend);
1042       if (Value.SymbolName)
1043         addRelocationForSymbol(RE, Value.SymbolName);
1044       else
1045         addRelocationForSection(RE, Value.SectionID);
1046       Section.StubOffset = StubOffset + getMaxStubSize();
1047     }
1048
1049     if (RelType == ELF::R_390_GOTENT)
1050       resolveRelocation(Section, Offset, StubAddress + 8,
1051                         ELF::R_390_PC32DBL, Addend);
1052     else
1053       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1054   } else {
1055     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1056     if (Value.SymbolName)
1057       addRelocationForSymbol(RE, Value.SymbolName);
1058     else
1059       addRelocationForSection(RE, Value.SectionID);
1060   }
1061 }
1062
1063 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1064   if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1065     return false;
1066   return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
1067 }
1068 } // namespace llvm