From 5a64a05b7073f244edf491e73df39dd4540f44d9 Mon Sep 17 00:00:00 2001 From: maxjivi05 Date: Wed, 2 Dec 2026 17:40:05 -0500 Subject: [PATCH] FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers --- ...at-ptrace-seccomp-and-proc-emulation.patch | 5051 +++++++++++++++++ 1 file changed, 5051 insertions(+) create mode 100644 tools/fex/patches/0020-anticheat-ptrace-seccomp-and-proc-emulation.patch diff --git a/tools/fex/patches/0020-anticheat-ptrace-seccomp-and-proc-emulation.patch b/tools/fex/patches/0020-anticheat-ptrace-seccomp-and-proc-emulation.patch new file mode 100644 index 0000000000..8fefa3d56f --- /dev/null +++ b/tools/fex/patches/0020-anticheat-ptrace-seccomp-and-proc-emulation.patch @@ -0,0 +1,5051 @@ +diff --git a/FEXCore/Source/CMakeLists.txt b/FEXCore/Source/CMakeLists.txt +index 61385d2c3..b515a4a02 100644 +--- a/FEXCore/Source/CMakeLists.txt ++++ b/FEXCore/Source/CMakeLists.txt +@@ -4,6 +4,7 @@ set(FEXCORE_BASE_SRCS + Interface/Config/Config.cpp + Utils/Allocator.cpp + Utils/FileLoading.cpp ++ Utils/FaultSafeRead.cpp + Utils/FileUtils.cpp + Utils/ForcedAssert.cpp + Utils/LogManager.cpp +diff --git a/FEXCore/Source/Interface/Config/Config.json.in b/FEXCore/Source/Interface/Config/Config.json.in +index 602b2a50d..5f59684e4 100644 +--- a/FEXCore/Source/Interface/Config/Config.json.in ++++ b/FEXCore/Source/Interface/Config/Config.json.in +@@ -602,6 +602,62 @@ + "\tfull: Validate code before every run (slow)" + ] + }, ++ "ProfileSampleHz": { ++ "Type": "uint32", ++ "Default": "0", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Samples the host PC of the main guest thread this many times per second into /dev/shm/fex--samples (in-process; no ptrace).", ++ "Use with LibraryJITNaming to attribute samples to guest libraries. 0 disables." ++ ] ++ }, ++ "ProfileSampleMinThreads": { ++ "Type": "uint32", ++ "Default": "100", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "ProfileSampleHz starts the sampler in the process that reaches this many guest threads (default 100: the application,", ++ "not the hundreds of helper processes of a Steam/Wine session). 1 samples every process from its first thread.", ++ "0: no sampler thread; each SIGPROF sent from outside stores a snapshot record of the receiving thread (ring in fex--snap)." ++ ] ++ }, ++ "ProfileSampleAllThreads": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "ProfileSampleHz samples every guest thread instead of only the main one." ++ ] ++ }, ++ "SignalTrace": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Records guest signal handling events (host signal arrival, masking decisions, delivery, rt_sigreturn, sigprocmask, kill/tgkill)", ++ "into a ring buffer in /dev/shm/fex--sigtrace. For diagnosing lost signals; decode with tools/harness/sigtrace.py." ++ ] ++ }, ++ "SignalMaskFix": { ++ "Type": "bool", ++ "Default": "true", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Run guest signal handlers with the signal mask Linux gives them (the interrupted mask plus sa_mask and the signal)", ++ "and restore the interrupted mask at rt_sigreturn. With false FEX blocks only sa_mask and the signal during the handler and keeps", ++ "a stale view of the mask afterwards, so a signal handler that restores its saved mask can unblock the signal it is running for." ++ ] ++ }, ++ "SMCHotPageFaults": { ++ "Type": "uint32", ++ "Default": "32", ++ "AffectsCodeGen": "true", ++ "Desc": [ ++ "Number of self-modifying-code write faults a guest page may take before FEX stops write-protecting it.", ++ "Instead the JIT verifies the code of every instruction it translates from such a page (like SMCChecks=full, but only for that page).", ++ "Only used with SMCChecks=mtrack. 0 disables the demotion (pages stay write-protected and keep faulting)." ++ ] ++ }, + "TSOEnabled": { + "Type": "bool", + "Default": "true", +@@ -689,6 +745,16 @@ + "Should only be used for applications that have issues with this set." + ] + }, ++ "EnableCPUIDFaulting": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "true", ++ "Desc": [ ++ "Honour ARCH_SET_CPUID. When a guest thread calls arch_prctl(ARCH_SET_CPUID, 0), CPUID from that", ++ "thread raises a #GP (SIGSEGV, si_code SI_KERNEL) like Linux with a CPUID-faulting CPU, instead of", ++ "executing transparently. Off by default, so a guest that never asks for it is unaffected." ++ ] ++ }, + "StartupSleep": { + "Type": "uint32", + "Default": "0", +diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h +index 9b91055bd..aa39b26d2 100644 +--- a/FEXCore/Source/Interface/Context/Context.h ++++ b/FEXCore/Source/Interface/Context/Context.h +@@ -223,8 +223,12 @@ public: + + void OnCodeBufferAllocated(const std::shared_ptr&) override; + void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) override; +- void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override; +- void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; ++ void InvalidateExecutableRangeCaches() override { ++ ExecutableRangeEpoch.fetch_add(1, std::memory_order_acq_rel); ++ } ++ bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override; ++ std::atomic ExecutableRangeEpoch {}; ++ void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) override; + FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() override { + return CodeInvalidationMutex; + } +@@ -354,6 +358,7 @@ public: + FEX_CONFIG_OPT(SingleStepConfig, SINGLESTEP); + FEX_CONFIG_OPT(GdbServer, GDBSERVER); + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); ++ FEX_CONFIG_OPT(EnableCPUIDFaulting, ENABLECPUIDFAULTING); + FEX_CONFIG_OPT(TSOEnabled, TSOENABLED); + FEX_CONFIG_OPT(VectorTSOEnabled, VECTORTSOENABLED); + FEX_CONFIG_OPT(MemcpySetTSOEnabled, MEMCPYSETTSOENABLED); +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +index 9f04358c5..02d9a280a 100644 +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -31,6 +31,7 @@ $end_info$ + #include "Utils/Allocator.h" + #include "Utils/Allocator/HostAllocator.h" + #include "Utils/crc32.h" ++#include + #include + #include "Utils/variable_length_integer.h" + +@@ -201,8 +202,11 @@ uint32_t ContextImpl::ReconstructCompactedEFLAGS(FEXCore::Core::InternalThreadSt + case X86State::RFLAG_SF_RAW_LOC: + case X86State::RFLAG_OF_RAW_LOC: + case X86State::RFLAG_DF_RAW_LOC: ++ case X86State::RFLAG_NZCV_LOC: ++ case X86State::RFLAG_NZCV_1_LOC: ++ case X86State::RFLAG_NZCV_2_LOC: ++ case X86State::RFLAG_NZCV_3_LOC: + // Intentionally do nothing. +- // These contain multiple bits which can corrupt other members when compacted. + break; + default: EFLAGS |= uint32_t {Frame->State.flags[i]} << i; break; + } +@@ -645,11 +649,13 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue + Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP); + } + +- if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection) { ++ if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection || SyscallHandler->IsSMCHotPage(InstAddress)) { + auto ExistingCodePtr = reinterpret_cast(Block.Entry + BlockInstructionsLength); + auto InstAddressReg = Thread->OpDispatcher->_EntrypointOffset(GPRSize, InstAddress - GuestRIP); + +- auto Value = FEXCore::Utils::crc32(ExistingCodePtr, DecodedInfo->InstSize); ++ uint8_t InstBytes[16]; ++ const bool Readable = FEXCore::Utils::FaultSafeRead::Copy(InstBytes, ExistingCodePtr, DecodedInfo->InstSize); ++ auto Value = Readable ? FEXCore::Utils::crc32(InstBytes, DecodedInfo->InstSize) : ~0U; + auto CRC = WantsDiskCachePatching ? + Thread->OpDispatcher->_PatchableGuestCRC(IR::OpSize::i64Bit, Value, (int64_t)ExistingCodePtr, DecodedInfo->InstSize) : + Thread->OpDispatcher->Constant(Value); +@@ -730,6 +736,8 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue + Thread->OpDispatcher->InvalidOp(DecodedInfo); + } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::UNIMPLEMENTED_INST) { + Thread->OpDispatcher->UnimplementedOp(DecodedInfo); ++ } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::TOO_LONG_INST) { ++ Thread->OpDispatcher->PermissionRestrictedOp(DecodedInfo); + } else { + Thread->OpDispatcher->NoExecOrPartialOp(DecodedInfo); + } +@@ -897,9 +905,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + auto LoadedCode = Thread->CPUBackend->LoadCachedCode(Hit->HostCode); + if (LoadedCode.BlockBegin) { + for (auto& CodePage : Hit->GuestPages) { +- if (Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) { + SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } ++ Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } + + LOGMAN_THROW_A_FMT(Hit->EntryPointRIPs.size() == Hit->EntryPointHostOffsets.size(), "Mismatched Disk Cache entrypoint pairs!"); +@@ -993,9 +1002,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + CodePages.reserve(BlockInfo->CodePages.size()); + CodePages.insert(CodePages.end(), BlockInfo->CodePages.begin(), BlockInfo->CodePages.end()); + for (auto CodePage : BlockInfo->CodePages) { +- if (Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) { + SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } ++ Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } + } + +@@ -1006,10 +1016,13 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + if (DebugData && DebugData->Relocations) { + Relocations = *DebugData->Relocations; + } +- std::span GuestCode = {reinterpret_cast(StartAddr), Length}; +- const Frontend::Decoder::DecodedBlockInformation* BlockInfo = +- NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr; +- DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo); ++ fextl::vector GuestCodeCopy(Length); ++ if (FEXCore::Utils::FaultSafeRead::Copy(GuestCodeCopy.data(), reinterpret_cast(StartAddr), Length)) { ++ std::span GuestCode = GuestCodeCopy; ++ const Frontend::Decoder::DecodedBlockInformation* BlockInfo = ++ NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr; ++ DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo); ++ } + } + + if (CodeMapWriter && Region && Region->FileStartVA != 0) { +@@ -1055,31 +1068,38 @@ uintptr_t ContextImpl::CompileSingleStep(FEXCore::Core::CpuStateFrame* Frame, ui + return (uintptr_t)CodePtr; + } + +-void ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) { ++bool ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) { + FEXCORE_PROFILE_SCOPED("InvalidateCodeBuffersCodeRange"); + + LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here"); + std::scoped_lock lk {CodeBufferListLock}; ++ bool Found = false; + auto it = CodeBufferList.begin(); + while (it != CodeBufferList.end()) { + if (auto Strong = it->lock()) { +- Strong->LookupCache->InvalidateRange(Start, Length); ++ Found |= Strong->LookupCache->InvalidateRange(Start, Length); + it++; + } else { + it = CodeBufferList.erase(it); + } + } ++ return Found; + } + +-void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { ++void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) { + LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here"); + + // Ensures now-modified mappings aren't cached as being in their previous non-executable state. + // Accessing FrontendDecoder is safe as the thread's code invalidation mutex must be locked here. + Thread->FrontendDecoder->ResetExecutableRangeCache(); + ++ if (!CodeMayBeCached) { ++ return; ++ } ++ + if (Thread->LookupCache->InvalidateCacheRange(Start, Length)) { + FEXCORE_PROFILE_SCOPED("InvalidateCallRet"); ++ FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedCallRetFlushCount, 1); + + // This may cause access violations in the thread on Windows as zeroing is not atomic, this is handled by the frontend + Allocator::VirtualDontNeed(Thread->CallRetStackBase, FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE); +diff --git a/FEXCore/Source/Interface/Core/DiskCache.cpp b/FEXCore/Source/Interface/Core/DiskCache.cpp +index 3c78b22da..d903216c1 100644 +--- a/FEXCore/Source/Interface/Core/DiskCache.cpp ++++ b/FEXCore/Source/Interface/Core/DiskCache.cpp +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -22,6 +23,23 @@ + #include + #include + ++namespace { ++template ++bool HashGuestMemory(UpdateFn&& Update, uint64_t Address, uint64_t Size) { ++ uint8_t Buffer[256]; ++ while (Size) { ++ const uint64_t Chunk = std::min(Size, sizeof(Buffer)); ++ if (!FEXCore::Utils::FaultSafeRead::Copy(Buffer, reinterpret_cast(Address), Chunk)) { ++ return false; ++ } ++ Update(Buffer, Chunk); ++ Address += Chunk; ++ Size -= Chunk; ++ } ++ return true; ++} ++} ++ + namespace FEXCore { + + namespace DiskCache { +@@ -576,12 +594,18 @@ namespace DiskCache { + } + uint64_t HashStart = SubBlock.Entry; + // skip over masked in-block data and data/etc gaps between blocks ++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) { ++ XXH3_64bits_update(&HashState, Bytes, Size); ++ }; + for (auto& DataMask : SubBlock.DataMasks) { +- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), DataMask.FieldAddress - HashStart); ++ if (!HashGuestMemory(Update, HashStart, DataMask.FieldAddress - HashStart)) { ++ return std::nullopt; ++ } + HashStart = DataMask.FieldAddress + DataMask.ValueSize; + } +- if (HashStart != SubBlock.Entry + SubBlock.Size) { +- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), SubBlock.Size - (HashStart - SubBlock.Entry)); ++ if (HashStart != SubBlock.Entry + SubBlock.Size && ++ !HashGuestMemory(Update, HashStart, SubBlock.Size - (HashStart - SubBlock.Entry))) { ++ return std::nullopt; + } + } + GuestCodeKey = XXH3_64bits_digest(&HashState); +@@ -704,8 +728,13 @@ namespace DiskCache { + if (FirstHash || LastFootprintHashed != CurrentFootprint) { + XXH3_state_t HashState; + XXH3_128bits_reset(&HashState); ++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) { ++ XXH3_128bits_update(&HashState, Bytes, Size); ++ }; + for (uint32_t i = 0; i < Entry.GuestExtents.size(); i += 2) { +- XXH3_128bits_update(&HashState, reinterpret_cast(GuestRIP) + Entry.GuestExtents[i], Entry.GuestExtents[i + 1]); ++ if (!HashGuestMemory(Update, GuestRIP + Entry.GuestExtents[i], Entry.GuestExtents[i + 1])) { ++ return std::nullopt; ++ } + } + LiveGuestHash = XXH3_128bits_digest(&HashState); + LastFootprintHashed = CurrentFootprint; +diff --git a/FEXCore/Source/Interface/Core/DiskCache.h b/FEXCore/Source/Interface/Core/DiskCache.h +index 4899cd250..85b4ec02a 100644 +--- a/FEXCore/Source/Interface/Core/DiskCache.h ++++ b/FEXCore/Source/Interface/Core/DiskCache.h +@@ -249,7 +249,7 @@ namespace DiskCache { + // The current version of the diskcache. + // This must be changed any time codegen changes occur! + // Be aware of the impact of changing this frequently! +- static constexpr uint16_t FormatVersion = 43; ++ static constexpr uint16_t FormatVersion = 0x8000 | (1 << 8) | 43; + + static constexpr uint32_t LOOKUP_KEY_MAX_BUCKET_DEPTH = 500; + +diff --git a/FEXCore/Source/Interface/Core/Frontend.cpp b/FEXCore/Source/Interface/Core/Frontend.cpp +index 8d1d8db47..47b465b2a 100644 +--- a/FEXCore/Source/Interface/Core/Frontend.cpp ++++ b/FEXCore/Source/Interface/Core/Frontend.cpp +@@ -19,6 +19,7 @@ $end_info$ + #include + #include + #include ++#include + #include + #include + #include +@@ -108,6 +109,11 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) { + } + } + ++ if (const auto Epoch = CTX->ExecutableRangeEpoch.load(std::memory_order_acquire); Epoch != ExecutableRangeEpochSeen) { ++ ExecutableRangeEpochSeen = Epoch; ++ ResetExecutableRangeCache(); ++ } ++ + uint64_t RemainingSize = Size; + while (Address < ExecutableRangeBase || Address + RemainingSize > ExecutableRangeEnd) { + auto RangeInfo = CTX->SyscallHandler->QueryGuestExecutableRange(Thread, Address); +@@ -132,8 +138,13 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) { + } + + uint8_t Decoder::ReadByte() { ++ if (InstructionSize >= MAX_INST_SIZE) { ++ HitInstructionLengthLimit = true; ++ return 0; ++ } ++ + std::optional Byte = PeekByte(0); +- if (!Byte || InstructionSize == MAX_INST_SIZE) { ++ if (!Byte) { + HitNonExecutableRange = true; + // Pretend we read 0, the main decode loop will see HitNonExecutableRange and rollback the instruction. + return 0; +@@ -146,8 +157,10 @@ uint8_t Decoder::ReadByte() { + + std::optional Decoder::PeekByte(uint8_t Offset) { + uint64_t ByteAddress = reinterpret_cast(InstStream.InstStream + InstructionSize + Offset); +- if (CheckRangeExecutable(ByteAddress, 1) == 1) { +- return InstStream.AdjustedInstStream[InstructionSize + Offset]; ++ uint8_t Byte; ++ if (CheckRangeExecutable(ByteAddress, 1) == 1 && ++ FEXCore::Utils::FaultSafeRead::Copy(&Byte, &InstStream.AdjustedInstStream[InstructionSize + Offset], 1)) { ++ return Byte; + } else { + return std::nullopt; + } +@@ -160,13 +173,24 @@ std::pair Decoder::ReadData(uint8_t Size) { + uint64_t Address = reinterpret_cast(InstStream.InstStream + InstructionSize); + LastFieldReadOffset = (uint8_t)InstructionSize; + LastFieldReadSize = Size; +- auto ReadableSize = CheckRangeExecutable(Address, Size); +- if (ReadableSize == Size) { +- std::memcpy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size); +- } else { +- HitNonExecutableRange = true; +- // See PeekByte, this specific case may cause some executable memory to read as 0 but it doesn't matter as the entire instruction will be rolled back anyway. ++ int32_t ReadableSize {}; ++ if (InstructionSize + Size > MAX_INST_SIZE) [[unlikely]] { ++ const int32_t FetchableSize = InstructionSize < MAX_INST_SIZE ? MAX_INST_SIZE - InstructionSize : 0; ++ ReadableSize = FetchableSize ? CheckRangeExecutable(Address, FetchableSize) : 0; ++ if (ReadableSize != FetchableSize) { ++ HitNonExecutableRange = true; ++ } ++ HitInstructionLengthLimit = true; + Res = 0; ++ } else { ++ ReadableSize = CheckRangeExecutable(Address, Size); ++ if (ReadableSize == Size && !FEXCore::Utils::FaultSafeRead::Copy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size)) { ++ ReadableSize = 0; ++ } ++ if (ReadableSize != Size) { ++ HitNonExecutableRange = true; ++ Res = 0; ++ } + } + + // Skip the number of decoded bytes regardless to get instruction size. +@@ -870,7 +894,7 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstructionImpl(uint64_t PC) { + + for (;;) { + if (InstructionSize >= MAX_INST_SIZE) { +- return DecodedBlockStatus::INVALID_INST; ++ return DecodedBlockStatus::TOO_LONG_INST; + } + uint8_t Op = ReadByte(); + switch (Op) { +@@ -1097,11 +1121,12 @@ void Decoder::DecodeREXIfValid(int8_t ExpectedOffset) { + Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) { + // Will be set if DecodeInstructionImpl tries to read non-executable memory + HitNonExecutableRange = false; ++ HitInstructionLengthLimit = false; + HitBadRelocation = false; + HitBreakpoint = ~0U; + auto ErrorDuringDecoding = DecodeInstructionImpl(PC); + +- if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitBadRelocation) [[unlikely]] { ++ if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitInstructionLengthLimit || HitBadRelocation) [[unlikely]] { + // Put an invalid instruction in the stream so the core can raise SIGILL if hit + // Error while decoding instruction. We don't know the table or instruction size + DecodeInst->TableInfo = nullptr; +@@ -1123,6 +1148,10 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) { + return DecodedBlockStatus::BAD_RELOCATION; + } + ++ if (HitInstructionLengthLimit) { ++ return DecodedBlockStatus::TOO_LONG_INST; ++ } ++ + return ErrorDuringDecoding; + } else if (!DecodeInst->TableInfo || (DecodeInst->TableInfo->Type == TYPE_INST && !DecodeInst->TableInfo->OpcodeDispatcher.OpDispatch)) { + // If there wasn't an error during decoding but we have no dispatcher for the instruction then claim invalid instruction. +@@ -1682,6 +1711,7 @@ void Decoder::DecodeLoop(const uint8_t* _InstStream, uint64_t GuestSizePause) { + BlockIt->BlockStatus == DecodedBlockStatus::BREAKPOINT_3 ? "Breakpoint" : + BlockIt->BlockStatus == DecodedBlockStatus::INVALID_INST ? "Invalid" : + BlockIt->BlockStatus == DecodedBlockStatus::NOEXEC_INST ? "NoExec" : ++ BlockIt->BlockStatus == DecodedBlockStatus::TOO_LONG_INST ? "TooLong" : + BlockIt->BlockStatus == DecodedBlockStatus::BAD_RELOCATION ? "BadRelocation" : + BlockIt->BlockStatus == DecodedBlockStatus::UNIMPLEMENTED_INST ? "Unimplemented" : + "PartialDecode", +diff --git a/FEXCore/Source/Interface/Core/Frontend.h b/FEXCore/Source/Interface/Core/Frontend.h +index ade14bc44..6d279b22c 100644 +--- a/FEXCore/Source/Interface/Core/Frontend.h ++++ b/FEXCore/Source/Interface/Core/Frontend.h +@@ -28,6 +28,7 @@ public: + INVALID_INST, + NOEXEC_INST, + PARTIAL_DECODE_INST, ++ TOO_LONG_INST, + BAD_RELOCATION, + UNIMPLEMENTED_INST, + BREAKPOINT_0, +@@ -93,6 +94,8 @@ public: + ExecutableRangeBase = ExecutableRangeEnd = 0; + } + ++ uint64_t ExecutableRangeEpochSeen {}; ++ + private: + // To pass any information from instruction prefixes + // down into the actual instruction handling machinery. +@@ -159,6 +162,7 @@ private: + uint64_t ExecutableRangeEnd {}; + bool ExecutableRangeWritable {}; + bool HitNonExecutableRange {}; ++ bool HitInstructionLengthLimit {}; + bool HitBadRelocation {}; + uint32_t HitBreakpoint {~0U}; + +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index 09437a1ea..06890a8b5 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -195,6 +195,21 @@ DEF_OP(ExitFunction) { + ARMEmitter::ForwardLabel SkipFullLookup; + auto RipReg = GetReg(Op->NewRIP); + ++ if (Op->Hint == IR::BranchHint::CheckTF || CompilingWithTF) { ++ ARMEmitter::ForwardLabel TFUnset; ++ ldrb(TMP1, STATE_PTR(CpuStateFrame, State.flags[X86State::RFLAG_TF_RAW_LOC])); ++ (void)cbz(ARMEmitter::Size::i32Bit, TMP1, &TFUnset); ++ if (Op->Hint == IR::BranchHint::Return) { ++ add(ARMEmitter::Size::i64Bit, REG_CALLRET_SP, REG_CALLRET_SP, 0x10); ++ } else if (Op->Hint == IR::BranchHint::Call) { ++ stp(ARMEmitter::XReg::zr, ARMEmitter::XReg::zr, REG_CALLRET_SP, -0x10); ++ } ++ str(RipReg.X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); ++ ldr(TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.DispatcherLoopTop)); ++ br(TMP2); ++ (void)Bind(&TFUnset); ++ } ++ + if (Op->Hint == IR::BranchHint::Return) { + // First try to pop from the call-ret stack, otherwise follow the normal path (but ending in a ret) + ldp(TMP1, TMP2, REG_CALLRET_SP, 0x10); +diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp +index 435afed5e..459b0a6ce 100644 +--- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp +@@ -862,6 +862,7 @@ CPUBackend::CompiledCode Arm64JITCore::EmitJITCode(uint64_t Entry, uint64_t Size + this->DebugData = DebugData; + this->IR = IR; + RequiresFarARM64Jumps = false; ++ CompilingWithTF = CheckTF; + SSANodeMultiplier = 24; + + // Prepare restart via long jump in case branch encoding fails. +diff --git a/FEXCore/Source/Interface/Core/JIT/JITClass.h b/FEXCore/Source/Interface/Core/JIT/JITClass.h +index 980a83237..42d86b43f 100644 +--- a/FEXCore/Source/Interface/Core/JIT/JITClass.h ++++ b/FEXCore/Source/Interface/Core/JIT/JITClass.h +@@ -82,6 +82,7 @@ private: + // In the rare case when those assumptions are broken, FEX needs to safely restart the JIT. + RestartOptions RestartControl {}; + bool RequiresFarARM64Jumps {}; ++ bool CompilingWithTF {}; + // Default to 6 instructions per SSA node. + uint32_t SSANodeMultiplier {24}; + +diff --git a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp +index 137c99c60..8ea457ec1 100644 +--- a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp +@@ -107,6 +107,42 @@ DEF_OP(Break) { + } + } + ++DEF_OP(BreakErrorCode) { ++ auto Op = IROp->C(); ++ ++ uxth(ARMEmitter::Size::i64Bit, TMP2, GetReg(Op->ErrorCode)); ++ ResetStack(); ++ ++ Core::CpuStateFrame::SynchronousFaultDataStruct State = { ++ .FaultToTopAndGeneratedException = 1, ++ .Signal = Op->Reason.Signal, ++ .TrapNo = Op->Reason.TrapNumber, ++ .si_code = Op->Reason.si_code, ++ .err_code = 0, ++ .FaultAddress = 0, ++ }; ++ static_assert(offsetof(Core::CpuStateFrame::SynchronousFaultDataStruct, err_code) == 4, "err_code is bits 32-47"); ++ ++ uint64_t Constant {}; ++ memcpy(&Constant, &State, sizeof(uint64_t)); ++ ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, static_cast(Constant)); ++ bfi(ARMEmitter::Size::i64Bit, TMP1, TMP2, 32, 16); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData)); ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData) + 8); ++ ++ if (CTX->HostFeatures.ProcessFeatures.SupportsFaultFreeSynchronousFaults) { ++ ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SynchronousFault)); ++ } else { ++ switch (Op->Reason.Signal) { ++ case Core::FAULT_SIGILL: ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SIGILL)); break; ++ case Core::FAULT_SIGSEGV: ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SIGSEGV)); break; ++ default: ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SIGTRAP)); break; ++ } ++ } ++ br(TMP1); ++} ++ + DEF_OP(GetRoundingMode) { + auto Dst = GetReg(Node); + mrs(Dst, ARMEmitter::SystemRegister::FPCR); +diff --git a/FEXCore/Source/Interface/Core/LookupCache.h b/FEXCore/Source/Interface/Core/LookupCache.h +index 391d48560..228d03969 100644 +--- a/FEXCore/Source/Interface/Core/LookupCache.h ++++ b/FEXCore/Source/Interface/Core/LookupCache.h +@@ -125,7 +125,7 @@ struct GuestToHostMap { + return BlockList.erase(Address) != 0; + } + +- void InvalidateRange(uint64_t Start, uint64_t Length) { ++ bool InvalidateRange(uint64_t Start, uint64_t Length) { + auto lk = AcquireWriteLock(); + + auto lower = CodePages.lower_bound(Start >> 12); +@@ -136,7 +136,9 @@ struct GuestToHostMap { + Erase(Entry, lk); + } + } ++ const bool Found = lower != upper; + CodePages.erase(lower, upper); ++ return Found; + } + + void AddBlockLink(uint64_t GuestDestination, FEXCore::Context::ExitFunctionLinkData* HostLink, +@@ -144,6 +146,11 @@ struct GuestToHostMap { + BlockLinks->insert({{GuestDestination, HostLink}, delinker}); + } + ++ bool HasBlockExecutableRange(uint64_t Page, const LookupCacheReadLockToken&) const { ++ auto it = CodePages.find(Page >> 12); ++ return it != CodePages.end() && !it->second.empty(); ++ } ++ + bool AddBlockExecutableRange(const std::ranges::input_range auto& Addresses, uint64_t Start, uint64_t Length, const LookupCacheWriteLockToken&) { + bool rv = false; + +@@ -282,6 +289,11 @@ public: + + GuestToHostMap* Shared = nullptr; + ++ bool HasBlockExecutableRange(uint64_t Page) { ++ auto lk = Shared->AcquireReadLock(); ++ return Shared->HasBlockExecutableRange(Page, lk); ++ } ++ + // Appends a list of Block {Address} to CodePages [Start, Start + Length) + // Returns true if new pages are marked as containing code + bool AddBlockExecutableRange(FEXCore::Core::InternalThreadState* Thread, auto& Addresses, uint64_t Start, uint64_t Length) { +diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +index 1a0366398..40dd2b2e0 100644 +--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp ++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +@@ -138,6 +138,31 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) { + + const auto GPRSize = GetGPROpSize(); + ++ { ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ ++ auto CondJump_ = CondJump(GetRFLAG(FEXCore::X86State::RFLAG_NT_LOC), CondClass::EQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ ++ _StoreContextGPR(GPRSize, GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip)); ++ ++ IR::BreakDefinition Reason {}; ++ Reason.ErrorRegister = 0; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ Break(Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ } ++ + Ref SP = _RMWHandle(LoadGPRRegister(X86State::REG_RSP)); + + // RIP (64/32/16 bits) +@@ -164,7 +189,7 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) { + StoreGPRRegister(X86State::REG_RSP, SP); + } + +- ExitFunction(NewRIP); ++ ExitFunction(NewRIP, BranchHint::CheckTF); + BlockSetRIP = true; + } + +@@ -1230,6 +1255,36 @@ void OpDispatchBuilder::FLAGControlOp(OpcodeArgs) { + } + + ++void OpDispatchBuilder::MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset) { ++ Ref Index = _Bfe(OpSize::i32Bit, 13, 3, Selector); ++ Ref TI = _Bfe(OpSize::i32Bit, 1, 2, Selector); ++ Ref Allowed = _And(OpSize::i32Bit, _Lshr(OpSize::i32Bit, Constant(0x8071), Index), Constant(1)); ++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::ULT, Index, Constant(16), Allowed, Constant(0)); ++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::EQ, TI, Constant(0), Allowed, Constant(0)); ++ ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ auto CondJump_ = CondJump(Allowed, CondClass::NEQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ Ref FaultSelector = LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags); ++ _StoreContextGPR(GetGPROpSize(), GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip)); ++ IR::BreakDefinition Reason {}; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ BreakErrorCode(_And(OpSize::i32Bit, FaultSelector, Constant(0xfffc)), Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ _StoreContextGPR(OpSize::i16Bit, LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags), IndexOffset); ++ _StoreContextGPR(OpSize::i64Bit, Constant(0), BaseOffset); ++} ++ + void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + // In x86-64 mode the accesses to the segment registers end up being constant zero moves + // Aside from FS/GS +@@ -1243,7 +1298,6 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + // selected for the registers + // This statement is actually untrue, the instructions will /actually/ load 16bits in to the selector portion of the register! + // Tested on a Zen+ CPU, the selector is the portion that is modified! +- // We don't currently support FS/GS selector modifying, so this needs to be asserted out + // The loads here also load the selector, NOT the base + + if (ToSeg) { +@@ -1281,8 +1335,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, gs_idx)); + UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX); + } else { +- LogMan::Msg::EFmt("We don't support modifying GS selector in 64bit mode!"); +- DecodeFailure = true; ++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, gs_idx), offsetof(FEXCore::Core::CPUState, gs_cached)); + } + break; + case FEXCore::X86State::REG_RSP: // FS +@@ -1291,8 +1344,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, fs_idx)); + UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX); + } else { +- LogMan::Msg::EFmt("We don't support modifying FS selector in 64bit mode!"); +- DecodeFailure = true; ++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, fs_idx), offsetof(FEXCore::Core::CPUState, fs_cached)); + } + break; + default: UnimplementedOp(Op); return; +@@ -1319,19 +1371,11 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + break; + case FEXCore::X86State::REG_RBP: // GS + case FEXCore::X86State::REG_R13: // GS +- if (Is64BitMode) { +- Segment = Constant(0); +- } else { +- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx)); +- } ++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx)); + break; + case FEXCore::X86State::REG_RSP: // FS + case FEXCore::X86State::REG_R12: // FS +- if (Is64BitMode) { +- Segment = Constant(0); +- } else { +- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx)); +- } ++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx)); + break; + default: UnimplementedOp(Op); return; + } +@@ -1373,6 +1417,33 @@ void OpDispatchBuilder::CPUIDOp(OpcodeArgs) { + Ref Src = LoadGPRRegister(X86State::REG_RAX); + Ref Leaf = LoadGPRRegister(X86State::REG_RCX); + ++ if (CTX->Config.EnableCPUIDFaulting()) { ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ ++ auto Fault = _LoadContextGPR(OpSize::i32Bit, offsetof(FEXCore::Core::CpuStateFrame, CPUIDFault)); ++ auto CondJump_ = CondJump(Fault, CondClass::EQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ ++ auto NewRIP = GetRelocatedPC(Op, -Op->InstSize); ++ _StoreContextGPR(GetGPROpSize(), NewRIP, offsetof(FEXCore::Core::CPUState, rip)); ++ ++ IR::BreakDefinition Reason {}; ++ Reason.ErrorRegister = 0; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ Break(Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ } ++ + Ref RAX = _AllocateGPR(false); + Ref RBX = _AllocateGPR(false); + Ref RCX = _AllocateGPR(false); +diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +index 4477c7266..f6f65209a 100644 +--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h ++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +@@ -214,6 +214,10 @@ public: + } + return _Break(Reason, RelocatedPC); + } ++ IRPair BreakErrorCode(Ref ErrorCode, BreakDefinition Reason) { ++ FlushRegisterCache(); ++ return _BreakErrorCode(ErrorCode, Reason); ++ } + IRPair Thunk(Ref ArgPtr, SHA256Sum ThunkNameHash) { + FlushRegisterCache(); + return _Thunk(ArgPtr, ThunkNameHash); +@@ -415,6 +419,7 @@ public: + void XCHGRAXOp(OpcodeArgs); + void SAHFOp(OpcodeArgs); + void LAHFOp(OpcodeArgs); ++ void MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset); + void MOVSegOp(OpcodeArgs, bool ToSeg); + void FLAGControlOp(OpcodeArgs); + void MOVOffsetOp(OpcodeArgs); +@@ -1906,8 +1911,8 @@ private: + // An exception should still be raised after an instruction that unsets TF, leave the unblocked bit set but unset + // the TF bit to cause such behaviour. The handling code at the start of the next block will then unset the + // unblocked bit before raising the exception. +- auto NewPackedTF = +- _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), Constant(1)); ++ auto NewPackedTF = _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), ++ _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, PackedTF, Constant(3), Constant(3), Constant(1))); + _StoreContextGPR(OpSize::i8Bit, NewPackedTF, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset)); + } else { + _StoreContextGPR(OpSize::i8Bit, Value, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset)); +diff --git a/FEXCore/Source/Interface/IR/IR.json b/FEXCore/Source/Interface/IR/IR.json +index 16c29e759..34122804b 100644 +--- a/FEXCore/Source/Interface/IR/IR.json ++++ b/FEXCore/Source/Interface/IR/IR.json +@@ -324,6 +324,12 @@ + "Break BreakDefinition:$Reason, GPR:$FaultAddress": { + "HasSideEffects": true + }, ++ "BreakErrorCode GPR:$ErrorCode, BreakDefinition:$Reason": { ++ "HasSideEffects": true, ++ "Desc": ["Break whose fault error code is the low 16 bits of $ErrorCode, known only at run time", ++ "(a #GP with a selector as its error code); Reason.ErrorRegister is not used" ++ ] ++ }, + "CallbackReturn": { + "HasSideEffects": true + }, +diff --git a/FEXCore/Source/Interface/IR/IREmitter.cpp b/FEXCore/Source/Interface/IR/IREmitter.cpp +index f305ad3e8..40b02b33d 100644 +--- a/FEXCore/Source/Interface/IR/IREmitter.cpp ++++ b/FEXCore/Source/Interface/IR/IREmitter.cpp +@@ -22,7 +22,8 @@ static bool IsFragmentExit(FEXCore::IR::IROps Op) { + case OP_THREADREMOVECODEENTRY: + case OP_SYSCALL: + case OP_EXITFUNCTION: +- case OP_BREAK: return true; ++ case OP_BREAK: ++ case OP_BREAKERRORCODE: return true; + default: return false; + } + } +diff --git a/FEXCore/Source/Utils/FaultSafeRead.cpp b/FEXCore/Source/Utils/FaultSafeRead.cpp +new file mode 100644 +index 000000000..aaa7a80cf +--- /dev/null ++++ b/FEXCore/Source/Utils/FaultSafeRead.cpp +@@ -0,0 +1,46 @@ ++// SPDX-License-Identifier: MIT ++#include ++ ++#include ++ ++namespace FEXCore::Utils::FaultSafeRead { ++#if defined(ARCHITECTURE_arm64) && !defined(_WIN32) ++__attribute__((naked)) static size_t CopyImpl(void* Dest, const void* Src, size_t Size) { ++ __asm volatile(R"( ++ // Early exit if a copy of size zero. ++ cbz x2, 2f; ++ ++ 1: ++ .globl FEXCore_FaultSafeRead_FaultInst ++ FEXCore_FaultSafeRead_FaultInst: ++ ldrb w3, [x1], 1; // <- This line can fault. ++ strb w3, [x0], 1; ++ sub x2, x2, 1; ++ cbnz x2, 1b; ++2: ++ mov x0, 0; ++ ret; ++ )" :: ++ : "memory"); ++} ++ ++extern "C" uint64_t FEXCore_FaultSafeRead_FaultInst; ++ ++bool Copy(void* Dest, const void* Src, size_t Size) { ++ return CopyImpl(Dest, Src, Size) == 0; ++} ++ ++bool IsFaultLocation(uint64_t PC) { ++ return reinterpret_cast(PC) == &FEXCore_FaultSafeRead_FaultInst; ++} ++#else ++bool Copy(void* Dest, const void* Src, size_t Size) { ++ memcpy(Dest, Src, Size); ++ return true; ++} ++ ++bool IsFaultLocation(uint64_t PC) { ++ return false; ++} ++#endif ++} +diff --git a/FEXCore/include/FEXCore/Core/Context.h b/FEXCore/include/FEXCore/Core/Context.h +index 8aa448e2e..865d292fd 100644 +--- a/FEXCore/include/FEXCore/Core/Context.h ++++ b/FEXCore/include/FEXCore/Core/Context.h +@@ -140,9 +140,11 @@ public: + virtual void FlushAndCloseCodeMap() = 0; + + FEX_DEFAULT_VISIBILITY virtual void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) = 0; +- FEX_DEFAULT_VISIBILITY virtual void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0; ++ FEX_DEFAULT_VISIBILITY virtual void InvalidateExecutableRangeCaches() = 0; ++ ++ FEX_DEFAULT_VISIBILITY virtual bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0; + FEX_DEFAULT_VISIBILITY virtual void +- InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) = 0; ++ InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached = true) = 0; + FEX_DEFAULT_VISIBILITY virtual FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() = 0; + + FEX_DEFAULT_VISIBILITY virtual void +diff --git a/FEXCore/include/FEXCore/Core/CoreState.h b/FEXCore/include/FEXCore/Core/CoreState.h +index c1cb5f03c..deb3b7a69 100644 +--- a/FEXCore/include/FEXCore/Core/CoreState.h ++++ b/FEXCore/include/FEXCore/Core/CoreState.h +@@ -274,6 +274,11 @@ struct alignas(64) CPUState { + + // TODO: This should be moved to the frontend. + constexpr static uint32_t DEFAULT_USER_CS = 6; ++ constexpr static uint32_t DEFAULT_USER_DS = 5; ++ ++ constexpr static uint32_t DEFAULT_USER_CS_SEL = (DEFAULT_USER_CS << 3) | 3; ++ constexpr static uint32_t DEFAULT_USER_DS_SEL = (DEFAULT_USER_DS << 3) | 3; ++ constexpr static uint32_t DEFAULT_USER32_CS_SEL = 0x23; + + // Follows encoding of the TI bit in segment selector encoding. + constexpr static uint32_t SEGMENT_ARRAY_INDEX_GDT = 0; +@@ -463,6 +468,8 @@ struct CpuStateFrame { + + uint32_t SignalHandlerRefCounter {}; + ++ uint32_t CPUIDFault {}; ++ + InternalThreadState* Thread; + + #ifdef _WIN32 +diff --git a/FEXCore/include/FEXCore/HLE/SyscallHandler.h b/FEXCore/include/FEXCore/HLE/SyscallHandler.h +index 0ba0218e3..89e36d52e 100644 +--- a/FEXCore/include/FEXCore/HLE/SyscallHandler.h ++++ b/FEXCore/include/FEXCore/HLE/SyscallHandler.h +@@ -33,6 +33,10 @@ public: + virtual void HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) = 0; + + virtual void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {} ++ ++ virtual bool IsSMCHotPage(uint64_t Address) { ++ return false; ++ } + virtual void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {} + virtual void MarkOvercommitRange(uint64_t Start, uint64_t Length) {} + virtual void UnmarkOvercommitRange(uint64_t Start, uint64_t Length) {} +diff --git a/FEXCore/include/FEXCore/Utils/FaultSafeRead.h b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h +new file mode 100644 +index 000000000..1fc7213b5 +--- /dev/null ++++ b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h +@@ -0,0 +1,12 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++#include ++ ++#include ++#include ++ ++namespace FEXCore::Utils::FaultSafeRead { ++FEX_DEFAULT_VISIBILITY bool Copy(void* Dest, const void* Src, size_t Size); ++ ++FEX_DEFAULT_VISIBILITY bool IsFaultLocation(uint64_t PC); ++} +diff --git a/FEXCore/include/FEXCore/Utils/SHMStats.h b/FEXCore/include/FEXCore/Utils/SHMStats.h +index c5844fe10..d646c6a2f 100644 +--- a/FEXCore/include/FEXCore/Utils/SHMStats.h ++++ b/FEXCore/include/FEXCore/Utils/SHMStats.h +@@ -74,7 +74,10 @@ struct ThreadStats { + uint64_t AccumulatedDiskCacheHitCount; + uint64_t AccumulatedDiskCacheMissCount; + uint64_t AccumulatedDiskCacheLookupTime; +- uint64_t Padding; ++ ++ uint64_t AccumulatedInvalidationCount; ++ uint64_t AccumulatedInvalidationTime; ++ uint64_t AccumulatedCallRetFlushCount; + }; + + // Ensure 16-byte alignment to take advantage of ARM single-copy atomicity. +diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +index 1bc6ca92a..79f47aa2d 100644 +--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp ++++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +@@ -595,8 +595,7 @@ int main(int argc, char** argv, char** const envp) { + // Create a thread without a RIP or stack pointer setup initially. + auto ParentThread = SyscallHandler->TM.CreateThread(); + SyscallHandler->TM.TrackThread(ParentThread); +- SignalDelegation->RegisterTLSState(ParentThread); +- ThunkHandler->RegisterTLSState(ParentThread); ++ SyscallHandler->RegisterTLSState(ParentThread); + + SyscallHandler->DeserializeSeccompFD(ParentThread, FEXSeccompFD); + +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 2e724929f..980aec485 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -20,6 +20,7 @@ namespace FEX::ArchHelpers::Context { + + enum ContextFlags : uint32_t { + CONTEXT_FLAG_INJIT = (1U << 0), ++ CONTEXT_FLAG_SYSCALLINFO_CLEARED = (1U << 1), + }; + + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED +@@ -40,7 +41,11 @@ struct X86ContextBackup { + FEXCore::x86_64::_libc_fpstate FPRState; + uint64_t sa_mask; + uint16_t InSyscallInfo; ++ uint16_t ClearedSyscallInfo; + bool FaultToTopAndGeneratedException; ++ uint64_t GuestSignalMask; ++ uint64_t SeccompTrapRIP; ++ uint64_t SavedJITStackSP; + + // Guest state + int Signal; +@@ -72,7 +77,11 @@ struct ArmContextBackup { + __uint128_t FPRs[32]; + uint64_t sa_mask; + uint16_t InSyscallInfo; ++ uint16_t ClearedSyscallInfo; + bool FaultToTopAndGeneratedException; ++ uint64_t GuestSignalMask; ++ uint64_t SeccompTrapRIP; ++ uint64_t SavedJITStackSP; + + // Guest state + int Signal; +diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt +index 715a8f132..3f02104ea 100644 +--- a/Source/Tools/LinuxEmulation/CMakeLists.txt ++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt +@@ -10,6 +10,9 @@ add_library(LinuxEmulation STATIC + LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp + LinuxSyscalls/FaultSafeUserMemAccess.cpp + LinuxSyscalls/FileManagement.cpp ++ LinuxSyscalls/PtraceEmu.cpp ++ LinuxSyscalls/SamplingProfiler.cpp ++ LinuxSyscalls/SignalTrace.cpp + LinuxSyscalls/LinuxAllocator.cpp + LinuxSyscalls/Seccomp/SeccompEmulator.cpp + LinuxSyscalls/Seccomp/BPFEmitter.cpp +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 83e90c27e..1b2396b01 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -10,6 +10,7 @@ $end_info$ + + #include "Common/CPUInfo.h" + #include "Common/FDUtils.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" + +@@ -24,6 +25,8 @@ $end_info$ + + #include + ++#include ++#include + #include + #include + #include +@@ -592,6 +595,10 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + FDReadCreators[procAuxv] = &EmulatedFDManager::ProcAuxv; + FDReadCreators["/proc/self/auxv"] = &EmulatedFDManager::ProcAuxv; + ++ fextl::string procStatus = fextl::fmt::format("/proc/{}/status", getpid()); ++ FDReadCreators[procStatus] = &EmulatedFDManager::ProcStatus; ++ FDReadCreators["/proc/self/status"] = &EmulatedFDManager::ProcStatus; ++ + if (ThreadsConfig > 1) { + cpus_online = fextl::fmt::format("0-{}", ThreadsConfig - 1); + } else { +@@ -601,6 +608,20 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + + EmulatedFDManager::~EmulatedFDManager() {} + ++static bool IsProcMapsPath(const char* Path) { ++ if (strncmp(Path, "/proc/", 6) != 0) { ++ return false; ++ } ++ const char* P = Path + 6; ++ if (!isdigit(*P)) { ++ return strcmp(P, "self/maps") == 0; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ return strcmp(P, "/maps") == 0; ++} ++ + int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) { + auto Creator = FDReadCreators.end(); + if (pathname) { +@@ -608,12 +629,148 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + } + + if (Creator == FDReadCreators.end()) { ++ if (pathname && IsProcMapsPath(pathname)) { ++ return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode); ++ } + return -1; + } + + return Creator->second(CTX, AT_FDCWD, pathname, flags, mode); + } + ++int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC); ++ if (HostFD < 0) { ++ return -1; ++ } ++ fextl::string In; ++ char Buf[65536]; ++ for (;;) { ++ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf)); ++ if (Len > 0) { ++ In.append(Buf, Len); ++ } else if (Len == 0) { ++ break; ++ } else if (errno != EINTR) { ++ LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno); ++ ::close(HostFD); ++ return -1; ++ } ++ } ++ ::close(HostFD); ++ ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; ++ fextl::string Out; ++ Out.reserve(In.size()); ++ size_t Pos = 0; ++ while (Pos < In.size()) { ++ size_t Eol = In.find('\n', Pos); ++ const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1; ++ const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16); ++ if (Start < X86_64TaskSizeMax) { ++ Out.append(In, Pos, End - Pos); ++ } ++ Pos = End; ++ } ++ ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Out.size();) { ++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ ++int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ char Buf[8192]; ++ ssize_t Len = 0; ++ { ++ int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ if (HostFD >= 0) { ++ Len = ::read(HostFD, Buf, sizeof(Buf) - 1); ++ ::close(HostFD); ++ } ++ } ++ if (Len < 0) { ++ Len = 0; ++ } ++ Buf[Len] = '\0'; ++ ++ uint32_t SeccompMode = SECCOMP_MODE_DISABLED; ++ if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) { ++ SeccompMode = Thread->SeccompMode; ++ } ++ ++ fextl::string Out; ++ Out.reserve(Len + 64); ++ const char* Cursor = Buf; ++ while (*Cursor) { ++ const char* Eol = strchr(Cursor, '\n'); ++ const size_t LineLen = Eol ? static_cast(Eol - Cursor) + 1 : strlen(Cursor); ++ if (strncmp(Cursor, "Seccomp:", 8) == 0) { ++ Out += fextl::fmt::format("Seccomp:\t{}\n", SeccompMode); ++ } else if (strncmp(Cursor, "TracerPid:", 10) == 0) { ++ if (FEX::HLE::PtraceEmu::IsAttached()) { ++ Out.append(Cursor, LineLen); ++ } else { ++ Out += "TracerPid:\t0\n"; ++ } ++ } else { ++ Out.append(Cursor, LineLen); ++ if (!Eol) { ++ break; ++ } ++ } ++ if (!Eol) { ++ break; ++ } ++ Cursor = Eol + 1; ++ } ++ ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Out.size();) { ++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ + int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { + const auto [auxvBase, auxvSize] = FEX::HLE::_SyscallHandler->GetCodeLoader()->GetAuxv(); + if (auxvBase == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +index 854232341..b98ef4bda 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +@@ -34,6 +34,8 @@ private: + fextl::unordered_map FDReadCreators; + + static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + const uint32_t ThreadsConfig; + }; + } // namespace FEX::EmulatedFile +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp +index 6471e6483..7a7e068e2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp +@@ -1,6 +1,8 @@ + // SPDX-License-Identifier: MIT + #include "LinuxSyscalls/Syscalls.h" + ++#include ++ + namespace FEX::HLE::FaultSafeUserMemAccess { + #ifdef ARCHITECTURE_arm64 + __attribute__((naked)) size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { +@@ -41,6 +43,26 @@ __attribute__((naked)) size_t CopyToUser(void* Dest, const void* Src, size_t Siz + : "memory"); + } + ++__attribute__((naked)) static size_t StringReadableImpl(const char* Src) { ++ __asm volatile(R"( ++ 1: ++ .globl StringReadable_FaultInst ++ StringReadable_FaultInst: ++ ldrb w1, [x0], 1; // <- This line can fault. ++ cbnz w1, 1b; ++ mov x0, 0; ++ ret; ++ )" :: ++ : "memory"); ++} ++ ++bool IsStringReadable(const char* Src) { ++ return Src == nullptr || StringReadableImpl(Src) == 0; ++} ++ ++extern "C" uint64_t StringReadable_FaultInst; ++void* const StringReadable_FaultLocation = &StringReadable_FaultInst; ++ + extern "C" uint64_t CopyFromUser_FaultInst; + void* const CopyFromUser_FaultLocation = &CopyFromUser_FaultInst; + +@@ -157,6 +179,8 @@ bool IsFaultLocation(uint64_t PC) { + bool IsMemcpyFault = false; + IsMemcpyFault |= reinterpret_cast(PC) == CopyToUser_FaultLocation; + IsMemcpyFault |= reinterpret_cast(PC) == CopyFromUser_FaultLocation; ++ IsMemcpyFault |= reinterpret_cast(PC) == StringReadable_FaultLocation; ++ IsMemcpyFault |= FEXCore::Utils::FaultSafeRead::IsFaultLocation(PC); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + IsMemcpyFault |= reinterpret_cast(PC) == UserReadable_FaultLocation; + IsMemcpyFault |= reinterpret_cast(PC) == UserWritable_FaultLocation; +@@ -176,6 +200,10 @@ size_t CopyToUser(void* Dest, const void* Src, size_t Size) { + return Size; + } + ++bool IsStringReadable(const char* Src) { ++ return true; ++} ++ + bool IsFaultLocation(uint64_t PC) { + return false; + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +index 2210e4508..62b6a2d27 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +@@ -13,6 +13,7 @@ $end_info$ + #include "FEXCore/Config/Config.h" + #include "LinuxSyscalls/FileManagement.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + +@@ -954,6 +955,27 @@ uint64_t FileManager::FAccessat2(int dirfd, const char* pathname, int mode, int + return ::syscall(SYSCALL_DEF(faccessat2), dirfd, SelfPath, mode, flags); + } + ++static std::optional ReadlinkTraceeExe(const char* Path, char* Buf, size_t BufSize) { ++ if (!Path || strncmp(Path, "/proc/", 6) != 0) { ++ return std::nullopt; ++ } ++ char* End = nullptr; ++ const long Pid = strtol(Path + 6, &End, 10); ++ if (End == Path + 6 || strcmp(End, "/exe") != 0) { ++ return std::nullopt; ++ } ++ const auto Exe = PtraceEmu::TraceeExePath(static_cast(Pid)); ++ if (!Exe) { ++ return std::nullopt; ++ } ++ const size_t Len = std::min(BufSize, Exe->size()); ++ if (FaultSafeUserMemAccess::CopyToUser(Buf, Exe->data(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++} ++ + uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) { + // calculate the non-self link to exe + // Some executables do getpid, stat("/proc/$pid/exe") +@@ -962,8 +984,16 @@ uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) { + + if (strcmp(pathname, "/proc/self/exe") == 0 || strcmp(pathname, "/proc/thread-self/exe") == 0 || strcmp(pathname, PidSelfPath) == 0) { + const auto& App = Filename(); +- strncpy(buf, App.c_str(), bufsiz); +- return std::min(bufsiz, App.size()); ++ const size_t Len = std::min(bufsiz, App.size()); ++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++ } ++ ++ if (auto Traced = ReadlinkTraceeExe(pathname, buf, bufsiz)) { ++ return *Traced; + } + + FDPathTmpData TmpFilename; +@@ -1039,8 +1069,18 @@ uint64_t FileManager::Readlinkat(int dirfd, const char* pathname, char* buf, siz + + if (Path == "/proc/self/exe" || Path == "/proc/thread-self/exe" || Path == PidSelfPath) { + const auto& App = Filename(); +- strncpy(buf, App.c_str(), bufsiz); +- return std::min(bufsiz, App.size()); ++ const size_t Len = std::min(bufsiz, App.size()); ++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++ } ++ ++ if (!Path.empty() && Path[0] == '/') { ++ if (auto Traced = ReadlinkTraceeExe(Path.c_str(), buf, bufsiz)) { ++ return *Traced; ++ } + } + + FDPathTmpData TmpFilename; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp +index 7ae8236b3..3be10d097 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp +@@ -50,6 +50,7 @@ public: + + void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) override; + int Munmap(void* addr, size_t length) override; ++ void TrackUnmapped(void* addr, size_t length) override; + void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) override; + uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) override; + uint64_t Shmdt(const void* shmaddr) override; +@@ -333,6 +334,17 @@ int MemAllocator32Bit::Munmap(void* addr, size_t length) { + return 0; + } + ++void MemAllocator32Bit::TrackUnmapped(void* addr, size_t length) { ++ std::scoped_lock lk {AllocMutex}; ++ ++ const uint64_t Addr = reinterpret_cast(addr); ++ const uint64_t PageAddr = std::max(Addr >> FEXCore::Utils::FEX_PAGE_SHIFT, BASE_KEY); ++ const uint64_t PageEnd = std::min(FEXCore::AlignUp(Addr + length, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT, TOP_KEY); ++ if (PageAddr < PageEnd) { ++ SetFreePages(PageAddr, PageEnd - PageAddr); ++ } ++} ++ + void* MemAllocator32Bit::Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) { + size_t OldPagesLength = FEXCore::AlignUp(old_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT; + size_t NewPagesLength = FEXCore::AlignUp(new_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h +index dd6ae074f..c84f85b4a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h +@@ -14,6 +14,7 @@ public: + virtual ~MemAllocator() = default; + virtual void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) = 0; + virtual int Munmap(void* addr, size_t length) = 0; ++ virtual void TrackUnmapped(void* addr, size_t length) {} + virtual void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) = 0; + virtual uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) = 0; + virtual uint64_t Shmdt(const void* shmaddr) = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +new file mode 100644 +index 000000000..ca4c86063 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -0,0 +1,838 @@ ++// SPDX-License-Identifier: MIT ++ ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/Syscalls.h" ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::PtraceEmu { ++namespace { ++#ifndef NT_X86_XSTATE ++ constexpr uintptr_t NT_X86_XSTATE = 0x202; ++#endif ++ ++ enum UserReg : unsigned { ++ R15, R14, R13, R12, Rbp, Rbx, R11, R10, R9, R8, Rax, Rcx, Rdx, Rsi, Rdi, OrigRax, Rip, Cs, Eflags, Rsp, Ss, FsBase, GsBase, Ds, Es, Fs, Gs, ++ }; ++ static_assert(Gs + 1 == NumUserRegs); ++ ++ constexpr uintptr_t UserDebugRegByteOffset = 848; ++ constexpr uintptr_t UserDebugRegByteEnd = UserDebugRegByteOffset + 8 * sizeof(uint64_t); ++ constexpr uintptr_t UserStructSize = 928; ++ ++ constexpr uint64_t UserTaskSizeMax = 0x00007ffffffff000ULL; ++ ++ bool DrFieldValid(uint64_t Field, uint64_t* AlignMask) { ++ const uint64_t Len = Field & 0xC; ++ switch (Field & 0x3) { ++ case 0x0: ++ if (Len != 0x0) { ++ return false; ++ } ++ *AlignMask = 0; ++ return true; ++ case 0x1: ++ case 0x3: ++ switch (Len) { ++ case 0x0: *AlignMask = 0; return true; ++ case 0x4: *AlignMask = 1; return true; ++ case 0xC: *AlignMask = 3; return true; ++ case 0x8: *AlignMask = 7; return true; ++ default: return false; ++ } ++ default: ++ return false; ++ } ++ } ++ ++ constexpr unsigned DrEnableShift(unsigned N) { return N * 2; } ++ constexpr unsigned DrFieldShift(unsigned N) { return 16 + N * 4; } ++ ++ bool DrAddressValid(uint64_t Addr, uint64_t AlignMask) { ++ return Addr < UserTaskSizeMax && (Addr & AlignMask) == 0; ++ } ++ ++ bool Dr7Valid(const uint64_t Dr[8], uint64_t NewDr7) { ++ for (unsigned N = 0; N < 4; ++N) { ++ const bool Enabled = (NewDr7 >> DrEnableShift(N)) & 0x3; ++ const bool Registered = Dr[N] != 0; ++ if (!Enabled && !Registered) { ++ continue; ++ } ++ const uint64_t Field = (NewDr7 >> DrFieldShift(N)) & 0xF; ++ uint64_t AlignMask = 0; ++ if (!DrFieldValid(Field, &AlignMask) || !DrAddressValid(Dr[N], AlignMask)) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ constexpr uint16_t UserCodeSegment = 0x33; ++ constexpr uint16_t UserStackSegment = 0x2b; ++ constexpr uint64_t UserFlags = 0x246; ++ constexpr uint64_t NoOverride = ~0ULL; ++ ++ constexpr int X86_PTRACE_GETREGS = 12; ++ constexpr int X86_PTRACE_SETREGS = 13; ++ constexpr int X86_PTRACE_EVENT_EXEC = 4; ++ ++ SharedState StaticState {SharedState::MagicValue}; ++ SharedState* Current = &StaticState; ++ thread_local uint64_t PendingRip = 0; ++ ++ struct OpenSyscall { ++ bool Open = false; ++ uint64_t Nr {}; ++ uint64_t Args[6] {}; ++ } Previous; ++ ++ constexpr const char* SidecarDirs[] = {"/dev/shm", "/tmp"}; ++ ++ std::string SidecarPath(const char* Dir, const char* Kind, pid_t Pid) { ++ return std::string(Dir) + "/fex-ptrace-" + Kind + "-" + std::to_string(Pid); ++ } ++ ++ int OpenSidecar(const char* Kind, pid_t Pid, int Flags) { ++ for (const char* Dir : SidecarDirs) { ++ const int fd = ::open(SidecarPath(Dir, Kind, Pid).c_str(), Flags | O_CLOEXEC, 0600); ++ if (fd >= 0) { ++ return fd; ++ } ++ } ++ return -1; ++ } ++ ++ void RemoveSidecar(const char* Kind, pid_t Pid) { ++ for (const char* Dir : SidecarDirs) { ++ ::unlink(SidecarPath(Dir, Kind, Pid).c_str()); ++ } ++ } ++ ++ bool IsMainThread() { ++ return ::syscall(SYS_gettid) == ::getpid(); ++ } ++ ++ bool HasHostTracer() { ++ const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ if (fd < 0) { ++ return true; ++ } ++ char Buf[2048]; ++ const ssize_t n = ::read(fd, Buf, sizeof(Buf) - 1); ++ ::close(fd); ++ if (n <= 0) { ++ return true; ++ } ++ Buf[n] = 0; ++ const char* Tag = strstr(Buf, "TracerPid:"); ++ return !Tag || atoi(Tag + sizeof("TracerPid:") - 1) != 0; ++ } ++ ++ ++ void BuildRegs(const FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, bool Entry, uint64_t Ret, uint64_t* X) { ++ using namespace FEXCore::X86State; ++ const auto& S = Frame->State; ++ X[R15] = S.gregs[REG_R15]; ++ X[R14] = S.gregs[REG_R14]; ++ X[R13] = S.gregs[REG_R13]; ++ X[R12] = S.gregs[REG_R12]; ++ X[Rbp] = S.gregs[REG_RBP]; ++ X[Rbx] = S.gregs[REG_RBX]; ++ X[R11] = UserFlags; ++ X[R10] = S.gregs[REG_R10]; ++ X[R9] = S.gregs[REG_R9]; ++ X[R8] = S.gregs[REG_R8]; ++ X[Rax] = Entry ? static_cast(-ENOSYS) : Ret; ++ X[Rcx] = S.gregs[REG_RCX]; ++ X[Rdx] = S.gregs[REG_RDX]; ++ X[Rsi] = S.gregs[REG_RSI]; ++ X[Rdi] = S.gregs[REG_RDI]; ++ X[OrigRax] = Nr; ++ X[Rip] = S.gregs[REG_RCX] ? S.gregs[REG_RCX] : S.rip; ++ X[Cs] = UserCodeSegment; ++ X[Eflags] = UserFlags; ++ X[Rsp] = S.gregs[REG_RSP]; ++ X[Ss] = UserStackSegment; ++ X[FsBase] = S.fs_cached; ++ X[GsBase] = S.gs_cached; ++ X[Ds] = X[Es] = X[Fs] = X[Gs] = 0; ++ } ++ ++ void Stop(uint64_t Nr, const uint64_t Args[6], bool Entry, uint64_t Ret, const uint64_t* Regs) { ++ SharedState& S = *Current; ++ if (!HasHostTracer()) { ++ S.SyscallStops = 0; ++ S.Attached = 0; ++ return; ++ } ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ S.Regs[i] = Regs[i]; ++ } ++ S.PendingNr = Nr; ++ for (unsigned i = 0; i < 6; ++i) { ++ S.PendingArgs[i] = Args[i]; ++ } ++ S.PendingRet = Ret; ++ S.PendingIsEntry = Entry ? 1 : 0; ++ S.Pending = 1; ++ ::syscall(SYS_tgkill, ::getpid(), ::syscall(SYS_gettid), SIGSTOP); ++ S.Pending = 0; ++ } ++ ++ uint64_t ApplyTracerWrites(FEXCore::Core::CpuStateFrame* Frame, bool Entry) { ++ using namespace FEXCore::X86State; ++ SharedState& S = *Current; ++ ++ if (S.FlushLen) { ++ const uint64_t Addr = S.FlushAddr; ++ const uint64_t Len = S.FlushLen; ++ S.FlushLen = 0; ++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len); ++ } ++ ++ const uint64_t Dirty = S.DirtyMask; ++ if (!Dirty) { ++ return NoOverride; ++ } ++ ++ static constexpr int Map[15] = {REG_R15, REG_R14, REG_R13, REG_R12, REG_RBP, REG_RBX, -1, REG_R10, REG_R9, REG_R8, -1, REG_RCX, REG_RDX, REG_RSI, REG_RDI}; ++ auto& State = Frame->State; ++ uint64_t Override = NoOverride; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!(Dirty & (1ULL << i))) { ++ continue; ++ } ++ const uint64_t V = S.Regs[i]; ++ if (i < 15) { ++ if (Map[i] >= 0) { ++ State.gregs[Map[i]] = V; ++ } ++ } else if (i == Rip) { ++ PendingRip = V; ++ } else if (i == Rsp) { ++ State.gregs[REG_RSP] = V; ++ } else if (i == FsBase) { ++ State.fs_cached = V; ++ } else if (i == GsBase) { ++ State.gs_cached = V; ++ } ++ if (i == Rax && !Entry) { ++ Override = V; ++ } ++ } ++ if (Entry && (Dirty & (1ULL << OrigRax))) { ++ State.gregs[REG_RAX] = S.Regs[OrigRax]; ++ } ++ S.DirtyMask = 0; ++ return Override; ++ } ++ ++ void PublishSharedPage() { ++ if (Current != &StaticState) { ++ return; ++ } ++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR | O_CREAT | O_TRUNC); ++ if (fd < 0) { ++ return; ++ } ++ if (::ftruncate(fd, 4096) == 0) { ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ if (Page != MAP_FAILED) { ++ std::memcpy(Page, &StaticState, sizeof(SharedState)); ++ Current = static_cast(Page); ++ } ++ } ++ ::close(fd); ++ } ++ ++ struct Remote { ++ uint8_t* Mapped = nullptr; ++ uintptr_t StaticAddr = 0; ++ std::array FpRegs {}; ++ bool FpValid = false; ++ std::array XState {}; ++ bool XStateValid = false; ++ }; ++ std::mutex RemotesLock; ++ std::unordered_map Remotes; ++ std::unordered_map ExePaths; ++ ++ uintptr_t FindFexImageBase(pid_t Pid) { ++ static const std::string SelfExe = []() { ++ char Buf[512]; ++ const ssize_t n = ::readlink("/proc/self/exe", Buf, sizeof(Buf) - 1); ++ return n > 0 ? std::string(Buf, n) : std::string(); ++ }(); ++ if (SelfExe.empty()) { ++ return 0; ++ } ++ const std::string Maps = Pid ? "/proc/" + std::to_string(Pid) + "/maps" : "/proc/self/maps"; ++ FILE* F = fopen(Maps.c_str(), "r"); ++ if (!F) { ++ return 0; ++ } ++ char Line[1024]; ++ uintptr_t Lowest = 0; ++ while (fgets(Line, sizeof(Line), F)) { ++ if (!strstr(Line, SelfExe.c_str())) { ++ continue; ++ } ++ unsigned long long Start = 0, End = 0, Offset = 0; ++ if (sscanf(Line, "%llx-%llx %*s %llx", &Start, &End, &Offset) == 3 && Offset == 0 && (!Lowest || Start < Lowest)) { ++ Lowest = Start; ++ } ++ } ++ fclose(F); ++ return Lowest; ++ } ++ ++ Remote* Lookup(pid_t Pid) { ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ return &It->second; ++ } ++ Remote R; ++ const int fd = OpenSidecar("state", Pid, O_RDWR); ++ if (fd >= 0) { ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ ::close(fd); ++ if (Page != MAP_FAILED) { ++ R.Mapped = static_cast(Page); ++ } ++ } ++ if (!R.Mapped) { ++ static const uintptr_t SelfBase = FindFexImageBase(0); ++ const uintptr_t TraceeBase = FindFexImageBase(Pid); ++ if (!SelfBase || !TraceeBase) { ++ return nullptr; ++ } ++ R.StaticAddr = TraceeBase + (reinterpret_cast(&StaticState) - SelfBase); ++ } ++ return &Remotes.emplace(Pid, std::move(R)).first->second; ++ } ++ ++ void Forget(pid_t Pid, bool Exited) { ++ std::lock_guard lk(RemotesLock); ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ if (It->second.Mapped) { ++ ::munmap(It->second.Mapped, 4096); ++ } ++ Remotes.erase(It); ++ } ++ RemoveSidecar("state", Pid); ++ if (Exited) { ++ ExePaths.erase(Pid); ++ } ++ } ++ ++ void CaptureExecPath(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && R->Mapped) { ++ auto* S = reinterpret_cast(R->Mapped); ++ if (S->Magic == SharedState::MagicValue && S->ExePath[0]) { ++ ExePaths[Pid] = std::string(S->ExePath, strnlen(S->ExePath, sizeof(S->ExePath))); ++ } ++ } ++ } ++ ++ uint64_t HostPtrace(int Request, pid_t Pid, void* Addr, void* Data) { ++ const long R = ::syscall(SYS_ptrace, Request, Pid, Addr, Data); ++ return R == -1 ? static_cast(-errno) : static_cast(R); ++ } ++ ++ bool ReadWord(pid_t Pid, size_t Offset, uint64_t* Out) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (!R) { ++ return false; ++ } ++ if (R->Mapped) { ++ *Out = *reinterpret_cast(R->Mapped + Offset); ++ return true; ++ } ++ return ::syscall(SYS_ptrace, PTRACE_PEEKDATA, Pid, R->StaticAddr + Offset, Out) == 0; ++ } ++ ++ bool WriteWord(pid_t Pid, size_t Offset, uint64_t Value) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (!R) { ++ return false; ++ } ++ if (R->Mapped) { ++ *reinterpret_cast(R->Mapped + Offset) = Value; ++ return true; ++ } ++ return ::syscall(SYS_ptrace, PTRACE_POKEDATA, Pid, R->StaticAddr + Offset, Value) == 0; ++ } ++ ++ bool IsFexTracee(pid_t Pid) { ++ uint64_t Magic = 0; ++ return ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue; ++ } ++ ++ bool ReadSlot(pid_t Pid, size_t Offset, uint64_t* Out) { ++ return ReadWord(Pid, Offset, Out); ++ } ++ ++ void MarkDirty(pid_t Pid, uint64_t Mask) { ++ uint64_t Dirty = 0; ++ ReadWord(Pid, offsetof(SharedState, DirtyMask), &Dirty); ++ WriteWord(Pid, offsetof(SharedState, DirtyMask), Dirty | Mask); ++ } ++ ++ constexpr size_t RegOffset(unsigned Index) { ++ return offsetof(SharedState, Regs) + Index * sizeof(uint64_t); ++ } ++ ++ bool ReadDebugReg(pid_t Pid, unsigned N, uint64_t* Out) { ++ if (N == 4 || N == 5) { ++ *Out = 0; ++ return true; ++ } ++ if (N > 7) { ++ return false; ++ } ++ return ReadWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Out); ++ } ++ ++ int WriteDebugReg(pid_t Pid, unsigned N, uint64_t Value) { ++ if (N == 4 || N == 5) { ++ return -EIO; ++ } ++ if (N <= 3) { ++ if (!DrAddressValid(Value, 0)) { ++ return -EINVAL; ++ } ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ if (N == 6) { ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 6 * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ uint64_t Dr[8] {}; ++ for (unsigned I = 0; I < 8; ++I) { ++ if (!ReadWord(Pid, offsetof(SharedState, DebugRegs) + I * sizeof(uint64_t), &Dr[I])) { ++ return -ESRCH; ++ } ++ } ++ if (!Dr7Valid(Dr, Value)) { ++ return -EINVAL; ++ } ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 7 * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ ++ Remote* XStateState(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && !R->XStateValid) { ++ R->XStateValid = true; ++ } ++ return R; ++ } ++ ++ Remote* FpState(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && !R->FpValid) { ++ const uint16_t Fcw = 0x37f; ++ const uint32_t Mxcsr = 0x1f80, MxcsrMask = 0xffff; ++ std::memcpy(&R->FpRegs[0], &Fcw, sizeof(Fcw)); ++ std::memcpy(&R->FpRegs[24], &Mxcsr, sizeof(Mxcsr)); ++ std::memcpy(&R->FpRegs[28], &MxcsrMask, sizeof(MxcsrMask)); ++ R->FpValid = true; ++ } ++ return R; ++ } ++} ++ ++ ++bool IsAttached() { ++ return Current->Attached != 0; ++} ++ ++bool WantsSyscallStops() { ++ return Current->SyscallStops && IsMainThread(); ++} ++ ++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]) { ++ uint64_t Regs[NumUserRegs]; ++ if (Previous.Open) { ++ BuildRegs(Frame, Previous.Nr, false, 0, Regs); ++ Stop(Previous.Nr, Previous.Args, false, 0, Regs); ++ } ++ BuildRegs(Frame, Nr, true, 0, Regs); ++ Stop(Nr, Args, true, 0, Regs); ++ ApplyTracerWrites(Frame, true); ++ ++ const uint64_t NewNr = Frame->State.gregs[FEXCore::X86State::REG_RAX]; ++ Previous.Open = Current->SyscallStops != 0; ++ Previous.Nr = NewNr; ++ std::copy(Args, Args + 6, Previous.Args); ++ return NewNr; ++} ++ ++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result) { ++ uint64_t Regs[NumUserRegs]; ++ BuildRegs(Frame, Nr, false, Result, Regs); ++ Stop(Nr, Args, false, Result, Regs); ++ const uint64_t Override = ApplyTracerWrites(Frame, false); ++ Previous.Open = false; ++ return Override != NoOverride ? Override : Result; ++} ++ ++void OnForkedChild(bool SharesAddressSpace) { ++ if (SharesAddressSpace) { ++ return; ++ } ++ Current = &StaticState; ++ StaticState.SyscallStops = 0; ++ StaticState.Attached = 0; ++ StaticState.Pending = 0; ++ Previous.Open = false; ++} ++ ++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame) { ++ SharedState& S = *Current; ++ if (S.FlushLen) { ++ const uint64_t Addr = S.FlushAddr; ++ const uint64_t Len = S.FlushLen; ++ S.FlushLen = 0; ++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len); ++ } ++} ++ ++uint64_t TakePendingRip() { ++ const uint64_t Rip = PendingRip; ++ PendingRip = 0; ++ return Rip; ++} ++ ++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal) { ++ if (Signal != SIGTRAP && Signal != SIGSEGV) { ++ return false; ++ } ++ if (!Frame->SynchronousFaultData.FaultToTopAndGeneratedException || !Current->Attached || !IsMainThread()) { ++ return false; ++ } ++ ++ uint64_t Regs[NumUserRegs]; ++ const uint64_t NoArgs[6] {}; ++ BuildRegs(Frame, ~0ULL, false, Frame->State.gregs[FEXCore::X86State::REG_RAX], Regs); ++ Regs[Rip] = Frame->State.rip; ++ ++ Current->SignalNumber = static_cast(Signal); ++ Stop(~0ULL, NoArgs, false, 0, Regs); ++ Current->SignalNumber = 0; ++ ++ const uint64_t Override = ApplyTracerWrites(Frame, false); ++ if (Override != NoOverride) { ++ Frame->State.gregs[FEXCore::X86State::REG_RAX] = Override; ++ } ++ if (const uint64_t NewRip = TakePendingRip()) { ++ Frame->State.rip = NewRip; ++ } ++ return true; ++} ++ ++void RecordExecPath(const std::string& GuestPath) { ++ if (!Current->Attached) { ++ return; ++ } ++ const size_t Len = std::min(GuestPath.size(), sizeof(Current->ExePath) - 1); ++ std::memcpy(Current->ExePath, GuestPath.data(), Len); ++ Current->ExePath[Len] = 0; ++} ++ ++ ++std::optional TraceeExePath(pid_t Pid) { ++ if (Pid <= 0 || Pid == ::getpid()) { ++ return std::nullopt; ++ } ++ std::lock_guard lk(RemotesLock); ++ auto It = ExePaths.find(Pid); ++ return It != ExePaths.end() ? std::optional(It->second) : std::nullopt; ++} ++ ++bool FixupWaitStatus(pid_t Pid, int* Status) { ++ if (!Status || Pid <= 0) { ++ return false; ++ } ++ const int St = *Status; ++ ++ if (WIFEXITED(St) || WIFSIGNALED(St)) { ++ Forget(Pid, true); ++ return false; ++ } ++ if (!WIFSTOPPED(St)) { ++ return false; ++ } ++ ++ if ((St >> 16) == 0 && (WSTOPSIG(St) == SIGTRAP || WSTOPSIG(St) == SIGSEGV) && IsFexTracee(Pid)) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(WSTOPSIG(St)))); ++ return true; ++ } ++ ++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGBUS && IsFexTracee(Pid)) { ++ siginfo_t Info {}; ++ if (HostPtrace(PTRACE_GETSIGINFO, Pid, nullptr, &Info) == 0 && Info.si_code == BUS_ADRALN) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(SIGBUS))); ++ return true; ++ } ++ } ++ ++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGPROF && IsFexTracee(Pid)) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, nullptr); ++ return true; ++ } ++ ++ if ((St >> 16) == X86_PTRACE_EVENT_EXEC) { ++ CaptureExecPath(Pid); ++ Forget(Pid, false); ++ } ++ ++ if (WSTOPSIG(St) == SIGSTOP) { ++ uint64_t Pending = 0; ++ if (ReadWord(Pid, offsetof(SharedState, Pending), &Pending) && Pending) { ++ uint64_t Signal = 0; ++ ReadWord(Pid, offsetof(SharedState, SignalNumber), &Signal); ++ *Status = (St & ~0xff00) | (static_cast(Signal ? Signal : (SIGTRAP | 0x80)) << 8); ++ } ++ } ++ return false; ++} ++ ++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result) { ++ switch (Request) { ++ case PTRACE_TRACEME: ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ if (*Result == 0) { ++ PublishSharedPage(); ++ Current->Attached = 1; ++ } ++ return true; ++ ++ case PTRACE_KILL: ++ case PTRACE_SEIZE: ++ case PTRACE_INTERRUPT: ++ case PTRACE_SETOPTIONS: ++ case PTRACE_GETEVENTMSG: ++ case PTRACE_SINGLESTEP: ++ case PTRACE_GETSIGINFO: *Result = HostPtrace(Request, Pid, Addr, Data); return true; ++ ++ case PTRACE_POKETEXT: ++ case PTRACE_POKEDATA: { ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ if (*Result == 0 && IsFexTracee(Pid)) { ++ const uint64_t Lo = reinterpret_cast(Addr) & ~0xfffULL; ++ const uint64_t Hi = Lo + 0x2000; ++ uint64_t OldAddr = 0, OldLen = 0; ++ ReadWord(Pid, offsetof(SharedState, FlushAddr), &OldAddr); ++ ReadWord(Pid, offsetof(SharedState, FlushLen), &OldLen); ++ uint64_t NewLo = Lo, NewHi = Hi; ++ if (OldLen) { ++ NewLo = std::min(OldAddr, Lo); ++ NewHi = std::max(OldAddr + OldLen, Hi); ++ } ++ WriteWord(Pid, offsetof(SharedState, FlushAddr), NewLo); ++ WriteWord(Pid, offsetof(SharedState, FlushLen), NewHi - NewLo); ++ } ++ return true; ++ } ++ ++ case PTRACE_CONT: ++ case PTRACE_SYSCALL: { ++ uint64_t Magic = 0; ++ if (ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue) { ++ WriteWord(Pid, offsetof(SharedState, SyscallStops), Request == PTRACE_SYSCALL ? 1 : 0); ++ WriteWord(Pid, offsetof(SharedState, Attached), 1); ++ } ++ *Result = HostPtrace(PTRACE_CONT, Pid, Addr, Data); ++ return true; ++ } ++ ++ case PTRACE_DETACH: { ++ if (IsFexTracee(Pid)) { ++ WriteWord(Pid, offsetof(SharedState, SyscallStops), 0); ++ WriteWord(Pid, offsetof(SharedState, Attached), 0); ++ } ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ Forget(Pid, false); ++ return true; ++ } ++ ++ case PTRACE_PEEKUSER: { ++ const uintptr_t Off = reinterpret_cast(Addr); ++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) { ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ uint64_t V = 0; ++ if (Off < NumUserRegs * sizeof(uint64_t)) { ++ if (!ReadSlot(Pid, RegOffset(Off / 8), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } else if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) { ++ if (!ReadDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } ++ *static_cast(Data) = V; ++ *Result = 0; ++ return true; ++ } ++ ++ case PTRACE_POKEUSER: { ++ const uintptr_t Off = reinterpret_cast(Addr); ++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) { ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ if (Off < NumUserRegs * sizeof(uint64_t)) { ++ if (!WriteWord(Pid, RegOffset(Off / 8), reinterpret_cast(Data))) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ MarkDirty(Pid, 1ULL << (Off / 8)); ++ *Result = 0; ++ return true; ++ } ++ if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) { ++ *Result = static_cast(WriteDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), reinterpret_cast(Data))); ++ return true; ++ } ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ ++ case X86_PTRACE_GETREGS: { ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ uint64_t V = 0; ++ if (!ReadSlot(Pid, RegOffset(i), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ static_cast(Data)[i] = V; ++ } ++ *Result = 0; ++ return true; ++ } ++ ++ case X86_PTRACE_SETREGS: { ++ uint64_t Mask = 0; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!WriteWord(Pid, RegOffset(i), static_cast(Data)[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ Mask |= 1ULL << i; ++ } ++ MarkDirty(Pid, Mask); ++ *Result = 0; ++ return true; ++ } ++ ++ case PTRACE_GETREGSET: ++ case PTRACE_SETREGSET: { ++ const auto NtType = reinterpret_cast(Addr); ++ auto* Iov = static_cast(Data); ++ if (!Iov) { ++ return false; ++ } ++ const bool Get = Request == PTRACE_GETREGSET; ++ ++ if (NtType == NT_PRSTATUS) { ++ if (Get) { ++ uint64_t Image[NumUserRegs]; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!ReadSlot(Pid, RegOffset(i), &Image[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } ++ const size_t Len = std::min(Iov->iov_len, sizeof(Image)); ++ std::memcpy(Iov->iov_base, Image, Len); ++ Iov->iov_len = Len; ++ } else { ++ const size_t Slots = std::min(Iov->iov_len / sizeof(uint64_t), NumUserRegs); ++ uint64_t Mask = 0; ++ for (size_t i = 0; i < Slots; ++i) { ++ if (!WriteWord(Pid, RegOffset(i), static_cast(Iov->iov_base)[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ Mask |= 1ULL << i; ++ } ++ MarkDirty(Pid, Mask); ++ Iov->iov_len = NumUserRegs * sizeof(uint64_t); ++ } ++ *Result = 0; ++ return true; ++ } ++ ++ if (NtType == NT_PRFPREG) { ++ Remote* R = FpState(Pid); ++ if (!R) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ const size_t Len = std::min(Iov->iov_len, R->FpRegs.size()); ++ if (Get) { ++ std::memcpy(Iov->iov_base, R->FpRegs.data(), Len); ++ } else { ++ std::memcpy(R->FpRegs.data(), Iov->iov_base, Len); ++ } ++ Iov->iov_len = Len; ++ *Result = 0; ++ return true; ++ } ++ ++ if (NtType == NT_X86_XSTATE) { ++ Remote* R = XStateState(Pid); ++ if (!R) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ const size_t Len = std::min(Iov->iov_len, R->XState.size()); ++ if (Get) { ++ std::memcpy(Iov->iov_base, R->XState.data(), Len); ++ } else { ++ std::memcpy(R->XState.data(), Iov->iov_base, Len); ++ } ++ Iov->iov_len = Len; ++ *Result = 0; ++ return true; ++ } ++ ++ *Result = static_cast(-EINVAL); ++ return true; ++ } ++ ++ default: return false; ++ } ++} ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h +new file mode 100644 +index 000000000..59194979a +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h +@@ -0,0 +1,63 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++#include ++#include ++ ++namespace FEXCore::Core { ++struct CpuStateFrame; ++} ++ ++namespace FEX::HLE::PtraceEmu { ++ ++constexpr unsigned NumUserRegs = 27; ++ ++struct SharedState { ++ static constexpr uint64_t MagicValue = 0xFE8E5E57CAFE0001ULL; ++ ++ volatile uint64_t Magic; ++ volatile uint64_t SyscallStops; ++ volatile uint64_t Attached; ++ volatile uint64_t Pending; ++ volatile uint64_t PendingIsEntry; ++ volatile uint64_t PendingNr; ++ volatile uint64_t PendingArgs[6]; ++ volatile uint64_t PendingRet; ++ volatile uint64_t Regs[NumUserRegs]; ++ volatile uint64_t DebugRegs[8]; ++ volatile uint64_t DirtyMask; ++ volatile uint64_t SignalNumber; ++ volatile uint64_t FlushAddr; ++ volatile uint64_t FlushLen; ++ char ExePath[1024]; ++}; ++ ++ ++bool WantsSyscallStops(); ++ ++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]); ++ ++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result); ++ ++void OnForkedChild(bool SharesAddressSpace); ++ ++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame); ++ ++uint64_t TakePendingRip(); ++ ++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal); ++ ++void RecordExecPath(const std::string& GuestPath); ++ ++bool IsAttached(); ++ ++ ++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result); ++ ++bool FixupWaitStatus(pid_t Pid, int* Status); ++ ++std::optional TraceeExePath(pid_t Pid); ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h +new file mode 100644 +index 000000000..3f36e79fd +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h +@@ -0,0 +1,90 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE { ++ ++class SMCHotPageTracker final { ++public: ++ static constexpr uint64_t PageShift = 12; ++ ++ bool RecordFault(uint64_t Address, uint32_t FaultThreshold) { ++ if (!FaultThreshold) { ++ return false; ++ } ++ const uint64_t Page = Address >> PageShift; ++ auto& Slot = Counters[Hash(Page) & (CounterSlots - 1)]; ++ ++ uint64_t Old = Slot.load(std::memory_order_relaxed); ++ uint64_t New; ++ do { ++ const uint64_t Count = (Old >> CountBits) == Page ? (Old & CountMask) + 1 : 1; ++ New = (Page << CountBits) | (Count < CountMask ? Count : CountMask); ++ } while (!Slot.compare_exchange_weak(Old, New, std::memory_order_relaxed)); ++ ++ return (New & CountMask) == FaultThreshold && MakeHot(Page); ++ } ++ ++ bool MarkHot(uint64_t Address) { ++ return MakeHot(Address >> PageShift); ++ } ++ ++ bool IsHot(uint64_t Address) const { ++ if (HotCount.load(std::memory_order_relaxed) == 0) { ++ return false; ++ } ++ ++ const uint64_t Key = (Address >> PageShift) + 1; ++ for (size_t i = 0, Idx = Hash(Key - 1); i < HotSlots; ++i, ++Idx) { ++ const uint64_t Entry = Hot[Idx & (HotSlots - 1)].load(std::memory_order_relaxed); ++ if (Entry == Key) { ++ return true; ++ } ++ if (Entry == 0) { ++ return false; ++ } ++ } ++ return false; ++ } ++ ++private: ++ static constexpr size_t CounterSlots = 4096; ++ static constexpr size_t HotSlots = 2048; ++ static constexpr unsigned CountBits = 20; ++ static constexpr uint64_t CountMask = (1ULL << CountBits) - 1; ++ static_assert((CounterSlots & (CounterSlots - 1)) == 0 && (HotSlots & (HotSlots - 1)) == 0); ++ ++ static size_t Hash(uint64_t Page) { ++ return static_cast((Page * 0x9E3779B97F4A7C15ULL) >> 40); ++ } ++ ++ bool MakeHot(uint64_t Page) { ++ if (HotCount.load(std::memory_order_relaxed) >= HotSlots / 4 * 3) { ++ return false; ++ } ++ ++ const uint64_t Key = Page + 1; ++ for (size_t i = 0, Idx = Hash(Page); i < HotSlots; ++i, ++Idx) { ++ auto& Entry = Hot[Idx & (HotSlots - 1)]; ++ uint64_t Expected = 0; ++ if (Entry.compare_exchange_strong(Expected, Key, std::memory_order_relaxed)) { ++ HotCount.fetch_add(1, std::memory_order_relaxed); ++ return true; ++ } ++ if (Expected == Key) { ++ return false; ++ } ++ } ++ return false; ++ } ++ ++ std::array, CounterSlots> Counters {}; ++ std::array, HotSlots> Hot {}; ++ std::atomic HotCount {}; ++}; ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp +new file mode 100644 +index 000000000..abc3284a3 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp +@@ -0,0 +1,278 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SamplingProfiler.h" ++#include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "ArchHelpers/MContext.h" ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE { ++namespace { ++ struct Sample { ++ uint64_t HostPC; ++ uint64_t Info; ++ }; ++ constexpr size_t MaxSamples = 1 << 18; ++ std::atomic RecordsPtr {nullptr}; ++ Sample* Records = nullptr; ++ std::atomic Count {0}; ++ ++ struct SnapRecord { ++ uint64_t Tid; ++ uint64_t HostPC; ++ uint64_t Rip; ++ uint64_t FutexWord; ++ uint64_t FutexExpected; ++ uint64_t FutexAddr; ++ uint64_t Gregs[16]; ++ uint64_t Stack[138]; ++ }; ++ static_assert(sizeof(SnapRecord) == 160 * 8); ++ constexpr size_t MaxSnaps = 1024; ++ SnapRecord* Snaps = nullptr; ++ std::atomic SnapCount {0}; ++ std::atomic SnapMode {false}; ++ bool ExternalMode = false; ++ FEX::HLE::SignalDelegator* Delegator = nullptr; ++ std::atomic ExternalOpen {false}; ++ ++ void OpenExternalSnaps() { ++ if (ExternalOpen.exchange(true)) { ++ return; ++ } ++ char Path[64]; ++ snprintf(Path, sizeof(Path), "/dev/shm/fex-%d-snap", static_cast(getpid())); ++ const int fd = open(Path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) { ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Snaps = static_cast(Map); ++ } ++ } ++ ++ bool IsInteresting(pid_t Tid) { ++ static thread_local std::unordered_map Last; ++ char Path[64]; ++ snprintf(Path, sizeof(Path), "/proc/self/task/%d/stat", Tid); ++ FILE* F = fopen(Path, "r"); ++ if (!F) { ++ return false; ++ } ++ char Buf[512]; ++ const bool Ok = fgets(Buf, sizeof(Buf), F) != nullptr; ++ fclose(F); ++ if (!Ok) { ++ return false; ++ } ++ const char* P = strrchr(Buf, ')'); ++ unsigned long Ut = 0, St = 0; ++ if (!P || sscanf(P + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &Ut, &St) != 2) { ++ return false; ++ } ++ auto& L = Last[Tid]; ++ const bool Busy = (Ut + St) > L; ++ L = Ut + St; ++ return Busy; ++ } ++ ++ bool OpenRecords(pid_t Pid) { ++ if (Records) { ++ return true; ++ } ++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-samples"; ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(Sample) * MaxSamples) != 0) { ++ return false; ++ } ++ void* Map = mmap(nullptr, sizeof(Sample) * MaxSamples, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map == MAP_FAILED) { ++ return false; ++ } ++ Records = static_cast(Map); ++ return true; ++ } ++ ++ void TakeSnapshot(pid_t Pid) { ++ if (!Snaps) { ++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-snap"; ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) { ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map == MAP_FAILED) { ++ return; ++ } ++ Snaps = static_cast(Map); ++ } ++ memset(Snaps, 0, sizeof(SnapRecord) * MaxSnaps); ++ SnapCount = 0; ++ SnapMode = true; ++ if (DIR* D = opendir("/proc/self/task")) { ++ while (auto* E = readdir(D)) { ++ const pid_t Tid = atoi(E->d_name); ++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid))) { ++ syscall(SYS_tgkill, Pid, Tid, SIGPROF); ++ } ++ } ++ closedir(D); ++ } ++ usleep(700000); ++ SnapMode = false; ++ } ++ ++ void* SamplerThread(void* Arg) { ++ const uint32_t Hz = static_cast(reinterpret_cast(Arg) & 0xffff); ++ const bool All = (reinterpret_cast(Arg) >> 16) != 0; ++ const pid_t Pid = getpid(); ++ const std::string Trigger = "/dev/shm/fex-" + std::to_string(Pid) + "-sample-on"; ++ const std::string SnapTrigger = "/dev/shm/fex-" + std::to_string(Pid) + "-snapshot"; ++ for (;;) { ++ if (access(SnapTrigger.c_str(), F_OK) == 0) { ++ unlink(SnapTrigger.c_str()); ++ TakeSnapshot(Pid); ++ continue; ++ } ++ if (access(Trigger.c_str(), F_OK) != 0) { ++ usleep(100000); ++ continue; ++ } ++ if (!OpenRecords(Pid)) { ++ usleep(100000); ++ continue; ++ } ++ usleep(1000000 / Hz); ++ if (FEX::HLE::PtraceEmu::IsAttached()) { ++ continue; ++ } ++ if (All) { ++ if (DIR* D = opendir("/proc/self/task")) { ++ while (auto* E = readdir(D)) { ++ const pid_t Tid = atoi(E->d_name); ++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid)) && IsInteresting(Tid)) { ++ syscall(SYS_tgkill, Pid, Tid, SIGPROF); ++ } ++ } ++ closedir(D); ++ } ++ } else { ++ syscall(SYS_tgkill, Pid, Pid, SIGPROF); ++ } ++ } ++ return nullptr; ++ } ++} ++ ++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External) { ++ if (!Hz) { ++ return; ++ } ++ ExternalMode = External; ++ Delegator = Signals; ++ Signals->RegisterHostSignalHandler( ++ SIGPROF, ++ [](FEXCore::Core::InternalThreadState* Thread, int, void*, void* UContext) { ++ if (ExternalMode) { ++ OpenExternalSnaps(); ++ } ++ if (ExternalMode || SnapMode.load(std::memory_order_relaxed)) { ++ uint32_t SIdx = SnapCount.fetch_add(1, std::memory_order_relaxed); ++ const uint32_t Seq = SIdx; ++ if (ExternalMode) { ++ SIdx %= MaxSnaps; ++ } ++ if (Snaps && SIdx < MaxSnaps) { ++ SnapRecord& R = Snaps[SIdx]; ++ R.Tid = static_cast(syscall(SYS_gettid)); ++ R.HostPC = ArchHelpers::Context::GetPc(UContext); ++ if (Thread) { ++ const auto& St = Thread->CurrentFrame->State; ++ R.Rip = St.rip; ++ for (unsigned i = 0; i < 16; ++i) { ++ R.Gregs[i] = St.gregs[i]; ++ } ++ iovec Local {R.Stack, sizeof(R.Stack)}; ++ iovec Remote {reinterpret_cast(St.gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)}; ++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0); ++ ++ const uint64_t Nr = St.gregs[FEXCore::X86State::REG_RAX]; ++ if (Nr == 202 || Nr == 449) { ++ uint64_t Addr = St.gregs[FEXCore::X86State::REG_RDI]; ++ uint64_t Expected = St.gregs[FEXCore::X86State::REG_RDX]; ++ if (Nr == 449) { ++ uint64_t Waiter[3] {}; ++ iovec WL {Waiter, sizeof(Waiter)}; ++ iovec WR {reinterpret_cast(Addr), sizeof(Waiter)}; ++ Addr = process_vm_readv(getpid(), &WL, 1, &WR, 1, 0) == static_cast(sizeof(Waiter)) ? Waiter[1] : 0; ++ Expected = Waiter[0]; ++ } ++ uint32_t Word = 0; ++ iovec FL {&Word, sizeof(Word)}; ++ iovec FR {reinterpret_cast(Addr), sizeof(Word)}; ++ if (Addr && process_vm_readv(getpid(), &FL, 1, &FR, 1, 0) == static_cast(sizeof(Word))) { ++ R.FutexWord = (1ULL << 63) | Word; ++ R.FutexExpected = Expected; ++ R.FutexAddr = Addr; ++ } ++ } ++ } ++ if (ExternalMode) { ++ R.FutexWord = 0; ++ R.FutexExpected = Seq; ++ R.FutexAddr = ArchHelpers::Context::GetSp(UContext); ++ if (Thread && Thread->CTX->IsAddressInCodeBuffer(Thread, R.HostPC)) { ++ R.FutexWord = 1; ++ R.Rip = Thread->CTX->RestoreRIPFromHostPC(Thread, R.HostPC); ++ const auto& Cfg = Delegator->GetConfig(); ++ for (size_t i = 0; i < Cfg.SRAGPRCount && i < 16; ++i) { ++ R.Gregs[i] = ArchHelpers::Context::GetArmReg(UContext, Cfg.SRAGPRMapping[i]); ++ } ++ iovec Local {R.Stack, sizeof(R.Stack)}; ++ iovec Remote {reinterpret_cast(R.Gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)}; ++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0); ++ } ++ } ++ } ++ return true; ++ } ++ const uint32_t Idx = Count.fetch_add(1, std::memory_order_relaxed); ++ if (Records && Idx < MaxSamples) { ++ Records[Idx] = {ArchHelpers::Context::GetPc(UContext), ++ static_cast(static_cast(syscall(SYS_gettid))) | (Thread ? (Thread->CurrentFrame->State.rip << 32) : 0)}; ++ } ++ return true; ++ }, ++ true); ++ ++ if (External) { ++ return; ++ } ++ pthread_t T; ++ pthread_attr_t Attr; ++ pthread_attr_init(&Attr); ++ pthread_attr_setdetachstate(&Attr, PTHREAD_CREATE_DETACHED); ++ pthread_create(&T, &Attr, SamplerThread, reinterpret_cast(static_cast(Hz | (AllThreads ? 0x10000 : 0)))); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h +new file mode 100644 +index 000000000..b6b433eca +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h +@@ -0,0 +1,13 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++ ++namespace FEXCore::Core { ++struct InternalThreadState; ++} ++namespace FEX::HLE { ++class SignalDelegator; ++ ++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External = false); ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp +index 7b0e9f91c..d2626fd8f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp +@@ -120,6 +120,16 @@ $end_info$ + // TRACE_syscall + // - ptrace unsupported + ++#ifndef PR_SET_SYSCALL_USER_DISPATCH ++#define PR_SET_SYSCALL_USER_DISPATCH 59 ++#define PR_SYS_DISPATCH_OFF 0 ++#define PR_SYS_DISPATCH_ON 1 ++#endif ++#ifndef SYSCALL_DISPATCH_FILTER_ALLOW ++#define SYSCALL_DISPATCH_FILTER_ALLOW 0 ++#define SYSCALL_DISPATCH_FILTER_BLOCK 1 ++#endif ++ + namespace FEX::HLE { + uint64_t SeccompEmulator::Handle(FEXCore::Core::CpuStateFrame* Frame, uint32_t Op, uint32_t flags, void* arg) { + // If seccomp isn't enabled then say so. +@@ -315,6 +325,60 @@ void SeccompEmulator::DeserializeFilters(FEXCore::Core::CpuStateFrame* Frame, in + close(FD); + } + ++void SeccompEmulator::QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, ++ uint64_t SyscallNumber, uint32_t Arch) { ++ siginfo_t Info { ++ .si_signo = SIGSYS, ++ .si_errno = static_cast(Errno), ++ .si_code = Code, ++ }; ++ ++ Info.si_call_addr = reinterpret_cast(PostSyscallRIP); ++ Info.si_syscall = SyscallNumber; ++ Info.si_arch = Arch; ++ ++ Thread->SeccompTrapRIP = PostSyscallRIP; ++ ++ SignalDelegation->PrepareForcedGuestSignal(Thread, SIGSYS); ++ SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true); ++} ++ ++void SeccompEmulator::ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) { ++ uint64_t Mask = 1ULL << (Signal - 1); ++ SignalDelegation->GuestSigProcMask(Thread, SIG_UNBLOCK, &Mask, nullptr); ++ SignalDelegation->UninstallHostHandler(Signal); ++ FHU::Syscalls::tgkill(::getpid(), ::gettid(), Signal); ++} ++ ++SeccompEmulator::ExecuteFilterResult ++SeccompEmulator::ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber) { ++ auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); ++ const auto& SUD = Thread->SyscallUserDispatch; ++ const uint64_t PostSyscallRIP = Thread->Thread->CTX->RestoreRIPFromHostPC(Frame->Thread, JITPC) + 2; ++ ++ if (PostSyscallRIP - SUD.Offset < SUD.Length) { ++ return {false, 0}; ++ } ++ ++ if (SUD.Selector) { ++ uint8_t State {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&State, reinterpret_cast(SUD.Selector), sizeof(State))) { ++ ForceExitSignal(Thread, SIGSEGV); ++ return {true, SyscallNumber}; ++ } ++ if (State == SYSCALL_DISPATCH_FILTER_ALLOW) { ++ return {false, 0}; ++ } ++ if (State != SYSCALL_DISPATCH_FILTER_BLOCK) { ++ ForceExitSignal(Thread, SIGSYS); ++ return {true, SyscallNumber}; ++ } ++ } ++ ++ QueueTrapSignal(Thread, 2 , 0, PostSyscallRIP, SyscallNumber, Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386); ++ return {true, SyscallNumber}; ++} ++ + SeccompEmulator::ExecuteFilterResult + SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args) { + if (!HasFilter(Frame)) { +@@ -325,6 +389,8 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + const uint64_t RIP = Thread->Thread->CTX->RestoreRIPFromHostPC(Frame->Thread, JITPC); + ++ const uint64_t PostSyscallRIP = RIP + 2; ++ + const auto Arch = Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386; + bool ShouldLog {}; + uint32_t SeccompResult {}; +@@ -429,18 +495,9 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT + break; + } + case SECCOMP_RET_TRAP: { +- siginfo_t Info { +- .si_signo = SIGSYS, +- .si_errno = static_cast(DataMasked), +- .si_code = 1, // SYS_SECCOMP +- }; +- +- Info.si_call_addr = reinterpret_cast(RIP); +- Info.si_syscall = Args->Argument[0]; +- Info.si_arch = Arch; ++ QueueTrapSignal(Thread, 1 , DataMasked, PostSyscallRIP, Args->Argument[0], Arch); + +- SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true); +- break; ++ return {true, Args->Argument[0]}; + } + case SECCOMP_RET_ERRNO: { + // errno return is clamped. +@@ -620,7 +677,8 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin + return -EINVAL; + } + +- if (!prog) { ++ sock_fprog UserProg; ++ if (FaultSafeUserMemAccess::CopyFromUser(&UserProg, prog, sizeof(UserProg))) { + return -EFAULT; + } + +@@ -629,12 +687,22 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin + return -EACCES; + } + +- if (prog->len > BPF_MAXINSNS || prog->len == 0) { ++ if (UserProg.len > BPF_MAXINSNS || UserProg.len == 0) { + // operation specified SECCOMP_SET_MODE_FILTER, but the filter program pointed to by args was not valid or the length of the filter + // program was zero or exceeded BPF_MAXINSNS (4096) instructions. + return -EINVAL; + } + ++ fextl::vector Instructions(UserProg.len); ++ if (FaultSafeUserMemAccess::CopyFromUser(Instructions.data(), UserProg.filter, UserProg.len * sizeof(sock_filter))) { ++ return -EFAULT; ++ } ++ const sock_fprog LocalProg { ++ .len = UserProg.len, ++ .filter = Instructions.data(), ++ }; ++ prog = &LocalProg; ++ + // Don't interrupt me while I'm jitting. + auto lk = FEXCore::MaskSignalsAndLockMutex(FilterMutex); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h +index b10f664ed..2d58f79c0 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h +@@ -61,6 +61,8 @@ public: + }; + ExecuteFilterResult ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args); + ++ ExecuteFilterResult ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber); ++ + bool HasFilter(FEXCore::Core::CpuStateFrame* Frame) const { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + return !Thread->Filters.empty(); +@@ -98,6 +100,10 @@ private: + + static void DumpProgram(const sock_fprog* prog); + ++ void QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, uint64_t SyscallNumber, ++ uint32_t Arch); ++ void ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal); ++ + // Multiple filter instruction count penalty. + // When multiple filters are installed there is a penalty per filter counted towards the maximum number of instructions. + constexpr static size_t BPF_MULTIFILTERPENALTY = 4; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 77f124a94..efe49dbf1 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -8,6 +8,8 @@ $end_info$ + + #include "LinuxSyscalls/SignalDelegator.h" + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" + + #include + #include +@@ -200,6 +202,10 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore:: + Context->UContextLocation = 0; + Context->SigInfoLocation = 0; + Context->InSyscallInfo = 0; ++ Context->ClearedSyscallInfo = 0; ++ Context->GuestSignalMask = 0; ++ Context->SeccompTrapRIP = 0; ++ Context->SavedJITStackSP = 0; + + // Store fault to top status and then reset it + Context->FaultToTopAndGeneratedException = Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException; +@@ -208,6 +214,8 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore:: + return Context; + } + ++static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread); ++ + void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thread, void* ucontext, RestoreType Type) { + uint64_t OldSP {}; + if (Type == RestoreType::TYPE_PAUSE) [[unlikely]] { +@@ -296,8 +304,38 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + uintptr_t NewSP = OldSP; + auto Context = reinterpret_cast(NewSP); + ++ if (Type != RestoreType::TYPE_PAUSE) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ for (size_t i = ThreadObject->TrapSignalFrameCount; i > 0; --i) { ++ if (ThreadObject->TrapSignalFrames[i - 1].ContextBackup == NewSP) { ++ ThreadObject->TrapSignalFrameCount = i - 1; ++ break; ++ } ++ } ++ } ++ + // Restore host state + ArchHelpers::Context::RestoreContext(ucontext, Context); ++ Thread->CurrentFrame->InSyscallInfo = (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_SYSCALLINFO_CLEARED) ? ++ Context->ClearedSyscallInfo : ++ Context->InSyscallInfo; ++ ++ { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::SigReturn, 0, Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP], ++ Context->GuestSignalMask); ++ if (Type != RestoreType::TYPE_PAUSE && SignalMaskFix()) { ++ uint64_t NewGuestMask = Context->GuestSignalMask; ++ if (Is64BitMode && Context->UContextLocation) { ++ auto* GuestUContext = reinterpret_cast(Context->UContextLocation); ++ NewGuestMask = GuestUContext->uc_sigmask.val[0] & ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1))); ++ } ++ ThreadObject->SignalInfo.CurrentSignalMask.Val = NewGuestMask; ++ CheckForPendingSignals(ThreadObject); ++ } ++ } ++ ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->JITStackSP = Context->SavedJITStackSP; + + // Reset the guest state + memcpy(&Thread->CurrentFrame->State, &Context->GuestState, sizeof(FEXCore::Core::CPUState)); +@@ -324,7 +362,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + + bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ ++ const int SigSysCode = Signal == SIGSYS ? static_cast(info)->si_code : 0; ++ const bool IsTrapSignal = (SigSysCode == 1 || SigSysCode == 2 ) && ThreadObject->SeccompTrapRIP && ++ !CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)); ++ if (IsTrapSignal) { ++ const uint64_t GuestRSP = Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP]; ++ while (ThreadObject->TrapSignalFrameCount) { ++ const auto& Abandoned = ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount - 1]; ++ if (GuestRSP <= Abandoned.GuestFrame || GuestRSP < Abandoned.GuestRSP) { ++ break; ++ } ++ ThreadObject->JITStackSP = Abandoned.JITStackSP; ++ --ThreadObject->TrapSignalFrameCount; ++ --Thread->CurrentFrame->SignalHandlerRefCounter; ++ } ++ const uint64_t Level = ThreadObject->JITStackSP ? ThreadObject->JITStackSP : Thread->CurrentFrame->ReturningStackLocation; ++ if (Level > ArchHelpers::Context::GetSp(ucontext)) { ++ ArchHelpers::Context::SetSp(ucontext, Level); ++ } ++ } ++ + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); ++ ContextBackup->GuestSignalMask = ThreadObject->SignalInfo.CurrentSignalMask.Val; ++ ++ if (SigSysCode == 1 || SigSysCode == 2 ) { ++ ContextBackup->SeccompTrapRIP = ThreadObject->SeccompTrapRIP; ++ ThreadObject->SeccompTrapRIP = 0; ++ } ++ ContextBackup->SavedJITStackSP = ThreadObject->JITStackSP; + + auto Frame = Thread->CurrentFrame; + auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; +@@ -363,8 +430,13 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { +- ContextBackup->InSyscallInfo = Frame->InSyscallInfo; +- Frame->InSyscallInfo = 0; ++ ThreadObject->JITStackSP = ArchHelpers::Context::GetSp(ucontext); ++ ++ if (Thread->CurrentFrame->InSyscallInfo != 0) { ++ ContextBackup->ClearedSyscallInfo = Thread->CurrentFrame->InSyscallInfo; ++ ContextBackup->Flags |= ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_SYSCALLINFO_CLEARED; ++ Thread->CurrentFrame->InSyscallInfo = 0; ++ } + + if (!IsAddressInDispatcher(OldPC)) { + // This is likely to cause issues but in some cases it isn't fatal +@@ -443,6 +515,14 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + + if (Is64BitMode) { + NewGuestSP = SetupFrame_x64(Thread, ContextBackup, Frame, Signal, HostSigInfo, ucontext, GuestAction, GuestStack, NewGuestSP, eflags); ++ if (IsTrapSignal && ThreadObject->TrapSignalFrameCount < ThreadObject->MaxTrapSignalFrames) { ++ ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount++] = { ++ .GuestFrame = NewGuestSP, ++ .GuestRSP = OldGuestSP, ++ .JITStackSP = ContextBackup->SavedJITStackSP, ++ .ContextBackup = reinterpret_cast(ContextBackup), ++ }; ++ } + } else { + const bool SigInfoFrame = (GuestAction->sa_flags & SA_SIGINFO) == SA_SIGINFO; + if (SigInfoFrame) { +@@ -464,8 +544,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + // This way signal handlers always go back to their original operating mode. + // Doesn't matter for 32-bit processes as they can only be 32-bit, but does + // matter for 64-bit processes as they could have potentially installed a 32-bit code segment. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; +- Frame->State.ss_idx = 0; ++ Frame->State.cs_idx = Is64BitMode ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; + Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx)); + Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx)); + +@@ -671,7 +751,7 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* + auto SigInfo = *static_cast(Info); + + if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) { +- ERROR_AND_DIE_FMT("Received invalid data to syscall. Crashing now!"); ++ return true; + } + + #ifdef ARCHITECTURE_arm64 +@@ -695,10 +775,21 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* + + void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObject, int Signal, void* Info, void* UContext) { + auto Thread = ThreadObject->Thread; ++ ++ if (PtraceEmu::TryGuestSignalStop(Thread->CurrentFrame, Signal)) { ++ Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException = false; ++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA); ++ ArchHelpers::Context::SetFillSRASingleInst(UContext, false); ++ ArchHelpers::Context::SetState(UContext, reinterpret_cast(Thread->CurrentFrame)); ++ return; ++ } ++ + ucontext_t* _context = (ucontext_t*)UContext; + auto SigInfo = *static_cast(Info); + + auto MustDeferSignal = (Thread->CurrentFrame->State.DeferredSignalRefCount.Load() != 0); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::HostArrive, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ++ (static_cast(MustDeferSignal) << 32) | static_cast(SigInfo.si_code)); + if (Signal == SIGSEGV && SigInfo.si_code == SEGV_ACCERR && SigInfo.si_addr == reinterpret_cast(&Thread->InterruptFaultPage)) { + if (!MustDeferSignal) { + // We just reached the end of the outermost signal-deferring section and faulted to check for pending signals. +@@ -762,6 +853,8 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again + sigmask_val[0] = GetNewSigMask(Signal); + ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Deferred, Signal, 0, 0); ++ + // Now update the faulting page permissions so it will fault on write. + mprotect(reinterpret_cast(&Thread->InterruptFaultPage), sizeof(Thread->InterruptFaultPage), PROT_NONE); + +@@ -774,6 +867,7 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + // This signal is masked, must defer until the guest updates the signal mask. + // Add it to the pending signal list + ThreadObject->SignalInfo.PendingSignals |= 1ULL << (Signal - 1); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Masked, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ThreadObject->SignalInfo.PendingSignals); + return; + } + +@@ -795,6 +889,21 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + if (Handler.GuestHandler && + Handler.GuestHandler(Thread, Signal, &SigInfo, UContext, &Handler.GuestAction, &ThreadObject->SignalInfo.GuestAltStack)) { + uint64_t NewMask = GetNewSigMask(Signal); ++ if (SignalMaskFix()) { ++ uint64_t GuestNew = ThreadObject->SignalInfo.CurrentSignalMask.Val | Handler.GuestAction.sa_mask.Val; ++ if (!(Handler.GuestAction.sa_flags & SA_NODEFER)) { ++ GuestNew |= 1ULL << (Signal - 1); ++ } ++ GuestNew &= ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1))); ++ ThreadObject->SignalInfo.CurrentSignalMask.Val = GuestNew; ++ NewMask = GuestNew; ++ for (size_t i = 0; i < MAX_SIGNALS; ++i) { ++ if (HostHandlers[i + 1].Required.load(std::memory_order_relaxed)) { ++ NewMask &= ~(1ULL << i); ++ } ++ } ++ } ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Delivered, Signal, reinterpret_cast(Handler.GuestAction.sigaction_handler.sigaction), NewMask); + + // Update our host signal mask so we don't hit race conditions with signals + // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again +@@ -942,6 +1051,30 @@ void SignalDelegator::UninstallHostHandler(int Signal) { + ::syscall(SYS_rt_sigaction, Signal, &SignalHandler.OldAction, nullptr, 8); + } + ++void SignalDelegator::ForceGuestSigSegv(uint64_t BadSP) { ++ static std::atomic Logged {false}; ++ if (!Logged.exchange(true, std::memory_order_relaxed)) { ++ LogMan::Msg::EFmt("Cannot write the guest signal frame at stack pointer 0x{:x}; forcing SIGSEGV " ++ "(Linux force_sigsegv). The guest stack pointer is not a live, writable mapping.", ++ BadSP); ++ } ++ ++ SignalHandler& Handler = HostHandlers[SIGSEGV]; ++ Handler.GuestAction.sigaction_handler.handler = SIG_DFL; ++ Handler.OldAction.handler = SIG_DFL; ++ ::signal(SIGSEGV, SIG_DFL); ++ ++ CTX->FlushAndCloseCodeMap(); ++ FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ ++ uint64_t SegvMask = 1ULL << (SIGSEGV - 1); ++ ::syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &SegvMask, nullptr, 8); ++ ::raise(SIGSEGV); ++ ++ ::syscall(SYS_exit, 128 + SIGSEGV); ++ FEX_UNREACHABLE; ++} ++ + void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask) { + bool WasIgnored {}; + bool WasMasked {}; +@@ -976,11 +1109,34 @@ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* + } + } + ++void SignalDelegator::PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) { ++ const uint64_t SignalMask = 1ULL << (Signal - 1); ++ const bool Blocked = Thread->SignalInfo.CurrentSignalMask.Val & SignalMask; ++ ++ GuestSigAction Action {}; ++ RegisterGuestSignalHandler(Signal, nullptr, &Action); ++ const bool Ignored = Action.sigaction_handler.handler == SIG_IGN; ++ ++ if (!Blocked && !Ignored) { ++ return; ++ } ++ ++ Action.sigaction_handler.handler = SIG_DFL; ++ RegisterGuestSignalHandler(Signal, &Action, nullptr); ++ if (Blocked) { ++ GuestSigProcMask(Thread, SIG_UNBLOCK, &SignalMask, nullptr); ++ } ++} ++ + SignalDelegator::SignalDelegator(FEXCore::Context::Context* _CTX, const std::string_view ApplicationName, bool SupportsAVX, bool SupportsSVE256) + : CTX {_CTX} + , ApplicationName {ApplicationName} + , SupportsAVX {SupportsAVX} + , SupportsSVE256 {SupportsSVE256} { ++ if (SignalTrace()) { ++ SigTrace::Init(); ++ } ++ + // Signal zero isn't real + HostHandlers[0].Installed = true; + +@@ -1143,23 +1299,36 @@ void SignalDelegator::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + } + } + +-void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { +- FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16); +- +- Thread->SignalInfo.AltStackPtr = nullptr; +- ++void SignalDelegator::ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread) { + stack_t altstack {}; + altstack.ss_flags = SS_DISABLE; +- +- // Uninstall the alt stack + const int Result = sigaltstack(&altstack, nullptr); + if (Result == -1) { + LogMan::Msg::EFmt("Failed to uninstall alternative signal stack {}", strerror(errno)); + } + ++ FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16); ++ Thread->SignalInfo.AltStackPtr = nullptr; ++ Thread->SignalInfo.AltStackReleaseDeferred = false; ++} ++ ++void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ stack_t Current {}; ++ if (sigaltstack(nullptr, &Current) == 0 && (Current.ss_flags & SS_ONSTACK)) { ++ Thread->SignalInfo.AltStackReleaseDeferred = true; ++ } else { ++ ReleaseAltStack(Thread); ++ } ++ + FEXCore::Allocator::UninstallTLSData(Thread->Thread); + } + ++void SignalDelegator::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ if (Thread->SignalInfo.AltStackReleaseDeferred) { ++ ReleaseAltStack(Thread); ++ } ++} ++ + void SignalDelegator::FrontendRegisterHostSignalHandler(int Signal, bool Required) { + // Linux signal handlers are per-process rather than per thread + // Multiple threads could be calling in to this +@@ -1302,6 +1471,7 @@ static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread) { + if (PendingSignals != 0) { + for (int i = 0; i < 64; ++i) { + if (PendingSignals & (1ULL << i)) { ++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::Reraise, i + 1, Thread->SignalInfo.CurrentSignalMask.Val, Thread->SignalInfo.PendingSignals); + FHU::Syscalls::tgkill(Thread->ThreadInfo.PID, Thread->ThreadInfo.TID, i + 1); + // We might not even return here which is spooky + } +@@ -1342,6 +1512,9 @@ uint64_t SignalDelegator::GuestSigProcMask(FEX::HLE::ThreadStateObject* Thread, + } + + ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &HostMask, nullptr, 8); ++ if (Thread->Thread->CurrentFrame->SignalHandlerRefCounter != 0) { ++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::ProcMask, how, *set, Thread->SignalInfo.CurrentSignalMask.Val); ++ } + } + + if (oldset) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +index c52832d73..e558ced19 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -62,6 +62,8 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread); + + /** + * @brief Registers a signal handler for the host to handle a signal +@@ -106,6 +108,10 @@ public: + void UninstallHostHandler(int Signal); + void QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask); + ++ void PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal); ++ ++ [[noreturn]] void ForceGuestSigSegv(uint64_t BadSP); ++ + void SetVDSOSymbols() { + // Get symbols from VDSO. + VDSOPointers = FEX::VDSO::GetVDSOSymbols(); +@@ -184,6 +190,8 @@ private: + FEXCore::Context::Context* CTX; + + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); ++ FEX_CONFIG_OPT(SignalMaskFix, SIGNALMASKFIX); ++ FEX_CONFIG_OPT(SignalTrace, SIGNALTRACE); + const fextl::string ApplicationName; + FEX_CONFIG_OPT(HalfBarrierTSOEnabled, HALFBARRIERTSOENABLED); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index 65f847a5e..aa72957fa 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -7,6 +7,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/Syscalls.h" + + #include + #include +@@ -14,11 +15,15 @@ $end_info$ + #include + #include + #include ++#include + ++#include + #include + #include + #include + #include ++#include ++#include + + namespace FEX::HLE { + constexpr uint32_t X86_SA_RESTORER = 0x04000000; +@@ -106,19 +111,35 @@ template + static void SetXStateInfo(T* xstate, bool is_avx_enabled) { + auto* fpstate = &xstate->fpstate; + +- fpstate->sw_reserved.magic1 = is_avx_enabled ? FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1 : 0; +- fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.magic1 = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1; + + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_FP | FEXCore::x86_64::fpx_sw_bytes::FEATURE_SSE; + if (is_avx_enabled) { + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_YMM; + } + +- fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if constexpr (std::is_same_v) { ++ if (!is_avx_enabled) { ++ fpstate->sw_reserved.xstate_size = sizeof(FEXCore::x86_64::_libc_fpstate); ++ fpstate->sw_reserved.extended_size = sizeof(FEXCore::x86_64::_libc_fpstate) + sizeof(uint32_t); ++ return; ++ } + +- if (is_avx_enabled) { +- xstate->xstate_hdr.xfeatures = 0; +- xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ const uint32_t UserSize = offsetof(FEXCore::x86_64::xstate, ymmh) + sizeof(FEXCore::x86_64::ymmh_state); ++ fpstate->sw_reserved.xstate_size = UserSize; ++ fpstate->sw_reserved.extended_size = UserSize + sizeof(uint32_t); ++ ++ xstate->xstate_hdr.xfeatures = fpstate->sw_reserved.xfeatures; ++ ++ *reinterpret_cast(reinterpret_cast(fpstate) + UserSize) = ++ FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } else { ++ fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if (is_avx_enabled) { ++ xstate->xstate_hdr.xfeatures = 0; ++ xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } + } + } + +@@ -153,14 +174,19 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + auto* guest_uctx = reinterpret_cast(Context->UContextLocation); + [[maybe_unused]] auto* guest_siginfo = reinterpret_cast(Context->SigInfoLocation); + +- // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { ++ CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); ++ ++ if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -176,9 +202,6 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx)); + Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx)); + +- // XXX: Full context setting +- CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); +- + #define COPY_REG(x) Frame->State.gregs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; + COPY_REG(R8); + COPY_REG(R9); +@@ -256,12 +279,15 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + SigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException || Context->SeccompTrapRIP) { + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -345,13 +371,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + RTSigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -431,9 +461,42 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + } + } + ++static bool GuestFrameWritable(uint64_t Begin, uint64_t End) { ++ if (End < Begin) { ++ return false; ++ } ++ ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ ++ constexpr uint64_t PageSize = 4096; ++ constexpr uint64_t MaxPages = 4096; ++ const uint64_t FirstPage = Begin & ~(PageSize - 1); ++ const uint64_t LastPage = End & ~(PageSize - 1); ++ ++ auto lk = FEXCore::MaskSignalsAndLockMutex(VMATracking.Mutex); ++ ++ for (uint64_t Page = FirstPage, PageCount = 0; Page <= LastPage; Page += PageSize, ++PageCount) { ++ if (PageCount >= MaxPages) { ++ return false; ++ } ++ ++ const auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry == VMATracking.VMAs.end()) { ++ return false; ++ } ++ ++ if (!Entry->second.Prot.Writable || (Entry->first + Entry->second.Length) < (Page + PageSize)) { ++ return false; ++ } ++ } ++ ++ return true; ++} ++ + uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, + FEXCore::Core::CpuStateFrame* Frame, int Signal, siginfo_t* HostSigInfo, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack, uint64_t NewGuestSP, const uint32_t eflags) { ++ const uint64_t RequestedGuestSP = NewGuestSP; + + // Back up past the redzone, which is 128bytes + // 32-bit doesn't have a redzone +@@ -475,6 +538,16 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + ContextBackup->UContextLocation = UContextLocation; + ContextBackup->SigInfoLocation = SigInfoLocation; + ++ const uint64_t UContextEnd = UContextLocation + sizeof(FEXCore::x86_64::ucontext_t); ++ const uint64_t FPStateEnd = ++ FPStateLocation + (SupportsAVX ? sizeof(FEXCore::x86_64::xstate) : sizeof(FEXCore::x86_64::_libc_fpstate)); ++ const uint64_t HostStackEnd = HostStackLocation + sizeof(uint64_t); ++ const uint64_t FrameEnd = std::max({UContextEnd, FPStateEnd, HostStackEnd}); ++ ++ if (!GuestFrameWritable(UContextLocation, FrameEnd)) { ++ ForceGuestSigSegv(RequestedGuestSP); ++ } ++ + FEXCore::x86_64::ucontext_t* guest_uctx = reinterpret_cast(UContextLocation); + siginfo_t* guest_siginfo = reinterpret_cast(SigInfoLocation); + // Store where the host context lives in the guest stack. +@@ -488,7 +561,8 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + auto* xstate = reinterpret_cast(FPStateLocation); + SetXStateInfo(xstate, SupportsAVX); + +- guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL] = eflags; + // This stores the CS/GS/FS selectors. It ALSO stores the SS selector in the top 16 bits...For some reason. + // Despite the naming, the endianness is swapped from what you'd expect. +@@ -572,6 +646,9 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + guest_uctx->uc_stack.ss_sp = GuestStack->ss_sp; + guest_uctx->uc_stack.ss_size = GuestStack->ss_size; + ++ memset(guest_uctx->uc_sigmask.val, 0, sizeof(guest_uctx->uc_sigmask.val)); ++ guest_uctx->uc_sigmask.val[0] = ContextBackup->GuestSignalMask; ++ + // Apparently RAX is always set to zero in case of badly misbehaving C applications and variadics. + Frame->State.gregs[FEXCore::X86State::REG_RAX] = 0; + Frame->State.gregs[FEXCore::X86State::REG_RDI] = Signal; +@@ -647,7 +724,7 @@ uint64_t SignalDelegator::SetupFrame_ia32(FEXCore::Core::InternalThreadState* Th + guest_uctx->sc.err = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->sc.ip = ContextBackup->OriginalRIP; ++ guest_uctx->sc.ip = ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->sc.flags = eflags; + guest_uctx->sc.sp_at_signal = 0; + +@@ -783,7 +860,8 @@ uint64_t SignalDelegator::SetupRTFrame_ia32(FEXCore::Core::InternalThreadState* + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_ERR] = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EFL] = eflags; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_UESP] = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + guest_uctx->uc.uc_mcontext.cr2 = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +new file mode 100644 +index 000000000..5db61d312 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +@@ -0,0 +1,45 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++Rec* Buf = nullptr; ++std::atomic Idx {0}; ++ ++namespace { ++ std::string PathFor(pid_t Pid) { ++ return "/dev/shm/fex-" + std::to_string(Pid) + "-sigtrace"; ++ } ++} ++ ++void Init() { ++ if (Buf) { ++ return; ++ } ++ const std::string Path = PathFor(getpid()); ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0) { ++ return; ++ } ++ if (ftruncate(fd, sizeof(Rec) * Recs) != 0) { ++ close(fd); ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(Rec) * Recs, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Buf = static_cast(Map); ++ } ++} ++ ++void CleanupForExit() { ++ if (!Buf) { ++ return; ++ } ++ unlink(PathFor(getpid()).c_str()); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +new file mode 100644 +index 000000000..d1a1bb8a6 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +@@ -0,0 +1,54 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++enum Event : uint16_t { ++ HostArrive = 1, ++ Masked = 2, ++ Deferred = 3, ++ Delivered = 4, ++ SigReturn = 5, ++ ProcMask = 6, ++ Reraise = 7, ++ Kill = 8, ++ Read16 = 9, ++ Write16 = 10, ++ EpollCtl = 11, ++}; ++ ++struct Rec { ++ uint64_t Tsc; ++ uint32_t Tid; ++ uint16_t Ev; ++ uint16_t Sig; ++ uint64_t A; ++ uint64_t B; ++}; ++ ++constexpr uint32_t Recs = 1u << 19; ++extern Rec* Buf; ++extern std::atomic Idx; ++ ++void Init(); ++ ++void CleanupForExit(); ++ ++inline bool Enabled() { ++ return Buf != nullptr; ++} ++ ++inline void Log(uint32_t Tid, uint16_t Ev, uint16_t Sig, uint64_t A, uint64_t B) { ++ if (!Buf) { ++ return; ++ } ++ uint64_t Tsc = 0; ++#if defined(__aarch64__) ++ asm volatile("mrs %0, cntvct_el0" : "=r"(Tsc)); ++#endif ++ Rec& R = Buf[Idx.fetch_add(1, std::memory_order_relaxed) & (Recs - 1)]; ++ R = {Tsc, Tid, Ev, Sig, A, B}; ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 4a77d8716..607ab0b97 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -15,6 +15,8 @@ $end_info$ + + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/Utils/Threads.h" +@@ -235,6 +237,11 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + return -ENOENT; + } + ++ if (PtraceEmu::IsAttached()) { ++ char Resolved[PATH_MAX]; ++ PtraceEmu::RecordExecPath(pathname[0] == '/' ? std::string(pathname) : std::string(realpath(Filename.c_str(), Resolved) ? Resolved : pathname)); ++ } ++ + int pid = getpid(); + + char PidSelfPath[50]; +@@ -332,7 +339,8 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + // - seccomp inheritance + // - FEXServer FD inheritance (unshare(CLONE_NEWNET)) + // - FD_CLOEXEC set on FD on anonymous file FD. +- const bool NeedsEnvpCopy = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || HasSeccomp || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsExecveFD = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsEnvpCopy = NeedsExecveFD || HasSeccomp; + + // We are trying to execute a shebang handled by a different architecture interpreter (e.g. /usr/bin/python from the host FS). + // In this case we just defer to the kernel. +@@ -348,7 +356,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + } + } + +- if (!IsBinfmtCompatible || NeedsFDCopy) { ++ if (NeedsExecveFD) { + if (NeedsFDCopy) { + // FEX needs the FD to live past execve when binfmt_misc isn't used, + // so duplicate the FD if FD_CLOEXEC is set, which removes the FD_CLOEXEC flag. +@@ -439,9 +447,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + + // It is valid to provide nullptr first argument. + if (*OldArgv) { +- // The direct fallback uses the executable path as argv[0]. An FD-backed load uses the +- // binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector. +- if (!NeedsLoaderFD && !IsFDExec) { ++ if (!IsFDExec && !NeedsLoaderFD) { + ++OldArgv; + } + while (*OldArgv) { +@@ -814,6 +820,9 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler( ++ SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); ++ + ExtendedMetaData = FEX::VolatileMetadata::ParseExtendedVolatileMetadata(FEXCore::Config::Get_EXTENDEDVOLATILEMETADATA()()); + } + +@@ -835,6 +844,14 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + Thread->Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RAX] = Result & Mask; + }; + ++ if (FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch.Enabled) [[unlikely]] { ++ const auto Result = SeccompEmulator.ExecuteSyscallUserDispatch(Frame, JITPC, GetArg(Is64Bit, Frame, 0)); ++ if (Result.EarlyReturn) { ++ SetResult(Frame, Result.Result); ++ return; ++ } ++ } ++ + if (SeccompEmulator.HasFilter(Frame)) { + FEX::HLE::SyscallArguments Args { + .Argument = +@@ -856,9 +873,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + } + +- const auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ ++ uint64_t TraceArgs[6] {}; ++ const bool ReportStops = Is64Bit && PtraceEmu::WantsSyscallStops(); ++ if (ReportStops) { ++ for (unsigned i = 0; i < 6; ++i) { ++ TraceArgs[i] = GetArg(Is64Bit, Frame, i + 1); ++ } ++ SyscallNum = PtraceEmu::SyscallEntryStop(Frame, SyscallNum, TraceArgs); ++ } ++ + if (SyscallNum >= Definitions.size()) { +- SetResult(Frame, -ENOSYS); ++ uint64_t Result = -ENOSYS; ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ SetResult(Frame, Result); + return; + } + +@@ -891,6 +922,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + #ifdef DEBUG_STRACE + Strace(Frame, Result); + #endif ++ ++ if constexpr (Is64Bit) { ++ PtraceEmu::ApplyPendingFlush(Frame); ++ if (Result == 0 && (SyscallNum == 56 || SyscallNum == 57 || SyscallNum == 58 || SyscallNum == 435)) { ++ constexpr uint64_t CloneVM = 0x100; ++ uint64_t Flags = 0; ++ if (SyscallNum == 56) { ++ Flags = GetArg(Is64Bit, Frame, 1); ++ } else if (SyscallNum == 435) { ++ Flags = *reinterpret_cast(GetArg(Is64Bit, Frame, 1)); ++ } ++ PtraceEmu::OnForkedChild((Flags & CloneVM) != 0); ++ } ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ } + SetResult(Frame, Result); + } + +@@ -906,9 +954,12 @@ void SyscallHandler::HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) { + HandleSyscallImpl(Frame, JITPC); + } + +- // Skip past the `syscall` or `int 0x80` instruction. Both of which are 2-bytes. + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); +- Thread->Thread->CurrentFrame->State.rip += 2; ++ if (const uint64_t NewRip = PtraceEmu::TakePendingRip()) { ++ Thread->Thread->CurrentFrame->State.rip = NewRip; ++ } else { ++ Thread->Thread->CurrentFrame->State.rip += 2; ++ } + } + + #ifdef DEBUG_STRACE +@@ -969,6 +1020,8 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + // Code maps are closed upon fork in the child + FM.SetProtectedCodeMapFD(-1); + ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(LiveThread)->SyscallUserDispatch = {}; ++ + VMATracking.Mutex.StealAndDropActiveLocks(); + CodeCachePatchingMutex.StealAndDropActiveLocks(); + } else { +@@ -985,10 +1038,16 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + void SyscallHandler::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->RegisterTLSState(Thread); + ThunkHandler->RegisterTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(Thread); + } + + void SyscallHandler::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->UninstallTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(nullptr); ++} ++ ++void SyscallHandler::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ SignalDelegation->ReleaseDeferredTLSState(Thread); + } + + static bool isHEX(char c) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index f55bce4fc..d643b4975 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/ThreadManager.h" + #include "LinuxSyscalls/Seccomp/SeccompEmulator.h" ++#include "LinuxSyscalls/SMCHotPages.h" + #include "LinuxSyscalls/SyscallsVMATracking.h" + #include "ArchHelpers/MContext.h" + +@@ -203,6 +204,7 @@ public: + FEX_CONFIG_OPT(RootFSPath, ROOTFS); + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); + FEX_CONFIG_OPT(SMCChecks, SMCCHECKS); ++ FEX_CONFIG_OPT(SMCHotPageFaults, SMCHOTPAGEFAULTS); + FEX_CONFIG_OPT(NeedsSeccomp, NEEDSSECCOMP); + FEX_CONFIG_OPT(EnableCodeCaching, ENABLECODECACHINGWIP); + FEX_CONFIG_OPT(EnableDiskCache, DISKCACHE); +@@ -287,8 +289,13 @@ public: + + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); ++ static void InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); ++ bool IsSMCHotPage(uint64_t Address) override; ++ ++ void PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +@@ -304,6 +311,7 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); + + SourcecodeResolver* GetSourcecodeResolver() override { + return this; +@@ -363,6 +371,8 @@ private: + // std::mutex CodeCachePatchingMutex; + FEXCore::ForkableUniqueMutex CodeCachePatchingMutex; + ++ SMCHotPageTracker SMCHotPages; ++ + FEX::CodeLoader* LocalLoader {}; + bool NeedToCheckXID {true}; + +@@ -607,11 +617,13 @@ uint64_t GetDentsEmulation(int fd, T* dirp, uint32_t count); + namespace FaultSafeUserMemAccess { + // These are little helper functions for cases when FEX needs to copy data to or from the application in a robust fashion. + // CopyFromUser and CopyToUser are memcpy routines that expect to safely SIGSEGV when reading or writing application memory respectively. +- // Returns zero if the memcpy completed, or crashes with SIGABRT and a log message if it faults. + [[nodiscard]] + size_t CopyFromUser(void* Dest, const void* Src, size_t Size); + [[nodiscard]] + size_t CopyToUser(void* Dest, const void* Src, size_t Size); ++ ++ [[nodiscard]] ++ bool IsStringReadable(const char* Src); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + // These helpers just check if the user pointer is readable and writable. + // This is useful in an assert build that can be safely sprinkled through the syscall handler without overhead in release builds. +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +index 9acf01ff5..1601de1ef 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +@@ -38,6 +38,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(open, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Open(pathname, flags, mode); + SYSCALL_ERRNO(); +@@ -59,6 +62,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(access, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Access(pathname, mode); + SYSCALL_ERRNO(); + }); +@@ -80,22 +86,34 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(openat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfs, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Openat(dirfs, pathname, flags, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(readlinkat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlinkat(dirfd, pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat(dirfd, pathname, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat2, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode, int flags) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat2(dirfd, pathname, mode, flags); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +index 64c9aae22..9eee296ec 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +@@ -52,6 +52,9 @@ void RegisterFS(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(readlink, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlink(pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +index 1b61282d3..f83006c0a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +@@ -6,6 +6,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + +@@ -34,9 +35,11 @@ using cap_user_header_t = void*; + using cap_user_data_t = void*; + + void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* buf) -> uint64_t { ++ REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* ubuf) -> uint64_t { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + ++ struct utsname Out {}; ++ auto buf = &Out; + struct utsname Local {}; + if (::uname(&Local) == 0) { + memcpy(buf->nodename, Local.nodename, sizeof(Local.nodename)); +@@ -66,6 +69,9 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + // Tell the guest that we are a 64bit kernel + strcpy(buf->machine, "x86_64"); + } ++ if (FaultSafeUserMemAccess::CopyToUser(ubuf, &Out, sizeof(Out))) { ++ return -EFAULT; ++ } + return 0; + }); + +@@ -97,13 +103,14 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + ptrace, [](FEXCore::Core::CpuStateFrame* Frame, int /*enum __ptrace_request*/ request, pid_t pid, void* addr, void* data) -> uint64_t { + uint64_t Result {}; + ++ if (PtraceEmu::HandleRequest(request, pid, addr, data, &Result)) { ++ return Result; ++ } ++ + switch (request) { + case PTRACE_PEEKTEXT: + case PTRACE_PEEKDATA: +- case PTRACE_POKETEXT: +- case PTRACE_POKEDATA: + case PTRACE_ATTACH: +- case PTRACE_DETACH: + // Passthrough these requests. Allows Wine to run the Ubisoft launcher. + Result = ::syscall(SYSCALL_DEF(ptrace), request, pid, addr, data); + SYSCALL_ERRNO(); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 21816674e..602e17570 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -9,6 +9,13 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include + + #include + #include +@@ -252,8 +259,23 @@ uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t a + } + + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(read, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(read), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Read16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); ++ REGISTER_SYSCALL_IMPL(write, [](FEXCore::Core::CpuStateFrame* Frame, int fd, const void* buf, size_t count) -> uint64_t { ++ uint64_t Result = ::syscall(SYSCALL_DEF(write), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Write16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(lseek, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_yield, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(msync, SyscallPassthrough3); +@@ -264,14 +286,26 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6); +- REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6); ++ REGISTER_SYSCALL_IMPL(recvfrom, ++ [](FEXCore::Core::CpuStateFrame* Frame, int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, ++ socklen_t* addrlen) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, len); ++ uint64_t Result = ::syscall(SYSCALL_DEF(recvfrom), sockfd, buf, len, flags, src_addr, addrlen); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(socketpair, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(kill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(kill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, pid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(kill), pid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(semget, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(msgget, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(msgsnd, SyscallPassthrough4); +@@ -334,7 +368,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(fgetxattr, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL(flistxattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(fremovexattr, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(tkill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(tkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tkill), tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(sched_setaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(io_setup, SyscallPassthrough2); +@@ -344,7 +384,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(remap_file_pages, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(timer_getoverrun, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(timer_delete, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(tgkill, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(tgkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tgid, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, tgid); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tgkill), tgid, tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(mbind, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(set_mempolicy, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(get_mempolicy, SyscallPassthrough5); +@@ -459,7 +505,11 @@ namespace x64 { + RegisterCommon(Handler); + REGISTER_SYSCALL_IMPL_X64(ftruncate, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(ioctl, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X64(pread_64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count, off_t offset) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(pread_64), fd, buf, count, offset); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(pwrite_64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(readv, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(writev, SyscallPassthrough3); +@@ -473,7 +523,14 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5); +- REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(wait4, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int* status, int options, struct rusage* ru) -> uint64_t { ++ uint64_t Result; ++ do { ++ Result = ::syscall(SYSCALL_DEF(wait4), pid, status, options, ru); ++ Result = Result == -1 ? -errno : Result; ++ } while (static_cast(Result) > 0 && PtraceEmu::FixupWaitStatus(static_cast(Result), status)); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(getrusage, SyscallPassthrough2); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +index 8723026ef..1956b0d52 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +@@ -25,13 +25,27 @@ struct GuestSigAction; + namespace FEX::HLE { + void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(rt_sigprocmask, [](FEXCore::Core::CpuStateFrame* Frame, int how, const uint64_t* set, uint64_t* oldset) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), +- how, set, oldset); ++ uint64_t NewSet; ++ uint64_t OldSet; ++ if (set && FaultSafeUserMemAccess::CopyFromUser(&NewSet, set, sizeof(NewSet))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), how, set ? &NewSet : nullptr, oldset ? &OldSet : nullptr); ++ if (Result == 0 && oldset && FaultSafeUserMemAccess::CopyToUser(oldset, &OldSet, sizeof(OldSet))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigpending, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* set, size_t sigsetsize) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), set, +- sigsetsize); ++ uint64_t Pending {}; ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), &Pending, sigsetsize); ++ if (Result == 0 && FaultSafeUserMemAccess::CopyToUser(set, &Pending, std::min(sigsetsize, sizeof(Pending)))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigsuspend, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* unewset, size_t sigsetsize) -> uint64_t { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +index 2c3edeef1..5ce7ee8bd 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +@@ -27,7 +27,9 @@ struct CpuStateFrame; + + namespace FEX::HLE { + void RegisterStubs(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { SYSCALL_STUB(restart_syscall); }); ++ REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { ++ return -EINTR; ++ }); + + REGISTER_SYSCALL_IMPL(rseq, [](FEXCore::Core::CpuStateFrame* Frame, struct rseq* rseq, uint32_t rseq_len, int flags, uint32_t sig) -> uint64_t { + // We don't support this +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +index 0a51b98a3..de6daa958 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +@@ -8,6 +8,7 @@ $end_info$ + #include "CodeLoader.h" + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -43,6 +44,12 @@ $end_info$ + #include + #include + ++#ifndef PR_SET_SYSCALL_USER_DISPATCH ++#define PR_SET_SYSCALL_USER_DISPATCH 59 ++#define PR_SYS_DISPATCH_OFF 0 ++#define PR_SYS_DISPATCH_ON 1 ++#endif ++ + ARG_TO_STR(idtype_t, "%u") + + namespace FEX::HLE { +@@ -492,6 +499,30 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return FEX::HLE::_SyscallHandler->SeccompEmulator.Handle(Frame, Operation, 0, reinterpret_cast(arg3)); + } + case PR_GET_SECCOMP: return FEX::HLE::_SyscallHandler->SeccompEmulator.GetSeccomp(Frame); ++ case PR_SET_SYSCALL_USER_DISPATCH: { ++ auto& SUD = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch; ++ switch (arg2) { ++ case PR_SYS_DISPATCH_OFF: ++ if (arg3 || arg4 || arg5) { ++ return -EINVAL; ++ } ++ SUD = {}; ++ return 0; ++ case PR_SYS_DISPATCH_ON: ++ if (arg3 && arg3 + arg4 <= arg3) { ++ return -EINVAL; ++ } ++ if (arg5 && arg5 >= SyscallHandler::TASK_MAX_64BIT) { ++ return -EFAULT; ++ } ++ SUD.Offset = arg3; ++ SUD.Length = arg4; ++ SUD.Selector = arg5; ++ SUD.Enabled = true; ++ return 0; ++ default: return -EINVAL; ++ } ++ } + case PR_GET_AUXV: { + if (arg4 || arg5) { + return -EINVAL; +@@ -524,6 +555,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.gs_cached = addr; ++ Frame->State.gs_idx = 0; + Result = 0; + break; + case 0x1002: // ARCH_SET_FS +@@ -532,25 +564,26 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.fs_cached = addr; ++ Frame->State.fs_idx = 0; + Result = 0; + break; + case 0x1003: // ARCH_GET_FS +- *reinterpret_cast(addr) = Frame->State.fs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.fs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x1004: // ARCH_GET_GS +- *reinterpret_cast(addr) = Frame->State.gs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.gs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x3001: // ARCH_CET_STATUS + Result = -EINVAL; // We don't support CET, return EINVAL + break; + case 0x1011: // ARCH_GET_CPUID +- return 1; +- break; +- case 0x1012: // ARCH_SET_CPUID +- return -ENODEV; // Claim we don't support faulting on CPUID +- break; ++ return FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting() ? (Frame->CPUIDFault == 0) : 1; ++ case 0x1012: ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return -ENODEV; ++ } ++ Frame->CPUIDFault = addr ? 0 : 1; ++ return 0; + default: + LogMan::Msg::EFmt("Unknown prctl: 0x{:x}", code); + Result = -EINVAL; +@@ -571,6 +604,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + // Save telemetry if we're exiting. + FEX::HLE::_SyscallHandler->GetSignalDelegator()->SaveTelemetry(); + FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ FEX::HLE::SigTrace::CleanupForExit(); + + syscall(SYSCALL_DEF(exit_group), status); + // This will never be reached +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 5d6c850d8..f9e85a26f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -42,6 +42,40 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + } + } + ++void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping) { ++ auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }; ++ ++ if (Mapping.Flags.Shared) { ++ LOGMAN_THROW_A_FMT(Mapping.Resource, "VMA tracking error"); ++ ++ auto Offset = FaultBase - EntryBase + Mapping.Offset; ++ ++ auto VMA = Mapping.Resource->FirstVMA; ++ LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); ++ ++ do { ++ if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { ++ auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; ++ ++ if (VMA->Prot.Writable) { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBaseMirrored, _SyscallHandler->SMCHotPageFaults()); ++ } ++ } while ((VMA = VMA->ResourceNextVMA)); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBase, _SyscallHandler->SMCHotPageFaults()); ++ } ++} ++ + // Handles segfaults from: + // - call-ret shadow stack overflow + // - guest-side self-modifying code (SMC) +@@ -52,9 +86,11 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); + auto CallRetStackInfo = ThreadObject->GetCallRetStackInfo(); + if (FaultAddress >= CallRetStackInfo.AllocationBase && FaultAddress < CallRetStackInfo.AllocationEnd) { +- // Reset REG_CALLRET_SP to the default location to allow for underflows/overflows +- ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); +- return true; ++ const uint64_t CallRetSP = ArchHelpers::Context::GetArmReg(ucontext, 25); ++ if (FaultAddress - (CallRetSP - 16) < 32) { ++ ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); ++ return true; ++ } + } + + { +@@ -84,41 +120,16 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + + auto FaultBase = FEXCore::AlignDown(FaultAddress, FEXCore::Utils::FEX_PAGE_SIZE); +- +- auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { +- auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); +- LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); +- }; +- +- if (Entry->second.Flags.Shared) { +- LOGMAN_THROW_A_FMT(Entry->second.Resource, "VMA tracking error"); +- +- auto Offset = FaultBase - Entry->first + Entry->second.Offset; +- +- auto VMA = Entry->second.Resource->FirstVMA; +- LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); +- +- // Flush all mirrors, remap the page writable as needed +- do { +- if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { +- auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; +- +- if (VMA->Prot.Writable) { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); +- } +- } +- } while ((VMA = VMA->ResourceNextVMA)); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } ++ InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); + + FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedSMCCount, 1); + ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress > MaxStoreSize ? FaultAddress - MaxStoreSize : 0; ++ + auto CTX = Thread->CTX; + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)) && !CTX->IsCurrentBlockSingleInst(Thread) && +- CTX->IsAddressInCurrentBlock(Thread, FaultAddress & FEXCore::Utils::FEX_PAGE_MASK, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { + // If we are not in a single-instruction block, and the SMC write address could intersect with the current block, + // reconstruct the context and repeat the faulting instruction as a single-instruction block so any SMC it performs + // is immediately picked up. +@@ -134,6 +145,48 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK || Length == 0) [[likely]] { ++ return; ++ } ++ ++ const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); ++ const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? ++ UINT64_MAX : ++ reinterpret_cast(Buf) + Length - 1; ++ const uint64_t End = FEXCore::AlignDown(Last, FEXCore::Utils::FEX_PAGE_SIZE) + (Last >= UINT64_MAX - FEXCore::Utils::FEX_PAGE_SIZE ? 0 : FEXCore::Utils::FEX_PAGE_SIZE); ++ ++ auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ auto Entry = VMATracking.VMAs.upper_bound(Start); ++ if (Entry != VMATracking.VMAs.begin() && std::prev(Entry)->first + std::prev(Entry)->second.Length > Start) { ++ --Entry; ++ } ++ ++ for (; Entry != VMATracking.VMAs.end() && Entry->first < End; ++Entry) { ++ const auto& Mapping = Entry->second; ++ if (!Mapping.Prot.Writable || !(Mapping.Prot.Executable || Mapping.Flags.Shared)) [[likely]] { ++ continue; ++ } ++ const uint64_t From = std::max(Start, Entry->first); ++ const uint64_t To = std::min(End, Entry->first + Mapping.Length); ++ if (Mapping.Flags.Shared) { ++ for (uint64_t Page = From; Page < To; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ InvalidateWrittenCodePage(Thread, Page, Entry->first, Mapping); ++ } ++ } else { ++ TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ } ++} ++ ++bool SyscallHandler::IsSMCHotPage(uint64_t Address) { ++ return SMCHotPages.IsHot(Address); ++} ++ + void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + const auto Base = Start & FEXCore::Utils::FEX_PAGE_MASK; + const auto Top = FEXCore::AlignUp(Start + Length, FEXCore::Utils::FEX_PAGE_SIZE); +@@ -143,6 +196,18 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + return; + } + ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ if (SMCHotPages.IsHot(Page)) { ++ if (Page > Base) { ++ MarkGuestExecutableRange(Thread, Base, Page - Base); ++ } ++ if (Page + FEXCore::Utils::FEX_PAGE_SIZE < Top) { ++ MarkGuestExecutableRange(Thread, Page + FEXCore::Utils::FEX_PAGE_SIZE, Top - (Page + FEXCore::Utils::FEX_PAGE_SIZE)); ++ } ++ return; ++ } ++ } ++ + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + + // Find the first mapping at or after the range ends, or ::end(). +@@ -407,16 +472,24 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto lk = FEXCore::GuardSignalDeferringSectionWithFallback(VMATracking.Mutex, Thread); + +- if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ if (!Is64Bit) { + Result = Get32BitAllocator()->Munmap(addr, length); + if (FEX::HLE::HasSyscallError(Result)) { + return Result; + } + } else { ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ const uint64_t Addr = reinterpret_cast(addr); ++ if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { ++ return -EINVAL; ++ } + Result = ::munmap(addr, length); + if (Result == -1) { + return -errno; + } ++ if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ Get32BitAllocator()->TrackUnmapped(addr, length); ++ } + } + TrackMunmap(Thread, addr, length); + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); +@@ -514,6 +587,21 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ fextl::vector UnlockedCode; ++ constexpr uint64_t MaxUnlockedCodePages = 64; ++ const auto Base = reinterpret_cast(addr) & FEXCore::Utils::FEX_PAGE_MASK; ++ const auto Top = FEXCore::AlignUp(reinterpret_cast(addr) + len, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (SMCChecks == FEXCore::Config::CONFIG_SMC_MTRACK && SMCHotPageFaults() && (prot & PROT_WRITE) && (prot & PROT_EXEC) && ++ Top > Base && (Top - Base) / FEXCore::Utils::FEX_PAGE_SIZE <= MaxUnlockedCodePages) { ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry != VMATracking.VMAs.end() && Entry->second.Prot.Executable && !Entry->second.Prot.Writable) { ++ UnlockedCode.push_back(Page); ++ } ++ } ++ } ++ + Result = ::mprotect(addr, len, prot); + if (Result == -1) { + return -errno; +@@ -523,6 +611,10 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + if (prot & PROT_WRITE) { + ProtectWritableAliasOfCode(reinterpret_cast(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); + } ++ ++ for (auto Page : UnlockedCode) { ++ SMCHotPages.MarkHot(Page); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast(addr), len, false); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 69e10b3d2..e13cb1ca9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" +@@ -158,6 +159,16 @@ void ThreadManager::StatAlloc::UnlockAfterFork(FEXCore::Core::InternalThreadStat + ThreadObject->Thread->ThreadStats = AllocateSlot(ThreadObject->ThreadInfo.TID); + } + ++static thread_local FEX::HLE::ThreadStateObject* CurrentThreadObject {}; ++ ++FEX::HLE::ThreadStateObject* ThreadManager::GetCurrentThreadObject() { ++ return CurrentThreadObject; ++} ++ ++void ThreadManager::SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread) { ++ CurrentThreadObject = Thread; ++} ++ + uint64_t ThreadManager::SetSignalMask(uint64_t Mask) { + ::syscall(SYSCALL_DEF(rt_sigprocmask), SIG_SETMASK, &Mask, &Mask, 8); + return Mask; +@@ -196,6 +207,16 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + Frame->State.callret_sp = ThreadStateObject->GetCallRetStackInfo().DefaultLocation; + + ThreadStateObject->Thread->FrontendPtr = ThreadStateObject; ++ ++ { ++ static std::atomic ThreadCount {0}; ++ FEX_CONFIG_OPT(ProfileSampleHz, PROFILESAMPLEHZ); ++ FEX_CONFIG_OPT(ProfileSampleAllThreads, PROFILESAMPLEALLTHREADS); ++ FEX_CONFIG_OPT(ProfileSampleMinThreads, PROFILESAMPLEMINTHREADS); ++ if (ProfileSampleHz() && ThreadCount.fetch_add(1) + 1 == std::max(ProfileSampleMinThreads(), 1)) { ++ StartSamplingProfiler(SignalDelegation, ProfileSampleHz(), ProfileSampleAllThreads(), ProfileSampleMinThreads() == 0); ++ } ++ } + if (ProfileStats()) { + ThreadStateObject->Thread->ThreadStats = Stat.AllocateSlot(ThreadStateObject->ThreadInfo.TID); + } +@@ -221,8 +242,8 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + } + } else { + // Without any thread data to inherit, setup the default gdt. +- // Default code segment indexes match the numbers that the Linux kernel uses. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; ++ Frame->State.cs_idx = ++ Is64BitMode() ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; + auto GDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.cs_idx); + FEXCore::Core::CPUState::SetGDTBase(GDT, 0); + FEXCore::Core::CPUState::SetGDTLimit(GDT, 0xF'FFFFU); +@@ -236,11 +257,20 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + GDT->L = 0; // L = Long Mode = 32-bit + GDT->D = 1; // D = Default Operand Size = 32-bit + } ++ ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; ++ auto SSGDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.ss_idx); ++ FEXCore::Core::CPUState::SetGDTBase(SSGDT, 0); ++ FEXCore::Core::CPUState::SetGDTLimit(SSGDT, 0xF'FFFFU); ++ SSGDT->L = 0; ++ SSGDT->D = 1; ++ Frame->State.ss_cached = FEXCore::Core::CPUState::CalculateGDTBase(*SSGDT); + } + + if (InheritThread) { + FEX::HLE::_SyscallHandler->SeccompEmulator.InheritSeccompFilters(InheritThread, ThreadStateObject); + ThreadStateObject->persona = InheritThread->persona; ++ Frame->CPUIDFault = InheritThread->Thread->CurrentFrame->CPUIDFault; + } else { + ThreadStateObject->persona = ::personality(0xffffffff); + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index e4a86a946..c5bfe3c25 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -15,6 +15,7 @@ $end_info$ + + #include + #include ++#include + #include + #include + #include +@@ -68,6 +69,7 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + SignalDelegator* Delegator {}; + + void* AltStackPtr {}; ++ bool AltStackReleaseDeferred {}; + stack_t GuestAltStack { + .ss_sp = nullptr, + .ss_flags = SS_DISABLE, // By default the guest alt stack is disabled +@@ -92,6 +94,27 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + uint32_t SeccompMode {SECCOMP_MODE_DISABLED}; + fextl::vector Filters {}; + ++ uint64_t SeccompTrapRIP {}; ++ ++ struct { ++ uint64_t Offset; ++ uint64_t Length; ++ uint64_t Selector; ++ bool Enabled; ++ } SyscallUserDispatch {}; ++ ++ uint64_t JITStackSP {}; ++ ++ struct TrapSignalFrame { ++ uint64_t GuestFrame; ++ uint64_t GuestRSP; ++ uint64_t JITStackSP; ++ uint64_t ContextBackup; ++ }; ++ static constexpr size_t MaxTrapSignalFrames = 16; ++ TrapSignalFrame TrapSignalFrames[MaxTrapSignalFrames] {}; ++ size_t TrapSignalFrameCount {}; ++ + // personality emulation. + uint32_t persona {}; + +@@ -189,6 +212,11 @@ public: + return static_cast(Thread->FrontendPtr); + } + ++ static FEX::HLE::ThreadStateObject* GetCurrentThreadObject(); ++ static void SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread); ++ ++ FEX_CONFIG_OPT(EnableCPUIDFaulting, ENABLECPUIDFAULTING); ++ + FEX::HLE::ThreadStateObject* CreateThread(const FEXCore::Core::CPUState* NewThreadState = nullptr, uint64_t ParentTID = 0, + FEX::HLE::ThreadStateObject* InheritThread = nullptr); + void TrackThread(FEX::HLE::ThreadStateObject* Thread) { +@@ -219,29 +247,38 @@ public: + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ const bool HadCode = CTX->InvalidateCodeBuffersCodeRange(Start, Length); ++ if (HadCode) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length, + FEXCore::Context::CodeRangeInvalidationFn after_callback) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ if (CTX->InvalidateCodeBuffersCodeRange(Start, Length)) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + + // Callback while holding the locks. +@@ -253,6 +290,20 @@ public: + } + + private: ++ struct InvalidationStats { ++ explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) ++ : Thread {Thread} ++ , Begin {Thread && Thread->ThreadStats ? FEXCore::SHMStats::GetCycleCounter() : 0} {} ++ ~InvalidationStats() { ++ if (Thread && Thread->ThreadStats) { ++ Thread->ThreadStats->AccumulatedInvalidationCount += 1; ++ Thread->ThreadStats->AccumulatedInvalidationTime += FEXCore::SHMStats::GetCycleCounter() - Begin; ++ } ++ } ++ FEXCore::Core::InternalThreadState* Thread; ++ uint64_t Begin; ++ }; ++ + StatAlloc Stat; + FEXCore::Context::Context* CTX; + FEX::HLE::SignalDelegator* SignalDelegation; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +index 8b9c25948..3b37e4a3e 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +@@ -347,6 +347,7 @@ namespace PThreads { + Thread->detach(); + + if (LongJumpExit) { ++ FEX::HLE::_SyscallHandler->ReleaseDeferredTLSState(ThreadObject); + // We have ownership of the thread object. Make sure to clean it up to prevent memory leaks. + FEX::HLE::_SyscallHandler->TM.DestroyThread(ThreadObject, true); + if (Status == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +index 361bfbec1..25b3b0742 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +@@ -802,6 +802,7 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X32( + pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, uint32_t count, uint32_t offset_low, uint32_t offset_high) -> uint64_t { + uint64_t Offset = (uint64_t(offset_high) << 32) | offset_low; ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); + uint64_t Result = ::pread64(fd, buf, count, Offset); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +index d1ab9cdf8..84c612940 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +@@ -6,6 +6,7 @@ tags: LinuxSyscalls|syscalls-x86-64 + $end_info$ + */ + ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Types.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -14,6 +15,7 @@ $end_info$ + #include + + #include ++#include + #include + #include + #include +@@ -50,6 +52,9 @@ void RegisterEpoll(FEX::HLE::SyscallHandler* Handler) { + EventPtr = &Event; + } + uint64_t Result = ::syscall(SYSCALL_DEF(epoll_ctl), epfd, op, fd, EventPtr); ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::EpollCtl, op, fd, (EventPtr ? EventPtr->events : 0) | (Result << 32)); ++ } + if (Result != -1 && event) { + FaultSafeUserMemAccess::VerifyIsWritable(event, sizeof(FEX::HLE::epoll_event_x86)); + *event = Event; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +index 91b5a103d..4eab76a59 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +@@ -63,14 +63,16 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(stat, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Stat(pathname, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -79,36 +81,41 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + struct stat host_stat; + uint64_t Result = ::fstat(fd, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64(lstat, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Lstat(path, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64( + newfstatat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, FEX::HLE::x64::guest_stat* buf, int flag) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.NewFSStatAt(dirfd, pathname, &host_stat, flag); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -140,8 +147,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(statfs, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, struct statfs* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Statfs(path, buf); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +index 36726ece6..c7b39bb46 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +@@ -25,10 +25,18 @@ void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + if (sigsetsize != 8) { + return -EINVAL; + } +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(act, sizeof(GuestSigAction)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(oldact, sizeof(GuestSigAction)); ++ GuestSigAction NewAct; ++ GuestSigAction OldAct; ++ if (act && FaultSafeUserMemAccess::CopyFromUser(&NewAct, act, sizeof(NewAct))) { ++ return -EFAULT; ++ } + +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act, oldact); ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act ? &NewAct : nullptr, ++ oldact ? &OldAct : nullptr); ++ if (Result == 0 && oldact && FaultSafeUserMemAccess::CopyToUser(oldact, &OldAct, sizeof(OldAct))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL_X64( +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +index c25ff5b94..0ec2933bc 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +@@ -233,6 +233,22 @@ enum Modify_ldt_func : int32_t { + LDT_WRITE = 0x11, + }; + ++static bool GatherStringArray(char* const* User, fextl::vector& Out) { ++ for (size_t i = 0;; ++i) { ++ const char* Str; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Str, &User[i], sizeof(Str))) { ++ return false; ++ } ++ Out.push_back(Str); ++ if (!Str) { ++ return true; ++ } ++ if (!FaultSafeUserMemAccess::IsStringReadable(Str)) { ++ return false; ++ } ++ } ++} ++ + void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X64(modify_ldt, [](FEXCore::Core::CpuStateFrame* Frame, int func, void* ptr, unsigned long bytecount) -> uint64_t { + switch (func) { +@@ -278,10 +294,17 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + })); + + REGISTER_SYSCALL_IMPL_X64(sigaltstack, [](FEXCore::Core::CpuStateFrame* Frame, const stack_t* ss, stack_t* old_ss) -> uint64_t { +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(ss, sizeof(*ss)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(old_ss, sizeof(*old_ss)); +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( +- FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss, old_ss); ++ stack_t NewStack; ++ stack_t OldStack; ++ if (ss && FaultSafeUserMemAccess::CopyFromUser(&NewStack, ss, sizeof(NewStack))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss ? &NewStack : nullptr, old_ss ? &OldStack : nullptr); ++ if (Result == 0 && old_ss && FaultSafeUserMemAccess::CopyToUser(old_ss, &OldStack, sizeof(OldStack))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + // launch a new process under fex +@@ -290,20 +313,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + auto* const* ArgsPtr = argv ? const_cast(Args.data()) : nullptr; +@@ -319,20 +331,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + FEX::HLE::ExecveAtArgs AtArgs {