xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/ExecutorProcessControl.cpp (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
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() = default;
23 
24 ExecutorProcessControl::~ExecutorProcessControl() = default;
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         sys::Process::getPageSizeEstimate());
36 
37   this->TargetTriple = std::move(TargetTriple);
38   this->PageSize = PageSize;
39   this->MemMgr = OwnedMemMgr.get();
40   this->MemAccess = this;
41   this->JDI = {ExecutorAddr::fromPtr(jitDispatchViaWrapperFunctionManager),
42                ExecutorAddr::fromPtr(this)};
43   if (this->TargetTriple.isOSBinFormatMachO())
44     GlobalManglingPrefix = '_';
45 }
46 
47 Expected<std::unique_ptr<SelfExecutorProcessControl>>
48 SelfExecutorProcessControl::Create(
49     std::shared_ptr<SymbolStringPool> SSP,
50     std::unique_ptr<TaskDispatcher> D,
51     std::unique_ptr<jitlink::JITLinkMemoryManager> MemMgr) {
52 
53   if (!SSP)
54     SSP = std::make_shared<SymbolStringPool>();
55 
56   if (!D) {
57 #if LLVM_ENABLE_THREADS
58     D = std::make_unique<DynamicThreadPoolTaskDispatcher>();
59 #else
60     D = std::make_unique<InPlaceTaskDispatcher>();
61 #endif
62   }
63 
64   auto PageSize = sys::Process::getPageSize();
65   if (!PageSize)
66     return PageSize.takeError();
67 
68   Triple TT(sys::getProcessTriple());
69 
70   return std::make_unique<SelfExecutorProcessControl>(
71       std::move(SSP), std::move(D), std::move(TT), *PageSize,
72       std::move(MemMgr));
73 }
74 
75 Expected<tpctypes::DylibHandle>
76 SelfExecutorProcessControl::loadDylib(const char *DylibPath) {
77   std::string ErrMsg;
78   auto Dylib = std::make_unique<sys::DynamicLibrary>(
79       sys::DynamicLibrary::getPermanentLibrary(DylibPath, &ErrMsg));
80   if (!Dylib->isValid())
81     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
82   DynamicLibraries.push_back(std::move(Dylib));
83   return pointerToJITTargetAddress(DynamicLibraries.back().get());
84 }
85 
86 Expected<std::vector<tpctypes::LookupResult>>
87 SelfExecutorProcessControl::lookupSymbols(ArrayRef<LookupRequest> Request) {
88   std::vector<tpctypes::LookupResult> R;
89 
90   for (auto &Elem : Request) {
91     auto *Dylib = jitTargetAddressToPointer<sys::DynamicLibrary *>(Elem.Handle);
92     assert(llvm::any_of(DynamicLibraries,
93                         [=](const std::unique_ptr<sys::DynamicLibrary> &DL) {
94                           return DL.get() == Dylib;
95                         }) &&
96            "Invalid handle");
97 
98     R.push_back(std::vector<JITTargetAddress>());
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(pointerToJITTargetAddress(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 void SelfExecutorProcessControl::callWrapperAsync(ExecutorAddr WrapperFnAddr,
125                                                   IncomingWFRHandler SendResult,
126                                                   ArrayRef<char> ArgBuffer) {
127   using WrapperFnTy =
128       shared::CWrapperFunctionResult (*)(const char *Data, size_t Size);
129   auto *WrapperFn = WrapperFnAddr.toPtr<WrapperFnTy>();
130   SendResult(WrapperFn(ArgBuffer.data(), ArgBuffer.size()));
131 }
132 
133 Error SelfExecutorProcessControl::disconnect() {
134   D->shutdown();
135   return Error::success();
136 }
137 
138 void SelfExecutorProcessControl::writeUInt8sAsync(
139     ArrayRef<tpctypes::UInt8Write> Ws, WriteResultFn OnWriteComplete) {
140   for (auto &W : Ws)
141     *W.Addr.toPtr<uint8_t *>() = W.Value;
142   OnWriteComplete(Error::success());
143 }
144 
145 void SelfExecutorProcessControl::writeUInt16sAsync(
146     ArrayRef<tpctypes::UInt16Write> Ws, WriteResultFn OnWriteComplete) {
147   for (auto &W : Ws)
148     *W.Addr.toPtr<uint16_t *>() = W.Value;
149   OnWriteComplete(Error::success());
150 }
151 
152 void SelfExecutorProcessControl::writeUInt32sAsync(
153     ArrayRef<tpctypes::UInt32Write> Ws, WriteResultFn OnWriteComplete) {
154   for (auto &W : Ws)
155     *W.Addr.toPtr<uint32_t *>() = W.Value;
156   OnWriteComplete(Error::success());
157 }
158 
159 void SelfExecutorProcessControl::writeUInt64sAsync(
160     ArrayRef<tpctypes::UInt64Write> Ws, WriteResultFn OnWriteComplete) {
161   for (auto &W : Ws)
162     *W.Addr.toPtr<uint64_t *>() = W.Value;
163   OnWriteComplete(Error::success());
164 }
165 
166 void SelfExecutorProcessControl::writeBuffersAsync(
167     ArrayRef<tpctypes::BufferWrite> Ws, WriteResultFn OnWriteComplete) {
168   for (auto &W : Ws)
169     memcpy(W.Addr.toPtr<char *>(), W.Buffer.data(), W.Buffer.size());
170   OnWriteComplete(Error::success());
171 }
172 
173 shared::CWrapperFunctionResult
174 SelfExecutorProcessControl::jitDispatchViaWrapperFunctionManager(
175     void *Ctx, const void *FnTag, const char *Data, size_t Size) {
176 
177   LLVM_DEBUG({
178     dbgs() << "jit-dispatch call with tag " << FnTag << " and " << Size
179            << " byte payload.\n";
180   });
181 
182   std::promise<shared::WrapperFunctionResult> ResultP;
183   auto ResultF = ResultP.get_future();
184   static_cast<SelfExecutorProcessControl *>(Ctx)
185       ->getExecutionSession()
186       .runJITDispatchHandler(
187           [ResultP = std::move(ResultP)](
188               shared::WrapperFunctionResult Result) mutable {
189             ResultP.set_value(std::move(Result));
190           },
191           pointerToJITTargetAddress(FnTag), {Data, Size});
192 
193   return ResultF.get().release();
194 }
195 
196 } // end namespace orc
197 } // end namespace llvm
198