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/EPCDebugObjectRegistrar.h"
20 #include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
21 #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h"
22 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
23 #include "llvm/ExecutionEngine/Orc/MachOPlatform.h"
24 #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
25 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSubtargetInfo.h"
33 #include "llvm/MC/MCTargetOptions.h"
34 #include "llvm/Object/COFF.h"
35 #include "llvm/Object/MachO.h"
36 #include "llvm/Object/ObjectFile.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/InitLLVM.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Process.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/Timer.h"
46 
47 #include <cstring>
48 #include <list>
49 #include <string>
50 
51 #ifdef LLVM_ON_UNIX
52 #include <netdb.h>
53 #include <netinet/in.h>
54 #include <sys/socket.h>
55 #include <unistd.h>
56 #endif // LLVM_ON_UNIX
57 
58 #define DEBUG_TYPE "llvm_jitlink"
59 
60 using namespace llvm;
61 using namespace llvm::jitlink;
62 using namespace llvm::orc;
63 
64 static cl::OptionCategory JITLinkCategory("JITLink Options");
65 
66 static cl::list<std::string> InputFiles(cl::Positional, cl::OneOrMore,
67                                         cl::desc("input files"),
68                                         cl::cat(JITLinkCategory));
69 
70 static cl::opt<bool> NoExec("noexec", cl::desc("Do not execute loaded code"),
71                             cl::init(false), cl::cat(JITLinkCategory));
72 
73 static cl::list<std::string>
74     CheckFiles("check", cl::desc("File containing verifier checks"),
75                cl::ZeroOrMore, cl::cat(JITLinkCategory));
76 
77 static cl::opt<std::string>
78     CheckName("check-name", cl::desc("Name of checks to match against"),
79               cl::init("jitlink-check"), cl::cat(JITLinkCategory));
80 
81 static cl::opt<std::string>
82     EntryPointName("entry", cl::desc("Symbol to call as main entry point"),
83                    cl::init(""), cl::cat(JITLinkCategory));
84 
85 static cl::list<std::string> JITLinkDylibs(
86     "jld",
87     cl::desc("Specifies the JITDylib to be used for any subsequent "
88              "input file arguments"),
89     cl::cat(JITLinkCategory));
90 
91 static cl::list<std::string>
92     Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"),
93            cl::ZeroOrMore, cl::cat(JITLinkCategory));
94 
95 static cl::list<std::string> InputArgv("args", cl::Positional,
96                                        cl::desc("<program arguments>..."),
97                                        cl::ZeroOrMore, cl::PositionalEatsArgs,
98                                        cl::cat(JITLinkCategory));
99 
100 static cl::opt<bool>
101     NoProcessSymbols("no-process-syms",
102                      cl::desc("Do not resolve to llvm-jitlink process symbols"),
103                      cl::init(false), cl::cat(JITLinkCategory));
104 
105 static cl::list<std::string> AbsoluteDefs(
106     "define-abs",
107     cl::desc("Inject absolute symbol definitions (syntax: <name>=<addr>)"),
108     cl::ZeroOrMore, cl::cat(JITLinkCategory));
109 
110 static cl::list<std::string> TestHarnesses("harness", cl::Positional,
111                                            cl::desc("Test harness files"),
112                                            cl::ZeroOrMore,
113                                            cl::PositionalEatsArgs,
114                                            cl::cat(JITLinkCategory));
115 
116 static cl::opt<bool> ShowInitialExecutionSessionState(
117     "show-init-es",
118     cl::desc("Print ExecutionSession state before resolving entry point"),
119     cl::init(false), cl::cat(JITLinkCategory));
120 
121 static cl::opt<bool> ShowAddrs(
122     "show-addrs",
123     cl::desc("Print registered symbol, section, got and stub addresses"),
124     cl::init(false), cl::cat(JITLinkCategory));
125 
126 static cl::opt<bool> ShowLinkGraph(
127     "show-graph",
128     cl::desc("Print the link graph after fixups have been applied"),
129     cl::init(false), cl::cat(JITLinkCategory));
130 
131 static cl::opt<bool> ShowSizes(
132     "show-sizes",
133     cl::desc("Show sizes pre- and post-dead stripping, and allocations"),
134     cl::init(false), cl::cat(JITLinkCategory));
135 
136 static cl::opt<bool> ShowTimes("show-times",
137                                cl::desc("Show times for llvm-jitlink phases"),
138                                cl::init(false), cl::cat(JITLinkCategory));
139 
140 static cl::opt<std::string> SlabAllocateSizeString(
141     "slab-allocate",
142     cl::desc("Allocate from a slab of the given size "
143              "(allowable suffixes: Kb, Mb, Gb. default = "
144              "Kb)"),
145     cl::init(""), cl::cat(JITLinkCategory));
146 
147 static cl::opt<uint64_t> SlabAddress(
148     "slab-address",
149     cl::desc("Set slab target address (requires -slab-allocate and -noexec)"),
150     cl::init(~0ULL), cl::cat(JITLinkCategory));
151 
152 static cl::opt<bool> ShowRelocatedSectionContents(
153     "show-relocated-section-contents",
154     cl::desc("show section contents after fixups have been applied"),
155     cl::init(false), cl::cat(JITLinkCategory));
156 
157 static cl::opt<bool> PhonyExternals(
158     "phony-externals",
159     cl::desc("resolve all otherwise unresolved externals to null"),
160     cl::init(false), cl::cat(JITLinkCategory));
161 
162 static cl::opt<std::string> OutOfProcessExecutor(
163     "oop-executor", cl::desc("Launch an out-of-process executor to run code"),
164     cl::ValueOptional, cl::cat(JITLinkCategory));
165 
166 static cl::opt<std::string> OutOfProcessExecutorConnect(
167     "oop-executor-connect",
168     cl::desc("Connect to an out-of-process executor via TCP"),
169     cl::cat(JITLinkCategory));
170 
171 // TODO: Default to false if compiler-rt is not built.
172 static cl::opt<bool> UseOrcRuntime("use-orc-runtime",
173                                    cl::desc("Do not required/load ORC runtime"),
174                                    cl::init(true), cl::cat(JITLinkCategory));
175 
176 static cl::opt<std::string>
177     OrcRuntimePath("orc-runtime-path", cl::desc("Add orc runtime to session"),
178                    cl::init(""), cl::cat(JITLinkCategory));
179 
180 ExitOnError ExitOnErr;
181 
182 LLVM_ATTRIBUTE_USED void linkComponents() {
183   errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper
184          << (void *)&llvm_orc_deregisterEHFrameSectionWrapper
185          << (void *)&llvm_orc_registerJITLoaderGDBWrapper;
186 }
187 
188 static bool UseTestResultOverride = false;
189 static int64_t TestResultOverride = 0;
190 
191 extern "C" void llvm_jitlink_setTestResultOverride(int64_t Value) {
192   TestResultOverride = Value;
193   UseTestResultOverride = true;
194 }
195 
196 namespace llvm {
197 
198 static raw_ostream &
199 operator<<(raw_ostream &OS, const Session::MemoryRegionInfo &MRI) {
200   return OS << "target addr = "
201             << format("0x%016" PRIx64, MRI.getTargetAddress())
202             << ", content: " << (const void *)MRI.getContent().data() << " -- "
203             << (const void *)(MRI.getContent().data() + MRI.getContent().size())
204             << " (" << MRI.getContent().size() << " bytes)";
205 }
206 
207 static raw_ostream &
208 operator<<(raw_ostream &OS, const Session::SymbolInfoMap &SIM) {
209   OS << "Symbols:\n";
210   for (auto &SKV : SIM)
211     OS << "  \"" << SKV.first() << "\" " << SKV.second << "\n";
212   return OS;
213 }
214 
215 static raw_ostream &
216 operator<<(raw_ostream &OS, const Session::FileInfo &FI) {
217   for (auto &SIKV : FI.SectionInfos)
218     OS << "  Section \"" << SIKV.first() << "\": " << SIKV.second << "\n";
219   for (auto &GOTKV : FI.GOTEntryInfos)
220     OS << "  GOT \"" << GOTKV.first() << "\": " << GOTKV.second << "\n";
221   for (auto &StubKV : FI.StubInfos)
222     OS << "  Stub \"" << StubKV.first() << "\": " << StubKV.second << "\n";
223   return OS;
224 }
225 
226 static raw_ostream &
227 operator<<(raw_ostream &OS, const Session::FileInfoMap &FIM) {
228   for (auto &FIKV : FIM)
229     OS << "File \"" << FIKV.first() << "\":\n" << FIKV.second;
230   return OS;
231 }
232 
233 static Error applyHarnessPromotions(Session &S, LinkGraph &G) {
234 
235   // If this graph is part of the test harness there's nothing to do.
236   if (S.HarnessFiles.empty() || S.HarnessFiles.count(G.getName()))
237     return Error::success();
238 
239   LLVM_DEBUG(dbgs() << "Appling promotions to graph " << G.getName() << "\n");
240 
241   // If this graph is part of the test then promote any symbols referenced by
242   // the harness to default scope, remove all symbols that clash with harness
243   // definitions.
244   std::vector<Symbol *> DefinitionsToRemove;
245   for (auto *Sym : G.defined_symbols()) {
246 
247     if (!Sym->hasName())
248       continue;
249 
250     if (Sym->getLinkage() == Linkage::Weak) {
251       if (!S.CanonicalWeakDefs.count(Sym->getName()) ||
252           S.CanonicalWeakDefs[Sym->getName()] != G.getName()) {
253         LLVM_DEBUG({
254           dbgs() << "  Externalizing weak symbol " << Sym->getName() << "\n";
255         });
256         DefinitionsToRemove.push_back(Sym);
257       } else {
258         LLVM_DEBUG({
259           dbgs() << "  Making weak symbol " << Sym->getName() << " strong\n";
260         });
261         if (S.HarnessExternals.count(Sym->getName()))
262           Sym->setScope(Scope::Default);
263         else
264           Sym->setScope(Scope::Hidden);
265         Sym->setLinkage(Linkage::Strong);
266       }
267     } else if (S.HarnessExternals.count(Sym->getName())) {
268       LLVM_DEBUG(dbgs() << "  Promoting " << Sym->getName() << "\n");
269       Sym->setScope(Scope::Default);
270       Sym->setLive(true);
271       continue;
272     } else if (S.HarnessDefinitions.count(Sym->getName())) {
273       LLVM_DEBUG(dbgs() << "  Externalizing " << Sym->getName() << "\n");
274       DefinitionsToRemove.push_back(Sym);
275     }
276   }
277 
278   for (auto *Sym : DefinitionsToRemove)
279     G.makeExternal(*Sym);
280 
281   return Error::success();
282 }
283 
284 static uint64_t computeTotalBlockSizes(LinkGraph &G) {
285   uint64_t TotalSize = 0;
286   for (auto *B : G.blocks())
287     TotalSize += B->getSize();
288   return TotalSize;
289 }
290 
291 static void dumpSectionContents(raw_ostream &OS, LinkGraph &G) {
292   constexpr JITTargetAddress DumpWidth = 16;
293   static_assert(isPowerOf2_64(DumpWidth), "DumpWidth must be a power of two");
294 
295   // Put sections in address order.
296   std::vector<Section *> Sections;
297   for (auto &S : G.sections())
298     Sections.push_back(&S);
299 
300   llvm::sort(Sections, [](const Section *LHS, const Section *RHS) {
301     if (llvm::empty(LHS->symbols()) && llvm::empty(RHS->symbols()))
302       return false;
303     if (llvm::empty(LHS->symbols()))
304       return false;
305     if (llvm::empty(RHS->symbols()))
306       return true;
307     SectionRange LHSRange(*LHS);
308     SectionRange RHSRange(*RHS);
309     return LHSRange.getStart() < RHSRange.getStart();
310   });
311 
312   for (auto *S : Sections) {
313     OS << S->getName() << " content:";
314     if (llvm::empty(S->symbols())) {
315       OS << "\n  section empty\n";
316       continue;
317     }
318 
319     // Sort symbols into order, then render.
320     std::vector<Symbol *> Syms(S->symbols().begin(), S->symbols().end());
321     llvm::sort(Syms, [](const Symbol *LHS, const Symbol *RHS) {
322       return LHS->getAddress() < RHS->getAddress();
323     });
324 
325     JITTargetAddress NextAddr = Syms.front()->getAddress() & ~(DumpWidth - 1);
326     for (auto *Sym : Syms) {
327       bool IsZeroFill = Sym->getBlock().isZeroFill();
328       JITTargetAddress SymStart = Sym->getAddress();
329       JITTargetAddress SymSize = Sym->getSize();
330       JITTargetAddress SymEnd = SymStart + SymSize;
331       const uint8_t *SymData = IsZeroFill ? nullptr
332                                           : reinterpret_cast<const uint8_t *>(
333                                                 Sym->getSymbolContent().data());
334 
335       // Pad any space before the symbol starts.
336       while (NextAddr != SymStart) {
337         if (NextAddr % DumpWidth == 0)
338           OS << formatv("\n{0:x16}:", NextAddr);
339         OS << "   ";
340         ++NextAddr;
341       }
342 
343       // Render the symbol content.
344       while (NextAddr != SymEnd) {
345         if (NextAddr % DumpWidth == 0)
346           OS << formatv("\n{0:x16}:", NextAddr);
347         if (IsZeroFill)
348           OS << " 00";
349         else
350           OS << formatv(" {0:x-2}", SymData[NextAddr - SymStart]);
351         ++NextAddr;
352       }
353     }
354     OS << "\n";
355   }
356 }
357 
358 class JITLinkSlabAllocator final : public JITLinkMemoryManager {
359 public:
360   static Expected<std::unique_ptr<JITLinkSlabAllocator>>
361   Create(uint64_t SlabSize) {
362     Error Err = Error::success();
363     std::unique_ptr<JITLinkSlabAllocator> Allocator(
364         new JITLinkSlabAllocator(SlabSize, Err));
365     if (Err)
366       return std::move(Err);
367     return std::move(Allocator);
368   }
369 
370   Expected<std::unique_ptr<JITLinkMemoryManager::Allocation>>
371   allocate(const JITLinkDylib *JD, const SegmentsRequestMap &Request) override {
372 
373     using AllocationMap = DenseMap<unsigned, sys::MemoryBlock>;
374 
375     // Local class for allocation.
376     class IPMMAlloc : public Allocation {
377     public:
378       IPMMAlloc(JITLinkSlabAllocator &Parent, AllocationMap SegBlocks)
379           : Parent(Parent), SegBlocks(std::move(SegBlocks)) {}
380       MutableArrayRef<char> getWorkingMemory(ProtectionFlags Seg) override {
381         assert(SegBlocks.count(Seg) && "No allocation for segment");
382         return {static_cast<char *>(SegBlocks[Seg].base()),
383                 SegBlocks[Seg].allocatedSize()};
384       }
385       JITTargetAddress getTargetMemory(ProtectionFlags Seg) override {
386         assert(SegBlocks.count(Seg) && "No allocation for segment");
387         return pointerToJITTargetAddress(SegBlocks[Seg].base()) +
388                Parent.TargetDelta;
389       }
390       void finalizeAsync(FinalizeContinuation OnFinalize) override {
391         OnFinalize(applyProtections());
392       }
393       Error deallocate() override {
394         for (auto &KV : SegBlocks)
395           if (auto EC = sys::Memory::releaseMappedMemory(KV.second))
396             return errorCodeToError(EC);
397         return Error::success();
398       }
399 
400     private:
401       Error applyProtections() {
402         for (auto &KV : SegBlocks) {
403           auto &Prot = KV.first;
404           auto &Block = KV.second;
405           if (auto EC = sys::Memory::protectMappedMemory(Block, Prot))
406             return errorCodeToError(EC);
407           if (Prot & sys::Memory::MF_EXEC)
408             sys::Memory::InvalidateInstructionCache(Block.base(),
409                                                     Block.allocatedSize());
410         }
411         return Error::success();
412       }
413 
414       JITLinkSlabAllocator &Parent;
415       AllocationMap SegBlocks;
416     };
417 
418     AllocationMap Blocks;
419 
420     for (auto &KV : Request) {
421       auto &Seg = KV.second;
422 
423       if (Seg.getAlignment() > PageSize)
424         return make_error<StringError>("Cannot request higher than page "
425                                        "alignment",
426                                        inconvertibleErrorCode());
427 
428       if (PageSize % Seg.getAlignment() != 0)
429         return make_error<StringError>("Page size is not a multiple of "
430                                        "alignment",
431                                        inconvertibleErrorCode());
432 
433       uint64_t ZeroFillStart = Seg.getContentSize();
434       uint64_t SegmentSize = ZeroFillStart + Seg.getZeroFillSize();
435 
436       // Round segment size up to page boundary.
437       SegmentSize = (SegmentSize + PageSize - 1) & ~(PageSize - 1);
438 
439       // Take segment bytes from the front of the slab.
440       void *SlabBase = SlabRemaining.base();
441       uint64_t SlabRemainingSize = SlabRemaining.allocatedSize();
442 
443       if (SegmentSize > SlabRemainingSize)
444         return make_error<StringError>("Slab allocator out of memory",
445                                        inconvertibleErrorCode());
446 
447       sys::MemoryBlock SegMem(SlabBase, SegmentSize);
448       SlabRemaining =
449           sys::MemoryBlock(reinterpret_cast<char *>(SlabBase) + SegmentSize,
450                            SlabRemainingSize - SegmentSize);
451 
452       // Zero out the zero-fill memory.
453       memset(static_cast<char *>(SegMem.base()) + ZeroFillStart, 0,
454              Seg.getZeroFillSize());
455 
456       // Record the block for this segment.
457       Blocks[KV.first] = std::move(SegMem);
458     }
459     return std::unique_ptr<InProcessMemoryManager::Allocation>(
460         new IPMMAlloc(*this, std::move(Blocks)));
461   }
462 
463 private:
464   JITLinkSlabAllocator(uint64_t SlabSize, Error &Err) {
465     ErrorAsOutParameter _(&Err);
466 
467     PageSize = sys::Process::getPageSizeEstimate();
468 
469     if (!isPowerOf2_64(PageSize)) {
470       Err = make_error<StringError>("Page size is not a power of 2",
471                                     inconvertibleErrorCode());
472       return;
473     }
474 
475     // Round slab request up to page size.
476     SlabSize = (SlabSize + PageSize - 1) & ~(PageSize - 1);
477 
478     const sys::Memory::ProtectionFlags ReadWrite =
479         static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
480                                                   sys::Memory::MF_WRITE);
481 
482     std::error_code EC;
483     SlabRemaining =
484         sys::Memory::allocateMappedMemory(SlabSize, nullptr, ReadWrite, EC);
485 
486     if (EC) {
487       Err = errorCodeToError(EC);
488       return;
489     }
490 
491     // Calculate the target address delta to link as-if slab were at
492     // SlabAddress.
493     if (SlabAddress != ~0ULL)
494       TargetDelta =
495           SlabAddress - pointerToJITTargetAddress(SlabRemaining.base());
496   }
497 
498   sys::MemoryBlock SlabRemaining;
499   uint64_t PageSize = 0;
500   int64_t TargetDelta = 0;
501 };
502 
503 Expected<uint64_t> getSlabAllocSize(StringRef SizeString) {
504   SizeString = SizeString.trim();
505 
506   uint64_t Units = 1024;
507 
508   if (SizeString.endswith_insensitive("kb"))
509     SizeString = SizeString.drop_back(2).rtrim();
510   else if (SizeString.endswith_insensitive("mb")) {
511     Units = 1024 * 1024;
512     SizeString = SizeString.drop_back(2).rtrim();
513   } else if (SizeString.endswith_insensitive("gb")) {
514     Units = 1024 * 1024 * 1024;
515     SizeString = SizeString.drop_back(2).rtrim();
516   }
517 
518   uint64_t SlabSize = 0;
519   if (SizeString.getAsInteger(10, SlabSize))
520     return make_error<StringError>("Invalid numeric format for slab size",
521                                    inconvertibleErrorCode());
522 
523   return SlabSize * Units;
524 }
525 
526 static std::unique_ptr<JITLinkMemoryManager> createMemoryManager() {
527   if (!SlabAllocateSizeString.empty()) {
528     auto SlabSize = ExitOnErr(getSlabAllocSize(SlabAllocateSizeString));
529     return ExitOnErr(JITLinkSlabAllocator::Create(SlabSize));
530   }
531   return std::make_unique<InProcessMemoryManager>();
532 }
533 
534 LLVMJITLinkObjectLinkingLayer::LLVMJITLinkObjectLinkingLayer(
535     Session &S, JITLinkMemoryManager &MemMgr)
536     : ObjectLinkingLayer(S.ES, MemMgr), S(S) {}
537 
538 Error LLVMJITLinkObjectLinkingLayer::add(ResourceTrackerSP RT,
539                                          std::unique_ptr<MemoryBuffer> O) {
540 
541   if (S.HarnessFiles.empty() || S.HarnessFiles.count(O->getBufferIdentifier()))
542     return ObjectLinkingLayer::add(std::move(RT), std::move(O));
543 
544   // Use getObjectSymbolInfo to compute the init symbol, but ignore
545   // the symbols field. We'll handle that manually to include promotion.
546   auto ObjSymInfo =
547       getObjectSymbolInfo(getExecutionSession(), O->getMemBufferRef());
548 
549   if (!ObjSymInfo)
550     return ObjSymInfo.takeError();
551 
552   auto &InitSymbol = ObjSymInfo->second;
553 
554   // If creating an object file was going to fail it would have happened above,
555   // so we can 'cantFail' this.
556   auto Obj =
557       cantFail(object::ObjectFile::createObjectFile(O->getMemBufferRef()));
558 
559   SymbolFlagsMap SymbolFlags;
560 
561   // The init symbol must be included in the SymbolFlags map if present.
562   if (InitSymbol)
563     SymbolFlags[InitSymbol] = JITSymbolFlags::MaterializationSideEffectsOnly;
564 
565   for (auto &Sym : Obj->symbols()) {
566     Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
567     if (!SymFlagsOrErr)
568       // TODO: Test this error.
569       return SymFlagsOrErr.takeError();
570 
571     // Skip symbols not defined in this object file.
572     if ((*SymFlagsOrErr & object::BasicSymbolRef::SF_Undefined))
573       continue;
574 
575     auto Name = Sym.getName();
576     if (!Name)
577       return Name.takeError();
578 
579     // Skip symbols that have type SF_File.
580     if (auto SymType = Sym.getType()) {
581       if (*SymType == object::SymbolRef::ST_File)
582         continue;
583     } else
584       return SymType.takeError();
585 
586     auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
587     if (!SymFlags)
588       return SymFlags.takeError();
589 
590     if (SymFlags->isWeak()) {
591       // If this is a weak symbol that's not defined in the harness then we
592       // need to either mark it as strong (if this is the first definition
593       // that we've seen) or discard it.
594       if (S.HarnessDefinitions.count(*Name) || S.CanonicalWeakDefs.count(*Name))
595         continue;
596       S.CanonicalWeakDefs[*Name] = O->getBufferIdentifier();
597       *SymFlags &= ~JITSymbolFlags::Weak;
598       if (!S.HarnessExternals.count(*Name))
599         *SymFlags &= ~JITSymbolFlags::Exported;
600     } else if (S.HarnessExternals.count(*Name)) {
601       *SymFlags |= JITSymbolFlags::Exported;
602     } else if (S.HarnessDefinitions.count(*Name) ||
603                !(*SymFlagsOrErr & object::BasicSymbolRef::SF_Global))
604       continue;
605 
606     auto InternedName = S.ES.intern(*Name);
607     SymbolFlags[InternedName] = std::move(*SymFlags);
608   }
609 
610   auto MU = std::make_unique<BasicObjectLayerMaterializationUnit>(
611       *this, std::move(O), std::move(SymbolFlags), std::move(InitSymbol));
612 
613   auto &JD = RT->getJITDylib();
614   return JD.define(std::move(MU), std::move(RT));
615 }
616 
617 static Error loadProcessSymbols(Session &S) {
618   auto FilterMainEntryPoint =
619       [EPName = S.ES.intern(EntryPointName)](SymbolStringPtr Name) {
620         return Name != EPName;
621       };
622   S.MainJD->addGenerator(
623       ExitOnErr(orc::EPCDynamicLibrarySearchGenerator::GetForTargetProcess(
624           S.ES, std::move(FilterMainEntryPoint))));
625 
626   return Error::success();
627 }
628 
629 static Error loadDylibs(Session &S) {
630   LLVM_DEBUG(dbgs() << "Loading dylibs...\n");
631   for (const auto &Dylib : Dylibs) {
632     LLVM_DEBUG(dbgs() << "  " << Dylib << "\n");
633     auto G = orc::EPCDynamicLibrarySearchGenerator::Load(S.ES, Dylib.c_str());
634     if (!G)
635       return G.takeError();
636     S.MainJD->addGenerator(std::move(*G));
637   }
638 
639   return Error::success();
640 }
641 
642 Expected<std::unique_ptr<ExecutorProcessControl>>
643 LLVMJITLinkRemoteExecutorProcessControl::LaunchExecutor() {
644 #ifndef LLVM_ON_UNIX
645   // FIXME: Add support for Windows.
646   return make_error<StringError>("-" + OutOfProcessExecutor.ArgStr +
647                                      " not supported on non-unix platforms",
648                                  inconvertibleErrorCode());
649 #else
650 
651   shared::registerStringError<LLVMJITLinkChannel>();
652 
653   constexpr int ReadEnd = 0;
654   constexpr int WriteEnd = 1;
655 
656   // Pipe FDs.
657   int ToExecutor[2];
658   int FromExecutor[2];
659 
660   pid_t ChildPID;
661 
662   // Create pipes to/from the executor..
663   if (pipe(ToExecutor) != 0 || pipe(FromExecutor) != 0)
664     return make_error<StringError>("Unable to create pipe for executor",
665                                    inconvertibleErrorCode());
666 
667   ChildPID = fork();
668 
669   if (ChildPID == 0) {
670     // In the child...
671 
672     // Close the parent ends of the pipes
673     close(ToExecutor[WriteEnd]);
674     close(FromExecutor[ReadEnd]);
675 
676     // Execute the child process.
677     std::unique_ptr<char[]> ExecutorPath, FDSpecifier;
678     {
679       ExecutorPath = std::make_unique<char[]>(OutOfProcessExecutor.size() + 1);
680       strcpy(ExecutorPath.get(), OutOfProcessExecutor.data());
681 
682       std::string FDSpecifierStr("filedescs=");
683       FDSpecifierStr += utostr(ToExecutor[ReadEnd]);
684       FDSpecifierStr += ',';
685       FDSpecifierStr += utostr(FromExecutor[WriteEnd]);
686       FDSpecifier = std::make_unique<char[]>(FDSpecifierStr.size() + 1);
687       strcpy(FDSpecifier.get(), FDSpecifierStr.c_str());
688     }
689 
690     char *const Args[] = {ExecutorPath.get(), FDSpecifier.get(), nullptr};
691     int RC = execvp(ExecutorPath.get(), Args);
692     if (RC != 0) {
693       errs() << "unable to launch out-of-process executor \""
694              << ExecutorPath.get() << "\"\n";
695       exit(1);
696     }
697   }
698   // else we're the parent...
699 
700   // Close the child ends of the pipes
701   close(ToExecutor[ReadEnd]);
702   close(FromExecutor[WriteEnd]);
703 
704   // Return an RPC channel connected to our end of the pipes.
705   auto SSP = std::make_shared<SymbolStringPool>();
706   auto Channel = std::make_unique<shared::FDRawByteChannel>(
707       FromExecutor[ReadEnd], ToExecutor[WriteEnd]);
708   auto Endpoint = std::make_unique<LLVMJITLinkRPCEndpoint>(*Channel, true);
709 
710   auto ReportError = [](Error Err) {
711     logAllUnhandledErrors(std::move(Err), errs(), "");
712   };
713 
714   Error Err = Error::success();
715   std::unique_ptr<LLVMJITLinkRemoteExecutorProcessControl> REPC(
716       new LLVMJITLinkRemoteExecutorProcessControl(
717           std::move(SSP), std::move(Channel), std::move(Endpoint),
718           std::move(ReportError), Err));
719   if (Err)
720     return std::move(Err);
721   return std::move(REPC);
722 #endif
723 }
724 
725 #ifdef LLVM_ON_UNIX
726 static Error createTCPSocketError(Twine Details) {
727   return make_error<StringError>(
728       formatv("Failed to connect TCP socket '{0}': {1}",
729               OutOfProcessExecutorConnect, Details),
730       inconvertibleErrorCode());
731 }
732 
733 static Expected<int> connectTCPSocket(std::string Host, std::string PortStr) {
734   addrinfo *AI;
735   addrinfo Hints{};
736   Hints.ai_family = AF_INET;
737   Hints.ai_socktype = SOCK_STREAM;
738   Hints.ai_flags = AI_NUMERICSERV;
739 
740   if (int EC = getaddrinfo(Host.c_str(), PortStr.c_str(), &Hints, &AI))
741     return createTCPSocketError("Address resolution failed (" +
742                                 StringRef(gai_strerror(EC)) + ")");
743 
744   // Cycle through the returned addrinfo structures and connect to the first
745   // reachable endpoint.
746   int SockFD;
747   addrinfo *Server;
748   for (Server = AI; Server != nullptr; Server = Server->ai_next) {
749     // socket might fail, e.g. if the address family is not supported. Skip to
750     // the next addrinfo structure in such a case.
751     if ((SockFD = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0)
752       continue;
753 
754     // If connect returns null, we exit the loop with a working socket.
755     if (connect(SockFD, Server->ai_addr, Server->ai_addrlen) == 0)
756       break;
757 
758     close(SockFD);
759   }
760   freeaddrinfo(AI);
761 
762   // If we reached the end of the loop without connecting to a valid endpoint,
763   // dump the last error that was logged in socket() or connect().
764   if (Server == nullptr)
765     return createTCPSocketError(std::strerror(errno));
766 
767   return SockFD;
768 }
769 #endif
770 
771 Expected<std::unique_ptr<ExecutorProcessControl>>
772 LLVMJITLinkRemoteExecutorProcessControl::ConnectToExecutor() {
773 #ifndef LLVM_ON_UNIX
774   // FIXME: Add TCP support for Windows.
775   return make_error<StringError>("-" + OutOfProcessExecutorConnect.ArgStr +
776                                      " not supported on non-unix platforms",
777                                  inconvertibleErrorCode());
778 #else
779 
780   shared::registerStringError<LLVMJITLinkChannel>();
781 
782   StringRef Host, PortStr;
783   std::tie(Host, PortStr) = StringRef(OutOfProcessExecutorConnect).split(':');
784   if (Host.empty())
785     return createTCPSocketError("Host name for -" +
786                                 OutOfProcessExecutorConnect.ArgStr +
787                                 " can not be empty");
788   if (PortStr.empty())
789     return createTCPSocketError("Port number in -" +
790                                 OutOfProcessExecutorConnect.ArgStr +
791                                 " can not be empty");
792   int Port = 0;
793   if (PortStr.getAsInteger(10, Port))
794     return createTCPSocketError("Port number '" + PortStr +
795                                 "' is not a valid integer");
796 
797   Expected<int> SockFD = connectTCPSocket(Host.str(), PortStr.str());
798   if (!SockFD)
799     return SockFD.takeError();
800 
801   auto SSP = std::make_shared<SymbolStringPool>();
802   auto Channel = std::make_unique<shared::FDRawByteChannel>(*SockFD, *SockFD);
803   auto Endpoint = std::make_unique<LLVMJITLinkRPCEndpoint>(*Channel, true);
804 
805   auto ReportError = [](Error Err) {
806     logAllUnhandledErrors(std::move(Err), errs(), "");
807   };
808 
809   Error Err = Error::success();
810   std::unique_ptr<LLVMJITLinkRemoteExecutorProcessControl> REPC(
811       new LLVMJITLinkRemoteExecutorProcessControl(
812           std::move(SSP), std::move(Channel), std::move(Endpoint),
813           std::move(ReportError), Err));
814   if (Err)
815     return std::move(Err);
816   return std::move(REPC);
817 #endif
818 }
819 
820 Error LLVMJITLinkRemoteExecutorProcessControl::disconnect() {
821   std::promise<MSVCPError> P;
822   auto F = P.get_future();
823   auto Err = closeConnection([&](Error Err) -> Error {
824     P.set_value(std::move(Err));
825     Finished = true;
826     return Error::success();
827   });
828   ListenerThread.join();
829   return joinErrors(std::move(Err), F.get());
830 }
831 
832 class PhonyExternalsGenerator : public DefinitionGenerator {
833 public:
834   Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
835                       JITDylibLookupFlags JDLookupFlags,
836                       const SymbolLookupSet &LookupSet) override {
837     SymbolMap PhonySymbols;
838     for (auto &KV : LookupSet)
839       PhonySymbols[KV.first] = JITEvaluatedSymbol(0, JITSymbolFlags::Exported);
840     return JD.define(absoluteSymbols(std::move(PhonySymbols)));
841   }
842 };
843 
844 Expected<std::unique_ptr<Session>> Session::Create(Triple TT) {
845 
846   auto PageSize = sys::Process::getPageSize();
847   if (!PageSize)
848     return PageSize.takeError();
849 
850   std::unique_ptr<ExecutorProcessControl> EPC;
851   if (OutOfProcessExecutor.getNumOccurrences()) {
852     /// If -oop-executor is passed then launch the executor.
853     if (auto REPC = LLVMJITLinkRemoteExecutorProcessControl::LaunchExecutor())
854       EPC = std::move(*REPC);
855     else
856       return REPC.takeError();
857   } else if (OutOfProcessExecutorConnect.getNumOccurrences()) {
858     /// If -oop-executor-connect is passed then connect to the executor.
859     if (auto REPC =
860             LLVMJITLinkRemoteExecutorProcessControl::ConnectToExecutor())
861       EPC = std::move(*REPC);
862     else
863       return REPC.takeError();
864   } else {
865     /// Otherwise use SelfExecutorProcessControl to target the current process.
866     EPC = std::make_unique<SelfExecutorProcessControl>(
867         std::make_shared<SymbolStringPool>(), std::move(TT), *PageSize,
868         createMemoryManager());
869   }
870 
871   Error Err = Error::success();
872   std::unique_ptr<Session> S(new Session(std::move(EPC), Err));
873 
874   // FIXME: Errors destroy the session, leaving the SymbolStringPtrs dangling,
875   // so just exit here. We could fix this by having errors keep the pool alive.
876   ExitOnErr(std::move(Err));
877   return std::move(S);
878 }
879 
880 Session::~Session() {
881   if (auto Err = ES.endSession())
882     ES.reportError(std::move(Err));
883 }
884 
885 Session::Session(std::unique_ptr<ExecutorProcessControl> EPC, Error &Err)
886     : ES(std::move(EPC)),
887       ObjLayer(*this, ES.getExecutorProcessControl().getMemMgr()) {
888 
889   /// Local ObjectLinkingLayer::Plugin class to forward modifyPassConfig to the
890   /// Session.
891   class JITLinkSessionPlugin : public ObjectLinkingLayer::Plugin {
892   public:
893     JITLinkSessionPlugin(Session &S) : S(S) {}
894     void modifyPassConfig(MaterializationResponsibility &MR, LinkGraph &G,
895                           PassConfiguration &PassConfig) override {
896       S.modifyPassConfig(G.getTargetTriple(), PassConfig);
897     }
898 
899     Error notifyFailed(MaterializationResponsibility &MR) override {
900       return Error::success();
901     }
902     Error notifyRemovingResources(ResourceKey K) override {
903       return Error::success();
904     }
905     void notifyTransferringResources(ResourceKey DstKey,
906                                      ResourceKey SrcKey) override {}
907 
908   private:
909     Session &S;
910   };
911 
912   ErrorAsOutParameter _(&Err);
913 
914   if (auto MainJDOrErr = ES.createJITDylib("main"))
915     MainJD = &*MainJDOrErr;
916   else {
917     Err = MainJDOrErr.takeError();
918     return;
919   }
920 
921   if (!NoProcessSymbols)
922     ExitOnErr(loadProcessSymbols(*this));
923   ExitOnErr(loadDylibs(*this));
924 
925   // Set up the platform.
926   auto &TT = ES.getExecutorProcessControl().getTargetTriple();
927   if (TT.isOSBinFormatMachO() && UseOrcRuntime) {
928     if (auto P = MachOPlatform::Create(ES, ObjLayer, *MainJD,
929                                        OrcRuntimePath.c_str()))
930       ES.setPlatform(std::move(*P));
931     else {
932       Err = P.takeError();
933       return;
934     }
935   } else if (!NoExec && !TT.isOSWindows() && !TT.isOSBinFormatMachO()) {
936     ObjLayer.addPlugin(std::make_unique<EHFrameRegistrationPlugin>(
937         ES, ExitOnErr(EPCEHFrameRegistrar::Create(this->ES))));
938     ObjLayer.addPlugin(std::make_unique<DebugObjectManagerPlugin>(
939         ES, ExitOnErr(createJITLoaderGDBRegistrar(this->ES))));
940   }
941 
942   ObjLayer.addPlugin(std::make_unique<JITLinkSessionPlugin>(*this));
943 
944   // Process any harness files.
945   for (auto &HarnessFile : TestHarnesses) {
946     HarnessFiles.insert(HarnessFile);
947 
948     auto ObjBuffer =
949         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(HarnessFile)));
950 
951     auto ObjSymbolInfo =
952         ExitOnErr(getObjectSymbolInfo(ES, ObjBuffer->getMemBufferRef()));
953 
954     for (auto &KV : ObjSymbolInfo.first)
955       HarnessDefinitions.insert(*KV.first);
956 
957     auto Obj = ExitOnErr(
958         object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef()));
959 
960     for (auto &Sym : Obj->symbols()) {
961       uint32_t SymFlags = ExitOnErr(Sym.getFlags());
962       auto Name = ExitOnErr(Sym.getName());
963 
964       if (Name.empty())
965         continue;
966 
967       if (SymFlags & object::BasicSymbolRef::SF_Undefined)
968         HarnessExternals.insert(Name);
969     }
970   }
971 
972   // If a name is defined by some harness file then it's a definition, not an
973   // external.
974   for (auto &DefName : HarnessDefinitions)
975     HarnessExternals.erase(DefName.getKey());
976 }
977 
978 void Session::dumpSessionInfo(raw_ostream &OS) {
979   OS << "Registered addresses:\n" << SymbolInfos << FileInfos;
980 }
981 
982 void Session::modifyPassConfig(const Triple &TT,
983                                PassConfiguration &PassConfig) {
984   if (!CheckFiles.empty())
985     PassConfig.PostFixupPasses.push_back([this](LinkGraph &G) {
986       auto &EPC = ES.getExecutorProcessControl();
987       if (EPC.getTargetTriple().getObjectFormat() == Triple::ELF)
988         return registerELFGraphInfo(*this, G);
989 
990       if (EPC.getTargetTriple().getObjectFormat() == Triple::MachO)
991         return registerMachOGraphInfo(*this, G);
992 
993       return make_error<StringError>("Unsupported object format for GOT/stub "
994                                      "registration",
995                                      inconvertibleErrorCode());
996     });
997 
998   if (ShowLinkGraph)
999     PassConfig.PostFixupPasses.push_back([](LinkGraph &G) -> Error {
1000       outs() << "Link graph \"" << G.getName() << "\" post-fixup:\n";
1001       G.dump(outs());
1002       return Error::success();
1003     });
1004 
1005   PassConfig.PrePrunePasses.push_back(
1006       [this](LinkGraph &G) { return applyHarnessPromotions(*this, G); });
1007 
1008   if (ShowSizes) {
1009     PassConfig.PrePrunePasses.push_back([this](LinkGraph &G) -> Error {
1010       SizeBeforePruning += computeTotalBlockSizes(G);
1011       return Error::success();
1012     });
1013     PassConfig.PostFixupPasses.push_back([this](LinkGraph &G) -> Error {
1014       SizeAfterFixups += computeTotalBlockSizes(G);
1015       return Error::success();
1016     });
1017   }
1018 
1019   if (ShowRelocatedSectionContents)
1020     PassConfig.PostFixupPasses.push_back([](LinkGraph &G) -> Error {
1021       outs() << "Relocated section contents for " << G.getName() << ":\n";
1022       dumpSectionContents(outs(), G);
1023       return Error::success();
1024     });
1025 }
1026 
1027 Expected<Session::FileInfo &> Session::findFileInfo(StringRef FileName) {
1028   auto FileInfoItr = FileInfos.find(FileName);
1029   if (FileInfoItr == FileInfos.end())
1030     return make_error<StringError>("file \"" + FileName + "\" not recognized",
1031                                    inconvertibleErrorCode());
1032   return FileInfoItr->second;
1033 }
1034 
1035 Expected<Session::MemoryRegionInfo &>
1036 Session::findSectionInfo(StringRef FileName, StringRef SectionName) {
1037   auto FI = findFileInfo(FileName);
1038   if (!FI)
1039     return FI.takeError();
1040   auto SecInfoItr = FI->SectionInfos.find(SectionName);
1041   if (SecInfoItr == FI->SectionInfos.end())
1042     return make_error<StringError>("no section \"" + SectionName +
1043                                        "\" registered for file \"" + FileName +
1044                                        "\"",
1045                                    inconvertibleErrorCode());
1046   return SecInfoItr->second;
1047 }
1048 
1049 Expected<Session::MemoryRegionInfo &>
1050 Session::findStubInfo(StringRef FileName, StringRef TargetName) {
1051   auto FI = findFileInfo(FileName);
1052   if (!FI)
1053     return FI.takeError();
1054   auto StubInfoItr = FI->StubInfos.find(TargetName);
1055   if (StubInfoItr == FI->StubInfos.end())
1056     return make_error<StringError>("no stub for \"" + TargetName +
1057                                        "\" registered for file \"" + FileName +
1058                                        "\"",
1059                                    inconvertibleErrorCode());
1060   return StubInfoItr->second;
1061 }
1062 
1063 Expected<Session::MemoryRegionInfo &>
1064 Session::findGOTEntryInfo(StringRef FileName, StringRef TargetName) {
1065   auto FI = findFileInfo(FileName);
1066   if (!FI)
1067     return FI.takeError();
1068   auto GOTInfoItr = FI->GOTEntryInfos.find(TargetName);
1069   if (GOTInfoItr == FI->GOTEntryInfos.end())
1070     return make_error<StringError>("no GOT entry for \"" + TargetName +
1071                                        "\" registered for file \"" + FileName +
1072                                        "\"",
1073                                    inconvertibleErrorCode());
1074   return GOTInfoItr->second;
1075 }
1076 
1077 bool Session::isSymbolRegistered(StringRef SymbolName) {
1078   return SymbolInfos.count(SymbolName);
1079 }
1080 
1081 Expected<Session::MemoryRegionInfo &>
1082 Session::findSymbolInfo(StringRef SymbolName, Twine ErrorMsgStem) {
1083   auto SymInfoItr = SymbolInfos.find(SymbolName);
1084   if (SymInfoItr == SymbolInfos.end())
1085     return make_error<StringError>(ErrorMsgStem + ": symbol " + SymbolName +
1086                                        " not found",
1087                                    inconvertibleErrorCode());
1088   return SymInfoItr->second;
1089 }
1090 
1091 } // end namespace llvm
1092 
1093 static Triple getFirstFileTriple() {
1094   static Triple FirstTT = []() {
1095     assert(!InputFiles.empty() && "InputFiles can not be empty");
1096     for (auto InputFile : InputFiles) {
1097       auto ObjBuffer =
1098           ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(InputFile)));
1099       switch (identify_magic(ObjBuffer->getBuffer())) {
1100       case file_magic::elf_relocatable:
1101       case file_magic::macho_object:
1102       case file_magic::coff_object: {
1103         auto Obj = ExitOnErr(
1104             object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef()));
1105         return Obj->makeTriple();
1106       }
1107       default:
1108         break;
1109       }
1110     }
1111     return Triple();
1112   }();
1113 
1114   return FirstTT;
1115 }
1116 
1117 static bool isOrcRuntimeSupported(const Triple &TT) {
1118   switch (TT.getObjectFormat()) {
1119   case Triple::MachO:
1120     switch (TT.getArch()) {
1121     case Triple::x86_64:
1122       return true;
1123     default:
1124       return false;
1125     }
1126   default:
1127     return false;
1128   }
1129 }
1130 
1131 static Error sanitizeArguments(const Triple &TT, const char *ArgV0) {
1132 
1133   // If we're in noexec mode and the user didn't explicitly specify
1134   // -use-orc-runtime then don't use it.
1135   if (NoExec && UseOrcRuntime.getNumOccurrences() == 0)
1136     UseOrcRuntime = false;
1137 
1138   // -noexec and --args should not be used together.
1139   if (NoExec && !InputArgv.empty())
1140     errs() << "Warning: --args passed to -noexec run will be ignored.\n";
1141 
1142   // Turn off UseOrcRuntime on platforms where it's not supported.
1143   if (UseOrcRuntime && !isOrcRuntimeSupported(TT)) {
1144     errs() << "Warning: Orc runtime not available for target platform. "
1145               "Use -use-orc-runtime=false to suppress this warning.\n";
1146     UseOrcRuntime = false;
1147   }
1148 
1149   // Set the entry point name if not specified.
1150   if (EntryPointName.empty())
1151     EntryPointName = TT.getObjectFormat() == Triple::MachO ? "_main" : "main";
1152 
1153   // If -slab-address is passed, require -slab-allocate and -noexec
1154   if (SlabAddress != ~0ULL) {
1155     if (SlabAllocateSizeString == "" || !NoExec)
1156       return make_error<StringError>(
1157           "-slab-address requires -slab-allocate and -noexec",
1158           inconvertibleErrorCode());
1159   }
1160 
1161   // Only one of -oop-executor and -oop-executor-connect can be used.
1162   if (!!OutOfProcessExecutor.getNumOccurrences() &&
1163       !!OutOfProcessExecutorConnect.getNumOccurrences())
1164     return make_error<StringError>(
1165         "Only one of -" + OutOfProcessExecutor.ArgStr + " and -" +
1166             OutOfProcessExecutorConnect.ArgStr + " can be specified",
1167         inconvertibleErrorCode());
1168 
1169   // If -oop-executor was used but no value was specified then use a sensible
1170   // default.
1171   if (!!OutOfProcessExecutor.getNumOccurrences() &&
1172       OutOfProcessExecutor.empty()) {
1173     SmallString<256> OOPExecutorPath(sys::fs::getMainExecutable(
1174         ArgV0, reinterpret_cast<void *>(&sanitizeArguments)));
1175     sys::path::remove_filename(OOPExecutorPath);
1176     sys::path::append(OOPExecutorPath, "llvm-jitlink-executor");
1177     OutOfProcessExecutor = OOPExecutorPath.str().str();
1178   }
1179 
1180   // If we're loading the Orc runtime then determine the path for it.
1181   if (UseOrcRuntime) {
1182     if (OrcRuntimePath.empty()) {
1183       SmallString<256> DefaultOrcRuntimePath(sys::fs::getMainExecutable(
1184           ArgV0, reinterpret_cast<void *>(&sanitizeArguments)));
1185       sys::path::remove_filename(
1186           DefaultOrcRuntimePath); // remove 'llvm-jitlink'
1187       while (!DefaultOrcRuntimePath.empty() &&
1188              DefaultOrcRuntimePath.back() == '/')
1189         DefaultOrcRuntimePath.pop_back();
1190       if (DefaultOrcRuntimePath.endswith("bin"))
1191         sys::path::remove_filename(DefaultOrcRuntimePath); // remove 'bin'
1192       sys::path::append(DefaultOrcRuntimePath,
1193                         ("lib/clang/" + Twine(LLVM_VERSION_MAJOR) + "." +
1194                          Twine(LLVM_VERSION_MINOR) + "." +
1195                          Twine(LLVM_VERSION_PATCH) +
1196                          "/lib/darwin/libclang_rt.orc_osx.a")
1197                             .str());
1198       OrcRuntimePath = DefaultOrcRuntimePath.str().str();
1199     }
1200   }
1201   return Error::success();
1202 }
1203 
1204 static void addPhonyExternalsGenerator(Session &S) {
1205   S.MainJD->addGenerator(std::make_unique<PhonyExternalsGenerator>());
1206 }
1207 
1208 static Error loadObjects(Session &S) {
1209   std::map<unsigned, JITDylib *> IdxToJLD;
1210 
1211   // First, set up JITDylibs.
1212   LLVM_DEBUG(dbgs() << "Creating JITDylibs...\n");
1213   {
1214     // Create a "main" JITLinkDylib.
1215     IdxToJLD[0] = S.MainJD;
1216     S.JDSearchOrder.push_back(S.MainJD);
1217     LLVM_DEBUG(dbgs() << "  0: " << S.MainJD->getName() << "\n");
1218 
1219     // Add any extra JITLinkDylibs from the command line.
1220     std::string JDNamePrefix("lib");
1221     for (auto JLDItr = JITLinkDylibs.begin(), JLDEnd = JITLinkDylibs.end();
1222          JLDItr != JLDEnd; ++JLDItr) {
1223       auto JD = S.ES.createJITDylib(JDNamePrefix + *JLDItr);
1224       if (!JD)
1225         return JD.takeError();
1226       unsigned JDIdx =
1227           JITLinkDylibs.getPosition(JLDItr - JITLinkDylibs.begin());
1228       IdxToJLD[JDIdx] = &*JD;
1229       S.JDSearchOrder.push_back(&*JD);
1230       LLVM_DEBUG(dbgs() << "  " << JDIdx << ": " << JD->getName() << "\n");
1231     }
1232 
1233     // Set every dylib to link against every other, in command line order.
1234     for (auto *JD : S.JDSearchOrder) {
1235       auto LookupFlags = JITDylibLookupFlags::MatchExportedSymbolsOnly;
1236       JITDylibSearchOrder LinkOrder;
1237       for (auto *JD2 : S.JDSearchOrder) {
1238         if (JD2 == JD)
1239           continue;
1240         LinkOrder.push_back(std::make_pair(JD2, LookupFlags));
1241       }
1242       JD->setLinkOrder(std::move(LinkOrder));
1243     }
1244   }
1245 
1246   LLVM_DEBUG(dbgs() << "Adding test harness objects...\n");
1247   for (auto HarnessFile : TestHarnesses) {
1248     LLVM_DEBUG(dbgs() << "  " << HarnessFile << "\n");
1249     auto ObjBuffer =
1250         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(HarnessFile)));
1251     ExitOnErr(S.ObjLayer.add(*S.MainJD, std::move(ObjBuffer)));
1252   }
1253 
1254   // Load each object into the corresponding JITDylib..
1255   LLVM_DEBUG(dbgs() << "Adding objects...\n");
1256   for (auto InputFileItr = InputFiles.begin(), InputFileEnd = InputFiles.end();
1257        InputFileItr != InputFileEnd; ++InputFileItr) {
1258     unsigned InputFileArgIdx =
1259         InputFiles.getPosition(InputFileItr - InputFiles.begin());
1260     const std::string &InputFile = *InputFileItr;
1261     auto &JD = *std::prev(IdxToJLD.lower_bound(InputFileArgIdx))->second;
1262     LLVM_DEBUG(dbgs() << "  " << InputFileArgIdx << ": \"" << InputFile
1263                       << "\" to " << JD.getName() << "\n";);
1264     auto ObjBuffer =
1265         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(InputFile)));
1266 
1267     auto Magic = identify_magic(ObjBuffer->getBuffer());
1268     if (Magic == file_magic::archive ||
1269         Magic == file_magic::macho_universal_binary)
1270       JD.addGenerator(ExitOnErr(StaticLibraryDefinitionGenerator::Load(
1271           S.ObjLayer, InputFile.c_str(),
1272           S.ES.getExecutorProcessControl().getTargetTriple())));
1273     else
1274       ExitOnErr(S.ObjLayer.add(JD, std::move(ObjBuffer)));
1275   }
1276 
1277   // Define absolute symbols.
1278   LLVM_DEBUG(dbgs() << "Defining absolute symbols...\n");
1279   for (auto AbsDefItr = AbsoluteDefs.begin(), AbsDefEnd = AbsoluteDefs.end();
1280        AbsDefItr != AbsDefEnd; ++AbsDefItr) {
1281     unsigned AbsDefArgIdx =
1282       AbsoluteDefs.getPosition(AbsDefItr - AbsoluteDefs.begin());
1283     auto &JD = *std::prev(IdxToJLD.lower_bound(AbsDefArgIdx))->second;
1284 
1285     StringRef AbsDefStmt = *AbsDefItr;
1286     size_t EqIdx = AbsDefStmt.find_first_of('=');
1287     if (EqIdx == StringRef::npos)
1288       return make_error<StringError>("Invalid absolute define \"" + AbsDefStmt +
1289                                      "\". Syntax: <name>=<addr>",
1290                                      inconvertibleErrorCode());
1291     StringRef Name = AbsDefStmt.substr(0, EqIdx).trim();
1292     StringRef AddrStr = AbsDefStmt.substr(EqIdx + 1).trim();
1293 
1294     uint64_t Addr;
1295     if (AddrStr.getAsInteger(0, Addr))
1296       return make_error<StringError>("Invalid address expression \"" + AddrStr +
1297                                      "\" in absolute define \"" + AbsDefStmt +
1298                                      "\"",
1299                                      inconvertibleErrorCode());
1300     JITEvaluatedSymbol AbsDef(Addr, JITSymbolFlags::Exported);
1301     if (auto Err = JD.define(absoluteSymbols({{S.ES.intern(Name), AbsDef}})))
1302       return Err;
1303 
1304     // Register the absolute symbol with the session symbol infos.
1305     S.SymbolInfos[Name] = {ArrayRef<char>(), Addr};
1306   }
1307 
1308   LLVM_DEBUG({
1309     dbgs() << "Dylib search order is [ ";
1310     for (auto *JD : S.JDSearchOrder)
1311       dbgs() << JD->getName() << " ";
1312     dbgs() << "]\n";
1313   });
1314 
1315   return Error::success();
1316 }
1317 
1318 static Error runChecks(Session &S) {
1319   const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
1320 
1321   if (CheckFiles.empty())
1322     return Error::success();
1323 
1324   LLVM_DEBUG(dbgs() << "Running checks...\n");
1325 
1326   auto TripleName = TT.str();
1327   std::string ErrorStr;
1328   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, ErrorStr);
1329   if (!TheTarget)
1330     ExitOnErr(make_error<StringError>("Error accessing target '" + TripleName +
1331                                           "': " + ErrorStr,
1332                                       inconvertibleErrorCode()));
1333 
1334   std::unique_ptr<MCSubtargetInfo> STI(
1335       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
1336   if (!STI)
1337     ExitOnErr(
1338         make_error<StringError>("Unable to create subtarget for " + TripleName,
1339                                 inconvertibleErrorCode()));
1340 
1341   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
1342   if (!MRI)
1343     ExitOnErr(make_error<StringError>("Unable to create target register info "
1344                                       "for " +
1345                                           TripleName,
1346                                       inconvertibleErrorCode()));
1347 
1348   MCTargetOptions MCOptions;
1349   std::unique_ptr<MCAsmInfo> MAI(
1350       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
1351   if (!MAI)
1352     ExitOnErr(make_error<StringError>("Unable to create target asm info " +
1353                                           TripleName,
1354                                       inconvertibleErrorCode()));
1355 
1356   MCContext Ctx(Triple(TripleName), MAI.get(), MRI.get(), STI.get());
1357 
1358   std::unique_ptr<MCDisassembler> Disassembler(
1359       TheTarget->createMCDisassembler(*STI, Ctx));
1360   if (!Disassembler)
1361     ExitOnErr(make_error<StringError>("Unable to create disassembler for " +
1362                                           TripleName,
1363                                       inconvertibleErrorCode()));
1364 
1365   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1366 
1367   std::unique_ptr<MCInstPrinter> InstPrinter(
1368       TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
1369 
1370   auto IsSymbolValid = [&S](StringRef Symbol) {
1371     return S.isSymbolRegistered(Symbol);
1372   };
1373 
1374   auto GetSymbolInfo = [&S](StringRef Symbol) {
1375     return S.findSymbolInfo(Symbol, "Can not get symbol info");
1376   };
1377 
1378   auto GetSectionInfo = [&S](StringRef FileName, StringRef SectionName) {
1379     return S.findSectionInfo(FileName, SectionName);
1380   };
1381 
1382   auto GetStubInfo = [&S](StringRef FileName, StringRef SectionName) {
1383     return S.findStubInfo(FileName, SectionName);
1384   };
1385 
1386   auto GetGOTInfo = [&S](StringRef FileName, StringRef SectionName) {
1387     return S.findGOTEntryInfo(FileName, SectionName);
1388   };
1389 
1390   RuntimeDyldChecker Checker(
1391       IsSymbolValid, GetSymbolInfo, GetSectionInfo, GetStubInfo, GetGOTInfo,
1392       TT.isLittleEndian() ? support::little : support::big, Disassembler.get(),
1393       InstPrinter.get(), dbgs());
1394 
1395   std::string CheckLineStart = "# " + CheckName + ":";
1396   for (auto &CheckFile : CheckFiles) {
1397     auto CheckerFileBuf =
1398         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(CheckFile)));
1399     if (!Checker.checkAllRulesInBuffer(CheckLineStart, &*CheckerFileBuf))
1400       ExitOnErr(make_error<StringError>(
1401           "Some checks in " + CheckFile + " failed", inconvertibleErrorCode()));
1402   }
1403 
1404   return Error::success();
1405 }
1406 
1407 static void dumpSessionStats(Session &S) {
1408   if (!ShowSizes)
1409     return;
1410   if (UseOrcRuntime)
1411     outs() << "Note: Session stats include runtime and entry point lookup, but "
1412               "not JITDylib initialization/deinitialization.\n";
1413   if (ShowSizes)
1414     outs() << "  Total size of all blocks before pruning: "
1415            << S.SizeBeforePruning
1416            << "\n  Total size of all blocks after fixups: " << S.SizeAfterFixups
1417            << "\n";
1418 }
1419 
1420 static Expected<JITEvaluatedSymbol> getMainEntryPoint(Session &S) {
1421   return S.ES.lookup(S.JDSearchOrder, EntryPointName);
1422 }
1423 
1424 static Expected<JITEvaluatedSymbol> getOrcRuntimeEntryPoint(Session &S) {
1425   std::string RuntimeEntryPoint = "__orc_rt_run_program_wrapper";
1426   const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
1427   if (TT.getObjectFormat() == Triple::MachO)
1428     RuntimeEntryPoint = '_' + RuntimeEntryPoint;
1429   return S.ES.lookup(S.JDSearchOrder, RuntimeEntryPoint);
1430 }
1431 
1432 static Expected<int> runWithRuntime(Session &S,
1433                                     JITTargetAddress EntryPointAddress) {
1434   StringRef DemangledEntryPoint = EntryPointName;
1435   const auto &TT = S.ES.getExecutorProcessControl().getTargetTriple();
1436   if (TT.getObjectFormat() == Triple::MachO &&
1437       DemangledEntryPoint.front() == '_')
1438     DemangledEntryPoint = DemangledEntryPoint.drop_front();
1439   using SPSRunProgramSig =
1440       int64_t(SPSString, SPSString, SPSSequence<SPSString>);
1441   int64_t Result;
1442   if (auto Err = S.ES.callSPSWrapper<SPSRunProgramSig>(
1443           EntryPointAddress, Result, S.MainJD->getName(), DemangledEntryPoint,
1444           static_cast<std::vector<std::string> &>(InputArgv)))
1445     return std::move(Err);
1446   return Result;
1447 }
1448 
1449 static Expected<int> runWithoutRuntime(Session &S,
1450                                        JITTargetAddress EntryPointAddress) {
1451   return S.ES.getExecutorProcessControl().runAsMain(EntryPointAddress,
1452                                                     InputArgv);
1453 }
1454 
1455 namespace {
1456 struct JITLinkTimers {
1457   TimerGroup JITLinkTG{"llvm-jitlink timers", "timers for llvm-jitlink phases"};
1458   Timer LoadObjectsTimer{"load", "time to load/add object files", JITLinkTG};
1459   Timer LinkTimer{"link", "time to link object files", JITLinkTG};
1460   Timer RunTimer{"run", "time to execute jitlink'd code", JITLinkTG};
1461 };
1462 } // namespace
1463 
1464 int main(int argc, char *argv[]) {
1465   InitLLVM X(argc, argv);
1466 
1467   InitializeAllTargetInfos();
1468   InitializeAllTargetMCs();
1469   InitializeAllDisassemblers();
1470 
1471   cl::HideUnrelatedOptions({&JITLinkCategory, &getColorCategory()});
1472   cl::ParseCommandLineOptions(argc, argv, "llvm jitlink tool");
1473   ExitOnErr.setBanner(std::string(argv[0]) + ": ");
1474 
1475   /// If timers are enabled, create a JITLinkTimers instance.
1476   std::unique_ptr<JITLinkTimers> Timers =
1477       ShowTimes ? std::make_unique<JITLinkTimers>() : nullptr;
1478 
1479   ExitOnErr(sanitizeArguments(getFirstFileTriple(), argv[0]));
1480 
1481   auto S = ExitOnErr(Session::Create(getFirstFileTriple()));
1482 
1483   {
1484     TimeRegion TR(Timers ? &Timers->LoadObjectsTimer : nullptr);
1485     ExitOnErr(loadObjects(*S));
1486   }
1487 
1488   if (PhonyExternals)
1489     addPhonyExternalsGenerator(*S);
1490 
1491   if (ShowInitialExecutionSessionState)
1492     S->ES.dump(outs());
1493 
1494   JITEvaluatedSymbol EntryPoint = 0;
1495   {
1496     TimeRegion TR(Timers ? &Timers->LinkTimer : nullptr);
1497     // Find the entry-point function unconditionally, since we want to force
1498     // it to be materialized to collect stats.
1499     EntryPoint = ExitOnErr(getMainEntryPoint(*S));
1500 
1501     // If we're running with the ORC runtime then replace the entry-point
1502     // with the __orc_rt_run_program symbol.
1503     if (UseOrcRuntime)
1504       EntryPoint = ExitOnErr(getOrcRuntimeEntryPoint(*S));
1505   }
1506 
1507   if (ShowAddrs)
1508     S->dumpSessionInfo(outs());
1509 
1510   ExitOnErr(runChecks(*S));
1511 
1512   dumpSessionStats(*S);
1513 
1514   if (NoExec)
1515     return 0;
1516 
1517   int Result = 0;
1518   {
1519     LLVM_DEBUG(dbgs() << "Running \"" << EntryPointName << "\"...\n");
1520     TimeRegion TR(Timers ? &Timers->RunTimer : nullptr);
1521     if (UseOrcRuntime)
1522       Result = ExitOnErr(runWithRuntime(*S, EntryPoint.getAddress()));
1523     else
1524       Result = ExitOnErr(runWithoutRuntime(*S, EntryPoint.getAddress()));
1525   }
1526 
1527   // Destroy the session.
1528   S.reset();
1529 
1530   // If the executing code set a test result override then use that.
1531   if (UseTestResultOverride)
1532     Result = TestResultOverride;
1533 
1534   return Result;
1535 }
1536