65110752e6c2b6fdab8d585dc614edee4390a6dd
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyld.cpp
1 //===-- RuntimeDyld.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 the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ExecutionEngine/RuntimeDyld.h"
15 #include "JITRegistrar.h"
16 #include "ObjectImageCommon.h"
17 #include "RuntimeDyldCheckerImpl.h"
18 #include "RuntimeDyldELF.h"
19 #include "RuntimeDyldImpl.h"
20 #include "RuntimeDyldMachO.h"
21 #include "llvm/Object/ELF.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MutexGuard.h"
24
25 using namespace llvm;
26 using namespace llvm::object;
27
28 #define DEBUG_TYPE "dyld"
29
30 // Empty out-of-line virtual destructor as the key function.
31 RuntimeDyldImpl::~RuntimeDyldImpl() {}
32
33 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
34 void JITRegistrar::anchor() {}
35 void ObjectImage::anchor() {}
36 void ObjectImageCommon::anchor() {}
37
38 namespace llvm {
39
40 void RuntimeDyldImpl::registerEHFrames() {}
41
42 void RuntimeDyldImpl::deregisterEHFrames() {}
43
44 #ifndef NDEBUG
45 static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
46   dbgs() << "----- Contents of section " << S.Name << " " << State << " -----";
47
48   const unsigned ColsPerRow = 16;
49
50   uint8_t *DataAddr = S.Address;
51   uint64_t LoadAddr = S.LoadAddress;
52
53   unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
54   unsigned BytesRemaining = S.Size;
55
56   if (StartPadding) {
57     dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr & ~(ColsPerRow - 1)) << ":";
58     while (StartPadding--)
59       dbgs() << "   ";
60   }
61
62   while (BytesRemaining > 0) {
63     if ((LoadAddr & (ColsPerRow - 1)) == 0)
64       dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
65
66     dbgs() << " " << format("%02x", *DataAddr);
67
68     ++DataAddr;
69     ++LoadAddr;
70     --BytesRemaining;
71   }
72
73   dbgs() << "\n";
74 }
75 #endif
76
77 // Resolve the relocations for all symbols we currently know about.
78 void RuntimeDyldImpl::resolveRelocations() {
79   MutexGuard locked(lock);
80
81   // First, resolve relocations associated with external symbols.
82   resolveExternalSymbols();
83
84   // Just iterate over the sections we have and resolve all the relocations
85   // in them. Gross overkill, but it gets the job done.
86   for (int i = 0, e = Sections.size(); i != e; ++i) {
87     // The Section here (Sections[i]) refers to the section in which the
88     // symbol for the relocation is located.  The SectionID in the relocation
89     // entry provides the section to which the relocation will be applied.
90     uint64_t Addr = Sections[i].LoadAddress;
91     DEBUG(dbgs() << "Resolving relocations Section #" << i << "\t"
92                  << format("0x%x", Addr) << "\n");
93     DEBUG(dumpSectionMemory(Sections[i], "before relocations"));
94     resolveRelocationList(Relocations[i], Addr);
95     DEBUG(dumpSectionMemory(Sections[i], "after relocations"));
96     Relocations.erase(i);
97   }
98 }
99
100 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
101                                         uint64_t TargetAddress) {
102   MutexGuard locked(lock);
103   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
104     if (Sections[i].Address == LocalAddress) {
105       reassignSectionAddress(i, TargetAddress);
106       return;
107     }
108   }
109   llvm_unreachable("Attempting to remap address of unknown section!");
110 }
111
112 static std::error_code getOffset(const SymbolRef &Sym, uint64_t &Result) {
113   uint64_t Address;
114   if (std::error_code EC = Sym.getAddress(Address))
115     return EC;
116
117   if (Address == UnknownAddressOrSize) {
118     Result = UnknownAddressOrSize;
119     return object_error::success;
120   }
121
122   const ObjectFile *Obj = Sym.getObject();
123   section_iterator SecI(Obj->section_begin());
124   if (std::error_code EC = Sym.getSection(SecI))
125     return EC;
126
127  if (SecI == Obj->section_end()) {
128    Result = UnknownAddressOrSize;
129    return object_error::success;
130  }
131
132   uint64_t SectionAddress;
133   if (std::error_code EC = SecI->getAddress(SectionAddress))
134     return EC;
135
136   Result = Address - SectionAddress;
137   return object_error::success;
138 }
139
140 std::unique_ptr<ObjectImage>
141 RuntimeDyldImpl::loadObject(std::unique_ptr<ObjectImage> Obj) {
142   MutexGuard locked(lock);
143
144   if (!Obj)
145     return nullptr;
146
147   // Save information about our target
148   Arch = (Triple::ArchType)Obj->getArch();
149   IsTargetLittleEndian = Obj->getObjectFile()->isLittleEndian();
150
151   // Compute the memory size required to load all sections to be loaded
152   // and pass this information to the memory manager
153   if (MemMgr->needsToReserveAllocationSpace()) {
154     uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
155     computeTotalAllocSize(*Obj, CodeSize, DataSizeRO, DataSizeRW);
156     MemMgr->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
157   }
158
159   // Symbols found in this object
160   StringMap<SymbolLoc> LocalSymbols;
161   // Used sections from the object file
162   ObjSectionToIDMap LocalSections;
163
164   // Common symbols requiring allocation, with their sizes and alignments
165   CommonSymbolMap CommonSymbols;
166   // Maximum required total memory to allocate all common symbols
167   uint64_t CommonSize = 0;
168
169   // Parse symbols
170   DEBUG(dbgs() << "Parse symbols:\n");
171   for (symbol_iterator I = Obj->begin_symbols(), E = Obj->end_symbols(); I != E;
172        ++I) {
173     object::SymbolRef::Type SymType;
174     StringRef Name;
175     Check(I->getType(SymType));
176     Check(I->getName(Name));
177
178     uint32_t Flags = I->getFlags();
179
180     bool IsCommon = Flags & SymbolRef::SF_Common;
181     if (IsCommon) {
182       // Add the common symbols to a list.  We'll allocate them all below.
183       if (!GlobalSymbolTable.count(Name)) {
184         uint32_t Align;
185         Check(I->getAlignment(Align));
186         uint64_t Size = 0;
187         Check(I->getSize(Size));
188         CommonSize += Size + Align;
189         CommonSymbols[*I] = CommonSymbolInfo(Size, Align);
190       }
191     } else {
192       if (SymType == object::SymbolRef::ST_Function ||
193           SymType == object::SymbolRef::ST_Data ||
194           SymType == object::SymbolRef::ST_Unknown) {
195         uint64_t SectOffset;
196         StringRef SectionData;
197         bool IsCode;
198         section_iterator SI = Obj->end_sections();
199         Check(getOffset(*I, SectOffset));
200         Check(I->getSection(SI));
201         if (SI == Obj->end_sections())
202           continue;
203         Check(SI->getContents(SectionData));
204         Check(SI->isText(IsCode));
205         unsigned SectionID =
206             findOrEmitSection(*Obj, *SI, IsCode, LocalSections);
207         LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
208         DEBUG(dbgs() << "\tOffset: " << format("%p", (uintptr_t)SectOffset)
209                      << " flags: " << Flags << " SID: " << SectionID);
210         GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
211       }
212     }
213     DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
214   }
215
216   // Allocate common symbols
217   if (CommonSize != 0)
218     emitCommonSymbols(*Obj, CommonSymbols, CommonSize, GlobalSymbolTable);
219
220   // Parse and process relocations
221   DEBUG(dbgs() << "Parse relocations:\n");
222   for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
223        SI != SE; ++SI) {
224     unsigned SectionID = 0;
225     StubMap Stubs;
226     section_iterator RelocatedSection = SI->getRelocatedSection();
227
228     relocation_iterator I = SI->relocation_begin();
229     relocation_iterator E = SI->relocation_end();
230
231     if (I == E && !ProcessAllSections)
232       continue;
233
234     bool IsCode = false;
235     Check(RelocatedSection->isText(IsCode));
236     SectionID =
237         findOrEmitSection(*Obj, *RelocatedSection, IsCode, LocalSections);
238     DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
239
240     for (; I != E;)
241       I = processRelocationRef(SectionID, I, *Obj, LocalSections, LocalSymbols,
242                                Stubs);
243
244     // If there is an attached checker, notify it about the stubs for this
245     // section so that they can be verified.
246     if (Checker)
247       Checker->registerStubMap(Obj->getImageName(), SectionID, Stubs);
248   }
249
250   // Give the subclasses a chance to tie-up any loose ends.
251   finalizeLoad(*Obj, LocalSections);
252
253   return Obj;
254 }
255
256 // A helper method for computeTotalAllocSize.
257 // Computes the memory size required to allocate sections with the given sizes,
258 // assuming that all sections are allocated with the given alignment
259 static uint64_t
260 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
261                                  uint64_t Alignment) {
262   uint64_t TotalSize = 0;
263   for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
264     uint64_t AlignedSize =
265         (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
266     TotalSize += AlignedSize;
267   }
268   return TotalSize;
269 }
270
271 // Compute an upper bound of the memory size that is required to load all
272 // sections
273 void RuntimeDyldImpl::computeTotalAllocSize(ObjectImage &Obj,
274                                             uint64_t &CodeSize,
275                                             uint64_t &DataSizeRO,
276                                             uint64_t &DataSizeRW) {
277   // Compute the size of all sections required for execution
278   std::vector<uint64_t> CodeSectionSizes;
279   std::vector<uint64_t> ROSectionSizes;
280   std::vector<uint64_t> RWSectionSizes;
281   uint64_t MaxAlignment = sizeof(void *);
282
283   // Collect sizes of all sections to be loaded;
284   // also determine the max alignment of all sections
285   for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
286        SI != SE; ++SI) {
287     const SectionRef &Section = *SI;
288
289     bool IsRequired;
290     Check(Section.isRequiredForExecution(IsRequired));
291
292     // Consider only the sections that are required to be loaded for execution
293     if (IsRequired) {
294       uint64_t DataSize = 0;
295       uint64_t Alignment64 = 0;
296       bool IsCode = false;
297       bool IsReadOnly = false;
298       StringRef Name;
299       Check(Section.getSize(DataSize));
300       Check(Section.getAlignment(Alignment64));
301       Check(Section.isText(IsCode));
302       Check(Section.isReadOnlyData(IsReadOnly));
303       Check(Section.getName(Name));
304       unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
305
306       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
307       uint64_t SectionSize = DataSize + StubBufSize;
308
309       // The .eh_frame section (at least on Linux) needs an extra four bytes
310       // padded
311       // with zeroes added at the end.  For MachO objects, this section has a
312       // slightly different name, so this won't have any effect for MachO
313       // objects.
314       if (Name == ".eh_frame")
315         SectionSize += 4;
316
317       if (SectionSize > 0) {
318         // save the total size of the section
319         if (IsCode) {
320           CodeSectionSizes.push_back(SectionSize);
321         } else if (IsReadOnly) {
322           ROSectionSizes.push_back(SectionSize);
323         } else {
324           RWSectionSizes.push_back(SectionSize);
325         }
326         // update the max alignment
327         if (Alignment > MaxAlignment) {
328           MaxAlignment = Alignment;
329         }
330       }
331     }
332   }
333
334   // Compute the size of all common symbols
335   uint64_t CommonSize = 0;
336   for (symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols(); I != E;
337        ++I) {
338     uint32_t Flags = I->getFlags();
339     if (Flags & SymbolRef::SF_Common) {
340       // Add the common symbols to a list.  We'll allocate them all below.
341       uint64_t Size = 0;
342       Check(I->getSize(Size));
343       CommonSize += Size;
344     }
345   }
346   if (CommonSize != 0) {
347     RWSectionSizes.push_back(CommonSize);
348   }
349
350   // Compute the required allocation space for each different type of sections
351   // (code, read-only data, read-write data) assuming that all sections are
352   // allocated with the max alignment. Note that we cannot compute with the
353   // individual alignments of the sections, because then the required size
354   // depends on the order, in which the sections are allocated.
355   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
356   DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
357   DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);
358 }
359
360 // compute stub buffer size for the given section
361 unsigned RuntimeDyldImpl::computeSectionStubBufSize(ObjectImage &Obj,
362                                                     const SectionRef &Section) {
363   unsigned StubSize = getMaxStubSize();
364   if (StubSize == 0) {
365     return 0;
366   }
367   // FIXME: this is an inefficient way to handle this. We should computed the
368   // necessary section allocation size in loadObject by walking all the sections
369   // once.
370   unsigned StubBufSize = 0;
371   for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
372        SI != SE; ++SI) {
373     section_iterator RelSecI = SI->getRelocatedSection();
374     if (!(RelSecI == Section))
375       continue;
376
377     for (const RelocationRef &Reloc : SI->relocations()) {
378       (void)Reloc;
379       StubBufSize += StubSize;
380     }
381   }
382
383   // Get section data size and alignment
384   uint64_t Alignment64;
385   uint64_t DataSize;
386   Check(Section.getSize(DataSize));
387   Check(Section.getAlignment(Alignment64));
388
389   // Add stubbuf size alignment
390   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
391   unsigned StubAlignment = getStubAlignment();
392   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
393   if (StubAlignment > EndAlignment)
394     StubBufSize += StubAlignment - EndAlignment;
395   return StubBufSize;
396 }
397
398 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
399                                              unsigned Size) const {
400   uint64_t Result = 0;
401   if (IsTargetLittleEndian) {
402     Src += Size - 1;
403     while (Size--)
404       Result = (Result << 8) | *Src--;
405   } else
406     while (Size--)
407       Result = (Result << 8) | *Src++;
408
409   return Result;
410 }
411
412 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
413                                           unsigned Size) const {
414   if (IsTargetLittleEndian) {
415     while (Size--) {
416       *Dst++ = Value & 0xFF;
417       Value >>= 8;
418     }
419   } else {
420     Dst += Size - 1;
421     while (Size--) {
422       *Dst-- = Value & 0xFF;
423       Value >>= 8;
424     }
425   }
426 }
427
428 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
429                                         const CommonSymbolMap &CommonSymbols,
430                                         uint64_t TotalSize,
431                                         SymbolTableMap &SymbolTable) {
432   // Allocate memory for the section
433   unsigned SectionID = Sections.size();
434   uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void *),
435                                               SectionID, StringRef(), false);
436   if (!Addr)
437     report_fatal_error("Unable to allocate memory for common symbols!");
438   uint64_t Offset = 0;
439   Sections.push_back(SectionEntry("<common symbols>", Addr, TotalSize, 0));
440   memset(Addr, 0, TotalSize);
441
442   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
443                << format("%p", Addr) << " DataSize: " << TotalSize << "\n");
444
445   // Assign the address of each symbol
446   for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
447        itEnd = CommonSymbols.end(); it != itEnd; ++it) {
448     uint64_t Size = it->second.first;
449     uint64_t Align = it->second.second;
450     StringRef Name;
451     it->first.getName(Name);
452     if (Align) {
453       // This symbol has an alignment requirement.
454       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
455       Addr += AlignOffset;
456       Offset += AlignOffset;
457       DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
458                    << format("%p\n", Addr));
459     }
460     Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
461     SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
462     Offset += Size;
463     Addr += Size;
464   }
465 }
466
467 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
468                                       const SectionRef &Section, bool IsCode) {
469
470   StringRef data;
471   uint64_t Alignment64;
472   Check(Section.getContents(data));
473   Check(Section.getAlignment(Alignment64));
474
475   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
476   bool IsRequired;
477   bool IsVirtual;
478   bool IsZeroInit;
479   bool IsReadOnly;
480   uint64_t DataSize;
481   unsigned PaddingSize = 0;
482   unsigned StubBufSize = 0;
483   StringRef Name;
484   Check(Section.isRequiredForExecution(IsRequired));
485   Check(Section.isVirtual(IsVirtual));
486   Check(Section.isZeroInit(IsZeroInit));
487   Check(Section.isReadOnlyData(IsReadOnly));
488   Check(Section.getSize(DataSize));
489   Check(Section.getName(Name));
490
491   StubBufSize = computeSectionStubBufSize(Obj, Section);
492
493   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
494   // with zeroes added at the end.  For MachO objects, this section has a
495   // slightly different name, so this won't have any effect for MachO objects.
496   if (Name == ".eh_frame")
497     PaddingSize = 4;
498
499   uintptr_t Allocate;
500   unsigned SectionID = Sections.size();
501   uint8_t *Addr;
502   const char *pData = nullptr;
503
504   // Some sections, such as debug info, don't need to be loaded for execution.
505   // Leave those where they are.
506   if (IsRequired) {
507     Allocate = DataSize + PaddingSize + StubBufSize;
508     Addr = IsCode ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID,
509                                                 Name)
510                   : MemMgr->allocateDataSection(Allocate, Alignment, SectionID,
511                                                 Name, IsReadOnly);
512     if (!Addr)
513       report_fatal_error("Unable to allocate section memory!");
514
515     // Virtual sections have no data in the object image, so leave pData = 0
516     if (!IsVirtual)
517       pData = data.data();
518
519     // Zero-initialize or copy the data from the image
520     if (IsZeroInit || IsVirtual)
521       memset(Addr, 0, DataSize);
522     else
523       memcpy(Addr, pData, DataSize);
524
525     // Fill in any extra bytes we allocated for padding
526     if (PaddingSize != 0) {
527       memset(Addr + DataSize, 0, PaddingSize);
528       // Update the DataSize variable so that the stub offset is set correctly.
529       DataSize += PaddingSize;
530     }
531
532     DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
533                  << " obj addr: " << format("%p", pData)
534                  << " new addr: " << format("%p", Addr)
535                  << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
536                  << " Allocate: " << Allocate << "\n");
537     Obj.updateSectionAddress(Section, (uint64_t)Addr);
538   } else {
539     // Even if we didn't load the section, we need to record an entry for it
540     // to handle later processing (and by 'handle' I mean don't do anything
541     // with these sections).
542     Allocate = 0;
543     Addr = nullptr;
544     DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
545                  << " obj addr: " << format("%p", data.data()) << " new addr: 0"
546                  << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
547                  << " Allocate: " << Allocate << "\n");
548   }
549
550   Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
551
552   if (Checker)
553     Checker->registerSection(Obj.getImageName(), SectionID);
554
555   return SectionID;
556 }
557
558 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
559                                             const SectionRef &Section,
560                                             bool IsCode,
561                                             ObjSectionToIDMap &LocalSections) {
562
563   unsigned SectionID = 0;
564   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
565   if (i != LocalSections.end())
566     SectionID = i->second;
567   else {
568     SectionID = emitSection(Obj, Section, IsCode);
569     LocalSections[Section] = SectionID;
570   }
571   return SectionID;
572 }
573
574 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
575                                               unsigned SectionID) {
576   Relocations[SectionID].push_back(RE);
577 }
578
579 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
580                                              StringRef SymbolName) {
581   // Relocation by symbol.  If the symbol is found in the global symbol table,
582   // create an appropriate section relocation.  Otherwise, add it to
583   // ExternalSymbolRelocations.
584   SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
585   if (Loc == GlobalSymbolTable.end()) {
586     ExternalSymbolRelocations[SymbolName].push_back(RE);
587   } else {
588     // Copy the RE since we want to modify its addend.
589     RelocationEntry RECopy = RE;
590     RECopy.Addend += Loc->second.second;
591     Relocations[Loc->second.first].push_back(RECopy);
592   }
593 }
594
595 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
596                                              unsigned AbiVariant) {
597   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
598     // This stub has to be able to access the full address space,
599     // since symbol lookup won't necessarily find a handy, in-range,
600     // PLT stub for functions which could be anywhere.
601     uint32_t *StubAddr = (uint32_t *)Addr;
602
603     // Stub can use ip0 (== x16) to calculate address
604     *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
605     StubAddr++;
606     *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
607     StubAddr++;
608     *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
609     StubAddr++;
610     *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
611     StubAddr++;
612     *StubAddr = 0xd61f0200; // br ip0
613
614     return Addr;
615   } else if (Arch == Triple::arm || Arch == Triple::armeb) {
616     // TODO: There is only ARM far stub now. We should add the Thumb stub,
617     // and stubs for branches Thumb - ARM and ARM - Thumb.
618     uint32_t *StubAddr = (uint32_t *)Addr;
619     *StubAddr = 0xe51ff004; // ldr pc,<label>
620     return (uint8_t *)++StubAddr;
621   } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
622     uint32_t *StubAddr = (uint32_t *)Addr;
623     // 0:   3c190000        lui     t9,%hi(addr).
624     // 4:   27390000        addiu   t9,t9,%lo(addr).
625     // 8:   03200008        jr      t9.
626     // c:   00000000        nop.
627     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
628     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
629
630     *StubAddr = LuiT9Instr;
631     StubAddr++;
632     *StubAddr = AdduiT9Instr;
633     StubAddr++;
634     *StubAddr = JrT9Instr;
635     StubAddr++;
636     *StubAddr = NopInstr;
637     return Addr;
638   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
639     // Depending on which version of the ELF ABI is in use, we need to
640     // generate one of two variants of the stub.  They both start with
641     // the same sequence to load the target address into r12.
642     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
643     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
644     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
645     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
646     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
647     if (AbiVariant == 2) {
648       // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
649       // The address is already in r12 as required by the ABI.  Branch to it.
650       writeInt32BE(Addr+20, 0xF8410018); // std   r2,  24(r1)
651       writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
652       writeInt32BE(Addr+28, 0x4E800420); // bctr
653     } else {
654       // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
655       // Load the function address on r11 and sets it to control register. Also
656       // loads the function TOC in r2 and environment pointer to r11.
657       writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
658       writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
659       writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
660       writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
661       writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
662       writeInt32BE(Addr+40, 0x4E800420); // bctr
663     }
664     return Addr;
665   } else if (Arch == Triple::systemz) {
666     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
667     writeInt16BE(Addr+2,  0x0000);
668     writeInt16BE(Addr+4,  0x0004);
669     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
670     // 8-byte address stored at Addr + 8
671     return Addr;
672   } else if (Arch == Triple::x86_64) {
673     *Addr      = 0xFF; // jmp
674     *(Addr+1)  = 0x25; // rip
675     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
676   } else if (Arch == Triple::x86) {
677     *Addr      = 0xE9; // 32-bit pc-relative jump.
678   }
679   return Addr;
680 }
681
682 // Assign an address to a symbol name and resolve all the relocations
683 // associated with it.
684 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
685                                              uint64_t Addr) {
686   // The address to use for relocation resolution is not
687   // the address of the local section buffer. We must be doing
688   // a remote execution environment of some sort. Relocations can't
689   // be applied until all the sections have been moved.  The client must
690   // trigger this with a call to MCJIT::finalize() or
691   // RuntimeDyld::resolveRelocations().
692   //
693   // Addr is a uint64_t because we can't assume the pointer width
694   // of the target is the same as that of the host. Just use a generic
695   // "big enough" type.
696   DEBUG(dbgs() << "Reassigning address for section "
697                << SectionID << " (" << Sections[SectionID].Name << "): "
698                << format("0x%016" PRIx64, Sections[SectionID].LoadAddress) << " -> "
699                << format("0x%016" PRIx64, Addr) << "\n");
700   Sections[SectionID].LoadAddress = Addr;
701 }
702
703 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
704                                             uint64_t Value) {
705   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
706     const RelocationEntry &RE = Relocs[i];
707     // Ignore relocations for sections that were not loaded
708     if (Sections[RE.SectionID].Address == nullptr)
709       continue;
710     resolveRelocation(RE, Value);
711   }
712 }
713
714 void RuntimeDyldImpl::resolveExternalSymbols() {
715   while (!ExternalSymbolRelocations.empty()) {
716     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
717
718     StringRef Name = i->first();
719     if (Name.size() == 0) {
720       // This is an absolute symbol, use an address of zero.
721       DEBUG(dbgs() << "Resolving absolute relocations."
722                    << "\n");
723       RelocationList &Relocs = i->second;
724       resolveRelocationList(Relocs, 0);
725     } else {
726       uint64_t Addr = 0;
727       SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
728       if (Loc == GlobalSymbolTable.end()) {
729         // This is an external symbol, try to get its address from
730         // MemoryManager.
731         Addr = MemMgr->getSymbolAddress(Name.data());
732         // The call to getSymbolAddress may have caused additional modules to
733         // be loaded, which may have added new entries to the
734         // ExternalSymbolRelocations map.  Consquently, we need to update our
735         // iterator.  This is also why retrieval of the relocation list
736         // associated with this symbol is deferred until below this point.
737         // New entries may have been added to the relocation list.
738         i = ExternalSymbolRelocations.find(Name);
739       } else {
740         // We found the symbol in our global table.  It was probably in a
741         // Module that we loaded previously.
742         SymbolLoc SymLoc = Loc->second;
743         Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
744       }
745
746       // FIXME: Implement error handling that doesn't kill the host program!
747       if (!Addr)
748         report_fatal_error("Program used external function '" + Name +
749                            "' which could not be resolved!");
750
751       updateGOTEntries(Name, Addr);
752       DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
753                    << format("0x%lx", Addr) << "\n");
754       // This list may have been updated when we called getSymbolAddress, so
755       // don't change this code to get the list earlier.
756       RelocationList &Relocs = i->second;
757       resolveRelocationList(Relocs, Addr);
758     }
759
760     ExternalSymbolRelocations.erase(i);
761   }
762 }
763
764 //===----------------------------------------------------------------------===//
765 // RuntimeDyld class implementation
766 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
767   // FIXME: There's a potential issue lurking here if a single instance of
768   // RuntimeDyld is used to load multiple objects.  The current implementation
769   // associates a single memory manager with a RuntimeDyld instance.  Even
770   // though the public class spawns a new 'impl' instance for each load,
771   // they share a single memory manager.  This can become a problem when page
772   // permissions are applied.
773   Dyld = nullptr;
774   MM = mm;
775   ProcessAllSections = false;
776   Checker = nullptr;
777 }
778
779 RuntimeDyld::~RuntimeDyld() {}
780
781 static std::unique_ptr<RuntimeDyldELF>
782 createRuntimeDyldELF(RTDyldMemoryManager *MM, bool ProcessAllSections,
783                      RuntimeDyldCheckerImpl *Checker) {
784   std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM));
785   Dyld->setProcessAllSections(ProcessAllSections);
786   Dyld->setRuntimeDyldChecker(Checker);
787   return Dyld;
788 }
789
790 static std::unique_ptr<RuntimeDyldMachO>
791 createRuntimeDyldMachO(Triple::ArchType Arch, RTDyldMemoryManager *MM,
792                        bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
793   std::unique_ptr<RuntimeDyldMachO> Dyld(RuntimeDyldMachO::create(Arch, MM));
794   Dyld->setProcessAllSections(ProcessAllSections);
795   Dyld->setRuntimeDyldChecker(Checker);
796   return Dyld;
797 }
798
799 std::unique_ptr<ObjectImage>
800 RuntimeDyld::loadObject(std::unique_ptr<ObjectFile> InputObject) {
801   std::unique_ptr<ObjectImage> InputImage;
802
803   ObjectFile &Obj = *InputObject;
804
805   if (InputObject->isELF()) {
806     InputImage.reset(RuntimeDyldELF::createObjectImageFromFile(std::move(InputObject)));
807     if (!Dyld)
808       Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker);
809   } else if (InputObject->isMachO()) {
810     InputImage.reset(RuntimeDyldMachO::createObjectImageFromFile(std::move(InputObject)));
811     if (!Dyld)
812       Dyld = createRuntimeDyldMachO(
813           static_cast<Triple::ArchType>(InputImage->getArch()), MM,
814           ProcessAllSections, Checker);
815   } else
816     report_fatal_error("Incompatible object format!");
817
818   if (!Dyld->isCompatibleFile(&Obj))
819     report_fatal_error("Incompatible object format!");
820
821   return Dyld->loadObject(std::move(InputImage));
822 }
823
824 std::unique_ptr<ObjectImage>
825 RuntimeDyld::loadObject(std::unique_ptr<ObjectBuffer> InputBuffer) {
826   std::unique_ptr<ObjectImage> InputImage;
827   sys::fs::file_magic Type = sys::fs::identify_magic(InputBuffer->getBuffer());
828   auto *InputBufferPtr = InputBuffer.get();
829
830   switch (Type) {
831   case sys::fs::file_magic::elf_relocatable:
832   case sys::fs::file_magic::elf_executable:
833   case sys::fs::file_magic::elf_shared_object:
834   case sys::fs::file_magic::elf_core:
835     InputImage = RuntimeDyldELF::createObjectImage(std::move(InputBuffer));
836     if (!Dyld)
837       Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker);
838     break;
839   case sys::fs::file_magic::macho_object:
840   case sys::fs::file_magic::macho_executable:
841   case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
842   case sys::fs::file_magic::macho_core:
843   case sys::fs::file_magic::macho_preload_executable:
844   case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
845   case sys::fs::file_magic::macho_dynamic_linker:
846   case sys::fs::file_magic::macho_bundle:
847   case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
848   case sys::fs::file_magic::macho_dsym_companion:
849     InputImage = RuntimeDyldMachO::createObjectImage(std::move(InputBuffer));
850     if (!Dyld)
851       Dyld = createRuntimeDyldMachO(
852           static_cast<Triple::ArchType>(InputImage->getArch()), MM,
853           ProcessAllSections, Checker);
854     break;
855   case sys::fs::file_magic::unknown:
856   case sys::fs::file_magic::bitcode:
857   case sys::fs::file_magic::archive:
858   case sys::fs::file_magic::coff_object:
859   case sys::fs::file_magic::coff_import_library:
860   case sys::fs::file_magic::pecoff_executable:
861   case sys::fs::file_magic::macho_universal_binary:
862   case sys::fs::file_magic::windows_resource:
863     report_fatal_error("Incompatible object format!");
864   }
865
866   if (!Dyld->isCompatibleFormat(InputBufferPtr))
867     report_fatal_error("Incompatible object format!");
868
869   return Dyld->loadObject(std::move(InputImage));
870 }
871
872 void *RuntimeDyld::getSymbolAddress(StringRef Name) const {
873   if (!Dyld)
874     return nullptr;
875   return Dyld->getSymbolAddress(Name);
876 }
877
878 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) const {
879   if (!Dyld)
880     return 0;
881   return Dyld->getSymbolLoadAddress(Name);
882 }
883
884 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
885
886 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
887   Dyld->reassignSectionAddress(SectionID, Addr);
888 }
889
890 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
891                                     uint64_t TargetAddress) {
892   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
893 }
894
895 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
896
897 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
898
899 void RuntimeDyld::registerEHFrames() {
900   if (Dyld)
901     Dyld->registerEHFrames();
902 }
903
904 void RuntimeDyld::deregisterEHFrames() {
905   if (Dyld)
906     Dyld->deregisterEHFrames();
907 }
908
909 } // end namespace llvm