fix(libkernel): keep ymm upper halves across a redirected raise #1478

Merged
awake-devel merged 1 commit from upstream-pr/1478 into main 2026-10-09 19:05:05 +00:00
awake-devel commented 2026-10-08 08:49:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by awake-devel on 2026-10-08T08:49:17Z.


⚠️ Needs testing on Windows before merge. This change was not built or run on Windows: the author has no Windows machine. Please test it on Windows (build, full ctest, and a title that exercises GC delivery) before merging.

What

On Windows, sceKernelRaiseException redirects a thread that is not in an alertable TimedWait wait: it reads the thread's context, points it at Aps5RedirectedEntryStub, runs the handler and resumes the thread with RtlRestoreContext. That context has no CONTEXT_XSTATE, so only the low 128 bits of each vector register are restored. The upper halves of ymm0-ymm15 come back as the handler and the delivery path left them, and anything there that runs vzeroupper or a VEX instruction (Zen 2 guest code compiled for AVX, the CRT's memcpy when it copies the CONTEXT) clears them. A guest thread interrupted in the middle of AVX code, for example a 32-byte copy loop, then resumes with zeroed upper lanes and writes wrong data. TechnicalDebt listed this as a known gap.

  • The entry stub now also stores ymm0-ymm15 in the delivery it already fills with the live registers, when the CPU and the OS enable AVX (__builtin_cpu_supports("avx"), which checks XCR0).
  • The redirected entry no longer calls RtlRestoreContext itself: a new exit routine loads the saved ymm0-ymm15 and then jumps to RtlRestoreContext, which restores the low halves (and any change the handler made to them through uc_mcontext) without touching the upper halves.
  • The delivery grows by 528 bytes on the target's stack below its red zone; the existing committed-stack check covers it.
  • The APC path and a raise on the calling thread are unchanged: there the handler runs inside a call, where the upper halves are not preserved by either ABI.
  • The TechnicalDebt line about the YMM upper halves is removed.

This touches lines that #1421 (open) and #1431 (open) also change in Exception.cpp, GuestRaiseException.cpp and TechnicalDebt.md; the conflicts are textual. The change does not depend on the restore path #1421 selects (NtContinue today, the user-mode iretq restore with #1421): neither touches the upper halves, which the exit loads right before it. It also applies on top of #1421; the conflicts are textual.

This PR was investigated and written by Claude Code (AI), and posted by me after review.

Tested

Not built or run on Windows. I have no Windows machine, so neither the fix nor the new test phase has been compiled with MinGW or executed. What was checked:

  • Offsets by hand against the Windows SDK layout: CONTEXT is 1232 bytes with Rax at 0x78, so in Delivery the context starts at 16, vectors at 1248 and saveVectors at 1760; the stub runs 40 bytes below the delivery, which gives the 176/1288/1800 displacements it uses. The static_asserts encode these and will fail the Windows build if any is wrong.
  • The stub and exit assembly assemble with GNU as on Linux (x86-64).
  • Linux (Arch, GCC, Release, -DBUILD_TESTING=ON, APS5_WRITE_WATCH_IMPORTS=watch): the changed code is under _WIN32 and the test is registered on Windows only, so Linux is unaffected. Full ctest -j4: 423/423 passed, 0 failed, 0 skipped, same as main (bc1fbe81). Under VK_LAYER_KHRONOS_validation (ctest -j2 -V): 423/423 passed, 27 Validation Error lines, the same VUIDs and counts as main.

