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