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