What needs to be run on Windows:

  • ctest -R ^guest_raise_exception$ --repeat until-fail:20: the new phase loads a pattern into ymm0-ymm15, spins, gets 100 raises whose handler runs vzeroall, and compares the registers afterwards. It is skipped on a CPU without AVX.
  • Mutation check: with this branch's Exception.cpp reverted to main (test kept), the new phase should fail (the upper lanes come back zeroed); with the fix it should pass.
  • Full ctest against main, and a Unity title that stops threads for GC (for example the one in discussion #726).

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

🤖 Generated with Claude Code

https://claude.ai/code/session_01HeC9bA3n74TzJRYv9AgBE8

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4784245756 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1478). Originally posted by [awake-devel](https://github.com/awake-devel) on 2026-10-08T08:49:17Z. --- > ⚠️ **Needs testing on Windows before merge.** This change was not built or run on Windows: the author has no Windows machine. Please test it on Windows (build, full ctest, and a title that exercises GC delivery) before merging. ### What On Windows, `sceKernelRaiseException` redirects a thread that is not in an alertable `TimedWait` wait: it reads the thread's context, points it at `Aps5RedirectedEntryStub`, runs the handler and resumes the thread with `RtlRestoreContext`. That context has no `CONTEXT_XSTATE`, so only the low 128 bits of each vector register are restored. The upper halves of `ymm0`-`ymm15` come back as the handler and the delivery path left them, and anything there that runs `vzeroupper` or a VEX instruction (Zen 2 guest code compiled for AVX, the CRT's `memcpy` when it copies the `CONTEXT`) clears them. A guest thread interrupted in the middle of AVX code, for example a 32-byte copy loop, then resumes with zeroed upper lanes and writes wrong data. TechnicalDebt listed this as a known gap. - The entry stub now also stores `ymm0`-`ymm15` in the delivery it already fills with the live registers, when the CPU and the OS enable AVX (`__builtin_cpu_supports("avx")`, which checks `XCR0`). - The redirected entry no longer calls `RtlRestoreContext` itself: a new exit routine loads the saved `ymm0`-`ymm15` and then jumps to `RtlRestoreContext`, which restores the low halves (and any change the handler made to them through `uc_mcontext`) without touching the upper halves. - The delivery grows by 528 bytes on the target's stack below its red zone; the existing committed-stack check covers it. - The APC path and a raise on the calling thread are unchanged: there the handler runs inside a call, where the upper halves are not preserved by either ABI. - The TechnicalDebt line about the YMM upper halves is removed. This touches lines that #1421 (open) and #1431 (open) also change in `Exception.cpp`, `GuestRaiseException.cpp` and `TechnicalDebt.md`; the conflicts are textual. The change does not depend on the restore path #1421 selects (`NtContinue` today, the user-mode `iretq` restore with #1421): neither touches the upper halves, which the exit loads right before it. It also applies on top of #1421; the conflicts are textual. This PR was investigated and written by Claude Code (AI), and posted by me after review. ### Tested **Not built or run on Windows.** I have no Windows machine, so neither the fix nor the new test phase has been compiled with MinGW or executed. What was checked: - Offsets by hand against the Windows SDK layout: `CONTEXT` is 1232 bytes with `Rax` at 0x78, so in `Delivery` the context starts at 16, `vectors` at 1248 and `saveVectors` at 1760; the stub runs 40 bytes below the delivery, which gives the 176/1288/1800 displacements it uses. The `static_assert`s encode these and will fail the Windows build if any is wrong. - The stub and exit assembly assemble with GNU as on Linux (x86-64). - Linux (Arch, GCC, Release, `-DBUILD_TESTING=ON`, `APS5_WRITE_WATCH_IMPORTS=watch`): the changed code is under `_WIN32` and the test is registered on Windows only, so Linux is unaffected. Full `ctest -j4`: 423/423 passed, 0 failed, 0 skipped, same as `main` (bc1fbe81). Under `VK_LAYER_KHRONOS_validation` (`ctest -j2 -V`): 423/423 passed, 27 `Validation Error` lines, the same VUIDs and counts as `main`. What needs to be run on Windows: - `ctest -R ^guest_raise_exception$ --repeat until-fail:20`: the new phase loads a pattern into `ymm0`-`ymm15`, spins, gets 100 raises whose handler runs `vzeroall`, and compares the registers afterwards. It is skipped on a CPU without AVX. - Mutation check: with this branch's `Exception.cpp` reverted to `main` (test kept), the new phase should fail (the upper lanes come back zeroed); with the fix it should pass. - Full ctest against `main`, and a Unity title that stops threads for GC (for example the one in discussion #726). ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01HeC9bA3n74TzJRYv9AgBE8
github-actions[bot] commented 2026-10-08 09:00:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-08T09:00:06Z.


Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#1562 core/libs/prx/libkernel/System/src/Exception.cpp L15-18, L83-112, L159-163, L186-190, L193-234, L247-266
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6056424112 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1478#issuecomment-6056424112). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-08T09:00:06Z. --- <!-- pr-overlap --> Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in **Depends on**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | #1562 | `core/libs/prx/libkernel/System/src/Exception.cpp` [L15-18](https://github.com/boykopovar/AnyPS5/blob/17350cf5fd54ad5c79ee495ed8e8615f4663bbd6/core/libs/prx/libkernel/System/src/Exception.cpp#L15-L18), [L83-112](https://github.com/boykopovar/AnyPS5/blob/17350cf5fd54ad5c79ee495ed8e8615f4663bbd6/core/libs/prx/libkernel/System/src/Exception.cpp#L83-L112), [L159-163](https://github.com/boykopovar/AnyPS5/blob/17350cf5fd54ad5c79ee495ed8e8615f4663bbd6/core/libs/prx/libkernel/System/src/Exception.cpp#L159-L163), [L186-190](https://github.com/boykopovar/AnyPS5/blob/17350cf5fd54ad5c79ee495ed8e8615f4663bbd6/core/libs/prx/libkernel/System/src/Exception.cpp#L186-L190), [L193-234](https://github.com/boykopovar/AnyPS5/blob/17350cf5fd54ad5c79ee495ed8e8615f4663bbd6/core/libs/prx/libkernel/System/src/Exception.cpp#L193-L234), [L247-266](https://github.com/boykopovar/AnyPS5/blob/17350cf5fd54ad5c79ee495ed8e8615f4663bbd6/core/libs/prx/libkernel/System/src/Exception.cpp#L247-L266) | | |
popcoder565 commented 2026-10-08 09:19:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-08T09:19:04Z.


I tested this on Windows 10 (19045) with MinGW-w64 GCC 15.2.0 (WinLibs r7), a Release build, on an Intel Core i7-12700H (AVX2, no AVX-512). It builds, the static_asserts hold, and the new phase does what it should. Below is the run on its own on main, then together with #1421.

This PR merged onto main e82e03f1

  • ctest -R ^guest_raise_exception$ --repeat until-fail:20: 3 passes, then a timeout in the busy-thread phase (only the first thread had started). This is the lost-delivery hang that #1421 fixes, and it happens on main without this PR too. The vector phase passed in the 3 runs that reached it. Those runs return through NtContinue, so that path keeps the reloaded upper halves as well.
  • Full ctest: 423 of 425 pass. agc_driver_srgb8_color_target failed (#1434, an NVIDIA import flake), and guest_raise_exception timed out, as above.
  • Mutation check (Exception.cpp back to main, test kept): 1 of 4 runs aborted, and 3 of 4 timed out. With main's context flags each handler returns through NtContinue. This phase raises again as soon as calls moves, so the next raise often finds the thread inside NtContinue, and that delivery is lost (#1421). ExpectDelivery's 5000 × sleep_for(1 ms) takes 15.6 ms per step on Windows (#1471), so a lost delivery outlasts the 30 s timeout instead of failing the Require. On main alone the mutation check is therefore noisy.

Together with #1421 (merged locally; the conflicts were textual):

  • In RaiseOn, I kept #1421's retry loop with this PR's Delivery initializers: {handler, signum, {}, {}, 0} for the APC copy and SaveVectors ? 1u : 0u for the redirect.
  • In the test, I kept both sets of phases with the vector phase last; its ExpectDelivery base adds ContinuingRounds + SelfingRounds.
  • I dropped the TechnicalDebt YMM line.

Results:

  • ctest -R ^guest_raise_exception$ --repeat until-fail:20: 20 of 20 pass, 10.1 to 10.6 s each.
  • Mutation check (#1421's Exception.cpp without this PR's changes, merged test kept): 5 of 5 runs abort at the vector comparison. With a temporary print before the memcmp, 256 of the 512 bytes differ, all of them in the upper halves; the low halves come back through RtlRestoreContext. With this PR the phase passes. So the user-mode iretq restore that #1421 selects also keeps the upper halves that Aps5RedirectedExit loads.
  • Full ctest: 424 of 425 pass, and the only failure is agc_driver_srgb8_color_target (#1434).

Not tested: a Unity title that stops threads for GC. I don't have one.

Tested with AI assistance (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6056729157 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1478#issuecomment-6056729157). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-08T09:19:04Z. --- I tested this on Windows 10 (19045) with MinGW-w64 GCC 15.2.0 (WinLibs r7), a Release build, on an Intel Core i7-12700H (AVX2, no AVX-512). It builds, the `static_assert`s hold, and the new phase does what it should. Below is the run on its own on `main`, then together with #1421. **This PR merged onto `main` e82e03f1** - `ctest -R ^guest_raise_exception$ --repeat until-fail:20`: 3 passes, then a timeout in the busy-thread phase (only the first thread had started). This is the lost-delivery hang that #1421 fixes, and it happens on `main` without this PR too. The vector phase passed in the 3 runs that reached it. Those runs return through `NtContinue`, so that path keeps the reloaded upper halves as well. - Full ctest: 423 of 425 pass. `agc_driver_srgb8_color_target` failed (#1434, an NVIDIA import flake), and `guest_raise_exception` timed out, as above. - Mutation check (`Exception.cpp` back to `main`, test kept): 1 of 4 runs aborted, and 3 of 4 timed out. With `main`'s context flags each handler returns through `NtContinue`. This phase raises again as soon as `calls` moves, so the next raise often finds the thread inside `NtContinue`, and that delivery is lost (#1421). `ExpectDelivery`'s 5000 × `sleep_for(1 ms)` takes 15.6 ms per step on Windows (#1471), so a lost delivery outlasts the 30 s timeout instead of failing the `Require`. On `main` alone the mutation check is therefore noisy. **Together with #1421** (merged locally; the conflicts were textual): - In `RaiseOn`, I kept #1421's retry loop with this PR's `Delivery` initializers: `{handler, signum, {}, {}, 0}` for the APC copy and `SaveVectors ? 1u : 0u` for the redirect. - In the test, I kept both sets of phases with the vector phase last; its `ExpectDelivery` base adds `ContinuingRounds + SelfingRounds`. - I dropped the TechnicalDebt YMM line. Results: - `ctest -R ^guest_raise_exception$ --repeat until-fail:20`: 20 of 20 pass, 10.1 to 10.6 s each. - Mutation check (#1421's `Exception.cpp` without this PR's changes, merged test kept): 5 of 5 runs abort at the vector comparison. With a temporary print before the `memcmp`, 256 of the 512 bytes differ, all of them in the upper halves; the low halves come back through `RtlRestoreContext`. With this PR the phase passes. So the user-mode `iretq` restore that #1421 selects also keeps the upper halves that `Aps5RedirectedExit` loads. - Full ctest: 424 of 425 pass, and the only failure is `agc_driver_srgb8_color_target` (#1434). Not tested: a Unity title that stops threads for GC. I don't have one. Tested with AI assistance (Claude Code).
hikazey commented 2026-10-08 10:24:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hikazey on 2026-10-08T10:24:27Z.


A second Windows machine, AMD this time: Windows 11 Pro (26200), MinGW-w64 GCC 15.2.0 (WinLibs r7, the CI build), Release, configured like CI, Ryzen 9 5900X (Zen 3, AVX2, no AVX-512). This commit merged onto main 73ac9ef7 on its own, without #1421.

build guest_raise_exception
this PR 6/6 passed; it builds, so the static_asserts on the CONTEXT/Delivery offsets hold
Exception.cpp from main, new test phase kept 6/6 aborted after about 9 s
full suite with this PR 429/429 passed (main alone: 429/429)

In the reverted runs the abort comes after the fifth thread starts and before the finished phase, which puts it in the new vector phase. So the ymm upper halves are lost on main on this CPU, and this change keeps them. No busy-thread hang (#1421) occurred in these 6 runs.

AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6057810527 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1478#issuecomment-6057810527). Originally posted by [hikazey](https://github.com/hikazey) on 2026-10-08T10:24:27Z. --- A second Windows machine, AMD this time: Windows 11 Pro (26200), MinGW-w64 GCC 15.2.0 (WinLibs r7, the CI build), Release, configured like CI, Ryzen 9 5900X (Zen 3, AVX2, no AVX-512). This commit merged onto `main` `73ac9ef7` on its own, without #1421. | build | `guest_raise_exception` | | --- | --- | | this PR | 6/6 passed; it builds, so the `static_assert`s on the `CONTEXT`/`Delivery` offsets hold | | `Exception.cpp` from `main`, new test phase kept | 6/6 aborted after about 9 s | | full suite with this PR | 429/429 passed (`main` alone: 429/429) | In the reverted runs the abort comes after the fifth thread starts and before the `finished` phase, which puts it in the new vector phase. So the ymm upper halves are lost on `main` on this CPU, and this change keeps them. No busy-thread hang (#1421) occurred in these 6 runs. AI-assisted: yes (Claude Code).
oneandonlydean commented 2026-10-09 09:56:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:56:06Z.


Could you rebase onto current main? The full build checks out this branch with main's workflow, and it stops at tools/check_test_registration.py not being on the branch yet, so nothing gets compiled. After a rebase it can get a full build and go in.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6078615988 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1478#issuecomment-6078615988). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T09:56:06Z. --- Could you rebase onto current main? The full build checks out this branch with main's workflow, and it stops at `tools/check_test_registration.py` not being on the branch yet, so nothing gets compiled. After a rebase it can get a full build and go in.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!1478
No description provided.