xref: /llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp (revision 4d7cea3d2e833209d06e201a273f97342035c196)
1 //===---- ExecutorProcessControl.cpp -- Executor process control APIs -----===//
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 #include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h"
10 
11 #include "llvm/ExecutionEngine/Orc/Core.h"
12 #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
13 #include "llvm/Support/FormatVariadic.h"
14 #include "llvm/Support/Host.h"
15 #include "llvm/Support/Process.h"
16 
17 #define DEBUG_TYPE "orc"
18 
19 namespace llvm {
20 namespace orc {
21 
22 ExecutorProcessControl::MemoryAccess::~MemoryAccess() {}
23 
24 ExecutorProcessControl::~ExecutorProcessControl() {}
25 
26 SelfExecutorProcessControl::SelfExecutorProcessControl(
27     std::shared_ptr<SymbolStringPool> SSP, std::unique_ptr<TaskDispatcher> D,
28     Triple TargetTriple, unsigned PageSize,
29     std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr)
30     : ExecutorProcessControl(std::move(SSP), std::move(D)) {
31 
32   OwnedMemMgr = std::move(MemMgr);
33   if (!OwnedMemMgr)
34     OwnedMemMgr = std::make_unique<jitlink::InProcessMemoryManager>();
35 
36   this->TargetTriple = std::move(TargetTriple);
37   this->PageSize = PageSize;
38   this->MemMgr = OwnedMemMgr.get();
39   this->MemAccess = this;
40   this->JDI = {ExecutorAddr::fromPtr(jitDispatchViaWrapperFunctionManager),
41                ExecutorAddr::fromPtr(this)};
42   if (this->TargetTriple.isOSBinFormatMachO())
43     GlobalManglingPrefix = '_';
44 }
45 
46 Expected<std::unique_ptr<SelfExecutorProcessControl>>
47 SelfExecutorProcessControl::Create(
48     std::shared_ptr<SymbolStringPool> SSP,
49     std::unique_ptr<TaskDispatcher> D,
50     std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr) {
51 
52   if (!SSP)
53     SSP = std::make_shared<SymbolStringPool>();
54 
55   if (!D) {
56 #if LLVM_ENABLE_THREADS
57     D = std::make_unique<DynamicThreadPoolTaskDispatcher>();
58 #else
59     D = std::make_unique<InPlaceTaskDispatcher>();
60 #endif
61   }
62 
63   auto PageSize = sys::Process::getPageSize();
64   if (!PageSize)
65     return PageSize.takeError();
66 
67   Triple TT(sys::getProcessTriple());
68 
69   return std::make_unique<SelfExecutorProcessControl>(
70       std::move(SSP), std::move(D), std::move(TT), *PageSize,
71       std::move(MemMgr));
72 }
73 
74 Expected<tpctypes::DylibHandle>
75 SelfExecutorProcessControl::loadDylib(const char *DylibPath) {
76   std::string ErrMsg;
77   auto Dylib = std::make_unique<sys::DynamicLibrary>(
78       sys::DynamicLibrary::getPermanentLibrary(DylibPath, &ErrMsg));
79   if (!Dylib->isValid())
80     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
81   DynamicLibraries.push_back(std::move(Dylib));
82   return pointerToJITTargetAddress(DynamicLibraries.back().get());
83 }
84 
85 Expected<std::vector<tpctypes::LookupResult>>
86 SelfExecutorProcessControl::lookupSymbols(ArrayRef<LookupRequest> Request) {
87   std::vector<tpctypes::LookupResult> R;
88 
89   for (auto &Elem : Request) {
90     auto *Dylib = jitTargetAddressToPointer<sys::DynamicLibrary *>(Elem.Handle);
91     assert(llvm::any_of(DynamicLibraries,
92                         [=](const std::unique_ptr<sys::DynamicLibrary> &DL) {
93                           return DL.get() == Dylib;
94                         }) &&
95            "Invalid handle");
96 
97     R.push_back(std::vector<JITTargetAddress>());
98     for (auto &KV : Elem.Symbols) {
99       auto &Sym = KV.first;
100       std::string Tmp((*Sym).data() + !!GlobalManglingPrefix,
101                       (*Sym).size() - !!GlobalManglingPrefix);
102       void *Addr = Dylib->getAddressOfSymbol(Tmp.c_str());
103       if (!Addr && KV.second == SymbolLookupFlags::RequiredSymbol) {
104         // FIXME: Collect all failing symbols before erroring out.
105         SymbolNameVector MissingSymbols;
106         MissingSymbols.push_back(Sym);
107         return make_error<SymbolsNotFound>(SSP, std::move(MissingSymbols));
108       }
109       R.back().push_back(pointerToJITTargetAddress(Addr));
110     }
111   }
112 
113   return R;
114 }
115 
116 Expected<int32_t>
117 SelfExecutorProcessControl::runAsMain(ExecutorAddr MainFnAddr,
118                                       ArrayRef<std::string> Args) {
119   using MainTy = int (*)(int, char *[]);
120   return orc::runAsMain(MainFnAddr.toPtr<MainTy>(), Args);
121 }
122 
123 void SelfExecutorProcessControl::callWrapperAsync(ExecutorAddr WrapperFnAddr,
124                                                   IncomingWFRHandler SendResult,
125                                                   ArrayRef<char> ArgBuffer) {
126   using WrapperFnTy =
127       shared::detail::CWrapperFunctionResult (*)(const char *Data, size_t Size);
128   auto *WrapperFn = WrapperFnAddr.toPtr<WrapperFnTy>();
129   SendResult(WrapperFn(ArgBuffer.data(), ArgBuffer.size()));
130 }
131 
132 Error SelfExecutorProcessControl::disconnect() { return Error::success(); }
133 
134 void SelfExecutorProcessControl::writeUInt8sAsync(
135     ArrayRef<tpctypes::UInt8Write> Ws, WriteResultFn OnWriteComplete) {
136   for (auto &W : Ws)
137     *jitTargetAddressToPointer<uint8_t *>(W.Address) = W.Value;
138   OnWriteComplete(Error::success());
139 }
140 
141 void SelfExecutorProcessControl::writeUInt16sAsync(
142     ArrayRef<tpctypes::UInt16Write> Ws, WriteResultFn OnWriteComplete) {
143   for (auto &W : Ws)
144     *jitTargetAddressToPointer<uint16_t *>(W.Address) = W.Value;
145   OnWriteComplete(Error::success());
146 }
147 
148 void SelfExecutorProcessControl::writeUInt32sAsync(
149     ArrayRef<tpctypes::UInt32Write> Ws, WriteResultFn OnWriteComplete) {
150   for (auto &W : Ws)
151     *jitTargetAddressToPointer<uint32_t *>(W.Address) = W.Value;
152   OnWriteComplete(Error::success());
153 }
154 
155 void SelfExecutorProcessControl::writeUInt64sAsync(
156     ArrayRef<tpctypes::UInt64Write> Ws, WriteResultFn OnWriteComplete) {
157   for (auto &W : Ws)
158     *jitTargetAddressToPointer<uint64_t *>(W.Address) = W.Value;
159   OnWriteComplete(Error::success());
160 }
161 
162 void SelfExecutorProcessControl::writeBuffersAsync(
163     ArrayRef<tpctypes::BufferWrite> Ws, WriteResultFn OnWriteComplete) {
164   for (auto &W : Ws)
165     memcpy(jitTargetAddressToPointer<char *>(W.Address), W.Buffer.data(),
166            W.Buffer.size());
167   OnWriteComplete(Error::success());
168 }
169 
170 shared::detail::CWrapperFunctionResult
171 SelfExecutorProcessControl::jitDispatchViaWrapperFunctionManager(
172     void *Ctx, const void *FnTag, const char *Data, size_t Size) {
173 
174   LLVM_DEBUG({
175     dbgs() << "jit-dispatch call with tag " << FnTag << " and " << Size
176            << " byte payload.\n";
177   });
178 
179   std::promise<shared::WrapperFunctionResult> ResultP;
180   auto ResultF = ResultP.get_future();
181   static_cast<SelfExecutorProcessControl *>(Ctx)
182       ->getExecutionSession()
183       .runJITDispatchHandler(
184           [ResultP = std::move(ResultP)](
185               shared::WrapperFunctionResult Result) mutable {
186             ResultP.set_value(std::move(Result));
187           },
188           pointerToJITTargetAddress(FnTag), {Data, Size});
189 
190   return ResultF.get().release();
191 }
192 
193 } // end namespace orc
194 } // end namespace llvm
195