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
13
14#include <future>
15
16using namespace llvm;
17using namespace llvm::orc;
18
19namespace llvm {
20namespace orc {
21
23public:
24 using IndirectStubInfo = EPCIndirectionUtils::IndirectStubInfo;
25 using IndirectStubInfoVector = EPCIndirectionUtils::IndirectStubInfoVector;
26
28 getIndirectStubs(EPCIndirectionUtils &EPCIU, unsigned NumStubs) {
29 return EPCIU.getIndirectStubs(NumStubs);
30 };
31};
32
33} // end namespace orc
34} // end namespace llvm
35
36namespace {
37
38class EPCTrampolinePool : public TrampolinePool {
39public:
40 EPCTrampolinePool(EPCIndirectionUtils &EPCIU);
41 Error deallocatePool();
42
43protected:
44 Error grow() override;
45
46 using FinalizedAlloc = jitlink::JITLinkMemoryManager::FinalizedAlloc;
47
48 EPCIndirectionUtils &EPCIU;
49 unsigned TrampolineSize = 0;
50 unsigned TrampolinesPerPage = 0;
51 std::vector<FinalizedAlloc> TrampolineBlocks;
52};
53
54class EPCIndirectStubsManager : public IndirectStubsManager,
56public:
57 EPCIndirectStubsManager(EPCIndirectionUtils &EPCIU) : EPCIU(EPCIU) {}
58
59 Error deallocateStubs();
60
61 Error createStub(StringRef StubName, ExecutorAddr StubAddr,
62 JITSymbolFlags StubFlags) override;
63
64 Error createStubs(const StubInitsMap &StubInits) override;
65
66 ExecutorSymbolDef findStub(StringRef Name, bool ExportedStubsOnly) override;
67
68 ExecutorSymbolDef findPointer(StringRef Name) override;
69
70 Error updatePointer(StringRef Name, ExecutorAddr NewAddr) override;
71
72private:
73 using StubInfo = std::pair<IndirectStubInfo, JITSymbolFlags>;
74
75 std::mutex ISMMutex;
76 EPCIndirectionUtils &EPCIU;
77 StringMap<StubInfo> StubInfos;
78};
79
80EPCTrampolinePool::EPCTrampolinePool(EPCIndirectionUtils &EPCIU)
81 : EPCIU(EPCIU) {
82 auto &EPC = EPCIU.getExecutorProcessControl();
83 auto &ABI = EPCIU.getABISupport();
84
85 TrampolineSize = ABI.getTrampolineSize();
86 TrampolinesPerPage =
87 (EPC.getPageSize() - ABI.getPointerSize()) / TrampolineSize;
88}
89
90Error EPCTrampolinePool::deallocatePool() {
91 std::promise<MSVCPError> DeallocResultP;
92 auto DeallocResultF = DeallocResultP.get_future();
93
95 std::move(TrampolineBlocks),
96 [&](Error Err) { DeallocResultP.set_value(std::move(Err)); });
97
98 return DeallocResultF.get();
99}
100
101Error EPCTrampolinePool::grow() {
102 using namespace jitlink;
103
104 assert(AvailableTrampolines.empty() &&
105 "Grow called with trampolines still available");
106
107 auto ResolverAddress = EPCIU.getResolverBlockAddress();
108 assert(ResolverAddress && "Resolver address can not be null");
109
110 auto &EPC = EPCIU.getExecutorProcessControl();
111 auto PageSize = EPC.getPageSize();
112 auto Alloc = SimpleSegmentAlloc::Create(
113 EPC.getMemMgr(), EPC.getSymbolStringPool(), EPC.getTargetTriple(),
114 nullptr, {{MemProt::Read | MemProt::Exec, {PageSize, Align(PageSize)}}});
115 if (!Alloc)
116 return Alloc.takeError();
117
118 unsigned NumTrampolines = TrampolinesPerPage;
119
120 auto SegInfo = Alloc->getSegInfo(MemProt::Read | MemProt::Exec);
122 SegInfo.WorkingMem.data(), SegInfo.Addr, ResolverAddress, NumTrampolines);
123 for (unsigned I = 0; I < NumTrampolines; ++I)
124 AvailableTrampolines.push_back(SegInfo.Addr + (I * TrampolineSize));
125
126 auto FA = Alloc->finalize();
127 if (!FA)
128 return FA.takeError();
129
130 TrampolineBlocks.push_back(std::move(*FA));
131
132 return Error::success();
133}
134
135Error EPCIndirectStubsManager::createStub(StringRef StubName,
136 ExecutorAddr StubAddr,
137 JITSymbolFlags StubFlags) {
138 StubInitsMap SIM;
139 SIM[StubName] = std::make_pair(StubAddr, StubFlags);
140 return createStubs(SIM);
141}
142
143Error EPCIndirectStubsManager::createStubs(const StubInitsMap &StubInits) {
144 auto AvailableStubInfos = getIndirectStubs(EPCIU, StubInits.size());
145 if (!AvailableStubInfos)
146 return AvailableStubInfos.takeError();
147
148 {
149 std::lock_guard<std::mutex> Lock(ISMMutex);
150 unsigned ASIdx = 0;
151 for (auto &SI : StubInits) {
152 auto &A = (*AvailableStubInfos)[ASIdx++];
153 StubInfos[SI.first()] = std::make_pair(A, SI.second.second);
154 }
155 }
156
157 auto &MemAccess = EPCIU.getMemoryAccess();
158 switch (EPCIU.getABISupport().getPointerSize()) {
159 case 4: {
160 unsigned ASIdx = 0;
161 std::vector<tpctypes::UInt32Write> PtrUpdates;
162 for (auto &SI : StubInits)
163 PtrUpdates.push_back({(*AvailableStubInfos)[ASIdx++].PointerAddress,
164 static_cast<uint32_t>(SI.second.first.getValue())});
165 return MemAccess.writeUInt32s(PtrUpdates);
166 }
167 case 8: {
168 unsigned ASIdx = 0;
169 std::vector<tpctypes::UInt64Write> PtrUpdates;
170 for (auto &SI : StubInits)
171 PtrUpdates.push_back({(*AvailableStubInfos)[ASIdx++].PointerAddress,
172 SI.second.first.getValue()});
173 return MemAccess.writeUInt64s(PtrUpdates);
174 }
175 default:
176 return make_error<StringError>("Unsupported pointer size",
178 }
179}
180
181ExecutorSymbolDef EPCIndirectStubsManager::findStub(StringRef Name,
182 bool ExportedStubsOnly) {
183 std::lock_guard<std::mutex> Lock(ISMMutex);
184 auto I = StubInfos.find(Name);
185 if (I == StubInfos.end())
186 return ExecutorSymbolDef();
187 return {I->second.first.StubAddress, I->second.second};
188}
189
190ExecutorSymbolDef EPCIndirectStubsManager::findPointer(StringRef Name) {
191 std::lock_guard<std::mutex> Lock(ISMMutex);
192 auto I = StubInfos.find(Name);
193 if (I == StubInfos.end())
194 return ExecutorSymbolDef();
195 return {I->second.first.PointerAddress, I->second.second};
196}
197
198Error EPCIndirectStubsManager::updatePointer(StringRef Name,
199 ExecutorAddr NewAddr) {
200
201 ExecutorAddr PtrAddr;
202 {
203 std::lock_guard<std::mutex> Lock(ISMMutex);
204 auto I = StubInfos.find(Name);
205 if (I == StubInfos.end())
206 return make_error<StringError>("Unknown stub name",
208 PtrAddr = I->second.first.PointerAddress;
209 }
210
211 auto &MemAccess = EPCIU.getMemoryAccess();
212 switch (EPCIU.getABISupport().getPointerSize()) {
213 case 4: {
214 tpctypes::UInt32Write PUpdate(PtrAddr, NewAddr.getValue());
215 return MemAccess.writeUInt32s(PUpdate);
216 }
217 case 8: {
218 tpctypes::UInt64Write PUpdate(PtrAddr, NewAddr.getValue());
219 return MemAccess.writeUInt64s(PUpdate);
220 }
221 default:
222 return make_error<StringError>("Unsupported pointer size",
224 }
225}
226
227} // end anonymous namespace.
228
229namespace llvm {
230namespace orc {
231
233
234Expected<std::unique_ptr<EPCIndirectionUtils>>
236 MemoryAccess &MemAccess) {
237 const auto &TT = EPC.getTargetTriple();
238 switch (TT.getArch()) {
239 default:
241 std::string("No EPCIndirectionUtils available for ") + TT.str(),
243 case Triple::aarch64:
245 return CreateWithABI<OrcAArch64>(EPC, MemAccess);
246
247 case Triple::x86:
248 return CreateWithABI<OrcI386>(EPC, MemAccess);
249
251 return CreateWithABI<OrcLoongArch64>(EPC, MemAccess);
252
253 case Triple::mips:
254 return CreateWithABI<OrcMips32Be>(EPC, MemAccess);
255
256 case Triple::mipsel:
257 return CreateWithABI<OrcMips32Le>(EPC, MemAccess);
258
259 case Triple::mips64:
260 case Triple::mips64el:
261 return CreateWithABI<OrcMips64>(EPC, MemAccess);
262
263 case Triple::riscv64:
264 return CreateWithABI<OrcRiscv64>(EPC, MemAccess);
265
266 case Triple::x86_64:
267 if (TT.getOS() == Triple::OSType::Win32)
268 return CreateWithABI<OrcX86_64_Win32>(EPC, MemAccess);
269 else
270 return CreateWithABI<OrcX86_64_SysV>(EPC, MemAccess);
271 }
272}
273
275
276 auto &MemMgr = EPC.getMemMgr();
277 auto Err = MemMgr.deallocate(std::move(IndirectStubAllocs));
278
279 if (TP)
280 Err = joinErrors(std::move(Err),
281 static_cast<EPCTrampolinePool &>(*TP).deallocatePool());
282
283 if (ResolverBlock)
284 Err =
285 joinErrors(std::move(Err), MemMgr.deallocate(std::move(ResolverBlock)));
286
287 return Err;
288}
289
292 ExecutorAddr ReentryCtxAddr) {
293 using namespace jitlink;
294
295 assert(ABI && "ABI can not be null");
296 auto ResolverSize = ABI->getResolverCodeSize();
297
298 auto Alloc =
299 SimpleSegmentAlloc::Create(EPC.getMemMgr(), EPC.getSymbolStringPool(),
300 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,
341 MemoryAccess &MemAccess,
342 std::unique_ptr<ABISupport> ABI)
343 : EPC(EPC), MemAccess(MemAccess), ABI(std::move(ABI)) {
344 assert(this->ABI && "ABI can not be null");
345
346 assert(EPC.getPageSize() > getABISupport().getStubSize() &&
347 "Stubs larger than one page are not supported");
348}
349
351EPCIndirectionUtils::getIndirectStubs(unsigned NumStubs) {
352 using namespace jitlink;
353
354 std::lock_guard<std::mutex> Lock(EPCUIMutex);
355
356 // If there aren't enough stubs available then allocate some more.
357 if (NumStubs > AvailableIndirectStubs.size()) {
358 auto NumStubsToAllocate = NumStubs;
359 auto PageSize = EPC.getPageSize();
360 auto StubBytes = alignTo(NumStubsToAllocate * ABI->getStubSize(), PageSize);
361 NumStubsToAllocate = StubBytes / ABI->getStubSize();
362 auto PtrBytes =
363 alignTo(NumStubsToAllocate * ABI->getPointerSize(), PageSize);
364
365 auto StubProt = MemProt::Read | MemProt::Exec;
366 auto PtrProt = MemProt::Read | MemProt::Write;
367
368 auto Alloc = SimpleSegmentAlloc::Create(
370 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.
static LLVM_ABI Expected< std::unique_ptr< EPCIndirectionUtils > > Create(ExecutorProcessControl &EPC, MemoryAccess &MemAccess)
Create based on the ExecutorProcessControl triple.
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.
LLVM_ABI LazyCallThroughManager & createLazyCallThroughManager(ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr)
Create a LazyCallThroughManager.
LLVM_ABI Error cleanup()
Release memory for resources held by this instance.
static std::unique_ptr< EPCIndirectionUtils > CreateWithABI(ExecutorProcessControl &EPC, MemoryAccess &MemAccess)
Create using the given ABI class.
LLVM_ABI TrampolinePool & getTrampolinePool()
Create a TrampolinePool for the executor process.
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.
jitlink::JITLinkMemoryManager & getMemMgr() const
Return a JITLinkMemoryManager for the 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:1917
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870