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
96 std::move(TrampolineBlocks),
97 [&](Error Err) { DeallocResultP.set_value(std::move(Err)); });
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 EPC.getMemMgr(), 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>>
237 MemoryAccess &MemAccess) {
238 const auto &TT = EPC.getTargetTriple();
239 switch (TT.getArch()) {
240 default:
242 std::string("No EPCIndirectionUtils available for ") + TT.str(),
244 case Triple::aarch64:
246 return CreateWithABI<OrcAArch64>(EPC, MemAccess);
247
248 case Triple::x86:
249 return CreateWithABI<OrcI386>(EPC, MemAccess);
250
252 return CreateWithABI<OrcLoongArch64>(EPC, MemAccess);
253
254 case Triple::mips:
255 return CreateWithABI<OrcMips32Be>(EPC, MemAccess);
256
257 case Triple::mipsel:
258 return CreateWithABI<OrcMips32Le>(EPC, MemAccess);
259
260 case Triple::mips64:
261 case Triple::mips64el:
262 return CreateWithABI<OrcMips64>(EPC, MemAccess);
263
264 case Triple::riscv64:
265 return CreateWithABI<OrcRiscv64>(EPC, MemAccess);
266
267 case Triple::x86_64:
268 if (TT.getOS() == Triple::OSType::Win32)
269 return CreateWithABI<OrcX86_64_Win32>(EPC, MemAccess);
270 else
271 return CreateWithABI<OrcX86_64_SysV>(EPC, MemAccess);
272 }
273}
274
276
277 auto &MemMgr = EPC.getMemMgr();
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 =
300 SimpleSegmentAlloc::Create(EPC.getMemMgr(), EPC.getSymbolStringPool(),
301 EPC.getTargetTriple(), nullptr,
302 {{MemProt::Read | MemProt::Exec,
303 {ResolverSize, Align(EPC.getPageSize())}}});
304
305 if (!Alloc)
306 return Alloc.takeError();
307
308 auto SegInfo = Alloc->getSegInfo(MemProt::Read | MemProt::Exec);
309 ResolverBlockAddr = SegInfo.Addr;
310 ABI->writeResolverCode(SegInfo.WorkingMem.data(), ResolverBlockAddr,
311 ReentryFnAddr, ReentryCtxAddr);
312
313 auto FA = Alloc->finalize();
314 if (!FA)
315 return FA.takeError();
316
317 ResolverBlock = std::move(*FA);
318 return ResolverBlockAddr;
319}
320
321std::unique_ptr<IndirectStubsManager>
323 return std::make_unique<EPCIndirectStubsManager>(*this);
324}
325
327 if (!TP)
328 TP = std::make_unique<EPCTrampolinePool>(*this);
329 return *TP;
330}
331
333 ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr) {
334 assert(!LCTM &&
335 "createLazyCallThroughManager can not have been called before");
336 LCTM = std::make_unique<LazyCallThroughManager>(ES, ErrorHandlerAddr,
338 return *LCTM;
339}
340
341EPCIndirectionUtils::EPCIndirectionUtils(ExecutorProcessControl &EPC,
342 MemoryAccess &MemAccess,
343 std::unique_ptr<ABISupport> ABI)
344 : EPC(EPC), 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(
371 nullptr,
372 {{StubProt, {static_cast<size_t>(StubBytes), Align(PageSize)}},
373 {PtrProt, {static_cast<size_t>(PtrBytes), Align(PageSize)}}});
374
375 if (!Alloc)
376 return Alloc.takeError();
377
378 auto StubSeg = Alloc->getSegInfo(StubProt);
379 auto PtrSeg = Alloc->getSegInfo(PtrProt);
380
381 ABI->writeIndirectStubsBlock(StubSeg.WorkingMem.data(), StubSeg.Addr,
382 PtrSeg.Addr, NumStubsToAllocate);
383
384 auto FA = Alloc->finalize();
385 if (!FA)
386 return FA.takeError();
387
388 IndirectStubAllocs.push_back(std::move(*FA));
389
390 auto StubExecutorAddr = StubSeg.Addr;
391 auto PtrExecutorAddr = PtrSeg.Addr;
392 for (unsigned I = 0; I != NumStubsToAllocate; ++I) {
393 AvailableIndirectStubs.push_back(
394 IndirectStubInfo(StubExecutorAddr, PtrExecutorAddr));
395 StubExecutorAddr += ABI->getStubSize();
396 PtrExecutorAddr += ABI->getPointerSize();
397 }
398 }
399
400 assert(NumStubs <= AvailableIndirectStubs.size() &&
401 "Sufficient stubs should have been allocated above");
402
403 IndirectStubInfoVector Result;
404 while (NumStubs--) {
405 Result.push_back(AvailableIndirectStubs.back());
406 AvailableIndirectStubs.pop_back();
407 }
408
409 return std::move(Result);
410}
411
413 JITTargetAddress TrampolineAddr) {
415 std::promise<ExecutorAddr> LandingAddrP;
416 auto LandingAddrF = LandingAddrP.get_future();
417 LCTM.resolveTrampolineLandingAddress(
418 ExecutorAddr(TrampolineAddr),
419 [&](ExecutorAddr Addr) { LandingAddrP.set_value(Addr); });
420 return LandingAddrF.get().getValue();
421}
422
424 auto &LCTM = EPCIU.getLazyCallThroughManager();
425 return EPCIU
428 .takeError();
429}
430
431} // end namespace orc
432} // 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