LLVM 22.0.0git
SelfExecutorProcessControl.cpp
Go to the documentation of this file.
1//===------ SelfExecutorProcessControl.cpp -- EPC for in-process JITs -----===//
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
10
17
18#define DEBUG_TYPE "orc"
19
20namespace llvm::orc {
21
23 std::shared_ptr<SymbolStringPool> SSP, std::unique_ptr<TaskDispatcher> D,
24 Triple TargetTriple, unsigned PageSize,
25 std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr)
27 IPMA(TargetTriple.isArch64Bit()) {
28
29 OwnedMemMgr = std::move(MemMgr);
30 if (!OwnedMemMgr)
31 OwnedMemMgr = std::make_unique<jitlink::InProcessMemoryManager>(
33
34 this->TargetTriple = std::move(TargetTriple);
35 this->PageSize = PageSize;
36 this->MemMgr = OwnedMemMgr.get();
37 this->MemAccess = &IPMA;
38 this->DylibMgr = this;
39 this->JDI = {ExecutorAddr::fromPtr(jitDispatchViaWrapperFunctionManager),
41
42 if (this->TargetTriple.isOSBinFormatMachO())
43 GlobalManglingPrefix = '_';
44
46
47#ifdef __APPLE__
48 // FIXME: Don't add an UnwindInfoManager by default -- it's redundant when
49 // the ORC runtime is loaded. We'll need a way to document this and
50 // allow clients to choose.
53#endif // __APPLE__
54}
55
58 std::shared_ptr<SymbolStringPool> SSP, std::unique_ptr<TaskDispatcher> D,
59 std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr) {
60
61 if (!SSP)
62 SSP = std::make_shared<SymbolStringPool>();
63
64 if (!D)
65 D = std::make_unique<InPlaceTaskDispatcher>();
66
68 if (!PageSize)
69 return PageSize.takeError();
70
72
73 return std::make_unique<SelfExecutorProcessControl>(
74 std::move(SSP), std::move(D), std::move(TT), *PageSize,
75 std::move(MemMgr));
76}
77
79SelfExecutorProcessControl::loadDylib(const char *DylibPath) {
80 std::string ErrMsg;
81 auto Dylib = sys::DynamicLibrary::getPermanentLibrary(DylibPath, &ErrMsg);
82 if (!Dylib.isValid())
83 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
84 return ExecutorAddr::fromPtr(Dylib.getOSSpecificHandle());
85}
86
87void SelfExecutorProcessControl::lookupSymbolsAsync(
90 std::vector<tpctypes::LookupResult> R;
91
92 for (auto &Elem : Request) {
93 sys::DynamicLibrary Dylib(Elem.Handle.toPtr<void *>());
94 R.push_back(std::vector<ExecutorSymbolDef>());
95 for (auto &KV : Elem.Symbols) {
96 auto &Sym = KV.first;
97 std::string Tmp((*Sym).data() + !!GlobalManglingPrefix,
98 (*Sym).size() - !!GlobalManglingPrefix);
99 void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str());
100 if (!Addr && KV.second == SymbolLookupFlags::RequiredSymbol) {
101 // FIXME: Collect all failing symbols before erroring out.
102 SymbolNameVector MissingSymbols;
103 MissingSymbols.push_back(Sym);
104 return Complete(
105 make_error<SymbolsNotFound>(SSP, std::move(MissingSymbols)));
106 }
107 // FIXME: determine accurate JITSymbolFlags.
108 R.back().push_back(
110 }
111 }
112
113 Complete(std::move(R));
114}
115
116Expected<int32_t>
119 using MainTy = int (*)(int, char *[]);
120 return orc::runAsMain(MainFnAddr.toPtr<MainTy>(), Args);
121}
122
125 using VoidTy = int (*)();
126 return orc::runAsVoidFunction(VoidFnAddr.toPtr<VoidTy>());
127}
128
131 using IntTy = int (*)(int);
132 return orc::runAsIntFunction(IntFnAddr.toPtr<IntTy>(), Arg);
133}
134
136 IncomingWFRHandler SendResult,
137 ArrayRef<char> ArgBuffer) {
138 using WrapperFnTy =
139 shared::CWrapperFunctionResult (*)(const char *Data, size_t Size);
140 auto *WrapperFn = WrapperFnAddr.toPtr<WrapperFnTy>();
141 SendResult(WrapperFn(ArgBuffer.data(), ArgBuffer.size()));
142}
143
145 D->shutdown();
146 return Error::success();
147}
148
150SelfExecutorProcessControl::jitDispatchViaWrapperFunctionManager(
151 void *Ctx, const void *FnTag, const char *Data, size_t Size) {
152
153 LLVM_DEBUG({
154 dbgs() << "jit-dispatch call with tag " << FnTag << " and " << Size
155 << " byte payload.\n";
156 });
157
158 std::promise<shared::WrapperFunctionResult> ResultP;
159 auto ResultF = ResultP.get_future();
160 static_cast<SelfExecutorProcessControl *>(Ctx)
163 [ResultP = std::move(ResultP)](
164 shared::WrapperFunctionResult Result) mutable {
165 ResultP.set_value(std::move(Result));
166 },
167 ExecutorAddr::fromPtr(FnTag), {Data, Size});
168
169 return ResultF.get().release();
170}
171
172} // namespace llvm::orc
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
uint64_t Addr
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
Provides a library for accessing information about this process and other processes on the operating ...
#define LLVM_DEBUG(...)
Definition: Debug.h:119
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
const T * data() const
Definition: ArrayRef.h:144
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:779
unique_function< void(Expected< std::vector< tpctypes::LookupResult > >)> SymbolLookupCompleteFn
Definition: DylibManager.h:62
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
Definition: Core.cpp:1937
Represents an address in the executor process.
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
std::enable_if_t< std::is_pointer< T >::value, T > toPtr(WrapFn &&Wrap=WrapFn()) const
Cast this ExecutorAddr to a pointer of the given type.
A handler or incoming WrapperFunctionResults – either return values from callWrapper* calls,...
ExecutorProcessControl supports interaction with a JIT target process.
std::unique_ptr< TaskDispatcher > D
std::shared_ptr< SymbolStringPool > SSP
StringMap< ExecutorAddr > BootstrapSymbols
StringMap< std::vector< char > > BootstrapMap
jitlink::JITLinkMemoryManager * MemMgr
ExecutionSession & getExecutionSession()
Return the ExecutionSession associated with this instance.
SelfExecutorProcessControl(std::shared_ptr< SymbolStringPool > SSP, std::unique_ptr< TaskDispatcher > D, Triple TargetTriple, unsigned PageSize, std::unique_ptr< jitlink::JITLinkMemoryManager > MemMgr)
Error disconnect() override
Disconnect from the target process.
Expected< int32_t > runAsVoidFunction(ExecutorAddr VoidFnAddr) override
Run function with a int (*)(void) signature.
Expected< int32_t > runAsMain(ExecutorAddr MainFnAddr, ArrayRef< std::string > Args) override
Run function with a main-like signature.
void callWrapperAsync(ExecutorAddr WrapperFnAddr, IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer) override
Run a wrapper function in the executor.
static Expected< std::unique_ptr< SelfExecutorProcessControl > > Create(std::shared_ptr< SymbolStringPool > SSP=nullptr, std::unique_ptr< TaskDispatcher > D=nullptr, std::unique_ptr< jitlink::JITLinkMemoryManager > MemMgr=nullptr)
Create a SelfExecutorProcessControl with the given symbol string pool and memory manager.
Expected< int32_t > runAsIntFunction(ExecutorAddr IntFnAddr, int Arg) override
Run function with a int (*)(int) signature.
static LLVM_ABI bool TryEnable()
If the libunwind find-dynamic-unwind-info callback registration APIs are available then this method w...
static LLVM_ABI void addBootstrapSymbols(StringMap< ExecutorAddr > &M)
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
static LLVM_ABI DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path using the library load operatio...
static LLVM_ABI Expected< unsigned > getPageSize()
Get the process's page size.
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
Definition: Process.h:62
LLVM_ABI void addDefaultBootstrapValuesForHostProcess(StringMap< std::vector< char > > &BootstrapMap, StringMap< ExecutorAddr > &BootstrapSymbols)
LLVM_ABI int runAsVoidFunction(int(*Func)(void))
LLVM_ABI int runAsIntFunction(int(*Func)(int), int Arg)
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
LLVM_ABI int runAsMain(int(*Main)(int, char *[]), ArrayRef< std::string > Args, std::optional< StringRef > ProgramName=std::nullopt)
Run a main function, returning the result.
LLVM_ABI std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition: Host.cpp:2434
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856