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