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 "RuntimeDyldCOFF.h"
16 #include "RuntimeDyldCheckerImpl.h"
17 #include "RuntimeDyldELF.h"
18 #include "RuntimeDyldImpl.h"
19 #include "RuntimeDyldMachO.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Object/ELFObjectFile.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/MutexGuard.h"
25 
26 using namespace llvm;
27 using namespace llvm::object;
28 
29 #define DEBUG_TYPE "dyld"
30 
31 namespace {
32 
33 enum RuntimeDyldErrorCode {
34   GenericRTDyldError = 1
35 };
36 
37 // FIXME: This class is only here to support the transition to llvm::Error. It
38 // will be removed once this transition is complete. Clients should prefer to
39 // deal with the Error value directly, rather than converting to error_code.
40 class RuntimeDyldErrorCategory : public std::error_category {
41 public:
42   const char *name() const noexcept override { return "runtimedyld"; }
43 
44   std::string message(int Condition) const override {
45     switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
46       case GenericRTDyldError: return "Generic RuntimeDyld error";
47     }
48     llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
49   }
50 };
51 
52 static ManagedStatic<RuntimeDyldErrorCategory> RTDyldErrorCategory;
53 
54 }
55 
56 char RuntimeDyldError::ID = 0;
57 
58 void RuntimeDyldError::log(raw_ostream &OS) const {
59   OS << ErrMsg << "\n";
60 }
61 
62 std::error_code RuntimeDyldError::convertToErrorCode() const {
63   return std::error_code(GenericRTDyldError, *RTDyldErrorCategory);
64 }
65 
66 // Empty out-of-line virtual destructor as the key function.
67 RuntimeDyldImpl::~RuntimeDyldImpl() {}
68 
69 // Pin LoadedObjectInfo's vtables to this file.
70 void RuntimeDyld::LoadedObjectInfo::anchor() {}
71 
72 namespace llvm {
73 
74 void RuntimeDyldImpl::registerEHFrames() {}
75 
76 void RuntimeDyldImpl::deregisterEHFrames() {
77   MemMgr.deregisterEHFrames();
78 }
79 
80 #ifndef NDEBUG
81 static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
82   dbgs() << "----- Contents of section " << S.getName() << " " << State
83          << " -----";
84 
85   if (S.getAddress() == nullptr) {
86     dbgs() << "\n          <section not emitted>\n";
87     return;
88   }
89 
90   const unsigned ColsPerRow = 16;
91 
92   uint8_t *DataAddr = S.getAddress();
93   uint64_t LoadAddr = S.getLoadAddress();
94 
95   unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
96   unsigned BytesRemaining = S.getSize();
97 
98   if (StartPadding) {
99     dbgs() << "\n" << format("0x%016" PRIx64,
100                              LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
101     while (StartPadding--)
102       dbgs() << "   ";
103   }
104 
105   while (BytesRemaining > 0) {
106     if ((LoadAddr & (ColsPerRow - 1)) == 0)
107       dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
108 
109     dbgs() << " " << format("%02x", *DataAddr);
110 
111     ++DataAddr;
112     ++LoadAddr;
113     --BytesRemaining;
114   }
115 
116   dbgs() << "\n";
117 }
118 #endif
119 
120 // Resolve the relocations for all symbols we currently know about.
121 void RuntimeDyldImpl::resolveRelocations() {
122   MutexGuard locked(lock);
123 
124   // Print out the sections prior to relocation.
125   LLVM_DEBUG(for (int i = 0, e = Sections.size(); i != e; ++i)
126                  dumpSectionMemory(Sections[i], "before relocations"););
127 
128   // First, resolve relocations associated with external symbols.
129   if (auto Err = resolveExternalSymbols()) {
130     HasError = true;
131     ErrorStr = toString(std::move(Err));
132   }
133 
134   // Iterate over all outstanding relocations
135   for (auto it = Relocations.begin(), e = Relocations.end(); it != e; ++it) {
136     // The Section here (Sections[i]) refers to the section in which the
137     // symbol for the relocation is located.  The SectionID in the relocation
138     // entry provides the section to which the relocation will be applied.
139     int Idx = it->first;
140     uint64_t Addr = Sections[Idx].getLoadAddress();
141     LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
142                       << format("%p", (uintptr_t)Addr) << "\n");
143     resolveRelocationList(it->second, Addr);
144   }
145   Relocations.clear();
146 
147   // Print out sections after relocation.
148   LLVM_DEBUG(for (int i = 0, e = Sections.size(); i != e; ++i)
149                  dumpSectionMemory(Sections[i], "after relocations"););
150 }
151 
152 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
153                                         uint64_t TargetAddress) {
154   MutexGuard locked(lock);
155   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
156     if (Sections[i].getAddress() == LocalAddress) {
157       reassignSectionAddress(i, TargetAddress);
158       return;
159     }
160   }
161   llvm_unreachable("Attempting to remap address of unknown section!");
162 }
163 
164 static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
165                        uint64_t &Result) {
166   Expected<uint64_t> AddressOrErr = Sym.getAddress();
167   if (!AddressOrErr)
168     return AddressOrErr.takeError();
169   Result = *AddressOrErr - Sec.getAddress();
170   return Error::success();
171 }
172 
173 Expected<RuntimeDyldImpl::ObjSectionToIDMap>
174 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
175   MutexGuard locked(lock);
176 
177   // Save information about our target
178   Arch = (Triple::ArchType)Obj.getArch();
179   IsTargetLittleEndian = Obj.isLittleEndian();
180   setMipsABI(Obj);
181 
182   // Compute the memory size required to load all sections to be loaded
183   // and pass this information to the memory manager
184   if (MemMgr.needsToReserveAllocationSpace()) {
185     uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
186     uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
187     if (auto Err = computeTotalAllocSize(Obj,
188                                          CodeSize, CodeAlign,
189                                          RODataSize, RODataAlign,
190                                          RWDataSize, RWDataAlign))
191       return std::move(Err);
192     MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
193                                   RWDataSize, RWDataAlign);
194   }
195 
196   // Used sections from the object file
197   ObjSectionToIDMap LocalSections;
198 
199   // Common symbols requiring allocation, with their sizes and alignments
200   CommonSymbolList CommonSymbolsToAllocate;
201 
202   uint64_t CommonSize = 0;
203   uint32_t CommonAlign = 0;
204 
205   // First, collect all weak and common symbols. We need to know if stronger
206   // definitions occur elsewhere.
207   JITSymbolResolver::LookupFlagsResult SymbolFlags;
208   {
209     JITSymbolResolver::LookupSet Symbols;
210     for (auto &Sym : Obj.symbols()) {
211       uint32_t Flags = Sym.getFlags();
212       if ((Flags & SymbolRef::SF_Common) || (Flags & SymbolRef::SF_Weak)) {
213         // Get symbol name.
214         if (auto NameOrErr = Sym.getName())
215           Symbols.insert(*NameOrErr);
216         else
217           return NameOrErr.takeError();
218       }
219     }
220 
221     if (auto FlagsResultOrErr = Resolver.lookupFlags(Symbols))
222       SymbolFlags = std::move(*FlagsResultOrErr);
223     else
224       return FlagsResultOrErr.takeError();
225   }
226 
227   // Parse symbols
228   LLVM_DEBUG(dbgs() << "Parse symbols:\n");
229   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
230        ++I) {
231     uint32_t Flags = I->getFlags();
232 
233     // Skip undefined symbols.
234     if (Flags & SymbolRef::SF_Undefined)
235       continue;
236 
237     // Get the symbol type.
238     object::SymbolRef::Type SymType;
239     if (auto SymTypeOrErr = I->getType())
240       SymType = *SymTypeOrErr;
241     else
242       return SymTypeOrErr.takeError();
243 
244     // Get symbol name.
245     StringRef Name;
246     if (auto NameOrErr = I->getName())
247       Name = *NameOrErr;
248     else
249       return NameOrErr.takeError();
250 
251     // Compute JIT symbol flags.
252     auto JITSymFlags = getJITSymbolFlags(*I);
253     if (!JITSymFlags)
254       return JITSymFlags.takeError();
255 
256     // If this is a weak definition, check to see if there's a strong one.
257     // If there is, skip this symbol (we won't be providing it: the strong
258     // definition will). If there's no strong definition, make this definition
259     // strong.
260     if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
261       // First check whether there's already a definition in this instance.
262       // FIXME: Override existing weak definitions with strong ones.
263       if (GlobalSymbolTable.count(Name))
264         continue;
265 
266       // Then check whether we found flags for an existing symbol during the
267       // flags lookup earlier.
268       auto FlagsI = SymbolFlags.find(Name);
269       if (FlagsI == SymbolFlags.end() ||
270           (JITSymFlags->isWeak() && !FlagsI->second.isStrong()) ||
271           (JITSymFlags->isCommon() && FlagsI->second.isCommon())) {
272         if (JITSymFlags->isWeak())
273           *JITSymFlags &= ~JITSymbolFlags::Weak;
274         if (JITSymFlags->isCommon()) {
275           *JITSymFlags &= ~JITSymbolFlags::Common;
276           uint32_t Align = I->getAlignment();
277           uint64_t Size = I->getCommonSize();
278           if (!CommonAlign)
279             CommonAlign = Align;
280           CommonSize = alignTo(CommonSize, Align) + Size;
281           CommonSymbolsToAllocate.push_back(*I);
282         }
283       } else
284         continue;
285     }
286 
287     if (Flags & SymbolRef::SF_Absolute &&
288         SymType != object::SymbolRef::ST_File) {
289       uint64_t Addr = 0;
290       if (auto AddrOrErr = I->getAddress())
291         Addr = *AddrOrErr;
292       else
293         return AddrOrErr.takeError();
294 
295       unsigned SectionID = AbsoluteSymbolSection;
296 
297       LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
298                         << " SID: " << SectionID
299                         << " Offset: " << format("%p", (uintptr_t)Addr)
300                         << " flags: " << Flags << "\n");
301       GlobalSymbolTable[Name] = SymbolTableEntry(SectionID, Addr, *JITSymFlags);
302     } else if (SymType == object::SymbolRef::ST_Function ||
303                SymType == object::SymbolRef::ST_Data ||
304                SymType == object::SymbolRef::ST_Unknown ||
305                SymType == object::SymbolRef::ST_Other) {
306 
307       section_iterator SI = Obj.section_end();
308       if (auto SIOrErr = I->getSection())
309         SI = *SIOrErr;
310       else
311         return SIOrErr.takeError();
312 
313       if (SI == Obj.section_end())
314         continue;
315 
316       // Get symbol offset.
317       uint64_t SectOffset;
318       if (auto Err = getOffset(*I, *SI, SectOffset))
319         return std::move(Err);
320 
321       bool IsCode = SI->isText();
322       unsigned SectionID;
323       if (auto SectionIDOrErr =
324               findOrEmitSection(Obj, *SI, IsCode, LocalSections))
325         SectionID = *SectionIDOrErr;
326       else
327         return SectionIDOrErr.takeError();
328 
329       LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
330                         << " SID: " << SectionID
331                         << " Offset: " << format("%p", (uintptr_t)SectOffset)
332                         << " flags: " << Flags << "\n");
333       GlobalSymbolTable[Name] =
334           SymbolTableEntry(SectionID, SectOffset, *JITSymFlags);
335     }
336   }
337 
338   // Allocate common symbols
339   if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
340                                    CommonAlign))
341     return std::move(Err);
342 
343   // Parse and process relocations
344   LLVM_DEBUG(dbgs() << "Parse relocations:\n");
345   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
346        SI != SE; ++SI) {
347     StubMap Stubs;
348     section_iterator RelocatedSection = SI->getRelocatedSection();
349 
350     if (RelocatedSection == SE)
351       continue;
352 
353     relocation_iterator I = SI->relocation_begin();
354     relocation_iterator E = SI->relocation_end();
355 
356     if (I == E && !ProcessAllSections)
357       continue;
358 
359     bool IsCode = RelocatedSection->isText();
360     unsigned SectionID = 0;
361     if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
362                                                 LocalSections))
363       SectionID = *SectionIDOrErr;
364     else
365       return SectionIDOrErr.takeError();
366 
367     LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
368 
369     for (; I != E;)
370       if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
371         I = *IOrErr;
372       else
373         return IOrErr.takeError();
374 
375     // If there is an attached checker, notify it about the stubs for this
376     // section so that they can be verified.
377     if (Checker)
378       Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
379   }
380 
381   // Give the subclasses a chance to tie-up any loose ends.
382   if (auto Err = finalizeLoad(Obj, LocalSections))
383     return std::move(Err);
384 
385 //   for (auto E : LocalSections)
386 //     llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
387 
388   return LocalSections;
389 }
390 
391 // A helper method for computeTotalAllocSize.
392 // Computes the memory size required to allocate sections with the given sizes,
393 // assuming that all sections are allocated with the given alignment
394 static uint64_t
395 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
396                                  uint64_t Alignment) {
397   uint64_t TotalSize = 0;
398   for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
399     uint64_t AlignedSize =
400         (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
401     TotalSize += AlignedSize;
402   }
403   return TotalSize;
404 }
405 
406 static bool isRequiredForExecution(const SectionRef Section) {
407   const ObjectFile *Obj = Section.getObject();
408   if (isa<object::ELFObjectFileBase>(Obj))
409     return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
410   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
411     const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
412     // Avoid loading zero-sized COFF sections.
413     // In PE files, VirtualSize gives the section size, and SizeOfRawData
414     // may be zero for sections with content. In Obj files, SizeOfRawData
415     // gives the section size, and VirtualSize is always zero. Hence
416     // the need to check for both cases below.
417     bool HasContent =
418         (CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
419     bool IsDiscardable =
420         CoffSection->Characteristics &
421         (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
422     return HasContent && !IsDiscardable;
423   }
424 
425   assert(isa<MachOObjectFile>(Obj));
426   return true;
427 }
428 
429 static bool isReadOnlyData(const SectionRef Section) {
430   const ObjectFile *Obj = Section.getObject();
431   if (isa<object::ELFObjectFileBase>(Obj))
432     return !(ELFSectionRef(Section).getFlags() &
433              (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
434   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
435     return ((COFFObj->getCOFFSection(Section)->Characteristics &
436              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
437              | COFF::IMAGE_SCN_MEM_READ
438              | COFF::IMAGE_SCN_MEM_WRITE))
439              ==
440              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
441              | COFF::IMAGE_SCN_MEM_READ));
442 
443   assert(isa<MachOObjectFile>(Obj));
444   return false;
445 }
446 
447 static bool isZeroInit(const SectionRef Section) {
448   const ObjectFile *Obj = Section.getObject();
449   if (isa<object::ELFObjectFileBase>(Obj))
450     return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
451   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
452     return COFFObj->getCOFFSection(Section)->Characteristics &
453             COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
454 
455   auto *MachO = cast<MachOObjectFile>(Obj);
456   unsigned SectionType = MachO->getSectionType(Section);
457   return SectionType == MachO::S_ZEROFILL ||
458          SectionType == MachO::S_GB_ZEROFILL;
459 }
460 
461 // Compute an upper bound of the memory size that is required to load all
462 // sections
463 Error RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
464                                              uint64_t &CodeSize,
465                                              uint32_t &CodeAlign,
466                                              uint64_t &RODataSize,
467                                              uint32_t &RODataAlign,
468                                              uint64_t &RWDataSize,
469                                              uint32_t &RWDataAlign) {
470   // Compute the size of all sections required for execution
471   std::vector<uint64_t> CodeSectionSizes;
472   std::vector<uint64_t> ROSectionSizes;
473   std::vector<uint64_t> RWSectionSizes;
474 
475   // Collect sizes of all sections to be loaded;
476   // also determine the max alignment of all sections
477   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
478        SI != SE; ++SI) {
479     const SectionRef &Section = *SI;
480 
481     bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
482 
483     // Consider only the sections that are required to be loaded for execution
484     if (IsRequired) {
485       uint64_t DataSize = Section.getSize();
486       uint64_t Alignment64 = Section.getAlignment();
487       unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
488       bool IsCode = Section.isText();
489       bool IsReadOnly = isReadOnlyData(Section);
490 
491       StringRef Name;
492       if (auto EC = Section.getName(Name))
493         return errorCodeToError(EC);
494 
495       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
496       uint64_t SectionSize = DataSize + StubBufSize;
497 
498       // The .eh_frame section (at least on Linux) needs an extra four bytes
499       // padded
500       // with zeroes added at the end.  For MachO objects, this section has a
501       // slightly different name, so this won't have any effect for MachO
502       // objects.
503       if (Name == ".eh_frame")
504         SectionSize += 4;
505 
506       if (!SectionSize)
507         SectionSize = 1;
508 
509       if (IsCode) {
510         CodeAlign = std::max(CodeAlign, Alignment);
511         CodeSectionSizes.push_back(SectionSize);
512       } else if (IsReadOnly) {
513         RODataAlign = std::max(RODataAlign, Alignment);
514         ROSectionSizes.push_back(SectionSize);
515       } else {
516         RWDataAlign = std::max(RWDataAlign, Alignment);
517         RWSectionSizes.push_back(SectionSize);
518       }
519     }
520   }
521 
522   // Compute Global Offset Table size. If it is not zero we
523   // also update alignment, which is equal to a size of a
524   // single GOT entry.
525   if (unsigned GotSize = computeGOTSize(Obj)) {
526     RWSectionSizes.push_back(GotSize);
527     RWDataAlign = std::max<uint32_t>(RWDataAlign, getGOTEntrySize());
528   }
529 
530   // Compute the size of all common symbols
531   uint64_t CommonSize = 0;
532   uint32_t CommonAlign = 1;
533   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
534        ++I) {
535     uint32_t Flags = I->getFlags();
536     if (Flags & SymbolRef::SF_Common) {
537       // Add the common symbols to a list.  We'll allocate them all below.
538       uint64_t Size = I->getCommonSize();
539       uint32_t Align = I->getAlignment();
540       // If this is the first common symbol, use its alignment as the alignment
541       // for the common symbols section.
542       if (CommonSize == 0)
543         CommonAlign = Align;
544       CommonSize = alignTo(CommonSize, Align) + Size;
545     }
546   }
547   if (CommonSize != 0) {
548     RWSectionSizes.push_back(CommonSize);
549     RWDataAlign = std::max(RWDataAlign, CommonAlign);
550   }
551 
552   // Compute the required allocation space for each different type of sections
553   // (code, read-only data, read-write data) assuming that all sections are
554   // allocated with the max alignment. Note that we cannot compute with the
555   // individual alignments of the sections, because then the required size
556   // depends on the order, in which the sections are allocated.
557   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
558   RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
559   RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
560 
561   return Error::success();
562 }
563 
564 // compute GOT size
565 unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
566   size_t GotEntrySize = getGOTEntrySize();
567   if (!GotEntrySize)
568     return 0;
569 
570   size_t GotSize = 0;
571   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
572        SI != SE; ++SI) {
573 
574     for (const RelocationRef &Reloc : SI->relocations())
575       if (relocationNeedsGot(Reloc))
576         GotSize += GotEntrySize;
577   }
578 
579   return GotSize;
580 }
581 
582 // compute stub buffer size for the given section
583 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
584                                                     const SectionRef &Section) {
585   unsigned StubSize = getMaxStubSize();
586   if (StubSize == 0) {
587     return 0;
588   }
589   // FIXME: this is an inefficient way to handle this. We should computed the
590   // necessary section allocation size in loadObject by walking all the sections
591   // once.
592   unsigned StubBufSize = 0;
593   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
594        SI != SE; ++SI) {
595     section_iterator RelSecI = SI->getRelocatedSection();
596     if (!(RelSecI == Section))
597       continue;
598 
599     for (const RelocationRef &Reloc : SI->relocations())
600       if (relocationNeedsStub(Reloc))
601         StubBufSize += StubSize;
602   }
603 
604   // Get section data size and alignment
605   uint64_t DataSize = Section.getSize();
606   uint64_t Alignment64 = Section.getAlignment();
607 
608   // Add stubbuf size alignment
609   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
610   unsigned StubAlignment = getStubAlignment();
611   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
612   if (StubAlignment > EndAlignment)
613     StubBufSize += StubAlignment - EndAlignment;
614   return StubBufSize;
615 }
616 
617 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
618                                              unsigned Size) const {
619   uint64_t Result = 0;
620   if (IsTargetLittleEndian) {
621     Src += Size - 1;
622     while (Size--)
623       Result = (Result << 8) | *Src--;
624   } else
625     while (Size--)
626       Result = (Result << 8) | *Src++;
627 
628   return Result;
629 }
630 
631 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
632                                           unsigned Size) const {
633   if (IsTargetLittleEndian) {
634     while (Size--) {
635       *Dst++ = Value & 0xFF;
636       Value >>= 8;
637     }
638   } else {
639     Dst += Size - 1;
640     while (Size--) {
641       *Dst-- = Value & 0xFF;
642       Value >>= 8;
643     }
644   }
645 }
646 
647 Expected<JITSymbolFlags>
648 RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {
649   return JITSymbolFlags::fromObjectSymbol(SR);
650 }
651 
652 Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
653                                          CommonSymbolList &SymbolsToAllocate,
654                                          uint64_t CommonSize,
655                                          uint32_t CommonAlign) {
656   if (SymbolsToAllocate.empty())
657     return Error::success();
658 
659   // Allocate memory for the section
660   unsigned SectionID = Sections.size();
661   uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
662                                              "<common symbols>", false);
663   if (!Addr)
664     report_fatal_error("Unable to allocate memory for common symbols!");
665   uint64_t Offset = 0;
666   Sections.push_back(
667       SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
668   memset(Addr, 0, CommonSize);
669 
670   LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
671                     << " new addr: " << format("%p", Addr)
672                     << " DataSize: " << CommonSize << "\n");
673 
674   // Assign the address of each symbol
675   for (auto &Sym : SymbolsToAllocate) {
676     uint32_t Align = Sym.getAlignment();
677     uint64_t Size = Sym.getCommonSize();
678     StringRef Name;
679     if (auto NameOrErr = Sym.getName())
680       Name = *NameOrErr;
681     else
682       return NameOrErr.takeError();
683     if (Align) {
684       // This symbol has an alignment requirement.
685       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
686       Addr += AlignOffset;
687       Offset += AlignOffset;
688     }
689     auto JITSymFlags = getJITSymbolFlags(Sym);
690 
691     if (!JITSymFlags)
692       return JITSymFlags.takeError();
693 
694     LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
695                       << format("%p", Addr) << "\n");
696     GlobalSymbolTable[Name] =
697         SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
698     Offset += Size;
699     Addr += Size;
700   }
701 
702   if (Checker)
703     Checker->registerSection(Obj.getFileName(), SectionID);
704 
705   return Error::success();
706 }
707 
708 Expected<unsigned>
709 RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
710                              const SectionRef &Section,
711                              bool IsCode) {
712   StringRef data;
713   uint64_t Alignment64 = Section.getAlignment();
714 
715   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
716   unsigned PaddingSize = 0;
717   unsigned StubBufSize = 0;
718   bool IsRequired = isRequiredForExecution(Section);
719   bool IsVirtual = Section.isVirtual();
720   bool IsZeroInit = isZeroInit(Section);
721   bool IsReadOnly = isReadOnlyData(Section);
722   uint64_t DataSize = Section.getSize();
723 
724   StringRef Name;
725   if (auto EC = Section.getName(Name))
726     return errorCodeToError(EC);
727 
728   StubBufSize = computeSectionStubBufSize(Obj, Section);
729 
730   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
731   // with zeroes added at the end.  For MachO objects, this section has a
732   // slightly different name, so this won't have any effect for MachO objects.
733   if (Name == ".eh_frame")
734     PaddingSize = 4;
735 
736   uintptr_t Allocate;
737   unsigned SectionID = Sections.size();
738   uint8_t *Addr;
739   const char *pData = nullptr;
740 
741   // If this section contains any bits (i.e. isn't a virtual or bss section),
742   // grab a reference to them.
743   if (!IsVirtual && !IsZeroInit) {
744     // In either case, set the location of the unrelocated section in memory,
745     // since we still process relocations for it even if we're not applying them.
746     if (auto EC = Section.getContents(data))
747       return errorCodeToError(EC);
748     pData = data.data();
749   }
750 
751   // Code section alignment needs to be at least as high as stub alignment or
752   // padding calculations may by incorrect when the section is remapped to a
753   // higher alignment.
754   if (IsCode) {
755     Alignment = std::max(Alignment, getStubAlignment());
756     if (StubBufSize > 0)
757       PaddingSize += getStubAlignment() - 1;
758   }
759 
760   // Some sections, such as debug info, don't need to be loaded for execution.
761   // Process those only if explicitly requested.
762   if (IsRequired || ProcessAllSections) {
763     Allocate = DataSize + PaddingSize + StubBufSize;
764     if (!Allocate)
765       Allocate = 1;
766     Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
767                                                Name)
768                   : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
769                                                Name, IsReadOnly);
770     if (!Addr)
771       report_fatal_error("Unable to allocate section memory!");
772 
773     // Zero-initialize or copy the data from the image
774     if (IsZeroInit || IsVirtual)
775       memset(Addr, 0, DataSize);
776     else
777       memcpy(Addr, pData, DataSize);
778 
779     // Fill in any extra bytes we allocated for padding
780     if (PaddingSize != 0) {
781       memset(Addr + DataSize, 0, PaddingSize);
782       // Update the DataSize variable to include padding.
783       DataSize += PaddingSize;
784 
785       // Align DataSize to stub alignment if we have any stubs (PaddingSize will
786       // have been increased above to account for this).
787       if (StubBufSize > 0)
788         DataSize &= ~(getStubAlignment() - 1);
789     }
790 
791     LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
792                       << Name << " obj addr: " << format("%p", pData)
793                       << " new addr: " << format("%p", Addr) << " DataSize: "
794                       << DataSize << " StubBufSize: " << StubBufSize
795                       << " Allocate: " << Allocate << "\n");
796   } else {
797     // Even if we didn't load the section, we need to record an entry for it
798     // to handle later processing (and by 'handle' I mean don't do anything
799     // with these sections).
800     Allocate = 0;
801     Addr = nullptr;
802     LLVM_DEBUG(
803         dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
804                << " obj addr: " << format("%p", data.data()) << " new addr: 0"
805                << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
806                << " Allocate: " << Allocate << "\n");
807   }
808 
809   Sections.push_back(
810       SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
811 
812   // Debug info sections are linked as if their load address was zero
813   if (!IsRequired)
814     Sections.back().setLoadAddress(0);
815 
816   if (Checker)
817     Checker->registerSection(Obj.getFileName(), SectionID);
818 
819   return SectionID;
820 }
821 
822 Expected<unsigned>
823 RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
824                                    const SectionRef &Section,
825                                    bool IsCode,
826                                    ObjSectionToIDMap &LocalSections) {
827 
828   unsigned SectionID = 0;
829   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
830   if (i != LocalSections.end())
831     SectionID = i->second;
832   else {
833     if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
834       SectionID = *SectionIDOrErr;
835     else
836       return SectionIDOrErr.takeError();
837     LocalSections[Section] = SectionID;
838   }
839   return SectionID;
840 }
841 
842 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
843                                               unsigned SectionID) {
844   Relocations[SectionID].push_back(RE);
845 }
846 
847 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
848                                              StringRef SymbolName) {
849   // Relocation by symbol.  If the symbol is found in the global symbol table,
850   // create an appropriate section relocation.  Otherwise, add it to
851   // ExternalSymbolRelocations.
852   RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
853   if (Loc == GlobalSymbolTable.end()) {
854     ExternalSymbolRelocations[SymbolName].push_back(RE);
855   } else {
856     // Copy the RE since we want to modify its addend.
857     RelocationEntry RECopy = RE;
858     const auto &SymInfo = Loc->second;
859     RECopy.Addend += SymInfo.getOffset();
860     Relocations[SymInfo.getSectionID()].push_back(RECopy);
861   }
862 }
863 
864 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
865                                              unsigned AbiVariant) {
866   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
867     // This stub has to be able to access the full address space,
868     // since symbol lookup won't necessarily find a handy, in-range,
869     // PLT stub for functions which could be anywhere.
870     // Stub can use ip0 (== x16) to calculate address
871     writeBytesUnaligned(0xd2e00010, Addr,    4); // movz ip0, #:abs_g3:<addr>
872     writeBytesUnaligned(0xf2c00010, Addr+4,  4); // movk ip0, #:abs_g2_nc:<addr>
873     writeBytesUnaligned(0xf2a00010, Addr+8,  4); // movk ip0, #:abs_g1_nc:<addr>
874     writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
875     writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
876 
877     return Addr;
878   } else if (Arch == Triple::arm || Arch == Triple::armeb) {
879     // TODO: There is only ARM far stub now. We should add the Thumb stub,
880     // and stubs for branches Thumb - ARM and ARM - Thumb.
881     writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]
882     return Addr + 4;
883   } else if (IsMipsO32ABI || IsMipsN32ABI) {
884     // 0:   3c190000        lui     t9,%hi(addr).
885     // 4:   27390000        addiu   t9,t9,%lo(addr).
886     // 8:   03200008        jr      t9.
887     // c:   00000000        nop.
888     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
889     const unsigned NopInstr = 0x0;
890     unsigned JrT9Instr = 0x03200008;
891     if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
892         (AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
893       JrT9Instr = 0x03200009;
894 
895     writeBytesUnaligned(LuiT9Instr, Addr, 4);
896     writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
897     writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
898     writeBytesUnaligned(NopInstr, Addr + 12, 4);
899     return Addr;
900   } else if (IsMipsN64ABI) {
901     // 0:   3c190000        lui     t9,%highest(addr).
902     // 4:   67390000        daddiu  t9,t9,%higher(addr).
903     // 8:   0019CC38        dsll    t9,t9,16.
904     // c:   67390000        daddiu  t9,t9,%hi(addr).
905     // 10:  0019CC38        dsll    t9,t9,16.
906     // 14:  67390000        daddiu  t9,t9,%lo(addr).
907     // 18:  03200008        jr      t9.
908     // 1c:  00000000        nop.
909     const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
910                    DsllT9Instr = 0x19CC38;
911     const unsigned NopInstr = 0x0;
912     unsigned JrT9Instr = 0x03200008;
913     if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
914       JrT9Instr = 0x03200009;
915 
916     writeBytesUnaligned(LuiT9Instr, Addr, 4);
917     writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
918     writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
919     writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
920     writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
921     writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
922     writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
923     writeBytesUnaligned(NopInstr, Addr + 28, 4);
924     return Addr;
925   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
926     // Depending on which version of the ELF ABI is in use, we need to
927     // generate one of two variants of the stub.  They both start with
928     // the same sequence to load the target address into r12.
929     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
930     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
931     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
932     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
933     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
934     if (AbiVariant == 2) {
935       // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
936       // The address is already in r12 as required by the ABI.  Branch to it.
937       writeInt32BE(Addr+20, 0xF8410018); // std   r2,  24(r1)
938       writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
939       writeInt32BE(Addr+28, 0x4E800420); // bctr
940     } else {
941       // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
942       // Load the function address on r11 and sets it to control register. Also
943       // loads the function TOC in r2 and environment pointer to r11.
944       writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
945       writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
946       writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
947       writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
948       writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
949       writeInt32BE(Addr+40, 0x4E800420); // bctr
950     }
951     return Addr;
952   } else if (Arch == Triple::systemz) {
953     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
954     writeInt16BE(Addr+2,  0x0000);
955     writeInt16BE(Addr+4,  0x0004);
956     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
957     // 8-byte address stored at Addr + 8
958     return Addr;
959   } else if (Arch == Triple::x86_64) {
960     *Addr      = 0xFF; // jmp
961     *(Addr+1)  = 0x25; // rip
962     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
963   } else if (Arch == Triple::x86) {
964     *Addr      = 0xE9; // 32-bit pc-relative jump.
965   }
966   return Addr;
967 }
968 
969 // Assign an address to a symbol name and resolve all the relocations
970 // associated with it.
971 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
972                                              uint64_t Addr) {
973   // The address to use for relocation resolution is not
974   // the address of the local section buffer. We must be doing
975   // a remote execution environment of some sort. Relocations can't
976   // be applied until all the sections have been moved.  The client must
977   // trigger this with a call to MCJIT::finalize() or
978   // RuntimeDyld::resolveRelocations().
979   //
980   // Addr is a uint64_t because we can't assume the pointer width
981   // of the target is the same as that of the host. Just use a generic
982   // "big enough" type.
983   LLVM_DEBUG(
984       dbgs() << "Reassigning address for section " << SectionID << " ("
985              << Sections[SectionID].getName() << "): "
986              << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
987              << " -> " << format("0x%016" PRIx64, Addr) << "\n");
988   Sections[SectionID].setLoadAddress(Addr);
989 }
990 
991 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
992                                             uint64_t Value) {
993   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
994     const RelocationEntry &RE = Relocs[i];
995     // Ignore relocations for sections that were not loaded
996     if (Sections[RE.SectionID].getAddress() == nullptr)
997       continue;
998     resolveRelocation(RE, Value);
999   }
1000 }
1001 
1002 Error RuntimeDyldImpl::resolveExternalSymbols() {
1003   StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
1004 
1005   // Resolution can trigger emission of more symbols, so iterate until
1006   // we've resolved *everything*.
1007   {
1008     JITSymbolResolver::LookupSet ResolvedSymbols;
1009 
1010     while (true) {
1011       JITSymbolResolver::LookupSet NewSymbols;
1012 
1013       for (auto &RelocKV : ExternalSymbolRelocations) {
1014         StringRef Name = RelocKV.first();
1015         if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
1016             !ResolvedSymbols.count(Name))
1017           NewSymbols.insert(Name);
1018       }
1019 
1020       if (NewSymbols.empty())
1021         break;
1022 
1023       auto NewResolverResults = Resolver.lookup(NewSymbols);
1024       if (!NewResolverResults)
1025         return NewResolverResults.takeError();
1026 
1027       assert(NewResolverResults->size() == NewSymbols.size() &&
1028              "Should have errored on unresolved symbols");
1029 
1030       for (auto &RRKV : *NewResolverResults) {
1031         assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
1032         ExternalSymbolMap.insert(RRKV);
1033         ResolvedSymbols.insert(RRKV.first);
1034       }
1035     }
1036   }
1037 
1038   while (!ExternalSymbolRelocations.empty()) {
1039 
1040     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
1041 
1042     StringRef Name = i->first();
1043     if (Name.size() == 0) {
1044       // This is an absolute symbol, use an address of zero.
1045       LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
1046                         << "\n");
1047       RelocationList &Relocs = i->second;
1048       resolveRelocationList(Relocs, 0);
1049     } else {
1050       uint64_t Addr = 0;
1051       JITSymbolFlags Flags;
1052       RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
1053       if (Loc == GlobalSymbolTable.end()) {
1054         auto RRI = ExternalSymbolMap.find(Name);
1055         assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
1056         Addr = RRI->second.getAddress();
1057         Flags = RRI->second.getFlags();
1058         // The call to getSymbolAddress may have caused additional modules to
1059         // be loaded, which may have added new entries to the
1060         // ExternalSymbolRelocations map.  Consquently, we need to update our
1061         // iterator.  This is also why retrieval of the relocation list
1062         // associated with this symbol is deferred until below this point.
1063         // New entries may have been added to the relocation list.
1064         i = ExternalSymbolRelocations.find(Name);
1065       } else {
1066         // We found the symbol in our global table.  It was probably in a
1067         // Module that we loaded previously.
1068         const auto &SymInfo = Loc->second;
1069         Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
1070                SymInfo.getOffset();
1071         Flags = SymInfo.getFlags();
1072       }
1073 
1074       // FIXME: Implement error handling that doesn't kill the host program!
1075       if (!Addr)
1076         report_fatal_error("Program used external function '" + Name +
1077                            "' which could not be resolved!");
1078 
1079       // If Resolver returned UINT64_MAX, the client wants to handle this symbol
1080       // manually and we shouldn't resolve its relocations.
1081       if (Addr != UINT64_MAX) {
1082 
1083         // Tweak the address based on the symbol flags if necessary.
1084         // For example, this is used by RuntimeDyldMachOARM to toggle the low bit
1085         // if the target symbol is Thumb.
1086         Addr = modifyAddressBasedOnFlags(Addr, Flags);
1087 
1088         LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
1089                           << format("0x%lx", Addr) << "\n");
1090         // This list may have been updated when we called getSymbolAddress, so
1091         // don't change this code to get the list earlier.
1092         RelocationList &Relocs = i->second;
1093         resolveRelocationList(Relocs, Addr);
1094       }
1095     }
1096 
1097     ExternalSymbolRelocations.erase(i);
1098   }
1099 
1100   return Error::success();
1101 }
1102 
1103 //===----------------------------------------------------------------------===//
1104 // RuntimeDyld class implementation
1105 
1106 uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
1107                                           const object::SectionRef &Sec) const {
1108 
1109   auto I = ObjSecToIDMap.find(Sec);
1110   if (I != ObjSecToIDMap.end())
1111     return RTDyld.Sections[I->second].getLoadAddress();
1112 
1113   return 0;
1114 }
1115 
1116 void RuntimeDyld::MemoryManager::anchor() {}
1117 void JITSymbolResolver::anchor() {}
1118 void LegacyJITSymbolResolver::anchor() {}
1119 
1120 RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
1121                          JITSymbolResolver &Resolver)
1122     : MemMgr(MemMgr), Resolver(Resolver) {
1123   // FIXME: There's a potential issue lurking here if a single instance of
1124   // RuntimeDyld is used to load multiple objects.  The current implementation
1125   // associates a single memory manager with a RuntimeDyld instance.  Even
1126   // though the public class spawns a new 'impl' instance for each load,
1127   // they share a single memory manager.  This can become a problem when page
1128   // permissions are applied.
1129   Dyld = nullptr;
1130   ProcessAllSections = false;
1131   Checker = nullptr;
1132 }
1133 
1134 RuntimeDyld::~RuntimeDyld() {}
1135 
1136 static std::unique_ptr<RuntimeDyldCOFF>
1137 createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1138                       JITSymbolResolver &Resolver, bool ProcessAllSections,
1139                       RuntimeDyldCheckerImpl *Checker) {
1140   std::unique_ptr<RuntimeDyldCOFF> Dyld =
1141     RuntimeDyldCOFF::create(Arch, MM, Resolver);
1142   Dyld->setProcessAllSections(ProcessAllSections);
1143   Dyld->setRuntimeDyldChecker(Checker);
1144   return Dyld;
1145 }
1146 
1147 static std::unique_ptr<RuntimeDyldELF>
1148 createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1149                      JITSymbolResolver &Resolver, bool ProcessAllSections,
1150                      RuntimeDyldCheckerImpl *Checker) {
1151   std::unique_ptr<RuntimeDyldELF> Dyld =
1152       RuntimeDyldELF::create(Arch, MM, Resolver);
1153   Dyld->setProcessAllSections(ProcessAllSections);
1154   Dyld->setRuntimeDyldChecker(Checker);
1155   return Dyld;
1156 }
1157 
1158 static std::unique_ptr<RuntimeDyldMachO>
1159 createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1160                        JITSymbolResolver &Resolver,
1161                        bool ProcessAllSections,
1162                        RuntimeDyldCheckerImpl *Checker) {
1163   std::unique_ptr<RuntimeDyldMachO> Dyld =
1164     RuntimeDyldMachO::create(Arch, MM, Resolver);
1165   Dyld->setProcessAllSections(ProcessAllSections);
1166   Dyld->setRuntimeDyldChecker(Checker);
1167   return Dyld;
1168 }
1169 
1170 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
1171 RuntimeDyld::loadObject(const ObjectFile &Obj) {
1172   if (!Dyld) {
1173     if (Obj.isELF())
1174       Dyld =
1175           createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
1176                                MemMgr, Resolver, ProcessAllSections, Checker);
1177     else if (Obj.isMachO())
1178       Dyld = createRuntimeDyldMachO(
1179                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
1180                ProcessAllSections, Checker);
1181     else if (Obj.isCOFF())
1182       Dyld = createRuntimeDyldCOFF(
1183                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
1184                ProcessAllSections, Checker);
1185     else
1186       report_fatal_error("Incompatible object format!");
1187   }
1188 
1189   if (!Dyld->isCompatibleFile(Obj))
1190     report_fatal_error("Incompatible object format!");
1191 
1192   auto LoadedObjInfo = Dyld->loadObject(Obj);
1193   MemMgr.notifyObjectLoaded(*this, Obj);
1194   return LoadedObjInfo;
1195 }
1196 
1197 void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
1198   if (!Dyld)
1199     return nullptr;
1200   return Dyld->getSymbolLocalAddress(Name);
1201 }
1202 
1203 JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
1204   if (!Dyld)
1205     return nullptr;
1206   return Dyld->getSymbol(Name);
1207 }
1208 
1209 std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
1210   if (!Dyld)
1211     return std::map<StringRef, JITEvaluatedSymbol>();
1212   return Dyld->getSymbolTable();
1213 }
1214 
1215 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
1216 
1217 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
1218   Dyld->reassignSectionAddress(SectionID, Addr);
1219 }
1220 
1221 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
1222                                     uint64_t TargetAddress) {
1223   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
1224 }
1225 
1226 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
1227 
1228 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
1229 
1230 void RuntimeDyld::finalizeWithMemoryManagerLocking() {
1231   bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
1232   MemMgr.FinalizationLocked = true;
1233   resolveRelocations();
1234   registerEHFrames();
1235   if (!MemoryFinalizationLocked) {
1236     MemMgr.finalizeMemory();
1237     MemMgr.FinalizationLocked = false;
1238   }
1239 }
1240 
1241 void RuntimeDyld::registerEHFrames() {
1242   if (Dyld)
1243     Dyld->registerEHFrames();
1244 }
1245 
1246 void RuntimeDyld::deregisterEHFrames() {
1247   if (Dyld)
1248     Dyld->deregisterEHFrames();
1249 }
1250 
1251 } // end namespace llvm
1252