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