FEX: restore stranded aio words before readable protection, report failures

Restore every pending aio word in the range before a readable guest
protection is applied, on both the high and low paths, and fail the guest
mprotect with the old protection kept when a word cannot be restored or its
window cannot be closed. Ignore user-sent SIGSEGV/SIGBUS after deferral,
read the cleared syscall info when resuming with guest GPRs and on restore,
and check exclusive acquisition from a separate thread in the harness.
This commit is contained in:
maxjivi05 committed 2026-12-04 19:19:28 -05:00
1 parent 6f3b66af49
commit 25d0a3df8d
4 files changed
+422 -144

No files matched your search

@@ -977,7 +977,7 @@ index e7e88f8f2..26b8186c8 100644
SyscallHandler->DeserializeSeccompFD(ParentThread, FEXSeccompFD);
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
index 2e724929f..980aec485 100644
index 2e724929f..62135b824 100644
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
@@ -20,6 +20,7 @@ namespace FEX::ArchHelpers::Context {
@@ -1012,6 +1012,18 @@ index 2e724929f..980aec485 100644
// Guest state
int Signal;
@@ -92,6 +101,11 @@ struct ArmContextBackup {
static constexpr int RedZoneSize = 0;
};
+template<typename Backup>
+static inline uint16_t SavedSyscallInfo(const Backup* Context) {
+ return (Context->Flags & CONTEXT_FLAG_SYSCALLINFO_CLEARED) ? Context->ClearedSyscallInfo : Context->InSyscallInfo;
+}
+
static inline ucontext_t* GetUContext(void* ucontext) {
ucontext_t* _context = (ucontext_t*)ucontext;
return _context;
diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt
index 715a8f132..3f02104ea 100644
--- a/Source/Tools/LinuxEmulation/CMakeLists.txt
@@ -2905,7 +2917,7 @@ index a4c7b70e0..31b489216 100644
// Multiple filter instruction count penalty.
// When multiple filters are installed there is a penalty per filter counted towards the maximum number of instructions.
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index e8e04b056..c6ef3fe04 100644
index e8e04b056..87b890e19 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -8,6 +8,8 @@ $end_info$
@@ -2937,7 +2949,7 @@ index e8e04b056..c6ef3fe04 100644
void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thread, void* ucontext, RestoreType Type) {
uint64_t OldSP {};
if (Type == RestoreType::TYPE_PAUSE) [[unlikely]] {
@@ -315,8 +323,38 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
@@ -315,8 +323,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
uintptr_t NewSP = OldSP;
auto Context = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(NewSP);
@@ -2953,9 +2965,7 @@ index e8e04b056..c6ef3fe04 100644
+
// Restore host state
ArchHelpers::Context::RestoreContext(ucontext, Context);
+ Thread->CurrentFrame->InSyscallInfo = (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_SYSCALLINFO_CLEARED) ?
+ Context->ClearedSyscallInfo :
+ Context->InSyscallInfo;
+ Thread->CurrentFrame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context);
+
+ {
+ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
@@ -2976,7 +2986,16 @@ index e8e04b056..c6ef3fe04 100644
// Reset the guest state
memcpy(&Thread->CurrentFrame->State, &Context->GuestState, sizeof(FEXCore::Core::CPUState));
@@ -343,7 +381,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
@@ -327,7 +363,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
// XXX: Unsupported since it needs state reconstruction
// If we are in the JIT then SRA might need to be restored to values from the context
// We can't currently support this since it might result in tearing without real state reconstruction
- Frame->InSyscallInfo = Context->InSyscallInfo;
+ Frame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context);
if (Is64BitMode) {
RestoreFrame_x64(Thread, Context, Frame, ucontext);
@@ -343,7 +379,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) {
@@ -3013,7 +3032,7 @@ index e8e04b056..c6ef3fe04 100644
auto Frame = Thread->CurrentFrame;
auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
@@ -382,8 +449,13 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -382,8 +447,13 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
Thread->CurrentFrame->InSyscallInfo = 0;
} else {
@@ -3029,7 +3048,7 @@ index e8e04b056..c6ef3fe04 100644
if (!IsAddressInDispatcher(OldPC)) {
// This is likely to cause issues but in some cases it isn't fatal
@@ -462,6 +534,14 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -462,6 +532,14 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
if (Is64BitMode) {
NewGuestSP = SetupFrame_x64(Thread, ContextBackup, Frame, Signal, HostSigInfo, ucontext, GuestAction, GuestStack, NewGuestSP, eflags);
@@ -3044,7 +3063,7 @@ index e8e04b056..c6ef3fe04 100644
} else {
const bool SigInfoFrame = (GuestAction->sa_flags & SA_SIGINFO) == SA_SIGINFO;
if (SigInfoFrame) {
@@ -483,8 +563,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -483,8 +561,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.
@@ -3055,7 +3074,7 @@ index e8e04b056..c6ef3fe04 100644
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));
@@ -690,7 +770,7 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState*
@@ -690,7 +768,7 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState*
auto SigInfo = *static_cast<siginfo_t*>(Info);
if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) {
@@ -3064,7 +3083,7 @@ index e8e04b056..c6ef3fe04 100644
}
#ifdef ARCHITECTURE_arm64
@@ -714,10 +794,21 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState*
@@ -714,10 +792,21 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState*
void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObject, int Signal, void* Info, void* UContext) {
auto Thread = ThreadObject->Thread;
@@ -3086,7 +3105,7 @@ index e8e04b056..c6ef3fe04 100644
if (Signal == SIGSEGV && SigInfo.si_code == SEGV_ACCERR && SigInfo.si_addr == reinterpret_cast<void*>(&Thread->InterruptFaultPage)) {
if (!MustDeferSignal) {
// We just reached the end of the outermost signal-deferring section and faulted to check for pending signals.
@@ -781,6 +872,8 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec
@@ -781,6 +870,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);
@@ -3095,7 +3114,7 @@ index e8e04b056..c6ef3fe04 100644
// Now update the faulting page permissions so it will fault on write.
mprotect(reinterpret_cast<void*>(&Thread->InterruptFaultPage), sizeof(Thread->InterruptFaultPage), PROT_NONE);
@@ -793,6 +886,7 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec
@@ -793,6 +884,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);
@@ -3103,7 +3122,7 @@ index e8e04b056..c6ef3fe04 100644
return;
}
@@ -814,6 +908,21 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec
@@ -814,6 +906,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);
@@ -3125,7 +3144,7 @@ index e8e04b056..c6ef3fe04 100644
// 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
@@ -961,6 +1070,30 @@ void SignalDelegator::UninstallHostHandler(int Signal) {
@@ -961,6 +1068,30 @@ void SignalDelegator::UninstallHostHandler(int Signal) {
::syscall(SYS_rt_sigaction, Signal, &SignalHandler.OldAction, nullptr, 8);
}
@@ -3156,7 +3175,7 @@ index e8e04b056..c6ef3fe04 100644
void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask) {
bool WasIgnored {};
bool WasMasked {};
@@ -995,11 +1128,34 @@ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t*
@@ -995,11 +1126,34 @@ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t*
}
}
@@ -3191,7 +3210,7 @@ index e8e04b056..c6ef3fe04 100644
// Signal zero isn't real
HostHandlers[0].Installed = true;
@@ -1162,23 +1318,36 @@ void SignalDelegator::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) {
@@ -1162,23 +1316,36 @@ void SignalDelegator::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) {
}
}
@@ -3235,7 +3254,7 @@ index e8e04b056..c6ef3fe04 100644
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
@@ -1321,6 +1490,7 @@ static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread) {
@@ -1321,6 +1488,7 @@ static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread) {
if (PendingSignals != 0) {
for (int i = 0; i < 64; ++i) {
if (PendingSignals & (1ULL << i)) {
@@ -3243,7 +3262,7 @@ index e8e04b056..c6ef3fe04 100644
FHU::Syscalls::tgkill(Thread->ThreadInfo.PID, Thread->ThreadInfo.TID, i + 1);
// We might not even return here which is spooky
}
@@ -1361,6 +1531,9 @@ uint64_t SignalDelegator::GuestSigProcMask(FEX::HLE::ThreadStateObject* Thread,
@@ -1361,6 +1529,9 @@ uint64_t SignalDelegator::GuestSigProcMask(FEX::HLE::ThreadStateObject* Thread,
}
::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &HostMask, nullptr, 8);
@@ -3287,7 +3306,7 @@ index 43898e700..0d5b5597d 100644
FEX_CONFIG_OPT(HalfBarrierTSOEnabled, HALFBARRIERTSOENABLED);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
index 38dc524f1..87199e10c 100644
index 38dc524f1..d0bcdbecb 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -7,6 +7,7 @@ $end_info$
@@ -3314,7 +3333,7 @@ index 38dc524f1..87199e10c 100644
namespace FEX::HLE {
constexpr uint32_t X86_SA_RESTORER = 0x04000000;
@@ -106,19 +111,35 @@ template<typename T>
@@ -106,26 +111,42 @@ template<typename T>
static void SetXStateInfo(T* xstate, bool is_avx_enabled) {
auto* fpstate = &xstate->fpstate;
@@ -3356,6 +3375,14 @@ index 38dc524f1..87199e10c 100644
}
}
void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) {
#ifdef ARCHITECTURE_arm64
- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;
+ const uint32_t Spilled = ArchHelpers::Context::SavedSyscallInfo(Context) & 0xFFFF;
const bool AllSpilled = Spilled == 0xFFFF;
if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {
return;
@@ -153,14 +174,19 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
[[maybe_unused]] auto* guest_siginfo = reinterpret_cast<siginfo_t*>(Context->SigInfoLocation);
@@ -13,20 +13,20 @@ writes to code in them invalidate translated blocks.
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
Source/Tools/LinuxEmulation/CMakeLists.txt | 1 +
.../LinuxSyscalls/GuestHighMemory.cpp | 2546 +++++++++++++++++
.../LinuxSyscalls/GuestHighMemory.cpp | 2598 +++++++++++++++++
.../LinuxSyscalls/GuestHighMemory.h | 65 +
.../LinuxSyscalls/SignalDelegator.cpp | 5 +
.../LinuxEmulation/LinuxSyscalls/Syscalls.cpp | 53 +-
.../LinuxSyscalls/Syscalls/Memory.cpp | 30 +
.../LinuxSyscalls/SyscallsSMCTracking.cpp | 65 +-
.../LinuxSyscalls/SyscallsSMCTracking.cpp | 68 +-
.../LinuxSyscalls/ThreadManager.cpp | 2 +
.../LinuxSyscalls/ThreadManager.h | 34 +
9 files changed, 2771 insertions(+), 30 deletions(-)
9 files changed, 2826 insertions(+), 30 deletions(-)
create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt
index 3f02104ea..acf4c4c13 100644
index 3f02104..acf4c4c 100644
--- a/Source/Tools/LinuxEmulation/CMakeLists.txt
+++ b/Source/Tools/LinuxEmulation/CMakeLists.txt
@@ -18,6 +18,7 @@ add_library(LinuxEmulation STATIC
@@ -39,10 +39,10 @@ index 3f02104ea..acf4c4c13 100644
LinuxSyscalls/SyscallsVMATracking.cpp
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
new file mode 100644
index 000000000..13f9e70e9
index 0000000..fa73c20
--- /dev/null
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
@@ -0,0 +1,2546 @@
@@ -0,0 +1,2598 @@
+#include "LinuxSyscalls/GuestHighMemory.h"
+#include "LinuxSyscalls/Syscalls.h"
+#include "LinuxSyscalls/SignalDelegator.h"
@@ -53,14 +53,17 @@ index 000000000..13f9e70e9
+#include <FEXCore/Debug/InternalThreadState.h>
+#include <FEXCore/Utils/Allocator.h>
+#include <FEXCore/Utils/AllocatorHooks.h>
+#include <FEXCore/Utils/FileLoading.h>
+#include <FEXCore/Utils/MathUtils.h>
+#include <FEXCore/Utils/SignalScopeGuards.h>
+#include <FEXCore/Utils/TypeDefines.h>
+#include <FEXCore/fextl/string.h>
+
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <cerrno>
+#include <charconv>
+#include <csignal>
+#include <cstddef>
+#include <cstring>
@@ -69,6 +72,7 @@ index 000000000..13f9e70e9
+#include <iterator>
+#include <mutex>
+#include <shared_mutex>
+#include <string_view>
+#include <sys/mman.h>
+#include <sys/syscall.h>
+#include <unistd.h>
@@ -1865,50 +1869,68 @@ index 000000000..13f9e70e9
+ PendingCount.store(PendingRestores.size(), std::memory_order_release);
+ }
+
+ bool RestoreInWindow(const SavedWord& Saved, int Prot) {
+ uint64_t Host {};
+ if (!TranslateRange(Saved.Address, sizeof(Saved.Value), &Host) || Host != Saved.Host || !HostMapped(Host, sizeof(Saved.Value))) {
+ return true;
+ }
+ constexpr uint64_t Mask = FEXCore::Utils::FEX_PAGE_SIZE - 1;
+ const auto First = Host & ~Mask;
+ const auto Span = ((Host + sizeof(Saved.Value) - 1) & ~Mask) - First + FEXCore::Utils::FEX_PAGE_SIZE;
+ auto* Window = reinterpret_cast<void*>(First);
+ if (::mprotect(Window, Span, PROT_READ | PROT_WRITE) != 0) {
+ bool PageProtection(uint64_t Page, int* Prot) {
+ fextl::string Maps;
+ if (!FEXCore::FileLoading::LoadFile(Maps, "/proc/self/maps")) {
+ return false;
+ }
+ uint64_t Current {};
+ auto* Word = reinterpret_cast<void*>(Host);
+ const bool Restored = FaultSafeUserMemAccess::CopyFromUser(&Current, Word, sizeof(Current)) == 0 &&
+ (Current != Saved.Patched || FaultSafeUserMemAccess::CopyToUser(Word, &Saved.Value, sizeof(Saved.Value)) == 0);
+ ::mprotect(Window, Span, Prot);
+ return Restored;
+ std::string_view Rest {Maps};
+ while (!Rest.empty()) {
+ const auto LineEnd = std::min(Rest.find('\n'), Rest.size());
+ const auto Line = Rest.substr(0, LineEnd);
+ Rest.remove_prefix(std::min(LineEnd + 1, Rest.size()));
+ const auto Dash = Line.find('-');
+ const auto Space = Line.find(' ');
+ if (Dash == std::string_view::npos || Space == std::string_view::npos || Dash > Space || Line.size() < Space + 4) {
+ continue;
+ }
+ uint64_t Start {};
+ uint64_t End {};
+ if (std::from_chars(Line.data(), Line.data() + Dash, Start, 16).ec != std::errc {} ||
+ std::from_chars(Line.data() + Dash + 1, Line.data() + Space, End, 16).ec != std::errc {}) {
+ continue;
+ }
+ if (Page >= Start && Page < End) {
+ *Prot = (Line[Space + 1] == 'r' ? PROT_READ : 0) | (Line[Space + 2] == 'w' ? PROT_WRITE : 0) | (Line[Space + 3] == 'x' ? PROT_EXEC : 0);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void RestoreProtected(uint64_t Address, uint64_t Length, int Prot) {
+ ReconcilePending();
+ if (PendingCount.load(std::memory_order_acquire) == 0) {
+ return;
+ int RestoreInWindow(const SavedWord& Saved, bool* Restored) {
+ *Restored = false;
+ uint64_t Host {};
+ if (!TranslateRange(Saved.Address, sizeof(Saved.Value), &Host) || Host != Saved.Host || !HostMapped(Host, sizeof(Saved.Value))) {
+ *Restored = true;
+ return 0;
+ }
+ const auto End = FEXCore::AlignUp(Address + Length, FEXCore::Utils::FEX_PAGE_SIZE);
+ auto lk = FEXCore::MaskSignalsAndLockMutex(PendingMutex, ~HeldSignalMask());
+ fextl::vector<PendingRestore> Left;
+ for (auto& Pending : PendingRestores) {
+ fextl::vector<SavedWord> Kept;
+ for (auto Saved = Pending.Words.rbegin(); Saved != Pending.Words.rend(); ++Saved) {
+ const bool Inside = Saved->Address >= Address && Saved->Address + sizeof(Saved->Value) <= End;
+ if (!Inside || !RestoreInWindow(*Saved, Prot)) {
+ Kept.push_back(*Saved);
+ }
+ }
+ std::reverse(Kept.begin(), Kept.end());
+ Pending.Words = std::move(Kept);
+ if (!Pending.Words.empty()) {
+ Left.push_back(std::move(Pending));
+ constexpr uint64_t Mask = FEXCore::Utils::FEX_PAGE_SIZE - 1;
+ const uint64_t Pages[2] = {Host & ~Mask, (Host + sizeof(Saved.Value) - 1) & ~Mask};
+ const size_t Count = Pages[0] == Pages[1] ? 1 : 2;
+ int Old[2] {};
+ for (size_t i = 0; i < Count; ++i) {
+ if (!PageProtection(Pages[i], &Old[i])) {
+ return 0;
+ }
+ }
+ PendingRestores = std::move(Left);
+ PendingCount.store(PendingRestores.size(), std::memory_order_release);
+ size_t Opened = 0;
+ while (Opened < Count && ::mprotect(reinterpret_cast<void*>(Pages[Opened]), FEXCore::Utils::FEX_PAGE_SIZE, PROT_READ | PROT_WRITE) == 0) {
+ ++Opened;
+ }
+ if (Opened == Count) {
+ uint64_t Current {};
+ auto* Word = reinterpret_cast<void*>(Host);
+ *Restored = FaultSafeUserMemAccess::CopyFromUser(&Current, Word, sizeof(Current)) == 0 &&
+ (Current != Saved.Patched || FaultSafeUserMemAccess::CopyToUser(Word, &Saved.Value, sizeof(Saved.Value)) == 0);
+ }
+ int Result = 0;
+ for (size_t i = 0; i < Opened; ++i) {
+ if (::mprotect(reinterpret_cast<void*>(Pages[i]), FEXCore::Utils::FEX_PAGE_SIZE, Old[i]) != 0) {
+ Result = -errno;
+ }
+ }
+ return Result;
+ }
+
+ bool ReserveSlot(ArgumentStorage* Storage) {
@@ -2189,8 +2211,12 @@ index 000000000..13f9e70e9
+}
+
+uint64_t Protect(uint64_t Address, uint64_t Length, int Prot) {
+ uint64_t Result = RestoreBeforeProtect(Address, Length, Prot);
+ if (Result != 0) {
+ return Result;
+ }
+ BeginWrite();
+ uint64_t Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [](void*, uint64_t, uint32_t) { return 0; });
+ Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [](void*, uint64_t, uint32_t) { return 0; });
+ if (Result == 0) {
+ Result = SplitLocked(Address, Length);
+ }
@@ -2205,11 +2231,7 @@ index 000000000..13f9e70e9
+ CoalesceLocked(Address, Address + std::min(FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE), TaskTop - Address));
+ }
+ EndWrite();
+ if (Result == 0) {
+ RestoreProtected(Address, Length, Prot);
+ } else {
+ ReconcilePending();
+ }
+ ReconcilePending();
+ return Result;
+}
+
@@ -2328,8 +2350,38 @@ index 000000000..13f9e70e9
+ ReconcilePending();
+}
+
+void ReconcileProtected(uint64_t Address, uint64_t Length, int Prot) {
+ RestoreProtected(Address, Length, Prot);
+uint64_t RestoreBeforeProtect(uint64_t Address, uint64_t Length, int Prot) {
+ ReconcilePending();
+ if (Prot == PROT_NONE || PendingCount.load(std::memory_order_acquire) == 0) {
+ return 0;
+ }
+ const auto End = FEXCore::AlignUp(Address + Length, FEXCore::Utils::FEX_PAGE_SIZE);
+ auto lk = FEXCore::MaskSignalsAndLockMutex(PendingMutex, ~HeldSignalMask());
+ uint64_t Result = 0;
+ fextl::vector<PendingRestore> Left;
+ for (auto& Pending : PendingRestores) {
+ fextl::vector<SavedWord> Kept;
+ for (auto Saved = Pending.Words.rbegin(); Saved != Pending.Words.rend(); ++Saved) {
+ bool Restored = false;
+ if (Result == 0 && Saved->Address < End && Saved->Address + sizeof(Saved->Value) > Address) {
+ Result = RestoreInWindow(*Saved, &Restored);
+ if (Result == 0 && !Restored) {
+ Result = -ENOMEM;
+ }
+ }
+ if (!Restored) {
+ Kept.push_back(*Saved);
+ }
+ }
+ std::reverse(Kept.begin(), Kept.end());
+ Pending.Words = std::move(Kept);
+ if (!Pending.Words.empty()) {
+ Left.push_back(std::move(Pending));
+ }
+ }
+ PendingRestores = std::move(Left);
+ PendingCount.store(PendingRestores.size(), std::memory_order_release);
+ return Result;
+}
+
+bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread) {
@@ -2413,7 +2465,7 @@ index 000000000..13f9e70e9
+ return false;
+ }
+
+ if (!Contains(FaultAddress) || Trap.Active || Trap.Mappings.Held) {
+ if (SigInfo->si_code <= SI_USER || !Contains(FaultAddress) || Trap.Active || Trap.Mappings.Held) {
+ return false;
+ }
+
@@ -2591,7 +2643,7 @@ index 000000000..13f9e70e9
+} // namespace FEX::HLE::GuestHighMemory
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
new file mode 100644
index 000000000..28341bf50
index 0000000..a73d88e
--- /dev/null
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
@@ -0,0 +1,65 @@
@@ -2653,7 +2705,7 @@ index 000000000..28341bf50
+uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t Count, ArgumentStorage* Storage);
+uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage);
+void ReconcileRestores();
+void ReconcileProtected(uint64_t Address, uint64_t Length, int Prot);
+uint64_t RestoreBeforeProtect(uint64_t Address, uint64_t Length, int Prot);
+bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread);
+bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext);
+bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext);
@@ -2661,7 +2713,7 @@ index 000000000..28341bf50
+void ReleaseThread(FEX::HLE::ThreadStateObject* Thread);
+} // namespace FEX::HLE::GuestHighMemory
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index c6ef3fe04..22a5a7f36 100644
index 87b890e..ababed9 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -7,6 +7,7 @@ $end_info$
@@ -2672,7 +2724,7 @@ index c6ef3fe04..22a5a7f36 100644
#include "LinuxSyscalls/Syscalls.h"
#include "LinuxSyscalls/PtraceEmu.h"
#include "LinuxSyscalls/SignalTrace.h"
@@ -767,6 +768,10 @@ uint64_t SignalDelegator::GetNewSigMask(int Signal) const {
@@ -765,6 +766,10 @@ uint64_t SignalDelegator::GetNewSigMask(int Signal) const {
}
bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) {
@@ -2684,7 +2736,7 @@ index c6ef3fe04..22a5a7f36 100644
if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
index 607ab0b97..5e684c4c7 100644
index 607ab0b..5e684c4 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
@@ -16,6 +16,7 @@ $end_info$
@@ -2763,7 +2815,7 @@ index 607ab0b97..5e684c4c7 100644
#ifdef DEBUG_STRACE
Strace(Frame, Result);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp
index 9397c9eb4..6095bf37f 100644
index 9397c9e..6095bf3 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp
@@ -5,12 +5,19 @@ tags: LinuxSyscalls|syscalls-shared
@@ -2817,7 +2869,7 @@ index 9397c9eb4..6095bf37f 100644
if (Result != -1) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
index f9e85a26f..3326a90fd 100644
index f9e85a2..1781c0a 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
@@ -21,6 +21,7 @@ $end_info$
@@ -2963,7 +3015,7 @@ index f9e85a26f..3326a90fd 100644
} else {
Result = reinterpret_cast<uint64_t>(Get32BitAllocator()->Mremap(old_address, old_size, new_size, flags, new_address));
if (FEX::HLE::HasSyscallError(Result)) {
@@ -602,9 +645,17 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa
@@ -602,9 +645,20 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa
}
}
@@ -2976,16 +3028,19 @@ index f9e85a26f..3326a90fd 100644
+ return Result;
+ }
+ } else {
+ Result = FEX::HLE::GuestHighMemory::RestoreBeforeProtect(reinterpret_cast<uint64_t>(addr), len, prot);
+ if (FEX::HLE::HasSyscallError(Result)) {
+ return Result;
+ }
+ Result = ::mprotect(addr, len, prot);
+ if (Result == -1) {
+ return -errno;
+ }
+ FEX::HLE::GuestHighMemory::ReconcileProtected(reinterpret_cast<uint64_t>(addr), len, prot);
}
TrackMprotect(Thread, addr, len, prot);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
index 2e59f2fb5..ee28680a7 100644
index 2e59f2f..ee28680 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
@@ -1,6 +1,7 @@
@@ -3005,7 +3060,7 @@ index 2e59f2fb5..ee28680a7 100644
FEX::HLE::_SyscallHandler->SeccompEmulator.FreeSeccompFilters(Thread);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
index 9c5f9f1c2..e43dfc79c 100644
index 9c5f9f1..e43dfc7 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -104,6 +104,40 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
+206 -57
View File
@@ -30,6 +30,7 @@ PRELUDE = r"""
#include <asm/unistd_64.h>
#include <atomic>
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <cstdio>
@@ -40,6 +41,8 @@ PRELUDE = r"""
#include <iterator>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include <sys/mman.h>
@@ -50,7 +53,7 @@ PRELUDE = r"""
#include <thread>
#include <type_traits>
#include <unistd.h>
namespace fextl { template<typename T> using vector = std::vector<T>; }
namespace fextl { template<typename T> using vector = std::vector<T>; using string = std::string; }
namespace FEXCore {
namespace Utils { constexpr uint64_t FEX_PAGE_SIZE = 4096; }
constexpr uint64_t AlignUp(uint64_t V, uint64_t A) { return (V + A - 1) & ~(A - 1); }
@@ -158,6 +161,42 @@ static ssize_t TestPwrite(int FD, const void* Buffer, size_t Size, off_t Offset)
return ForcedEmulated ? EmulatedAccess(const_cast<void*>(Buffer), Size, Offset, true) : pwrite(FD, Buffer, Size, Offset);
}
#define pwrite TestPwrite
static int ProtectCalls;
static int FailProtectCall;
static uint64_t* WatchWord;
static uint64_t WatchOriginal;
static int WatchProt = -1;
static int ScratchExposed;
static int TestMprotect(void* Address, size_t Size, int Prot) {
if (++ProtectCalls == FailProtectCall) {
errno = ENOMEM;
return -1;
}
const int Result = mprotect(Address, Size, Prot);
const auto Word = reinterpret_cast<uintptr_t>(WatchWord);
const auto First = reinterpret_cast<uintptr_t>(Address);
if (Result == 0 && WatchWord && Prot == WatchProt && Word >= First && Word < First + Size && *WatchWord != WatchOriginal) {
++ScratchExposed;
}
return Result;
}
#define mprotect TestMprotect
namespace FEXCore::FileLoading {
inline bool LoadFile(std::string& Data, const std::string& Path, size_t = 0) {
const int FD = open(Path.c_str(), O_RDONLY | O_CLOEXEC);
if (FD < 0) {
return false;
}
char Chunk[4096];
ssize_t Read;
Data.clear();
while ((Read = read(FD, Chunk, sizeof(Chunk))) > 0) {
Data.append(Chunk, static_cast<size_t>(Read));
}
close(FD);
return Read == 0;
}
}
namespace FEXCore {
template<template<typename> class LockType = std::unique_lock, typename MutexType>
inline auto MaskSignalsAndLockMutex(MutexType& Mutex, uint64_t = ~0ULL) { return LockType<MutexType> {Mutex}; }
@@ -202,6 +241,11 @@ struct TestHold {
static std::atomic<int> TrapsSeen;
static std::atomic<int> TrapCode;
static std::atomic<int> TrapValue;
static bool ExclusiveFromAnotherThread() {
std::thread Writer([] { std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; });
Writer.join();
return true;
}
static void CountTrap(int, siginfo_t* Info, void*) {
++TrapsSeen;
TrapCode = Info->si_code;
@@ -1223,26 +1267,69 @@ int main() {
Show("io_submit_hidden_restored", SealingBlock->Buffer == reinterpret_cast<uint64_t>(Scatter));
Show("io_submit_hidden_freed", PendingRestores.size() - PendingBefore);
SealingBlock->Buffer = reinterpret_cast<uint64_t>(Scatter);
auto StrandSealed = [&](ArgumentStorage* Pending) {
SealingBlock->Buffer = reinterpret_cast<uint64_t>(Scatter);
uint64_t Args[6] = {1, 1, reinterpret_cast<uint64_t>(SealingList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, Args, Pending);
Protect(Sealing, Page, PROT_NONE);
ForcedPageProt = PROT_NONE;
ForcedReadFailures = 1;
FinishResult(1, Pending);
ForcedReadFailures = 0;
ForcedWriteFailures = 1 << 20;
return PendingRestores.size() - PendingBefore;
};
auto Unseal = [&] {
ForcedWriteFailures = 0;
ForcedPageProt = PROT_READ;
Protect(Sealing, Page, PROT_READ | PROT_WRITE);
};
ArgumentStorage Readable;
uint64_t ReadableArgs[6] = {1, 1, reinterpret_cast<uint64_t>(SealingList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, ReadableArgs, &Readable);
Protect(Sealing, Page, PROT_NONE);
ForcedPageProt = PROT_NONE;
ForcedReadFailures = 1;
FinishResult(1, &Readable);
Show("io_submit_readable_pending", PendingRestores.size() - PendingBefore);
ForcedReadFailures = 0;
ForcedWriteFailures = 1 << 20;
ForcedWrites = 0;
Protect(Sealing, Page, PROT_READ);
Show("io_submit_readable_pending", StrandSealed(&Readable));
WatchWord = &SealingBlock->Buffer;
WatchOriginal = reinterpret_cast<uint64_t>(Scatter);
WatchProt = PROT_READ;
ScratchExposed = 0;
Show("io_submit_readable_result", Protect(Sealing, Page, PROT_READ));
WatchWord = nullptr;
Show("io_submit_readable_exposed", ScratchExposed);
Show("io_submit_readable_restored", SealingBlock->Buffer == reinterpret_cast<uint64_t>(Scatter));
Show("io_submit_readable_freed", PendingRestores.size() - PendingBefore);
ForcedWriteFailures = 0;
ForcedPageProt = PROT_READ;
uint64_t SealedProbe = 0;
Show("io_submit_readable_sealed", FEX::HLE::FaultSafeUserMemAccess::CopyToUser(&SealingBlock->Buffer, &SealedProbe, sizeof(SealedProbe)) != 0);
Protect(Sealing, Page, PROT_READ | PROT_WRITE);
Unseal();
ArgumentStorage Stuck;
Show("io_submit_refused_pending", StrandSealed(&Stuck));
ProtectCalls = 0;
FailProtectCall = 1;
Show("io_submit_refused_result", Protect(Sealing, Page, PROT_READ));
FailProtectCall = 0;
Show("io_submit_refused_kept", PendingRestores.size() - PendingBefore);
Show("io_submit_refused_unreadable", FEX::HLE::FaultSafeUserMemAccess::CopyFromUser(&SealedProbe, &SealingBlock->Buffer, sizeof(SealedProbe)) != 0);
Show("io_submit_refused_retry", Protect(Sealing, Page, PROT_READ));
Show("io_submit_refused_restored", SealingBlock->Buffer == reinterpret_cast<uint64_t>(Scatter));
Show("io_submit_refused_freed", PendingRestores.size() - PendingBefore);
Unseal();
ArgumentStorage Unsealed;
Show("io_submit_unsealed_pending", StrandSealed(&Unsealed));
ProtectCalls = 0;
FailProtectCall = 2;
Show("io_submit_unsealed_result", Protect(Sealing, Page, PROT_READ));
FailProtectCall = 0;
Show("io_submit_unsealed_restored", SealingBlock->Buffer == reinterpret_cast<uint64_t>(Scatter));
Show("io_submit_unsealed_freed", PendingRestores.size() - PendingBefore);
Unseal();
ArgumentStorage Hiding;
Show("io_submit_hiding_pending", StrandSealed(&Hiding));
ProtectCalls = 0;
Show("io_submit_hiding_result", Protect(Sealing, Page, PROT_NONE));
Show("io_submit_hiding_kept", PendingRestores.size() - PendingBefore);
Show("io_submit_hiding_unwindowed", ProtectCalls);
Unseal();
Show("io_submit_hiding_freed", PendingRestores.size() - PendingBefore);
Protect(Sealing, Page, PROT_NONE);
ForcedReadFailures = 1 << 20;
@@ -1379,28 +1466,62 @@ int main() {
LowBlock = static_cast<TestIocb*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
LowList[0] = reinterpret_cast<uint64_t>(LowBlock);
*LowBlock = {};
LowBlock->Opcode = 7;
LowBlock->Buffer = reinterpret_cast<uint64_t>(Scatter);
LowBlock->Bytes = 2;
auto StrandLowSealed = [&](ArgumentStorage* Pending) {
*LowBlock = {};
LowBlock->Opcode = 7;
LowBlock->Buffer = reinterpret_cast<uint64_t>(Scatter);
LowBlock->Bytes = 2;
uint64_t Args[6] = {1, 1, reinterpret_cast<uint64_t>(LowList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, Args, Pending);
mprotect(LowBlock, Page, PROT_NONE);
ForcedPageProt = PROT_NONE;
ForcedReadFailures = 1;
FinishResult(1, Pending);
ForcedReadFailures = 0;
ForcedWriteFailures = 1 << 20;
return PendingRestores.size() - PendingBefore;
};
auto GuestLowProtect = [&](int Prot) -> uint64_t {
const uint64_t Result = RestoreBeforeProtect(reinterpret_cast<uint64_t>(LowBlock), Page, Prot);
if (FEX::HLE::HasSyscallError(Result)) {
return Result;
}
return mprotect(LowBlock, Page, Prot) == 0 ? 0 : -errno;
};
auto UnsealLow = [&] {
ForcedWriteFailures = 0;
ForcedPageProt = PROT_READ;
GuestLowProtect(PROT_READ | PROT_WRITE);
};
ArgumentStorage LowHidden;
uint64_t LowHiddenArgs[6] = {1, 1, reinterpret_cast<uint64_t>(LowList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, LowHiddenArgs, &LowHidden);
mprotect(LowBlock, Page, PROT_NONE);
ForcedPageProt = PROT_NONE;
ForcedReadFailures = 1;
FinishResult(1, &LowHidden);
Show("low_iocb_readable_pending", PendingRestores.size() - PendingBefore);
ForcedReadFailures = 0;
ForcedWriteFailures = 1 << 20;
mprotect(LowBlock, Page, PROT_READ);
ReconcileProtected(reinterpret_cast<uint64_t>(LowBlock), Page, PROT_READ);
ForcedWriteFailures = 0;
ForcedPageProt = PROT_READ;
Show("low_iocb_readable_pending", StrandLowSealed(&LowHidden));
WatchWord = &LowBlock->Buffer;
WatchOriginal = reinterpret_cast<uint64_t>(Scatter);
WatchProt = PROT_READ;
ScratchExposed = 0;
Show("low_iocb_readable_result", GuestLowProtect(PROT_READ));
WatchWord = nullptr;
Show("low_iocb_readable_exposed", ScratchExposed);
Show("low_iocb_readable_restored", LowBlock->Buffer == reinterpret_cast<uint64_t>(Scatter));
Show("low_iocb_readable_freed", PendingRestores.size() - PendingBefore);
uint64_t LowProbe = 0;
Show("low_iocb_readable_sealed", FEX::HLE::FaultSafeUserMemAccess::CopyToUser(&LowBlock->Buffer, &LowProbe, sizeof(LowProbe)) != 0);
UnsealLow();
ArgumentStorage LowRefused;
Show("low_iocb_refused_pending", StrandLowSealed(&LowRefused));
ProtectCalls = 0;
FailProtectCall = 1;
Show("low_iocb_refused_result", GuestLowProtect(PROT_READ));
FailProtectCall = 0;
Show("low_iocb_refused_kept", PendingRestores.size() - PendingBefore);
Show("low_iocb_refused_unreadable", FEX::HLE::FaultSafeUserMemAccess::CopyFromUser(&LowProbe, &LowBlock->Buffer, sizeof(LowProbe)) != 0);
ProtectCalls = 0;
FailProtectCall = 2;
Show("low_iocb_unsealed_result", GuestLowProtect(PROT_READ));
FailProtectCall = 0;
Show("low_iocb_unsealed_restored", LowBlock->Buffer == reinterpret_cast<uint64_t>(Scatter));
Show("low_iocb_unsealed_freed", PendingRestores.size() - PendingBefore);
UnsealLow();
munmap(LowBlock, Page);
auto* CapPage = static_cast<uint32_t*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
@@ -1782,11 +1903,7 @@ int main() {
{
MappingHold Hold {Held};
}
const bool Free = FEX::HLE::_SyscallHandler->VMATracking.Mutex.try_lock();
if (Free) {
FEX::HLE::_SyscallHandler->VMATracking.Mutex.unlock();
}
HoldResults[3] = Free * 0x10 + Held.Held;
HoldResults[3] = ExclusiveFromAnotherThread() * 0x10 + Held.Held;
});
Holder.join();
Show("hold_kept_held", HoldResults[0]);
@@ -1823,11 +1940,7 @@ int main() {
DeferResults[3] = TrapsSeen.load();
DeferResults[4] = ReleaseMappings(Deferred);
DeferResults[5] = TrapsSeen.load() * 0x10 + Deferred.Held;
const bool Free = FEX::HLE::_SyscallHandler->VMATracking.Mutex.try_lock();
if (Free) {
FEX::HLE::_SyscallHandler->VMATracking.Mutex.unlock();
}
DeferResults[6] = Free;
DeferResults[6] = ExclusiveFromAnotherThread();
sigset_t Trap;
sigemptyset(&Trap);
sigaddset(&Trap, SIGTRAP);
@@ -1940,7 +2053,7 @@ def harness():
"bool TranslateRange(",
"uint64_t TranslateSyscallArguments(",
"void ReconcileRestores(",
"void ReconcileProtected(",
"uint64_t RestoreBeforeProtect(",
("void FinishSyscallArguments(", "uint64_t FinishSyscallArguments("),
))
body = "namespace FEX::HLE::GuestHighMemory {\nnamespace {\n" + hidden + "\n}\n" + public + "\n}\n"
@@ -2585,8 +2698,9 @@ class GuestHighMemoryTest(unittest.TestCase):
self.assertEqual(text.count("FEX::HLE::GuestHighMemory::ReconcileRestores();"), 3)
self.assertIn(" Result = ::munmap(addr, length);\n if (Result == -1) {\n return -errno;\n }\n"
" FEX::HLE::GuestHighMemory::ReconcileRestores();", text)
self.assertIn(" Result = ::mprotect(addr, len, prot);\n if (Result == -1) {\n return -errno;\n }\n"
" FEX::HLE::GuestHighMemory::ReconcileProtected(reinterpret_cast<uint64_t>(addr), len, prot);", text)
self.assertIn(" Result = FEX::HLE::GuestHighMemory::RestoreBeforeProtect(reinterpret_cast<uint64_t>(addr), len, prot);\n"
" if (FEX::HLE::HasSyscallError(Result)) {\n return Result;\n }\n"
" Result = ::mprotect(addr, len, prot);\n if (Result == -1) {\n return -errno;\n }", text)
def test_split_ordered_accesses_keep_their_ordering(self):
self.assertEqual(self.value("ordered_load_parts"), 2)
@@ -2650,17 +2764,52 @@ class GuestHighMemoryTest(unittest.TestCase):
smc = added_lines(text, "Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp")
self.assertIn(" if (FEX::HLE::GuestHighMemory::Contains(FaultAddress) || FEX::HLE::GuestHighMemory::HoldsMappings(Thread)) {", smc)
def test_readable_protection_restores_stranded_aio_words(self):
self.assertEqual(self.value("io_submit_readable_pending"), 1)
self.assertEqual(self.value("io_submit_readable_restored"), 1)
self.assertEqual(self.value("io_submit_readable_freed"), 0)
self.assertEqual(self.value("io_submit_readable_sealed"), 1)
self.assertEqual(self.value("low_iocb_readable_pending"), 1)
self.assertEqual(self.value("low_iocb_readable_restored"), 1)
self.assertEqual(self.value("low_iocb_readable_freed"), 0)
self.assertEqual(self.value("low_iocb_readable_sealed"), 1)
protect = block(added_lines(PATCH.read_text(), SOURCE), "uint64_t Protect(")
self.assertIn("RestoreProtected(Address, Length, Prot);", protect)
def test_readable_protection_restores_stranded_aio_words_first(self):
for prefix in ("io_submit_readable", "low_iocb_readable"):
self.assertEqual(self.value(prefix + "_pending"), 1)
self.assertEqual(self.value(prefix + "_result"), 0)
self.assertEqual(self.value(prefix + "_exposed"), 0)
self.assertEqual(self.value(prefix + "_restored"), 1)
self.assertEqual(self.value(prefix + "_freed"), 0)
self.assertEqual(self.value(prefix + "_sealed"), 1)
lines = added_lines(PATCH.read_text(), SOURCE)
protect = block(lines, "uint64_t Protect(")
self.assertLess(protect.index("RestoreBeforeProtect(Address, Length, Prot);"), protect.index("BeginWrite();"))
self.assertNotIn("RestoreProtected", PATCH.read_text())
def test_protection_fails_when_a_stranded_word_cannot_be_restored(self):
enomem = (1 << 64) - 12
for prefix in ("io_submit_refused", "low_iocb_refused"):
self.assertEqual(self.value(prefix + "_pending"), 1)
self.assertEqual(self.value(prefix + "_result"), enomem)
self.assertEqual(self.value(prefix + "_kept"), 1)
self.assertEqual(self.value(prefix + "_unreadable"), 1)
self.assertEqual(self.value("io_submit_refused_retry"), 0)
self.assertEqual(self.value("io_submit_refused_restored"), 1)
self.assertEqual(self.value("io_submit_refused_freed"), 0)
def test_protection_fails_when_the_window_cannot_be_closed(self):
enomem = (1 << 64) - 12
self.assertEqual(self.value("io_submit_unsealed_pending"), 1)
for prefix in ("io_submit_unsealed", "low_iocb_unsealed"):
self.assertEqual(self.value(prefix + "_result"), enomem)
self.assertEqual(self.value(prefix + "_restored"), 1)
self.assertEqual(self.value(prefix + "_freed"), 0)
window = block(added_lines(PATCH.read_text(), SOURCE), "int RestoreInWindow(")
self.assertIn("if (::mprotect(reinterpret_cast<void*>(Pages[i]), FEXCore::Utils::FEX_PAGE_SIZE, Old[i]) != 0) {", window)
def test_hiding_protection_leaves_stranded_words_pending(self):
self.assertEqual(self.value("io_submit_hiding_pending"), 1)
self.assertEqual(self.value("io_submit_hiding_result"), 0)
self.assertEqual(self.value("io_submit_hiding_kept"), 1)
self.assertEqual(self.value("io_submit_hiding_unwindowed"), 1)
self.assertEqual(self.value("io_submit_hiding_freed"), 0)
def test_user_faults_skip_replay(self):
fault = block(added_lines(PATCH.read_text(), SOURCE), "bool HandleFault(")
check = fault.index("SigInfo->si_code <= SI_USER")
self.assertLess(fault.index("DeferWhileHeld("), check)
self.assertLess(check, fault.index("MappingHold Hold {Trap.Mappings};"))
def test_user_signals_wait_until_the_mappings_are_released(self):
self.assertEqual(self.value("defer_unheld"), 0)
+49 -2
View File
@@ -8,14 +8,17 @@ from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
EMULATION = FEX / "patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch"
MCONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
PROBE = FEX / "probes/signal-register-update.c"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
def files(patch=PATCH):
sections = re.split(r"^diff --git a/(\S+) \S+\n", patch.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
@@ -96,6 +99,50 @@ class SignalRegisterUpdateTest(unittest.TestCase):
self.assertNotIn("Fixed-upstream", PATCH.read_text())
class ClearedSyscallInfoTest(unittest.TestCase):
SOURCE = "ArchHelpers::Context::SavedSyscallInfo(Context)"
def saved_info(self):
lines = [line[1:] for line in files(EMULATION)[MCONTEXT].splitlines() if line.startswith("+") and not line.startswith("+++")]
start = lines.index("template<typename Backup>")
end = lines.index("}", start)
return "\n".join(lines[start:end + 1])
def test_register_writeback_reads_the_same_saved_state_as_the_restore(self):
frames = files(EMULATION)[FRAMES]
self.assertIn("- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;", frames)
self.assertIn("+ const uint32_t Spilled = " + self.SOURCE + " & 0xFFFF;", frames)
delegator = added(files(EMULATION)[DELEGATOR])
self.assertIn("Thread->CurrentFrame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = Context->InSyscallInfo;", removed(files(EMULATION)[DELEGATOR]))
self.assertNotIn("Context->ClearedSyscallInfo :", "\n".join(delegator))
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "needs a C++ compiler")
def test_cleared_state_is_preferred_only_when_flagged(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
source = "\n".join([
"#include <cstdint>",
"#include <cstdio>",
"enum ContextFlags : uint32_t { CONTEXT_FLAG_INJIT = 1U << 0, CONTEXT_FLAG_SYSCALLINFO_CLEARED = 1U << 1 };",
"struct Backup { uint16_t InSyscallInfo; uint16_t ClearedSyscallInfo; uint32_t Flags; };",
self.saved_info(),
"int main() {",
" const Backup Thunk {0, 0xFFFF, CONTEXT_FLAG_SYSCALLINFO_CLEARED};",
" const Backup Jit {0x0F0F, 0x1234, CONTEXT_FLAG_INJIT};",
" const Backup Idle {0, 0x1234, 0};",
" std::printf(\"%x %x %x\\n\", SavedSyscallInfo(&Thunk), SavedSyscallInfo(&Jit), SavedSyscallInfo(&Idle));",
"}",
])
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "saved.cpp"
binary = Path(tmp) / "saved"
path.write_text(source)
subprocess.run([compiler, "-std=c++20", "-Wall", "-Werror", "-o", str(binary), str(path)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
self.assertEqual(output.split(), ["ffff", "f0f", "0"])
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalRegisterUpdateProbeTest(unittest.TestCase):
@classmethod