LLVM 23.0.0git
EPCIndirectionUtils.cpp
Go to the documentation of this file.
1//===------- EPCIndirectionUtils.cpp -- EPC based indirection 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
10
14
15#include <future>
16
17using namespace llvm;
18using namespace llvm::orc;
19
20namespace llvm {
21namespace orc {
22
24public:
25 using IndirectStubInfo = EPCIndirectionUtils::IndirectStubInfo;
26 using IndirectStubInfoVector = EPCIndirectionUtils::IndirectStubInfoVector;
27
29 getIndirectStubs(EPCIndirectionUtils &EPCIU, unsigned NumStubs) {
30 return EPCIU.getIndirectStubs(NumStubs);
31 };
32};
33
34} // end namespace orc
35} // end namespace llvm
36
37namespace {
38
39class EPCTrampolinePool : public TrampolinePool {
40public:
41 EPCTrampolinePool(EPCIndirectionUtils &EPCIU);
42 Error deallocatePool();
43
44protected:
45 Error grow() override;
46
47 using FinalizedAlloc = jitlink::JITLinkMemoryManager::FinalizedAlloc;
48
49 EPCIndirectionUtils &EPCIU;
50 unsigned TrampolineSize = 0;
51 unsigned TrampolinesPerPage = 0;
52 std::vector<FinalizedAlloc> TrampolineBlocks;
53};
54
55class EPCIndirectStubsManager : public IndirectStubsManager,
57public:
58 EPCIndirectStubsManager(EPCIndirectionUtils &EPCIU) : EPCIU(EPCIU) {}
59
60 Error deallocateStubs();
61
62 Error createStub(StringRef StubName, ExecutorAddr StubAddr,
63 JITSymbolFlags StubFlags) override;
64
65 Error createStubs(const StubInitsMap &StubInits) override;
66
67 ExecutorSymbolDef findStub(StringRef Name, bool ExportedStubsOnly) override;
68
69 ExecutorSymbolDef findPointer(StringRef Name) override;
70
71 Error updatePointer(StringRef Name, ExecutorAddr NewAddr) override;
72
73private:
74 using StubInfo = std::pair<IndirectStubInfo, JITSymbolFlags>;
75
76 std::mutex ISMMutex;
77 EPCIndirectionUtils &EPCIU;
78 StringMap<StubInfo> StubInfos;
79};
80
81EPCTrampolinePool::EPCTrampolinePool(EPCIndirectionUtils &EPCIU)
82 : EPCIU(EPCIU) {
83 auto &EPC = EPCIU.getExecutorProcessControl();
84 auto &ABI = EPCIU.getABISupport();
85
86 TrampolineSize = ABI.getTrampolineSize();
87 TrampolinesPerPage =
88 (EPC.getPageSize() - ABI.getPointerSize()) / TrampolineSize;
89}
90
91Error EPCTrampolinePool::deallocatePool() {
92 std::promise<MSVCPError> DeallocResultP;
93 auto DeallocResultF = DeallocResultP.get_future();
94
95 EPCIU.getMemManager().deallocate(std::move(TrampolineBlocks), [&](Error Err) {
96 DeallocResultP.set_value(std::move(Err));
97 });
98
99 return DeallocResultF.get();
100}
101
102Error EPCTrampolinePool::grow() {
103 using namespace jitlink;
104
105 assert(AvailableTrampolines.empty() &&
106 "Grow called with trampolines still available");
107
108 auto ResolverAddress = EPCIU.getResolverBlockAddress();
109 assert(ResolverAddress && "Resolver address can not be null");
110
111 auto &EPC = EPCIU.getExecutorProcessControl();
112 auto PageSize = EPC.getPageSize();
113 auto Alloc = SimpleSegmentAlloc::Create(
114 EPCIU.getMemManager(), EPC.getSymbolStringPool(), EPC.getTargetTriple(),
115 nullptr, {{MemProt::Read | MemProt::Exec, {PageSize, Align(PageSize)}}});
116 if (!Alloc)
117 return Alloc.takeError();
118
119 unsigned NumTrampolines = TrampolinesPerPage;
120
121 auto SegInfo = Alloc->getSegInfo(MemProt::Read | MemProt::Exec);
123 SegInfo.WorkingMem.data(), SegInfo.Addr, ResolverAddress, NumTrampolines);
124 for (unsigned I = 0; I < NumTrampolines; ++I)
125 AvailableTrampolines.push_back(SegInfo.Addr + (I * TrampolineSize));
126
127 auto FA = Alloc->finalize();
128 if (!FA)
129 return FA.takeError();
130
131 TrampolineBlocks.push_back(std::move(*FA));
132
133 return Error::success();
134}
135
136Error EPCIndirectStubsManager::createStub(StringRef StubName,
137 ExecutorAddr StubAddr,
138 JITSymbolFlags StubFlags) {
139 StubInitsMap SIM;
140 SIM[StubName] = std::make_pair(StubAddr, StubFlags);
141 return createStubs(SIM);
142}
143
144Error EPCIndirectStubsManager::createStubs(const StubInitsMap &StubInits) {
145 auto AvailableStubInfos = getIndirectStubs(EPCIU, StubInits.size());
146 if (!AvailableStubInfos)
147 return AvailableStubInfos.takeError();
148
149 {
150 std::lock_guard<std::mutex> Lock(ISMMutex);
151 unsigned ASIdx = 0;
152 for (auto &SI : StubInits) {
153 auto &A = (*AvailableStubInfos)[ASIdx++];
154 StubInfos[SI.first()] = std::make_pair(A, SI.second.second);
155 }
156 }
157
158 auto &MemAccess = EPCIU.getMemoryAccess();
159 switch (EPCIU.getABISupport().getPointerSize()) {
160 case 4: {
161 unsigned ASIdx = 0;
162 std::vector<tpctypes::UInt32Write> PtrUpdates;
163 for (auto &SI : StubInits)
164 PtrUpdates.push_back({(*AvailableStubInfos)[ASIdx++].PointerAddress,
165 static_cast<uint32_t>(SI.second.first.getValue())});
166 return MemAccess.writeUInt32s(PtrUpdates);
167 }
168 case 8: {
169 unsigned ASIdx = 0;
170 std::vector<tpctypes::UInt64Write> PtrUpdates;
171 for (auto &SI : StubInits)
172 PtrUpdates.push_back({(*AvailableStubInfos)[ASIdx++].PointerAddress,
173 SI.second.first.getValue()});
174 return MemAccess.writeUInt64s(PtrUpdates);
175 }
176 default:
177 return make_error<StringError>("Unsupported pointer size",
179 }
180}
181
182ExecutorSymbolDef EPCIndirectStubsManager::findStub(StringRef Name,
183 bool ExportedStubsOnly) {
184 std::lock_guard<std::mutex> Lock(ISMMutex);
185 auto I = StubInfos.find(Name);
186 if (I == StubInfos.end())
187 return ExecutorSymbolDef();
188 return {I->second.first.StubAddress, I->second.second};
189}
190
191ExecutorSymbolDef EPCIndirectStubsManager::findPointer(StringRef Name) {
192 std::lock_guard<std::mutex> Lock(ISMMutex);
193 auto I = StubInfos.find(Name);
194 if (I == StubInfos.end())
195 return ExecutorSymbolDef();
196 return {I->second.first.PointerAddress, I->second.second};
197}
198
199Error EPCIndirectStubsManager::updatePointer(StringRef Name,
200 ExecutorAddr NewAddr) {
201
202 ExecutorAddr PtrAddr;
203 {
204 std::lock_guard<std::mutex> Lock(ISMMutex);
205 auto I = StubInfos.find(Name);
206 if (I == StubInfos.end())
207 return make_error<StringError>("Unknown stub name",
209 PtrAddr = I->second.first.PointerAddress;
210 }
211
212 auto &MemAccess = EPCIU.getMemoryAccess();
213 switch (EPCIU.getABISupport().getPointerSize()) {
214 case 4: {
215 tpctypes::UInt32Write PUpdate(PtrAddr, NewAddr.getValue());
216 return MemAccess.writeUInt32s(PUpdate);
217 }
218 case 8: {
219 tpctypes::UInt64Write PUpdate(PtrAddr, NewAddr.getValue());
220 return MemAccess.writeUInt64s(PUpdate);
221 }
222 default:
223 return make_error<StringError>("Unsupported pointer size",
225 }
226}
227
228} // end anonymous namespace.
229
230namespace llvm {
231namespace orc {
232
234
235Expected<std::unique_ptr<EPCIndirectionUtils>>
238 MemoryAccess &MemAccess) {
239 const auto &TT = EPC.getTargetTriple();
240 switch (TT.getArch()) {
241 default:
243 std::string("No EPCIndirectionUtils available for ") + TT.str(),
245 case Triple::aarch64:
247 return CreateWithABI<OrcAArch64>(EPC, MemMgr, MemAccess);
248
249 case Triple::x86:
250 return CreateWithABI<OrcI386>(EPC, MemMgr, MemAccess);
251
253 return CreateWithABI<OrcLoongArch64>(EPC, MemMgr, MemAccess);
254
255 case Triple::mips:
256 return CreateWithABI<OrcMips32Be>(EPC, MemMgr, MemAccess);
257
258 case Triple::mipsel:
259 return CreateWithABI<OrcMips32Le>(EPC, MemMgr, MemAccess);
260
261 case Triple::mips64:
262 case Triple::mips64el:
263 return CreateWithABI<OrcMips64>(EPC, MemMgr, MemAccess);
264
265 case Triple::riscv64:
266 return CreateWithABI<OrcRiscv64>(EPC, MemMgr, MemAccess);
267
268 case Triple::x86_64:
269 if (TT.getOS() == Triple::OSType::Win32)
270 return CreateWithABI<OrcX86_64_Win32>(EPC, MemMgr, MemAccess);
271 else
272 return CreateWithABI<OrcX86_64_SysV>(EPC, MemMgr, MemAccess);
273 }
274}
275
277
278 auto Err = MemMgr.deallocate(std::move(IndirectStubAllocs));
279
280 if (TP)
281 Err = joinErrors(std::move(Err),
282 static_cast<EPCTrampolinePool &>(*TP).deallocatePool());
283
284 if (ResolverBlock)
285 Err =
286 joinErrors(std::move(Err), MemMgr.deallocate(std::move(ResolverBlock)));
287
288 return Err;
289}
290
293 ExecutorAddr ReentryCtxAddr) {
294 using namespace jitlink;
295
296 assert(ABI && "ABI can not be null");
297 auto ResolverSize = ABI->getResolverCodeSize();
298
299 auto Alloc = SimpleSegmentAlloc::Create(
300 MemMgr, EPC.getSymbolStringPool(), EPC.getTargetTriple(), nullptr,
301 {{MemProt::Read | MemProt::Exec,
302 {ResolverSize, Align(EPC.getPageSize())}}});
303
304 if (!Alloc)
305 return Alloc.takeError();
306
307 auto SegInfo = Alloc->getSegInfo(MemProt::Read | MemProt::Exec);
308 ResolverBlockAddr = SegInfo.Addr;
309 ABI->writeResolverCode(SegInfo.WorkingMem.data(), ResolverBlockAddr,
310 ReentryFnAddr, ReentryCtxAddr);
311
312 auto FA = Alloc->finalize();
313 if (!FA)
314 return FA.takeError();
315
316 ResolverBlock = std::move(*FA);
317 return ResolverBlockAddr;
318}
319
320std::unique_ptr<IndirectStubsManager>
322 return std::make_unique<EPCIndirectStubsManager>(*this);
323}
324
326 if (!TP)
327 TP = std::make_unique<EPCTrampolinePool>(*this);
328 return *TP;
329}
330
332 ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr) {
333 assert(!LCTM &&
334 "createLazyCallThroughManager can not have been called before");
335 LCTM = std::make_unique<LazyCallThroughManager>(ES, ErrorHandlerAddr,
337 return *LCTM;
338}
339
340EPCIndirectionUtils::EPCIndirectionUtils(ExecutorProcessControl &EPC,
342 MemoryAccess &MemAccess,
343 std::unique_ptr<ABISupport> ABI)
344 : EPC(EPC), MemMgr(MemMgr), MemAccess(MemAccess), ABI(std::move(ABI)) {
345 assert(this->ABI && "ABI can not be null");
346
347 assert(EPC.getPageSize() > getABISupport().getStubSize() &&
348 "Stubs larger than one page are not supported");
349}
350
352EPCIndirectionUtils::getIndirectStubs(unsigned NumStubs) {
353 using namespace jitlink;
354
355 std::lock_guard<std::mutex> Lock(EPCUIMutex);
356
357 // If there aren't enough stubs available then allocate some more.
358 if (NumStubs > AvailableIndirectStubs.size()) {
359 auto NumStubsToAllocate = NumStubs;
360 auto PageSize = EPC.getPageSize();
361 auto StubBytes = alignTo(NumStubsToAllocate * ABI->getStubSize(), PageSize);
362 NumStubsToAllocate = StubBytes / ABI->getStubSize();
363 auto PtrBytes =
364 alignTo(NumStubsToAllocate * ABI->getPointerSize(), PageSize);
365
366 auto StubProt = MemProt::Read | MemProt::Exec;
367 auto PtrProt = MemProt::Read | MemProt::Write;
368
369 auto Alloc = SimpleSegmentAlloc::Create(
370 MemMgr, EPC.getSymbolStringPool(), EPC.getTargetTriple(), nullptr,
371 {{StubProt, {static_cast<size_t>(StubBytes), Align(PageSize)}},
372 {PtrProt, {static_cast<size_t>(PtrBytes), Align(PageSize)}}});
373
374 if (!Alloc)
375 return Alloc.takeError();
376
377 auto StubSeg = Alloc->getSegInfo(StubProt);
378 auto PtrSeg = Alloc->getSegInfo(PtrProt);
379
380 ABI->writeIndirectStubsBlock(StubSeg.WorkingMem.data(), StubSeg.Addr,
381 PtrSeg.Addr, NumStubsToAllocate);
382
383 auto FA = Alloc->finalize();
384 if (!FA)
385 return FA.takeError();
386
387 IndirectStubAllocs.push_back(std::move(*FA));
388
389 auto StubExecutorAddr = StubSeg.Addr;
390 auto PtrExecutorAddr = PtrSeg.Addr;
391 for (unsigned I = 0; I != NumStubsToAllocate; ++I) {
392 AvailableIndirectStubs.push_back(
393 IndirectStubInfo(StubExecutorAddr, PtrExecutorAddr));
394 StubExecutorAddr += ABI->getStubSize();
395 PtrExecutorAddr += ABI->getPointerSize();
396 }
397 }
398
399 assert(NumStubs <= AvailableIndirectStubs.size() &&
400 "Sufficient stubs should have been allocated above");
401
402 IndirectStubInfoVector Result;
403 while (NumStubs--) {
404 Result.push_back(AvailableIndirectStubs.back());
405 AvailableIndirectStubs.pop_back();
406 }
407
408 return std::move(Result);
409}
410
412 JITTargetAddress TrampolineAddr) {
414 std::promise<ExecutorAddr> LandingAddrP;
415 auto LandingAddrF = LandingAddrP.get_future();
416 LCTM.resolveTrampolineLandingAddress(
417 ExecutorAddr(TrampolineAddr),
418 [&](ExecutorAddr Addr) { LandingAddrP.set_value(Addr); });
419 return LandingAddrF.get().getValue();
420}
421
423 auto &LCTM = EPCIU.getLazyCallThroughManager();
424 return EPCIU
427 .takeError();
428}
429
430} // end namespace orc
431} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
#define I(x, y, z)
Definition MD5.cpp:57
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
@ loongarch64
Definition Triple.h:65
EPCIndirectionUtils::IndirectStubInfo IndirectStubInfo
static Expected< IndirectStubInfoVector > getIndirectStubs(EPCIndirectionUtils &EPCIU, unsigned NumStubs)
EPCIndirectionUtils::IndirectStubInfoVector IndirectStubInfoVector
virtual void writeTrampolines(char *TrampolineBlockWorkingMem, ExecutorAddr TrampolineBlockTragetAddr, ExecutorAddr ResolverAddr, unsigned NumTrampolines) const =0
Provides ExecutorProcessControl based indirect stubs, trampoline pool and lazy call through manager.
LLVM_ABI std::unique_ptr< IndirectStubsManager > createIndirectStubsManager()
Create an IndirectStubsManager for the executor process.
LLVM_ABI Expected< ExecutorAddr > writeResolverBlock(ExecutorAddr ReentryFnAddr, ExecutorAddr ReentryCtxAddr)
Write resolver code to the executor process and return its address.
LazyCallThroughManager & getLazyCallThroughManager()
Create a LazyCallThroughManager for the executor process.
MemoryAccess & getMemoryAccess() const
Return a reference to the MemoryAccess object for this instance.
ExecutorProcessControl & getExecutorProcessControl() const
Return a reference to the ExecutorProcessControl object.
jitlink::JITLinkMemoryManager & getMemManager() const
Return a reference to the JITLinkMemoryManager object for this instance.
static LLVM_ABI Expected< std::unique_ptr< EPCIndirectionUtils > > Create(ExecutorProcessControl &EPC, jitlink::JITLinkMemoryManager &MemMgr, MemoryAccess &MemAccess)
Create based on the ExecutorProcessControl triple.
LLVM_ABI LazyCallThroughManager & createLazyCallThroughManager(ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr)
Create a LazyCallThroughManager.
LLVM_ABI Error cleanup()
Release memory for resources held by this instance.
LLVM_ABI TrampolinePool & getTrampolinePool()
Create a TrampolinePool for the executor process.
static std::unique_ptr< EPCIndirectionUtils > CreateWithABI(ExecutorProcessControl &EPC, jitlink::JITLinkMemoryManager &MemMgr, MemoryAccess &MemAccess)
Create using the given ABI class.
ABISupport & getABISupport() const
Return a reference to the ABISupport object for this instance.
ExecutorAddr getResolverBlockAddress() const
Returns the address of the Resolver block.
An ExecutionSession represents a running JIT program.
Definition Core.h:1355
Represents an address in the executor process.
uint64_t getValue() const
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
ExecutorProcessControl supports interaction with a JIT target process.
const Triple & getTargetTriple() const
Return the Triple for the target process.
std::shared_ptr< SymbolStringPool > getSymbolStringPool() const
Return a shared pointer to the SymbolStringPool for this instance.
unsigned getPageSize() const
Get the page size for the target process.
Represents a defining location for a JIT symbol.
Base class for managing collections of named indirect stubs.
Manages a set of 'lazy call-through' trampolines.
APIs for manipulating memory in the target process.
Base class for pools of compiler re-entry trampolines.
UIntWrite< uint64_t > UInt64Write
Describes a write to a uint64_t.
UIntWrite< uint32_t > UInt32Write
Describes a write to a uint32_t.
LLVM_ABI Error setUpInProcessLCTMReentryViaEPCIU(EPCIndirectionUtils &EPCIU)
This will call writeResolver on the given EPCIndirectionUtils instance to set up re-entry via a funct...
static JITTargetAddress reentry(JITTargetAddress LCTMAddr, JITTargetAddress TrampolineAddr)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
T jitTargetAddressToPointer(JITTargetAddress Addr)
Convert a JITTargetAddress to a pointer.
Definition JITSymbol.h:51
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Definition JITSymbol.h:43
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870