diff --git a/README.md b/README.md index b6f80f6220..a1094c8d14 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). -- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. +- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - `WriteProcessMemory` hooks fall back to `/proc//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 3d7876c2f5..d4b99759d5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -228,7 +228,69 @@ alone would then read as an installed client. context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in 2000 carried the interrupted registers, natively all of them. The return now restores the value saved - when the signal arrived. + when the signal arrived, and only when the signal interrupted JIT code, which is the only case that + saves it. Restoring it for a signal that interrupted a system call cleared the mark while that call + was still running, so the next signal in the call's return path spilled clobbered registers: + `setitimer` at 100 Hz around `time()` crashed in 15 of 15 runs, and with the guard as often as the + same build without the patch (about half; a separate crash that FEX-2611.1 also shows). + - `0009-signal-handler-escape-frees-host-stack`: FEX keeps each signal's host context on the host + stack and frees it only on `rt_sigreturn`. A guest that leaves its handler another way (`siglongjmp`, + or CoreCLR resuming a `catch` after a NullReferenceException) left that 2 KB block and one + `SignalHandlerRefCounter` count behind. About 3500 such exceptions on one thread overran the 8 MB + host stack, which has no guard page, and the CurseForge agent died with "Internal CLR error. + (0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second + addon scan. FEX now chains each thread's signal frames with the guest frame range and alternate + stack they used. When a signal arrives in JIT code that runs at the host level of the newest frame + and the guest stack pointer shows the guest has left that frame (above its frame, or back off the + alternate stack above where the outermost frame on it interrupted), the left frames are dropped and + the new context is stored where the newest live frame (or the dispatcher entry) left the host stack. + `rt_sigreturn` pops its frame and any newer ones it skips. Signals that arrive inside system calls or + thunk callbacks are left alone. `tools/fex/probes/signal-handler-escape.c` leaves handlers on and + off the alternate stack, mixes them with handlers that return, and leaves nested handlers: FEX-2611.1 + with 0001 to 0008 crashed (SIGSEGV) before 2000 iterations of it, and `siglongjmp` out of a SIGSEGV + handler died after about 3500; with this patch 350000 escapes and 200000 straight `siglongjmp`s + finish, as natively. The approach is the one suggested in FEX-Emu/FEX#2487. + - `0010-syscall-exit-resets-host-stack` (`Fixed-upstream: FEX-2612`): a backport of FEX's + "JIT: Ensure IR ops that jump out of the JIT reset the stack" (FEX-Emu/FEX#6122). A system call or + code-entry removal that ends a block jumps to the dispatcher without dropping the block's spill + slots, and the syscall handler's fast path branches straight into the next block, so every such + exit leaked up to 32 bytes per spill slot of host stack. AVX and MMX code keeps enough values live to + spill, and `tools/fex/probes/syscall-host-stack.c` overran the 8 MB host stack after about 65000 + system calls; with the patch 2000000 finish, as natively. The CPUID hunk of the upstream commit is + left out, since CPUID returns to the JIT in 2611. + - `0011-thunk-calls-mark-spilled-state`: a thunk call (every vDSO `clock_gettime`, `gettimeofday` + and `time`, and the host library thunks) spills the static registers to the guest frame and calls + host code, which clobbers the caller-saved host registers. A signal that arrived in the JIT code + after the host call returned and before the registers were refilled took the interrupted state from + those clobbered host registers: the guest handler got garbage registers, and the interrupted code + resumed with them, or FEX built the signal frame at a garbage stack pointer and crashed. The thunk + call now marks every static register as spilled (`InSyscallInfo = 0xFFFF`, as the system call + handler does) until the refill ends, and a fully spilled mark takes only RIP from the host PC and + leaves the frame's GPRs, vector registers and flags alone (the 16-bit mask could not name the + x16/x17 and v16 to v31 registers the host call clobbers). Every guest signal now saves and clears the + mark, so guest handlers and nested signals never inherit it, and every return puts back the value it + saved; 0008 restored it only for JIT code because the other paths saved none. A handler that changes + RIP restarts at the dispatcher with no mark, and thunk callbacks into guest code run with none. + `tools/fex/probes/vdso-signal-state.c` calls `clock_gettime` under a 1 kHz `SIGALRM` and checks the + values held across each call: FEX-2611 crashed in 3 of 8 runs, with 0001 to 0010 in 7 of 8; with + this patch 0 of 28, as natively. This was the "separate crash" noted under 0008. + - `0012-signal-return-applies-guest-registers`: a signal return that kept RIP threw away every + register change the guest handler made in its `ucontext`; only a changed RIP made FEX reload the + guest state from it. CoreCLR suspends threads for garbage collection with a signal and, in fully + interruptible code, runs the collection from that handler and writes the moved object references + back into the interrupted registers, so under FEX the thread resumed with pointers into the old heap. + The CurseForge agent's crashes during parallel addon scans (an `AccessViolationException` in + `Curse.Hashing.MurmurHash2.ComputeHash` or `RegexInterpreter`, or "Internal CLR error. (0x80131506)" + with a stack overflow) look like this, but they still happen with this patch, so it is not a fix for + them. When RIP is + unchanged, each guest GPR the handler changed is now written where the resumed code reads it: the + guest frame for registers the interrupted code had spilled (all of them inside a system call or + thunk call), otherwise the static host register. Unchanged registers are left alone, signals that + interrupted code outside the JIT (and not inside a system call or thunk call) keep the old + behaviour, and 32-bit frames compare and write only the low 32 bits. `tools/fex/probes/signal-register-update.c` + spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): + FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all + three see it on the first signal, as natively. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch index 6a8e14e1d0..6592a94550 100644 --- a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -1,12 +1,18 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index b4c7b24..e6777aa 100644 +index b4c7b24..643185d 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -262,6 +262,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr - - if (Context->UContextLocation) { +@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr auto Frame = Thread->CurrentFrame; -+ Frame->InSyscallInfo = Context->InSyscallInfo; if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { // 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; + } + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); + } else { + if (Type == RestoreType::TYPE_NONREALTIME) { diff --git a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch new file mode 100644 index 0000000000..fbeec5ec96 --- /dev/null +++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch @@ -0,0 +1,174 @@ +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 02bb6bf..2e72492 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -49,6 +49,11 @@ struct X86ContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + static constexpr int RedZoneSize = 128; + }; +@@ -76,6 +81,11 @@ struct ArmContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + + // Arm64 doesn't have a red zone +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 643185d..53179c4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* + #endif + } + ++namespace { ++ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) { ++ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd; ++ } ++ ++ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) { ++ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP); ++ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) { ++ return GuestSP >= Backup->GuestFrameEnd; ++ } ++ if (SPOnAlt) { ++ return false; ++ } ++ auto Entry = Backup; ++ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) { ++ if (--Limit == 0 || !Entry->PrevGuestFrame) { ++ return false; ++ } ++ Entry = reinterpret_cast(Entry->PrevGuestFrame); ++ } ++ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase && ++ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP; ++ } ++} ++ + ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) { + // We can end up getting a signal at any point in our host state + // Jump to a handler that saves all state so we can safely return +@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + } + + OldSP = *reinterpret_cast(GuestSP); ++ ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; ++ uint64_t Entry = SignalInfo.GuestFrames; ++ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) { ++ auto EntryBackup = reinterpret_cast(Entry); ++ if (Entry == OldSP) { ++ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame; ++ SignalInfo.GuestFrameCount -= Depth; ++ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1; ++ break; ++ } ++ Entry = EntryBackup->PrevGuestFrame; ++ } + } + + uintptr_t NewSP = OldSP; +@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); + + auto Frame = Thread->CurrentFrame; ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; + + // Ref count our faults + // We use this to track if it is safe to clear cache +@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + + uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + uint64_t NewGuestSP = OldGuestSP; ++ uint64_t GuestAltBase = 0; ++ uint64_t GuestAltEnd = 0; + + // altstack is only used if the signal handler was setup with SA_ONSTACK + if (GuestAction->sa_flags & SA_ONSTACK) { +@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + // Then that means we are hitting recursive signals and we need to walk back the stack correctly + uint64_t AltStackBase = reinterpret_cast(GuestStack->ss_sp); + uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size; ++ GuestAltBase = AltStackBase; ++ GuestAltEnd = AltStackEnd; + if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) { + // We are already in the alt stack, the rest of the code will handle adjusting this + } else { +@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + } + } + ++#ifdef ARCHITECTURE_arm64 ++ auto Newest = reinterpret_cast(SignalInfo.GuestFrames); ++ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames && ++ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) { ++ uint32_t LeftFrames = 0; ++ while (Newest && LeftFrames < SignalInfo.GuestFrameCount && ++ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) { ++ Newest = reinterpret_cast(Newest->PrevGuestFrame); ++ ++LeftFrames; ++ } ++ ++ const uint64_t HostTop = Newest ? reinterpret_cast(Newest) : Frame->ReturningStackLocation; ++ const uint64_t MovedBackup = FEXCore::AlignDown( ++ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16); ++ if (MovedBackup > reinterpret_cast(ContextBackup)) { ++ memmove(reinterpret_cast(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup)); ++ ContextBackup = reinterpret_cast(MovedBackup); ++ ContextBackup->PrevSP = HostTop; ++ ArchHelpers::Context::SetSp(ucontext, MovedBackup); ++ SignalInfo.GuestFrames = reinterpret_cast(Newest); ++ SignalInfo.GuestFrameCount -= LeftFrames; ++ Frame->SignalHandlerRefCounter -= LeftFrames; ++ } ++ } ++#endif ++ ++ ContextBackup->GuestFrameEnd = NewGuestSP; ++ ContextBackup->GuestInterruptedSP = OldGuestSP; ++ ContextBackup->GuestAltBase = GuestAltBase; ++ ContextBackup->GuestAltEnd = GuestAltEnd; ++ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames; ++ SignalInfo.GuestFrames = reinterpret_cast(ContextBackup); ++ ++SignalInfo.GuestFrameCount; ++ + // siginfo_t + siginfo_t* HostSigInfo = reinterpret_cast(info); + +@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre + + // Our ref counting doesn't matter anymore + Thread->CurrentFrame->SignalHandlerRefCounter = 0; ++ ThreadObject->SignalInfo.GuestFrames = 0; ++ ThreadObject->SignalInfo.GuestFrameCount = 0; + + // Set the new PC + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index dfcd4b0..e4a86a9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + // Queue of thread local signal frames that have been deferred. + // Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO. + fextl::vector DeferredSignalFrames; ++ ++ uint64_t GuestFrames {}; ++ uint32_t GuestFrameCount {}; + } SignalInfo {}; + + // Seccomp thread specific data. diff --git a/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch new file mode 100644 index 0000000000..790a5390d8 --- /dev/null +++ b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch @@ -0,0 +1,23 @@ +Fixed-upstream: FEX-2612 +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index c2b1d8e287..fcdf261484 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -285,6 +285,8 @@ DEF_OP(CondJump) { + DEF_OP(Syscall) { + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Jump to the syscall dispatch handler. We won't return after this. + ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler)); + br(TMP1); +@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) { + + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Store the new RIP to go to. + str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); + diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch new file mode 100644 index 0000000000..626c726b59 --- /dev/null +++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch @@ -0,0 +1,109 @@ +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -383,7 +383,11 @@ + } + + void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) { +- static_cast(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP); ++ auto Frame = Thread->CurrentFrame; ++ const auto InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ static_cast(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP); ++ Frame->InSyscallInfo = InSyscallInfo; + } + + void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) { +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -305,6 +305,9 @@ + + PushDynamicRegs(TMP1); + ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); ++ + mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr)); + + InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash); +@@ -320,6 +323,8 @@ + FillStaticRegs({ + .NZCV = false, + }); ++ ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); + } + + DEF_OP(ValidateCode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -107,6 +107,10 @@ + #ifdef ARCHITECTURE_arm64 + Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext)); + ++ if ((IgnoreMask & 0xFFFF) == 0xFFFF) { ++ return; ++ } ++ + for (size_t i = 0; i < Config.SRAGPRCount; i++) { + const uint8_t SRAIdxMap = Config.SRAGPRMapping[i]; + if (IgnoreMask & (1U << SRAIdxMap)) { +@@ -301,12 +305,10 @@ + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; + +- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { +- // 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; +- } ++ // 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; + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); +@@ -361,6 +363,9 @@ + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { ++ ContextBackup->InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ + if (!IsAddressInDispatcher(OldPC)) { + // This is likely to cause issues but in some cases it isn't fatal + // This can also happen if we have put a signal on hold, then we just reenabled the signal +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -131,7 +131,7 @@ + if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ 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 +@@ -211,7 +211,7 @@ + // If the guest modified the RIP then we need to take special precautions here + if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ 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 +@@ -290,7 +290,7 @@ + if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ 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 diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch new file mode 100644 index 0000000000..d97a75bee3 --- /dev/null +++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch @@ -0,0 +1,112 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -263,6 +263,8 @@ + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); + void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); ++ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, ++ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask); + + ///< Setup the signal frame for x64. + uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -122,6 +122,32 @@ + } + } + ++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 bool AllSpilled = Spilled == 0xFFFF; ++ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ return; ++ } ++ ++ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) { ++ const uint8_t HostReg = Config.SRAGPRMapping[i]; ++ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg)); ++ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg); ++ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) { ++ continue; ++ } ++ ++ if (InFrame) { ++ Frame->State.gregs[i] = GuestGPRs[i]; ++ } else { ++ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]); ++ } ++ } ++#endif ++} ++ + void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + auto* guest_uctx = reinterpret_cast(Context->UContextLocation); +@@ -202,6 +228,27 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0])); + } ++ } else { ++ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS]; ++#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; ++ COPY_REG(R8); ++ COPY_REG(R9); ++ COPY_REG(R10); ++ COPY_REG(R11); ++ COPY_REG(R12); ++ COPY_REG(R13); ++ COPY_REG(R14); ++ COPY_REG(R15); ++ COPY_REG(RDI); ++ COPY_REG(RSI); ++ COPY_REG(RBP); ++ COPY_REG(RBX); ++ COPY_REG(RDX); ++ COPY_REG(RAX); ++ COPY_REG(RCX); ++ COPY_REG(RSP); ++#undef COPY_REG ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL); + } + } + +@@ -280,6 +327,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + +@@ -359,6 +417,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX]; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX]; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX]; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX]; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP]; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP]; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI]; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI]; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + diff --git a/tools/fex/probes/signal-handler-escape.c b/tools/fex/probes/signal-handler-escape.c new file mode 100644 index 0000000000..71e1a12fca --- /dev/null +++ b/tools/fex/probes/signal-handler-escape.c @@ -0,0 +1,90 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +static sigjmp_buf main_env, inner_env; +static volatile int depth, nested_mode; +static volatile long escapes, nested, returns, wrong; + +static void fault(long i) { + *(volatile int *)(long)(8 + (i & 7)) = 1; +} + +static void segv(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + if (!nested_mode) { + escapes++; + siglongjmp(main_env, 1); + } + if (depth == 1) { + nested++; + siglongjmp(inner_env, 1); + } + depth = 1; + for (volatile int k = 0; k < 3; k++) + if (sigsetjmp(inner_env, 0) == 0) + fault(k); + depth = 0; + escapes++; + siglongjmp(main_env, 1); +} + +static void trap(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + returns++; +} + +static void install(int onstack) { + struct sigaction action; + memset(&action, 0, sizeof(action)); + action.sa_sigaction = segv; + action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0); + sigaction(SIGSEGV, &action, NULL); +} + +static long run(long count, int with_trap) { + long start = escapes; + for (volatile long i = 0; i < count; i++) { + if (with_trap) { + volatile long before = i * 3; + __asm__ volatile("int3" ::: "memory"); + if (before != i * 3) + wrong++; + } + if (sigsetjmp(main_env, 1) == 0) + fault(i); + } + return escapes - start; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 50000; + stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144}; + struct sigaction action; + sigaltstack(&ss, NULL); + memset(&action, 0, sizeof(action)); + action.sa_sigaction = trap; + action.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &action, NULL); + + install(1); + long onstack = run(want, 0); + install(0); + long offstack = run(want, 0); + install(1); + long mixed = run(want, 1); + nested_mode = 1; + long outer = run(want, 0); + + printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns, + outer, nested, wrong); + return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0 + : 1; +} diff --git a/tools/fex/probes/signal-register-update.c b/tools/fex/probes/signal-register-update.c new file mode 100644 index 0000000000..a1fdaec4d5 --- /dev/null +++ b/tools/fex/probes/signal-register-update.c @@ -0,0 +1,88 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#define MARK 0x5eed + +static volatile sig_atomic_t alarms; +static volatile sig_atomic_t give_up; + +static void count_alarm(void) { + if (++alarms > 100) { + give_up = 1; + } +} + +static void on_alarm(int sig, siginfo_t *si, void *ctx) { + (void)sig; + (void)si; + ucontext_t *uc = ctx; + count_alarm(); +#ifdef __x86_64__ + uc->uc_mcontext.gregs[REG_R12] = MARK; +#else + uc->uc_mcontext.gregs[REG_ESI] = MARK; +#endif +} + +#ifdef __i386__ +static void on_alarm_legacy(int sig, struct sigcontext sc) { + (void)sig; + count_alarm(); + ((volatile struct sigcontext *)&sc)->esi = MARK; +} +#endif + +int main(int argc, char **argv) { + int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_flags = SA_RESTART; +#ifdef __i386__ + if (legacy) { + sa.sa_handler = (void (*)(int))on_alarm_legacy; + } else +#endif + { + legacy = 0; + sa.sa_sigaction = on_alarm; + sa.sa_flags |= SA_SIGINFO; + } + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 20000}, {0, 20000}}; + setitimer(ITIMER_REAL, &it, NULL); + + unsigned long spins, seen; +#ifdef __x86_64__ + __asm__ volatile("xor %%r12, %%r12\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%r12, %%r12\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%r12, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "r12", "cc"); +#else + __asm__ volatile("xor %%esi, %%esi\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%esi, %%esi\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%esi, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "esi", "cc"); +#endif + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins); + return seen == MARK ? 0 : 1; +} diff --git a/tools/fex/probes/syscall-host-stack.c b/tools/fex/probes/syscall-host-stack.c new file mode 100644 index 0000000000..bd348fcfd3 --- /dev/null +++ b/tools/fex/probes/syscall-host-stack.c @@ -0,0 +1,65 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define YMM_STEP(a, b) "vpaddq %%ymm" #b ", %%ymm" #a ", %%ymm" #a "\n" +#define MMX_STEP(a, b) "paddq %%mm" #b ", %%mm" #a "\n" + +static int has_avx2(void) { + unsigned a, b, c, d; + if (!__get_cpuid(1, &a, &b, &c, &d) || !(c & bit_AVX) || !(c & bit_OSXSAVE)) + return 0; + unsigned lo, hi; + __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); + if ((lo & 6) != 6 || !__get_cpuid_count(7, 0, &a, &b, &c, &d)) + return 0; + return (b & bit_AVX2) != 0; +} + +static long ymm_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + YMM_STEP(0, 1) YMM_STEP(1, 2) YMM_STEP(2, 3) YMM_STEP(3, 4) YMM_STEP(4, 5) YMM_STEP(5, 6) YMM_STEP(6, 7) YMM_STEP(7, 8) + YMM_STEP(8, 9) YMM_STEP(9, 10) YMM_STEP(10, 11) YMM_STEP(11, 12) YMM_STEP(12, 13) YMM_STEP(13, 14) YMM_STEP(14, 15) + YMM_STEP(15, 0) YMM_STEP(0, 15) YMM_STEP(1, 14) YMM_STEP(2, 13) YMM_STEP(3, 12) YMM_STEP(4, 11) YMM_STEP(5, 10) + YMM_STEP(6, 9) YMM_STEP(7, 8) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", + "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"); + } + __asm__ volatile("vzeroupper" ::: "memory"); + return pid; +} + +static long mmx_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + MMX_STEP(0, 1) MMX_STEP(1, 2) MMX_STEP(2, 3) MMX_STEP(3, 4) MMX_STEP(4, 5) MMX_STEP(5, 6) MMX_STEP(6, 7) MMX_STEP(7, 0) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"); + } + __asm__ volatile("emms" ::: "memory"); + return pid; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 2000000; + int avx = has_avx2(); + long done = 0; + for (; done < want; done += 1000) { + if (avx ? ymm_round(1000) <= 0 : mmx_round(1000) <= 0) + return 2; + } + printf("mode=%s syscalls=%ld\n", avx ? "avx" : "mmx", done); + return 0; +} diff --git a/tools/fex/probes/vdso-signal-state.c b/tools/fex/probes/vdso-signal-state.c new file mode 100644 index 0000000000..56057594c3 --- /dev/null +++ b/tools/fex/probes/vdso-signal-state.c @@ -0,0 +1,49 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t alarms; + +static void on_alarm(int sig) { + (void)sig; + alarms++; +} + +int main(int argc, char **argv) { + int seconds = argc > 1 ? atoi(argv[1]) : 3; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_alarm; + sa.sa_flags = SA_RESTART; + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 1000}, {0, 1000}}; + setitimer(ITIMER_REAL, &it, NULL); + + struct timespec start, now, last; + clock_gettime(CLOCK_MONOTONIC, &start); + last = start; + unsigned long calls = 0, bad = 0; + unsigned long a = 1, b = 3, c = 1 ^ 0x5a5a5a5a5a5a5a5aUL; + do { + clock_gettime(CLOCK_MONOTONIC, &now); + calls++; + __asm__ volatile("" : "+r"(a), "+r"(b), "+r"(c)); + if (b != a * 3 || c != (a ^ 0x5a5a5a5a5a5a5a5aUL)) + bad++; + if (now.tv_sec < last.tv_sec || (now.tv_sec == last.tv_sec && now.tv_nsec < last.tv_nsec)) + bad++; + last = now; + a = a * 6364136223846793005UL + 1442695040888963407UL; + b = a * 3; + c = a ^ 0x5a5a5a5a5a5a5a5aUL; + } while ((now.tv_sec - start.tv_sec) * 1000000000L + (now.tv_nsec - start.tv_nsec) < seconds * 1000000000L); + + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("calls=%lu alarms=%d bad=%lu\n", calls, (int)alarms, bad); + return bad || alarms == 0; +} diff --git a/tools/tests/test_fex_signal_handler_escape.py b/tools/tests/test_fex_signal_handler_escape.py new file mode 100644 index 0000000000..c208b874bf --- /dev/null +++ b/tools/tests/test_fex_signal_handler_escape.py @@ -0,0 +1,117 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch" +PROBE = FEX / "probes/signal-handler-escape.c" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h" +THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h" +FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"] + + +def files(): + 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)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +class SignalHandlerEscapeTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS])) + + def test_nothing_is_removed(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertFalse("//" in line or "/*" in line, f"{name}: {line}") + + def test_both_context_backups_record_the_guest_frame(self): + lines = added(files()[CONTEXT]) + self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2) + + def test_each_thread_keeps_its_frame_chain(self): + self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"]) + + def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self): + found = hunks(files()[DELEGATOR]) + delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function) + lines = added(delivery) + self.assertIn("#ifdef ARCHITECTURE_arm64", lines) + gate = " ".join(lines) + self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate) + self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate) + self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate) + self.assertIn("ContextBackup->PrevSP = HostTop;", lines) + self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines) + self.assertIn("SignalInfo.GuestFrames = reinterpret_cast(ContextBackup);", lines) + self.assertIn("++SignalInfo.GuestFrameCount;", lines) + self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;")) + + def test_signal_return_pops_its_frame_and_any_newer_ones(self): + found = hunks(files()[DELEGATOR]) + restore = "".join(body for function, body in found if "RestoreThreadState" in function) + lines = added(restore) + self.assertIn("if (Entry == OldSP) {", lines) + self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines) + self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_thread_stop_clears_the_chain(self): + found = hunks(files()[DELEGATOR]) + pause = "".join(body for function, body in found if "HandleSignalPause" in function) + self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"]) + + def test_patch_follows_the_syscall_state_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SignalHandlerEscapeProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_survives_every_escape(self): + result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + for phase in ("onstack", "offstack", "mixed", "returns", "outer"): + self.assertEqual(counts[phase], "20000", phase) + self.assertEqual(counts["nested"], "60000") + self.assertEqual(counts["wrong"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_register_update.py b/tools/tests/test_fex_signal_register_update.py new file mode 100644 index 0000000000..dabc5afff3 --- /dev/null +++ b/tools/tests/test_fex_signal_register_update.py @@ -0,0 +1,134 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch" +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) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def added(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def helper(): + lines = added(files()[FRAMES]) + start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs(")) + end = lines.index("#endif", start) + return lines[start:end + 1] + + +class SignalRegisterUpdateTest(unittest.TestCase): + def test_only_signal_frame_files_change(self): + self.assertEqual(sorted(files()), sorted([FRAMES, HEADER])) + + def test_patch_only_adds_code(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertNotIn("//", line, name) + self.assertNotIn("/*", line, name) + + def test_helper_is_declared_once(self): + self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1) + + def test_only_changed_registers_are_written_back(self): + body = helper() + self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body) + self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;") + + def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self): + body = helper() + self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body) + self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body) + self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body) + self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body) + + def test_signals_outside_jit_code_are_left_alone(self): + body = helper() + guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {") + self.assertEqual(body[guard + 1], "return;") + self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64") + + def test_every_frame_type_applies_registers_when_rip_is_unchanged(self): + lines = added(files()[FRAMES]) + calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")] + self.assertEqual(calls, [ + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + ]) + branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")] + self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"]) + + def test_registers_are_stored_by_guest_register_index(self): + lines = added(files()[FRAMES]) + x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m] + self.assertEqual(sorted(x64), sorted(X64_ORDER)) + self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines) + legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines)) + self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8])) + rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines)) + self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8])) + + def test_patch_follows_the_thunk_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code") +class SignalRegisterUpdateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not cls.compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-")) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def build(self, *flags): + binary = self.tmp / ("probe" + "".join(flags)) + result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True) + return binary if result.returncode == 0 else None + + def check(self, binary, *args): + result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertIn("seen=1", result.stdout) + + def test_native_kernel_applies_handler_register_changes(self): + self.check(self.build()) + + def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self): + binary = self.build("-m32") + if binary is None: + self.skipTest("no 32-bit toolchain") + self.check(binary) + self.check(binary, "legacy") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py index 1aaa03feb3..5638a41fea 100644 --- a/tools/tests/test_fex_signal_syscall_state.py +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -24,7 +24,7 @@ class SignalReturnSyscallStateTest(unittest.TestCase): self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) self.assertEqual(len(found), 1) - def test_every_guest_frame_return_restores_the_interrupted_syscall_state(self): + def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self): _, found = hunks() function, body = found[0] self.assertIn("SignalDelegator::RestoreThreadState", function) @@ -34,10 +34,12 @@ class SignalReturnSyscallStateTest(unittest.TestCase): self.assertEqual(added, [RESTORE]) self.assertEqual(removed, []) context = [line[1:].strip() for line in lines] - guest_frame = context.index("if (Context->UContextLocation) {") - self.assertEqual(context[guest_frame + 1], "auto Frame = Thread->CurrentFrame;") - self.assertEqual(context[guest_frame + 2], RESTORE) - self.assertLess(context.index(RESTORE), context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")) + self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;") + in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {") + restore = context.index(RESTORE) + self.assertLess(in_jit, restore) + self.assertEqual(context[restore + 1], "}") + self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);")) def test_thread_pause_returns_are_untouched(self): _, found = hunks() diff --git a/tools/tests/test_fex_syscall_host_stack.py b/tools/tests/test_fex_syscall_host_stack.py new file mode 100644 index 0000000000..018863cf59 --- /dev/null +++ b/tools/tests/test_fex_syscall_host_stack.py @@ -0,0 +1,67 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch" +PROBE = FEX / "probes/syscall-host-stack.c" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SyscallHostStackTest(unittest.TestCase): + def test_only_the_branch_ops_change(self): + files, found = hunks() + self.assertEqual(files, [BRANCH_OPS]) + self.assertEqual(len(found), 2) + + def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self): + _, found = hunks() + for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")): + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + self.assertEqual([line for line in added if line], ["ResetStack();"], op) + self.assertEqual([line for line in lines if line.startswith("-")], [], op) + context = [line[1:].strip() for line in lines] + self.assertIn(op, function + " " + " ".join(context)) + self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op) + + def test_patch_is_skipped_once_upstream_ships_it(self): + self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612") + self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SyscallHostStackProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_runs_every_syscall(self): + result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertIn(counts["mode"], ("avx", "mmx")) + self.assertEqual(counts["syscalls"], "200000") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_thunk_signal_state.py b/tools/tests/test_fex_thunk_signal_state.py new file mode 100644 index 0000000000..83d6008589 --- /dev/null +++ b/tools/tests/test_fex_thunk_signal_state.py @@ -0,0 +1,124 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch" +PROBE = FEX / "probes/vdso-signal-state.c" +CORE = "FEXCore/Source/Interface/Core/Core.cpp" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def files(): + 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)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def context(body): + return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")] + + +class ThunkSignalStateTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES])) + + def test_added_code_has_no_new_comments(self): + for name, section in files().items(): + moved = set(removed(section)) + for line in added(section): + if "//" in line or "/*" in line: + self.assertIn(line, moved, f"{name}: {line}") + + def test_thunk_call_marks_all_state_spilled_until_the_refill(self): + section = files()[BRANCH_OPS] + lines = context(section) + self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR]) + self.assertEqual(removed(section), []) + self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK)) + self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);")) + refill = lines.index("FillStaticRegs({") + self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"]) + self.assertLess(refill, lines.index(CLEAR)) + + def test_fully_spilled_state_is_never_respilled_from_host_registers(self): + found = hunks(files()[DELEGATOR]) + spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body) + lines = context(spill) + guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {") + self.assertIn("RestoreRIPFromHostPC", lines[guard - 2]) + self.assertEqual(lines[guard + 1], "return;") + self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5]) + + def test_every_guest_signal_saves_and_clears_the_mark(self): + section = files()[DELEGATOR] + lines = added(section) + self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines) + self.assertIn("Frame->InSyscallInfo = 0;", lines) + self.assertIn(RESTORE, lines) + self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section)) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_redirected_returns_restart_with_no_mark(self): + section = files()[FRAMES] + self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3) + self.assertEqual(removed(section), [RESTORE] * 3) + + def test_guest_callbacks_run_with_no_mark(self): + lines = added(files()[CORE]) + self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"]) + self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;") + self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2]) + + def test_patch_follows_the_host_stack_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class VdsoSignalStateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self): + result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreater(int(counts["calls"]), 0) + self.assertGreater(int(counts["alarms"]), 0) + self.assertEqual(counts["bad"], "0") + + +if __name__ == "__main__": + unittest.main()