AArch64: implement first relocation required for 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   }
300 }
301
302 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
303                                           uint64_t Offset,
304                                           uint32_t Value,
305                                           uint32_t Type,
306                                           int32_t Addend) {
307   // TODO: Add Thumb relocations.
308   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
309   uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
310   Value += Addend;
311
312   DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
313                << Section.Address + Offset
314                << " FinalAddress: " << format("%p",FinalAddress)
315                << " Value: " << format("%x",Value)
316                << " Type: " << format("%x",Type)
317                << " Addend: " << format("%x",Addend)
318                << "\n");
319
320   switch(Type) {
321   default:
322     llvm_unreachable("Not implemented relocation type!");
323
324   // Write a 32bit value to relocation address, taking into account the
325   // implicit addend encoded in the target.
326   case ELF::R_ARM_TARGET1 :
327   case ELF::R_ARM_ABS32 :
328     *TargetPtr += Value;
329     break;
330
331   // Write first 16 bit of 32 bit value to the mov instruction.
332   // Last 4 bit should be shifted.
333   case ELF::R_ARM_MOVW_ABS_NC :
334     // We are not expecting any other addend in the relocation address.
335     // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
336     // non-contiguous fields.
337     assert((*TargetPtr & 0x000F0FFF) == 0);
338     Value = Value & 0xFFFF;
339     *TargetPtr |= Value & 0xFFF;
340     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
341     break;
342
343   // Write last 16 bit of 32 bit value to the mov instruction.
344   // Last 4 bit should be shifted.
345   case ELF::R_ARM_MOVT_ABS :
346     // We are not expecting any other addend in the relocation address.
347     // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
348     assert((*TargetPtr & 0x000F0FFF) == 0);
349     Value = (Value >> 16) & 0xFFFF;
350     *TargetPtr |= Value & 0xFFF;
351     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
352     break;
353
354   // Write 24 bit relative value to the branch instruction.
355   case ELF::R_ARM_PC24 :    // Fall through.
356   case ELF::R_ARM_CALL :    // Fall through.
357   case ELF::R_ARM_JUMP24 :
358     int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
359     RelValue = (RelValue & 0x03FFFFFC) >> 2;
360     *TargetPtr &= 0xFF000000;
361     *TargetPtr |= RelValue;
362     break;
363   }
364 }
365
366 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
367                                            uint64_t Offset,
368                                            uint32_t Value,
369                                            uint32_t Type,
370                                            int32_t Addend) {
371   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
372   Value += Addend;
373
374   DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
375                << Section.Address + Offset
376                << " FinalAddress: "
377                << format("%p",Section.LoadAddress + Offset)
378                << " Value: " << format("%x",Value)
379                << " Type: " << format("%x",Type)
380                << " Addend: " << format("%x",Addend)
381                << "\n");
382
383   switch(Type) {
384   default:
385     llvm_unreachable("Not implemented relocation type!");
386     break;
387   case ELF::R_MIPS_32:
388     *TargetPtr = Value + (*TargetPtr);
389     break;
390   case ELF::R_MIPS_26:
391     *TargetPtr = ((*TargetPtr) & 0xfc000000) | (( Value & 0x0fffffff) >> 2);
392     break;
393   case ELF::R_MIPS_HI16:
394     // Get the higher 16-bits. Also add 1 if bit 15 is 1.
395     Value += ((*TargetPtr) & 0x0000ffff) << 16;
396     *TargetPtr = ((*TargetPtr) & 0xffff0000) |
397                  (((Value + 0x8000) >> 16) & 0xffff);
398     break;
399    case ELF::R_MIPS_LO16:
400     Value += ((*TargetPtr) & 0x0000ffff);
401     *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
402     break;
403    }
404 }
405
406 // Return the .TOC. section address to R_PPC64_TOC relocations.
407 uint64_t RuntimeDyldELF::findPPC64TOC() const {
408   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
409   // order. The TOC starts where the first of these sections starts.
410   SectionList::const_iterator it = Sections.begin();
411   SectionList::const_iterator ite = Sections.end();
412   for (; it != ite; ++it) {
413     if (it->Name == ".got" ||
414         it->Name == ".toc" ||
415         it->Name == ".tocbss" ||
416         it->Name == ".plt")
417       break;
418   }
419   if (it == ite) {
420     // This may happen for
421     // * references to TOC base base (sym@toc, .odp relocation) without
422     // a .toc directive.
423     // In this case just use the first section (which is usually
424     // the .odp) since the code won't reference the .toc base
425     // directly.
426     it = Sections.begin();
427   }
428   assert (it != ite);
429   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
430   // thus permitting a full 64 Kbytes segment.
431   return it->LoadAddress + 0x8000;
432 }
433
434 // Returns the sections and offset associated with the ODP entry referenced
435 // by Symbol.
436 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
437                                          ObjSectionToIDMap &LocalSections,
438                                          RelocationValueRef &Rel) {
439   // Get the ELF symbol value (st_value) to compare with Relocation offset in
440   // .opd entries
441
442   error_code err;
443   for (section_iterator si = Obj.begin_sections(),
444      se = Obj.end_sections(); si != se; si.increment(err)) {
445     StringRef SectionName;
446     check(si->getName(SectionName));
447     if (SectionName != ".opd")
448       continue;
449
450     for (relocation_iterator i = si->begin_relocations(),
451          e = si->end_relocations(); i != e;) {
452       check(err);
453
454       // The R_PPC64_ADDR64 relocation indicates the first field
455       // of a .opd entry
456       uint64_t TypeFunc;
457       check(i->getType(TypeFunc));
458       if (TypeFunc != ELF::R_PPC64_ADDR64) {
459         i.increment(err);
460         continue;
461       }
462
463       SymbolRef TargetSymbol;
464       uint64_t TargetSymbolOffset;
465       int64_t TargetAdditionalInfo;
466       check(i->getSymbol(TargetSymbol));
467       check(i->getOffset(TargetSymbolOffset));
468       check(i->getAdditionalInfo(TargetAdditionalInfo));
469
470       i = i.increment(err);
471       if (i == e)
472         break;
473       check(err);
474
475       // Just check if following relocation is a R_PPC64_TOC
476       uint64_t TypeTOC;
477       check(i->getType(TypeTOC));
478       if (TypeTOC != ELF::R_PPC64_TOC)
479         continue;
480
481       // Finally compares the Symbol value and the target symbol offset
482       // to check if this .opd entry refers to the symbol the relocation
483       // points to.
484       if (Rel.Addend != (intptr_t)TargetSymbolOffset)
485         continue;
486
487       section_iterator tsi(Obj.end_sections());
488       check(TargetSymbol.getSection(tsi));
489       Rel.SectionID = findOrEmitSection(Obj, (*tsi), true, LocalSections);
490       Rel.Addend = (intptr_t)TargetAdditionalInfo;
491       return;
492     }
493   }
494   llvm_unreachable("Attempting to get address of ODP entry!");
495 }
496
497 // Relocation masks following the #lo(value), #hi(value), #higher(value),
498 // and #highest(value) macros defined in section 4.5.1. Relocation Types
499 // in PPC-elf64abi document.
500 //
501 static inline
502 uint16_t applyPPClo (uint64_t value)
503 {
504   return value & 0xffff;
505 }
506
507 static inline
508 uint16_t applyPPChi (uint64_t value)
509 {
510   return (value >> 16) & 0xffff;
511 }
512
513 static inline
514 uint16_t applyPPChigher (uint64_t value)
515 {
516   return (value >> 32) & 0xffff;
517 }
518
519 static inline
520 uint16_t applyPPChighest (uint64_t value)
521 {
522   return (value >> 48) & 0xffff;
523 }
524
525 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
526                                             uint64_t Offset,
527                                             uint64_t Value,
528                                             uint32_t Type,
529                                             int64_t Addend) {
530   uint8_t* LocalAddress = Section.Address + Offset;
531   switch (Type) {
532   default:
533     llvm_unreachable("Relocation type not implemented yet!");
534   break;
535   case ELF::R_PPC64_ADDR16_LO :
536     writeInt16BE(LocalAddress, applyPPClo (Value + Addend));
537     break;
538   case ELF::R_PPC64_ADDR16_HI :
539     writeInt16BE(LocalAddress, applyPPChi (Value + Addend));
540     break;
541   case ELF::R_PPC64_ADDR16_HIGHER :
542     writeInt16BE(LocalAddress, applyPPChigher (Value + Addend));
543     break;
544   case ELF::R_PPC64_ADDR16_HIGHEST :
545     writeInt16BE(LocalAddress, applyPPChighest (Value + Addend));
546     break;
547   case ELF::R_PPC64_ADDR14 : {
548     assert(((Value + Addend) & 3) == 0);
549     // Preserve the AA/LK bits in the branch instruction
550     uint8_t aalk = *(LocalAddress+3);
551     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
552   } break;
553   case ELF::R_PPC64_ADDR32 : {
554     int32_t Result = static_cast<int32_t>(Value + Addend);
555     if (SignExtend32<32>(Result) != Result)
556       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
557     writeInt32BE(LocalAddress, Result);
558   } break;
559   case ELF::R_PPC64_REL24 : {
560     uint64_t FinalAddress = (Section.LoadAddress + Offset);
561     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
562     if (SignExtend32<24>(delta) != delta)
563       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
564     // Generates a 'bl <address>' instruction
565     writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
566   } break;
567   case ELF::R_PPC64_REL32 : {
568     uint64_t FinalAddress = (Section.LoadAddress + Offset);
569     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
570     if (SignExtend32<32>(delta) != delta)
571       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
572     writeInt32BE(LocalAddress, delta);
573   } break;
574   case ELF::R_PPC64_ADDR64 :
575     writeInt64BE(LocalAddress, Value + Addend);
576     break;
577   case ELF::R_PPC64_TOC :
578     writeInt64BE(LocalAddress, findPPC64TOC());
579     break;
580   case ELF::R_PPC64_TOC16 : {
581     uint64_t TOCStart = findPPC64TOC();
582     Value = applyPPClo((Value + Addend) - TOCStart);
583     writeInt16BE(LocalAddress, applyPPClo(Value));
584   } break;
585   case ELF::R_PPC64_TOC16_DS : {
586     uint64_t TOCStart = findPPC64TOC();
587     Value = ((Value + Addend) - TOCStart);
588     writeInt16BE(LocalAddress, applyPPClo(Value));
589   } break;
590   }
591 }
592
593 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
594                                               uint64_t Offset,
595                                               uint64_t Value,
596                                               uint32_t Type,
597                                               int64_t Addend) {
598   uint8_t *LocalAddress = Section.Address + Offset;
599   switch (Type) {
600   default:
601     llvm_unreachable("Relocation type not implemented yet!");
602     break;
603   case ELF::R_390_PC16DBL:
604   case ELF::R_390_PLT16DBL: {
605     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
606     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
607     writeInt16BE(LocalAddress, Delta / 2);
608     break;
609   }
610   case ELF::R_390_PC32DBL:
611   case ELF::R_390_PLT32DBL: {
612     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
613     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
614     writeInt32BE(LocalAddress, Delta / 2);
615     break;
616   }
617   case ELF::R_390_PC32: {
618     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
619     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
620     writeInt32BE(LocalAddress, Delta);
621     break;
622   }
623   case ELF::R_390_64:
624     writeInt64BE(LocalAddress, Value + Addend);
625     break;
626   }
627 }
628
629 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
630                                        uint64_t Value) {
631   const SectionEntry &Section = Sections[RE.SectionID];
632   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend);
633 }
634
635 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
636                                        uint64_t Offset,
637                                        uint64_t Value,
638                                        uint32_t Type,
639                                        int64_t Addend) {
640   switch (Arch) {
641   case Triple::x86_64:
642     resolveX86_64Relocation(Section, Offset, Value, Type, Addend);
643     break;
644   case Triple::x86:
645     resolveX86Relocation(Section, Offset,
646                          (uint32_t)(Value & 0xffffffffL), Type,
647                          (uint32_t)(Addend & 0xffffffffL));
648     break;
649   case Triple::aarch64:
650     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
651     break;
652   case Triple::arm:    // Fall through.
653   case Triple::thumb:
654     resolveARMRelocation(Section, Offset,
655                          (uint32_t)(Value & 0xffffffffL), Type,
656                          (uint32_t)(Addend & 0xffffffffL));
657     break;
658   case Triple::mips:    // Fall through.
659   case Triple::mipsel:
660     resolveMIPSRelocation(Section, Offset,
661                           (uint32_t)(Value & 0xffffffffL), Type,
662                           (uint32_t)(Addend & 0xffffffffL));
663     break;
664   case Triple::ppc64:
665     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
666     break;
667   case Triple::systemz:
668     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
669     break;
670   default: llvm_unreachable("Unsupported CPU type!");
671   }
672 }
673
674 void RuntimeDyldELF::processRelocationRef(unsigned SectionID,
675                                           RelocationRef RelI,
676                                           ObjectImage &Obj,
677                                           ObjSectionToIDMap &ObjSectionToID,
678                                           const SymbolTableMap &Symbols,
679                                           StubMap &Stubs) {
680   uint64_t RelType;
681   Check(RelI.getType(RelType));
682   int64_t Addend;
683   Check(RelI.getAdditionalInfo(Addend));
684   SymbolRef Symbol;
685   Check(RelI.getSymbol(Symbol));
686
687   // Obtain the symbol name which is referenced in the relocation
688   StringRef TargetName;
689   Symbol.getName(TargetName);
690   DEBUG(dbgs() << "\t\tRelType: " << RelType
691                << " Addend: " << Addend
692                << " TargetName: " << TargetName
693                << "\n");
694   RelocationValueRef Value;
695   // First search for the symbol in the local symbol table
696   SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
697   SymbolRef::Type SymType;
698   Symbol.getType(SymType);
699   if (lsi != Symbols.end()) {
700     Value.SectionID = lsi->second.first;
701     Value.Addend = lsi->second.second + Addend;
702   } else {
703     // Search for the symbol in the global symbol table
704     SymbolTableMap::const_iterator gsi =
705         GlobalSymbolTable.find(TargetName.data());
706     if (gsi != GlobalSymbolTable.end()) {
707       Value.SectionID = gsi->second.first;
708       Value.Addend = gsi->second.second + Addend;
709     } else {
710       switch (SymType) {
711         case SymbolRef::ST_Debug: {
712           // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
713           // and can be changed by another developers. Maybe best way is add
714           // a new symbol type ST_Section to SymbolRef and use it.
715           section_iterator si(Obj.end_sections());
716           Symbol.getSection(si);
717           if (si == Obj.end_sections())
718             llvm_unreachable("Symbol section not found, bad object file format!");
719           DEBUG(dbgs() << "\t\tThis is section symbol\n");
720           // Default to 'true' in case isText fails (though it never does).
721           bool isCode = true;
722           si->isText(isCode);
723           Value.SectionID = findOrEmitSection(Obj,
724                                               (*si),
725                                               isCode,
726                                               ObjSectionToID);
727           Value.Addend = Addend;
728           break;
729         }
730         case SymbolRef::ST_Unknown: {
731           Value.SymbolName = TargetName.data();
732           Value.Addend = Addend;
733           break;
734         }
735         default:
736           llvm_unreachable("Unresolved symbol type!");
737           break;
738       }
739     }
740   }
741   uint64_t Offset;
742   Check(RelI.getOffset(Offset));
743
744   DEBUG(dbgs() << "\t\tSectionID: " << SectionID
745                << " Offset: " << Offset
746                << "\n");
747   if (Arch == Triple::arm &&
748       (RelType == ELF::R_ARM_PC24 ||
749        RelType == ELF::R_ARM_CALL ||
750        RelType == ELF::R_ARM_JUMP24)) {
751     // This is an ARM branch relocation, need to use a stub function.
752     DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
753     SectionEntry &Section = Sections[SectionID];
754
755     // Look for an existing stub.
756     StubMap::const_iterator i = Stubs.find(Value);
757     if (i != Stubs.end()) {
758         resolveRelocation(Section, Offset,
759                           (uint64_t)Section.Address + i->second, RelType, 0);
760       DEBUG(dbgs() << " Stub function found\n");
761     } else {
762       // Create a new stub function.
763       DEBUG(dbgs() << " Create a new stub function\n");
764       Stubs[Value] = Section.StubOffset;
765       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
766                                                    Section.StubOffset);
767       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
768                          ELF::R_ARM_ABS32, Value.Addend);
769       if (Value.SymbolName)
770         addRelocationForSymbol(RE, Value.SymbolName);
771       else
772         addRelocationForSection(RE, Value.SectionID);
773
774       resolveRelocation(Section, Offset,
775                         (uint64_t)Section.Address + Section.StubOffset,
776                         RelType, 0);
777       Section.StubOffset += getMaxStubSize();
778     }
779   } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
780              RelType == ELF::R_MIPS_26) {
781     // This is an Mips branch relocation, need to use a stub function.
782     DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
783     SectionEntry &Section = Sections[SectionID];
784     uint8_t *Target = Section.Address + Offset;
785     uint32_t *TargetAddress = (uint32_t *)Target;
786
787     // Extract the addend from the instruction.
788     uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
789
790     Value.Addend += Addend;
791
792     //  Look up for existing stub.
793     StubMap::const_iterator i = Stubs.find(Value);
794     if (i != Stubs.end()) {
795       resolveRelocation(Section, Offset,
796                         (uint64_t)Section.Address + i->second, RelType, 0);
797       DEBUG(dbgs() << " Stub function found\n");
798     } else {
799       // Create a new stub function.
800       DEBUG(dbgs() << " Create a new stub function\n");
801       Stubs[Value] = Section.StubOffset;
802       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
803                                                    Section.StubOffset);
804
805       // Creating Hi and Lo relocations for the filled stub instructions.
806       RelocationEntry REHi(SectionID,
807                            StubTargetAddr - Section.Address,
808                            ELF::R_MIPS_HI16, Value.Addend);
809       RelocationEntry RELo(SectionID,
810                            StubTargetAddr - Section.Address + 4,
811                            ELF::R_MIPS_LO16, Value.Addend);
812
813       if (Value.SymbolName) {
814         addRelocationForSymbol(REHi, Value.SymbolName);
815         addRelocationForSymbol(RELo, Value.SymbolName);
816       } else {
817         addRelocationForSection(REHi, Value.SectionID);
818         addRelocationForSection(RELo, Value.SectionID);
819       }
820
821       resolveRelocation(Section, Offset,
822                         (uint64_t)Section.Address + Section.StubOffset,
823                         RelType, 0);
824       Section.StubOffset += getMaxStubSize();
825     }
826   } else if (Arch == Triple::ppc64) {
827     if (RelType == ELF::R_PPC64_REL24) {
828       // A PPC branch relocation will need a stub function if the target is
829       // an external symbol (Symbol::ST_Unknown) or if the target address
830       // is not within the signed 24-bits branch address.
831       SectionEntry &Section = Sections[SectionID];
832       uint8_t *Target = Section.Address + Offset;
833       bool RangeOverflow = false;
834       if (SymType != SymbolRef::ST_Unknown) {
835         // A function call may points to the .opd entry, so the final symbol value
836         // in calculated based in the relocation values in .opd section.
837         findOPDEntrySection(Obj, ObjSectionToID, Value);
838         uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
839         int32_t delta = static_cast<int32_t>(Target - RelocTarget);
840         // If it is within 24-bits branch range, just set the branch target
841         if (SignExtend32<24>(delta) == delta) {
842           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
843           if (Value.SymbolName)
844             addRelocationForSymbol(RE, Value.SymbolName);
845           else
846             addRelocationForSection(RE, Value.SectionID);
847         } else {
848           RangeOverflow = true;
849         }
850       }
851       if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
852         // It is an external symbol (SymbolRef::ST_Unknown) or within a range
853         // larger than 24-bits.
854         StubMap::const_iterator i = Stubs.find(Value);
855         if (i != Stubs.end()) {
856           // Symbol function stub already created, just relocate to it
857           resolveRelocation(Section, Offset,
858                             (uint64_t)Section.Address + i->second, RelType, 0);
859           DEBUG(dbgs() << " Stub function found\n");
860         } else {
861           // Create a new stub function.
862           DEBUG(dbgs() << " Create a new stub function\n");
863           Stubs[Value] = Section.StubOffset;
864           uint8_t *StubTargetAddr = createStubFunction(Section.Address +
865                                                        Section.StubOffset);
866           RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
867                              ELF::R_PPC64_ADDR64, Value.Addend);
868
869           // Generates the 64-bits address loads as exemplified in section
870           // 4.5.1 in PPC64 ELF ABI.
871           RelocationEntry REhst(SectionID,
872                                 StubTargetAddr - Section.Address + 2,
873                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
874           RelocationEntry REhr(SectionID,
875                                StubTargetAddr - Section.Address + 6,
876                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
877           RelocationEntry REh(SectionID,
878                               StubTargetAddr - Section.Address + 14,
879                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
880           RelocationEntry REl(SectionID,
881                               StubTargetAddr - Section.Address + 18,
882                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
883
884           if (Value.SymbolName) {
885             addRelocationForSymbol(REhst, Value.SymbolName);
886             addRelocationForSymbol(REhr,  Value.SymbolName);
887             addRelocationForSymbol(REh,   Value.SymbolName);
888             addRelocationForSymbol(REl,   Value.SymbolName);
889           } else {
890             addRelocationForSection(REhst, Value.SectionID);
891             addRelocationForSection(REhr,  Value.SectionID);
892             addRelocationForSection(REh,   Value.SectionID);
893             addRelocationForSection(REl,   Value.SectionID);
894           }
895
896           resolveRelocation(Section, Offset,
897                             (uint64_t)Section.Address + Section.StubOffset,
898                             RelType, 0);
899           if (SymType == SymbolRef::ST_Unknown)
900             // Restore the TOC for external calls
901             writeInt32BE(Target+4, 0xE8410028); // ld r2,40(r1)
902           Section.StubOffset += getMaxStubSize();
903         }
904       }
905     } else {
906       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
907       // Extra check to avoid relocation againt empty symbols (usually
908       // the R_PPC64_TOC).
909       if (Value.SymbolName && !TargetName.empty())
910         addRelocationForSymbol(RE, Value.SymbolName);
911       else
912         addRelocationForSection(RE, Value.SectionID);
913     }
914   } else if (Arch == Triple::systemz &&
915              (RelType == ELF::R_390_PLT32DBL ||
916               RelType == ELF::R_390_GOTENT)) {
917     // Create function stubs for both PLT and GOT references, regardless of
918     // whether the GOT reference is to data or code.  The stub contains the
919     // full address of the symbol, as needed by GOT references, and the
920     // executable part only adds an overhead of 8 bytes.
921     //
922     // We could try to conserve space by allocating the code and data
923     // parts of the stub separately.  However, as things stand, we allocate
924     // a stub for every relocation, so using a GOT in JIT code should be
925     // no less space efficient than using an explicit constant pool.
926     DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
927     SectionEntry &Section = Sections[SectionID];
928
929     // Look for an existing stub.
930     StubMap::const_iterator i = Stubs.find(Value);
931     uintptr_t StubAddress;
932     if (i != Stubs.end()) {
933       StubAddress = uintptr_t(Section.Address) + i->second;
934       DEBUG(dbgs() << " Stub function found\n");
935     } else {
936       // Create a new stub function.
937       DEBUG(dbgs() << " Create a new stub function\n");
938
939       uintptr_t BaseAddress = uintptr_t(Section.Address);
940       uintptr_t StubAlignment = getStubAlignment();
941       StubAddress = (BaseAddress + Section.StubOffset +
942                      StubAlignment - 1) & -StubAlignment;
943       unsigned StubOffset = StubAddress - BaseAddress;
944
945       Stubs[Value] = StubOffset;
946       createStubFunction((uint8_t *)StubAddress);
947       RelocationEntry RE(SectionID, StubOffset + 8,
948                          ELF::R_390_64, Value.Addend - Addend);
949       if (Value.SymbolName)
950         addRelocationForSymbol(RE, Value.SymbolName);
951       else
952         addRelocationForSection(RE, Value.SectionID);
953       Section.StubOffset = StubOffset + getMaxStubSize();
954     }
955
956     if (RelType == ELF::R_390_GOTENT)
957       resolveRelocation(Section, Offset, StubAddress + 8,
958                         ELF::R_390_PC32DBL, Addend);
959     else
960       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
961   } else {
962     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
963     if (Value.SymbolName)
964       addRelocationForSymbol(RE, Value.SymbolName);
965     else
966       addRelocationForSection(RE, Value.SectionID);
967   }
968 }
969
970 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
971   if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
972     return false;
973   return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
974 }
975 } // namespace llvm