xref: /freebsd-src/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp (revision cb14a3fe5122c879eae1fb480ed7ce82a699ddb6)
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       InProcessMemoryAccess(TargetTriple.isArch64Bit()) {
34 
35   OwnedMemMgr = std::move(MemMgr);
36   if (!OwnedMemMgr)
37     OwnedMemMgr = std::make_unique<jitlink::InProcessMemoryManager>(
38         sys::Process::getPageSizeEstimate());
39 
40   this->TargetTriple = std::move(TargetTriple);
41   this->PageSize = PageSize;
42   this->MemMgr = OwnedMemMgr.get();
43   this->MemAccess = this;
44   this->JDI = {ExecutorAddr::fromPtr(jitDispatchViaWrapperFunctionManager),
45                ExecutorAddr::fromPtr(this)};
46   if (this->TargetTriple.isOSBinFormatMachO())
47     GlobalManglingPrefix = '_';
48 
49   this->BootstrapSymbols[rt::RegisterEHFrameSectionWrapperName] =
50       ExecutorAddr::fromPtr(&llvm_orc_registerEHFrameSectionWrapper);
51   this->BootstrapSymbols[rt::DeregisterEHFrameSectionWrapperName] =
52       ExecutorAddr::fromPtr(&llvm_orc_deregisterEHFrameSectionWrapper);
53 }
54 
55 Expected<std::unique_ptr<SelfExecutorProcessControl>>
56 SelfExecutorProcessControl::Create(
57     std::shared_ptr<SymbolStringPool> SSP,
58     std::unique_ptr<TaskDispatcher> D,
59     std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr) {
60 
61   if (!SSP)
62     SSP = std::make_shared<SymbolStringPool>();
63 
64   if (!D) {
65 #if LLVM_ENABLE_THREADS
66     D = std::make_unique<DynamicThreadPoolTaskDispatcher>();
67 #else
68     D = std::make_unique<InPlaceTaskDispatcher>();
69 #endif
70   }
71 
72   auto PageSize = sys::Process::getPageSize();
73   if (!PageSize)
74     return PageSize.takeError();
75 
76   Triple TT(sys::getProcessTriple());
77 
78   return std::make_unique<SelfExecutorProcessControl>(
79       std::move(SSP), std::move(D), std::move(TT), *PageSize,
80       std::move(MemMgr));
81 }
82 
83 Expected<tpctypes::DylibHandle>
84 SelfExecutorProcessControl::loadDylib(const char *DylibPath) {
85   std::string ErrMsg;
86   auto Dylib = sys::DynamicLibrary::getPermanentLibrary(DylibPath, &ErrMsg);
87   if (!Dylib.isValid())
88     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
89   return ExecutorAddr::fromPtr(Dylib.getOSSpecificHandle());
90 }
91 
92 Expected<std::vector<tpctypes::LookupResult>>
93 SelfExecutorProcessControl::lookupSymbols(ArrayRef<LookupRequest> Request) {
94   std::vector<tpctypes::LookupResult> R;
95 
96   for (auto &Elem : Request) {
97     sys::DynamicLibrary Dylib(Elem.Handle.toPtr<void *>());
98     R.push_back(std::vector<ExecutorAddr>());
99     for (auto &KV : Elem.Symbols) {
100       auto &Sym = KV.first;
101       std::string Tmp((*Sym).data() + !!GlobalManglingPrefix,
102                       (*Sym).size() - !!GlobalManglingPrefix);
103       void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str());
104       if (!Addr && KV.second == SymbolLookupFlags::RequiredSymbol) {
105         // FIXME: Collect all failing symbols before erroring out.
106         SymbolNameVector MissingSymbols;
107         MissingSymbols.push_back(Sym);
108         return make_error<SymbolsNotFound>(SSP, std::move(MissingSymbols));
109       }
110       R.back().push_back(ExecutorAddr::fromPtr(Addr));
111     }
112   }
113 
114   return R;
115 }
116 
117 Expected<int32_t>
118 SelfExecutorProcessControl::runAsMain(ExecutorAddr MainFnAddr,
119                                       ArrayRef<std::string> Args) {
120   using MainTy = int (*)(int, char *[]);
121   return orc::runAsMain(MainFnAddr.toPtr<MainTy>(), Args);
122 }
123 
124 Expected<int32_t>
125 SelfExecutorProcessControl::runAsVoidFunction(ExecutorAddr VoidFnAddr) {
126   using VoidTy = int (*)();
127   return orc::runAsVoidFunction(VoidFnAddr.toPtr<VoidTy>());
128 }
129 
130 Expected<int32_t>
131 SelfExecutorProcessControl::runAsIntFunction(ExecutorAddr IntFnAddr, int Arg) {
132   using IntTy = int (*)(int);
133   return orc::runAsIntFunction(IntFnAddr.toPtr<IntTy>(), Arg);
134 }
135 
136 void SelfExecutorProcessControl::callWrapperAsync(ExecutorAddr WrapperFnAddr,
137                                                   IncomingWFRHandler SendResult,
138                                                   ArrayRef<char> ArgBuffer) {
139   using WrapperFnTy =
140       shared::CWrapperFunctionResult (*)(const char *Data, size_t Size);
141   auto *WrapperFn = WrapperFnAddr.toPtr<WrapperFnTy>();
142   SendResult(WrapperFn(ArgBuffer.data(), ArgBuffer.size()));
143 }
144 
145 Error SelfExecutorProcessControl::disconnect() {
146   D->shutdown();
147   return Error::success();
148 }
149 
150 void InProcessMemoryAccess::writeUInt8sAsync(ArrayRef<tpctypes::UInt8Write> Ws,
151                                              WriteResultFn OnWriteComplete) {
152   for (auto &W : Ws)
153     *W.Addr.toPtr<uint8_t *>() = W.Value;
154   OnWriteComplete(Error::success());
155 }
156 
157 void InProcessMemoryAccess::writeUInt16sAsync(
158     ArrayRef<tpctypes::UInt16Write> Ws, WriteResultFn OnWriteComplete) {
159   for (auto &W : Ws)
160     *W.Addr.toPtr<uint16_t *>() = W.Value;
161   OnWriteComplete(Error::success());
162 }
163 
164 void InProcessMemoryAccess::writeUInt32sAsync(
165     ArrayRef<tpctypes::UInt32Write> Ws, WriteResultFn OnWriteComplete) {
166   for (auto &W : Ws)
167     *W.Addr.toPtr<uint32_t *>() = W.Value;
168   OnWriteComplete(Error::success());
169 }
170 
171 void InProcessMemoryAccess::writeUInt64sAsync(
172     ArrayRef<tpctypes::UInt64Write> Ws, WriteResultFn OnWriteComplete) {
173   for (auto &W : Ws)
174     *W.Addr.toPtr<uint64_t *>() = W.Value;
175   OnWriteComplete(Error::success());
176 }
177 
178 void InProcessMemoryAccess::writeBuffersAsync(
179     ArrayRef<tpctypes::BufferWrite> Ws, WriteResultFn OnWriteComplete) {
180   for (auto &W : Ws)
181     memcpy(W.Addr.toPtr<char *>(), W.Buffer.data(), W.Buffer.size());
182   OnWriteComplete(Error::success());
183 }
184 
185 void InProcessMemoryAccess::writePointersAsync(
186     ArrayRef<tpctypes::PointerWrite> Ws, WriteResultFn OnWriteComplete) {
187   if (IsArch64Bit) {
188     for (auto &W : Ws)
189       *W.Addr.toPtr<uint64_t *>() = W.Value.getValue();
190   } else {
191     for (auto &W : Ws)
192       *W.Addr.toPtr<uint32_t *>() = static_cast<uint32_t>(W.Value.getValue());
193   }
194 
195   OnWriteComplete(Error::success());
196 }
197 
198 shared::CWrapperFunctionResult
199 SelfExecutorProcessControl::jitDispatchViaWrapperFunctionManager(
200     void *Ctx, const void *FnTag, const char *Data, size_t Size) {
201 
202   LLVM_DEBUG({
203     dbgs() << "jit-dispatch call with tag " << FnTag << " and " << Size
204            << " byte payload.\n";
205   });
206 
207   std::promise<shared::WrapperFunctionResult> ResultP;
208   auto ResultF = ResultP.get_future();
209   static_cast<SelfExecutorProcessControl *>(Ctx)
210       ->getExecutionSession()
211       .runJITDispatchHandler(
212           [ResultP = std::move(ResultP)](
213               shared::WrapperFunctionResult Result) mutable {
214             ResultP.set_value(std::move(Result));
215           },
216           ExecutorAddr::fromPtr(FnTag), {Data, Size});
217 
218   return ResultF.get().release();
219 }
220 
221 } // end namespace orc
222 } // end namespace llvm
223