LLVM 24.0.0git
SimpleRemoteEPCServer.cpp
Go to the documentation of this file.
1//===------- SimpleEPCServer.cpp - EPC over simple abstract channel -------===//
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
16
17#define DEBUG_TYPE "orc"
18
19using namespace llvm::orc::shared;
20
21namespace llvm {
22namespace orc {
23
25
27
28#if LLVM_ENABLE_THREADS
29void SimpleRemoteEPCServer::ThreadDispatcher::dispatch(
30 unique_function<void()> Work) {
31 {
32 std::lock_guard<std::mutex> Lock(DispatchMutex);
33 if (!Running)
34 return;
35 ++Outstanding;
36 }
37
38 std::thread([this, Work = std::move(Work)]() mutable {
39 Work();
40 std::lock_guard<std::mutex> Lock(DispatchMutex);
41 --Outstanding;
42 OutstandingCV.notify_all();
43 }).detach();
44}
45
46void SimpleRemoteEPCServer::ThreadDispatcher::shutdown() {
47 std::unique_lock<std::mutex> Lock(DispatchMutex);
48 Running = false;
49 OutstandingCV.wait(Lock, [this]() { return Outstanding == 0; });
50}
51#endif
52
58
61 ExecutorAddr TagAddr,
63
65 dbgs() << "SimpleRemoteEPCServer::handleMessage: opc = ";
66 switch (OpC) {
68 dbgs() << "Setup";
69 assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
70 assert(!TagAddr && "Non-zero TagAddr for Setup?");
71 break;
73 dbgs() << "Hangup";
74 assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
75 assert(!TagAddr && "Non-zero TagAddr for Hangup?");
76 break;
78 dbgs() << "Result";
79 break;
81 dbgs() << "CallWrapper";
82 break;
83 }
84 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
85 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
86 << " bytes\n";
87 });
88
89 using UT = std::underlying_type_t<SimpleRemoteEPCOpcode>;
90 if (static_cast<UT>(OpC) > static_cast<UT>(SimpleRemoteEPCOpcode::LastOpC))
91 return make_error<StringError>("Unexpected opcode",
93
94 // TODO: Clean detach message?
95 switch (OpC) {
97 return make_error<StringError>("Unexpected Setup opcode",
100 {
101 std::lock_guard<std::mutex> Lock(ServerStateMutex);
102 RemoteHangup = true;
103 }
104 if (auto Err = decodeHangupPayload(std::move(ArgBytes)))
105 return std::move(Err);
107 }
109 if (auto Err = handleResult(SeqNo, TagAddr, std::move(ArgBytes)))
110 return std::move(Err);
111 break;
113 handleCallWrapper(SeqNo, TagAddr, std::move(ArgBytes));
114 break;
115 }
116 return ContinueSession;
117}
118
120 std::unique_lock<std::mutex> Lock(ServerStateMutex);
121 ShutdownCV.wait(Lock, [this]() { return RunState == ServerShutDown; });
122 return std::move(ShutdownErr);
123}
124
126 PendingJITDispatchResultsMap TmpPending;
127
128 {
129 std::lock_guard<std::mutex> Lock(ServerStateMutex);
130 std::swap(TmpPending, PendingJITDispatchResults);
131 RunState = ServerShuttingDown;
132 }
133
134 // Send out-of-band errors to any waiting threads.
135 for (auto &KV : TmpPending)
136 KV.second->set_value(
138
139 // Wait for dispatcher to clear.
140 D->shutdown();
141
142 // Shut down services.
143 while (!Services.empty()) {
144 ShutdownErr =
145 joinErrors(std::move(ShutdownErr), Services.back()->shutdown());
146 Services.pop_back();
147 }
148
149 std::lock_guard<std::mutex> Lock(ServerStateMutex);
150
151 // The server never initiates a disconnection, so if the transport reported no
152 // error and no hangup arrived then the controller went away without telling
153 // us. The cause is not knowable from here -- it may have crashed, been
154 // killed, or become unreachable -- so report what was observed rather than a
155 // cause.
156 //
157 // A missing hangup is evidence, not proof: a hangup can also be lost in
158 // transit, since closing a TCP socket with unread data queued sends an RST,
159 // which can discard bytes the peer had already delivered. We accept that
160 // rather than draining the read side before closing -- the cost is a
161 // misleading diagnostic on a session that is ending regardless, whereas a
162 // drain risks stalling teardown on a peer that never closes.
163 Error DisconnectReason =
164 (!Err && !RemoteHangup)
165 ? make_error<StringError>("Connection closed without hangup",
167 : std::move(Err);
168
169 ShutdownErr = joinErrors(std::move(ShutdownErr), std::move(DisconnectReason));
170 RunState = ServerShutDown;
171 ShutdownCV.notify_all();
172}
173
174Error SimpleRemoteEPCServer::sendMessage(SimpleRemoteEPCOpcode OpC,
175 uint64_t SeqNo, ExecutorAddr TagAddr,
176 ArrayRef<char> ArgBytes) {
177
178 LLVM_DEBUG({
179 dbgs() << "SimpleRemoteEPCServer::sendMessage: opc = ";
180 switch (OpC) {
182 dbgs() << "Setup";
183 assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
184 assert(!TagAddr && "Non-zero TagAddr for Setup?");
185 break;
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 break;
195 dbgs() << "CallWrapper";
196 break;
197 }
198 dbgs() << ", seqno = " << SeqNo << ", tag-addr = " << TagAddr
199 << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
200 << " bytes\n";
201 });
202 auto Err = T->sendMessage(OpC, SeqNo, TagAddr, ArgBytes);
203 LLVM_DEBUG({
204 if (Err)
205 dbgs() << " \\--> SimpleRemoteEPC::sendMessage failed\n";
206 });
207 return Err;
208}
209
210Error SimpleRemoteEPCServer::sendSetupMessage(
211 StringMap<std::vector<char>> BootstrapMap,
212 StringMap<ExecutorAddr> BootstrapSymbols) {
213
214 using namespace SimpleRemoteEPCDefaultBootstrapSymbolNames;
215
216 SimpleRemoteEPCExecutorInfo EI;
219 EI.PageSize = *PageSize;
220 else
221 return PageSize.takeError();
222 EI.BootstrapMap = std::move(BootstrapMap);
223 EI.BootstrapSymbols = std::move(BootstrapSymbols);
224
225 assert(!EI.BootstrapSymbols.count(ExecutorSessionObjectName) &&
226 "Dispatch context name should not be set");
227 assert(!EI.BootstrapSymbols.count(DispatchFnName) &&
228 "Dispatch function name should not be set");
232
233 using SPSSerialize =
234 shared::SPSArgList<shared::SPSSimpleRemoteEPCExecutorInfo>;
235 auto SetupPacketBytes =
236 shared::WrapperFunctionBuffer::allocate(SPSSerialize::size(EI));
237 shared::SPSOutputBuffer OB(SetupPacketBytes.data(), SetupPacketBytes.size());
238 if (!SPSSerialize::serialize(OB, EI))
239 return make_error<StringError>("Could not send setup packet",
241
242 return sendMessage(SimpleRemoteEPCOpcode::Setup, 0, ExecutorAddr(),
243 {SetupPacketBytes.data(), SetupPacketBytes.size()});
244}
245
246Error SimpleRemoteEPCServer::handleResult(
247 uint64_t SeqNo, ExecutorAddr TagAddr,
249 std::promise<shared::WrapperFunctionBuffer> *P = nullptr;
250
251 auto R = decodeResultMessage(TagAddr, std::move(ArgBytes));
252 if (!R)
253 return R.takeError();
254
255 {
256 std::lock_guard<std::mutex> Lock(ServerStateMutex);
257 auto I = PendingJITDispatchResults.find(SeqNo);
258 if (I == PendingJITDispatchResults.end())
259 return make_error<StringError>("No call for sequence number " +
260 Twine(SeqNo),
262 P = I->second;
263 PendingJITDispatchResults.erase(I);
264 releaseSeqNo(SeqNo);
265 }
266 P->set_value(std::move(*R));
267 return Error::success();
268}
269
270void SimpleRemoteEPCServer::handleCallWrapper(
271 uint64_t RemoteSeqNo, ExecutorAddr TagAddr,
273 D->dispatch([this, RemoteSeqNo, TagAddr, ArgBytes = std::move(ArgBytes)]() {
274 using WrapperFnTy =
275 shared::CWrapperFunctionBuffer (*)(const char *, size_t);
276 auto *Fn = TagAddr.toPtr<WrapperFnTy>();
277 shared::WrapperFunctionBuffer ResultBytes(
278 Fn(ArgBytes.data(), ArgBytes.size()));
279 auto [ResultTag, Payload] = encodeResultMessage(std::move(ResultBytes));
280 if (auto Err = sendMessage(SimpleRemoteEPCOpcode::Result, RemoteSeqNo,
281 ResultTag, {Payload.data(), Payload.size()}))
282 ReportError(std::move(Err));
283 });
284}
285
287SimpleRemoteEPCServer::doJITDispatch(const void *FnTag, const char *ArgData,
288 size_t ArgSize) {
289 uint64_t SeqNo;
290 std::promise<shared::WrapperFunctionBuffer> ResultP;
291 auto ResultF = ResultP.get_future();
292 {
293 std::lock_guard<std::mutex> Lock(ServerStateMutex);
294 if (RunState != ServerRunning)
296 "jit_dispatch not available (EPC server shut down)");
297
298 SeqNo = getNextSeqNo();
299 assert(!PendingJITDispatchResults.count(SeqNo) && "SeqNo already in use");
300 PendingJITDispatchResults[SeqNo] = &ResultP;
301 }
302
303 if (auto Err = sendMessage(SimpleRemoteEPCOpcode::CallWrapper, SeqNo,
304 ExecutorAddr::fromPtr(FnTag), {ArgData, ArgSize}))
305 ReportError(std::move(Err));
306
307 return ResultF.get();
308}
309
311SimpleRemoteEPCServer::jitDispatchEntry(void *DispatchCtx, const void *FnTag,
312 const char *ArgData, size_t ArgSize) {
313 return reinterpret_cast<SimpleRemoteEPCServer *>(DispatchCtx)
314 ->doJITDispatch(FnTag, ArgData, ArgSize)
315 .release();
316}
317
318} // end namespace orc
319} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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 T
#define P(N)
Provides a library for accessing information about this process and other processes on the operating ...
#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
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
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.
static StringMap< ExecutorAddr > defaultBootstrapSymbols()
void handleDisconnect(Error Err) override
Handle a disconnection from the underlying transport.
Expected< HandleMessageAction > handleMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo, ExecutorAddr TagAddr, shared::WrapperFunctionBuffer ArgBytes) override
Call to handle an incoming message.
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.
char * data()
Get a pointer to the data contained in this instance.
static WrapperFunctionBuffer allocate(size_t Size)
Create a WrapperFunctionBuffer with the given size and return a pointer to the underlying memory.
static LLVM_ABI Expected< unsigned > getPageSize()
Get the process's page size.
unique_function is a type-erasing functor similar to std::function.
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
LLVM_ABI void addTo(StringMap< ExecutorAddr > &M)
Adds all default target-process bootstrap wrappers.
LLVM_ABI void addDefaultBootstrapValuesForHostProcess(StringMap< std::vector< char > > &BootstrapMap, StringMap< ExecutorAddr > &BootstrapSymbols)
LLVM_ABI std::pair< ExecutorAddr, shared::WrapperFunctionBuffer > encodeResultMessage(shared::WrapperFunctionBuffer ResultBytes)
Encode a wrapper function result as the TagAddr and payload of a Result message.
LLVM_ABI Error decodeHangupPayload(shared::WrapperFunctionBuffer Payload)
Decode a Hangup payload produced by encodeHangupPayload.
LLVM_ABI Expected< shared::WrapperFunctionBuffer > decodeResultMessage(ExecutorAddr TagAddr, shared::WrapperFunctionBuffer Payload)
Decode a Result message produced by encodeResultMessage, returning the result to complete the pending...
LLVM_ABI std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition Host.cpp:2653
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
StringMap< std::vector< char > > BootstrapMap