This threads SectionName through the allocateCodeSection/allocateDataSection APIs...
[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                                              uint64_t SymOffset) {
207   switch (Type) {
208   default:
209     llvm_unreachable("Relocation type not implemented yet!");
210   break;
211   case ELF::R_X86_64_64: {
212     uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
213     *Target = Value + Addend;
214     DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend))
215                  << " at " << format("%p\n",Target));
216     break;
217   }
218   case ELF::R_X86_64_32:
219   case ELF::R_X86_64_32S: {
220     Value += Addend;
221     assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
222            (Type == ELF::R_X86_64_32S &&
223              ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
224     uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
225     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
226     *Target = TruncatedAddr;
227     DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr)
228                  << " at " << format("%p\n",Target));
229     break;
230   }
231   case ELF::R_X86_64_GOTPCREL: {
232     // findGOTEntry returns the 'G + GOT' part of the relocation calculation
233     // based on the load/target address of the GOT (not the current/local addr).
234     uint64_t GOTAddr = findGOTEntry(Value, SymOffset);
235     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
236     uint64_t  FinalAddress = Section.LoadAddress + Offset;
237     // The processRelocationRef method combines the symbol offset and the addend
238     // and in most cases that's what we want.  For this relocation type, we need
239     // the raw addend, so we subtract the symbol offset to get it.
240     int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress;
241     assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
242     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
243     *Target = TruncOffset;
244     break;
245   }
246   case ELF::R_X86_64_PC32: {
247     // Get the placeholder value from the generated object since
248     // a previous relocation attempt may have overwritten the loaded version
249     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
250                                                                    + Offset);
251     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
252     uint64_t  FinalAddress = Section.LoadAddress + Offset;
253     int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
254     assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
255     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
256     *Target = TruncOffset;
257     break;
258   }
259   case ELF::R_X86_64_PC64: {
260     // Get the placeholder value from the generated object since
261     // a previous relocation attempt may have overwritten the loaded version
262     uint64_t *Placeholder = reinterpret_cast<uint64_t*>(Section.ObjAddress
263                                                                    + Offset);
264     uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
265     uint64_t  FinalAddress = Section.LoadAddress + Offset;
266     *Target = *Placeholder + Value + Addend - FinalAddress;
267     break;
268   }
269   }
270 }
271
272 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
273                                           uint64_t Offset,
274                                           uint32_t Value,
275                                           uint32_t Type,
276                                           int32_t Addend) {
277   switch (Type) {
278   case ELF::R_386_32: {
279     // Get the placeholder value from the generated object since
280     // a previous relocation attempt may have overwritten the loaded version
281     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
282                                                                    + Offset);
283     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
284     *Target = *Placeholder + Value + Addend;
285     break;
286   }
287   case ELF::R_386_PC32: {
288     // Get the placeholder value from the generated object since
289     // a previous relocation attempt may have overwritten the loaded version
290     uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
291                                                                    + Offset);
292     uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
293     uint32_t  FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
294     uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
295     *Target = RealOffset;
296     break;
297     }
298     default:
299       // There are other relocation types, but it appears these are the
300       // only ones currently used by the LLVM ELF object writer
301       llvm_unreachable("Relocation type not implemented yet!");
302       break;
303   }
304 }
305
306 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
307                                               uint64_t Offset,
308                                               uint64_t Value,
309                                               uint32_t Type,
310                                               int64_t Addend) {
311   uint32_t *TargetPtr = reinterpret_cast<uint32_t*>(Section.Address + Offset);
312   uint64_t FinalAddress = Section.LoadAddress + Offset;
313
314   DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
315                << format("%llx", Section.Address + Offset)
316                << " FinalAddress: 0x" << format("%llx",FinalAddress)
317                << " Value: 0x" << format("%llx",Value)
318                << " Type: 0x" << format("%x",Type)
319                << " Addend: 0x" << format("%llx",Addend)
320                << "\n");
321
322   switch (Type) {
323   default:
324     llvm_unreachable("Relocation type not implemented yet!");
325     break;
326   case ELF::R_AARCH64_ABS64: {
327     uint64_t *TargetPtr = reinterpret_cast<uint64_t*>(Section.Address + Offset);
328     *TargetPtr = Value + Addend;
329     break;
330   }
331   case ELF::R_AARCH64_PREL32: {
332     uint64_t Result = Value + Addend - FinalAddress;
333     assert(static_cast<int64_t>(Result) >= INT32_MIN &&
334            static_cast<int64_t>(Result) <= UINT32_MAX);
335     *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
336     break;
337   }
338   case ELF::R_AARCH64_CALL26: // fallthrough
339   case ELF::R_AARCH64_JUMP26: {
340     // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
341     // calculation.
342     uint64_t BranchImm = Value + Addend - FinalAddress;
343
344     // "Check that -2^27 <= result < 2^27".
345     assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
346            static_cast<int64_t>(BranchImm) < (1LL << 27));
347
348     // AArch64 code is emitted with .rela relocations. The data already in any
349     // bits affected by the relocation on entry is garbage.
350     *TargetPtr &= 0xfc000000U;
351     // Immediate goes in bits 25:0 of B and BL.
352     *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
353     break;
354   }
355   case ELF::R_AARCH64_MOVW_UABS_G3: {
356     uint64_t Result = Value + Addend;
357
358     // AArch64 code is emitted with .rela relocations. The data already in any
359     // bits affected by the relocation on entry is garbage.
360     *TargetPtr &= 0xffe0001fU;
361     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
362     *TargetPtr |= Result >> (48 - 5);
363     // Shift must be "lsl #48", in bits 22:21
364     assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
365     break;
366   }
367   case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
368     uint64_t Result = Value + Addend;
369
370     // AArch64 code is emitted with .rela relocations. The data already in any
371     // bits affected by the relocation on entry is garbage.
372     *TargetPtr &= 0xffe0001fU;
373     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
374     *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
375     // Shift must be "lsl #32", in bits 22:21
376     assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
377     break;
378   }
379   case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
380     uint64_t Result = Value + Addend;
381
382     // AArch64 code is emitted with .rela relocations. The data already in any
383     // bits affected by the relocation on entry is garbage.
384     *TargetPtr &= 0xffe0001fU;
385     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
386     *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
387     // Shift must be "lsl #16", in bits 22:2
388     assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
389     break;
390   }
391   case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
392     uint64_t Result = Value + Addend;
393
394     // AArch64 code is emitted with .rela relocations. The data already in any
395     // bits affected by the relocation on entry is garbage.
396     *TargetPtr &= 0xffe0001fU;
397     // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
398     *TargetPtr |= ((Result & 0xffffU) << 5);
399     // Shift must be "lsl #0", in bits 22:21.
400     assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
401     break;
402   }
403   }
404 }
405
406 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
407                                           uint64_t Offset,
408                                           uint32_t Value,
409                                           uint32_t Type,
410                                           int32_t Addend) {
411   // TODO: Add Thumb relocations.
412   uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
413                                                       Offset);
414   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
415   uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
416   Value += Addend;
417
418   DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
419                << Section.Address + Offset
420                << " FinalAddress: " << format("%p",FinalAddress)
421                << " Value: " << format("%x",Value)
422                << " Type: " << format("%x",Type)
423                << " Addend: " << format("%x",Addend)
424                << "\n");
425
426   switch(Type) {
427   default:
428     llvm_unreachable("Not implemented relocation type!");
429
430   // Write a 32bit value to relocation address, taking into account the
431   // implicit addend encoded in the target.
432   case ELF::R_ARM_TARGET1:
433   case ELF::R_ARM_ABS32:
434     *TargetPtr = *Placeholder + Value;
435     break;
436   // Write first 16 bit of 32 bit value to the mov instruction.
437   // Last 4 bit should be shifted.
438   case ELF::R_ARM_MOVW_ABS_NC:
439     // We are not expecting any other addend in the relocation address.
440     // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
441     // non-contiguous fields.
442     assert((*Placeholder & 0x000F0FFF) == 0);
443     Value = Value & 0xFFFF;
444     *TargetPtr = *Placeholder | (Value & 0xFFF);
445     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
446     break;
447   // Write last 16 bit of 32 bit value to the mov instruction.
448   // Last 4 bit should be shifted.
449   case ELF::R_ARM_MOVT_ABS:
450     // We are not expecting any other addend in the relocation address.
451     // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
452     assert((*Placeholder & 0x000F0FFF) == 0);
453
454     Value = (Value >> 16) & 0xFFFF;
455     *TargetPtr = *Placeholder | (Value & 0xFFF);
456     *TargetPtr |= ((Value >> 12) & 0xF) << 16;
457     break;
458   // Write 24 bit relative value to the branch instruction.
459   case ELF::R_ARM_PC24 :    // Fall through.
460   case ELF::R_ARM_CALL :    // Fall through.
461   case ELF::R_ARM_JUMP24: {
462     int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
463     RelValue = (RelValue & 0x03FFFFFC) >> 2;
464     assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
465     *TargetPtr &= 0xFF000000;
466     *TargetPtr |= RelValue;
467     break;
468   }
469   case ELF::R_ARM_PRIVATE_0:
470     // This relocation is reserved by the ARM ELF ABI for internal use. We
471     // appropriate it here to act as an R_ARM_ABS32 without any addend for use
472     // in the stubs created during JIT (which can't put an addend into the
473     // original object file).
474     *TargetPtr = Value;
475     break;
476   }
477 }
478
479 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
480                                            uint64_t Offset,
481                                            uint32_t Value,
482                                            uint32_t Type,
483                                            int32_t Addend) {
484   uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
485                                                       Offset);
486   uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
487   Value += Addend;
488
489   DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
490                << Section.Address + Offset
491                << " FinalAddress: "
492                << format("%p",Section.LoadAddress + Offset)
493                << " Value: " << format("%x",Value)
494                << " Type: " << format("%x",Type)
495                << " Addend: " << format("%x",Addend)
496                << "\n");
497
498   switch(Type) {
499   default:
500     llvm_unreachable("Not implemented relocation type!");
501     break;
502   case ELF::R_MIPS_32:
503     *TargetPtr = Value + (*Placeholder);
504     break;
505   case ELF::R_MIPS_26:
506     *TargetPtr = ((*Placeholder) & 0xfc000000) | (( Value & 0x0fffffff) >> 2);
507     break;
508   case ELF::R_MIPS_HI16:
509     // Get the higher 16-bits. Also add 1 if bit 15 is 1.
510     Value += ((*Placeholder) & 0x0000ffff) << 16;
511     *TargetPtr = ((*Placeholder) & 0xffff0000) |
512                  (((Value + 0x8000) >> 16) & 0xffff);
513     break;
514   case ELF::R_MIPS_LO16:
515     Value += ((*Placeholder) & 0x0000ffff);
516     *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
517     break;
518   case ELF::R_MIPS_UNUSED1:
519     // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
520     // are used for internal JIT purpose. These relocations are similar to
521     // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
522     // account.
523     *TargetPtr = ((*TargetPtr) & 0xffff0000) |
524                  (((Value + 0x8000) >> 16) & 0xffff);
525     break;
526   case ELF::R_MIPS_UNUSED2:
527     *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
528     break;
529    }
530 }
531
532 // Return the .TOC. section address to R_PPC64_TOC relocations.
533 uint64_t RuntimeDyldELF::findPPC64TOC() const {
534   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
535   // order. The TOC starts where the first of these sections starts.
536   SectionList::const_iterator it = Sections.begin();
537   SectionList::const_iterator ite = Sections.end();
538   for (; it != ite; ++it) {
539     if (it->Name == ".got" ||
540         it->Name == ".toc" ||
541         it->Name == ".tocbss" ||
542         it->Name == ".plt")
543       break;
544   }
545   if (it == ite) {
546     // This may happen for
547     // * references to TOC base base (sym@toc, .odp relocation) without
548     // a .toc directive.
549     // In this case just use the first section (which is usually
550     // the .odp) since the code won't reference the .toc base
551     // directly.
552     it = Sections.begin();
553   }
554   assert (it != ite);
555   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
556   // thus permitting a full 64 Kbytes segment.
557   return it->LoadAddress + 0x8000;
558 }
559
560 // Returns the sections and offset associated with the ODP entry referenced
561 // by Symbol.
562 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
563                                          ObjSectionToIDMap &LocalSections,
564                                          RelocationValueRef &Rel) {
565   // Get the ELF symbol value (st_value) to compare with Relocation offset in
566   // .opd entries
567
568   error_code err;
569   for (section_iterator si = Obj.begin_sections(),
570      se = Obj.end_sections(); si != se; si.increment(err)) {
571     section_iterator RelSecI = si->getRelocatedSection();
572     if (RelSecI == Obj.end_sections())
573       continue;
574
575     StringRef RelSectionName;
576     check(RelSecI->getName(RelSectionName));
577     if (RelSectionName != ".opd")
578       continue;
579
580     for (relocation_iterator i = si->begin_relocations(),
581          e = si->end_relocations(); i != e;) {
582       check(err);
583
584       // The R_PPC64_ADDR64 relocation indicates the first field
585       // of a .opd entry
586       uint64_t TypeFunc;
587       check(i->getType(TypeFunc));
588       if (TypeFunc != ELF::R_PPC64_ADDR64) {
589         i.increment(err);
590         continue;
591       }
592
593       uint64_t TargetSymbolOffset;
594       symbol_iterator TargetSymbol = i->getSymbol();
595       check(i->getOffset(TargetSymbolOffset));
596       int64_t Addend;
597       check(getELFRelocationAddend(*i, Addend));
598
599       i = i.increment(err);
600       if (i == e)
601         break;
602       check(err);
603
604       // Just check if following relocation is a R_PPC64_TOC
605       uint64_t TypeTOC;
606       check(i->getType(TypeTOC));
607       if (TypeTOC != ELF::R_PPC64_TOC)
608         continue;
609
610       // Finally compares the Symbol value and the target symbol offset
611       // to check if this .opd entry refers to the symbol the relocation
612       // points to.
613       if (Rel.Addend != (int64_t)TargetSymbolOffset)
614         continue;
615
616       section_iterator tsi(Obj.end_sections());
617       check(TargetSymbol->getSection(tsi));
618       Rel.SectionID = findOrEmitSection(Obj, (*tsi), true, LocalSections);
619       Rel.Addend = (intptr_t)Addend;
620       return;
621     }
622   }
623   llvm_unreachable("Attempting to get address of ODP entry!");
624 }
625
626 // Relocation masks following the #lo(value), #hi(value), #higher(value),
627 // and #highest(value) macros defined in section 4.5.1. Relocation Types
628 // in PPC-elf64abi document.
629 //
630 static inline
631 uint16_t applyPPClo (uint64_t value)
632 {
633   return value & 0xffff;
634 }
635
636 static inline
637 uint16_t applyPPChi (uint64_t value)
638 {
639   return (value >> 16) & 0xffff;
640 }
641
642 static inline
643 uint16_t applyPPChigher (uint64_t value)
644 {
645   return (value >> 32) & 0xffff;
646 }
647
648 static inline
649 uint16_t applyPPChighest (uint64_t value)
650 {
651   return (value >> 48) & 0xffff;
652 }
653
654 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
655                                             uint64_t Offset,
656                                             uint64_t Value,
657                                             uint32_t Type,
658                                             int64_t Addend) {
659   uint8_t* LocalAddress = Section.Address + Offset;
660   switch (Type) {
661   default:
662     llvm_unreachable("Relocation type not implemented yet!");
663   break;
664   case ELF::R_PPC64_ADDR16_LO :
665     writeInt16BE(LocalAddress, applyPPClo (Value + Addend));
666     break;
667   case ELF::R_PPC64_ADDR16_HI :
668     writeInt16BE(LocalAddress, applyPPChi (Value + Addend));
669     break;
670   case ELF::R_PPC64_ADDR16_HIGHER :
671     writeInt16BE(LocalAddress, applyPPChigher (Value + Addend));
672     break;
673   case ELF::R_PPC64_ADDR16_HIGHEST :
674     writeInt16BE(LocalAddress, applyPPChighest (Value + Addend));
675     break;
676   case ELF::R_PPC64_ADDR14 : {
677     assert(((Value + Addend) & 3) == 0);
678     // Preserve the AA/LK bits in the branch instruction
679     uint8_t aalk = *(LocalAddress+3);
680     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
681   } break;
682   case ELF::R_PPC64_ADDR32 : {
683     int32_t Result = static_cast<int32_t>(Value + Addend);
684     if (SignExtend32<32>(Result) != Result)
685       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
686     writeInt32BE(LocalAddress, Result);
687   } break;
688   case ELF::R_PPC64_REL24 : {
689     uint64_t FinalAddress = (Section.LoadAddress + Offset);
690     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
691     if (SignExtend32<24>(delta) != delta)
692       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
693     // Generates a 'bl <address>' instruction
694     writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
695   } break;
696   case ELF::R_PPC64_REL32 : {
697     uint64_t FinalAddress = (Section.LoadAddress + Offset);
698     int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
699     if (SignExtend32<32>(delta) != delta)
700       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
701     writeInt32BE(LocalAddress, delta);
702   } break;
703   case ELF::R_PPC64_REL64: {
704     uint64_t FinalAddress = (Section.LoadAddress + Offset);
705     uint64_t Delta = Value - FinalAddress + Addend;
706     writeInt64BE(LocalAddress, Delta);
707   } break;
708   case ELF::R_PPC64_ADDR64 :
709     writeInt64BE(LocalAddress, Value + Addend);
710     break;
711   case ELF::R_PPC64_TOC :
712     writeInt64BE(LocalAddress, findPPC64TOC());
713     break;
714   case ELF::R_PPC64_TOC16 : {
715     uint64_t TOCStart = findPPC64TOC();
716     Value = applyPPClo((Value + Addend) - TOCStart);
717     writeInt16BE(LocalAddress, applyPPClo(Value));
718   } break;
719   case ELF::R_PPC64_TOC16_DS : {
720     uint64_t TOCStart = findPPC64TOC();
721     Value = ((Value + Addend) - TOCStart);
722     writeInt16BE(LocalAddress, applyPPClo(Value));
723   } break;
724   }
725 }
726
727 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
728                                               uint64_t Offset,
729                                               uint64_t Value,
730                                               uint32_t Type,
731                                               int64_t Addend) {
732   uint8_t *LocalAddress = Section.Address + Offset;
733   switch (Type) {
734   default:
735     llvm_unreachable("Relocation type not implemented yet!");
736     break;
737   case ELF::R_390_PC16DBL:
738   case ELF::R_390_PLT16DBL: {
739     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
740     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
741     writeInt16BE(LocalAddress, Delta / 2);
742     break;
743   }
744   case ELF::R_390_PC32DBL:
745   case ELF::R_390_PLT32DBL: {
746     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
747     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
748     writeInt32BE(LocalAddress, Delta / 2);
749     break;
750   }
751   case ELF::R_390_PC32: {
752     int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
753     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
754     writeInt32BE(LocalAddress, Delta);
755     break;
756   }
757   case ELF::R_390_64:
758     writeInt64BE(LocalAddress, Value + Addend);
759     break;
760   }
761 }
762
763 // The target location for the relocation is described by RE.SectionID and
764 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
765 // SectionEntry has three members describing its location.
766 // SectionEntry::Address is the address at which the section has been loaded
767 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
768 // address that the section will have in the target process.
769 // SectionEntry::ObjAddress is the address of the bits for this section in the
770 // original emitted object image (also in the current address space).
771 //
772 // Relocations will be applied as if the section were loaded at
773 // SectionEntry::LoadAddress, but they will be applied at an address based
774 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
775 // Target memory contents if they are required for value calculations.
776 //
777 // The Value parameter here is the load address of the symbol for the
778 // relocation to be applied.  For relocations which refer to symbols in the
779 // current object Value will be the LoadAddress of the section in which
780 // the symbol resides (RE.Addend provides additional information about the
781 // symbol location).  For external symbols, Value will be the address of the
782 // symbol in the target address space.
783 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
784                                        uint64_t Value) {
785   const SectionEntry &Section = Sections[RE.SectionID];
786   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
787                            RE.SymOffset);
788 }
789
790 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
791                                        uint64_t Offset,
792                                        uint64_t Value,
793                                        uint32_t Type,
794                                        int64_t  Addend,
795                                        uint64_t SymOffset) {
796   switch (Arch) {
797   case Triple::x86_64:
798     resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
799     break;
800   case Triple::x86:
801     resolveX86Relocation(Section, Offset,
802                          (uint32_t)(Value & 0xffffffffL), Type,
803                          (uint32_t)(Addend & 0xffffffffL));
804     break;
805   case Triple::aarch64:
806     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
807     break;
808   case Triple::arm:    // Fall through.
809   case Triple::thumb:
810     resolveARMRelocation(Section, Offset,
811                          (uint32_t)(Value & 0xffffffffL), Type,
812                          (uint32_t)(Addend & 0xffffffffL));
813     break;
814   case Triple::mips:    // Fall through.
815   case Triple::mipsel:
816     resolveMIPSRelocation(Section, Offset,
817                           (uint32_t)(Value & 0xffffffffL), Type,
818                           (uint32_t)(Addend & 0xffffffffL));
819     break;
820   case Triple::ppc64:   // Fall through.
821   case Triple::ppc64le:
822     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
823     break;
824   case Triple::systemz:
825     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
826     break;
827   default: llvm_unreachable("Unsupported CPU type!");
828   }
829 }
830
831 void RuntimeDyldELF::processRelocationRef(unsigned SectionID,
832                                           RelocationRef RelI,
833                                           ObjectImage &Obj,
834                                           ObjSectionToIDMap &ObjSectionToID,
835                                           const SymbolTableMap &Symbols,
836                                           StubMap &Stubs) {
837   uint64_t RelType;
838   Check(RelI.getType(RelType));
839   int64_t Addend;
840   Check(getELFRelocationAddend(RelI, Addend));
841   symbol_iterator Symbol = RelI.getSymbol();
842
843   // Obtain the symbol name which is referenced in the relocation
844   StringRef TargetName;
845   if (Symbol != Obj.end_symbols())
846     Symbol->getName(TargetName);
847   DEBUG(dbgs() << "\t\tRelType: " << RelType
848                << " Addend: " << Addend
849                << " TargetName: " << TargetName
850                << "\n");
851   RelocationValueRef Value;
852   // First search for the symbol in the local symbol table
853   SymbolTableMap::const_iterator lsi = Symbols.end();
854   SymbolRef::Type SymType = SymbolRef::ST_Unknown;
855   if (Symbol != Obj.end_symbols()) {
856     lsi = Symbols.find(TargetName.data());
857     Symbol->getType(SymType);
858   }
859   if (lsi != Symbols.end()) {
860     Value.SectionID = lsi->second.first;
861     Value.Offset = lsi->second.second;
862     Value.Addend = lsi->second.second + Addend;
863   } else {
864     // Search for the symbol in the global symbol table
865     SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
866     if (Symbol != Obj.end_symbols())
867       gsi = GlobalSymbolTable.find(TargetName.data());
868     if (gsi != GlobalSymbolTable.end()) {
869       Value.SectionID = gsi->second.first;
870       Value.Offset = gsi->second.second;
871       Value.Addend = gsi->second.second + Addend;
872     } else {
873       switch (SymType) {
874         case SymbolRef::ST_Debug: {
875           // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
876           // and can be changed by another developers. Maybe best way is add
877           // a new symbol type ST_Section to SymbolRef and use it.
878           section_iterator si(Obj.end_sections());
879           Symbol->getSection(si);
880           if (si == Obj.end_sections())
881             llvm_unreachable("Symbol section not found, bad object file format!");
882           DEBUG(dbgs() << "\t\tThis is section symbol\n");
883           // Default to 'true' in case isText fails (though it never does).
884           bool isCode = true;
885           si->isText(isCode);
886           Value.SectionID = findOrEmitSection(Obj,
887                                               (*si),
888                                               isCode,
889                                               ObjSectionToID);
890           Value.Addend = Addend;
891           break;
892         }
893         case SymbolRef::ST_Data:
894         case SymbolRef::ST_Unknown: {
895           Value.SymbolName = TargetName.data();
896           Value.Addend = Addend;
897
898           // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
899           // will manifest here as a NULL symbol name.
900           // We can set this as a valid (but empty) symbol name, and rely
901           // on addRelocationForSymbol to handle this.
902           if (!Value.SymbolName)
903               Value.SymbolName = "";
904           break;
905         }
906         default:
907           llvm_unreachable("Unresolved symbol type!");
908           break;
909       }
910     }
911   }
912   uint64_t Offset;
913   Check(RelI.getOffset(Offset));
914
915   DEBUG(dbgs() << "\t\tSectionID: " << SectionID
916                << " Offset: " << Offset
917                << "\n");
918   if (Arch == Triple::aarch64 &&
919       (RelType == ELF::R_AARCH64_CALL26 ||
920        RelType == ELF::R_AARCH64_JUMP26)) {
921     // This is an AArch64 branch relocation, need to use a stub function.
922     DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
923     SectionEntry &Section = Sections[SectionID];
924
925     // Look for an existing stub.
926     StubMap::const_iterator i = Stubs.find(Value);
927     if (i != Stubs.end()) {
928         resolveRelocation(Section, Offset,
929                           (uint64_t)Section.Address + i->second, RelType, 0);
930       DEBUG(dbgs() << " Stub function found\n");
931     } else {
932       // Create a new stub function.
933       DEBUG(dbgs() << " Create a new stub function\n");
934       Stubs[Value] = Section.StubOffset;
935       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
936                                                    Section.StubOffset);
937
938       RelocationEntry REmovz_g3(SectionID,
939                                 StubTargetAddr - Section.Address,
940                                 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
941       RelocationEntry REmovk_g2(SectionID,
942                                 StubTargetAddr - Section.Address + 4,
943                                 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
944       RelocationEntry REmovk_g1(SectionID,
945                                 StubTargetAddr - Section.Address + 8,
946                                 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
947       RelocationEntry REmovk_g0(SectionID,
948                                 StubTargetAddr - Section.Address + 12,
949                                 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
950
951       if (Value.SymbolName) {
952         addRelocationForSymbol(REmovz_g3, Value.SymbolName);
953         addRelocationForSymbol(REmovk_g2, Value.SymbolName);
954         addRelocationForSymbol(REmovk_g1, Value.SymbolName);
955         addRelocationForSymbol(REmovk_g0, Value.SymbolName);
956       } else {
957         addRelocationForSection(REmovz_g3, Value.SectionID);
958         addRelocationForSection(REmovk_g2, Value.SectionID);
959         addRelocationForSection(REmovk_g1, Value.SectionID);
960         addRelocationForSection(REmovk_g0, Value.SectionID);
961       }
962       resolveRelocation(Section, Offset,
963                         (uint64_t)Section.Address + Section.StubOffset,
964                         RelType, 0);
965       Section.StubOffset += getMaxStubSize();
966     }
967   } else if (Arch == Triple::arm &&
968       (RelType == ELF::R_ARM_PC24 ||
969        RelType == ELF::R_ARM_CALL ||
970        RelType == ELF::R_ARM_JUMP24)) {
971     // This is an ARM branch relocation, need to use a stub function.
972     DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
973     SectionEntry &Section = Sections[SectionID];
974
975     // Look for an existing stub.
976     StubMap::const_iterator i = Stubs.find(Value);
977     if (i != Stubs.end()) {
978         resolveRelocation(Section, Offset,
979                           (uint64_t)Section.Address + i->second, RelType, 0);
980       DEBUG(dbgs() << " Stub function found\n");
981     } else {
982       // Create a new stub function.
983       DEBUG(dbgs() << " Create a new stub function\n");
984       Stubs[Value] = Section.StubOffset;
985       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
986                                                    Section.StubOffset);
987       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
988                          ELF::R_ARM_PRIVATE_0, Value.Addend);
989       if (Value.SymbolName)
990         addRelocationForSymbol(RE, Value.SymbolName);
991       else
992         addRelocationForSection(RE, Value.SectionID);
993
994       resolveRelocation(Section, Offset,
995                         (uint64_t)Section.Address + Section.StubOffset,
996                         RelType, 0);
997       Section.StubOffset += getMaxStubSize();
998     }
999   } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1000              RelType == ELF::R_MIPS_26) {
1001     // This is an Mips branch relocation, need to use a stub function.
1002     DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1003     SectionEntry &Section = Sections[SectionID];
1004     uint8_t *Target = Section.Address + Offset;
1005     uint32_t *TargetAddress = (uint32_t *)Target;
1006
1007     // Extract the addend from the instruction.
1008     uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1009
1010     Value.Addend += Addend;
1011
1012     //  Look up for existing stub.
1013     StubMap::const_iterator i = Stubs.find(Value);
1014     if (i != Stubs.end()) {
1015       resolveRelocation(Section, Offset,
1016                         (uint64_t)Section.Address + i->second, RelType, 0);
1017       DEBUG(dbgs() << " Stub function found\n");
1018     } else {
1019       // Create a new stub function.
1020       DEBUG(dbgs() << " Create a new stub function\n");
1021       Stubs[Value] = Section.StubOffset;
1022       uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1023                                                    Section.StubOffset);
1024
1025       // Creating Hi and Lo relocations for the filled stub instructions.
1026       RelocationEntry REHi(SectionID,
1027                            StubTargetAddr - Section.Address,
1028                            ELF::R_MIPS_UNUSED1, Value.Addend);
1029       RelocationEntry RELo(SectionID,
1030                            StubTargetAddr - Section.Address + 4,
1031                            ELF::R_MIPS_UNUSED2, Value.Addend);
1032
1033       if (Value.SymbolName) {
1034         addRelocationForSymbol(REHi, Value.SymbolName);
1035         addRelocationForSymbol(RELo, Value.SymbolName);
1036       } else {
1037         addRelocationForSection(REHi, Value.SectionID);
1038         addRelocationForSection(RELo, Value.SectionID);
1039       }
1040
1041       resolveRelocation(Section, Offset,
1042                         (uint64_t)Section.Address + Section.StubOffset,
1043                         RelType, 0);
1044       Section.StubOffset += getMaxStubSize();
1045     }
1046   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1047     if (RelType == ELF::R_PPC64_REL24) {
1048       // A PPC branch relocation will need a stub function if the target is
1049       // an external symbol (Symbol::ST_Unknown) or if the target address
1050       // is not within the signed 24-bits branch address.
1051       SectionEntry &Section = Sections[SectionID];
1052       uint8_t *Target = Section.Address + Offset;
1053       bool RangeOverflow = false;
1054       if (SymType != SymbolRef::ST_Unknown) {
1055         // A function call may points to the .opd entry, so the final symbol value
1056         // in calculated based in the relocation values in .opd section.
1057         findOPDEntrySection(Obj, ObjSectionToID, Value);
1058         uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1059         int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1060         // If it is within 24-bits branch range, just set the branch target
1061         if (SignExtend32<24>(delta) == delta) {
1062           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1063           if (Value.SymbolName)
1064             addRelocationForSymbol(RE, Value.SymbolName);
1065           else
1066             addRelocationForSection(RE, Value.SectionID);
1067         } else {
1068           RangeOverflow = true;
1069         }
1070       }
1071       if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1072         // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1073         // larger than 24-bits.
1074         StubMap::const_iterator i = Stubs.find(Value);
1075         if (i != Stubs.end()) {
1076           // Symbol function stub already created, just relocate to it
1077           resolveRelocation(Section, Offset,
1078                             (uint64_t)Section.Address + i->second, RelType, 0);
1079           DEBUG(dbgs() << " Stub function found\n");
1080         } else {
1081           // Create a new stub function.
1082           DEBUG(dbgs() << " Create a new stub function\n");
1083           Stubs[Value] = Section.StubOffset;
1084           uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1085                                                        Section.StubOffset);
1086           RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1087                              ELF::R_PPC64_ADDR64, Value.Addend);
1088
1089           // Generates the 64-bits address loads as exemplified in section
1090           // 4.5.1 in PPC64 ELF ABI.
1091           RelocationEntry REhst(SectionID,
1092                                 StubTargetAddr - Section.Address + 2,
1093                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1094           RelocationEntry REhr(SectionID,
1095                                StubTargetAddr - Section.Address + 6,
1096                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1097           RelocationEntry REh(SectionID,
1098                               StubTargetAddr - Section.Address + 14,
1099                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
1100           RelocationEntry REl(SectionID,
1101                               StubTargetAddr - Section.Address + 18,
1102                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
1103
1104           if (Value.SymbolName) {
1105             addRelocationForSymbol(REhst, Value.SymbolName);
1106             addRelocationForSymbol(REhr,  Value.SymbolName);
1107             addRelocationForSymbol(REh,   Value.SymbolName);
1108             addRelocationForSymbol(REl,   Value.SymbolName);
1109           } else {
1110             addRelocationForSection(REhst, Value.SectionID);
1111             addRelocationForSection(REhr,  Value.SectionID);
1112             addRelocationForSection(REh,   Value.SectionID);
1113             addRelocationForSection(REl,   Value.SectionID);
1114           }
1115
1116           resolveRelocation(Section, Offset,
1117                             (uint64_t)Section.Address + Section.StubOffset,
1118                             RelType, 0);
1119           if (SymType == SymbolRef::ST_Unknown)
1120             // Restore the TOC for external calls
1121             writeInt32BE(Target+4, 0xE8410028); // ld r2,40(r1)
1122           Section.StubOffset += getMaxStubSize();
1123         }
1124       }
1125     } else {
1126       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1127       // Extra check to avoid relocation againt empty symbols (usually
1128       // the R_PPC64_TOC).
1129       if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1130         Value.SymbolName = NULL;
1131
1132       if (Value.SymbolName)
1133         addRelocationForSymbol(RE, Value.SymbolName);
1134       else
1135         addRelocationForSection(RE, Value.SectionID);
1136     }
1137   } else if (Arch == Triple::systemz &&
1138              (RelType == ELF::R_390_PLT32DBL ||
1139               RelType == ELF::R_390_GOTENT)) {
1140     // Create function stubs for both PLT and GOT references, regardless of
1141     // whether the GOT reference is to data or code.  The stub contains the
1142     // full address of the symbol, as needed by GOT references, and the
1143     // executable part only adds an overhead of 8 bytes.
1144     //
1145     // We could try to conserve space by allocating the code and data
1146     // parts of the stub separately.  However, as things stand, we allocate
1147     // a stub for every relocation, so using a GOT in JIT code should be
1148     // no less space efficient than using an explicit constant pool.
1149     DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1150     SectionEntry &Section = Sections[SectionID];
1151
1152     // Look for an existing stub.
1153     StubMap::const_iterator i = Stubs.find(Value);
1154     uintptr_t StubAddress;
1155     if (i != Stubs.end()) {
1156       StubAddress = uintptr_t(Section.Address) + i->second;
1157       DEBUG(dbgs() << " Stub function found\n");
1158     } else {
1159       // Create a new stub function.
1160       DEBUG(dbgs() << " Create a new stub function\n");
1161
1162       uintptr_t BaseAddress = uintptr_t(Section.Address);
1163       uintptr_t StubAlignment = getStubAlignment();
1164       StubAddress = (BaseAddress + Section.StubOffset +
1165                      StubAlignment - 1) & -StubAlignment;
1166       unsigned StubOffset = StubAddress - BaseAddress;
1167
1168       Stubs[Value] = StubOffset;
1169       createStubFunction((uint8_t *)StubAddress);
1170       RelocationEntry RE(SectionID, StubOffset + 8,
1171                          ELF::R_390_64, Value.Addend - Addend);
1172       if (Value.SymbolName)
1173         addRelocationForSymbol(RE, Value.SymbolName);
1174       else
1175         addRelocationForSection(RE, Value.SectionID);
1176       Section.StubOffset = StubOffset + getMaxStubSize();
1177     }
1178
1179     if (RelType == ELF::R_390_GOTENT)
1180       resolveRelocation(Section, Offset, StubAddress + 8,
1181                         ELF::R_390_PC32DBL, Addend);
1182     else
1183       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1184   } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1185     // The way the PLT relocations normally work is that the linker allocates the
1186     // PLT and this relocation makes a PC-relative call into the PLT.  The PLT
1187     // entry will then jump to an address provided by the GOT.  On first call, the
1188     // GOT address will point back into PLT code that resolves the symbol.  After
1189     // the first call, the GOT entry points to the actual function.
1190     //
1191     // For local functions we're ignoring all of that here and just replacing
1192     // the PLT32 relocation type with PC32, which will translate the relocation
1193     // into a PC-relative call directly to the function. For external symbols we
1194     // can't be sure the function will be within 2^32 bytes of the call site, so
1195     // we need to create a stub, which calls into the GOT.  This case is
1196     // equivalent to the usual PLT implementation except that we use the stub
1197     // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1198     // rather than allocating a PLT section.
1199     if (Value.SymbolName) {
1200       // This is a call to an external function.
1201       // Look for an existing stub.
1202       SectionEntry &Section = Sections[SectionID];
1203       StubMap::const_iterator i = Stubs.find(Value);
1204       uintptr_t StubAddress;
1205       if (i != Stubs.end()) {
1206         StubAddress = uintptr_t(Section.Address) + i->second;
1207         DEBUG(dbgs() << " Stub function found\n");
1208       } else {
1209         // Create a new stub function (equivalent to a PLT entry).
1210         DEBUG(dbgs() << " Create a new stub function\n");
1211
1212         uintptr_t BaseAddress = uintptr_t(Section.Address);
1213         uintptr_t StubAlignment = getStubAlignment();
1214         StubAddress = (BaseAddress + Section.StubOffset +
1215                       StubAlignment - 1) & -StubAlignment;
1216         unsigned StubOffset = StubAddress - BaseAddress;
1217         Stubs[Value] = StubOffset;
1218         createStubFunction((uint8_t *)StubAddress);
1219
1220         // Create a GOT entry for the external function.
1221         GOTEntries.push_back(Value);
1222
1223         // Make our stub function a relative call to the GOT entry.
1224         RelocationEntry RE(SectionID, StubOffset + 2,
1225                            ELF::R_X86_64_GOTPCREL, -4);
1226         addRelocationForSymbol(RE, Value.SymbolName);
1227
1228         // Bump our stub offset counter
1229         Section.StubOffset = StubOffset + getMaxStubSize();
1230       }
1231
1232       // Make the target call a call into the stub table.
1233       resolveRelocation(Section, Offset, StubAddress,
1234                       ELF::R_X86_64_PC32, Addend);
1235     } else {
1236       RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1237                          Value.Offset);
1238       addRelocationForSection(RE, Value.SectionID);
1239     }
1240   } else {
1241     if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1242       GOTEntries.push_back(Value);
1243     }
1244     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1245     if (Value.SymbolName)
1246       addRelocationForSymbol(RE, Value.SymbolName);
1247     else
1248       addRelocationForSection(RE, Value.SectionID);
1249   }
1250 }
1251
1252 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1253   for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1254     if (GOTEntries[i].SymbolName != 0 && GOTEntries[i].SymbolName == Name) {
1255       GOTEntries[i].Offset = Addr;
1256     }
1257   }
1258 }
1259
1260 size_t RuntimeDyldELF::getGOTEntrySize() {
1261   // We don't use the GOT in all of these cases, but it's essentially free
1262   // to put them all here.
1263   size_t Result = 0;
1264   switch (Arch) {
1265   case Triple::x86_64:
1266   case Triple::aarch64:
1267   case Triple::ppc64:
1268   case Triple::ppc64le:
1269   case Triple::systemz:
1270     Result = sizeof(uint64_t);
1271     break;
1272   case Triple::x86:
1273   case Triple::arm:
1274   case Triple::thumb:
1275   case Triple::mips:
1276   case Triple::mipsel:
1277     Result = sizeof(uint32_t);
1278     break;
1279   default: llvm_unreachable("Unsupported CPU type!");
1280   }
1281   return Result;
1282 }
1283
1284 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress,
1285                                       uint64_t Offset) {
1286   assert(GOTSectionID != 0
1287          && "Attempting to lookup GOT entry but the GOT was never allocated.");
1288   if (GOTSectionID == 0) {
1289     return 0;
1290   }
1291
1292   size_t GOTEntrySize = getGOTEntrySize();
1293
1294   // Find the matching entry in our vector.
1295   int GOTIndex = -1;
1296   uint64_t SymbolOffset = 0;
1297   for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1298     if (GOTEntries[i].SymbolName == 0) {
1299       if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1300           GOTEntries[i].Offset == Offset) {
1301         GOTIndex = i;
1302         SymbolOffset = GOTEntries[i].Offset;
1303         break;
1304       }
1305     } else {
1306       // GOT entries for external symbols use the addend as the address when
1307       // the external symbol has been resolved.
1308       if (GOTEntries[i].Offset == LoadAddress) {
1309         GOTIndex = i;
1310         // Don't use the Addend here.  The relocation handler will use it.
1311         break;
1312       }
1313     }
1314   }
1315   assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1316   if (GOTIndex == -1)
1317     return 0;
1318
1319   if (GOTEntrySize == sizeof(uint64_t)) {
1320     uint64_t *LocalGOTAddr = (uint64_t*)getSectionAddress(GOTSectionID);
1321     // Fill in this entry with the address of the symbol being referenced.
1322     LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1323   } else {
1324     uint32_t *LocalGOTAddr = (uint32_t*)getSectionAddress(GOTSectionID);
1325     // Fill in this entry with the address of the symbol being referenced.
1326     LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1327   }
1328
1329   // Calculate the load address of this entry
1330   return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1331 }
1332
1333 void RuntimeDyldELF::finalizeLoad() {
1334   // Allocate the GOT if necessary
1335   size_t numGOTEntries = GOTEntries.size();
1336   if (numGOTEntries != 0) {
1337     // Allocate memory for the section
1338     unsigned SectionID = Sections.size();
1339     size_t TotalSize = numGOTEntries * getGOTEntrySize();
1340     uint8_t *Addr = MemMgr->allocateDataSection(
1341       TotalSize, getGOTEntrySize(), SectionID, ".got", false);
1342     if (!Addr)
1343       report_fatal_error("Unable to allocate memory for GOT!");
1344     Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1345     // For now, initialize all GOT entries to zero.  We'll fill them in as
1346     // needed when GOT-based relocations are applied.
1347     memset(Addr, 0, TotalSize);
1348     GOTSectionID = SectionID;
1349   }
1350 }
1351
1352 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1353   if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1354     return false;
1355   return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
1356 }
1357 } // namespace llvm