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