1 //===- ExecutorProcessControl.h - Executor process control APIs -*- C++ -*-===//
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 //
9 // Utilities for interacting with the executor processes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTORPROCESSCONTROL_H
14 #define LLVM_EXECUTIONENGINE_ORC_EXECUTORPROCESSCONTROL_H
15 
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
19 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
20 #include "llvm/ExecutionEngine/Orc/Shared/TargetProcessControlTypes.h"
21 #include "llvm/ExecutionEngine/Orc/Shared/WrapperFunctionUtils.h"
22 #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h"
23 #include "llvm/ExecutionEngine/Orc/TaskDispatch.h"
24 #include "llvm/Support/DynamicLibrary.h"
25 #include "llvm/Support/MSVCErrorWorkarounds.h"
26 
27 #include <future>
28 #include <mutex>
29 #include <vector>
30 
31 namespace llvm {
32 namespace orc {
33 
34 class ExecutionSession;
35 class SymbolLookupSet;
36 
37 /// ExecutorProcessControl supports interaction with a JIT target process.
38 class ExecutorProcessControl {
39   friend class ExecutionSession;
40 public:
41 
42   /// A handler or incoming WrapperFunctionResults -- either return values from
43   /// callWrapper* calls, or incoming JIT-dispatch requests.
44   ///
45   /// IncomingWFRHandlers are constructible from
46   /// unique_function<void(shared::WrapperFunctionResult)>s using the
47   /// runInPlace function or a RunWithDispatch object.
48   class IncomingWFRHandler {
49     friend class ExecutorProcessControl;
50   public:
51     IncomingWFRHandler() = default;
52     explicit operator bool() const { return !!H; }
operator()53     void operator()(shared::WrapperFunctionResult WFR) { H(std::move(WFR)); }
54   private:
IncomingWFRHandler(FnT && Fn)55     template <typename FnT> IncomingWFRHandler(FnT &&Fn)
56       : H(std::forward<FnT>(Fn)) {}
57 
58     unique_function<void(shared::WrapperFunctionResult)> H;
59   };
60 
61   /// Constructs an IncomingWFRHandler from a function object that is callable
62   /// as void(shared::WrapperFunctionResult). The function object will be called
63   /// directly. This should be used with care as it may block listener threads
64   /// in remote EPCs. It is only suitable for simple tasks (e.g. setting a
65   /// future), or for performing some quick analysis before dispatching "real"
66   /// work as a Task.
67   class RunInPlace {
68   public:
69     template <typename FnT>
operator()70     IncomingWFRHandler operator()(FnT &&Fn) {
71       return IncomingWFRHandler(std::forward<FnT>(Fn));
72     }
73   };
74 
75   /// Constructs an IncomingWFRHandler from a function object by creating a new
76   /// function object that dispatches the original using a TaskDispatcher,
77   /// wrapping the original as a GenericNamedTask.
78   ///
79   /// This is the default approach for running WFR handlers.
80   class RunAsTask {
81   public:
RunAsTask(TaskDispatcher & D)82     RunAsTask(TaskDispatcher &D) : D(D) {}
83 
84     template <typename FnT>
operator()85     IncomingWFRHandler operator()(FnT &&Fn) {
86       return IncomingWFRHandler(
87           [&D = this->D, Fn = std::move(Fn)]
88           (shared::WrapperFunctionResult WFR) mutable {
89               D.dispatch(
90                 makeGenericNamedTask(
91                     [Fn = std::move(Fn), WFR = std::move(WFR)]() mutable {
92                       Fn(std::move(WFR));
93                     }, "WFR handler task"));
94           });
95     }
96   private:
97     TaskDispatcher &D;
98   };
99 
100   /// APIs for manipulating memory in the target process.
101   class MemoryAccess {
102   public:
103     /// Callback function for asynchronous writes.
104     using WriteResultFn = unique_function<void(Error)>;
105 
106     virtual ~MemoryAccess();
107 
108     virtual void writeUInt8sAsync(ArrayRef<tpctypes::UInt8Write> Ws,
109                                   WriteResultFn OnWriteComplete) = 0;
110 
111     virtual void writeUInt16sAsync(ArrayRef<tpctypes::UInt16Write> Ws,
112                                    WriteResultFn OnWriteComplete) = 0;
113 
114     virtual void writeUInt32sAsync(ArrayRef<tpctypes::UInt32Write> Ws,
115                                    WriteResultFn OnWriteComplete) = 0;
116 
117     virtual void writeUInt64sAsync(ArrayRef<tpctypes::UInt64Write> Ws,
118                                    WriteResultFn OnWriteComplete) = 0;
119 
120     virtual void writeBuffersAsync(ArrayRef<tpctypes::BufferWrite> Ws,
121                                    WriteResultFn OnWriteComplete) = 0;
122 
writeUInt8s(ArrayRef<tpctypes::UInt8Write> Ws)123     Error writeUInt8s(ArrayRef<tpctypes::UInt8Write> Ws) {
124       std::promise<MSVCPError> ResultP;
125       auto ResultF = ResultP.get_future();
126       writeUInt8sAsync(Ws,
127                        [&](Error Err) { ResultP.set_value(std::move(Err)); });
128       return ResultF.get();
129     }
130 
writeUInt16s(ArrayRef<tpctypes::UInt16Write> Ws)131     Error writeUInt16s(ArrayRef<tpctypes::UInt16Write> Ws) {
132       std::promise<MSVCPError> ResultP;
133       auto ResultF = ResultP.get_future();
134       writeUInt16sAsync(Ws,
135                         [&](Error Err) { ResultP.set_value(std::move(Err)); });
136       return ResultF.get();
137     }
138 
writeUInt32s(ArrayRef<tpctypes::UInt32Write> Ws)139     Error writeUInt32s(ArrayRef<tpctypes::UInt32Write> Ws) {
140       std::promise<MSVCPError> ResultP;
141       auto ResultF = ResultP.get_future();
142       writeUInt32sAsync(Ws,
143                         [&](Error Err) { ResultP.set_value(std::move(Err)); });
144       return ResultF.get();
145     }
146 
writeUInt64s(ArrayRef<tpctypes::UInt64Write> Ws)147     Error writeUInt64s(ArrayRef<tpctypes::UInt64Write> Ws) {
148       std::promise<MSVCPError> ResultP;
149       auto ResultF = ResultP.get_future();
150       writeUInt64sAsync(Ws,
151                         [&](Error Err) { ResultP.set_value(std::move(Err)); });
152       return ResultF.get();
153     }
154 
writeBuffers(ArrayRef<tpctypes::BufferWrite> Ws)155     Error writeBuffers(ArrayRef<tpctypes::BufferWrite> Ws) {
156       std::promise<MSVCPError> ResultP;
157       auto ResultF = ResultP.get_future();
158       writeBuffersAsync(Ws,
159                         [&](Error Err) { ResultP.set_value(std::move(Err)); });
160       return ResultF.get();
161     }
162   };
163 
164   /// A pair of a dylib and a set of symbols to be looked up.
165   struct LookupRequest {
LookupRequestLookupRequest166     LookupRequest(tpctypes::DylibHandle Handle, const SymbolLookupSet &Symbols)
167         : Handle(Handle), Symbols(Symbols) {}
168     tpctypes::DylibHandle Handle;
169     const SymbolLookupSet &Symbols;
170   };
171 
172   /// Contains the address of the dispatch function and context that the ORC
173   /// runtime can use to call functions in the JIT.
174   struct JITDispatchInfo {
175     ExecutorAddr JITDispatchFunction;
176     ExecutorAddr JITDispatchContext;
177   };
178 
ExecutorProcessControl(std::shared_ptr<SymbolStringPool> SSP,std::unique_ptr<TaskDispatcher> D)179   ExecutorProcessControl(std::shared_ptr<SymbolStringPool> SSP,
180                          std::unique_ptr<TaskDispatcher> D)
181     : SSP(std::move(SSP)), D(std::move(D)) {}
182 
183   virtual ~ExecutorProcessControl();
184 
185   /// Return the ExecutionSession associated with this instance.
186   /// Not callable until the ExecutionSession has been associated.
getExecutionSession()187   ExecutionSession &getExecutionSession() {
188     assert(ES && "No ExecutionSession associated yet");
189     return *ES;
190   }
191 
192   /// Intern a symbol name in the SymbolStringPool.
intern(StringRef SymName)193   SymbolStringPtr intern(StringRef SymName) { return SSP->intern(SymName); }
194 
195   /// Return a shared pointer to the SymbolStringPool for this instance.
getSymbolStringPool()196   std::shared_ptr<SymbolStringPool> getSymbolStringPool() const { return SSP; }
197 
getDispatcher()198   TaskDispatcher &getDispatcher() { return *D; }
199 
200   /// Return the Triple for the target process.
getTargetTriple()201   const Triple &getTargetTriple() const { return TargetTriple; }
202 
203   /// Get the page size for the target process.
getPageSize()204   unsigned getPageSize() const { return PageSize; }
205 
206   /// Get the JIT dispatch function and context address for the executor.
getJITDispatchInfo()207   const JITDispatchInfo &getJITDispatchInfo() const { return JDI; }
208 
209   /// Return a MemoryAccess object for the target process.
getMemoryAccess()210   MemoryAccess &getMemoryAccess() const {
211     assert(MemAccess && "No MemAccess object set.");
212     return *MemAccess;
213   }
214 
215   /// Return a JITLinkMemoryManager for the target process.
getMemMgr()216   jitlink::JITLinkMemoryManager &getMemMgr() const {
217     assert(MemMgr && "No MemMgr object set");
218     return *MemMgr;
219   }
220 
221   /// Returns the bootstrap symbol map.
getBootstrapSymbolsMap()222   const StringMap<ExecutorAddr> &getBootstrapSymbolsMap() const {
223     return BootstrapSymbols;
224   }
225 
226   /// For each (ExecutorAddr&, StringRef) pair, looks up the string in the
227   /// bootstrap symbols map and writes its address to the ExecutorAddr if
228   /// found. If any symbol is not found then the function returns an error.
getBootstrapSymbols(ArrayRef<std::pair<ExecutorAddr &,StringRef>> Pairs)229   Error getBootstrapSymbols(
230       ArrayRef<std::pair<ExecutorAddr &, StringRef>> Pairs) const {
231     for (auto &KV : Pairs) {
232       auto I = BootstrapSymbols.find(KV.second);
233       if (I == BootstrapSymbols.end())
234         return make_error<StringError>("Symbol \"" + KV.second +
235                                            "\" not found "
236                                            "in bootstrap symbols map",
237                                        inconvertibleErrorCode());
238 
239       KV.first = I->second;
240     }
241     return Error::success();
242   }
243 
244   /// Load the dynamic library at the given path and return a handle to it.
245   /// If LibraryPath is null this function will return the global handle for
246   /// the target process.
247   virtual Expected<tpctypes::DylibHandle> loadDylib(const char *DylibPath) = 0;
248 
249   /// Search for symbols in the target process.
250   ///
251   /// The result of the lookup is a 2-dimentional array of target addresses
252   /// that correspond to the lookup order. If a required symbol is not
253   /// found then this method will return an error. If a weakly referenced
254   /// symbol is not found then it be assigned a '0' value.
255   virtual Expected<std::vector<tpctypes::LookupResult>>
256   lookupSymbols(ArrayRef<LookupRequest> Request) = 0;
257 
258   /// Run function with a main-like signature.
259   virtual Expected<int32_t> runAsMain(ExecutorAddr MainFnAddr,
260                                       ArrayRef<std::string> Args) = 0;
261 
262   /// Run a wrapper function in the executor. The given WFRHandler will be
263   /// called on the result when it is returned.
264   ///
265   /// The wrapper function should be callable as:
266   ///
267   /// \code{.cpp}
268   ///   CWrapperFunctionResult fn(uint8_t *Data, uint64_t Size);
269   /// \endcode{.cpp}
270   virtual void callWrapperAsync(ExecutorAddr WrapperFnAddr,
271                                 IncomingWFRHandler OnComplete,
272                                 ArrayRef<char> ArgBuffer) = 0;
273 
274   /// Run a wrapper function in the executor using the given Runner to dispatch
275   /// OnComplete when the result is ready.
276   template <typename RunPolicyT, typename FnT>
callWrapperAsync(RunPolicyT && Runner,ExecutorAddr WrapperFnAddr,FnT && OnComplete,ArrayRef<char> ArgBuffer)277   void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
278                         FnT &&OnComplete, ArrayRef<char> ArgBuffer) {
279     callWrapperAsync(
280         WrapperFnAddr, Runner(std::forward<FnT>(OnComplete)), ArgBuffer);
281   }
282 
283   /// Run a wrapper function in the executor. OnComplete will be dispatched
284   /// as a GenericNamedTask using this instance's TaskDispatch object.
285   template <typename FnT>
callWrapperAsync(ExecutorAddr WrapperFnAddr,FnT && OnComplete,ArrayRef<char> ArgBuffer)286   void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete,
287                         ArrayRef<char> ArgBuffer) {
288     callWrapperAsync(RunAsTask(*D), WrapperFnAddr,
289                      std::forward<FnT>(OnComplete), ArgBuffer);
290   }
291 
292   /// Run a wrapper function in the executor. The wrapper function should be
293   /// callable as:
294   ///
295   /// \code{.cpp}
296   ///   CWrapperFunctionResult fn(uint8_t *Data, uint64_t Size);
297   /// \endcode{.cpp}
callWrapper(ExecutorAddr WrapperFnAddr,ArrayRef<char> ArgBuffer)298   shared::WrapperFunctionResult callWrapper(ExecutorAddr WrapperFnAddr,
299                                             ArrayRef<char> ArgBuffer) {
300     std::promise<shared::WrapperFunctionResult> RP;
301     auto RF = RP.get_future();
302     callWrapperAsync(
303         RunInPlace(), WrapperFnAddr,
304         [&](shared::WrapperFunctionResult R) {
305           RP.set_value(std::move(R));
306         }, ArgBuffer);
307     return RF.get();
308   }
309 
310   /// Run a wrapper function using SPS to serialize the arguments and
311   /// deserialize the results.
312   template <typename SPSSignature, typename RunPolicyT, typename SendResultT,
313             typename... ArgTs>
callSPSWrapperAsync(RunPolicyT && Runner,ExecutorAddr WrapperFnAddr,SendResultT && SendResult,const ArgTs &...Args)314   void callSPSWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
315                            SendResultT &&SendResult, const ArgTs &...Args) {
316     shared::WrapperFunction<SPSSignature>::callAsync(
317         [this, WrapperFnAddr, Runner = std::move(Runner)]
318         (auto &&SendResult, const char *ArgData, size_t ArgSize) mutable {
319           this->callWrapperAsync(std::move(Runner), WrapperFnAddr,
320                                  std::move(SendResult),
321                                  ArrayRef<char>(ArgData, ArgSize));
322         },
323         std::forward<SendResultT>(SendResult), Args...);
324   }
325 
326   /// Run a wrapper function using SPS to serialize the arguments and
327   /// deserialize the results.
328   template <typename SPSSignature, typename SendResultT, typename... ArgTs>
callSPSWrapperAsync(ExecutorAddr WrapperFnAddr,SendResultT && SendResult,const ArgTs &...Args)329   void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult,
330                            const ArgTs &...Args) {
331     callSPSWrapperAsync<SPSSignature>(RunAsTask(*D), WrapperFnAddr,
332                                       std::forward<SendResultT>(SendResult),
333                                       Args...);
334   }
335 
336   /// Run a wrapper function using SPS to serialize the arguments and
337   /// deserialize the results.
338   ///
339   /// If SPSSignature is a non-void function signature then the second argument
340   /// (the first in the Args list) should be a reference to a return value.
341   template <typename SPSSignature, typename... WrapperCallArgTs>
callSPSWrapper(ExecutorAddr WrapperFnAddr,WrapperCallArgTs &&...WrapperCallArgs)342   Error callSPSWrapper(ExecutorAddr WrapperFnAddr,
343                        WrapperCallArgTs &&...WrapperCallArgs) {
344     return shared::WrapperFunction<SPSSignature>::call(
345         [this, WrapperFnAddr](const char *ArgData, size_t ArgSize) {
346           return callWrapper(WrapperFnAddr, ArrayRef<char>(ArgData, ArgSize));
347         },
348         std::forward<WrapperCallArgTs>(WrapperCallArgs)...);
349   }
350 
351   /// Disconnect from the target process.
352   ///
353   /// This should be called after the JIT session is shut down.
354   virtual Error disconnect() = 0;
355 
356 protected:
357 
358   std::shared_ptr<SymbolStringPool> SSP;
359   std::unique_ptr<TaskDispatcher> D;
360   ExecutionSession *ES = nullptr;
361   Triple TargetTriple;
362   unsigned PageSize = 0;
363   JITDispatchInfo JDI;
364   MemoryAccess *MemAccess = nullptr;
365   jitlink::JITLinkMemoryManager *MemMgr = nullptr;
366   StringMap<ExecutorAddr> BootstrapSymbols;
367 };
368 
369 /// A ExecutorProcessControl instance that asserts if any of its methods are
370 /// used. Suitable for use is unit tests, and by ORC clients who haven't moved
371 /// to ExecutorProcessControl-based APIs yet.
372 class UnsupportedExecutorProcessControl : public ExecutorProcessControl {
373 public:
374   UnsupportedExecutorProcessControl(
375       std::shared_ptr<SymbolStringPool> SSP = nullptr,
376       std::unique_ptr<TaskDispatcher> D = nullptr,
377       const std::string &TT = "", unsigned PageSize = 0)
378       : ExecutorProcessControl(SSP ? std::move(SSP)
379                                : std::make_shared<SymbolStringPool>(),
380                                D ? std::move(D)
381                                : std::make_unique<InPlaceTaskDispatcher>()) {
382     this->TargetTriple = Triple(TT);
383     this->PageSize = PageSize;
384   }
385 
loadDylib(const char * DylibPath)386   Expected<tpctypes::DylibHandle> loadDylib(const char *DylibPath) override {
387     llvm_unreachable("Unsupported");
388   }
389 
390   Expected<std::vector<tpctypes::LookupResult>>
lookupSymbols(ArrayRef<LookupRequest> Request)391   lookupSymbols(ArrayRef<LookupRequest> Request) override {
392     llvm_unreachable("Unsupported");
393   }
394 
runAsMain(ExecutorAddr MainFnAddr,ArrayRef<std::string> Args)395   Expected<int32_t> runAsMain(ExecutorAddr MainFnAddr,
396                               ArrayRef<std::string> Args) override {
397     llvm_unreachable("Unsupported");
398   }
399 
callWrapperAsync(ExecutorAddr WrapperFnAddr,IncomingWFRHandler OnComplete,ArrayRef<char> ArgBuffer)400   void callWrapperAsync(ExecutorAddr WrapperFnAddr,
401                         IncomingWFRHandler OnComplete,
402                         ArrayRef<char> ArgBuffer) override {
403     llvm_unreachable("Unsupported");
404   }
405 
disconnect()406   Error disconnect() override { return Error::success(); }
407 };
408 
409 /// A ExecutorProcessControl implementation targeting the current process.
410 class SelfExecutorProcessControl
411     : public ExecutorProcessControl,
412       private ExecutorProcessControl::MemoryAccess {
413 public:
414   SelfExecutorProcessControl(
415       std::shared_ptr<SymbolStringPool> SSP, std::unique_ptr<TaskDispatcher> D,
416       Triple TargetTriple, unsigned PageSize,
417       std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr);
418 
419   /// Create a SelfExecutorProcessControl with the given symbol string pool and
420   /// memory manager.
421   /// If no symbol string pool is given then one will be created.
422   /// If no memory manager is given a jitlink::InProcessMemoryManager will
423   /// be created and used by default.
424   static Expected<std::unique_ptr<SelfExecutorProcessControl>>
425   Create(std::shared_ptr<SymbolStringPool> SSP = nullptr,
426          std::unique_ptr<TaskDispatcher> D = nullptr,
427          std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr = nullptr);
428 
429   Expected<tpctypes::DylibHandle> loadDylib(const char *DylibPath) override;
430 
431   Expected<std::vector<tpctypes::LookupResult>>
432   lookupSymbols(ArrayRef<LookupRequest> Request) override;
433 
434   Expected<int32_t> runAsMain(ExecutorAddr MainFnAddr,
435                               ArrayRef<std::string> Args) override;
436 
437   void callWrapperAsync(ExecutorAddr WrapperFnAddr,
438                         IncomingWFRHandler OnComplete,
439                         ArrayRef<char> ArgBuffer) override;
440 
441   Error disconnect() override;
442 
443 private:
444   void writeUInt8sAsync(ArrayRef<tpctypes::UInt8Write> Ws,
445                         WriteResultFn OnWriteComplete) override;
446 
447   void writeUInt16sAsync(ArrayRef<tpctypes::UInt16Write> Ws,
448                          WriteResultFn OnWriteComplete) override;
449 
450   void writeUInt32sAsync(ArrayRef<tpctypes::UInt32Write> Ws,
451                          WriteResultFn OnWriteComplete) override;
452 
453   void writeUInt64sAsync(ArrayRef<tpctypes::UInt64Write> Ws,
454                          WriteResultFn OnWriteComplete) override;
455 
456   void writeBuffersAsync(ArrayRef<tpctypes::BufferWrite> Ws,
457                          WriteResultFn OnWriteComplete) override;
458 
459   static shared::detail::CWrapperFunctionResult
460   jitDispatchViaWrapperFunctionManager(void *Ctx, const void *FnTag,
461                                        const char *Data, size_t Size);
462 
463   std::unique_ptr<jitlink::JITLinkMemoryManager> OwnedMemMgr;
464   char GlobalManglingPrefix = 0;
465   std::vector<std::unique_ptr<sys::DynamicLibrary>> DynamicLibraries;
466 };
467 
468 } // end namespace orc
469 } // end namespace llvm
470 
471 #endif // LLVM_EXECUTIONENGINE_ORC_EXECUTORPROCESSCONTROL_H
472