xref: /llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp (revision 122ebe3b500190b1f408e2e6db753853e297ba28)
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/Shared/OrcRTBridge.h"
13 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
14 #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h"
15 #include "llvm/Support/FormatVariadic.h"
16 #include "llvm/Support/Process.h"
17 #include "llvm/TargetParser/Host.h"
18 
19 #define DEBUG_TYPE "orc"
20 
21 namespace llvm {
22 namespace orc {
23 
24 ExecutorProcessControl::MemoryAccess::~MemoryAccess() = default;
25 
26 ExecutorProcessControl::~ExecutorProcessControl() = default;
27 
28 SelfExecutorProcessControl::SelfExecutorProcessControl(
29     std::shared_ptr<SymbolStringPool> SSP, std::unique_ptr<TaskDispatcher> D,
30     Triple TargetTriple, unsigned PageSize,
31     std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr)
32     : ExecutorProcessControl(std::move(SSP), std::move(D)) {
33 
34   OwnedMemMgr = std::move(MemMgr);
35   if (!OwnedMemMgr)
36     OwnedMemMgr = std::make_unique<jitlink::InProcessMemoryManager>(
37         sys::Process::getPageSizeEstimate());
38 
39   this->TargetTriple = std::move(TargetTriple);
40   this->PageSize = PageSize;
41   this->MemMgr = OwnedMemMgr.get();
42   this->MemAccess = this;
43   this->JDI = {ExecutorAddr::fromPtr(jitDispatchViaWrapperFunctionManager),
44                ExecutorAddr::fromPtr(this)};
45   if (this->TargetTriple.isOSBinFormatMachO())
46     GlobalManglingPrefix = '_';
47 
48   this->BootstrapSymbols[rt::RegisterEHFrameSectionWrapperName] =
49       ExecutorAddr::fromPtr(&llvm_orc_registerEHFrameSectionWrapper);
50   this->BootstrapSymbols[rt::DeregisterEHFrameSectionWrapperName] =
51       ExecutorAddr::fromPtr(&llvm_orc_deregisterEHFrameSectionWrapper);
52 }
53 
54 Expected<std::unique_ptr<SelfExecutorProcessControl>>
55 SelfExecutorProcessControl::Create(
56     std::shared_ptr<SymbolStringPool> SSP,
57     std::unique_ptr<TaskDispatcher> D,
58     std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr) {
59 
60   if (!SSP)
61     SSP = std::make_shared<SymbolStringPool>();
62 
63   if (!D) {
64 #if LLVM_ENABLE_THREADS
65     D = std::make_unique<DynamicThreadPoolTaskDispatcher>();
66 #else
67     D = std::make_unique<InPlaceTaskDispatcher>();
68 #endif
69   }
70 
71   auto PageSize = sys::Process::getPageSize();
72   if (!PageSize)
73     return PageSize.takeError();
74 
75   Triple TT(sys::getProcessTriple());
76 
77   return std::make_unique<SelfExecutorProcessControl>(
78       std::move(SSP), std::move(D), std::move(TT), *PageSize,
79       std::move(MemMgr));
80 }
81 
82 Expected<tpctypes::DylibHandle>
83 SelfExecutorProcessControl::loadDylib(const char *DylibPath) {
84   std::string ErrMsg;
85   auto Dylib = sys::DynamicLibrary::getPermanentLibrary(DylibPath, &ErrMsg);
86   if (!Dylib.isValid())
87     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
88   return ExecutorAddr::fromPtr(Dylib.getOSSpecificHandle());
89 }
90 
91 Expected<std::vector<tpctypes::LookupResult>>
92 SelfExecutorProcessControl::lookupSymbols(ArrayRef<LookupRequest> Request) {
93   std::vector<tpctypes::LookupResult> R;
94 
95   for (auto &Elem : Request) {
96     sys::DynamicLibrary Dylib(Elem.Handle.toPtr<void *>());
97     R.push_back(std::vector<ExecutorAddr>());
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(ExecutorAddr::fromPtr(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 Expected<int32_t>
124 SelfExecutorProcessControl::runAsVoidFunction(ExecutorAddr VoidFnAddr) {
125   using VoidTy = int (*)();
126   return orc::runAsVoidFunction(VoidFnAddr.toPtr<VoidTy>());
127 }
128 
129 Expected<int32_t>
130 SelfExecutorProcessControl::runAsIntFunction(ExecutorAddr IntFnAddr, int Arg) {
131   using IntTy = int (*)(int);
132   return orc::runAsIntFunction(IntFnAddr.toPtr<IntTy>(), Arg);
133 }
134 
135 void SelfExecutorProcessControl::callWrapperAsync(ExecutorAddr WrapperFnAddr,
136                                                   IncomingWFRHandler SendResult,
137                                                   ArrayRef<char> ArgBuffer) {
138   using WrapperFnTy =
139       shared::CWrapperFunctionResult (*)(const char *Data, size_t Size);
140   auto *WrapperFn = WrapperFnAddr.toPtr<WrapperFnTy>();
141   SendResult(WrapperFn(ArgBuffer.data(), ArgBuffer.size()));
142 }
143 
144 Error SelfExecutorProcessControl::disconnect() {
145   D->shutdown();
146   return Error::success();
147 }
148 
149 void SelfExecutorProcessControl::writeUInt8sAsync(
150     ArrayRef<tpctypes::UInt8Write> Ws, WriteResultFn OnWriteComplete) {
151   for (auto &W : Ws)
152     *W.Addr.toPtr<uint8_t *>() = W.Value;
153   OnWriteComplete(Error::success());
154 }
155 
156 void SelfExecutorProcessControl::writeUInt16sAsync(
157     ArrayRef<tpctypes::UInt16Write> Ws, WriteResultFn OnWriteComplete) {
158   for (auto &W : Ws)
159     *W.Addr.toPtr<uint16_t *>() = W.Value;
160   OnWriteComplete(Error::success());
161 }
162 
163 void SelfExecutorProcessControl::writeUInt32sAsync(
164     ArrayRef<tpctypes::UInt32Write> Ws, WriteResultFn OnWriteComplete) {
165   for (auto &W : Ws)
166     *W.Addr.toPtr<uint32_t *>() = W.Value;
167   OnWriteComplete(Error::success());
168 }
169 
170 void SelfExecutorProcessControl::writeUInt64sAsync(
171     ArrayRef<tpctypes::UInt64Write> Ws, WriteResultFn OnWriteComplete) {
172   for (auto &W : Ws)
173     *W.Addr.toPtr<uint64_t *>() = W.Value;
174   OnWriteComplete(Error::success());
175 }
176 
177 void SelfExecutorProcessControl::writeBuffersAsync(
178     ArrayRef<tpctypes::BufferWrite> Ws, WriteResultFn OnWriteComplete) {
179   for (auto &W : Ws)
180     memcpy(W.Addr.toPtr<char *>(), W.Buffer.data(), W.Buffer.size());
181   OnWriteComplete(Error::success());
182 }
183 
184 shared::CWrapperFunctionResult
185 SelfExecutorProcessControl::jitDispatchViaWrapperFunctionManager(
186     void *Ctx, const void *FnTag, const char *Data, size_t Size) {
187 
188   LLVM_DEBUG({
189     dbgs() << "jit-dispatch call with tag " << FnTag << " and " << Size
190            << " byte payload.\n";
191   });
192 
193   std::promise<shared::WrapperFunctionResult> ResultP;
194   auto ResultF = ResultP.get_future();
195   static_cast<SelfExecutorProcessControl *>(Ctx)
196       ->getExecutionSession()
197       .runJITDispatchHandler(
198           [ResultP = std::move(ResultP)](
199               shared::WrapperFunctionResult Result) mutable {
200             ResultP.set_value(std::move(Result));
201           },
202           ExecutorAddr::fromPtr(FnTag), {Data, Size});
203 
204   return ResultF.get().release();
205 }
206 
207 } // end namespace orc
208 } // end namespace llvm
209