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
180Error SimpleRemoteEPC::sendMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo,
181 ExecutorAddr TagAddr,
182 ArrayRef<char> ArgBytes) {
184 "SimpleRemoteEPC sending Setup message? That's the wrong direction.");
185
186 LLVM_DEBUG({
187 dbgs() << "SimpleRemoteEPC::sendMessage: opc = ";
188 switch (OpC) {
190 dbgs() << "Hangup";
191 assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
192 assert(!TagAddr && "Non-zero TagAddr for Hangup?");
193 break;
195 dbgs() << "Result";
196 assert(!TagAddr && "Non-zero TagAddr for Result?");
197 break;
199 dbgs() << "CallWrapper";
200 break;
201 default:
202 llvm_unreachable("Invalid opcode");
203 }
204 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
205 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
206 << " bytes\n";
207 });
208 auto Err = T->sendMessage(OpC, SeqNo, TagAddr, ArgBytes);
209 LLVM_DEBUG({
210 if (Err)
211 dbgs() << " \\--> SimpleRemoteEPC::sendMessage failed\n";
212 });
213 return Err;
214}
215
216Error SimpleRemoteEPC::handleSetup(uint64_t SeqNo, ExecutorAddr TagAddr,
218 if (SeqNo != 0)
219 return make_error<StringError>("Setup packet SeqNo not zero",
221
222 if (TagAddr)
223 return make_error<StringError>("Setup packet TagAddr not zero",
225
226 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
227 auto I = PendingCallWrapperResults.find(0);
228 assert(PendingCallWrapperResults.size() == 1 &&
229 I != PendingCallWrapperResults.end() &&
230 "Setup message handler not connectly set up");
231 auto SetupMsgHandler = std::move(I->second);
232 PendingCallWrapperResults.erase(I);
233
234 auto WFR =
235 shared::WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
236 SetupMsgHandler(std::move(WFR));
237 return Error::success();
238}
239
240Error SimpleRemoteEPC::setup() {
241 using namespace SimpleRemoteEPCDefaultBootstrapSymbolNames;
242
243 std::promise<MSVCPExpected<SimpleRemoteEPCExecutorInfo>> EIP;
244 auto EIF = EIP.get_future();
245
246 // Prepare a handler for the setup packet.
247 PendingCallWrapperResults[0] =
248 RunInPlace()(
249 [&](shared::WrapperFunctionBuffer SetupMsgBytes) {
250 if (const char *ErrMsg = SetupMsgBytes.getOutOfBandError()) {
251 EIP.set_value(
253 return;
254 }
255 using SPSSerialize =
256 shared::SPSArgList<shared::SPSSimpleRemoteEPCExecutorInfo>;
257 shared::SPSInputBuffer IB(SetupMsgBytes.data(), SetupMsgBytes.size());
258 SimpleRemoteEPCExecutorInfo EI;
259 if (SPSSerialize::deserialize(IB, EI))
260 EIP.set_value(EI);
261 else
262 EIP.set_value(make_error<StringError>(
263 "Could not deserialize setup message", inconvertibleErrorCode()));
264 });
265
266 // Start the transport.
267 if (auto Err = T->start())
268 return Err;
269
270 // Wait for setup packet to arrive.
271 auto EI = EIF.get();
272 if (!EI) {
273 T->disconnect();
274 return EI.takeError();
275 }
276
277 LLVM_DEBUG({
278 dbgs() << "SimpleRemoteEPC received setup message:\n"
279 << " Triple: " << EI->TargetTriple << "\n"
280 << " Page size: " << EI->PageSize << "\n"
281 << " Bootstrap map" << (EI->BootstrapMap.empty() ? " empty" : ":")
282 << "\n";
283 for (const auto &KV : EI->BootstrapMap)
284 dbgs() << " " << KV.first() << ": " << KV.second.size()
285 << "-byte SPS encoded buffer\n";
286 dbgs() << " Bootstrap symbols"
287 << (EI->BootstrapSymbols.empty() ? " empty" : ":") << "\n";
288 for (const auto &KV : EI->BootstrapSymbols)
289 dbgs() << " " << KV.first() << ": " << KV.second << "\n";
290 });
291 TargetTriple = Triple(EI->TargetTriple);
292 PageSize = EI->PageSize;
293 BootstrapMap = std::move(EI->BootstrapMap);
294 BootstrapSymbols = std::move(EI->BootstrapSymbols);
295
299
300 if (auto Err =
302 return Err;
303
304 return Error::success();
305}
306
307Error SimpleRemoteEPC::handleResult(uint64_t SeqNo, ExecutorAddr TagAddr,
309 IncomingWFRHandler SendResult;
310
311 if (TagAddr)
312 return make_error<StringError>("Unexpected TagAddr in result message",
314
315 {
316 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
317 auto I = PendingCallWrapperResults.find(SeqNo);
318 if (I == PendingCallWrapperResults.end())
319 return make_error<StringError>("No call for sequence number " +
320 Twine(SeqNo),
322 SendResult = std::move(I->second);
323 PendingCallWrapperResults.erase(I);
324 releaseSeqNo(SeqNo);
325 }
326
327 auto WFR =
328 shared::WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
329 SendResult(std::move(WFR));
330 return Error::success();
331}
332
333void SimpleRemoteEPC::handleCallWrapper(
334 uint64_t RemoteSeqNo, ExecutorAddr TagAddr,
336 assert(ES && "No ExecutionSession attached");
337 D->dispatch(makeGenericNamedTask(
338 [this, RemoteSeqNo, TagAddr, ArgBytes = std::move(ArgBytes)]() mutable {
339 ES->runJITDispatchHandler(
340 [this, RemoteSeqNo](shared::WrapperFunctionBuffer WFR) {
341 if (auto Err =
342 sendMessage(SimpleRemoteEPCOpcode::Result, RemoteSeqNo,
343 ExecutorAddr(), {WFR.data(), WFR.size()}))
344 getExecutionSession().reportError(std::move(Err));
345 },
346 TagAddr, std::move(ArgBytes));
347 },
348 "callWrapper task"));
349}
350
351Error SimpleRemoteEPC::handleHangup(shared::WrapperFunctionBuffer ArgBytes) {
352 using namespace llvm::orc::shared;
353 auto WFR = WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
354 if (const char *ErrMsg = WFR.getOutOfBandError())
356
357 orc::shared::detail::SPSSerializableError Info;
358 SPSInputBuffer IB(WFR.data(), WFR.size());
359 if (!SPSArgList<SPSError>::deserialize(IB, Info))
360 return make_error<StringError>("Could not deserialize hangup info",
362 return fromSPSSerializable(std::move(Info));
363}
364
365} // end namespace orc
366} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
#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
size_t size() const
Get the array size.
Definition ArrayRef.h:141
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
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)
Create an EPCGenericJITLinkMemoryManager for the ORC runtime's SimpleNativeMemoryMap interface,...
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,...
Constructs an IncomingWFRHandler from a function object that is callable as void(shared::WrapperFunct...
std::unique_ptr< TaskDispatcher > D
StringMap< ExecutorAddr > BootstrapSymbols
StringMap< std::vector< char > > BootstrapMap
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.
static WrapperFunctionBuffer copyFrom(const char *Source, size_t Size)
Copy from the given char range.
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.
LLVM_ABI const char *const DispatchCtxName
LLVM_ABI const char *const DispatchName
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
static constexpr char Name[]
Definition CallSPSCI.h:32