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