LLVM 24.0.0git
SimpleRemoteEPC.cpp
Go to the documentation of this file.
1//===------- SimpleRemoteEPC.cpp -- Simple remote executor control --------===//
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
16
17#define DEBUG_TYPE "orc"
18
19namespace llvm {
20namespace orc {
21
23#ifndef NDEBUG
24 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
25 assert(Disconnected && "Destroyed without disconnection");
26#endif // NDEBUG
27}
28
31 int64_t Result = 0;
33 RunAsMainAddr, Result, MainFnAddr, Args))
34 return std::move(Err);
35 return Result;
36}
37
39 IncomingWFRHandler OnComplete,
40 ArrayRef<char> ArgBuffer) {
41 uint64_t SeqNo;
42 {
43 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
44 SeqNo = getNextSeqNo();
45 assert(!PendingCallWrapperResults.count(SeqNo) && "SeqNo already in use");
46 PendingCallWrapperResults[SeqNo] = std::move(OnComplete);
47 }
48
49 if (auto Err = sendMessage(SimpleRemoteEPCOpcode::CallWrapper, SeqNo,
50 WrapperFnAddr, ArgBuffer)) {
52
53 // We just registered OnComplete, but there may be a race between this
54 // thread returning from sendMessage and handleDisconnect being called from
55 // the transport's listener thread. If handleDisconnect gets there first
56 // then it will have failed 'H' for us. If we get there first (or if
57 // handleDisconnect already ran) then we need to take care of it.
58 {
59 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
60 auto I = PendingCallWrapperResults.find(SeqNo);
61 if (I != PendingCallWrapperResults.end()) {
62 H = std::move(I->second);
63 PendingCallWrapperResults.erase(I);
64 }
65 }
66
67 if (H)
69
70 getExecutionSession().reportError(std::move(Err));
71 }
72}
73
78
82 if (!DM)
83 return DM.takeError();
84 return std::make_unique<EPCGenericDylibManager>(std::move(*DM));
85}
86
91
93 T->disconnect();
94 D->shutdown();
95 std::unique_lock<std::mutex> Lock(SimpleRemoteEPCMutex);
96 DisconnectCV.wait(Lock, [this] { return Disconnected; });
97 return std::move(DisconnectErr);
98}
99
102 ExecutorAddr TagAddr,
104
105 LLVM_DEBUG({
106 dbgs() << "SimpleRemoteEPC::handleMessage: opc = ";
107 switch (OpC) {
109 dbgs() << "Setup";
110 assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
111 assert(!TagAddr && "Non-zero TagAddr for Setup?");
112 break;
114 dbgs() << "Hangup";
115 assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
116 assert(!TagAddr && "Non-zero TagAddr for Hangup?");
117 break;
119 dbgs() << "Result";
120 assert(!TagAddr && "Non-zero TagAddr for Result?");
121 break;
123 dbgs() << "CallWrapper";
124 break;
125 }
126 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
127 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
128 << " bytes\n";
129 });
130
131 using UT = std::underlying_type_t<SimpleRemoteEPCOpcode>;
132 if (static_cast<UT>(OpC) > static_cast<UT>(SimpleRemoteEPCOpcode::LastOpC))
133 return make_error<StringError>("Unexpected opcode",
135
136 switch (OpC) {
138 if (auto Err = handleSetup(SeqNo, TagAddr, std::move(ArgBytes)))
139 return std::move(Err);
140 break;
142 T->disconnect();
143 if (auto Err = handleHangup(std::move(ArgBytes)))
144 return std::move(Err);
145 return EndSession;
147 if (auto Err = handleResult(SeqNo, TagAddr, std::move(ArgBytes)))
148 return std::move(Err);
149 break;
151 handleCallWrapper(SeqNo, TagAddr, std::move(ArgBytes));
152 break;
153 }
154 return ContinueSession;
155}
156
158 LLVM_DEBUG({
159 dbgs() << "SimpleRemoteEPC::handleDisconnect: "
160 << (Err ? "failure" : "success") << "\n";
161 });
162
163 PendingCallWrapperResultsMap TmpPending;
164
165 {
166 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
167 std::swap(TmpPending, PendingCallWrapperResults);
168 }
169
170 for (auto &KV : TmpPending)
171 KV.second(
173
174 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
175 DisconnectErr = joinErrors(std::move(DisconnectErr), std::move(Err));
176 Disconnected = true;
177 DisconnectCV.notify_all();
178}
179
183 if (auto Err = SREPC.getBootstrapSymbols(
184 {{SAs.Allocator, rt::SimpleExecutorMemoryManagerInstanceName},
185 {SAs.Reserve, rt::SimpleExecutorMemoryManagerReserveWrapperName},
186 {SAs.Initialize,
187 rt::SimpleExecutorMemoryManagerInitializeWrapperName},
188 {SAs.Release, rt::SimpleExecutorMemoryManagerReleaseWrapperName}}))
189 return std::move(Err);
190
191 return std::make_unique<EPCGenericJITLinkMemoryManager>(SREPC, SAs);
192}
193
194Error SimpleRemoteEPC::sendMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo,
195 ExecutorAddr TagAddr,
196 ArrayRef<char> ArgBytes) {
197 assert(OpC != SimpleRemoteEPCOpcode::Setup &&
198 "SimpleRemoteEPC sending Setup message? That's the wrong direction.");
199
200 LLVM_DEBUG({
201 dbgs() << "SimpleRemoteEPC::sendMessage: opc = ";
202 switch (OpC) {
203 case SimpleRemoteEPCOpcode::Hangup:
204 dbgs() << "Hangup";
205 assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
206 assert(!TagAddr && "Non-zero TagAddr for Hangup?");
207 break;
208 case SimpleRemoteEPCOpcode::Result:
209 dbgs() << "Result";
210 assert(!TagAddr && "Non-zero TagAddr for Result?");
211 break;
212 case SimpleRemoteEPCOpcode::CallWrapper:
213 dbgs() << "CallWrapper";
214 break;
215 default:
216 llvm_unreachable("Invalid opcode");
217 }
218 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
219 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
220 << " bytes\n";
221 });
222 auto Err = T->sendMessage(OpC, SeqNo, TagAddr, ArgBytes);
223 LLVM_DEBUG({
224 if (Err)
225 dbgs() << " \\--> SimpleRemoteEPC::sendMessage failed\n";
226 });
227 return Err;
228}
229
230Error SimpleRemoteEPC::handleSetup(uint64_t SeqNo, ExecutorAddr TagAddr,
231 shared::WrapperFunctionBuffer ArgBytes) {
232 if (SeqNo != 0)
233 return make_error<StringError>("Setup packet SeqNo not zero",
235
236 if (TagAddr)
237 return make_error<StringError>("Setup packet TagAddr not zero",
239
240 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
241 auto I = PendingCallWrapperResults.find(0);
242 assert(PendingCallWrapperResults.size() == 1 &&
243 I != PendingCallWrapperResults.end() &&
244 "Setup message handler not connectly set up");
245 auto SetupMsgHandler = std::move(I->second);
246 PendingCallWrapperResults.erase(I);
247
248 auto WFR =
249 shared::WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
250 SetupMsgHandler(std::move(WFR));
251 return Error::success();
252}
253
254Error SimpleRemoteEPC::setup() {
255 using namespace SimpleRemoteEPCDefaultBootstrapSymbolNames;
256
257 std::promise<MSVCPExpected<SimpleRemoteEPCExecutorInfo>> EIP;
258 auto EIF = EIP.get_future();
259
260 // Prepare a handler for the setup packet.
261 PendingCallWrapperResults[0] =
262 RunInPlace()(
263 [&](shared::WrapperFunctionBuffer SetupMsgBytes) {
264 if (const char *ErrMsg = SetupMsgBytes.getOutOfBandError()) {
265 EIP.set_value(
267 return;
268 }
269 using SPSSerialize =
270 shared::SPSArgList<shared::SPSSimpleRemoteEPCExecutorInfo>;
271 shared::SPSInputBuffer IB(SetupMsgBytes.data(), SetupMsgBytes.size());
272 SimpleRemoteEPCExecutorInfo EI;
273 if (SPSSerialize::deserialize(IB, EI))
274 EIP.set_value(EI);
275 else
276 EIP.set_value(make_error<StringError>(
277 "Could not deserialize setup message", inconvertibleErrorCode()));
278 });
279
280 // Start the transport.
281 if (auto Err = T->start())
282 return Err;
283
284 // Wait for setup packet to arrive.
285 auto EI = EIF.get();
286 if (!EI) {
287 T->disconnect();
288 return EI.takeError();
289 }
290
291 LLVM_DEBUG({
292 dbgs() << "SimpleRemoteEPC received setup message:\n"
293 << " Triple: " << EI->TargetTriple << "\n"
294 << " Page size: " << EI->PageSize << "\n"
295 << " Bootstrap map" << (EI->BootstrapMap.empty() ? " empty" : ":")
296 << "\n";
297 for (const auto &KV : EI->BootstrapMap)
298 dbgs() << " " << KV.first() << ": " << KV.second.size()
299 << "-byte SPS encoded buffer\n";
300 dbgs() << " Bootstrap symbols"
301 << (EI->BootstrapSymbols.empty() ? " empty" : ":") << "\n";
302 for (const auto &KV : EI->BootstrapSymbols)
303 dbgs() << " " << KV.first() << ": " << KV.second << "\n";
304 });
305 TargetTriple = Triple(EI->TargetTriple);
306 PageSize = EI->PageSize;
307 BootstrapMap = std::move(EI->BootstrapMap);
308 BootstrapSymbols = std::move(EI->BootstrapSymbols);
309
310 BootstrapSymbols[rt::DispatchName] = BootstrapSymbols[DispatchFnName];
311 BootstrapSymbols[rt::DispatchCtxName] =
312 BootstrapSymbols[ExecutorSessionObjectName];
313
314 if (auto Err =
315 getBootstrapSymbols({{RunAsMainAddr, rt::sps::CallMainCIName}}))
316 return Err;
317
318 return Error::success();
319}
320
321Error SimpleRemoteEPC::handleResult(uint64_t SeqNo, ExecutorAddr TagAddr,
322 shared::WrapperFunctionBuffer ArgBytes) {
323 IncomingWFRHandler SendResult;
324
325 if (TagAddr)
326 return make_error<StringError>("Unexpected TagAddr in result message",
328
329 {
330 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
331 auto I = PendingCallWrapperResults.find(SeqNo);
332 if (I == PendingCallWrapperResults.end())
333 return make_error<StringError>("No call for sequence number " +
334 Twine(SeqNo),
336 SendResult = std::move(I->second);
337 PendingCallWrapperResults.erase(I);
338 releaseSeqNo(SeqNo);
339 }
340
341 auto WFR =
342 shared::WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
343 SendResult(std::move(WFR));
344 return Error::success();
345}
346
347void SimpleRemoteEPC::handleCallWrapper(
348 uint64_t RemoteSeqNo, ExecutorAddr TagAddr,
349 shared::WrapperFunctionBuffer ArgBytes) {
350 assert(ES && "No ExecutionSession attached");
351 D->dispatch(makeGenericNamedTask(
352 [this, RemoteSeqNo, TagAddr, ArgBytes = std::move(ArgBytes)]() mutable {
353 ES->runJITDispatchHandler(
354 [this, RemoteSeqNo](shared::WrapperFunctionBuffer WFR) {
355 if (auto Err =
356 sendMessage(SimpleRemoteEPCOpcode::Result, RemoteSeqNo,
357 ExecutorAddr(), {WFR.data(), WFR.size()}))
358 getExecutionSession().reportError(std::move(Err));
359 },
360 TagAddr, std::move(ArgBytes));
361 },
362 "callWrapper task"));
363}
364
365Error SimpleRemoteEPC::handleHangup(shared::WrapperFunctionBuffer ArgBytes) {
366 using namespace llvm::orc::shared;
367 auto WFR = WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
368 if (const char *ErrMsg = WFR.getOutOfBandError())
370
372 SPSInputBuffer IB(WFR.data(), WFR.size());
373 if (!SPSArgList<SPSError>::deserialize(IB, Info))
374 return make_error<StringError>("Could not deserialize hangup info",
376 return fromSPSSerializable(std::move(Info));
377}
378
379} // end namespace orc
380} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
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)
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
#define T
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Expected< EPCGenericDylibManager > Create(JITDylib &JD)
Create an EPCGenericDylibManager for the ORC runtime's NativeDylibManager interface,...
static Expected< std::unique_ptr< EPCGenericJITLinkMemoryManager > > Create(JITDylib &JD, rt::SimpleExecutorMemoryManagerSymbolNames SNs=rt::orc_rt_SimpleNativeMemoryMapSPSSymbols)
Create an EPCGenericJITLinkMemoryManager using the given implementation symbol names.
static Expected< std::unique_ptr< MemoryAccess > > Create(ExecutionSession &ES)
Create an EPCGenericMemoryAccess instance that reaches the memory-access wrappers in ES's bootstrap J...
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1267
Represents an address in the executor process.
A handler or incoming WrapperFunctionBuffers – either return values from callWrapper* calls,...
std::unique_ptr< TaskDispatcher > D
Error callSPSWrapper(ExecutorAddr WrapperFnAddr, WrapperCallArgTs &&...WrapperCallArgs)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Error getBootstrapSymbols(ArrayRef< std::pair< ExecutorAddr &, StringRef > > Pairs) const
For each (ExecutorAddr&, StringRef) pair, looks up the string in the bootstrap symbols map and writes...
ExecutionSession & getExecutionSession()
Return the ExecutionSession associated with this instance.
void handleDisconnect(Error Err) override
Handle a disconnection from the underlying transport.
Expected< std::unique_ptr< MemoryAccess > > createDefaultMemoryAccess() override
Create a default MemoryAccess for the target process.
Expected< int32_t > runAsMain(ExecutorAddr MainFnAddr, ArrayRef< std::string > Args) override
Run function with a main-like signature.
Expected< std::unique_ptr< jitlink::JITLinkMemoryManager > > createDefaultMemoryManager() override
Create a default JITLinkMemoryManager for the target process.
Expected< HandleMessageAction > handleMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo, ExecutorAddr TagAddr, shared::WrapperFunctionBuffer ArgBytes) override
Handle receipt of a message.
Expected< std::unique_ptr< DylibManager > > createDefaultDylibMgr() override
Create a default DylibManager for the target process.
Error disconnect() override
Disconnect from the target process.
void callWrapperAsync(ExecutorAddr WrapperFnAddr, IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer) override
Run a wrapper function in the executor.
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
size_t size() const
Returns the size of the data contained in this instance.
static WrapperFunctionBuffer createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Error fromSPSSerializable(SPSSerializableError BSE)
std::unique_ptr< GenericNamedTask > makeGenericNamedTask(FnT &&Fn, std::string Desc)
Create a generic named task from a std::string description.
This is an optimization pass for GlobalISel generic memory operations.
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:94
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
Symbol addresses for memory management implementation.