kernel: preserve Windows guest stack bounds #2125
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!2125
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2125"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@giulienh on GitHub · 2026-11-05 15:43 UTC · original
giulienh:fix/pragmata-windows-stack→main· +510 −166 · 6 files · 15 commits · openThe emulator terminated during startup on Windows with
0xc0000409 / FAST_FAIL_INVALID_SET_OF_CONTEXTinntdll!RtlRestoreContext. This was observed with Pragmata version01.200.000and Ghost of Yōtei version01.008.000.Windows rejected the saved stack pointer while restoring the execution context. The pointer was inside the allocated guest stack, but both Windows stack bounds were set to zero. Pragmata hit this in a guest worker thread. Ghost of Yōtei hit the same problem in the main guest thread, which uses a separate entry path.
Changes
src/kernel/pthread.cpp:Modified
RunThreadto calculate the upper guest-stack bound and pass both bounds toRunOnGuestStackas additional parameters. The assembly block writes these bounds instead of the previous zero values. It saves the required input values before reusing their possible registers. The existing restoration of the original host stack bounds remains in place.src/loader/runtimeLinker.cpp:Applied the same correction to the main-thread entry path.
RunEntrynow receives the allocated main-stack bounds and writes them into the Windows TEB during guest execution. It restores the original host bounds on return.src/graphics/shader/recompiler/ir/Value.h:The size check for
IR::Instnow takes the actual size ofstd::vector<Use>into account, including the additional memory needed for debug iterator bookkeeping.src/kernel/pthread.cpp,src/kernel/pthread.handtests/VirtualMemoryAllocationTests.cpp:Added tests for normal return,
PthreadExit, and continuation after a handled access violation on the guest stack. The--guest-stack-onlyoption runs these cases separately from the full suite. The existing main-entry test now checks the actual guest bounds and restoration of the host bounds instead of expecting zero bounds, and is included in this option.Tests
Debug and Release builds compile successfully with VS 2022 and clang-cl 19.1.5. All four stack tests pass in both configurations. They check the guest stack pointer and bounds, return values, restoration of the original host bounds, and memory release. The handled-fault test also checks that Windows resumes the failed read after the test handler permits access to its private test page.
The modified main-entry test fails with the previous zero-bounds implementation and passes with the correction.
I tested Pragmata on Windows 11 26H2. It passes the previous crash point at around frame 300 and progresses through the startup sequence in Debug and Release. It later terminates on a Vulkan validation error because
fragmentShaderBarycentricis unavailable on my RX 5700.In a debugger reproduction, Ghost of Yōtei also terminated with zero main-thread stack bounds. With the main-entry correction, a subsequent run progressed further. Its later dump reports
0xc00000fd(stack overflow) inShaderRecompiler::IR::TrackResources. That shader issue is outside this change.The full
virtual_memory_allocationsuite passes in Release. The existingSmallFiberStacksAndMigrationtest fails in Debug. The same failure also occurs when rebuilding the original thread and test sources without this fix under the same Debug configuration.Still open
__chkstk) behavior with the per-stack bounds.The current tests cover the reported crashes and the paths described above. Further game testing is still in progress; reports from other users would help identify regressions.
AI was used for error and code analysis, explanations, code suggestions, test design, and automated builds and checks. I reviewed the earlier code changes and tested Pragmata myself.
@coderabbitai[bot] on GitHub · 2026-11-05 21:57 UTC · original · edited 2026-11-08 19:48 UTC
Walkthrough
The pthread and loader paths pass guest stack bounds into guest execution. On Windows, these paths set the TEB bounds during guest execution and restore the host bounds afterward. Windows x64 fiber switching saves native stack bounds, clears the TEB bounds during guest-fiber execution, and restores them afterward. Windows-only tests cover normal return,
PthreadExit, handled faults, and main-entry stack-bound behavior. TheInstsize assertion also changes.Suggested reviewers:
nmzikChange: Bug fix
Merge Risk:
Moderate · previous review
c7811The virtual-memory test target will not build because the test runner calls three test functions that do not exist. Remove the stale call and reconcile or restore the two rollback tests before merging.
Pre-merge checks:
4 ·
1
Full details: Title check
Explanation
The title "kernel: preserve Windows guest stack bounds" matches the main change: passing guest stack bounds into RunOnGuestStack and RunEntry, writing them into the Windows TEB during guest execution, and restoring host bounds afterward. It is specific and concise, and it follows the subsystem-prefix style.
Full details: Description check
Explanation
The description states the crash (0xc0000409 / FAST_FAIL_INVALID_SET_OF_CONTEXT in RtlRestoreContext), its cause (zero Windows stack bounds while the saved stack pointer lies in the guest stack), and the changes in pthread.cpp, runtimeLinker.cpp, Value.h, and the tests. It also gives test results and open items, so it is clearly related to the changeset.
Full details: Docstring Coverage
Explanation
Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 36 functions across 6 files.
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share
@coderabbitai[bot] on GitHub · 2026-11-05 21:57 UTC · original · reviewed
178a10b0-1476-412b-b8c8-afced467553bReviewing files that changed from the base of the PR and between
a0268f1de4and511855a8e7.src/graphics/shader/recompiler/ir/Value.hsrc/kernel/pthread.cppsrc/kernel/pthread.hsrc/loader/runtimeLinker.cpptests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@Nawid3333 on GitHub · 2026-11-07 22:00 UTC · original
On your two open points (
__chkstkwith per-stack bounds, and fibers on a different stack): they interact. A fiber runs withrspinside the game's fiber context (FiberStartOnGuestStack,addr_context + size_context), which can be any guest memory, not the thread's stack.FiberRun,FiberSwitch,FiberReturnToThreadandFiberRestoreContextnever touchgs:0x08/gs:0x10, so while a fiber runs the TEB still holds the thread's bounds fromRunOnGuestStack.With real bounds that matters for every host frame larger than a page:
__chkstkcompares the newrspwithgs:0x10and, when it is below, probes downward from StackLimit page by page. For a fiber context below the thread stack that walks into the thread stack's guard page or unmapped memory. Host frames that guest calls can reach from a fiber includeEmulator::LoadExec(wchar_t executable[32768], viaSystemServiceLoadExec),QueueUsbAudioindualSenseHaptics.cpp(16 KiBdiscarded, viaAudioOutOutputs) and the CRT's console write (5 KiB translation buffer in_write).I hit this in a lab test on Windows 11: a fiber whose stack lies below the thread's StackLimit ends with
0xC00000FDas soon as it callsLog::WriteToConsoleAndLog; the same run withgs:0x08/gs:0x10set to 0, as main does, passes.Two ways out: keep 0 while a fiber is current, or install the fiber's range (
addr_context,addr_context + size_context) on every fiber entry, switch and resume, and restore the caller's bounds on return to the thread (including after a fiber migrated to another thread).@giulienh on GitHub · 2026-11-08 11:15 UTC · original
Thanks for mentioning, I’m gonna Look at that later
@giulienh on GitHub · 2026-11-08 17:34 UTC · original
Issue with fibers should now be resolved
@coderabbitai[bot] on GitHub · 2026-11-08 17:41 UTC · original · reviewed
8bafa12b-88e4-4261-a8d0-fc783f26c4d0Reviewing files that changed from the base of the PR and between
995cca2543and83d96d56d8.src/libs/libKernel.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@Nawid3333 on GitHub · 2026-11-08 17:51 UTC · original · edited 2026-11-08 17:54 UTC
Thanks, I read
83d96d56d. It covers the__chkstkcase:FiberRunclearsgs:0x08/gs:0x10before the fiber runs, so__chkstkno longer probes from the thread's stack limit into unrelated memory,FiberSwitchkeeps the 0/0 bounds, and whenFiberRunreturns it restores the bounds it read on entry, so a fiber that moves between threads leaves each thread with its own bounds.Two small things:
tests/VirtualMemoryAllocationTests.cpp. The other files merge cleanly.UmtxOp,KernelStopUnloadModule, the AIO code and a few fiber functions. Leaving those out would make the fix easier to review.@coderabbitai[bot] on GitHub · 2026-11-08 18:49 UTC · original · reviewed
d75b8254-f784-40ca-82f8-9c48ca6f6356Reviewing files that changed from the base of the PR and between
83d96d56d8andf072bd857a.src/graphics/shader/recompiler/ir/Value.hsrc/kernel/pthread.cppsrc/kernel/pthread.hsrc/libs/libKernel.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@giulienh on GitHub · 2026-11-08 19:13 UTC · original
yeah i get what you mean, i fixed the merge conflict, fixing the reformating would take a very long time so i think I will just leave it like this, still thanks for your help
@Nawid3333 on GitHub · 2026-11-08 19:15 UTC · original
if you like i could have another look at it tomorrow
@ -1264,0 +1292,4 @@#endif/// Reports failures in the loader's main-entry stack and host-bound restoration checks.void TestMainEntryUsesGuestStackAndRestoresHostBounds() {@coderabbitai[bot] on GitHub · 2026-11-08 19:16 UTC · original · edited 2026-11-08 19:49 UTC
Remove the stale main-entry test call.
Line 5925 still calls
TestMainEntryUsesGuestStackAndDisablesHostChecks, but this rename removes its definition. The test target cannot compile on any platform. Remove the stale call; Line 5922 already runs the renamed test. (raw.githubusercontent.com)✅ Addressed in commit
11fb836@coderabbitai[bot] on GitHub · 2026-11-08 19:16 UTC · original · edited 2026-11-08 19:49 UTC
On
tests/VirtualMemoryAllocationTests.cppline 5924 (outdated):Reconcile the rollback test calls with their fixtures.
Neither rollback test is defined in this revision, so these calls also prevent the test target from compiling. Reconcile the calls with the current fixtures or restore the missing tests and their dependencies. (raw.githubusercontent.com)
✅ Addressed in commit
11fb836@coderabbitai[bot] on GitHub · 2026-11-08 19:16 UTC · original · reviewed
Actionable comments posted: 2
2aecc385-76e0-4db1-91f8-51cb9150aeb4Reviewing files that changed from the base of the PR and between
f072bd857aandc78115ff53.src/graphics/shader/recompiler/ir/Value.htests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@giulienh on GitHub · 2026-11-08 19:49 UTC · original
if you want to, sure
@Nawid3333 on GitHub · 2026-11-09 14:40 UTC · original
@giulienh I had the other look at
11fb83629. It merges cleanly with mainf399d4818, and on that merge (Windows 11, clang-cl)--guest-stack-onlyand the fullvirtual_memory_allocation_testspass. I went through everything that touchesgs:0x08/gs:0x10(main entry, worker threads, thePthreadExitfast path, a handled fault,FiberRun,FiberSwitch,FiberReturnToThread, a fiber that moves to another thread) and found no path with wrong bounds. The 3 test calls removed in11fb83629are stale: two name tests main no longer has, and the third is the old name of your renamed main-entry test.One gap: nothing tests the fiber part of
83d96d56d, so removing theFiberSetThreadStackBoundscalls inFiberRunstill passes. This case covers it; on that merge it passes, and it fails when I remove either the clear or the restore:Register it next to
TestSmallFiberStacksAndMigrationwithRunTest(under the same Windows check). Up to you whether you take it.View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.