11#include "llvm/Config/llvm-config.h"
15#if defined(LLVM_ON_UNIX) && !defined(__ANDROID__)
39 return PageSize.takeError();
40 return std::make_unique<InProcessMemoryMapper>(*PageSize);
53 std::lock_guard<std::mutex> Lock(
Mutex);
54 Reservations[MB.base()].Size = MB.allocatedSize();
62 return Addr.toPtr<
char *>();
73 auto Size = Segment.ContentSize + Segment.ZeroFillSize;
81 std::memset((
Base + Segment.ContentSize).toPtr<
void *>(), 0,
82 Segment.ZeroFillSize);
93 std::vector<shared::WrapperFunctionCall> DeinitializeActions;
95 std::promise<MSVCPExpected<std::vector<shared::WrapperFunctionCall>>>
P;
96 auto F =
P.get_future();
99 P.set_value(std::move(R));
101 if (
auto DeinitializeActionsOrErr =
F.get())
102 DeinitializeActions = std::move(*DeinitializeActionsOrErr);
104 return OnInitialized(DeinitializeActionsOrErr.takeError());
108 std::lock_guard<std::mutex> Lock(
Mutex);
111 auto &
Alloc = Allocations[MinAddr];
112 Alloc.Size = MaxAddr - MinAddr;
113 Alloc.DeinitializationActions = std::move(DeinitializeActions);
114 Reservations[AI.
MappingBase.
toPtr<
void *>()].Allocations.push_back(MinAddr);
117 OnInitialized(MinAddr);
126 std::lock_guard<std::mutex> Lock(
Mutex);
131 Allocations[
Base].DeinitializationActions, [&](
Error Err) {
132 AllErr =
joinErrors(std::move(AllErr), std::move(Err));
147 OnDeinitialized(std::move(AllErr));
154 for (
auto Base : Bases) {
155 std::vector<ExecutorAddr> AllocAddrs;
158 std::lock_guard<std::mutex> Lock(
Mutex);
159 auto &R = Reservations[
Base.toPtr<
void *>()];
161 AllocAddrs.swap(R.Allocations);
165 std::promise<MSVCPError>
P;
166 auto F =
P.get_future();
180 std::lock_guard<std::mutex> Lock(
Mutex);
181 Reservations.
erase(
Base.toPtr<
void *>());
184 OnReleased(std::move(Err));
188 std::vector<ExecutorAddr> ReservationAddrs;
190 std::lock_guard<std::mutex> Lock(
Mutex);
192 ReservationAddrs.reserve(Reservations.
size());
193 for (
const auto &R : Reservations) {
198 std::promise<MSVCPError>
P;
199 auto F =
P.get_future();
200 release(ReservationAddrs, [&](
Error Err) {
P.set_value(std::move(Err)); });
209#if (!defined(LLVM_ON_UNIX) || defined(__ANDROID__)) && !defined(_WIN32)
210 llvm_unreachable(
"SharedMemoryMapper is not supported on this platform yet");
216#if (defined(LLVM_ON_UNIX) && !defined(__ANDROID__)) || defined(_WIN32)
219 return PageSize.takeError();
221 return std::make_unique<SharedMemoryMapper>(EPC, SAs, *PageSize);
223 return make_error<StringError>(
224 "SharedMemoryMapper is not supported on this platform yet",
231#if (defined(LLVM_ON_UNIX) && !defined(__ANDROID__)) || defined(_WIN32)
233 int SharedMemoryId = -1;
237 [
this, NumBytes, OnReserved = std::move(OnReserved), SharedMemoryId](
238 Error SerializationErr,
240 if (SerializationErr) {
242 return OnReserved(std::move(SerializationErr));
246 return OnReserved(
Result.takeError());
249 std::string SharedMemoryName;
250 std::tie(RemoteAddr, SharedMemoryName) = std::move(*
Result);
252 void *LocalAddr =
nullptr;
254#if defined(LLVM_ON_UNIX)
258 reinterpret_cast<const uint8_t *
>(SharedMemoryName.c_str()),
259 SharedMemoryName.size());
260 auto HashedName = BLAKE3::hash<sizeof(key_t)>(
Data);
261 key_t Key = *
reinterpret_cast<key_t *
>(HashedName.data());
263 shmget(Key, NumBytes, IPC_CREAT | __IPC_SHAREAS | 0700);
264 if (SharedMemoryId < 0) {
266 std::error_code(errno, std::generic_category())));
268 LocalAddr = shmat(SharedMemoryId,
nullptr, 0);
269 if (LocalAddr ==
reinterpret_cast<void *
>(-1)) {
271 std::error_code(errno, std::generic_category())));
274 int SharedMemoryFile = shm_open(SharedMemoryName.c_str(), O_RDWR, 0700);
275 if (SharedMemoryFile < 0) {
280 shm_unlink(SharedMemoryName.c_str());
282 LocalAddr = mmap(
nullptr, NumBytes, PROT_READ | PROT_WRITE, MAP_SHARED,
283 SharedMemoryFile, 0);
284 if (LocalAddr == MAP_FAILED) {
288 close(SharedMemoryFile);
293 std::wstring WideSharedMemoryName(SharedMemoryName.begin(),
294 SharedMemoryName.end());
295 HANDLE SharedMemoryFile = OpenFileMappingW(
296 FILE_MAP_ALL_ACCESS, FALSE, WideSharedMemoryName.c_str());
297 if (!SharedMemoryFile)
301 MapViewOfFile(SharedMemoryFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
303 CloseHandle(SharedMemoryFile);
307 CloseHandle(SharedMemoryFile);
311 std::lock_guard<std::mutex> Lock(
Mutex);
313 {RemoteAddr, {LocalAddr, NumBytes, SharedMemoryId}});
321 OnReserved(make_error<StringError>(
322 "SharedMemoryMapper is not supported on this platform yet",
328 auto R = Reservations.upper_bound(
Addr);
329 assert(R != Reservations.begin() &&
"Attempt to prepare unreserved range");
334 return static_cast<char *
>(R->second.LocalAddr) +
Offset;
339 auto Reservation = Reservations.upper_bound(AI.
MappingBase);
340 assert(Reservation != Reservations.begin() &&
"Attempt to initialize unreserved range");
343 auto AllocationOffset = AI.
MappingBase - Reservation->first;
352 char *
Base =
static_cast<char *
>(Reservation->second.LocalAddr) +
353 AllocationOffset + Segment.Offset;
354 std::memset(
Base + Segment.ContentSize, 0, Segment.ZeroFillSize);
357 SegReq.
RAG = {Segment.AG.getMemProt(),
360 SegReq.
Size = Segment.ContentSize + Segment.ZeroFillSize;
368 [OnInitialized = std::move(OnInitialized)](
370 if (SerializationErr) {
372 return OnInitialized(std::move(SerializationErr));
375 OnInitialized(std::move(
Result));
377 SAs.
Instance, Reservation->first, std::move(FR));
386 [OnDeinitialized = std::move(OnDeinitialized)](
Error SerializationErr,
388 if (SerializationErr) {
390 return OnDeinitialized(std::move(SerializationErr));
393 OnDeinitialized(std::move(
Result));
400#if (defined(LLVM_ON_UNIX) && !defined(__ANDROID__)) || defined(_WIN32)
404 std::lock_guard<std::mutex> Lock(
Mutex);
406 for (
auto Base : Bases) {
408#if defined(LLVM_ON_UNIX)
411 if (shmdt(Reservations[
Base].LocalAddr) < 0 ||
412 shmctl(Reservations[
Base].SharedMemoryId, IPC_RMID, NULL) < 0)
415 if (munmap(Reservations[
Base].LocalAddr, Reservations[
Base].
Size) != 0)
421 if (!UnmapViewOfFile(Reservations[
Base].LocalAddr))
427 Reservations.erase(
Base);
434 [OnReleased = std::move(OnReleased),
436 if (SerializationErr) {
439 joinErrors(std::move(Err), std::move(SerializationErr)));
446 OnReleased(make_error<StringError>(
447 "SharedMemoryMapper is not supported on this platform yet",
453 std::lock_guard<std::mutex> Lock(
Mutex);
454 for (
const auto &R : Reservations) {
456#if defined(LLVM_ON_UNIX) && !defined(__ANDROID__)
459 shmdt(R.second.LocalAddr);
461 munmap(R.second.LocalAddr, R.second.Size);
466 UnmapViewOfFile(R.second.LocalAddr);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool erase(const KeyT &Val)
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
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)
~InProcessMemoryMapper() override
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...
~SharedMemoryMapper() override
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.
static LLVM_ABI 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 LLVM_ABI std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method.
static LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI 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
shared::SPSError(shared::SPSExecutorAddr, shared::SPSSequence< shared::SPSExecutorAddr >) SPSExecutorSharedMemoryMapperServiceReleaseSignature
shared::SPSExpected< shared::SPSTuple< shared::SPSExecutorAddr, shared::SPSString > >(shared::SPSExecutorAddr, uint64_t) SPSExecutorSharedMemoryMapperServiceReserveSignature
shared::SPSError(shared::SPSExecutorAddr, shared::SPSSequence< shared::SPSExecutorAddr >) SPSExecutorSharedMemoryMapperServiceDeinitializeSignature
LLVM_ABI void runDeallocActions(ArrayRef< WrapperFunctionCall > DAs, OnRunDeallocActionsComeleteFn OnComplete)
Run deallocation actions.
LLVM_ABI void runFinalizeActions(AllocActions &AAs, OnRunFinalizeActionsCompleteFn OnComplete)
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.
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...
auto reverse(ContainerTy &&C)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI std::error_code mapWindowsError(unsigned EV)
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Represents an address range in the exceutor process.
Represents a single allocation containing multiple segments and initialization and deinitialization a...
std::vector< SegInfo > Segments
shared::AllocActions Actions
ExecutorAddr Deinitialize
std::vector< SharedMemorySegFinalizeRequest > Segments
shared::AllocActions Actions