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