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