1bb72f073SLang Hames //===------- SimpleEPCServer.cpp - EPC over simple abstract channel -------===//
2bb72f073SLang Hames //
3bb72f073SLang Hames // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4bb72f073SLang Hames // See https://llvm.org/LICENSE.txt for license information.
5bb72f073SLang Hames // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bb72f073SLang Hames //
7bb72f073SLang Hames //===----------------------------------------------------------------------===//
8bb72f073SLang Hames 
9bb72f073SLang Hames #include "llvm/ExecutionEngine/Orc/TargetProcess/SimpleRemoteEPCServer.h"
10bb72f073SLang Hames 
11bb72f073SLang Hames #include "llvm/ExecutionEngine/Orc/Shared/TargetProcessControlTypes.h"
12bb72f073SLang Hames #include "llvm/Support/FormatVariadic.h"
13bb72f073SLang Hames #include "llvm/Support/Host.h"
14bb72f073SLang Hames #include "llvm/Support/Process.h"
15bb72f073SLang Hames 
162c8e7849SLang Hames #include "OrcRTBootstrap.h"
172c8e7849SLang Hames 
18bb72f073SLang Hames #define DEBUG_TYPE "orc"
19bb72f073SLang Hames 
20bb72f073SLang Hames using namespace llvm::orc::shared;
21bb72f073SLang Hames 
22bb72f073SLang Hames namespace llvm {
23bb72f073SLang Hames namespace orc {
24bb72f073SLang Hames 
2578b083dbSLang Hames ExecutorBootstrapService::~ExecutorBootstrapService() {}
2678b083dbSLang Hames 
27bb72f073SLang Hames SimpleRemoteEPCServer::Dispatcher::~Dispatcher() {}
28bb72f073SLang Hames 
29bb72f073SLang Hames #if LLVM_ENABLE_THREADS
30bb72f073SLang Hames void SimpleRemoteEPCServer::ThreadDispatcher::dispatch(
31bb72f073SLang Hames     unique_function<void()> Work) {
32bb72f073SLang Hames   {
33bb72f073SLang Hames     std::lock_guard<std::mutex> Lock(DispatchMutex);
34bb72f073SLang Hames     if (!Running)
35bb72f073SLang Hames       return;
36bb72f073SLang Hames     ++Outstanding;
37bb72f073SLang Hames   }
38bb72f073SLang Hames 
39bb72f073SLang Hames   std::thread([this, Work = std::move(Work)]() mutable {
40bb72f073SLang Hames     Work();
41bb72f073SLang Hames     std::lock_guard<std::mutex> Lock(DispatchMutex);
42bb72f073SLang Hames     --Outstanding;
43bb72f073SLang Hames     OutstandingCV.notify_all();
44bb72f073SLang Hames   }).detach();
45bb72f073SLang Hames }
46bb72f073SLang Hames 
47bb72f073SLang Hames void SimpleRemoteEPCServer::ThreadDispatcher::shutdown() {
48bb72f073SLang Hames   std::unique_lock<std::mutex> Lock(DispatchMutex);
49bb72f073SLang Hames   Running = false;
50bb72f073SLang Hames   OutstandingCV.wait(Lock, [this]() { return Outstanding == 0; });
51bb72f073SLang Hames }
52bb72f073SLang Hames #endif
53bb72f073SLang Hames 
54ef391df2SLang Hames StringMap<ExecutorAddr> SimpleRemoteEPCServer::defaultBootstrapSymbols() {
55ef391df2SLang Hames   StringMap<ExecutorAddr> DBS;
562c8e7849SLang Hames   rt_bootstrap::addTo(DBS);
57bb72f073SLang Hames   return DBS;
58bb72f073SLang Hames }
59bb72f073SLang Hames 
60bb72f073SLang Hames Expected<SimpleRemoteEPCTransportClient::HandleMessageAction>
61bb72f073SLang Hames SimpleRemoteEPCServer::handleMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo,
62ef391df2SLang Hames                                      ExecutorAddr TagAddr,
63bb72f073SLang Hames                                      SimpleRemoteEPCArgBytesVector ArgBytes) {
64*175c1a39SLang Hames 
65*175c1a39SLang Hames   LLVM_DEBUG({
66*175c1a39SLang Hames     dbgs() << "SimpleRemoteEPCServer::handleMessage: opc = ";
67*175c1a39SLang Hames     switch (OpC) {
68*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::Setup:
69*175c1a39SLang Hames       dbgs() << "Setup";
70*175c1a39SLang Hames       assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
71*175c1a39SLang Hames       assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Setup?");
72*175c1a39SLang Hames       break;
73*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::Hangup:
74*175c1a39SLang Hames       dbgs() << "Hangup";
75*175c1a39SLang Hames       assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
76*175c1a39SLang Hames       assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Hangup?");
77*175c1a39SLang Hames       break;
78*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::Result:
79*175c1a39SLang Hames       dbgs() << "Result";
80*175c1a39SLang Hames       assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Result?");
81*175c1a39SLang Hames       break;
82*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::CallWrapper:
83*175c1a39SLang Hames       dbgs() << "CallWrapper";
84*175c1a39SLang Hames       break;
85*175c1a39SLang Hames     }
86*175c1a39SLang Hames     dbgs() << ", seqno = " << SeqNo
87*175c1a39SLang Hames            << ", tag-addr = " << formatv("{0:x}", TagAddr.getValue())
88*175c1a39SLang Hames            << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
89*175c1a39SLang Hames            << " bytes\n";
90*175c1a39SLang Hames   });
91*175c1a39SLang Hames 
92bb72f073SLang Hames   using UT = std::underlying_type_t<SimpleRemoteEPCOpcode>;
93d11a0c5dSLang Hames   if (static_cast<UT>(OpC) > static_cast<UT>(SimpleRemoteEPCOpcode::LastOpC))
94bb72f073SLang Hames     return make_error<StringError>("Unexpected opcode",
95bb72f073SLang Hames                                    inconvertibleErrorCode());
96bb72f073SLang Hames 
97bb72f073SLang Hames   // TODO: Clean detach message?
98bb72f073SLang Hames   switch (OpC) {
99bb72f073SLang Hames   case SimpleRemoteEPCOpcode::Setup:
100bb72f073SLang Hames     return make_error<StringError>("Unexpected Setup opcode",
101bb72f073SLang Hames                                    inconvertibleErrorCode());
102bb72f073SLang Hames   case SimpleRemoteEPCOpcode::Hangup:
103bb72f073SLang Hames     return SimpleRemoteEPCTransportClient::EndSession;
104bb72f073SLang Hames   case SimpleRemoteEPCOpcode::Result:
105bb72f073SLang Hames     if (auto Err = handleResult(SeqNo, TagAddr, std::move(ArgBytes)))
106bb72f073SLang Hames       return std::move(Err);
107bb72f073SLang Hames     break;
108bb72f073SLang Hames   case SimpleRemoteEPCOpcode::CallWrapper:
109bb72f073SLang Hames     handleCallWrapper(SeqNo, TagAddr, std::move(ArgBytes));
110bb72f073SLang Hames     break;
111bb72f073SLang Hames   }
112bb72f073SLang Hames   return ContinueSession;
113bb72f073SLang Hames }
114bb72f073SLang Hames 
115bb72f073SLang Hames Error SimpleRemoteEPCServer::waitForDisconnect() {
116bb72f073SLang Hames   std::unique_lock<std::mutex> Lock(ServerStateMutex);
117bb72f073SLang Hames   ShutdownCV.wait(Lock, [this]() { return RunState == ServerShutDown; });
118bb72f073SLang Hames   return std::move(ShutdownErr);
119bb72f073SLang Hames }
120bb72f073SLang Hames 
121bb72f073SLang Hames void SimpleRemoteEPCServer::handleDisconnect(Error Err) {
122bb72f073SLang Hames   PendingJITDispatchResultsMap TmpPending;
123bb72f073SLang Hames 
124bb72f073SLang Hames   {
125bb72f073SLang Hames     std::lock_guard<std::mutex> Lock(ServerStateMutex);
126bb72f073SLang Hames     std::swap(TmpPending, PendingJITDispatchResults);
127bb72f073SLang Hames     RunState = ServerShuttingDown;
128bb72f073SLang Hames   }
129bb72f073SLang Hames 
130bb72f073SLang Hames   // Send out-of-band errors to any waiting threads.
131bb72f073SLang Hames   for (auto &KV : TmpPending)
132bb72f073SLang Hames     KV.second->set_value(
133bb72f073SLang Hames         shared::WrapperFunctionResult::createOutOfBandError("disconnecting"));
134bb72f073SLang Hames 
135bb72f073SLang Hames   // TODO: Free attached resources.
136bb72f073SLang Hames   // 1. Close libraries in DylibHandles.
137bb72f073SLang Hames 
138bb72f073SLang Hames   // Wait for dispatcher to clear.
139bb72f073SLang Hames   D->shutdown();
140bb72f073SLang Hames 
141c965fde7SLang Hames   // Shut down services.
142c965fde7SLang Hames   while (!Services.empty()) {
143c965fde7SLang Hames     ShutdownErr =
144c965fde7SLang Hames       joinErrors(std::move(ShutdownErr), Services.back()->shutdown());
145c965fde7SLang Hames     Services.pop_back();
146c965fde7SLang Hames   }
147c965fde7SLang Hames 
148bb72f073SLang Hames   std::lock_guard<std::mutex> Lock(ServerStateMutex);
149bb72f073SLang Hames   ShutdownErr = joinErrors(std::move(ShutdownErr), std::move(Err));
150bb72f073SLang Hames   RunState = ServerShutDown;
151bb72f073SLang Hames   ShutdownCV.notify_all();
152bb72f073SLang Hames }
153bb72f073SLang Hames 
154*175c1a39SLang Hames Error SimpleRemoteEPCServer::sendMessage(SimpleRemoteEPCOpcode OpC,
155*175c1a39SLang Hames                                          uint64_t SeqNo, ExecutorAddr TagAddr,
156*175c1a39SLang Hames                                          ArrayRef<char> ArgBytes) {
157*175c1a39SLang Hames 
158*175c1a39SLang Hames   LLVM_DEBUG({
159*175c1a39SLang Hames     dbgs() << "SimpleRemoteEPCServer::sendMessage: opc = ";
160*175c1a39SLang Hames     switch (OpC) {
161*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::Setup:
162*175c1a39SLang Hames       dbgs() << "Setup";
163*175c1a39SLang Hames       assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
164*175c1a39SLang Hames       assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Setup?");
165*175c1a39SLang Hames       break;
166*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::Hangup:
167*175c1a39SLang Hames       dbgs() << "Hangup";
168*175c1a39SLang Hames       assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
169*175c1a39SLang Hames       assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Hangup?");
170*175c1a39SLang Hames       break;
171*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::Result:
172*175c1a39SLang Hames       dbgs() << "Result";
173*175c1a39SLang Hames       assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Result?");
174*175c1a39SLang Hames       break;
175*175c1a39SLang Hames     case SimpleRemoteEPCOpcode::CallWrapper:
176*175c1a39SLang Hames       dbgs() << "CallWrapper";
177*175c1a39SLang Hames       break;
178*175c1a39SLang Hames     }
179*175c1a39SLang Hames     dbgs() << ", seqno = " << SeqNo
180*175c1a39SLang Hames            << ", tag-addr = " << formatv("{0:x}", TagAddr.getValue())
181*175c1a39SLang Hames            << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
182*175c1a39SLang Hames            << " bytes\n";
183*175c1a39SLang Hames   });
184*175c1a39SLang Hames   auto Err = T->sendMessage(OpC, SeqNo, TagAddr, ArgBytes);
185*175c1a39SLang Hames   LLVM_DEBUG({
186*175c1a39SLang Hames     if (Err)
187*175c1a39SLang Hames       dbgs() << "  \\--> SimpleRemoteEPC::sendMessage failed\n";
188*175c1a39SLang Hames   });
189*175c1a39SLang Hames   return Err;
190*175c1a39SLang Hames }
191*175c1a39SLang Hames 
192bb72f073SLang Hames Error SimpleRemoteEPCServer::sendSetupMessage(
193ef391df2SLang Hames     StringMap<ExecutorAddr> BootstrapSymbols) {
194bb72f073SLang Hames 
195bb72f073SLang Hames   using namespace SimpleRemoteEPCDefaultBootstrapSymbolNames;
196bb72f073SLang Hames 
197bb72f073SLang Hames   std::vector<char> SetupPacket;
198bb72f073SLang Hames   SimpleRemoteEPCExecutorInfo EI;
199bb72f073SLang Hames   EI.TargetTriple = sys::getProcessTriple();
200bb72f073SLang Hames   if (auto PageSize = sys::Process::getPageSize())
201bb72f073SLang Hames     EI.PageSize = *PageSize;
202bb72f073SLang Hames   else
203bb72f073SLang Hames     return PageSize.takeError();
204bb72f073SLang Hames   EI.BootstrapSymbols = std::move(BootstrapSymbols);
205bb72f073SLang Hames 
206bb72f073SLang Hames   assert(!EI.BootstrapSymbols.count(ExecutorSessionObjectName) &&
207bb72f073SLang Hames          "Dispatch context name should not be set");
208bb72f073SLang Hames   assert(!EI.BootstrapSymbols.count(DispatchFnName) &&
209bb72f073SLang Hames          "Dispatch function name should not be set");
210ef391df2SLang Hames   EI.BootstrapSymbols[ExecutorSessionObjectName] = ExecutorAddr::fromPtr(this);
211ef391df2SLang Hames   EI.BootstrapSymbols[DispatchFnName] = ExecutorAddr::fromPtr(jitDispatchEntry);
212bb72f073SLang Hames 
213bb72f073SLang Hames   using SPSSerialize =
214bb72f073SLang Hames       shared::SPSArgList<shared::SPSSimpleRemoteEPCExecutorInfo>;
215bb72f073SLang Hames   auto SetupPacketBytes =
216bb72f073SLang Hames       shared::WrapperFunctionResult::allocate(SPSSerialize::size(EI));
217bb72f073SLang Hames   shared::SPSOutputBuffer OB(SetupPacketBytes.data(), SetupPacketBytes.size());
218bb72f073SLang Hames   if (!SPSSerialize::serialize(OB, EI))
219bb72f073SLang Hames     return make_error<StringError>("Could not send setup packet",
220bb72f073SLang Hames                                    inconvertibleErrorCode());
221bb72f073SLang Hames 
222*175c1a39SLang Hames   return sendMessage(SimpleRemoteEPCOpcode::Setup, 0, ExecutorAddr(),
223bb72f073SLang Hames                      {SetupPacketBytes.data(), SetupPacketBytes.size()});
224bb72f073SLang Hames }
225bb72f073SLang Hames 
226bb72f073SLang Hames Error SimpleRemoteEPCServer::handleResult(
227ef391df2SLang Hames     uint64_t SeqNo, ExecutorAddr TagAddr,
228bb72f073SLang Hames     SimpleRemoteEPCArgBytesVector ArgBytes) {
229bb72f073SLang Hames   std::promise<shared::WrapperFunctionResult> *P = nullptr;
230bb72f073SLang Hames   {
231bb72f073SLang Hames     std::lock_guard<std::mutex> Lock(ServerStateMutex);
232bb72f073SLang Hames     auto I = PendingJITDispatchResults.find(SeqNo);
233bb72f073SLang Hames     if (I == PendingJITDispatchResults.end())
234bb72f073SLang Hames       return make_error<StringError>("No call for sequence number " +
235bb72f073SLang Hames                                          Twine(SeqNo),
236bb72f073SLang Hames                                      inconvertibleErrorCode());
237bb72f073SLang Hames     P = I->second;
238bb72f073SLang Hames     PendingJITDispatchResults.erase(I);
239bb72f073SLang Hames     releaseSeqNo(SeqNo);
240bb72f073SLang Hames   }
241bb72f073SLang Hames   auto R = shared::WrapperFunctionResult::allocate(ArgBytes.size());
242bb72f073SLang Hames   memcpy(R.data(), ArgBytes.data(), ArgBytes.size());
243bb72f073SLang Hames   P->set_value(std::move(R));
244bb72f073SLang Hames   return Error::success();
245bb72f073SLang Hames }
246bb72f073SLang Hames 
247bb72f073SLang Hames void SimpleRemoteEPCServer::handleCallWrapper(
248ef391df2SLang Hames     uint64_t RemoteSeqNo, ExecutorAddr TagAddr,
249bb72f073SLang Hames     SimpleRemoteEPCArgBytesVector ArgBytes) {
250bb72f073SLang Hames   D->dispatch([this, RemoteSeqNo, TagAddr, ArgBytes = std::move(ArgBytes)]() {
251bb72f073SLang Hames     using WrapperFnTy =
252bb72f073SLang Hames         shared::detail::CWrapperFunctionResult (*)(const char *, size_t);
253bb72f073SLang Hames     auto *Fn = TagAddr.toPtr<WrapperFnTy>();
254bb72f073SLang Hames     shared::WrapperFunctionResult ResultBytes(
255bb72f073SLang Hames         Fn(ArgBytes.data(), ArgBytes.size()));
256*175c1a39SLang Hames     if (auto Err = sendMessage(SimpleRemoteEPCOpcode::Result, RemoteSeqNo,
257ef391df2SLang Hames                                ExecutorAddr(),
258bb72f073SLang Hames                                {ResultBytes.data(), ResultBytes.size()}))
259bb72f073SLang Hames       ReportError(std::move(Err));
260bb72f073SLang Hames   });
261bb72f073SLang Hames }
262bb72f073SLang Hames 
263bb72f073SLang Hames shared::WrapperFunctionResult
264bb72f073SLang Hames SimpleRemoteEPCServer::doJITDispatch(const void *FnTag, const char *ArgData,
265bb72f073SLang Hames                                      size_t ArgSize) {
266bb72f073SLang Hames   uint64_t SeqNo;
267bb72f073SLang Hames   std::promise<shared::WrapperFunctionResult> ResultP;
268bb72f073SLang Hames   auto ResultF = ResultP.get_future();
269bb72f073SLang Hames   {
270bb72f073SLang Hames     std::lock_guard<std::mutex> Lock(ServerStateMutex);
271bb72f073SLang Hames     if (RunState != ServerRunning)
272bb72f073SLang Hames       return shared::WrapperFunctionResult::createOutOfBandError(
273bb72f073SLang Hames           "jit_dispatch not available (EPC server shut down)");
274bb72f073SLang Hames 
275bb72f073SLang Hames     SeqNo = getNextSeqNo();
276bb72f073SLang Hames     assert(!PendingJITDispatchResults.count(SeqNo) && "SeqNo already in use");
277bb72f073SLang Hames     PendingJITDispatchResults[SeqNo] = &ResultP;
278bb72f073SLang Hames   }
279bb72f073SLang Hames 
280*175c1a39SLang Hames   if (auto Err = sendMessage(SimpleRemoteEPCOpcode::CallWrapper, SeqNo,
281ef391df2SLang Hames                              ExecutorAddr::fromPtr(FnTag), {ArgData, ArgSize}))
282bb72f073SLang Hames     ReportError(std::move(Err));
283bb72f073SLang Hames 
284bb72f073SLang Hames   return ResultF.get();
285bb72f073SLang Hames }
286bb72f073SLang Hames 
287bb72f073SLang Hames shared::detail::CWrapperFunctionResult
288bb72f073SLang Hames SimpleRemoteEPCServer::jitDispatchEntry(void *DispatchCtx, const void *FnTag,
289bb72f073SLang Hames                                         const char *ArgData, size_t ArgSize) {
290bb72f073SLang Hames   return reinterpret_cast<SimpleRemoteEPCServer *>(DispatchCtx)
291bb72f073SLang Hames       ->doJITDispatch(FnTag, ArgData, ArgSize)
292bb72f073SLang Hames       .release();
293bb72f073SLang Hames }
294bb72f073SLang Hames 
295bb72f073SLang Hames } // end namespace orc
296bb72f073SLang Hames } // end namespace llvm
297