loader: keep the caller's flags in the TLS stubs #1571

Manually merged
github merged 1 commit from gh-pr/1571/head into gh-pr/1571/base 2026-11-26 10:00:01 +00:00
Owner

@⁠Nawid3333 on GitHub · 2026-10-16 21:43 UTC · original
Nawid3333:loader/tls-stubs-keep-flags → main · +68 −9 · 2 files · 1 commits · merged 2026-10-16 22:05 UTC

A patched TLS load (mov reg, fs:[0] replaced by a call to TlsRegStub, which calls SafeCall) changed the guest's arithmetic flags. Both stubs moved RSP past the red zone with sub rsp,0x80 and add rsp,0x80, and SUB and ADD write the flags: the subs ran before SafeCall's pushfq saved them, and the adds after its popfq restored them. Guest code that compares, loads fs:[0] and then branches on the result could therefore branch on the stack-pointer arithmetic instead.

Change (jit.h): lea rsp,[rsp-0x80] plus a two-byte nop, so the patched call offset, the register byte and SafeCall's function pointer stay at the same offsets, and lea rsp,[rsp+0x80]. LEA doesn't touch the flags.

Test: TlsStubsPreserveFlags (VirtualMemoryAllocationTests) places SafeCall and a TlsRegStub the way RuntimeLinker does and calls the stub right after add al,1 with two inputs: 0x7f (OF, SF and AF set) and 0xff (CF, PF, AF and ZF set). It checks the six status flags, the output register and RAX. With the old bytes it fails; with the change all VirtualMemoryAllocationTests pass (Windows 11, clang-cl), and fork CI runs it on Windows and Linux (macOS skips it like the file's other JIT tests).

I don't know of a game where this shows; it affects any guest code that keeps flags live across a TLS load.

The same fix is in fxpw's fork (a980b942f, "Preserve arithmetic flags across guest TLS MOV replacements") and in ClGratton's (201eaf049); this one keeps the test in the existing loader tests.

If you'd like this done differently, tell me and I'll change it.

Written with Claude Code (AI): it wrote the change and the test and ran them on my PC (Windows 11). I reviewed the diff and this description before opening the PR.

🤖 Generated with Claude Code

**@⁠Nawid3333** on GitHub · 2026-10-16 21:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1571) `Nawid3333:loader/tls-stubs-keep-flags` → `main` · +68 −9 · 2 files · 1 commits · merged 2026-10-16 22:05 UTC A patched TLS load (`mov reg, fs:[0]` replaced by a call to `TlsRegStub`, which calls `SafeCall`) changed the guest's arithmetic flags. Both stubs moved RSP past the red zone with `sub rsp,0x80` and `add rsp,0x80`, and SUB and ADD write the flags: the subs ran before `SafeCall`'s `pushfq` saved them, and the adds after its `popfq` restored them. Guest code that compares, loads `fs:[0]` and then branches on the result could therefore branch on the stack-pointer arithmetic instead. **Change** (`jit.h`): `lea rsp,[rsp-0x80]` plus a two-byte nop, so the patched call offset, the register byte and `SafeCall`'s function pointer stay at the same offsets, and `lea rsp,[rsp+0x80]`. LEA doesn't touch the flags. **Test:** `TlsStubsPreserveFlags` (`VirtualMemoryAllocationTests`) places `SafeCall` and a `TlsRegStub` the way `RuntimeLinker` does and calls the stub right after `add al,1` with two inputs: 0x7f (OF, SF and AF set) and 0xff (CF, PF, AF and ZF set). It checks the six status flags, the output register and RAX. With the old bytes it fails; with the change all `VirtualMemoryAllocationTests` pass (Windows 11, clang-cl), and fork CI runs it on Windows and Linux (macOS skips it like the file's other JIT tests). I don't know of a game where this shows; it affects any guest code that keeps flags live across a TLS load. The same fix is in fxpw's fork (a980b942f, "Preserve arithmetic flags across guest TLS MOV replacements") and in ClGratton's (201eaf049); this one keeps the test in the existing loader tests. If you'd like this done differently, tell me and I'll change it. Written with Claude Code (AI): it wrote the change and the test and ran them on my PC (Windows 11). I reviewed the diff and this description before opening the PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
A patched TLS load calls TlsRegStub and SafeCall, which moved RSP past the
red zone with sub/add rsp,0x80. ADD and SUB write the arithmetic flags, so
the sub ran before SafeCall's pushfq saved them and the add ran after its
popfq restored them: guest code that compares, loads fs:[0] and then
branches on the flags could branch the wrong way. lea moves RSP without
touching the flags. The entry lea plus a two-byte nop keeps every patched
offset in both stubs; the exit lea is one byte longer and moves only ret.

TlsStubsPreserveFlags calls the stubs with two flag patterns and checks
the status flags, the output register and RAX; it fails with the old
bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:00:01 +00:00
github manually merged commit 50f618f571 into gh-pr/1571/base 2026-11-26 10:00:01 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-16 21:46 UTC · original

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 09a83ecd-977a-41c4-bc03-2f02fb451a79
📥 Commits

Reviewing files that changed from the base of the PR and between 5dec523143 and 50f618f571.

📒 Files selected for processing: 2
  • src/loader/jit.h
  • tests/VirtualMemoryAllocationTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

📝 Walkthrough

The JIT call stubs replace stack arithmetic with LEA instructions and add NOP instructions while retaining their declared buffer sizes. A Linux/Windows test invokes a TLS register stub through SafeCall and checks the returned TLS address, RAX, and status flags for inputs 0x7f and 0xff.

Suggested reviewers: nmzik

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 50f61

This change keeps the caller's CPU flags intact across TLS stub calls and adds a test for it. No merge-blocking risk was found.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description check Passed The description clearly explains the TLS flag-preservation issue, the LEA-based fix, offset compatibility, and the added regression test.
Title check Passed The title is concise and accurately identifies the main change: preserving the caller's arithmetic flags in TLS stubs.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-16 21:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1571#issuecomment-6225303407) <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1571?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `09a83ecd-977a-41c4-bc03-2f02fb451a79` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 5dec523143930e35a6a5a9839f972774420b7958 and 50f618f571b9cf6fcfafaf4c1290c061d2f6c9af. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing: 2</strong></summary> <dl> <dd> * `src/loader/jit.h` * `tests/VirtualMemoryAllocationTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The JIT call stubs replace stack arithmetic with LEA instructions and add NOP instructions while retaining their declared buffer sizes. A Linux/Windows test invokes a TLS register stub through `SafeCall` and checks the returned TLS address, RAX, and status flags for inputs `0x7f` and `0xff`. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"50f618f571b9cf6fcfafaf4c1290c061d2f6c9af" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>50f61</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `50f61` --> <!-- final_review_risk_coverage:{"sourceCommitId":"50f618f571b9cf6fcfafaf4c1290c061d2f6c9af","coveredCommitId":"50f618f571b9cf6fcfafaf4c1290c061d2f6c9af","kind":"reviewed"} --> This change keeps the caller's CPU flags intact across TLS stub calls and adds a test for it. No merge-blocking risk was found. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the TLS flag-preservation issue, the LEA-based fix, offset compatibility, and the added regression test. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title is concise and accurately identifies the main change: preserving the caller's arithmetic flags in TLS stubs. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1571)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.