LLVM 20.0.0git
MemoryMapper.cpp
Go to the documentation of this file.
1//===- MemoryMapper.cpp - Cross-process memory mapper ------------*- C++ -*-==//
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
11#include "llvm/Config/llvm-config.h" // for LLVM_ON_UNIX
14
15#if defined(LLVM_ON_UNIX) && !defined(__ANDROID__)
16#include <fcntl.h>
17#include <sys/mman.h>
18#if defined(__MVS__)
19#include "llvm/Support/BLAKE3.h"
20#include <sys/shm.h>
21#endif
22#include <unistd.h>
23#elif defined(_WIN32)
24#include <windows.h>
25#endif
26
27namespace llvm {
28namespace orc {
29
31
33 : PageSize(PageSize) {}
34
37 auto PageSize = sys::Process::getPageSize();
38 if (!PageSize)
39 return PageSize.takeError();
40 return std::make_unique<InProcessMemoryMapper>(*PageSize);
41}
42
43void InProcessMemoryMapper::reserve(size_t NumBytes,
44 OnReservedFunction OnReserved) {
45 std::error_code EC;
47 NumBytes, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
48
49 if (EC)
50 return OnReserved(errorCodeToError(EC));
51
52 {
53 std::lock_guard<std::mutex> Lock(Mutex);
54 Reservations[MB.base()].Size = MB.allocatedSize();
55 }
56
57 OnReserved(
58 ExecutorAddrRange(ExecutorAddr::fromPtr(MB.base()), MB.allocatedSize()));
59}
60
62 return Addr.toPtr<char *>();
63}
64
66 OnInitializedFunction OnInitialized) {
67 ExecutorAddr MinAddr(~0ULL);
68 ExecutorAddr MaxAddr(0);
69
70 // FIXME: Release finalize lifetime segments.
71 for (auto &Segment : AI.Segments) {
72 auto Base = AI.MappingBase + Segment.Offset;
73 auto Size = Segment.ContentSize + Segment.ZeroFillSize;
74
75 if (Base < MinAddr)
76 MinAddr = Base;
77
78 if (Base + Size > MaxAddr)
79 MaxAddr = Base + Size;
80
81 std::memset((Base + Segment.ContentSize).toPtr<void *>(), 0,
82 Segment.ZeroFillSize);
83
85 {Base.toPtr<void *>(), Size},
86 toSysMemoryProtectionFlags(Segment.AG.getMemProt()))) {
87 return OnInitialized(errorCodeToError(EC));
88 }
89 if ((Segment.AG.getMemProt() & MemProt::Exec) == MemProt::Exec)
91 }
92
93 auto DeinitializeActions = shared::runFinalizeActions(AI.Actions);
94 if (!DeinitializeActions)
95 return OnInitialized(DeinitializeActions.takeError());
96
97 {
98 std::lock_guard<std::mutex> Lock(Mutex);
99
100 // This is the maximum range whose permission have been possibly modified
101 Allocations[MinAddr].Size = MaxAddr - MinAddr;
102 Allocations[MinAddr].DeinitializationActions =
103 std::move(*DeinitializeActions);
104 Reservations[AI.MappingBase.toPtr<void *>()].Allocations.push_back(MinAddr);
105 }
106
107 OnInitialized(MinAddr);
108}
109
113 Error AllErr = Error::success();
114
115 {
116 std::lock_guard<std::mutex> Lock(Mutex);
117
118 for (auto Base : llvm::reverse(Bases)) {
119
121 Allocations[Base].DeinitializationActions)) {
122 AllErr = joinErrors(std::move(AllErr), std::move(Err));
123 }
124
125 // Reset protections to read/write so the area can be reused
127 {Base.toPtr<void *>(), Allocations[Base].Size},
130 AllErr = joinErrors(std::move(AllErr), errorCodeToError(EC));
131 }
132
133 Allocations.erase(Base);
134 }
135 }
136
137 OnDeinitialized(std::move(AllErr));
138}
139
141 OnReleasedFunction OnReleased) {
142 Error Err = Error::success();
143
144 for (auto Base : Bases) {
145 std::vector<ExecutorAddr> AllocAddrs;
146 size_t Size;
147 {
148 std::lock_guard<std::mutex> Lock(Mutex);
149 auto &R = Reservations[Base.toPtr<void *>()];
150 Size = R.Size;
151 AllocAddrs.swap(R.Allocations);
152 }
153
154 // deinitialize sub allocations
155 std::promise<MSVCPError> P;
156 auto F = P.get_future();
157 deinitialize(AllocAddrs, [&](Error Err) { P.set_value(std::move(Err)); });
158 if (Error E = F.get()) {
159 Err = joinErrors(std::move(Err), std::move(E));
160 }
161
162 // free the memory
163 auto MB = sys::MemoryBlock(Base.toPtr<void *>(), Size);
164
166 if (EC) {
167 Err = joinErrors(std::move(Err), errorCodeToError(EC));
168 }
169
170 std::lock_guard<std::mutex> Lock(Mutex);
171 Reservations.erase(Base.toPtr<void *>());
172 }
173
174 OnReleased(std::move(Err));
175}
176
178 std::vector<ExecutorAddr> ReservationAddrs;
179 {
180 std::lock_guard<std::mutex> Lock(Mutex);
181
182 ReservationAddrs.reserve(Reservations.size());
183 for (const auto &R : Reservations) {
184 ReservationAddrs.push_back(ExecutorAddr::fromPtr(R.getFirst()));
185 }
186 }
187
188 std::promise<MSVCPError> P;
189 auto F = P.get_future();
190 release(ReservationAddrs, [&](Error Err) { P.set_value(std::move(Err)); });
191 cantFail(F.get());
192}
193
194// SharedMemoryMapper
195
197 SymbolAddrs SAs, size_t PageSize)
198 : EPC(EPC), SAs(SAs), PageSize(PageSize) {
199#if (!defined(LLVM_ON_UNIX) || defined(__ANDROID__)) && !defined(_WIN32)
200 llvm_unreachable("SharedMemoryMapper is not supported on this platform yet");
201#endif
202}
203
206#if (defined(LLVM_ON_UNIX) && !defined(__ANDROID__)) || defined(_WIN32)
207 auto PageSize = sys::Process::getPageSize();
208 if (!PageSize)
209 return PageSize.takeError();
210
211 return std::make_unique<SharedMemoryMapper>(EPC, SAs, *PageSize);
212#else
213 return make_error<StringError>(
214 "SharedMemoryMapper is not supported on this platform yet",
216#endif
217}
218
219void SharedMemoryMapper::reserve(size_t NumBytes,
220 OnReservedFunction OnReserved) {
221#if (defined(LLVM_ON_UNIX) && !defined(__ANDROID__)) || defined(_WIN32)
222
225 SAs.Reserve,
226 [this, NumBytes, OnReserved = std::move(OnReserved)](
227 Error SerializationErr,
229 if (SerializationErr) {
230 cantFail(Result.takeError());
231 return OnReserved(std::move(SerializationErr));
232 }
233
234 if (!Result)
235 return OnReserved(Result.takeError());
236
237 ExecutorAddr RemoteAddr;
238 std::string SharedMemoryName;
239 std::tie(RemoteAddr, SharedMemoryName) = std::move(*Result);
240
241 void *LocalAddr = nullptr;
242
243#if defined(LLVM_ON_UNIX)
244
245#if defined(__MVS__)
247 reinterpret_cast<const uint8_t *>(SharedMemoryName.c_str()),
248 SharedMemoryName.size());
249 auto HashedName = BLAKE3::hash<sizeof(key_t)>(Data);
250 key_t Key = *reinterpret_cast<key_t *>(HashedName.data());
251 int SharedMemoryId =
252 shmget(Key, NumBytes, IPC_CREAT | __IPC_SHAREAS | 0700);
253 if (SharedMemoryId < 0) {
254 return OnReserved(errorCodeToError(
255 std::error_code(errno, std::generic_category())));
256 }
257 LocalAddr = shmat(SharedMemoryId, nullptr, 0);
258 if (LocalAddr == reinterpret_cast<void *>(-1)) {
259 return OnReserved(errorCodeToError(
260 std::error_code(errno, std::generic_category())));
261 }
262#else
263 int SharedMemoryFile = shm_open(SharedMemoryName.c_str(), O_RDWR, 0700);
264 if (SharedMemoryFile < 0) {
265 return OnReserved(errorCodeToError(errnoAsErrorCode()));
266 }
267
268 // this prevents other processes from accessing it by name
269 shm_unlink(SharedMemoryName.c_str());
270
271 LocalAddr = mmap(nullptr, NumBytes, PROT_READ | PROT_WRITE, MAP_SHARED,
272 SharedMemoryFile, 0);
273 if (LocalAddr == MAP_FAILED) {
274 return OnReserved(errorCodeToError(errnoAsErrorCode()));
275 }
276
277 close(SharedMemoryFile);
278#endif
279
280#elif defined(_WIN32)
281
282 std::wstring WideSharedMemoryName(SharedMemoryName.begin(),
283 SharedMemoryName.end());
284 HANDLE SharedMemoryFile = OpenFileMappingW(
285 FILE_MAP_ALL_ACCESS, FALSE, WideSharedMemoryName.c_str());
286 if (!SharedMemoryFile)
287 return OnReserved(errorCodeToError(mapWindowsError(GetLastError())));
288
289 LocalAddr =
290 MapViewOfFile(SharedMemoryFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
291 if (!LocalAddr) {
292 CloseHandle(SharedMemoryFile);
293 return OnReserved(errorCodeToError(mapWindowsError(GetLastError())));
294 }
295
296 CloseHandle(SharedMemoryFile);
297
298#endif
299 {
300 std::lock_guard<std::mutex> Lock(Mutex);
301 Reservations.insert({RemoteAddr, {LocalAddr, NumBytes}});
302 }
303
304 OnReserved(ExecutorAddrRange(RemoteAddr, NumBytes));
305 },
306 SAs.Instance, static_cast<uint64_t>(NumBytes));
307
308#else
309 OnReserved(make_error<StringError>(
310 "SharedMemoryMapper is not supported on this platform yet",
312#endif
313}
314
316 auto R = Reservations.upper_bound(Addr);
317 assert(R != Reservations.begin() && "Attempt to prepare unreserved range");
318 R--;
319
320 ExecutorAddrDiff Offset = Addr - R->first;
321
322 return static_cast<char *>(R->second.LocalAddr) + Offset;
323}
324
326 OnInitializedFunction OnInitialized) {
327 auto Reservation = Reservations.upper_bound(AI.MappingBase);
328 assert(Reservation != Reservations.begin() && "Attempt to initialize unreserved range");
329 Reservation--;
330
331 auto AllocationOffset = AI.MappingBase - Reservation->first;
332
334
335 AI.Actions.swap(FR.Actions);
336
337 FR.Segments.reserve(AI.Segments.size());
338
339 for (auto Segment : AI.Segments) {
340 char *Base = static_cast<char *>(Reservation->second.LocalAddr) +
341 AllocationOffset + Segment.Offset;
342 std::memset(Base + Segment.ContentSize, 0, Segment.ZeroFillSize);
343
345 SegReq.RAG = {Segment.AG.getMemProt(),
346 Segment.AG.getMemLifetime() == MemLifetime::Finalize};
347 SegReq.Addr = AI.MappingBase + Segment.Offset;
348 SegReq.Size = Segment.ContentSize + Segment.ZeroFillSize;
349
350 FR.Segments.push_back(SegReq);
351 }
352
355 SAs.Initialize,
356 [OnInitialized = std::move(OnInitialized)](
357 Error SerializationErr, Expected<ExecutorAddr> Result) mutable {
358 if (SerializationErr) {
359 cantFail(Result.takeError());
360 return OnInitialized(std::move(SerializationErr));
361 }
362
363 OnInitialized(std::move(Result));
364 },
365 SAs.Instance, Reservation->first, std::move(FR));
366}
367
369 ArrayRef<ExecutorAddr> Allocations,
373 SAs.Deinitialize,
374 [OnDeinitialized = std::move(OnDeinitialized)](Error SerializationErr,
375 Error Result) mutable {
376 if (SerializationErr) {
377 cantFail(std::move(Result));
378 return OnDeinitialized(std::move(SerializationErr));
379 }
380
381 OnDeinitialized(std::move(Result));
382 },
383 SAs.Instance, Allocations);
384}
385
387 OnReleasedFunction OnReleased) {
388#if (defined(LLVM_ON_UNIX) && !defined(__ANDROID__)) || defined(_WIN32)
389 Error Err = Error::success();
390
391 {
392 std::lock_guard<std::mutex> Lock(Mutex);
393
394 for (auto Base : Bases) {
395
396#if defined(LLVM_ON_UNIX)
397
398#if defined(__MVS__)
399 if (shmdt(Reservations[Base].LocalAddr) < 0)
400 Err = joinErrors(std::move(Err), errorCodeToError(errnoAsErrorCode()));
401#else
402 if (munmap(Reservations[Base].LocalAddr, Reservations[Base].Size) != 0)
403 Err = joinErrors(std::move(Err), errorCodeToError(errnoAsErrorCode()));
404#endif
405
406#elif defined(_WIN32)
407
408 if (!UnmapViewOfFile(Reservations[Base].LocalAddr))
409 Err = joinErrors(std::move(Err),
410 errorCodeToError(mapWindowsError(GetLastError())));
411
412#endif
413
414 Reservations.erase(Base);
415 }
416 }
417
420 SAs.Release,
421 [OnReleased = std::move(OnReleased),
422 Err = std::move(Err)](Error SerializationErr, Error Result) mutable {
423 if (SerializationErr) {
424 cantFail(std::move(Result));
425 return OnReleased(
426 joinErrors(std::move(Err), std::move(SerializationErr)));
427 }
428
429 return OnReleased(joinErrors(std::move(Err), std::move(Result)));
430 },
431 SAs.Instance, Bases);
432#else
433 OnReleased(make_error<StringError>(
434 "SharedMemoryMapper is not supported on this platform yet",
436#endif
437}
438
440 std::lock_guard<std::mutex> Lock(Mutex);
441 for (const auto &R : Reservations) {
442
443#if defined(LLVM_ON_UNIX) && !defined(__ANDROID__)
444
445#if defined(__MVS__)
446 shmdt(R.second.LocalAddr);
447#else
448 munmap(R.second.LocalAddr, R.second.Size);
449#endif
450
451#elif defined(_WIN32)
452
453 UnmapViewOfFile(R.second.LocalAddr);
454
455#else
456
457 (void)R;
458
459#endif
460 }
461}
462
463} // namespace orc
464
465} // namespace llvm
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
uint64_t Addr
uint64_t Size
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 F(x, y, z)
Definition: MD5.cpp:55
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
bool erase(const KeyT &Val)
Definition: DenseMap.h:321
unsigned size() const
Definition: DenseMap.h:99
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Represents an address in the executor process.
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
std::enable_if_t< std::is_pointer< T >::value, T > toPtr(WrapFn &&Wrap=WrapFn()) const
Cast this ExecutorAddr to a pointer of the given type.
ExecutorProcessControl supports interaction with a JIT target process.
void callSPSWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr, SendResultT &&SendResult, const ArgTs &...Args)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
void initialize(AllocInfo &AI, OnInitializedFunction OnInitialized) override
Ensures executor memory is synchronized with working copy memory, sends functions to be called after ...
void reserve(size_t NumBytes, OnReservedFunction OnReserved) override
Reserves address space in executor process.
InProcessMemoryMapper(size_t PageSize)
void deinitialize(ArrayRef< ExecutorAddr > Allocations, OnDeinitializedFunction OnDeInitialized) override
Runs previously specified deinitialization actions Executor addresses returned by initialize should b...
static Expected< std::unique_ptr< InProcessMemoryMapper > > Create()
char * prepare(ExecutorAddr Addr, size_t ContentSize) override
Provides working memory.
void release(ArrayRef< ExecutorAddr > Reservations, OnReleasedFunction OnRelease) override
Release address space acquired through reserve()
static Expected< std::unique_ptr< SharedMemoryMapper > > Create(ExecutorProcessControl &EPC, SymbolAddrs SAs)
void reserve(size_t NumBytes, OnReservedFunction OnReserved) override
Reserves address space in executor process.
void deinitialize(ArrayRef< ExecutorAddr > Allocations, OnDeinitializedFunction OnDeInitialized) override
Runs previously specified deinitialization actions Executor addresses returned by initialize should b...
void initialize(AllocInfo &AI, OnInitializedFunction OnInitialized) override
Ensures executor memory is synchronized with working copy memory, sends functions to be called after ...
char * prepare(ExecutorAddr Addr, size_t ContentSize) override
Provides working memory.
void release(ArrayRef< ExecutorAddr > Reservations, OnReleasedFunction OnRelease) override
Release address space acquired through reserve()
SharedMemoryMapper(ExecutorProcessControl &EPC, SymbolAddrs SAs, size_t PageSize)
This class encapsulates the notion of a memory block which has an address and a size.
Definition: Memory.h:32
static std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method.
static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e....
static void InvalidateInstructionCache(const void *Addr, size_t Len)
InvalidateInstructionCache - Before the JIT can run a block of code that has been emitted it must inv...
static std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags)
This method sets the protection flags for a block of memory to the state specified by /p Flags.
static Expected< unsigned > getPageSize()
Get the process's page size.
unique_function is a type-erasing functor similar to std::function.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
shared::SPSExpected< shared::SPSExecutorAddr >(shared::SPSExecutorAddr, shared::SPSExecutorAddr, shared::SPSSharedMemoryFinalizeRequest) SPSExecutorSharedMemoryMapperServiceInitializeSignature
Definition: OrcRTBridge.h:79
shared::SPSError(shared::SPSExecutorAddr, shared::SPSSequence< shared::SPSExecutorAddr >) SPSExecutorSharedMemoryMapperServiceReleaseSignature
Definition: OrcRTBridge.h:84
shared::SPSExpected< shared::SPSTuple< shared::SPSExecutorAddr, shared::SPSString > >(shared::SPSExecutorAddr, uint64_t) SPSExecutorSharedMemoryMapperServiceReserveSignature
Definition: OrcRTBridge.h:75
shared::SPSError(shared::SPSExecutorAddr, shared::SPSSequence< shared::SPSExecutorAddr >) SPSExecutorSharedMemoryMapperServiceDeinitializeSignature
Definition: OrcRTBridge.h:82
Error runDeallocActions(ArrayRef< WrapperFunctionCall > DAs)
Run deallocation actions.
Expected< std::vector< WrapperFunctionCall > > runFinalizeActions(AllocActions &AAs)
Run finalize actions.
@ Finalize
Finalize memory should be allocated by the allocator, and then be overwritten and deallocated after a...
sys::Memory::ProtectionFlags toSysMemoryProtectionFlags(MemProt MP)
Convert a MemProt value to a corresponding sys::Memory::ProtectionFlags value.
Definition: MemoryFlags.h:44
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:438
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition: Error.h:1226
std::error_code mapWindowsError(unsigned EV)
Represents an address range in the exceutor process.
Represents a single allocation containing multiple segments and initialization and deinitialization a...
Definition: MemoryMapper.h:30
std::vector< SegInfo > Segments
Definition: MemoryMapper.h:40
shared::AllocActions Actions
Definition: MemoryMapper.h:41
std::vector< SharedMemorySegFinalizeRequest > Segments