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
83
88
90 T->disconnect();
91 D->shutdown();
92 std::unique_lock<std::mutex> Lock(SimpleRemoteEPCMutex);
93 DisconnectCV.wait(Lock, [this] { return Disconnected; });
94 return std::move(DisconnectErr);
95}
96
99 ExecutorAddr TagAddr,
101
102 LLVM_DEBUG({
103 dbgs() << "SimpleRemoteEPC::handleMessage: opc = ";
104 switch (OpC) {
106 dbgs() << "Setup";
107 assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
108 assert(!TagAddr && "Non-zero TagAddr for Setup?");
109 break;
111 dbgs() << "Hangup";
112 assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
113 assert(!TagAddr && "Non-zero TagAddr for Hangup?");
114 break;
116 dbgs() << "Result";
117 assert(!TagAddr && "Non-zero TagAddr for Result?");
118 break;
120 dbgs() << "CallWrapper";
121 break;
122 }
123 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
124 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
125 << " bytes\n";
126 });
127
128 using UT = std::underlying_type_t<SimpleRemoteEPCOpcode>;
129 if (static_cast<UT>(OpC) > static_cast<UT>(SimpleRemoteEPCOpcode::LastOpC))
130 return make_error<StringError>("Unexpected opcode",
132
133 switch (OpC) {
135 if (auto Err = handleSetup(SeqNo, TagAddr, std::move(ArgBytes)))
136 return std::move(Err);
137 break;
139 T->disconnect();
140 if (auto Err = handleHangup(std::move(ArgBytes)))
141 return std::move(Err);
142 return EndSession;
144 if (auto Err = handleResult(SeqNo, TagAddr, std::move(ArgBytes)))
145 return std::move(Err);
146 break;
148 handleCallWrapper(SeqNo, TagAddr, std::move(ArgBytes));
149 break;
150 }
151 return ContinueSession;
152}
153
155 LLVM_DEBUG({
156 dbgs() << "SimpleRemoteEPC::handleDisconnect: "
157 << (Err ? "failure" : "success") << "\n";
158 });
159
160 PendingCallWrapperResultsMap TmpPending;
161
162 {
163 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
164 std::swap(TmpPending, PendingCallWrapperResults);
165 }
166
167 for (auto &KV : TmpPending)
168 KV.second(
170
171 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
172 DisconnectErr = joinErrors(std::move(DisconnectErr), std::move(Err));
173 Disconnected = true;
174 DisconnectCV.notify_all();
175}
176
177Error SimpleRemoteEPC::sendMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo,
178 ExecutorAddr TagAddr,
179 ArrayRef<char> ArgBytes) {
181 "SimpleRemoteEPC sending Setup message? That's the wrong direction.");
182
183 LLVM_DEBUG({
184 dbgs() << "SimpleRemoteEPC::sendMessage: opc = ";
185 switch (OpC) {
187 dbgs() << "Hangup";
188 assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
189 assert(!TagAddr && "Non-zero TagAddr for Hangup?");
190 break;
192 dbgs() << "Result";
193 assert(!TagAddr && "Non-zero TagAddr for Result?");
194 break;
196 dbgs() << "CallWrapper";
197 break;
198 default:
199 llvm_unreachable("Invalid opcode");
200 }
201 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
202 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
203 << " bytes\n";
204 });
205 auto Err = T->sendMessage(OpC, SeqNo, TagAddr, ArgBytes);
206 LLVM_DEBUG({
207 if (Err)
208 dbgs() << " \\--> SimpleRemoteEPC::sendMessage failed\n";
209 });
210 return Err;
211}
212
213Error SimpleRemoteEPC::handleSetup(uint64_t SeqNo, ExecutorAddr TagAddr,
215 if (SeqNo != 0)
216 return make_error<StringError>("Setup packet SeqNo not zero",
218
219 if (TagAddr)
220 return make_error<StringError>("Setup packet TagAddr not zero",
222
223 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
224 auto I = PendingCallWrapperResults.find(0);
225 assert(PendingCallWrapperResults.size() == 1 &&
226 I != PendingCallWrapperResults.end() &&
227 "Setup message handler not connectly set up");
228 auto SetupMsgHandler = std::move(I->second);
229 PendingCallWrapperResults.erase(I);
230
231 auto WFR =
232 shared::WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
233 SetupMsgHandler(std::move(WFR));
234 return Error::success();
235}
236
237Error SimpleRemoteEPC::setup() {
238 using namespace SimpleRemoteEPCDefaultBootstrapSymbolNames;
239
240 std::promise<MSVCPExpected<SimpleRemoteEPCExecutorInfo>> EIP;
241 auto EIF = EIP.get_future();
242
243 // Prepare a handler for the setup packet.
244 PendingCallWrapperResults[0] =
245 RunInPlace()(
246 [&](shared::WrapperFunctionBuffer SetupMsgBytes) {
247 if (const char *ErrMsg = SetupMsgBytes.getOutOfBandError()) {
248 EIP.set_value(
250 return;
251 }
252 using SPSSerialize =
253 shared::SPSArgList<shared::SPSSimpleRemoteEPCExecutorInfo>;
254 shared::SPSInputBuffer IB(SetupMsgBytes.data(), SetupMsgBytes.size());
255 SimpleRemoteEPCExecutorInfo EI;
256 if (SPSSerialize::deserialize(IB, EI))
257 EIP.set_value(EI);
258 else
259 EIP.set_value(make_error<StringError>(
260 "Could not deserialize setup message", inconvertibleErrorCode()));
261 });
262
263 // Start the transport.
264 if (auto Err = T->start())
265 return Err;
266
267 // Wait for setup packet to arrive.
268 auto EI = EIF.get();
269 if (!EI) {
270 T->disconnect();
271 return EI.takeError();
272 }
273
274 LLVM_DEBUG({
275 dbgs() << "SimpleRemoteEPC received setup message:\n"
276 << " Triple: " << EI->TargetTriple << "\n"
277 << " Page size: " << EI->PageSize << "\n"
278 << " Bootstrap map" << (EI->BootstrapMap.empty() ? " empty" : ":")
279 << "\n";
280 for (const auto &KV : EI->BootstrapMap)
281 dbgs() << " " << KV.first() << ": " << KV.second.size()
282 << "-byte SPS encoded buffer\n";
283 dbgs() << " Bootstrap symbols"
284 << (EI->BootstrapSymbols.empty() ? " empty" : ":") << "\n";
285 for (const auto &KV : EI->BootstrapSymbols)
286 dbgs() << " " << KV.first() << ": " << KV.second << "\n";
287 });
288 TargetTriple = Triple(EI->TargetTriple);
289 PageSize = EI->PageSize;
290 BootstrapMap = std::move(EI->BootstrapMap);
291 BootstrapSymbols = std::move(EI->BootstrapSymbols);
292
296
297 if (auto Err =
299 return Err;
300
301 return Error::success();
302}
303
304Error SimpleRemoteEPC::handleResult(uint64_t SeqNo, ExecutorAddr TagAddr,
306 IncomingWFRHandler SendResult;
307
308 if (TagAddr)
309 return make_error<StringError>("Unexpected TagAddr in result message",
311
312 {
313 std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
314 auto I = PendingCallWrapperResults.find(SeqNo);
315 if (I == PendingCallWrapperResults.end())
316 return make_error<StringError>("No call for sequence number " +
317 Twine(SeqNo),
319 SendResult = std::move(I->second);
320 PendingCallWrapperResults.erase(I);
321 releaseSeqNo(SeqNo);
322 }
323
324 auto WFR =
325 shared::WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
326 SendResult(std::move(WFR));
327 return Error::success();
328}
329
330void SimpleRemoteEPC::handleCallWrapper(
331 uint64_t RemoteSeqNo, ExecutorAddr TagAddr,
333 assert(ES && "No ExecutionSession attached");
334 D->dispatch(makeGenericNamedTask(
335 [this, RemoteSeqNo, TagAddr, ArgBytes = std::move(ArgBytes)]() mutable {
336 ES->runJITDispatchHandler(
337 [this, RemoteSeqNo](shared::WrapperFunctionBuffer WFR) {
338 if (auto Err =
339 sendMessage(SimpleRemoteEPCOpcode::Result, RemoteSeqNo,
340 ExecutorAddr(), {WFR.data(), WFR.size()}))
341 getExecutionSession().reportError(std::move(Err));
342 },
343 TagAddr, std::move(ArgBytes));
344 },
345 "callWrapper task"));
346}
347
348Error SimpleRemoteEPC::handleHangup(shared::WrapperFunctionBuffer ArgBytes) {
349 using namespace llvm::orc::shared;
350 auto WFR = WrapperFunctionBuffer::copyFrom(ArgBytes.data(), ArgBytes.size());
351 if (const char *ErrMsg = WFR.getOutOfBandError())
353
354 orc::shared::detail::SPSSerializableError Info;
355 SPSInputBuffer IB(WFR.data(), WFR.size());
356 if (!SPSArgList<SPSError>::deserialize(IB, Info))
357 return make_error<StringError>("Could not deserialize hangup info",
359 return fromSPSSerializable(std::move(Info));
360}
361
362} // end namespace orc
363} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#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
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)
LLVM_ABI Expected< std::unique_ptr< EPCGenericJITLinkMemoryManager > > createEPCGenericJITLinkMemoryManager(JITDylib &JD)
Create an EPCGenericJITLinkMemoryManager for the ORC runtime's SimpleNativeMemoryMap interface,...
LLVM_ABI Expected< std::unique_ptr< EPCGenericDylibManager > > createEPCGenericDylibManager(JITDylib &JD)
Create an EPCGenericDylibManager for the ORC runtime's NativeDylibManager interface,...
LLVM_ABI Expected< std::unique_ptr< EPCGenericMemoryAccess > > createEPCGenericMemoryAccess(JITDylib &JD)
Create an EPCGenericMemoryAccess that reaches the memory-access wrappers in the given JITDylib via th...
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