Adding comments to document RuntimeDyld relocation handling
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldELF.cpp
1 //===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of ELF support for the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dyld"
15 #include "RuntimeDyldELF.h"
16 #include "JITRegistrar.h"
17 #include "ObjectImageCommon.h"
18 #include "llvm/ADT/IntervalMap.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ExecutionEngine/ObjectBuffer.h"
24 #include "llvm/ExecutionEngine/ObjectImage.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Support/ELF.h"
28 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 StringRef RuntimeDyldELF::getEHFrameSection() {
155   for (int i = 0, e = Sections.size(); i != e; ++i) {
156     if (Sections[i].Name == ".eh_frame")
157       return StringRef((const char*)Sections[i].Address, Sections[i].Size);
158   }
159   return StringRef();
160 }
161
162 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
163   if (Buffer->getBufferSize() < ELF::EI_NIDENT)
164     llvm_unreachable("Unexpected ELF object size");
165   std::pair<unsigned char, unsigned char> Ident = std::make_pair(
166                          (uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
167                          (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
168   error_code ec;
169
170   if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
171     DyldELFObject<ELFType<support::little, 4, false> > *Obj =
172       new DyldELFObject<ELFType<support::little, 4, false> >(
173         Buffer->getMemBuffer(), ec);
174     return new ELFObjectImage<ELFType<support::little, 4, false> >(Buffer, Obj);
175   }
176   else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB) {
177     DyldELFObject<ELFType<support::big, 4, false> > *Obj =
178       new DyldELFObject<ELFType<support::big, 4, false> >(
179         Buffer->getMemBuffer(), ec);
180     return new ELFObjectImage<ELFType<support::big, 4, false> >(Buffer, Obj);
181   }
182   else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB) {
183     DyldELFObject<ELFType<support::big, 8, true> > *Obj =
184       new DyldELFObject<ELFType<support::big, 8, true> >(
185         Buffer->getMemBuffer(), ec);
186     return new ELFObjectImage<ELFType<support::big, 8, true> >(Buffer, Obj);
187   }
188   else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB) {
189     DyldELFObject<ELFType<support::little, 8, true> > *Obj =
190       new DyldELFObject<ELFType<support::little, 8, true> >(
191         Buffer->getMemBuffer(), ec);
192     return new ELFObjectImage<ELFType<support::little, 8, true> >(Buffer, Obj);
193   }
194   else
195     llvm_unreachable("Unexpected ELF format");
196 }
197
198 RuntimeDyldELF::~RuntimeDyldELF() {
199 }
200
201 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
202                                              uint64_t Offset,
203                                              uint64_t Value,
204                                              uint32_t Type,
205                                              int64_t Addend) {
206   switch (Type) {
207   default:
208     llvm_unreachable("Relocation type not implemented yet!");
209   break;
210   case ELF::R_X86_64_64: {
211     uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
212     *Target = Value + Addend;
213     DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend))
214                  << " at " << format("%p\n",Target));
215     break;
216   }
217   case ELF::R_X86_64_32:
218   case ELF::R_X86_64_32S: {
219     Value += Addend;
220     assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
221            (Type == ELF::R_X86_64_32S &&
222              ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
223     uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
224     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
225     *Target = TruncatedAddr;
226     DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr)
227                  << " at " << format("%p\n",Target));
228     break;
229   }
230   case ELF::R_X86_64_PC32: {
231     // Get the placeholder value from the generated object since
232     // a previous relocation attempt may have overwritten the loaded version
233     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
234                                                                    + Offset);
235     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
236     uint64_t  FinalAddress = Section.LoadAddress + Offset;
237     int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
238     assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
239     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
240     *Target = TruncOffset;
241     break;
242   }
243   }
244 }
245
246 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
247                                           uint64_t Offset,
248                                           uint32_t Value,
249                                           uint32_t Type,
250                                           int32_t Addend) {
251   switch (Type) {
252   case ELF::R_386_32: {
253     // Get the placeholder value from the generated object since
254     // a previous relocation attempt may have overwritten the loaded version
255     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
256                                                                    + Offset);
257     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
258     *Target = *Placeholder + Value + Addend;
259     break;
260   }
261   case ELF::R_386_PC32: {
262     // Get the placeholder value from the generated object since
263     // a previous relocation attempt may have overwritten the loaded version
264     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
265                                                                    + Offset);
266     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
267     uint32_t  FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
268     uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
269     *Target = RealOffset;
270     break;
271     }
272     default:
273       // There are other relocation types, but it appears these are the
274       // only ones currently used by the LLVM ELF object writer
275       llvm_unreachable("Relocation type not implemented yet!");
276       break;
277   }
278 }
279
280 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
281                                               uint64_t Offset,
282                                               uint64_t Value,
283                                               uint32_t Type,
284                                               int64_t Addend) {
285   uint32_t *TargetPtr = reinterpret_cast<uint32_t*>(Section.Address + Offset);
286   uint64_t FinalAddress = Section.LoadAddress + Offset;
287
288   DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
289                << format("%llx", Section.Address + Offset)
290                << " FinalAddress: 0x" << format("%llx",FinalAddress)
291                << " Value: 0x" << format("%llx",Value)
292                << " Type: 0x" << format("%x",Type)
293                << " Addend: 0x" << format("%llx",Addend)
294                << "\n");
295
296   switch (Type) {
297   default:
298     llvm_unreachable("Relocation type not implemented yet!");
299     break;
300   case ELF::R_AARCH64_ABS64: {
301     uint64_t *TargetPtr = reinterpret_cast<uint64_t*>(Section.Address + Offset);
302     *TargetPtr = Value + Addend;
303     break;
304   }
305   case ELF::R_AARCH64_PREL32: {
306     uint64_t Result = Value + Addend - FinalAddress;
307     assert(static_cast<int64_t>(Result) >= INT32_MIN &&
308            static_cast<int64_t>(Result) <= UINT32_MAX);
309     *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
310     break;
311   }
312   case ELF::R_AARCH64_CALL26: // fallthrough
313   case ELF::R_AARCH64_JUMP26: {
314     // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
315     // calculation.
316     uint64_t BranchImm = Value + Addend - FinalAddress;
317
318     // "Check that -2^27 <= result < 2^27".
319     assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
320            static_cast<int64_t>(BranchImm) < (1LL << 27));
321
322     // AArch64 code is emitted with .rela relocations. The data already in any
323     // bits affected by the relocation on entry is garbage.
324     *TargetPtr &= 0xfc000000U;
325     // Immediate goes in bits 25:0 of B and BL.
326     *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
327     break;
328   }
329   case ELF::R_AARCH64_MOVW_UABS_G3: {
330     uint64_t Result = Value + Addend;
331
332     // AArch64 code is emitted with .rela relocations. The data already in any
333     // bits affected by the relocation on entry is garbage.
334     *TargetPtr &= 0xffe0001fU;
335     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
336     *TargetPtr |= Result >> (48 - 5);
337     // Shift must be "lsl #48", in bits 22:21
338     assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
339     break;
340   }
341   case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
342     uint64_t Result = Value + Addend;
343
344     // AArch64 code is emitted with .rela relocations. The data already in any
345     // bits affected by the relocation on entry is garbage.
346     *TargetPtr &= 0xffe0001fU;
347     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
348     *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
349     // Shift must be "lsl #32", in bits 22:21
350     assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
351     break;
352   }
353   case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
354     uint64_t Result = Value + Addend;
355
356     // AArch64 code is emitted with .rela relocations. The data already in any
357     // bits affected by the relocation on entry is garbage.
358     *TargetPtr &= 0xffe0001fU;
359     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
360     *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
361     // Shift must be "lsl #16", in bits 22:2
362     assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
363     break;
364   }
365   case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
366     uint64_t Result = Value + Addend;
367
368     // AArch64 code is emitted with .rela relocations. The data already in any
369     // bits affected by the relocation on entry is garbage.
370     *TargetPtr &= 0xffe0001fU;
371     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
372     *TargetPtr |= ((Result & 0xffffU) << 5);
373     // Shift must be "lsl #0", in bits 22:21.
374     assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
375     break;
376   }
377   }
378 }
379
380 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
381                                           uint64_t Offset,
382                                           uint32_t Value,
383                                           uint32_t Type,
384                                           int32_t Addend) {
385   // TODO: Add Thumb relocations.
386   uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
387                                                       Offset);
388   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
389   uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
390   Value += Addend;
391
392   DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
393                << Section.Address + Offset
394                << " FinalAddress: " << format("%p",FinalAddress)
395                << " Value: " << format("%x",Value)
396                << " Type: " << format("%x",Type)
397                << " Addend: " << format("%x",Addend)
398                << "\n");
399
400   switch(Type) {
401   default:
402     llvm_unreachable("Not implemented relocation type!");
403
404   // Write a 32bit value to relocation address, taking into account the
405   // implicit addend encoded in the target.
406   case ELF::R_ARM_TARGET1:
407   case ELF::R_ARM_ABS32:
408     *TargetPtr = *Placeholder + Value;
409     break;
410   // Write first 16 bit of 32 bit value to the mov instruction.
411   // Last 4 bit should be shifted.
412   case ELF::R_ARM_MOVW_ABS_NC:
413     // We are not expecting any other addend in the relocation address.
414     // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
415     // non-contiguous fields.
416     assert((*Placeholder & 0x000F0FFF) == 0);
417     Value = Value & 0xFFFF;
418     *TargetPtr = *Placeholder | (Value & 0xFFF);
419     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
420     break;
421   // Write last 16 bit of 32 bit value to the mov instruction.
422   // Last 4 bit should be shifted.
423   case ELF::R_ARM_MOVT_ABS:
424     // We are not expecting any other addend in the relocation address.
425     // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
426     assert((*Placeholder & 0x000F0FFF) == 0);
427
428     Value = (Value >> 16) & 0xFFFF;
429     *TargetPtr = *Placeholder | (Value & 0xFFF);
430     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
431     break;
432   // Write 24 bit relative value to the branch instruction.
433   case ELF::R_ARM_PC24 :    // Fall through.
434   case ELF::R_ARM_CALL :    // Fall through.
435   case ELF::R_ARM_JUMP24: {
436     int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
437     RelValue = (RelValue & 0x03FFFFFC) >> 2;
438     assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
439     *TargetPtr &= 0xFF000000;
440     *TargetPtr |= RelValue;
441     break;
442   }
443   case ELF::R_ARM_PRIVATE_0:
444     // This relocation is reserved by the ARM ELF ABI for internal use. We
445     // appropriate it here to act as an R_ARM_ABS32 without any addend for use
446     // in the stubs created during JIT (which can't put an addend into the
447     // original object file).
448     *TargetPtr = Value;
449     break;
450   }
451 }
452
453 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
454                                            uint64_t Offset,
455                                            uint32_t Value,
456                                            uint32_t Type,
457                                            int32_t Addend) {
458   uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
459                                                       Offset);
460   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
461   Value += Addend;
462
463   DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
464                << Section.Address + Offset
465                << " FinalAddress: "
466                << format("%p",Section.LoadAddress + Offset)
467                << " Value: " << format("%x",Value)
468                << " Type: " << format("%x",Type)
469                << " Addend: " << format("%x",Addend)
470                << "\n");
471
472   switch(Type) {
473   default:
474     llvm_unreachable("Not implemented relocation type!");
475     break;
476   case ELF::R_MIPS_32:
477     *TargetPtr = Value + (*Placeholder);
478     break;
479   case ELF::R_MIPS_26:
480     *TargetPtr = ((*Placeholder) & 0xfc000000) | (( Value & 0x0fffffff) >> 2);
481     break;
482   case ELF::R_MIPS_HI16:
483     // Get the higher 16-bits. Also add 1 if bit 15 is 1.
484     Value += ((*Placeholder) & 0x0000ffff) << 16;
485     *TargetPtr = ((*Placeholder) & 0xffff0000) |
486                  (((Value + 0x8000) >> 16) & 0xffff);
487     break;
488   case ELF::R_MIPS_LO16:
489     Value += ((*Placeholder) & 0x0000ffff);
490     *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
491     break;
492   case ELF::R_MIPS_UNUSED1:
493     // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
494     // are used for internal JIT purpose. These relocations are similar to
495     // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
496     // account.
497     *TargetPtr = ((*TargetPtr) & 0xffff0000) |
498                  (((Value + 0x8000) >> 16) & 0xffff);
499     break;
500   case ELF::R_MIPS_UNUSED2:
501     *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
502     break;
503    }
504 }
505
506 // Return the .TOC. section address to R_PPC64_TOC relocations.
507 uint64_t RuntimeDyldELF::findPPC64TOC() const {
508   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
509   // order. The TOC starts where the first of these sections starts.
510   SectionList::const_iterator it = Sections.begin();
511   SectionList::const_iterator ite = Sections.end();
512   for (; it != ite; ++it) {
513     if (it->Name == ".got" ||
514         it->Name == ".toc" ||
515         it->Name == ".tocbss" ||
516         it->Name == ".plt")
517       break;
518   }
519   if (it == ite) {
520     // This may happen for
521     // * references to TOC base base (sym@toc, .odp relocation) without
522     // a .toc directive.
523     // In this case just use the first section (which is usually
524     // the .odp) since the code won't reference the .toc base
525     // directly.
526     it = Sections.begin();
527   }
528   assert (it != ite);
529   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
530   // thus permitting a full 64 Kbytes segment.
531   return it->LoadAddress + 0x8000;
532 }
533
534 // Returns the sections and offset associated with the ODP entry referenced
535 // by Symbol.
536 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
537                                          ObjSectionToIDMap &LocalSections,
538                                          RelocationValueRef &Rel) {
539   // Get the ELF symbol value (st_value) to compare with Relocation offset in
540   // .opd entries
541
542   error_code err;
543   for (section_iterator si = Obj.begin_sections(),
544      se = Obj.end_sections(); si != se; si.increment(err)) {
545     section_iterator RelSecI = si->getRelocatedSection();
546     if (RelSecI == Obj.end_sections())
547       continue;
548
549     StringRef RelSectionName;
550     check(RelSecI->getName(RelSectionName));
551     if (RelSectionName != ".opd")
552       continue;
553
554     for (relocation_iterator i = si->begin_relocations(),
555          e = si->end_relocations(); i != e;) {
556       check(err);
557
558       // The R_PPC64_ADDR64 relocation indicates the first field
559       // of a .opd entry
560       uint64_t TypeFunc;
561       check(i->getType(TypeFunc));
562       if (TypeFunc != ELF::R_PPC64_ADDR64) {
563         i.increment(err);
564         continue;
565       }
566
567       uint64_t TargetSymbolOffset;
568       symbol_iterator TargetSymbol = i->getSymbol();
569       check(i->getOffset(TargetSymbolOffset));
570       int64_t Addend;
571       check(getELFRelocationAddend(*i, Addend));
572
573       i = i.increment(err);
574       if (i == e)
575         break;
576       check(err);
577
578       // Just check if following relocation is a R_PPC64_TOC
579       uint64_t TypeTOC;
580       check(i->getType(TypeTOC));
581       if (TypeTOC != ELF::R_PPC64_TOC)
582         continue;
583
584       // Finally compares the Symbol value and the target symbol offset
585       // to check if this .opd entry refers to the symbol the relocation
586       // points to.
587       if (Rel.Addend != (intptr_t)TargetSymbolOffset)
588         continue;
589
590       section_iterator tsi(Obj.end_sections());
591       check(TargetSymbol->getSection(tsi));
592       Rel.SectionID = findOrEmitSection(Obj, (*tsi), true, LocalSections);
593       Rel.Addend = (intptr_t)Addend;
594       return;
595     }
596   }
597   llvm_unreachable("Attempting to get address of ODP entry!");
598 }
599
600 // Relocation masks following the #lo(value), #hi(value), #higher(value),
601 // and #highest(value) macros defined in section 4.5.1. Relocation Types
602 // in PPC-elf64abi document.
603 //
604 static inline
605 uint16_t applyPPClo (uint64_t value)
606 {
607   return value & 0xffff;
608 }
609
610 static inline
611 uint16_t applyPPChi (uint64_t value)
612 {
613   return (value >> 16) & 0xffff;
614 }
615
616 static inline
617 uint16_t applyPPChigher (uint64_t value)
618 {
619   return (value >> 32) & 0xffff;
620 }
621
622 static inline
623 uint16_t applyPPChighest (uint64_t value)
624 {
625   return (value >> 48) & 0xffff;
626 }
627
628 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
629                                             uint64_t Offset,
630                                             uint64_t Value,
631                                             uint32_t Type,
632                                             int64_t Addend) {
633   uint8_t* LocalAddress = Section.Address + Offset;
634   switch (Type) {
635   default:
636     llvm_unreachable("Relocation type not implemented yet!");
637   break;
638   case ELF::R_PPC64_ADDR16_LO :
639     writeInt16BE(LocalAddress, applyPPClo (Value + Addend));
640     break;
641   case ELF::R_PPC64_ADDR16_HI :
642     writeInt16BE(LocalAddress, applyPPChi (Value + Addend));
643     break;
644   case ELF::R_PPC64_ADDR16_HIGHER :
645     writeInt16BE(LocalAddress, applyPPChigher (Value + Addend));
646     break;
647   case ELF::R_PPC64_ADDR16_HIGHEST :
648     writeInt16BE(LocalAddress, applyPPChighest (Value + Addend));
649     break;
650   case ELF::R_PPC64_ADDR14 : {
651     assert(((Value + Addend) & 3) == 0);
652     // Preserve the AA/LK bits in the branch instruction
653     uint8_t aalk = *(LocalAddress+3);
654     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
655   } break;
656   case ELF::R_PPC64_ADDR32 : {
657     int32_t Result = static_cast<int32_t>(Value + Addend);
658     if (SignExtend32<32>(Result) != Result)
659       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
660     writeInt32BE(LocalAddress, Result);
661   } break;
662   case ELF::R_PPC64_REL24 : {
663     uint64_t FinalAddress = (Section.LoadAddress + Offset);
664     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
665     if (SignExtend32<24>(delta) != delta)
666       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
667     // Generates a 'bl <address>' instruction
668     writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
669   } break;
670   case ELF::R_PPC64_REL32 : {
671     uint64_t FinalAddress = (Section.LoadAddress + Offset);
672     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
673     if (SignExtend32<32>(delta) != delta)
674       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
675     writeInt32BE(LocalAddress, delta);
676   } break;
677   case ELF::R_PPC64_REL64: {
678     uint64_t FinalAddress = (Section.LoadAddress + Offset);
679     uint64_t Delta = Value - FinalAddress + Addend;
680     writeInt64BE(LocalAddress, Delta);
681   } break;
682   case ELF::R_PPC64_ADDR64 :
683     writeInt64BE(LocalAddress, Value + Addend);
684     break;
685   case ELF::R_PPC64_TOC :
686     writeInt64BE(LocalAddress, findPPC64TOC());
687     break;
688   case ELF::R_PPC64_TOC16 : {
689     uint64_t TOCStart = findPPC64TOC();
690     Value = applyPPClo((Value + Addend) - TOCStart);
691     writeInt16BE(LocalAddress, applyPPClo(Value));
692   } break;
693   case ELF::R_PPC64_TOC16_DS : {
694     uint64_t TOCStart = findPPC64TOC();
695     Value = ((Value + Addend) - TOCStart);
696     writeInt16BE(LocalAddress, applyPPClo(Value));
697   } break;
698   }
699 }
700
701 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
702                                               uint64_t Offset,
703                                               uint64_t Value,
704                                               uint32_t Type,
705                                               int64_t Addend) {
706   uint8_t *LocalAddress = Section.Address + Offset;
707   switch (Type) {
708   default:
709     llvm_unreachable("Relocation type not implemented yet!");
710     break;
711   case ELF::R_390_PC16DBL:
712   case ELF::R_390_PLT16DBL: {
713     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
714     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
715     writeInt16BE(LocalAddress, Delta / 2);
716     break;
717   }
718   case ELF::R_390_PC32DBL:
719   case ELF::R_390_PLT32DBL: {
720     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
721     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
722     writeInt32BE(LocalAddress, Delta / 2);
723     break;
724   }
725   case ELF::R_390_PC32: {
726     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
727     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
728     writeInt32BE(LocalAddress, Delta);
729     break;
730   }
731   case ELF::R_390_64:
732     writeInt64BE(LocalAddress, Value + Addend);
733     break;
734   }
735 }
736
737 // The target location for the relocation is described by RE.SectionID and
738 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
739 // SectionEntry has three members describing its location.
740 // SectionEntry::Address is the address at which the section has been loaded
741 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
742 // address that the section will have in the target process.
743 // SectionEntry::ObjAddress is the address of the bits for this section in the
744 // original emitted object image (also in the current address space).
745 //
746 // Relocations will be applied as if the section were loaded at
747 // SectionEntry::LoadAddress, but they will be applied at an address based
748 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
749 // Target memory contents if they are required for value calculations.
750 //
751 // The Value parameter here is the load address of the symbol for the
752 // relocation to be applied.  For relocations which refer to symbols in the
753 // current object Value will be the LoadAddress of the section in which
754 // the symbol resides (RE.Addend provides additional information about the
755 // symbol location).  For external symbols, Value will be the address of the
756 // symbol in the target address space.
757 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
758                                        uint64_t Value) {
759   const SectionEntry &Section = Sections[RE.SectionID];
760   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend);
761 }
762
763 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
764                                        uint64_t Offset,
765                                        uint64_t Value,
766                                        uint32_t Type,
767                                        int64_t Addend) {
768   switch (Arch) {
769   case Triple::x86_64:
770     resolveX86_64Relocation(Section, Offset, Value, Type, Addend);
771     break;
772   case Triple::x86:
773     resolveX86Relocation(Section, Offset,
774                          (uint32_t)(Value & 0xffffffffL), Type,
775                          (uint32_t)(Addend & 0xffffffffL));
776     break;
777   case Triple::aarch64:
778     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
779     break;
780   case Triple::arm:    // Fall through.
781   case Triple::thumb:
782     resolveARMRelocation(Section, Offset,
783                          (uint32_t)(Value & 0xffffffffL), Type,
784                          (uint32_t)(Addend & 0xffffffffL));
785     break;
786   case Triple::mips:    // Fall through.
787   case Triple::mipsel:
788     resolveMIPSRelocation(Section, Offset,
789                           (uint32_t)(Value & 0xffffffffL), Type,
790                           (uint32_t)(Addend & 0xffffffffL));
791     break;
792   case Triple::ppc64:   // Fall through.
793   case Triple::ppc64le:
794     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
795     break;
796   case Triple::systemz:
797     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
798     break;
799   default: llvm_unreachable("Unsupported CPU type!");
800   }
801 }
802
803 void RuntimeDyldELF::processRelocationRef(unsigned SectionID,
804                                           RelocationRef RelI,
805                                           ObjectImage &Obj,
806                                           ObjSectionToIDMap &ObjSectionToID,
807                                           const SymbolTableMap &Symbols,
808                                           StubMap &Stubs) {
809   uint64_t RelType;
810   Check(RelI.getType(RelType));
811   int64_t Addend;
812   Check(getELFRelocationAddend(RelI, Addend));
813   symbol_iterator Symbol = RelI.getSymbol();
814
815   // Obtain the symbol name which is referenced in the relocation
816   StringRef TargetName;
817   if (Symbol != Obj.end_symbols())
818     Symbol->getName(TargetName);
819   DEBUG(dbgs() << "\t\tRelType: " << RelType
820                << " Addend: " << Addend
821                << " TargetName: " << TargetName
822                << "\n");
823   RelocationValueRef Value;
824   // First search for the symbol in the local symbol table
825   SymbolTableMap::const_iterator lsi = Symbols.end();
826   SymbolRef::Type SymType = SymbolRef::ST_Unknown;
827   if (Symbol != Obj.end_symbols()) {
828     lsi = Symbols.find(TargetName.data());
829     Symbol->getType(SymType);
830   }
831   if (lsi != Symbols.end()) {
832     Value.SectionID = lsi->second.first;
833     Value.Addend = lsi->second.second + Addend;
834   } else {
835     // Search for the symbol in the global symbol table
836     SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
837     if (Symbol != Obj.end_symbols())
838       gsi = GlobalSymbolTable.find(TargetName.data());
839     if (gsi != GlobalSymbolTable.end()) {
840       Value.SectionID = gsi->second.first;
841       Value.Addend = gsi->second.second + Addend;
842     } else {
843       switch (SymType) {
844         case SymbolRef::ST_Debug: {
845           // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
846           // and can be changed by another developers. Maybe best way is add
847           // a new symbol type ST_Section to SymbolRef and use it.
848           section_iterator si(Obj.end_sections());
849           Symbol->getSection(si);
850           if (si == Obj.end_sections())
851             llvm_unreachable("Symbol section not found, bad object file format!");
852           DEBUG(dbgs() << "\t\tThis is section symbol\n");
853           // Default to 'true' in case isText fails (though it never does).
854           bool isCode = true;
855           si->isText(isCode);
856           Value.SectionID = findOrEmitSection(Obj,
857                                               (*si),
858                                               isCode,
859                                               ObjSectionToID);
860           Value.Addend = Addend;
861           break;
862         }
863         case SymbolRef::ST_Unknown: {
864           Value.SymbolName = TargetName.data();
865           Value.Addend = Addend;
866
867           // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
868           // will manifest here as a NULL symbol name.
869           // We can set this as a valid (but empty) symbol name, and rely
870           // on addRelocationForSymbol to handle this.
871           if (!Value.SymbolName)
872               Value.SymbolName = "";
873           break;
874         }
875         default:
876           llvm_unreachable("Unresolved symbol type!");
877           break;
878       }
879     }
880   }
881   uint64_t Offset;
882   Check(RelI.getOffset(Offset));
883
884   DEBUG(dbgs() << "\t\tSectionID: " << SectionID
885                << " Offset: " << Offset
886                << "\n");
887   if (Arch == Triple::aarch64 &&
888       (RelType == ELF::R_AARCH64_CALL26 ||
889        RelType == ELF::R_AARCH64_JUMP26)) {
890     // This is an AArch64 branch relocation, need to use a stub function.
891     DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
892     SectionEntry &Section = Sections[SectionID];
893
894     // Look for an existing stub.
895     StubMap::const_iterator i = Stubs.find(Value);
896     if (i != Stubs.end()) {
897         resolveRelocation(Section, Offset,
898                           (uint64_t)Section.Address + i->second, RelType, 0);
899       DEBUG(dbgs() << " Stub function found\n");
900     } else {
901       // Create a new stub function.
902       DEBUG(dbgs() << " Create a new stub function\n");
903       Stubs[Value] = Section.StubOffset;
904       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
905                                                    Section.StubOffset);
906
907       RelocationEntry REmovz_g3(SectionID,
908                                 StubTargetAddr - Section.Address,
909                                 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
910       RelocationEntry REmovk_g2(SectionID,
911                                 StubTargetAddr - Section.Address + 4,
912                                 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
913       RelocationEntry REmovk_g1(SectionID,
914                                 StubTargetAddr - Section.Address + 8,
915                                 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
916       RelocationEntry REmovk_g0(SectionID,
917                                 StubTargetAddr - Section.Address + 12,
918                                 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
919
920       if (Value.SymbolName) {
921         addRelocationForSymbol(REmovz_g3, Value.SymbolName);
922         addRelocationForSymbol(REmovk_g2, Value.SymbolName);
923         addRelocationForSymbol(REmovk_g1, Value.SymbolName);
924         addRelocationForSymbol(REmovk_g0, Value.SymbolName);
925       } else {
926         addRelocationForSection(REmovz_g3, Value.SectionID);
927         addRelocationForSection(REmovk_g2, Value.SectionID);
928         addRelocationForSection(REmovk_g1, Value.SectionID);
929         addRelocationForSection(REmovk_g0, Value.SectionID);
930       }
931       resolveRelocation(Section, Offset,
932                         (uint64_t)Section.Address + Section.StubOffset,
933                         RelType, 0);
934       Section.StubOffset += getMaxStubSize();
935     }
936   } else if (Arch == Triple::arm &&
937       (RelType == ELF::R_ARM_PC24 ||
938        RelType == ELF::R_ARM_CALL ||
939        RelType == ELF::R_ARM_JUMP24)) {
940     // This is an ARM branch relocation, need to use a stub function.
941     DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
942     SectionEntry &Section = Sections[SectionID];
943
944     // Look for an existing stub.
945     StubMap::const_iterator i = Stubs.find(Value);
946     if (i != Stubs.end()) {
947         resolveRelocation(Section, Offset,
948                           (uint64_t)Section.Address + i->second, RelType, 0);
949       DEBUG(dbgs() << " Stub function found\n");
950     } else {
951       // Create a new stub function.
952       DEBUG(dbgs() << " Create a new stub function\n");
953       Stubs[Value] = Section.StubOffset;
954       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
955                                                    Section.StubOffset);
956       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
957                          ELF::R_ARM_PRIVATE_0, Value.Addend);
958       if (Value.SymbolName)
959         addRelocationForSymbol(RE, Value.SymbolName);
960       else
961         addRelocationForSection(RE, Value.SectionID);
962
963       resolveRelocation(Section, Offset,
964                         (uint64_t)Section.Address + Section.StubOffset,
965                         RelType, 0);
966       Section.StubOffset += getMaxStubSize();
967     }
968   } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
969              RelType == ELF::R_MIPS_26) {
970     // This is an Mips branch relocation, need to use a stub function.
971     DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
972     SectionEntry &Section = Sections[SectionID];
973     uint8_t *Target = Section.Address + Offset;
974     uint32_t *TargetAddress = (uint32_t *)Target;
975
976     // Extract the addend from the instruction.
977     uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
978
979     Value.Addend += Addend;
980
981     //  Look up for existing stub.
982     StubMap::const_iterator i = Stubs.find(Value);
983     if (i != Stubs.end()) {
984       resolveRelocation(Section, Offset,
985                         (uint64_t)Section.Address + i->second, RelType, 0);
986       DEBUG(dbgs() << " Stub function found\n");
987     } else {
988       // Create a new stub function.
989       DEBUG(dbgs() << " Create a new stub function\n");
990       Stubs[Value] = Section.StubOffset;
991       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
992                                                    Section.StubOffset);
993
994       // Creating Hi and Lo relocations for the filled stub instructions.
995       RelocationEntry REHi(SectionID,
996                            StubTargetAddr - Section.Address,
997                            ELF::R_MIPS_UNUSED1, Value.Addend);
998       RelocationEntry RELo(SectionID,
999                            StubTargetAddr - Section.Address + 4,
1000                            ELF::R_MIPS_UNUSED2, Value.Addend);
1001
1002       if (Value.SymbolName) {
1003         addRelocationForSymbol(REHi, Value.SymbolName);
1004         addRelocationForSymbol(RELo, Value.SymbolName);
1005       } else {
1006         addRelocationForSection(REHi, Value.SectionID);
1007         addRelocationForSection(RELo, Value.SectionID);
1008       }
1009
1010       resolveRelocation(Section, Offset,
1011                         (uint64_t)Section.Address + Section.StubOffset,
1012                         RelType, 0);
1013       Section.StubOffset += getMaxStubSize();
1014     }
1015   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1016     if (RelType == ELF::R_PPC64_REL24) {
1017       // A PPC branch relocation will need a stub function if the target is
1018       // an external symbol (Symbol::ST_Unknown) or if the target address
1019       // is not within the signed 24-bits branch address.
1020       SectionEntry &Section = Sections[SectionID];
1021       uint8_t *Target = Section.Address + Offset;
1022       bool RangeOverflow = false;
1023       if (SymType != SymbolRef::ST_Unknown) {
1024         // A function call may points to the .opd entry, so the final symbol value
1025         // in calculated based in the relocation values in .opd section.
1026         findOPDEntrySection(Obj, ObjSectionToID, Value);
1027         uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1028         int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1029         // If it is within 24-bits branch range, just set the branch target
1030         if (SignExtend32<24>(delta) == delta) {
1031           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1032           if (Value.SymbolName)
1033             addRelocationForSymbol(RE, Value.SymbolName);
1034           else
1035             addRelocationForSection(RE, Value.SectionID);
1036         } else {
1037           RangeOverflow = true;
1038         }
1039       }
1040       if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1041         // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1042         // larger than 24-bits.
1043         StubMap::const_iterator i = Stubs.find(Value);
1044         if (i != Stubs.end()) {
1045           // Symbol function stub already created, just relocate to it
1046           resolveRelocation(Section, Offset,
1047                             (uint64_t)Section.Address + i->second, RelType, 0);
1048           DEBUG(dbgs() << " Stub function found\n");
1049         } else {
1050           // Create a new stub function.
1051           DEBUG(dbgs() << " Create a new stub function\n");
1052           Stubs[Value] = Section.StubOffset;
1053           uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1054                                                        Section.StubOffset);
1055           RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1056                              ELF::R_PPC64_ADDR64, Value.Addend);
1057
1058           // Generates the 64-bits address loads as exemplified in section
1059           // 4.5.1 in PPC64 ELF ABI.
1060           RelocationEntry REhst(SectionID,
1061                                 StubTargetAddr - Section.Address + 2,
1062                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1063           RelocationEntry REhr(SectionID,
1064                                StubTargetAddr - Section.Address + 6,
1065                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1066           RelocationEntry REh(SectionID,
1067                               StubTargetAddr - Section.Address + 14,
1068                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
1069           RelocationEntry REl(SectionID,
1070                               StubTargetAddr - Section.Address + 18,
1071                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
1072
1073           if (Value.SymbolName) {
1074             addRelocationForSymbol(REhst, Value.SymbolName);
1075             addRelocationForSymbol(REhr,  Value.SymbolName);
1076             addRelocationForSymbol(REh,   Value.SymbolName);
1077             addRelocationForSymbol(REl,   Value.SymbolName);
1078           } else {
1079             addRelocationForSection(REhst, Value.SectionID);
1080             addRelocationForSection(REhr,  Value.SectionID);
1081             addRelocationForSection(REh,   Value.SectionID);
1082             addRelocationForSection(REl,   Value.SectionID);
1083           }
1084
1085           resolveRelocation(Section, Offset,
1086                             (uint64_t)Section.Address + Section.StubOffset,
1087                             RelType, 0);
1088           if (SymType == SymbolRef::ST_Unknown)
1089             // Restore the TOC for external calls
1090             writeInt32BE(Target+4, 0xE8410028); // ld r2,40(r1)
1091           Section.StubOffset += getMaxStubSize();
1092         }
1093       }
1094     } else {
1095       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1096       // Extra check to avoid relocation againt empty symbols (usually
1097       // the R_PPC64_TOC).
1098       if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1099         Value.SymbolName = NULL;
1100
1101       if (Value.SymbolName)
1102         addRelocationForSymbol(RE, Value.SymbolName);
1103       else
1104         addRelocationForSection(RE, Value.SectionID);
1105     }
1106   } else if (Arch == Triple::systemz &&
1107              (RelType == ELF::R_390_PLT32DBL ||
1108               RelType == ELF::R_390_GOTENT)) {
1109     // Create function stubs for both PLT and GOT references, regardless of
1110     // whether the GOT reference is to data or code.  The stub contains the
1111     // full address of the symbol, as needed by GOT references, and the
1112     // executable part only adds an overhead of 8 bytes.
1113     //
1114     // We could try to conserve space by allocating the code and data
1115     // parts of the stub separately.  However, as things stand, we allocate
1116     // a stub for every relocation, so using a GOT in JIT code should be
1117     // no less space efficient than using an explicit constant pool.
1118     DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1119     SectionEntry &Section = Sections[SectionID];
1120
1121     // Look for an existing stub.
1122     StubMap::const_iterator i = Stubs.find(Value);
1123     uintptr_t StubAddress;
1124     if (i != Stubs.end()) {
1125       StubAddress = uintptr_t(Section.Address) + i->second;
1126       DEBUG(dbgs() << " Stub function found\n");
1127     } else {
1128       // Create a new stub function.
1129       DEBUG(dbgs() << " Create a new stub function\n");
1130
1131       uintptr_t BaseAddress = uintptr_t(Section.Address);
1132       uintptr_t StubAlignment = getStubAlignment();
1133       StubAddress = (BaseAddress + Section.StubOffset +
1134                      StubAlignment - 1) & -StubAlignment;
1135       unsigned StubOffset = StubAddress - BaseAddress;
1136
1137       Stubs[Value] = StubOffset;
1138       createStubFunction((uint8_t *)StubAddress);
1139       RelocationEntry RE(SectionID, StubOffset + 8,
1140                          ELF::R_390_64, Value.Addend - Addend);
1141       if (Value.SymbolName)
1142         addRelocationForSymbol(RE, Value.SymbolName);
1143       else
1144         addRelocationForSection(RE, Value.SectionID);
1145       Section.StubOffset = StubOffset + getMaxStubSize();
1146     }
1147
1148     if (RelType == ELF::R_390_GOTENT)
1149       resolveRelocation(Section, Offset, StubAddress + 8,
1150                         ELF::R_390_PC32DBL, Addend);
1151     else
1152       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1153   } else {
1154     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1155     if (Value.SymbolName)
1156       addRelocationForSymbol(RE, Value.SymbolName);
1157     else
1158       addRelocationForSection(RE, Value.SectionID);
1159   }
1160 }
1161
1162 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1163   if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1164     return false;
1165   return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
1166 }
1167 } // namespace llvm