1 //===- llvm-jitlink.cpp -- Command line interface/tester for llvm-jitlink -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility provides a simple command line interface to the llvm jitlink
10 // library, which makes relocatable object files executable in memory. Its
11 // primary function is as a testing utility for the jitlink library.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm-jitlink.h"
16 
17 #include "llvm/BinaryFormat/Magic.h"
18 #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
19 #include "llvm/ExecutionEngine/Orc/DebuggerSupportPlugin.h"
20 #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h"
21 #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h"
22 #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
23 #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
24 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
25 #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
26 #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
27 #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
28 #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
29 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
33 #include "llvm/MC/MCInstPrinter.h"
34 #include "llvm/MC/MCInstrAnalysis.h"
35 #include "llvm/MC/MCInstrInfo.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCTargetOptions.h"
39 #include "llvm/MC/TargetRegistry.h"
40 #include "llvm/Object/COFF.h"
41 #include "llvm/Object/MachO.h"
42 #include "llvm/Object/ObjectFile.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/Timer.h"
51 
52 #include <cstring>
53 #include <list>
54 #include <string>
55 
56 #ifdef LLVM_ON_UNIX
57 #include <netdb.h>
58 #include <netinet/in.h>
59 #include <sys/socket.h>
60 #include <unistd.h>
61 #endif // LLVM_ON_UNIX
62 
63 #define DEBUG_TYPE "llvm_jitlink"
64 
65 using namespace llvm;
66 using namespace llvm::jitlink;
67 using namespace llvm::orc;
68 
69 static cl::OptionCategory JITLinkCategory("JITLink Options");
70 
71 static cl::list<std::string> InputFiles(cl::Positional, cl::OneOrMore,
72                                         cl::desc("input files"),
73                                         cl::cat(JITLinkCategory));
74 
75 static cl::list<std::string>
76     LibrarySearchPaths("L",
77                        cl::desc("Add dir to the list of library search paths"),
78                        cl::Prefix, cl::cat(JITLinkCategory));
79 
80 static cl::list<std::string>
81     Libraries("l",
82               cl::desc("Link against library X in the library search paths"),
83               cl::Prefix, cl::cat(JITLinkCategory));
84 
85 static cl::list<std::string>
86     LibrariesHidden("hidden-l",
87                     cl::desc("Link against library X in the library search "
88                              "paths with hidden visibility"),
89                     cl::Prefix, cl::cat(JITLinkCategory));
90 
91 static cl::list<std::string>
92     LoadHidden("load_hidden",
93                cl::desc("Link against library X with hidden visibility"),
94                cl::cat(JITLinkCategory));
95 
96 static cl::opt<bool> NoExec("noexec", cl::desc("Do not execute loaded code"),
97                             cl::init(false), cl::cat(JITLinkCategory));
98 
99 static cl::list<std::string>
100     CheckFiles("check", cl::desc("File containing verifier checks"),
101                cl::ZeroOrMore, cl::cat(JITLinkCategory));
102 
103 static cl::opt<std::string>
104     CheckName("check-name", cl::desc("Name of checks to match against"),
105               cl::init("jitlink-check"), cl::cat(JITLinkCategory));
106 
107 static cl::opt<std::string>
108     EntryPointName("entry", cl::desc("Symbol to call as main entry point"),
109                    cl::init(""), cl::cat(JITLinkCategory));
110 
111 static cl::list<std::string> JITDylibs(
112     "jd",
113     cl::desc("Specifies the JITDylib to be used for any subsequent "
114              "input file, -L<seacrh-path>, and -l<library> arguments"),
115     cl::cat(JITLinkCategory));
116 
117 static cl::list<std::string>
118     Dylibs("preload",
119            cl::desc("Pre-load dynamic libraries (e.g. language runtimes "
120                     "required by the ORC runtime)"),
121            cl::ZeroOrMore, cl::cat(JITLinkCategory));
122 
123 static cl::list<std::string> InputArgv("args", cl::Positional,
124                                        cl::desc("<program arguments>..."),
125                                        cl::ZeroOrMore, cl::PositionalEatsArgs,
126                                        cl::cat(JITLinkCategory));
127 
128 static cl::opt<bool>
129     DebuggerSupport("debugger-support",
130                     cl::desc("Enable debugger suppport (default = !-noexec)"),
131                     cl::init(true), cl::Hidden, cl::cat(JITLinkCategory));
132 
133 static cl::opt<bool>
134     NoProcessSymbols("no-process-syms",
135                      cl::desc("Do not resolve to llvm-jitlink process symbols"),
136                      cl::init(false), cl::cat(JITLinkCategory));
137 
138 static cl::list<std::string> AbsoluteDefs(
139     "define-abs",
140     cl::desc("Inject absolute symbol definitions (syntax: <name>=<addr>)"),
141     cl::ZeroOrMore, cl::cat(JITLinkCategory));
142 
143 static cl::list<std::string> TestHarnesses("harness", cl::Positional,
144                                            cl::desc("Test harness files"),
145                                            cl::ZeroOrMore,
146                                            cl::PositionalEatsArgs,
147                                            cl::cat(JITLinkCategory));
148 
149 static cl::opt<bool> ShowInitialExecutionSessionState(
150     "show-init-es",
151     cl::desc("Print ExecutionSession state before resolving entry point"),
152     cl::init(false), cl::cat(JITLinkCategory));
153 
154 static cl::opt<bool> ShowEntryExecutionSessionState(
155     "show-entry-es",
156     cl::desc("Print ExecutionSession state after resolving entry point"),
157     cl::init(false), cl::cat(JITLinkCategory));
158 
159 static cl::opt<bool> ShowAddrs(
160     "show-addrs",
161     cl::desc("Print registered symbol, section, got and stub addresses"),
162     cl::init(false), cl::cat(JITLinkCategory));
163 
164 static cl::opt<bool> ShowLinkGraph(
165     "show-graph",
166     cl::desc("Print the link graph after fixups have been applied"),
167     cl::init(false), cl::cat(JITLinkCategory));
168 
169 static cl::opt<bool> ShowSizes(
170     "show-sizes",
171     cl::desc("Show sizes pre- and post-dead stripping, and allocations"),
172     cl::init(false), cl::cat(JITLinkCategory));
173 
174 static cl::opt<bool> ShowTimes("show-times",
175                                cl::desc("Show times for llvm-jitlink phases"),
176                                cl::init(false), cl::cat(JITLinkCategory));
177 
178 static cl::opt<std::string> SlabAllocateSizeString(
179     "slab-allocate",
180     cl::desc("Allocate from a slab of the given size "
181              "(allowable suffixes: Kb, Mb, Gb. default = "
182              "Kb)"),
183     cl::init(""), cl::cat(JITLinkCategory));
184 
185 static cl::opt<uint64_t> SlabAddress(
186     "slab-address",
187     cl::desc("Set slab target address (requires -slab-allocate and -noexec)"),
188     cl::init(~0ULL), cl::cat(JITLinkCategory));
189 
190 static cl::opt<uint64_t> SlabPageSize(
191     "slab-page-size",
192     cl::desc("Set page size for slab (requires -slab-allocate and -noexec)"),
193     cl::init(0), cl::cat(JITLinkCategory));
194 
195 static cl::opt<bool> ShowRelocatedSectionContents(
196     "show-relocated-section-contents",
197     cl::desc("show section contents after fixups have been applied"),
198     cl::init(false), cl::cat(JITLinkCategory));
199 
200 static cl::opt<bool> PhonyExternals(
201     "phony-externals",
202     cl::desc("resolve all otherwise unresolved externals to null"),
203     cl::init(false), cl::cat(JITLinkCategory));
204 
205 static cl::opt<std::string> OutOfProcessExecutor(
206     "oop-executor", cl::desc("Launch an out-of-process executor to run code"),
207     cl::ValueOptional, cl::cat(JITLinkCategory));
208 
209 static cl::opt<std::string> OutOfProcessExecutorConnect(
210     "oop-executor-connect",
211     cl::desc("Connect to an out-of-process executor via TCP"),
212     cl::cat(JITLinkCategory));
213 
214 static cl::opt<std::string>
215     OrcRuntime("orc-runtime", cl::desc("Use ORC runtime from given path"),
216                cl::init(""), cl::cat(JITLinkCategory));
217 
218 static cl::opt<bool> AddSelfRelocations(
219     "add-self-relocations",
220     cl::desc("Add relocations to function pointers to the current function"),
221     cl::init(false), cl::cat(JITLinkCategory));
222 
223 ExitOnError ExitOnErr;
224 
225 LLVM_ATTRIBUTE_USED void linkComponents() {
226   errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
227          << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
228          << (void *)&llvm_orc_registerJITLoaderGDBWrapper;
229 }
230 
231 static bool UseTestResultOverride = false;
232 static int64_t TestResultOverride = 0;
233 
234 extern "C" LLVM_ATTRIBUTE_USED void
235 llvm_jitlink_setTestResultOverride(int64_t Value) {
236   TestResultOverride = Value;
237   UseTestResultOverride = true;
238 }
239 
240 static Error addSelfRelocations(LinkGraph &G);
241 
242 namespace llvm {
243 
244 static raw_ostream &
245 operator<<(raw_ostream &OS, const Session::MemoryRegionInfo &MRI) {
246   return OS << "target addr = "
247             << format("0x%016" PRIx64, MRI.getTargetAddress())
248             << ", content: " << (const void *)MRI.getContent().data() << " -- "
249             << (const void *)(MRI.getContent().data() + MRI.getContent().size())
250             << " (" << MRI.getContent().size() << " bytes)";
251 }
252 
253 static raw_ostream &
254 operator<<(raw_ostream &OS, const Session::SymbolInfoMap &SIM) {
255   OS << "Symbols:\n";
256   for (auto &SKV : SIM)
257     OS << "  \"" << SKV.first() << "\" " << SKV.second << "\n";
258   return OS;
259 }
260 
261 static raw_ostream &
262 operator<<(raw_ostream &OS, const Session::FileInfo &FI) {
263   for (auto &SIKV : FI.SectionInfos)
264     OS << "  Section \"" << SIKV.first() << "\": " << SIKV.second << "\n";
265   for (auto &GOTKV : FI.GOTEntryInfos)
266     OS << "  GOT \"" << GOTKV.first() << "\": " << GOTKV.second << "\n";
267   for (auto &StubKV : FI.StubInfos)
268     OS << "  Stub \"" << StubKV.first() << "\": " << StubKV.second << "\n";
269   return OS;
270 }
271 
272 static raw_ostream &
273 operator<<(raw_ostream &OS, const Session::FileInfoMap &FIM) {
274   for (auto &FIKV : FIM)
275     OS << "File \"" << FIKV.first() << "\":\n" << FIKV.second;
276   return OS;
277 }
278 
279 static Error applyHarnessPromotions(Session &S, LinkGraph &G) {
280 
281   // If this graph is part of the test harness there's nothing to do.
282   if (S.HarnessFiles.empty() || S.HarnessFiles.count(G.getName()))
283     return Error::success();
284 
285   LLVM_DEBUG(dbgs() << "Applying promotions to graph " << G.getName() << "\n");
286 
287   // If this graph is part of the test then promote any symbols referenced by
288   // the harness to default scope, remove all symbols that clash with harness
289   // definitions.
290   std::vector<Symbol *> DefinitionsToRemove;
291   for (auto *Sym : G.defined_symbols()) {
292 
293     if (!Sym->hasName())
294       continue;
295 
296     if (Sym->getLinkage() == Linkage::Weak) {
297       if (!S.CanonicalWeakDefs.count(Sym->getName()) ||
298           S.CanonicalWeakDefs[Sym->getName()] != G.getName()) {
299         LLVM_DEBUG({
300           dbgs() << "  Externalizing weak symbol " << Sym->getName() << "\n";
301         });
302         DefinitionsToRemove.push_back(Sym);
303       } else {
304         LLVM_DEBUG({
305           dbgs() << "  Making weak symbol " << Sym->getName() << " strong\n";
306         });
307         if (S.HarnessExternals.count(Sym->getName()))
308           Sym->setScope(Scope::Default);
309         else
310           Sym->setScope(Scope::Hidden);
311         Sym->setLinkage(Linkage::Strong);
312       }
313     } else if (S.HarnessExternals.count(Sym->getName())) {
314       LLVM_DEBUG(dbgs() << "  Promoting " << Sym->getName() << "\n");
315       Sym->setScope(Scope::Default);
316       Sym->setLive(true);
317       continue;
318     } else if (S.HarnessDefinitions.count(Sym->getName())) {
319       LLVM_DEBUG(dbgs() << "  Externalizing " << Sym->getName() << "\n");
320       DefinitionsToRemove.push_back(Sym);
321     }
322   }
323 
324   for (auto *Sym : DefinitionsToRemove)
325     G.makeExternal(*Sym);
326 
327   return Error::success();
328 }
329 
330 static uint64_t computeTotalBlockSizes(LinkGraph &G) {
331   uint64_t TotalSize = 0;
332   for (auto *B : G.blocks())
333     TotalSize += B->getSize();
334   return TotalSize;
335 }
336 
337 static void dumpSectionContents(raw_ostream &OS, LinkGraph &G) {
338   constexpr orc::ExecutorAddrDiff DumpWidth = 16;
339   static_assert(isPowerOf2_64(DumpWidth), "DumpWidth must be a power of two");
340 
341   // Put sections in address order.
342   std::vector<Section *> Sections;
343   for (auto &S : G.sections())
344     Sections.push_back(&S);
345 
346   llvm::sort(Sections, [](const Section *LHS, const Section *RHS) {
347     if (llvm::empty(LHS->symbols()) && llvm::empty(RHS->symbols()))
348       return false;
349     if (llvm::empty(LHS->symbols()))
350       return false;
351     if (llvm::empty(RHS->symbols()))
352       return true;
353     SectionRange LHSRange(*LHS);
354     SectionRange RHSRange(*RHS);
355     return LHSRange.getStart() < RHSRange.getStart();
356   });
357 
358   for (auto *S : Sections) {
359     OS << S->getName() << " content:";
360     if (llvm::empty(S->symbols())) {
361       OS << "\n  section empty\n";
362       continue;
363     }
364 
365     // Sort symbols into order, then render.
366     std::vector<Symbol *> Syms(S->symbols().begin(), S->symbols().end());
367     llvm::sort(Syms, [](const Symbol *LHS, const Symbol *RHS) {
368       return LHS->getAddress() < RHS->getAddress();
369     });
370 
371     orc::ExecutorAddr NextAddr(Syms.front()->getAddress().getValue() &
372                                ~(DumpWidth - 1));
373     for (auto *Sym : Syms) {
374       bool IsZeroFill = Sym->getBlock().isZeroFill();
375       auto SymStart = Sym->getAddress();
376       auto SymSize = Sym->getSize();
377       auto SymEnd = SymStart + SymSize;
378       const uint8_t *SymData = IsZeroFill ? nullptr
379                                           : reinterpret_cast<const uint8_t *>(
380                                                 Sym->getSymbolContent().data());
381 
382       // Pad any space before the symbol starts.
383       while (NextAddr != SymStart) {
384         if (NextAddr % DumpWidth == 0)
385           OS << formatv("\n{0:x16}:", NextAddr);
386         OS << "   ";
387         ++NextAddr;
388       }
389 
390       // Render the symbol content.
391       while (NextAddr != SymEnd) {
392         if (NextAddr % DumpWidth == 0)
393           OS << formatv("\n{0:x16}:", NextAddr);
394         if (IsZeroFill)
395           OS << " 00";
396         else
397           OS << formatv(" {0:x-2}", SymData[NextAddr - SymStart]);
398         ++NextAddr;
399       }
400     }
401     OS << "\n";
402   }
403 }
404 
405 class JITLinkSlabAllocator final : public JITLinkMemoryManager {
406 private:
407   struct FinalizedAllocInfo {
408     FinalizedAllocInfo(sys::MemoryBlock Mem,
409                        std::vector<shared::WrapperFunctionCall> DeallocActions)
410         : Mem(Mem), DeallocActions(std::move(DeallocActions)) {}
411     sys::MemoryBlock Mem;
412     std::vector<shared::WrapperFunctionCall> DeallocActions;
413   };
414 
415 public:
416   static Expected<std::unique_ptr<JITLinkSlabAllocator>>
417   Create(uint64_t SlabSize) {
418     Error Err = Error::success();
419     std::unique_ptr<JITLinkSlabAllocator> Allocator(
420         new JITLinkSlabAllocator(SlabSize, Err));
421     if (Err)
422       return std::move(Err);
423     return std::move(Allocator);
424   }
425 
426   void allocate(const JITLinkDylib *JD, LinkGraph &G,
427                 OnAllocatedFunction OnAllocated) override {
428 
429     // Local class for allocation.
430     class IPMMAlloc : public InFlightAlloc {
431     public:
432       IPMMAlloc(JITLinkSlabAllocator &Parent, BasicLayout BL,
433                 sys::MemoryBlock StandardSegs, sys::MemoryBlock FinalizeSegs)
434           : Parent(Parent), BL(std::move(BL)),
435             StandardSegs(std::move(StandardSegs)),
436             FinalizeSegs(std::move(FinalizeSegs)) {}
437 
438       void finalize(OnFinalizedFunction OnFinalized) override {
439         if (auto Err = applyProtections()) {
440           OnFinalized(std::move(Err));
441           return;
442         }
443 
444         auto DeallocActions = runFinalizeActions(BL.graphAllocActions());
445         if (!DeallocActions) {
446           OnFinalized(DeallocActions.takeError());
447           return;
448         }
449 
450         if (auto Err = Parent.freeBlock(FinalizeSegs)) {
451           OnFinalized(
452               joinErrors(std::move(Err), runDeallocActions(*DeallocActions)));
453           return;
454         }
455 
456         OnFinalized(FinalizedAlloc(ExecutorAddr::fromPtr(
457             new FinalizedAllocInfo(StandardSegs, std::move(*DeallocActions)))));
458       }
459 
460       void abandon(OnAbandonedFunction OnAbandoned) override {
461         OnAbandoned(joinErrors(Parent.freeBlock(StandardSegs),
462                                Parent.freeBlock(FinalizeSegs)));
463       }
464 
465     private:
466       Error applyProtections() {
467         for (auto &KV : BL.segments()) {
468           const auto &Group = KV.first;
469           auto &Seg = KV.second;
470 
471           auto Prot = toSysMemoryProtectionFlags(Group.getMemProt());
472 
473           uint64_t SegSize =
474               alignTo(Seg.ContentSize + Seg.ZeroFillSize, Parent.PageSize);
475           sys::MemoryBlock MB(Seg.WorkingMem, SegSize);
476           if (auto EC = sys::Memory::protectMappedMemory(MB, Prot))
477             return errorCodeToError(EC);
478           if (Prot & sys::Memory::MF_EXEC)
479             sys::Memory::InvalidateInstructionCache(MB.base(),
480                                                     MB.allocatedSize());
481         }
482         return Error::success();
483       }
484 
485       JITLinkSlabAllocator &Parent;
486       BasicLayout BL;
487       sys::MemoryBlock StandardSegs;
488       sys::MemoryBlock FinalizeSegs;
489     };
490 
491     BasicLayout BL(G);
492     auto SegsSizes = BL.getContiguousPageBasedLayoutSizes(PageSize);
493 
494     if (!SegsSizes) {
495       OnAllocated(SegsSizes.takeError());
496       return;
497     }
498 
499     char *AllocBase = nullptr;
500     {
501       std::lock_guard<std::mutex> Lock(SlabMutex);
502 
503       if (SegsSizes->total() > SlabRemaining.allocatedSize()) {
504         OnAllocated(make_error<StringError>(
505             "Slab allocator out of memory: request for " +
506                 formatv("{0:x}", SegsSizes->total()) +
507                 " bytes exceeds remaining capacity of " +
508                 formatv("{0:x}", SlabRemaining.allocatedSize()) + " bytes",
509             inconvertibleErrorCode()));
510         return;
511       }
512 
513       AllocBase = reinterpret_cast<char *>(SlabRemaining.base());
514       SlabRemaining =
515           sys::MemoryBlock(AllocBase + SegsSizes->total(),
516                            SlabRemaining.allocatedSize() - SegsSizes->total());
517     }
518 
519     sys::MemoryBlock StandardSegs(AllocBase, SegsSizes->StandardSegs);
520     sys::MemoryBlock FinalizeSegs(AllocBase + SegsSizes->StandardSegs,
521                                   SegsSizes->FinalizeSegs);
522 
523     auto NextStandardSegAddr = ExecutorAddr::fromPtr(StandardSegs.base());
524     auto NextFinalizeSegAddr = ExecutorAddr::fromPtr(FinalizeSegs.base());
525 
526     LLVM_DEBUG({
527       dbgs() << "JITLinkSlabAllocator allocated:\n";
528       if (SegsSizes->StandardSegs)
529         dbgs() << formatv("  [ {0:x16} -- {1:x16} ]", NextStandardSegAddr,
530                           NextStandardSegAddr + StandardSegs.allocatedSize())
531                << " to stardard segs\n";
532       else
533         dbgs() << "  no standard segs\n";
534       if (SegsSizes->FinalizeSegs)
535         dbgs() << formatv("  [ {0:x16} -- {1:x16} ]", NextFinalizeSegAddr,
536                           NextFinalizeSegAddr + FinalizeSegs.allocatedSize())
537                << " to finalize segs\n";
538       else
539         dbgs() << "  no finalize segs\n";
540     });
541 
542     for (auto &KV : BL.segments()) {
543       auto &Group = KV.first;
544       auto &Seg = KV.second;
545 
546       auto &SegAddr =
547           (Group.getMemDeallocPolicy() == MemDeallocPolicy::Standard)
548               ? NextStandardSegAddr
549               : NextFinalizeSegAddr;
550 
551       LLVM_DEBUG({
552         dbgs() << "  " << Group << " -> " << formatv("{0:x16}", SegAddr)
553                << "\n";
554       });
555       Seg.WorkingMem = SegAddr.toPtr<char *>();
556       Seg.Addr = SegAddr + NextSlabDelta;
557 
558       SegAddr += alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
559 
560       // Zero out the zero-fill memory.
561       if (Seg.ZeroFillSize != 0)
562         memset(Seg.WorkingMem + Seg.ContentSize, 0, Seg.ZeroFillSize);
563     }
564 
565     NextSlabDelta += SegsSizes->total();
566 
567     if (auto Err = BL.apply()) {
568       OnAllocated(std::move(Err));
569       return;
570     }
571 
572     OnAllocated(std::unique_ptr<InProcessMemoryManager::InFlightAlloc>(
573         new IPMMAlloc(*this, std::move(BL), std::move(StandardSegs),
574                       std::move(FinalizeSegs))));
575   }
576 
577   void deallocate(std::vector<FinalizedAlloc> FinalizedAllocs,
578                   OnDeallocatedFunction OnDeallocated) override {
579     Error Err = Error::success();
580     for (auto &FA : FinalizedAllocs) {
581       std::unique_ptr<FinalizedAllocInfo> FAI(
582           FA.release().toPtr<FinalizedAllocInfo *>());
583 
584       // FIXME: Run dealloc actions.
585 
586       Err = joinErrors(std::move(Err), freeBlock(FAI->Mem));
587     }
588     OnDeallocated(std::move(Err));
589   }
590 
591 private:
592   JITLinkSlabAllocator(uint64_t SlabSize, Error &Err) {
593     ErrorAsOutParameter _(&Err);
594 
595     if (!SlabPageSize) {
596       if (auto PageSizeOrErr = sys::Process::getPageSize())
597         PageSize = *PageSizeOrErr;
598       else {
599         Err = PageSizeOrErr.takeError();
600         return;
601       }
602 
603       if (PageSize == 0) {
604         Err = make_error<StringError>("Page size is zero",
605                                       inconvertibleErrorCode());
606         return;
607       }
608     } else
609       PageSize = SlabPageSize;
610 
611     if (!isPowerOf2_64(PageSize)) {
612       Err = make_error<StringError>("Page size is not a power of 2",
613                                     inconvertibleErrorCode());
614       return;
615     }
616 
617     // Round slab request up to page size.
618     SlabSize = (SlabSize + PageSize - 1) & ~(PageSize - 1);
619 
620     const sys::Memory::ProtectionFlags ReadWrite =
621         static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
622                                                   sys::Memory::MF_WRITE);
623 
624     std::error_code EC;
625     SlabRemaining =
626         sys::Memory::allocateMappedMemory(SlabSize, nullptr, ReadWrite, EC);
627 
628     if (EC) {
629       Err = errorCodeToError(EC);
630       return;
631     }
632 
633     // Calculate the target address delta to link as-if slab were at
634     // SlabAddress.
635     if (SlabAddress != ~0ULL)
636       NextSlabDelta = ExecutorAddr(SlabAddress) -
637                       ExecutorAddr::fromPtr(SlabRemaining.base());
638   }
639 
640   Error freeBlock(sys::MemoryBlock MB) {
641     // FIXME: Return memory to slab.
642     return Error::success();
643   }
644 
645   std::mutex SlabMutex;
646   sys::MemoryBlock SlabRemaining;
647   uint64_t PageSize = 0;
648   int64_t NextSlabDelta = 0;
649 };
650 
651 Expected<uint64_t> getSlabAllocSize(StringRef SizeString) {
652   SizeString = SizeString.trim();
653 
654   uint64_t Units = 1024;
655 
656   if (SizeString.endswith_insensitive("kb"))
657     SizeString = SizeString.drop_back(2).rtrim();
658   else if (SizeString.endswith_insensitive("mb")) {
659     Units = 1024 * 1024;
660     SizeString = SizeString.drop_back(2).rtrim();
661   } else if (SizeString.endswith_insensitive("gb")) {
662     Units = 1024 * 1024 * 1024;
663     SizeString = SizeString.drop_back(2).rtrim();
664   }
665 
666   uint64_t SlabSize = 0;
667   if (SizeString.getAsInteger(10, SlabSize))
668     return make_error<StringError>("Invalid numeric format for slab size",
669                                    inconvertibleErrorCode());
670 
671   return SlabSize * Units;
672 }
673 
674 static std::unique_ptr<JITLinkMemoryManager> createMemoryManager() {
675   if (!SlabAllocateSizeString.empty()) {
676     auto SlabSize = ExitOnErr(getSlabAllocSize(SlabAllocateSizeString));
677     return ExitOnErr(JITLinkSlabAllocator::Create(SlabSize));
678   }
679   return ExitOnErr(InProcessMemoryManager::Create());
680 }
681 
682 static Expected<MaterializationUnit::Interface>
683 getTestObjectFileInterface(Session &S, MemoryBufferRef O) {
684 
685   // Get the standard interface for this object, but ignore the symbols field.
686   // We'll handle that manually to include promotion.
687   auto I = getObjectFileInterface(S.ES, O);
688   if (!I)
689     return I.takeError();
690   I->SymbolFlags.clear();
691 
692   // If creating an object file was going to fail it would have happened above,
693   // so we can 'cantFail' this.
694   auto Obj = cantFail(object::ObjectFile::createObjectFile(O));
695 
696   // The init symbol must be included in the SymbolFlags map if present.
697   if (I->InitSymbol)
698     I->SymbolFlags[I->InitSymbol] =
699         JITSymbolFlags::MaterializationSideEffectsOnly;
700 
701   for (auto &Sym : Obj->symbols()) {
702     Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
703     if (!SymFlagsOrErr)
704       // TODO: Test this error.
705       return SymFlagsOrErr.takeError();
706 
707     // Skip symbols not defined in this object file.
708     if ((*SymFlagsOrErr & object::BasicSymbolRef::SF_Undefined))
709       continue;
710 
711     auto Name = Sym.getName();
712     if (!Name)
713       return Name.takeError();
714 
715     // Skip symbols that have type SF_File.
716     if (auto SymType = Sym.getType()) {
717       if (*SymType == object::SymbolRef::ST_File)
718         continue;
719     } else
720       return SymType.takeError();
721 
722     auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
723     if (!SymFlags)
724       return SymFlags.takeError();
725 
726     if (SymFlags->isWeak()) {
727       // If this is a weak symbol that's not defined in the harness then we
728       // need to either mark it as strong (if this is the first definition
729       // that we've seen) or discard it.
730       if (S.HarnessDefinitions.count(*Name) || S.CanonicalWeakDefs.count(*Name))
731         continue;
732       S.CanonicalWeakDefs[*Name] = O.getBufferIdentifier();
733       *SymFlags &= ~JITSymbolFlags::Weak;
734       if (!S.HarnessExternals.count(*Name))
735         *SymFlags &= ~JITSymbolFlags::Exported;
736     } else if (S.HarnessExternals.count(*Name)) {
737       *SymFlags |= JITSymbolFlags::Exported;
738     } else if (S.HarnessDefinitions.count(*Name) ||
739                !(*SymFlagsOrErr & object::BasicSymbolRef::SF_Global))
740       continue;
741 
742     auto InternedName = S.ES.intern(*Name);
743     I->SymbolFlags[InternedName] = std::move(*SymFlags);
744   }
745 
746   return I;
747 }
748 
749 static Error loadProcessSymbols(Session &S) {
750   auto FilterMainEntryPoint =
751       [EPName = S.ES.intern(EntryPointName)](SymbolStringPtr Name) {
752         return Name != EPName;
753       };
754   S.MainJD->addGenerator(
755       ExitOnErr(orc::EPCDynamicLibrarySearchGenerator::GetForTargetProcess(
756           S.ES, std::move(FilterMainEntryPoint))));
757 
758   return Error::success();
759 }
760 
761 static Error loadDylibs(Session &S) {
762   LLVM_DEBUG(dbgs() << "Loading dylibs...\n");
763   for (const auto &Dylib : Dylibs) {
764     LLVM_DEBUG(dbgs() << "  " << Dylib << "\n");
765     auto G = orc::EPCDynamicLibrarySearchGenerator::Load(S.ES, Dylib.c_str());
766     if (!G)
767       return G.takeError();
768     S.MainJD->addGenerator(std::move(*G));
769   }
770 
771   return Error::success();
772 }
773 
774 static Expected<std::unique_ptr<ExecutorProcessControl>> launchExecutor() {
775 #ifndef LLVM_ON_UNIX
776   // FIXME: Add support for Windows.
777   return make_error<StringError>("-" + OutOfProcessExecutor.ArgStr +
778                                      " not supported on non-unix platforms",
779                                  inconvertibleErrorCode());
780 #elif !LLVM_ENABLE_THREADS
781   // Out of process mode using SimpleRemoteEPC depends on threads.
782   return make_error<StringError>(
783       "-" + OutOfProcessExecutor.ArgStr +
784           " requires threads, but LLVM was built with "
785           "LLVM_ENABLE_THREADS=Off",
786       inconvertibleErrorCode());
787 #else
788 
789   constexpr int ReadEnd = 0;
790   constexpr int WriteEnd = 1;
791 
792   // Pipe FDs.
793   int ToExecutor[2];
794   int FromExecutor[2];
795 
796   pid_t ChildPID;
797 
798   // Create pipes to/from the executor..
799   if (pipe(ToExecutor) != 0 || pipe(FromExecutor) != 0)
800     return make_error<StringError>("Unable to create pipe for executor",
801                                    inconvertibleErrorCode());
802 
803   ChildPID = fork();
804 
805   if (ChildPID == 0) {
806     // In the child...
807 
808     // Close the parent ends of the pipes
809     close(ToExecutor[WriteEnd]);
810     close(FromExecutor[ReadEnd]);
811 
812     // Execute the child process.
813     std::unique_ptr<char[]> ExecutorPath, FDSpecifier;
814     {
815       ExecutorPath = std::make_unique<char[]>(OutOfProcessExecutor.size() + 1);
816       strcpy(ExecutorPath.get(), OutOfProcessExecutor.data());
817 
818       std::string FDSpecifierStr("filedescs=");
819       FDSpecifierStr += utostr(ToExecutor[ReadEnd]);
820       FDSpecifierStr += ',';
821       FDSpecifierStr += utostr(FromExecutor[WriteEnd]);
822       FDSpecifier = std::make_unique<char[]>(FDSpecifierStr.size() + 1);
823       strcpy(FDSpecifier.get(), FDSpecifierStr.c_str());
824     }
825 
826     char *const Args[] = {ExecutorPath.get(), FDSpecifier.get(), nullptr};
827     int RC = execvp(ExecutorPath.get(), Args);
828     if (RC != 0) {
829       errs() << "unable to launch out-of-process executor \""
830              << ExecutorPath.get() << "\"\n";
831       exit(1);
832     }
833   }
834   // else we're the parent...
835 
836   // Close the child ends of the pipes
837   close(ToExecutor[ReadEnd]);
838   close(FromExecutor[WriteEnd]);
839 
840   return SimpleRemoteEPC::Create<FDSimpleRemoteEPCTransport>(
841       std::make_unique<DynamicThreadPoolTaskDispatcher>(),
842       SimpleRemoteEPC::Setup(), FromExecutor[ReadEnd], ToExecutor[WriteEnd]);
843 #endif
844 }
845 
846 #if LLVM_ON_UNIX && LLVM_ENABLE_THREADS
847 static Error createTCPSocketError(Twine Details) {
848   return make_error<StringError>(
849       formatv("Failed to connect TCP socket '{0}': {1}",
850               OutOfProcessExecutorConnect, Details),
851       inconvertibleErrorCode());
852 }
853 
854 static Expected<int> connectTCPSocket(std::string Host, std::string PortStr) {
855   addrinfo *AI;
856   addrinfo Hints{};
857   Hints.ai_family = AF_INET;
858   Hints.ai_socktype = SOCK_STREAM;
859   Hints.ai_flags = AI_NUMERICSERV;
860 
861   if (int EC = getaddrinfo(Host.c_str(), PortStr.c_str(), &Hints, &AI))
862     return createTCPSocketError("Address resolution failed (" +
863                                 StringRef(gai_strerror(EC)) + ")");
864 
865   // Cycle through the returned addrinfo structures and connect to the first
866   // reachable endpoint.
867   int SockFD;
868   addrinfo *Server;
869   for (Server = AI; Server != nullptr; Server = Server->ai_next) {
870     // socket might fail, e.g. if the address family is not supported. Skip to
871     // the next addrinfo structure in such a case.
872     if ((SockFD = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0)
873       continue;
874 
875     // If connect returns null, we exit the loop with a working socket.
876     if (connect(SockFD, Server->ai_addr, Server->ai_addrlen) == 0)
877       break;
878 
879     close(SockFD);
880   }
881   freeaddrinfo(AI);
882 
883   // If we reached the end of the loop without connecting to a valid endpoint,
884   // dump the last error that was logged in socket() or connect().
885   if (Server == nullptr)
886     return createTCPSocketError(std::strerror(errno));
887 
888   return SockFD;
889 }
890 #endif
891 
892 static Expected<std::unique_ptr<ExecutorProcessControl>> connectToExecutor() {
893 #ifndef LLVM_ON_UNIX
894   // FIXME: Add TCP support for Windows.
895   return make_error<StringError>("-" + OutOfProcessExecutorConnect.ArgStr +
896                                      " not supported on non-unix platforms",
897                                  inconvertibleErrorCode());
898 #elif !LLVM_ENABLE_THREADS
899   // Out of process mode using SimpleRemoteEPC depends on threads.
900   return make_error<StringError>(
901       "-" + OutOfProcessExecutorConnect.ArgStr +
902           " requires threads, but LLVM was built with "
903           "LLVM_ENABLE_THREADS=Off",
904       inconvertibleErrorCode());
905 #else
906 
907   StringRef Host, PortStr;
908   std::tie(Host, PortStr) = StringRef(OutOfProcessExecutorConnect).split(':');
909   if (Host.empty())
910     return createTCPSocketError("Host name for -" +
911                                 OutOfProcessExecutorConnect.ArgStr +
912                                 " can not be empty");
913   if (PortStr.empty())
914     return createTCPSocketError("Port number in -" +
915                                 OutOfProcessExecutorConnect.ArgStr +
916                                 " can not be empty");
917   int Port = 0;
918   if (PortStr.getAsInteger(10, Port))
919     return createTCPSocketError("Port number '" + PortStr +
920                                 "' is not a valid integer");
921 
922   Expected<int> SockFD = connectTCPSocket(Host.str(), PortStr.str());
923   if (!SockFD)
924     return SockFD.takeError();
925 
926   return SimpleRemoteEPC::Create<FDSimpleRemoteEPCTransport>(
927       std::make_unique<DynamicThreadPoolTaskDispatcher>(),
928       SimpleRemoteEPC::Setup(), *SockFD, *SockFD);
929 #endif
930 }
931 
932 class PhonyExternalsGenerator : public DefinitionGenerator {
933 public:
934   Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
935                       JITDylibLookupFlags JDLookupFlags,
936                       const SymbolLookupSet &LookupSet) override {
937     SymbolMap PhonySymbols;
938     for (auto &KV : LookupSet)
939       PhonySymbols[KV.first] = JITEvaluatedSymbol(0, JITSymbolFlags::Exported);
940     return JD.define(absoluteSymbols(std::move(PhonySymbols)));
941   }
942 };
943 
944 Expected<std::unique_ptr<Session>> Session::Create(Triple TT) {
945 
946   std::unique_ptr<ExecutorProcessControl> EPC;
947   if (OutOfProcessExecutor.getNumOccurrences()) {
948     /// If -oop-executor is passed then launch the executor.
949     if (auto REPC = launchExecutor())
950       EPC = std::move(*REPC);
951     else
952       return REPC.takeError();
953   } else if (OutOfProcessExecutorConnect.getNumOccurrences()) {
954     /// If -oop-executor-connect is passed then connect to the executor.
955     if (auto REPC = connectToExecutor())
956       EPC = std::move(*REPC);
957     else
958       return REPC.takeError();
959   } else {
960     /// Otherwise use SelfExecutorProcessControl to target the current process.
961     auto PageSize = sys::Process::getPageSize();
962     if (!PageSize)
963       return PageSize.takeError();
964     EPC = std::make_unique<SelfExecutorProcessControl>(
965         std::make_shared<SymbolStringPool>(),
966         std::make_unique<InPlaceTaskDispatcher>(), std::move(TT), *PageSize,
967         createMemoryManager());
968   }
969 
970   Error Err = Error::success();
971   std::unique_ptr<Session> S(new Session(std::move(EPC), Err));
972   if (Err)
973     return std::move(Err);
974   return std::move(S);
975 }
976 
977 Session::~Session() {
978   if (auto Err = ES.endSession())
979     ES.reportError(std::move(Err));
980 }
981 
982 Session::Session(std::unique_ptr<ExecutorProcessControl> EPC, Error &Err)
983     : ES(std::move(EPC)),
984       ObjLayer(ES, ES.getExecutorProcessControl().getMemMgr()) {
985 
986   /// Local ObjectLinkingLayer::Plugin class to forward modifyPassConfig to the
987   /// Session.
988   class JITLinkSessionPlugin : public ObjectLinkingLayer::Plugin {
989   public:
990     JITLinkSessionPlugin(Session &S) : S(S) {}
991     void modifyPassConfig(MaterializationResponsibility &MR, LinkGraph &G,
992                           PassConfiguration &PassConfig) override {
993       S.modifyPassConfig(G.getTargetTriple(), PassConfig);
994     }
995 
996     Error notifyFailed(MaterializationResponsibility &MR) override {
997       return Error::success();
998     }
999     Error notifyRemovingResources(ResourceKey K) override {
1000       return Error::success();
1001     }
1002     void notifyTransferringResources(ResourceKey DstKey,
1003                                      ResourceKey SrcKey) override {}
1004 
1005   private:
1006     Session &S;
1007   };
1008 
1009   ErrorAsOutParameter _(&Err);
1010 
1011   if (auto MainJDOrErr = ES.createJITDylib("main"))
1012     MainJD = &*MainJDOrErr;
1013   else {
1014     Err = MainJDOrErr.takeError();
1015     return;
1016   }
1017 
1018   if (!NoProcessSymbols)
1019     ExitOnErr(loadProcessSymbols(*this));
1020   ExitOnErr(loadDylibs(*this));
1021 
1022   auto &TT = ES.getExecutorProcessControl().getTargetTriple();
1023 
1024   if (DebuggerSupport && TT.isOSBinFormatMachO())
1025     ObjLayer.addPlugin(ExitOnErr(
1026         GDBJITDebugInfoRegistrationPlugin::Create(this->ES, *MainJD, TT)));
1027 
1028   // Set up the platform.
1029   if (TT.isOSBinFormatMachO() && !OrcRuntime.empty()) {
1030     if (auto P =
1031             MachOPlatform::Create(ES, ObjLayer, *MainJD, OrcRuntime.c_str()))
1032       ES.setPlatform(std::move(*P));
1033     else {
1034       Err = P.takeError();
1035       return;
1036     }
1037   } else if (TT.isOSBinFormatELF() && !OrcRuntime.empty()) {
1038     if (auto P =
1039             ELFNixPlatform::Create(ES, ObjLayer, *MainJD, OrcRuntime.c_str()))
1040       ES.setPlatform(std::move(*P));
1041     else {
1042       Err = P.takeError();
1043       return;
1044     }
1045   } else if (!TT.isOSWindows() && !TT.isOSBinFormatMachO()) {
1046     if (!NoExec)
1047       ObjLayer.addPlugin(std::make_unique<EHFrameRegistrationPlugin>(
1048           ES, ExitOnErr(EPCEHFrameRegistrar::Create(this->ES))));
1049     if (DebuggerSupport)
1050       ObjLayer.addPlugin(std::make_unique<DebugObjectManagerPlugin>(
1051           ES, ExitOnErr(createJITLoaderGDBRegistrar(this->ES))));
1052   }
1053 
1054   ObjLayer.addPlugin(std::make_unique<JITLinkSessionPlugin>(*this));
1055 
1056   // Process any harness files.
1057   for (auto &HarnessFile : TestHarnesses) {
1058     HarnessFiles.insert(HarnessFile);
1059 
1060     auto ObjBuffer =
1061         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(HarnessFile)));
1062 
1063     auto ObjInterface =
1064         ExitOnErr(getObjectFileInterface(ES, ObjBuffer->getMemBufferRef()));
1065 
1066     for (auto &KV : ObjInterface.SymbolFlags)
1067       HarnessDefinitions.insert(*KV.first);
1068 
1069     auto Obj = ExitOnErr(
1070         object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef()));
1071 
1072     for (auto &Sym : Obj->symbols()) {
1073       uint32_t SymFlags = ExitOnErr(Sym.getFlags());
1074       auto Name = ExitOnErr(Sym.getName());
1075 
1076       if (Name.empty())
1077         continue;
1078 
1079       if (SymFlags & object::BasicSymbolRef::SF_Undefined)
1080         HarnessExternals.insert(Name);
1081     }
1082   }
1083 
1084   // If a name is defined by some harness file then it's a definition, not an
1085   // external.
1086   for (auto &DefName : HarnessDefinitions)
1087     HarnessExternals.erase(DefName.getKey());
1088 }
1089 
1090 void Session::dumpSessionInfo(raw_ostream &OS) {
1091   OS << "Registered addresses:\n" << SymbolInfos << FileInfos;
1092 }
1093 
1094 void Session::modifyPassConfig(const Triple &TT,
1095                                PassConfiguration &PassConfig) {
1096   if (!CheckFiles.empty())
1097     PassConfig.PostFixupPasses.push_back([this](LinkGraph &G) {
1098       auto &EPC = ES.getExecutorProcessControl();
1099       if (EPC.getTargetTriple().getObjectFormat() == Triple::ELF)
1100         return registerELFGraphInfo(*this, G);
1101 
1102       if (EPC.getTargetTriple().getObjectFormat() == Triple::MachO)
1103         return registerMachOGraphInfo(*this, G);
1104 
1105       return make_error<StringError>("Unsupported object format for GOT/stub "
1106                                      "registration",
1107                                      inconvertibleErrorCode());
1108     });
1109 
1110   if (ShowLinkGraph)
1111     PassConfig.PostFixupPasses.push_back([](LinkGraph &G) -> Error {
1112       outs() << "Link graph \"" << G.getName() << "\" post-fixup:\n";
1113       G.dump(outs());
1114       return Error::success();
1115     });
1116 
1117   PassConfig.PrePrunePasses.push_back(
1118       [this](LinkGraph &G) { return applyHarnessPromotions(*this, G); });
1119 
1120   if (ShowSizes) {
1121     PassConfig.PrePrunePasses.push_back([this](LinkGraph &G) -> Error {
1122       SizeBeforePruning += computeTotalBlockSizes(G);
1123       return Error::success();
1124     });
1125     PassConfig.PostFixupPasses.push_back([this](LinkGraph &G) -> Error {
1126       SizeAfterFixups += computeTotalBlockSizes(G);
1127       return Error::success();
1128     });
1129   }
1130 
1131   if (ShowRelocatedSectionContents)
1132     PassConfig.PostFixupPasses.push_back([](LinkGraph &G) -> Error {
1133       outs() << "Relocated section contents for " << G.getName() << ":\n";
1134       dumpSectionContents(outs(), G);
1135       return Error::success();
1136     });
1137 
1138   if (AddSelfRelocations)
1139     PassConfig.PostPrunePasses.push_back(addSelfRelocations);
1140 }
1141 
1142 Expected<Session::FileInfo &> Session::findFileInfo(StringRef FileName) {
1143   auto FileInfoItr = FileInfos.find(FileName);
1144   if (FileInfoItr == FileInfos.end())
1145     return make_error<StringError>("file \"" + FileName + "\" not recognized",
1146                                    inconvertibleErrorCode());
1147   return FileInfoItr->second;
1148 }
1149 
1150 Expected<Session::MemoryRegionInfo &>
1151 Session::findSectionInfo(StringRef FileName, StringRef SectionName) {
1152   auto FI = findFileInfo(FileName);
1153   if (!FI)
1154     return FI.takeError();
1155   auto SecInfoItr = FI->SectionInfos.find(SectionName);
1156   if (SecInfoItr == FI->SectionInfos.end())
1157     return make_error<StringError>("no section \"" + SectionName +
1158                                        "\" registered for file \"" + FileName +
1159                                        "\"",
1160                                    inconvertibleErrorCode());
1161   return SecInfoItr->second;
1162 }
1163 
1164 Expected<Session::MemoryRegionInfo &>
1165 Session::findStubInfo(StringRef FileName, StringRef TargetName) {
1166   auto FI = findFileInfo(FileName);
1167   if (!FI)
1168     return FI.takeError();
1169   auto StubInfoItr = FI->StubInfos.find(TargetName);
1170   if (StubInfoItr == FI->StubInfos.end())
1171     return make_error<StringError>("no stub for \"" + TargetName +
1172                                        "\" registered for file \"" + FileName +
1173                                        "\"",
1174                                    inconvertibleErrorCode());
1175   return StubInfoItr->second;
1176 }
1177 
1178 Expected<Session::MemoryRegionInfo &>
1179 Session::findGOTEntryInfo(StringRef FileName, StringRef TargetName) {
1180   auto FI = findFileInfo(FileName);
1181   if (!FI)
1182     return FI.takeError();
1183   auto GOTInfoItr = FI->GOTEntryInfos.find(TargetName);
1184   if (GOTInfoItr == FI->GOTEntryInfos.end())
1185     return make_error<StringError>("no GOT entry for \"" + TargetName +
1186                                        "\" registered for file \"" + FileName +
1187                                        "\"",
1188                                    inconvertibleErrorCode());
1189   return GOTInfoItr->second;
1190 }
1191 
1192 bool Session::isSymbolRegistered(StringRef SymbolName) {
1193   return SymbolInfos.count(SymbolName);
1194 }
1195 
1196 Expected<Session::MemoryRegionInfo &>
1197 Session::findSymbolInfo(StringRef SymbolName, Twine ErrorMsgStem) {
1198   auto SymInfoItr = SymbolInfos.find(SymbolName);
1199   if (SymInfoItr == SymbolInfos.end())
1200     return make_error<StringError>(ErrorMsgStem + ": symbol " + SymbolName +
1201                                        " not found",
1202                                    inconvertibleErrorCode());
1203   return SymInfoItr->second;
1204 }
1205 
1206 } // end namespace llvm
1207 
1208 static Triple getFirstFileTriple() {
1209   static Triple FirstTT = []() {
1210     assert(!InputFiles.empty() && "InputFiles can not be empty");
1211     for (auto InputFile : InputFiles) {
1212       auto ObjBuffer =
1213           ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(InputFile)));
1214       switch (identify_magic(ObjBuffer->getBuffer())) {
1215       case file_magic::elf_relocatable:
1216       case file_magic::macho_object:
1217       case file_magic::coff_object: {
1218         auto Obj = ExitOnErr(
1219             object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef()));
1220         return Obj->makeTriple();
1221       }
1222       default:
1223         break;
1224       }
1225     }
1226     return Triple();
1227   }();
1228 
1229   return FirstTT;
1230 }
1231 
1232 static Error sanitizeArguments(const Triple &TT, const char *ArgV0) {
1233 
1234   // -noexec and --args should not be used together.
1235   if (NoExec && !InputArgv.empty())
1236     errs() << "Warning: --args passed to -noexec run will be ignored.\n";
1237 
1238   // Set the entry point name if not specified.
1239   if (EntryPointName.empty())
1240     EntryPointName = TT.getObjectFormat() == Triple::MachO ? "_main" : "main";
1241 
1242   // Disable debugger support by default in noexec tests.
1243   if (DebuggerSupport.getNumOccurrences() == 0 && NoExec)
1244     DebuggerSupport = false;
1245 
1246   // If -slab-allocate is passed, check that we're not trying to use it in
1247   // -oop-executor or -oop-executor-connect mode.
1248   //
1249   // FIXME: Remove once we enable remote slab allocation.
1250   if (SlabAllocateSizeString != "") {
1251     if (OutOfProcessExecutor.getNumOccurrences() ||
1252         OutOfProcessExecutorConnect.getNumOccurrences())
1253       return make_error<StringError>(
1254           "-slab-allocate cannot be used with -oop-executor or "
1255           "-oop-executor-connect",
1256           inconvertibleErrorCode());
1257   }
1258 
1259   // If -slab-address is passed, require -slab-allocate and -noexec
1260   if (SlabAddress != ~0ULL) {
1261     if (SlabAllocateSizeString == "" || !NoExec)
1262       return make_error<StringError>(
1263           "-slab-address requires -slab-allocate and -noexec",
1264           inconvertibleErrorCode());
1265 
1266     if (SlabPageSize == 0)
1267       errs() << "Warning: -slab-address used without -slab-page-size.\n";
1268   }
1269 
1270   if (SlabPageSize != 0) {
1271     // -slab-page-size requires slab alloc.
1272     if (SlabAllocateSizeString == "")
1273       return make_error<StringError>("-slab-page-size requires -slab-allocate",
1274                                      inconvertibleErrorCode());
1275 
1276     // Check -slab-page-size / -noexec interactions.
1277     if (!NoExec) {
1278       if (auto RealPageSize = sys::Process::getPageSize()) {
1279         if (SlabPageSize % *RealPageSize)
1280           return make_error<StringError>(
1281               "-slab-page-size must be a multiple of real page size for exec "
1282               "tests (did you mean to use -noexec ?)\n",
1283               inconvertibleErrorCode());
1284       } else {
1285         errs() << "Could not retrieve process page size:\n";
1286         logAllUnhandledErrors(RealPageSize.takeError(), errs(), "");
1287         errs() << "Executing with slab page size = "
1288                << formatv("{0:x}", SlabPageSize) << ".\n"
1289                << "Tool may crash if " << formatv("{0:x}", SlabPageSize)
1290                << " is not a multiple of the real process page size.\n"
1291                << "(did you mean to use -noexec ?)";
1292       }
1293     }
1294   }
1295 
1296   // Only one of -oop-executor and -oop-executor-connect can be used.
1297   if (!!OutOfProcessExecutor.getNumOccurrences() &&
1298       !!OutOfProcessExecutorConnect.getNumOccurrences())
1299     return make_error<StringError>(
1300         "Only one of -" + OutOfProcessExecutor.ArgStr + " and -" +
1301             OutOfProcessExecutorConnect.ArgStr + " can be specified",
1302         inconvertibleErrorCode());
1303 
1304   // If -oop-executor was used but no value was specified then use a sensible
1305   // default.
1306   if (!!OutOfProcessExecutor.getNumOccurrences() &&
1307       OutOfProcessExecutor.empty()) {
1308     SmallString<256> OOPExecutorPath(sys::fs::getMainExecutable(
1309         ArgV0, reinterpret_cast<void *>(&sanitizeArguments)));
1310     sys::path::remove_filename(OOPExecutorPath);
1311     sys::path::append(OOPExecutorPath, "llvm-jitlink-executor");
1312     OutOfProcessExecutor = OOPExecutorPath.str().str();
1313   }
1314 
1315   return Error::success();
1316 }
1317 
1318 static void addPhonyExternalsGenerator(Session &S) {
1319   S.MainJD->addGenerator(std::make_unique<PhonyExternalsGenerator>());
1320 }
1321 
1322 static Error createJITDylibs(Session &S,
1323                              std::map<unsigned, JITDylib *> &IdxToJD) {
1324   // First, set up JITDylibs.
1325   LLVM_DEBUG(dbgs() << "Creating JITDylibs...\n");
1326   {
1327     // Create a "main" JITLinkDylib.
1328     IdxToJD[0] = S.MainJD;
1329     S.JDSearchOrder.push_back({S.MainJD, JITDylibLookupFlags::MatchAllSymbols});
1330     LLVM_DEBUG(dbgs() << "  0: " << S.MainJD->getName() << "\n");
1331 
1332     // Add any extra JITDylibs from the command line.
1333     for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end();
1334          JDItr != JDEnd; ++JDItr) {
1335       auto JD = S.ES.createJITDylib(*JDItr);
1336       if (!JD)
1337         return JD.takeError();
1338       unsigned JDIdx = JITDylibs.getPosition(JDItr - JITDylibs.begin());
1339       IdxToJD[JDIdx] = &*JD;
1340       S.JDSearchOrder.push_back({&*JD, JITDylibLookupFlags::MatchAllSymbols});
1341       LLVM_DEBUG(dbgs() << "  " << JDIdx << ": " << JD->getName() << "\n");
1342     }
1343   }
1344 
1345   LLVM_DEBUG({
1346     dbgs() << "Dylib search order is [ ";
1347     for (auto &KV : S.JDSearchOrder)
1348       dbgs() << KV.first->getName() << " ";
1349     dbgs() << "]\n";
1350   });
1351 
1352   return Error::success();
1353 }
1354 
1355 static Error addAbsoluteSymbols(Session &S,
1356                                 const std::map<unsigned, JITDylib *> &IdxToJD) {
1357   // Define absolute symbols.
1358   LLVM_DEBUG(dbgs() << "Defining absolute symbols...\n");
1359   for (auto AbsDefItr = AbsoluteDefs.begin(), AbsDefEnd = AbsoluteDefs.end();
1360        AbsDefItr != AbsDefEnd; ++AbsDefItr) {
1361     unsigned AbsDefArgIdx =
1362       AbsoluteDefs.getPosition(AbsDefItr - AbsoluteDefs.begin());
1363     auto &JD = *std::prev(IdxToJD.lower_bound(AbsDefArgIdx))->second;
1364 
1365     StringRef AbsDefStmt = *AbsDefItr;
1366     size_t EqIdx = AbsDefStmt.find_first_of('=');
1367     if (EqIdx == StringRef::npos)
1368       return make_error<StringError>("Invalid absolute define \"" + AbsDefStmt +
1369                                      "\". Syntax: <name>=<addr>",
1370                                      inconvertibleErrorCode());
1371     StringRef Name = AbsDefStmt.substr(0, EqIdx).trim();
1372     StringRef AddrStr = AbsDefStmt.substr(EqIdx + 1).trim();
1373 
1374     uint64_t Addr;
1375     if (AddrStr.getAsInteger(0, Addr))
1376       return make_error<StringError>("Invalid address expression \"" + AddrStr +
1377                                      "\" in absolute define \"" + AbsDefStmt +
1378                                      "\"",
1379                                      inconvertibleErrorCode());
1380     JITEvaluatedSymbol AbsDef(Addr, JITSymbolFlags::Exported);
1381     if (auto Err = JD.define(absoluteSymbols({{S.ES.intern(Name), AbsDef}})))
1382       return Err;
1383 
1384     // Register the absolute symbol with the session symbol infos.
1385     S.SymbolInfos[Name] = {ArrayRef<char>(), Addr};
1386   }
1387 
1388   return Error::success();
1389 }
1390 
1391 static Error addTestHarnesses(Session &S) {
1392   LLVM_DEBUG(dbgs() << "Adding test harness objects...\n");
1393   for (auto HarnessFile : TestHarnesses) {
1394     LLVM_DEBUG(dbgs() << "  " << HarnessFile << "\n");
1395     auto ObjBuffer = errorOrToExpected(MemoryBuffer::getFile(HarnessFile));
1396     if (!ObjBuffer)
1397       return ObjBuffer.takeError();
1398     if (auto Err = S.ObjLayer.add(*S.MainJD, std::move(*ObjBuffer)))
1399       return Err;
1400   }
1401   return Error::success();
1402 }
1403 
1404 static Error addObjects(Session &S,
1405                         const std::map<unsigned, JITDylib *> &IdxToJD) {
1406 
1407   // Load each object into the corresponding JITDylib..
1408   LLVM_DEBUG(dbgs() << "Adding objects...\n");
1409   for (auto InputFileItr = InputFiles.begin(), InputFileEnd = InputFiles.end();
1410        InputFileItr != InputFileEnd; ++InputFileItr) {
1411     unsigned InputFileArgIdx =
1412         InputFiles.getPosition(InputFileItr - InputFiles.begin());
1413     const std::string &InputFile = *InputFileItr;
1414     if (StringRef(InputFile).endswith(".a"))
1415       continue;
1416     auto &JD = *std::prev(IdxToJD.lower_bound(InputFileArgIdx))->second;
1417     LLVM_DEBUG(dbgs() << "  " << InputFileArgIdx << ": \"" << InputFile
1418                       << "\" to " << JD.getName() << "\n";);
1419     auto ObjBuffer = errorOrToExpected(MemoryBuffer::getFile(InputFile));
1420     if (!ObjBuffer)
1421       return ObjBuffer.takeError();
1422 
1423     if (S.HarnessFiles.empty()) {
1424       if (auto Err = S.ObjLayer.add(JD, std::move(*ObjBuffer)))
1425         return Err;
1426     } else {
1427       // We're in -harness mode. Use a custom interface for this
1428       // test object.
1429       auto ObjInterface =
1430           getTestObjectFileInterface(S, (*ObjBuffer)->getMemBufferRef());
1431       if (!ObjInterface)
1432         return ObjInterface.takeError();
1433       if (auto Err = S.ObjLayer.add(JD, std::move(*ObjBuffer),
1434                                     std::move(*ObjInterface)))
1435         return Err;
1436     }
1437   }
1438 
1439   return Error::success();
1440 }
1441 
1442 static Expected<MaterializationUnit::Interface>
1443 getObjectFileInterfaceHidden(ExecutionSession &ES, MemoryBufferRef ObjBuffer) {
1444   auto I = getObjectFileInterface(ES, ObjBuffer);
1445   if (I) {
1446     for (auto &KV : I->SymbolFlags)
1447       KV.second &= ~JITSymbolFlags::Exported;
1448   }
1449   return I;
1450 }
1451 
1452 static Error addLibraries(Session &S,
1453                           const std::map<unsigned, JITDylib *> &IdxToJD) {
1454 
1455   // 1. Collect search paths for each JITDylib.
1456   DenseMap<const JITDylib *, SmallVector<StringRef, 2>> JDSearchPaths;
1457 
1458   for (auto LSPItr = LibrarySearchPaths.begin(),
1459             LSPEnd = LibrarySearchPaths.end();
1460        LSPItr != LSPEnd; ++LSPItr) {
1461     unsigned LibrarySearchPathIdx =
1462         LibrarySearchPaths.getPosition(LSPItr - LibrarySearchPaths.begin());
1463     auto &JD = *std::prev(IdxToJD.lower_bound(LibrarySearchPathIdx))->second;
1464 
1465     StringRef LibrarySearchPath = *LSPItr;
1466     if (sys::fs::get_file_type(LibrarySearchPath) !=
1467         sys::fs::file_type::directory_file)
1468       return make_error<StringError>("While linking " + JD.getName() + ", -L" +
1469                                          LibrarySearchPath +
1470                                          " does not point to a directory",
1471                                      inconvertibleErrorCode());
1472 
1473     JDSearchPaths[&JD].push_back(*LSPItr);
1474   }
1475 
1476   LLVM_DEBUG({
1477     if (!JDSearchPaths.empty())
1478       dbgs() << "Search paths:\n";
1479     for (auto &KV : JDSearchPaths) {
1480       dbgs() << "  " << KV.first->getName() << ": [";
1481       for (auto &LibSearchPath : KV.second)
1482         dbgs() << " \"" << LibSearchPath << "\"";
1483       dbgs() << " ]\n";
1484     }
1485   });
1486 
1487   // 2. Collect library loads
1488   struct LibraryLoad {
1489     StringRef LibName;
1490     bool IsPath = false;
1491     unsigned Position;
1492     StringRef *CandidateExtensions;
1493     enum { Standard, Hidden } Modifier;
1494   };
1495   std::vector<LibraryLoad> LibraryLoads;
1496   // Add archive files from the inputs to LibraryLoads.
1497   for (auto InputFileItr = InputFiles.begin(), InputFileEnd = InputFiles.end();
1498        InputFileItr != InputFileEnd; ++InputFileItr) {
1499     StringRef InputFile = *InputFileItr;
1500     if (!InputFile.endswith(".a"))
1501       continue;
1502     LibraryLoad LL;
1503     LL.LibName = InputFile;
1504     LL.IsPath = true;
1505     LL.Position = InputFiles.getPosition(InputFileItr - InputFiles.begin());
1506     LL.CandidateExtensions = nullptr;
1507     LL.Modifier = LibraryLoad::Standard;
1508     LibraryLoads.push_back(std::move(LL));
1509   }
1510 
1511   // Add -load_hidden arguments to LibraryLoads.
1512   for (auto LibItr = LoadHidden.begin(), LibEnd = LoadHidden.end();
1513        LibItr != LibEnd; ++LibItr) {
1514     LibraryLoad LL;
1515     LL.LibName = *LibItr;
1516     LL.IsPath = true;
1517     LL.Position = LoadHidden.getPosition(LibItr - LoadHidden.begin());
1518     LL.CandidateExtensions = nullptr;
1519     LL.Modifier = LibraryLoad::Hidden;
1520     LibraryLoads.push_back(std::move(LL));
1521   }
1522   StringRef StandardExtensions[] = {".so", ".dylib", ".a"};
1523   StringRef ArchiveExtensionsOnly[] = {".a"};
1524 
1525   // Add -lx arguments to LibraryLoads.
1526   for (auto LibItr = Libraries.begin(), LibEnd = Libraries.end();
1527        LibItr != LibEnd; ++LibItr) {
1528     LibraryLoad LL;
1529     LL.LibName = *LibItr;
1530     LL.Position = Libraries.getPosition(LibItr - Libraries.begin());
1531     LL.CandidateExtensions = StandardExtensions;
1532     LL.Modifier = LibraryLoad::Standard;
1533     LibraryLoads.push_back(std::move(LL));
1534   }
1535 
1536   // Add -hidden-lx arguments to LibraryLoads.
1537   for (auto LibHiddenItr = LibrariesHidden.begin(),
1538             LibHiddenEnd = LibrariesHidden.end();
1539        LibHiddenItr != LibHiddenEnd; ++LibHiddenItr) {
1540     LibraryLoad LL;
1541     LL.LibName = *LibHiddenItr;
1542     LL.Position =
1543         LibrariesHidden.getPosition(LibHiddenItr - LibrariesHidden.begin());
1544     LL.CandidateExtensions = ArchiveExtensionsOnly;
1545     LL.Modifier = LibraryLoad::Hidden;
1546     LibraryLoads.push_back(std::move(LL));
1547   }
1548 
1549   // If there are any load-<modified> options then turn on flag overrides
1550   // to avoid flag mismatch errors.
1551   if (!LibrariesHidden.empty() || !LoadHidden.empty())
1552     S.ObjLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
1553 
1554   // Sort library loads by position in the argument list.
1555   llvm::sort(LibraryLoads, [](const LibraryLoad &LHS, const LibraryLoad &RHS) {
1556     return LHS.Position < RHS.Position;
1557   });
1558 
1559   // 3. Process library loads.
1560   auto AddArchive = [&](const char *Path, const LibraryLoad &LL)
1561       -> Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>> {
1562     unique_function<Expected<MaterializationUnit::Interface>(
1563         ExecutionSession & ES, MemoryBufferRef ObjBuffer)>
1564         GetObjFileInterface;
1565     switch (LL.Modifier) {
1566     case LibraryLoad::Standard:
1567       GetObjFileInterface = getObjectFileInterface;
1568       break;
1569     case LibraryLoad::Hidden:
1570       GetObjFileInterface = getObjectFileInterfaceHidden;
1571       break;
1572     }
1573     return StaticLibraryDefinitionGenerator::Load(
1574         S.ObjLayer, Path, S.ES.getExecutorProcessControl().getTargetTriple(),
1575         std::move(GetObjFileInterface));
1576   };
1577 
1578   for (auto &LL : LibraryLoads) {
1579     bool LibFound = false;
1580     auto &JD = *std::prev(IdxToJD.lower_bound(LL.Position))->second;
1581 
1582     // If this is the name of a JITDylib then link against that.
1583     if (auto *LJD = S.ES.getJITDylibByName(LL.LibName)) {
1584       JD.addToLinkOrder(*LJD);
1585       continue;
1586     }
1587 
1588     if (LL.IsPath) {
1589       auto G = AddArchive(LL.LibName.str().c_str(), LL);
1590       if (!G)
1591         return createFileError(LL.LibName, G.takeError());
1592       JD.addGenerator(std::move(*G));
1593       LLVM_DEBUG({
1594         dbgs() << "Adding generator for static library " << LL.LibName << " to "
1595                << JD.getName() << "\n";
1596       });
1597       continue;
1598     }
1599 
1600     // Otherwise look through the search paths.
1601     auto JDSearchPathsItr = JDSearchPaths.find(&JD);
1602     if (JDSearchPathsItr != JDSearchPaths.end()) {
1603       for (StringRef SearchPath : JDSearchPathsItr->second) {
1604         for (const char *LibExt : {".dylib", ".so", ".a"}) {
1605           SmallVector<char, 256> LibPath;
1606           LibPath.reserve(SearchPath.size() + strlen("lib") +
1607                           LL.LibName.size() + strlen(LibExt) +
1608                           2); // +2 for pathsep, null term.
1609           llvm::copy(SearchPath, std::back_inserter(LibPath));
1610           sys::path::append(LibPath, "lib" + LL.LibName + LibExt);
1611           LibPath.push_back('\0');
1612 
1613           // Skip missing or non-regular paths.
1614           if (sys::fs::get_file_type(LibPath.data()) !=
1615               sys::fs::file_type::regular_file) {
1616             continue;
1617           }
1618 
1619           file_magic Magic;
1620           if (auto EC = identify_magic(LibPath, Magic)) {
1621             // If there was an error loading the file then skip it.
1622             LLVM_DEBUG({
1623               dbgs() << "Library search found \"" << LibPath
1624                      << "\", but could not identify file type (" << EC.message()
1625                      << "). Skipping.\n";
1626             });
1627             continue;
1628           }
1629 
1630           // We identified the magic. Assume that we can load it -- we'll reset
1631           // in the default case.
1632           LibFound = true;
1633           switch (Magic) {
1634           case file_magic::elf_shared_object:
1635           case file_magic::macho_dynamically_linked_shared_lib: {
1636             // TODO: On first reference to LibPath this should create a JITDylib
1637             // with a generator and add it to JD's links-against list. Subsquent
1638             // references should use the JITDylib created on the first
1639             // reference.
1640             auto G =
1641                 EPCDynamicLibrarySearchGenerator::Load(S.ES, LibPath.data());
1642             if (!G)
1643               return G.takeError();
1644             LLVM_DEBUG({
1645               dbgs() << "Adding generator for dynamic library "
1646                      << LibPath.data() << " to " << JD.getName() << "\n";
1647             });
1648             JD.addGenerator(std::move(*G));
1649             break;
1650           }
1651           case file_magic::archive:
1652           case file_magic::macho_universal_binary: {
1653             auto G = AddArchive(LibPath.data(), LL);
1654             if (!G)
1655               return G.takeError();
1656             JD.addGenerator(std::move(*G));
1657             LLVM_DEBUG({
1658               dbgs() << "Adding generator for static library " << LibPath.data()
1659                      << " to " << JD.getName() << "\n";
1660             });
1661             break;
1662           }
1663           default:
1664             // This file isn't a recognized library kind.
1665             LLVM_DEBUG({
1666               dbgs() << "Library search found \"" << LibPath
1667                      << "\", but file type is not supported. Skipping.\n";
1668             });
1669             LibFound = false;
1670             break;
1671           }
1672           if (LibFound)
1673             break;
1674         }
1675         if (LibFound)
1676           break;
1677       }
1678     }
1679 
1680     if (!LibFound)
1681       return make_error<StringError>("While linking " + JD.getName() +
1682                                          ", could not find library for -l" +
1683                                          LL.LibName,
1684                                      inconvertibleErrorCode());
1685   }
1686 
1687   return Error::success();
1688 }
1689 
1690 static Error addProcessSymbols(Session &S,
1691                                const std::map<unsigned, JITDylib *> &IdxToJD) {
1692 
1693   if (NoProcessSymbols)
1694     return Error::success();
1695 
1696   for (auto &KV : IdxToJD) {
1697     auto &JD = *KV.second;
1698     JD.addGenerator(ExitOnErr(
1699         orc::EPCDynamicLibrarySearchGenerator::GetForTargetProcess(S.ES)));
1700   }
1701 
1702   return Error::success();
1703 }
1704 
1705 static Error addSessionInputs(Session &S) {
1706   std::map<unsigned, JITDylib *> IdxToJD;
1707 
1708   if (auto Err = createJITDylibs(S, IdxToJD))
1709     return Err;
1710 
1711   if (auto Err = addAbsoluteSymbols(S, IdxToJD))
1712     return Err;
1713 
1714   if (!TestHarnesses.empty())
1715     if (auto Err = addTestHarnesses(S))
1716       return Err;
1717 
1718   if (auto Err = addObjects(S, IdxToJD))
1719     return Err;
1720 
1721   if (auto Err = addLibraries(S, IdxToJD))
1722     return Err;
1723 
1724   if (auto Err = addProcessSymbols(S, IdxToJD))
1725     return Err;
1726 
1727   return Error::success();
1728 }
1729 
1730 namespace {
1731 struct TargetInfo {
1732   const Target *TheTarget;
1733   std::unique_ptr<MCSubtargetInfo> STI;
1734   std::unique_ptr<MCRegisterInfo> MRI;
1735   std::unique_ptr<MCAsmInfo> MAI;
1736   std::unique_ptr<MCContext> Ctx;
1737   std::unique_ptr<MCDisassembler> Disassembler;
1738   std::unique_ptr<MCInstrInfo> MII;
1739   std::unique_ptr<MCInstrAnalysis> MIA;
1740   std::unique_ptr<MCInstPrinter> InstPrinter;
1741 };
1742 } // anonymous namespace
1743 
1744 static TargetInfo getTargetInfo(const Triple &TT) {
1745   auto TripleName = TT.str();
1746   std::string ErrorStr;
1747   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, ErrorStr);
1748   if (!TheTarget)
1749     ExitOnErr(make_error<StringError>("Error accessing target '" + TripleName +
1750                                           "': " + ErrorStr,
1751                                       inconvertibleErrorCode()));
1752 
1753   std::unique_ptr<MCSubtargetInfo> STI(
1754       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
1755   if (!STI)
1756     ExitOnErr(
1757         make_error<StringError>("Unable to create subtarget for " + TripleName,
1758                                 inconvertibleErrorCode()));
1759 
1760   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
1761   if (!MRI)
1762     ExitOnErr(make_error<StringError>("Unable to create target register info "
1763                                       "for " +
1764                                           TripleName,
1765                                       inconvertibleErrorCode()));
1766 
1767   MCTargetOptions MCOptions;
1768   std::unique_ptr<MCAsmInfo> MAI(
1769       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
1770   if (!MAI)
1771     ExitOnErr(make_error<StringError>("Unable to create target asm info " +
1772                                           TripleName,
1773                                       inconvertibleErrorCode()));
1774 
1775   auto Ctx = std::make_unique<MCContext>(Triple(TripleName), MAI.get(),
1776                                          MRI.get(), STI.get());
1777 
1778   std::unique_ptr<MCDisassembler> Disassembler(
1779       TheTarget->createMCDisassembler(*STI, *Ctx));
1780   if (!Disassembler)
1781     ExitOnErr(make_error<StringError>("Unable to create disassembler for " +
1782                                           TripleName,
1783                                       inconvertibleErrorCode()));
1784 
1785   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1786   if (!MII)
1787     ExitOnErr(make_error<StringError>("Unable to create instruction info for" +
1788                                           TripleName,
1789                                       inconvertibleErrorCode()));
1790 
1791   std::unique_ptr<MCInstrAnalysis> MIA(
1792       TheTarget->createMCInstrAnalysis(MII.get()));
1793   if (!MIA)
1794     ExitOnErr(make_error<StringError>(
1795         "Unable to create instruction analysis for" + TripleName,
1796         inconvertibleErrorCode()));
1797 
1798   std::unique_ptr<MCInstPrinter> InstPrinter(
1799       TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
1800   if (!InstPrinter)
1801     ExitOnErr(make_error<StringError>(
1802         "Unable to create instruction printer for" + TripleName,
1803         inconvertibleErrorCode()));
1804   return {TheTarget,      std::move(STI), std::move(MRI),
1805           std::move(MAI), std::move(Ctx), std::move(Disassembler),
1806           std::move(MII), std::move(MIA), std::move(InstPrinter)};
1807 }
1808 
1809 static Error runChecks(Session &S) {
1810   const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
1811 
1812   if (CheckFiles.empty())
1813     return Error::success();
1814 
1815   LLVM_DEBUG(dbgs() << "Running checks...\n");
1816 
1817   auto TI = getTargetInfo(TT);
1818 
1819   auto IsSymbolValid = [&S](StringRef Symbol) {
1820     return S.isSymbolRegistered(Symbol);
1821   };
1822 
1823   auto GetSymbolInfo = [&S](StringRef Symbol) {
1824     return S.findSymbolInfo(Symbol, "Can not get symbol info");
1825   };
1826 
1827   auto GetSectionInfo = [&S](StringRef FileName, StringRef SectionName) {
1828     return S.findSectionInfo(FileName, SectionName);
1829   };
1830 
1831   auto GetStubInfo = [&S](StringRef FileName, StringRef SectionName) {
1832     return S.findStubInfo(FileName, SectionName);
1833   };
1834 
1835   auto GetGOTInfo = [&S](StringRef FileName, StringRef SectionName) {
1836     return S.findGOTEntryInfo(FileName, SectionName);
1837   };
1838 
1839   RuntimeDyldChecker Checker(
1840       IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo, GetGOTInfo,
1841       TT.isLittleEndian() ? support::little : support::big,
1842       TI.Disassembler.get(), TI.InstPrinter.get(), dbgs());
1843 
1844   std::string CheckLineStart = "# " + CheckName + ":";
1845   for (auto &CheckFile : CheckFiles) {
1846     auto CheckerFileBuf =
1847         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(CheckFile)));
1848     if (!Checker.checkAllRulesInBuffer(CheckLineStart, &*CheckerFileBuf))
1849       ExitOnErr(make_error<StringError>(
1850           "Some checks in " + CheckFile + " failed", inconvertibleErrorCode()));
1851   }
1852 
1853   return Error::success();
1854 }
1855 
1856 static Error addSelfRelocations(LinkGraph &G) {
1857   auto TI = getTargetInfo(G.getTargetTriple());
1858   for (auto *Sym : G.defined_symbols())
1859     if (Sym->isCallable())
1860       if (auto Err = addFunctionPointerRelocationsToCurrentSymbol(
1861               *Sym, G, *TI.Disassembler, *TI.MIA))
1862         return Err;
1863   return Error::success();
1864 }
1865 
1866 static void dumpSessionStats(Session &S) {
1867   if (!ShowSizes)
1868     return;
1869   if (!OrcRuntime.empty())
1870     outs() << "Note: Session stats include runtime and entry point lookup, but "
1871               "not JITDylib initialization/deinitialization.\n";
1872   if (ShowSizes)
1873     outs() << "  Total size of all blocks before pruning: "
1874            << S.SizeBeforePruning
1875            << "\n  Total size of all blocks after fixups: " << S.SizeAfterFixups
1876            << "\n";
1877 }
1878 
1879 static Expected<JITEvaluatedSymbol> getMainEntryPoint(Session &S) {
1880   return S.ES.lookup(S.JDSearchOrder, S.ES.intern(EntryPointName));
1881 }
1882 
1883 static Expected<JITEvaluatedSymbol> getOrcRuntimeEntryPoint(Session &S) {
1884   std::string RuntimeEntryPoint = "__orc_rt_run_program_wrapper";
1885   const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
1886   if (TT.getObjectFormat() == Triple::MachO)
1887     RuntimeEntryPoint = '_' + RuntimeEntryPoint;
1888   return S.ES.lookup(S.JDSearchOrder, S.ES.intern(RuntimeEntryPoint));
1889 }
1890 
1891 static Expected<int> runWithRuntime(Session &S, ExecutorAddr EntryPointAddr) {
1892   StringRef DemangledEntryPoint = EntryPointName;
1893   const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
1894   if (TT.getObjectFormat() == Triple::MachO &&
1895       DemangledEntryPoint.front() == '_')
1896     DemangledEntryPoint = DemangledEntryPoint.drop_front();
1897   using SPSRunProgramSig =
1898       int64_t(SPSString, SPSString, SPSSequence<SPSString>);
1899   int64_t Result;
1900   if (auto Err = S.ES.callSPSWrapper<SPSRunProgramSig>(
1901           EntryPointAddr, Result, S.MainJD->getName(), DemangledEntryPoint,
1902           static_cast<std::vector<std::string> &>(InputArgv)))
1903     return std::move(Err);
1904   return Result;
1905 }
1906 
1907 static Expected<int> runWithoutRuntime(Session &S,
1908                                        ExecutorAddr EntryPointAddr) {
1909   return S.ES.getExecutorProcessControl().runAsMain(EntryPointAddr, InputArgv);
1910 }
1911 
1912 namespace {
1913 struct JITLinkTimers {
1914   TimerGroup JITLinkTG{"llvm-jitlink timers", "timers for llvm-jitlink phases"};
1915   Timer LoadObjectsTimer{"load", "time to load/add object files", JITLinkTG};
1916   Timer LinkTimer{"link", "time to link object files", JITLinkTG};
1917   Timer RunTimer{"run", "time to execute jitlink'd code", JITLinkTG};
1918 };
1919 } // namespace
1920 
1921 int main(int argc, char *argv[]) {
1922   InitLLVM X(argc, argv);
1923 
1924   InitializeAllTargetInfos();
1925   InitializeAllTargetMCs();
1926   InitializeAllDisassemblers();
1927 
1928   cl::HideUnrelatedOptions({&JITLinkCategory, &getColorCategory()});
1929   cl::ParseCommandLineOptions(argc, argv, "llvm jitlink tool");
1930   ExitOnErr.setBanner(std::string(argv[0]) + ": ");
1931 
1932   /// If timers are enabled, create a JITLinkTimers instance.
1933   std::unique_ptr<JITLinkTimers> Timers =
1934       ShowTimes ? std::make_unique<JITLinkTimers>() : nullptr;
1935 
1936   ExitOnErr(sanitizeArguments(getFirstFileTriple(), argv[0]));
1937 
1938   auto S = ExitOnErr(Session::Create(getFirstFileTriple()));
1939 
1940   {
1941     TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr);
1942     ExitOnErr(addSessionInputs(*S));
1943   }
1944 
1945   if (PhonyExternals)
1946     addPhonyExternalsGenerator(*S);
1947 
1948   if (ShowInitialExecutionSessionState)
1949     S->ES.dump(outs());
1950 
1951   JITEvaluatedSymbol EntryPoint = nullptr;
1952   {
1953     TimeRegion TR(Timers ? &Timers->LinkTimer : nullptr);
1954     // Find the entry-point function unconditionally, since we want to force
1955     // it to be materialized to collect stats.
1956     EntryPoint = ExitOnErr(getMainEntryPoint(*S));
1957     LLVM_DEBUG({
1958       dbgs() << "Using entry point \"" << EntryPointName
1959              << "\": " << formatv("{0:x16}", EntryPoint.getAddress()) << "\n";
1960     });
1961 
1962     // If we're running with the ORC runtime then replace the entry-point
1963     // with the __orc_rt_run_program symbol.
1964     if (!OrcRuntime.empty()) {
1965       EntryPoint = ExitOnErr(getOrcRuntimeEntryPoint(*S));
1966       LLVM_DEBUG({
1967         dbgs() << "(called via __orc_rt_run_program_wrapper at "
1968                << formatv("{0:x16}", EntryPoint.getAddress()) << ")\n";
1969       });
1970     }
1971   }
1972 
1973   if (ShowEntryExecutionSessionState)
1974     S->ES.dump(outs());
1975 
1976   if (ShowAddrs)
1977     S->dumpSessionInfo(outs());
1978 
1979   ExitOnErr(runChecks(*S));
1980 
1981   dumpSessionStats(*S);
1982 
1983   if (NoExec)
1984     return 0;
1985 
1986   int Result = 0;
1987   {
1988     LLVM_DEBUG(dbgs() << "Running \"" << EntryPointName << "\"...\n");
1989     TimeRegion TR(Timers ? &Timers->RunTimer : nullptr);
1990     if (!OrcRuntime.empty())
1991       Result =
1992           ExitOnErr(runWithRuntime(*S, ExecutorAddr(EntryPoint.getAddress())));
1993     else
1994       Result = ExitOnErr(
1995           runWithoutRuntime(*S, ExecutorAddr(EntryPoint.getAddress())));
1996   }
1997 
1998   // Destroy the session.
1999   ExitOnErr(S->ES.endSession());
2000   S.reset();
2001 
2002   // If the executing code set a test result override then use that.
2003   if (UseTestResultOverride)
2004     Result = TestResultOverride;
2005 
2006   return Result;
2007 }
2008