LLVM 24.0.0git
EPCGenericRTDyldMemoryManager.cpp
Go to the documentation of this file.
1//===----- EPCGenericRTDyldMemoryManager.cpp - EPC-bbasde MemMgr -----===//
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
15
16#define DEBUG_TYPE "orc"
17
18using namespace llvm::orc::shared;
19
20namespace llvm {
21namespace orc {
22
23Expected<std::unique_ptr<EPCGenericRTDyldMemoryManager>>
26 auto &BootstrapJD = EPC.getExecutionSession().getBootstrapJITDylib();
27 SymbolAddrs SAs;
28 if (auto Err = lookupAndApply(
30 &SAs.RegisterEHFrame),
32 &SAs.DeregisterEHFrame)}))
33 return std::move(Err);
34 // Bind the memory manager last: this may create an executor-side instance,
35 // which would otherwise be left unused if a lookup above failed.
36 if (auto MemMgr = sps::createSimpleMemoryMapBindings(BootstrapJD))
37 SAs.MemMgr = std::move(*MemMgr);
38 else
39 return MemMgr.takeError();
40 return std::make_unique<EPCGenericRTDyldMemoryManager>(EPC, std::move(SAs));
41}
42
45 : EPC(EPC), SAs(std::move(SAs)) {
46 LLVM_DEBUG(dbgs() << "Created remote allocator " << (void *)this << "\n");
47}
48
50 LLVM_DEBUG(dbgs() << "Destroyed remote allocator " << (void *)this << "\n");
51 if (!ErrMsg.empty())
52 errs() << "Destroying with existing errors:\n" << ErrMsg << "\n";
53
54 // FIXME: Report errors through EPC once that functionality is available.
55 if (auto Err = SAs.MemMgr.Release(EPC.getExecutionSession(),
56 SAs.MemMgr.Instance, FinalizedAllocs))
57 logAllUnhandledErrors(std::move(Err), errs(), "");
58}
59
61 uintptr_t Size, unsigned Alignment, unsigned SectionID,
63 std::lock_guard<std::mutex> Lock(M);
65 dbgs() << "Allocator " << (void *)this << " allocating code section "
66 << SectionName << ": size = " << formatv("{0:x}", Size)
67 << " bytes, alignment = " << Alignment << "\n";
68 });
69 auto &Seg = Unmapped.back().CodeAllocs;
70 Seg.emplace_back(Size, Alignment);
71 return reinterpret_cast<uint8_t *>(
72 alignAddr(Seg.back().Contents.get(), Align(Alignment)));
73}
74
76 uintptr_t Size, unsigned Alignment, unsigned SectionID,
77 StringRef SectionName, bool IsReadOnly) {
78 std::lock_guard<std::mutex> Lock(M);
80 dbgs() << "Allocator " << (void *)this << " allocating "
81 << (IsReadOnly ? "ro" : "rw") << "-data section " << SectionName
82 << ": size = " << formatv("{0:x}", Size) << " bytes, alignment "
83 << Alignment << ")\n";
84 });
85
86 auto &Seg =
87 IsReadOnly ? Unmapped.back().RODataAllocs : Unmapped.back().RWDataAllocs;
88
89 Seg.emplace_back(Size, Alignment);
90 return reinterpret_cast<uint8_t *>(
91 alignAddr(Seg.back().Contents.get(), Align(Alignment)));
92}
93
95 uintptr_t CodeSize, Align CodeAlign, uintptr_t RODataSize,
96 Align RODataAlign, uintptr_t RWDataSize, Align RWDataAlign) {
97
98 {
99 std::lock_guard<std::mutex> Lock(M);
100 // If there's already an error then bail out.
101 if (!ErrMsg.empty())
102 return;
103
104 if (CodeAlign > EPC.getPageSize()) {
105 ErrMsg = "Invalid code alignment in reserveAllocationSpace";
106 return;
107 }
108 if (RODataAlign > EPC.getPageSize()) {
109 ErrMsg = "Invalid ro-data alignment in reserveAllocationSpace";
110 return;
111 }
112 if (RWDataAlign > EPC.getPageSize()) {
113 ErrMsg = "Invalid rw-data alignment in reserveAllocationSpace";
114 return;
115 }
116 }
117
118 uint64_t TotalSize = 0;
119 TotalSize += alignTo(CodeSize, EPC.getPageSize());
120 TotalSize += alignTo(RODataSize, EPC.getPageSize());
121 TotalSize += alignTo(RWDataSize, EPC.getPageSize());
122
123 LLVM_DEBUG({
124 dbgs() << "Allocator " << (void *)this << " reserving "
125 << formatv("{0:x}", TotalSize) << " bytes.\n";
126 });
127
128 Expected<ExecutorAddr> TargetAllocAddr = SAs.MemMgr.Reserve(
129 EPC.getExecutionSession(), SAs.MemMgr.Instance, TotalSize);
130 if (!TargetAllocAddr) {
131 std::lock_guard<std::mutex> Lock(M);
132 ErrMsg = toString(TargetAllocAddr.takeError());
133 return;
134 }
135
136 std::lock_guard<std::mutex> Lock(M);
137 Unmapped.push_back(SectionAllocGroup());
138 Unmapped.back().RemoteCode = {
139 *TargetAllocAddr, ExecutorAddrDiff(alignTo(CodeSize, EPC.getPageSize()))};
140 Unmapped.back().RemoteROData = {
141 Unmapped.back().RemoteCode.End,
142 ExecutorAddrDiff(alignTo(RODataSize, EPC.getPageSize()))};
143 Unmapped.back().RemoteRWData = {
144 Unmapped.back().RemoteROData.End,
145 ExecutorAddrDiff(alignTo(RWDataSize, EPC.getPageSize()))};
146}
147
151
153 uint64_t LoadAddr,
154 size_t Size) {
155 LLVM_DEBUG({
156 dbgs() << "Allocator " << (void *)this << " added unfinalized eh-frame "
157 << formatv("[ {0:x} {1:x} ]", LoadAddr, LoadAddr + Size) << "\n";
158 });
159 std::lock_guard<std::mutex> Lock(M);
160 // Bail out early if there's already an error.
161 if (!ErrMsg.empty())
162 return;
163
164 ExecutorAddr LA(LoadAddr);
165 for (auto &SecAllocGroup : llvm::reverse(Unfinalized)) {
166 if (SecAllocGroup.RemoteCode.contains(LA) ||
167 SecAllocGroup.RemoteROData.contains(LA) ||
168 SecAllocGroup.RemoteRWData.contains(LA)) {
169 SecAllocGroup.UnfinalizedEHFrames.push_back({LA, Size});
170 return;
171 }
172 }
173 ErrMsg = "eh-frame does not lie inside unfinalized alloc";
174}
175
177 // This is a no-op for us: We've registered a deallocation action for it.
178}
179
181 RuntimeDyld &Dyld, const object::ObjectFile &Obj) {
182 std::lock_guard<std::mutex> Lock(M);
183 LLVM_DEBUG(dbgs() << "Allocator " << (void *)this << " applied mappings:\n");
184 for (auto &ObjAllocs : Unmapped) {
185 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.CodeAllocs,
186 ObjAllocs.RemoteCode.Start);
187 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RODataAllocs,
188 ObjAllocs.RemoteROData.Start);
189 mapAllocsToRemoteAddrs(Dyld, ObjAllocs.RWDataAllocs,
190 ObjAllocs.RemoteRWData.Start);
191 Unfinalized.push_back(std::move(ObjAllocs));
192 }
193 Unmapped.clear();
194}
195
197 LLVM_DEBUG(dbgs() << "Allocator " << (void *)this << " finalizing:\n");
198
199 // If there's an error then bail out here.
200 std::vector<SectionAllocGroup> SecAllocGroups;
201 {
202 std::lock_guard<std::mutex> Lock(M);
203 if (ErrMsg && !this->ErrMsg.empty()) {
204 *ErrMsg = std::move(this->ErrMsg);
205 return true;
206 }
207 std::swap(SecAllocGroups, Unfinalized);
208 }
209
210 // Loop over unfinalized objects to make finalization requests.
211 for (auto &SecAllocGroup : SecAllocGroups) {
212
215
216 ExecutorAddrRange *RemoteAddrs[3] = {&SecAllocGroup.RemoteCode,
217 &SecAllocGroup.RemoteROData,
218 &SecAllocGroup.RemoteRWData};
219
220 std::vector<SectionAlloc> *SegSections[3] = {&SecAllocGroup.CodeAllocs,
221 &SecAllocGroup.RODataAllocs,
222 &SecAllocGroup.RWDataAllocs};
223
225 std::unique_ptr<char[]> AggregateContents[3];
226
227 for (unsigned I = 0; I != 3; ++I) {
228 FR.Segments.push_back({});
229 auto &Seg = FR.Segments.back();
230 Seg.RAG = SegMemProts[I];
231 Seg.Addr = RemoteAddrs[I]->Start;
232 for (auto &SecAlloc : *SegSections[I]) {
233 Seg.Size = alignTo(Seg.Size, SecAlloc.Align);
234 Seg.Size += SecAlloc.Size;
235 }
236 AggregateContents[I] = std::make_unique<char[]>(Seg.Size);
237 size_t SecOffset = 0;
238 for (auto &SecAlloc : *SegSections[I]) {
239 SecOffset = alignTo(SecOffset, SecAlloc.Align);
240 memcpy(&AggregateContents[I][SecOffset],
241 reinterpret_cast<const char *>(
242 alignAddr(SecAlloc.Contents.get(), Align(SecAlloc.Align))),
243 SecAlloc.Size);
244 SecOffset += SecAlloc.Size;
245 // FIXME: Can we reset SecAlloc.Content here, now that it's copied into
246 // the aggregated content?
247 }
248 Seg.Content = {AggregateContents[I].get(), SecOffset};
249 }
250
251 for (auto &Frame : SecAllocGroup.UnfinalizedEHFrames)
252 FR.Actions.push_back(
253 {cantFail(
255 SAs.RegisterEHFrame, Frame)),
256 cantFail(
258 SAs.DeregisterEHFrame, Frame))});
259
260 // We'll also need to make an extra allocation for the eh-frame wrapper call
261 // arguments.
262 Expected<ExecutorAddr> InitializeKey = SAs.MemMgr.Initialize(
263 EPC.getExecutionSession(), SAs.MemMgr.Instance, std::move(FR));
264 if (!InitializeKey) {
265 std::lock_guard<std::mutex> Lock(M);
266 this->ErrMsg = toString(InitializeKey.takeError());
267 dbgs() << "Finalization error: " << this->ErrMsg << "\n";
268 if (ErrMsg)
269 *ErrMsg = this->ErrMsg;
270 return true;
271 }
272 }
273
274 return false;
275}
276
277void EPCGenericRTDyldMemoryManager::mapAllocsToRemoteAddrs(
278 RuntimeDyld &Dyld, std::vector<SectionAlloc> &Allocs,
279 ExecutorAddr NextAddr) {
280 for (auto &Alloc : Allocs) {
281 NextAddr.setValue(alignTo(NextAddr.getValue(), Alloc.Align));
282 LLVM_DEBUG({
283 dbgs() << " " << static_cast<void *>(Alloc.Contents.get()) << " -> "
284 << format("0x%016" PRIx64, NextAddr.getValue()) << "\n";
285 });
286 Dyld.mapSectionAddress(reinterpret_cast<const void *>(alignAddr(
287 Alloc.Contents.get(), Align(Alloc.Align))),
288 NextAddr.getValue());
289 Alloc.RemoteAddr = NextAddr;
290 // Only advance NextAddr if it was non-null to begin with,
291 // otherwise leave it as null.
292 if (NextAddr)
293 NextAddr += ExecutorAddrDiff(Alloc.Size);
294 }
295}
296
297} // end namespace orc
298} // end namespace llvm
#define I(x, y, z)
Definition MD5.cpp:57
#define LLVM_DEBUG(...)
Definition Debug.h:119
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
LLVM_ABI void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
Map a section to its target address space value.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This class is the base class for all object file types.
Definition ObjectFile.h:231
uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override
Allocate a memory block of (at least) the given size suitable for data.
bool finalizeMemory(std::string *ErrMsg=nullptr) override
This method is called when object loading is complete and section page permissions can be applied.
bool needsToReserveAllocationSpace() override
Override to return true to enable the reserveAllocationSpace callback.
static Expected< std::unique_ptr< EPCGenericRTDyldMemoryManager > > CreateWithDefaultBootstrapSymbols(ExecutorProcessControl &EPC)
Create an EPCGenericRTDyldMemoryManager using the given EPC, looking up the default symbol names in t...
EPCGenericRTDyldMemoryManager(ExecutorProcessControl &EPC, SymbolAddrs SAs)
Create an EPCGenericRTDyldMemoryManager using the given EPC and symbol addrs.
void reserveAllocationSpace(uintptr_t CodeSize, Align CodeAlign, uintptr_t RODataSize, Align RODataAlign, uintptr_t RWDataSize, Align RWDataAlign) override
Inform the memory manager about the total amount of memory required to allocate all sections to be lo...
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override
Register the EH frames with the runtime so that c++ exceptions work.
void notifyObjectLoaded(RuntimeDyld &Dyld, const object::ObjectFile &Obj) override
This method is called after an object has been loaded into memory but before relocations are applied ...
uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override
Allocate a memory block of (at least) the given size suitable for executable code.
Represents an address in the executor process.
uint64_t getValue() const
void setValue(uint64_t Addr)
ExecutorProcessControl supports interaction with a JIT target process.
A utility class for serializing to a blob from a variadic list.
static Expected< WrapperFunctionCall > Create(ExecutorAddr FnAddr, const ArgTs &...Args)
Create a WrapperFunctionCall using the given SPS serializer to serialize the arguments.
LLVM_ABI const SymbolNameSpec DeregisterEHFrameSectionAllocActionName
LLVM_ABI const SymbolNameSpec RegisterEHFrameSectionAllocActionName
LLVM_ABI Expected< SimpleMemoryMapBindings > createSimpleMemoryMapBindings(JITDylib &JD)
Build bindings over the SPS controller interface, resolving the operations in the given JITDylib unde...
MemProt
Describes Read/Write/Exec permissions for memory.
Definition MemoryFlags.h:27
LLVM_ABI void lookupAndApply(unique_function< void(Error)> OnApplied, LookupKind K, const JITDylibSearchOrder &SearchOrder, ArrayRef< LookupPrepareFn > PrepareFns)
Resolve the symbols contributed by every prepare function with a single lookup, then let each of thei...
uint64_t ExecutorAddrDiff
LookupPrepareFn recordAddr(SymbolNameSpec Name, ExecutorAddr *A, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Records the address of the symbol with the given name.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
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:1933
uintptr_t alignAddr(const void *Addr, Align Alignment)
Aligns Addr to Alignment bytes, rounding up.
Definition Alignment.h:181
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Bindings to the executor-side memory manager, plus the EH-frame registration alloc-action wrappers.
Represents an address range in the exceutor process.
std::vector< SegFinalizeRequest > Segments