SimpleRemoteEPC.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
  9. #include "llvm/ExecutionEngine/Orc/EPCGenericJITLinkMemoryManager.h"
  10. #include "llvm/ExecutionEngine/Orc/EPCGenericMemoryAccess.h"
  11. #include "llvm/ExecutionEngine/Orc/Shared/OrcRTBridge.h"
  12. #include "llvm/Support/FormatVariadic.h"
  13. #define DEBUG_TYPE "orc"
  14. namespace llvm {
  15. namespace orc {
  16. SimpleRemoteEPC::~SimpleRemoteEPC() {
  17. #ifndef NDEBUG
  18. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  19. assert(Disconnected && "Destroyed without disconnection");
  20. #endif // NDEBUG
  21. }
  22. Expected<tpctypes::DylibHandle>
  23. SimpleRemoteEPC::loadDylib(const char *DylibPath) {
  24. return DylibMgr->open(DylibPath, 0);
  25. }
  26. Expected<std::vector<tpctypes::LookupResult>>
  27. SimpleRemoteEPC::lookupSymbols(ArrayRef<LookupRequest> Request) {
  28. std::vector<tpctypes::LookupResult> Result;
  29. for (auto &Element : Request) {
  30. if (auto R = DylibMgr->lookup(Element.Handle, Element.Symbols)) {
  31. Result.push_back({});
  32. Result.back().reserve(R->size());
  33. for (auto Addr : *R)
  34. Result.back().push_back(Addr.getValue());
  35. } else
  36. return R.takeError();
  37. }
  38. return std::move(Result);
  39. }
  40. Expected<int32_t> SimpleRemoteEPC::runAsMain(ExecutorAddr MainFnAddr,
  41. ArrayRef<std::string> Args) {
  42. int64_t Result = 0;
  43. if (auto Err = callSPSWrapper<rt::SPSRunAsMainSignature>(
  44. RunAsMainAddr, Result, ExecutorAddr(MainFnAddr), Args))
  45. return std::move(Err);
  46. return Result;
  47. }
  48. void SimpleRemoteEPC::callWrapperAsync(ExecutorAddr WrapperFnAddr,
  49. IncomingWFRHandler OnComplete,
  50. ArrayRef<char> ArgBuffer) {
  51. uint64_t SeqNo;
  52. {
  53. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  54. SeqNo = getNextSeqNo();
  55. assert(!PendingCallWrapperResults.count(SeqNo) && "SeqNo already in use");
  56. PendingCallWrapperResults[SeqNo] = std::move(OnComplete);
  57. }
  58. if (auto Err = sendMessage(SimpleRemoteEPCOpcode::CallWrapper, SeqNo,
  59. WrapperFnAddr, ArgBuffer)) {
  60. IncomingWFRHandler H;
  61. // We just registered OnComplete, but there may be a race between this
  62. // thread returning from sendMessage and handleDisconnect being called from
  63. // the transport's listener thread. If handleDisconnect gets there first
  64. // then it will have failed 'H' for us. If we get there first (or if
  65. // handleDisconnect already ran) then we need to take care of it.
  66. {
  67. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  68. auto I = PendingCallWrapperResults.find(SeqNo);
  69. if (I != PendingCallWrapperResults.end()) {
  70. H = std::move(I->second);
  71. PendingCallWrapperResults.erase(I);
  72. }
  73. }
  74. if (H)
  75. H(shared::WrapperFunctionResult::createOutOfBandError("disconnecting"));
  76. getExecutionSession().reportError(std::move(Err));
  77. }
  78. }
  79. Error SimpleRemoteEPC::disconnect() {
  80. T->disconnect();
  81. D->shutdown();
  82. std::unique_lock<std::mutex> Lock(SimpleRemoteEPCMutex);
  83. DisconnectCV.wait(Lock, [this] { return Disconnected; });
  84. return std::move(DisconnectErr);
  85. }
  86. Expected<SimpleRemoteEPCTransportClient::HandleMessageAction>
  87. SimpleRemoteEPC::handleMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo,
  88. ExecutorAddr TagAddr,
  89. SimpleRemoteEPCArgBytesVector ArgBytes) {
  90. LLVM_DEBUG({
  91. dbgs() << "SimpleRemoteEPC::handleMessage: opc = ";
  92. switch (OpC) {
  93. case SimpleRemoteEPCOpcode::Setup:
  94. dbgs() << "Setup";
  95. assert(SeqNo == 0 && "Non-zero SeqNo for Setup?");
  96. assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Setup?");
  97. break;
  98. case SimpleRemoteEPCOpcode::Hangup:
  99. dbgs() << "Hangup";
  100. assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
  101. assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Hangup?");
  102. break;
  103. case SimpleRemoteEPCOpcode::Result:
  104. dbgs() << "Result";
  105. assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Result?");
  106. break;
  107. case SimpleRemoteEPCOpcode::CallWrapper:
  108. dbgs() << "CallWrapper";
  109. break;
  110. }
  111. dbgs() << ", seqno = " << SeqNo
  112. << ", tag-addr = " << formatv("{0:x}", TagAddr.getValue())
  113. << ", arg-buffer = " << formatv("{0:x}", ArgBytes.size())
  114. << " bytes\n";
  115. });
  116. using UT = std::underlying_type_t<SimpleRemoteEPCOpcode>;
  117. if (static_cast<UT>(OpC) > static_cast<UT>(SimpleRemoteEPCOpcode::LastOpC))
  118. return make_error<StringError>("Unexpected opcode",
  119. inconvertibleErrorCode());
  120. switch (OpC) {
  121. case SimpleRemoteEPCOpcode::Setup:
  122. if (auto Err = handleSetup(SeqNo, TagAddr, std::move(ArgBytes)))
  123. return std::move(Err);
  124. break;
  125. case SimpleRemoteEPCOpcode::Hangup:
  126. T->disconnect();
  127. if (auto Err = handleHangup(std::move(ArgBytes)))
  128. return std::move(Err);
  129. return EndSession;
  130. case SimpleRemoteEPCOpcode::Result:
  131. if (auto Err = handleResult(SeqNo, TagAddr, std::move(ArgBytes)))
  132. return std::move(Err);
  133. break;
  134. case SimpleRemoteEPCOpcode::CallWrapper:
  135. handleCallWrapper(SeqNo, TagAddr, std::move(ArgBytes));
  136. break;
  137. }
  138. return ContinueSession;
  139. }
  140. void SimpleRemoteEPC::handleDisconnect(Error Err) {
  141. LLVM_DEBUG({
  142. dbgs() << "SimpleRemoteEPC::handleDisconnect: "
  143. << (Err ? "failure" : "success") << "\n";
  144. });
  145. PendingCallWrapperResultsMap TmpPending;
  146. {
  147. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  148. std::swap(TmpPending, PendingCallWrapperResults);
  149. }
  150. for (auto &KV : TmpPending)
  151. KV.second(
  152. shared::WrapperFunctionResult::createOutOfBandError("disconnecting"));
  153. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  154. DisconnectErr = joinErrors(std::move(DisconnectErr), std::move(Err));
  155. Disconnected = true;
  156. DisconnectCV.notify_all();
  157. }
  158. Expected<std::unique_ptr<jitlink::JITLinkMemoryManager>>
  159. SimpleRemoteEPC::createDefaultMemoryManager(SimpleRemoteEPC &SREPC) {
  160. EPCGenericJITLinkMemoryManager::SymbolAddrs SAs;
  161. if (auto Err = SREPC.getBootstrapSymbols(
  162. {{SAs.Allocator, rt::SimpleExecutorMemoryManagerInstanceName},
  163. {SAs.Reserve, rt::SimpleExecutorMemoryManagerReserveWrapperName},
  164. {SAs.Finalize, rt::SimpleExecutorMemoryManagerFinalizeWrapperName},
  165. {SAs.Deallocate,
  166. rt::SimpleExecutorMemoryManagerDeallocateWrapperName}}))
  167. return std::move(Err);
  168. return std::make_unique<EPCGenericJITLinkMemoryManager>(SREPC, SAs);
  169. }
  170. Expected<std::unique_ptr<ExecutorProcessControl::MemoryAccess>>
  171. SimpleRemoteEPC::createDefaultMemoryAccess(SimpleRemoteEPC &SREPC) {
  172. return nullptr;
  173. }
  174. Error SimpleRemoteEPC::sendMessage(SimpleRemoteEPCOpcode OpC, uint64_t SeqNo,
  175. ExecutorAddr TagAddr,
  176. ArrayRef<char> ArgBytes) {
  177. assert(OpC != SimpleRemoteEPCOpcode::Setup &&
  178. "SimpleRemoteEPC sending Setup message? That's the wrong direction.");
  179. LLVM_DEBUG({
  180. dbgs() << "SimpleRemoteEPC::sendMessage: opc = ";
  181. switch (OpC) {
  182. case SimpleRemoteEPCOpcode::Hangup:
  183. dbgs() << "Hangup";
  184. assert(SeqNo == 0 && "Non-zero SeqNo for Hangup?");
  185. assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Hangup?");
  186. break;
  187. case SimpleRemoteEPCOpcode::Result:
  188. dbgs() << "Result";
  189. assert(TagAddr.getValue() == 0 && "Non-zero TagAddr for Result?");
  190. break;
  191. case SimpleRemoteEPCOpcode::CallWrapper:
  192. dbgs() << "CallWrapper";
  193. break;
  194. default:
  195. llvm_unreachable("Invalid opcode");
  196. }
  197. dbgs() << ", seqno = " << SeqNo
  198. << ", tag-addr = " << formatv("{0:x}", TagAddr.getValue())
  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. Error SimpleRemoteEPC::handleSetup(uint64_t SeqNo, ExecutorAddr TagAddr,
  210. SimpleRemoteEPCArgBytesVector ArgBytes) {
  211. if (SeqNo != 0)
  212. return make_error<StringError>("Setup packet SeqNo not zero",
  213. inconvertibleErrorCode());
  214. if (TagAddr)
  215. return make_error<StringError>("Setup packet TagAddr not zero",
  216. inconvertibleErrorCode());
  217. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  218. auto I = PendingCallWrapperResults.find(0);
  219. assert(PendingCallWrapperResults.size() == 1 &&
  220. I != PendingCallWrapperResults.end() &&
  221. "Setup message handler not connectly set up");
  222. auto SetupMsgHandler = std::move(I->second);
  223. PendingCallWrapperResults.erase(I);
  224. auto WFR =
  225. shared::WrapperFunctionResult::copyFrom(ArgBytes.data(), ArgBytes.size());
  226. SetupMsgHandler(std::move(WFR));
  227. return Error::success();
  228. }
  229. Error SimpleRemoteEPC::setup(Setup S) {
  230. using namespace SimpleRemoteEPCDefaultBootstrapSymbolNames;
  231. std::promise<MSVCPExpected<SimpleRemoteEPCExecutorInfo>> EIP;
  232. auto EIF = EIP.get_future();
  233. // Prepare a handler for the setup packet.
  234. PendingCallWrapperResults[0] =
  235. RunInPlace()(
  236. [&](shared::WrapperFunctionResult SetupMsgBytes) {
  237. if (const char *ErrMsg = SetupMsgBytes.getOutOfBandError()) {
  238. EIP.set_value(
  239. make_error<StringError>(ErrMsg, inconvertibleErrorCode()));
  240. return;
  241. }
  242. using SPSSerialize =
  243. shared::SPSArgList<shared::SPSSimpleRemoteEPCExecutorInfo>;
  244. shared::SPSInputBuffer IB(SetupMsgBytes.data(), SetupMsgBytes.size());
  245. SimpleRemoteEPCExecutorInfo EI;
  246. if (SPSSerialize::deserialize(IB, EI))
  247. EIP.set_value(EI);
  248. else
  249. EIP.set_value(make_error<StringError>(
  250. "Could not deserialize setup message", inconvertibleErrorCode()));
  251. });
  252. // Start the transport.
  253. if (auto Err = T->start())
  254. return Err;
  255. // Wait for setup packet to arrive.
  256. auto EI = EIF.get();
  257. if (!EI) {
  258. T->disconnect();
  259. return EI.takeError();
  260. }
  261. LLVM_DEBUG({
  262. dbgs() << "SimpleRemoteEPC received setup message:\n"
  263. << " Triple: " << EI->TargetTriple << "\n"
  264. << " Page size: " << EI->PageSize << "\n"
  265. << " Bootstrap symbols:\n";
  266. for (const auto &KV : EI->BootstrapSymbols)
  267. dbgs() << " " << KV.first() << ": "
  268. << formatv("{0:x16}", KV.second.getValue()) << "\n";
  269. });
  270. TargetTriple = Triple(EI->TargetTriple);
  271. PageSize = EI->PageSize;
  272. BootstrapSymbols = std::move(EI->BootstrapSymbols);
  273. if (auto Err = getBootstrapSymbols(
  274. {{JDI.JITDispatchContext, ExecutorSessionObjectName},
  275. {JDI.JITDispatchFunction, DispatchFnName},
  276. {RunAsMainAddr, rt::RunAsMainWrapperName}}))
  277. return Err;
  278. if (auto DM =
  279. EPCGenericDylibManager::CreateWithDefaultBootstrapSymbols(*this))
  280. DylibMgr = std::make_unique<EPCGenericDylibManager>(std::move(*DM));
  281. else
  282. return DM.takeError();
  283. // Set a default CreateMemoryManager if none is specified.
  284. if (!S.CreateMemoryManager)
  285. S.CreateMemoryManager = createDefaultMemoryManager;
  286. if (auto MemMgr = S.CreateMemoryManager(*this)) {
  287. OwnedMemMgr = std::move(*MemMgr);
  288. this->MemMgr = OwnedMemMgr.get();
  289. } else
  290. return MemMgr.takeError();
  291. // Set a default CreateMemoryAccess if none is specified.
  292. if (!S.CreateMemoryAccess)
  293. S.CreateMemoryAccess = createDefaultMemoryAccess;
  294. if (auto MemAccess = S.CreateMemoryAccess(*this)) {
  295. OwnedMemAccess = std::move(*MemAccess);
  296. this->MemAccess = OwnedMemAccess.get();
  297. } else
  298. return MemAccess.takeError();
  299. return Error::success();
  300. }
  301. Error SimpleRemoteEPC::handleResult(uint64_t SeqNo, ExecutorAddr TagAddr,
  302. SimpleRemoteEPCArgBytesVector ArgBytes) {
  303. IncomingWFRHandler SendResult;
  304. if (TagAddr)
  305. return make_error<StringError>("Unexpected TagAddr in result message",
  306. inconvertibleErrorCode());
  307. {
  308. std::lock_guard<std::mutex> Lock(SimpleRemoteEPCMutex);
  309. auto I = PendingCallWrapperResults.find(SeqNo);
  310. if (I == PendingCallWrapperResults.end())
  311. return make_error<StringError>("No call for sequence number " +
  312. Twine(SeqNo),
  313. inconvertibleErrorCode());
  314. SendResult = std::move(I->second);
  315. PendingCallWrapperResults.erase(I);
  316. releaseSeqNo(SeqNo);
  317. }
  318. auto WFR =
  319. shared::WrapperFunctionResult::copyFrom(ArgBytes.data(), ArgBytes.size());
  320. SendResult(std::move(WFR));
  321. return Error::success();
  322. }
  323. void SimpleRemoteEPC::handleCallWrapper(
  324. uint64_t RemoteSeqNo, ExecutorAddr TagAddr,
  325. SimpleRemoteEPCArgBytesVector ArgBytes) {
  326. assert(ES && "No ExecutionSession attached");
  327. D->dispatch(makeGenericNamedTask(
  328. [this, RemoteSeqNo, TagAddr, ArgBytes = std::move(ArgBytes)]() {
  329. ES->runJITDispatchHandler(
  330. [this, RemoteSeqNo](shared::WrapperFunctionResult WFR) {
  331. if (auto Err =
  332. sendMessage(SimpleRemoteEPCOpcode::Result, RemoteSeqNo,
  333. ExecutorAddr(), {WFR.data(), WFR.size()}))
  334. getExecutionSession().reportError(std::move(Err));
  335. },
  336. TagAddr.getValue(), ArgBytes);
  337. },
  338. "callWrapper task"));
  339. }
  340. Error SimpleRemoteEPC::handleHangup(SimpleRemoteEPCArgBytesVector ArgBytes) {
  341. using namespace llvm::orc::shared;
  342. auto WFR = WrapperFunctionResult::copyFrom(ArgBytes.data(), ArgBytes.size());
  343. if (const char *ErrMsg = WFR.getOutOfBandError())
  344. return make_error<StringError>(ErrMsg, inconvertibleErrorCode());
  345. detail::SPSSerializableError Info;
  346. SPSInputBuffer IB(WFR.data(), WFR.size());
  347. if (!SPSArgList<SPSError>::deserialize(IB, Info))
  348. return make_error<StringError>("Could not deserialize hangup info",
  349. inconvertibleErrorCode());
  350. return fromSPSSerializable(std::move(Info));
  351. }
  352. } // end namespace orc
  353. } // end namespace llvm