windows: patch guest FS TCB accesses through host TLS #1080

Closed
github-bot wants to merge 3 commits from gh-pr/1080/head into gh-pr/1080/base
Owner

@⁠NabuOX on GitHub · 2026-10-05 19:54 UTC · original
NabuOX:windows-tcb-upstream → main · +516 −41 · 6 files · 3 commits · closed without merging

Problem

On Windows, guest binaries can use absolute FS:[disp] accesses for PS5/FreeBSD thread-control-block fields, for example mov rax, qword ptr fs:[0x28] (64 48 8B 04 25 28 00 00 00).

Host Windows FS state does not directly represent the guest TCB — the host FS base is the TEB and cannot be pointed at guest memory — so these accesses cannot execute natively as-is. Unpatched they read host thread state, which either faults at the low address (0x28) or silently returns a value unrelated to the guest TCB.

Existing KytyPS5 handling covers narrower cases only:

  • it nops one specific fs:[0x28] store byte pattern, and
  • it redirects fs:[0x00] reads with a zero displacement, in non-shared modules only.

General 64-bit absolute FS reads and compares in executable and shared modules are not covered.

Solution

  • Allocate one process-lifetime Windows TLS key.
  • Publish each host thread's current guest TCB through its own TLS slot.
  • Initialize that value before main guest entry, pthread guest entry, and module init/fini entry; clear stale values when a thread or program is torn down.
  • Statically rewrite supported absolute FS:[disp] 64-bit MOV, XOR and CMP accesses, for displacements 0x00..0x3f.
  • Preserve registers, flags and guest red-zone semantics: the scratch register is saved and restored, and the stack pointer is parked below the guest frame while the rewrite reads the TCB.
  • Support both normal and expansion Windows TLS slots.

The rewrite is Windows-only and is compiled out on other hosts, which are unchanged. The existing inherited behaviour (the fs:[0x28] store nop and the fs:[0x00] read trampoline) is preserved rather than replaced.

Tests

Native Windows, clang-cl 23.1.2 / MSVC 14.44.35207 / SDK 10.0.26100.0, Release + IPO:

  • focused TCB patcher (virtual_memory_allocation_tests --tcb-patcher-only): PASS
  • base TLS slot: PASS
  • expansion TLS slot: PASS
  • two-thread isolation (each host thread observes only its own guest TCB): PASS
  • full suite, run serially with -j 1: 52/52 PASS

The new WindowsGuestTcbStaticPatcher executes the patched fixture and checks MOV/XOR/CMP results, equality and inequality flags, zero/positive/high-bit values, scratch-register preservation, safe skipping of non-TCB FS/GS accesses, and both TLS slot kinds. The TCB patch counts are asserted with exact equality, so the fixture fails if any access stops being rewritten.

Linux/WSL (Ubuntu 26.04, clang 21.1.8, llvmpipe):

  • 33/49 PASS before and after the change
  • same 16 known llvmpipe/Vulkan capability failures in both runs
  • no regression

Note on the suite: it should be run with -j 1. Each guest-memory test reserves ~13.5 GB, and on a 16 GB host a parallel ctest run can produce false commit-limit failures that are unrelated to code.

Status / scope

Related: #1044 — the FS:[disp] read pattern was observed there.

The FC27 report that exposed the fs:[0x28] pattern was not reproduced locally because no legal PS5 runtime dump was available. No FC27 compatibility milestone is claimed.

**@⁠NabuOX** on GitHub · 2026-10-05 19:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080) `NabuOX:windows-tcb-upstream` → `main` · +516 −41 · 6 files · 3 commits · closed without merging ### Problem On Windows, guest binaries can use absolute `FS:[disp]` accesses for PS5/FreeBSD thread-control-block fields, for example `mov rax, qword ptr fs:[0x28]` (`64 48 8B 04 25 28 00 00 00`). Host Windows FS state does not directly represent the guest TCB — the host FS base is the TEB and cannot be pointed at guest memory — so these accesses cannot execute natively as-is. Unpatched they read host thread state, which either faults at the low address (`0x28`) or silently returns a value unrelated to the guest TCB. Existing KytyPS5 handling covers narrower cases only: - it nops one specific `fs:[0x28]` **store** byte pattern, and - it redirects `fs:[0x00]` **reads** with a zero displacement, in non-shared modules only. General 64-bit absolute FS reads and compares in executable and shared modules are not covered. ### Solution - Allocate one process-lifetime Windows TLS key. - Publish each host thread's current guest TCB through its own TLS slot. - Initialize that value before main guest entry, pthread guest entry, and module init/fini entry; clear stale values when a thread or program is torn down. - Statically rewrite supported absolute `FS:[disp]` 64-bit MOV, XOR and CMP accesses, for displacements `0x00..0x3f`. - Preserve registers, flags and guest red-zone semantics: the scratch register is saved and restored, and the stack pointer is parked below the guest frame while the rewrite reads the TCB. - Support both normal and expansion Windows TLS slots. The rewrite is Windows-only and is compiled out on other hosts, which are unchanged. The existing inherited behaviour (the `fs:[0x28]` store nop and the `fs:[0x00]` read trampoline) is preserved rather than replaced. ### Tests Native Windows, clang-cl 23.1.2 / MSVC 14.44.35207 / SDK 10.0.26100.0, Release + IPO: - focused TCB patcher (`virtual_memory_allocation_tests --tcb-patcher-only`): PASS - base TLS slot: PASS - expansion TLS slot: PASS - two-thread isolation (each host thread observes only its own guest TCB): PASS - full suite, run serially with `-j 1`: 52/52 PASS The new `WindowsGuestTcbStaticPatcher` executes the patched fixture and checks MOV/XOR/CMP results, equality and inequality flags, zero/positive/high-bit values, scratch-register preservation, safe skipping of non-TCB FS/GS accesses, and both TLS slot kinds. The TCB patch counts are asserted with exact equality, so the fixture fails if any access stops being rewritten. Linux/WSL (Ubuntu 26.04, clang 21.1.8, llvmpipe): - 33/49 PASS before and after the change - same 16 known llvmpipe/Vulkan capability failures in both runs - no regression Note on the suite: it should be run with `-j 1`. Each guest-memory test reserves ~13.5 GB, and on a 16 GB host a parallel `ctest` run can produce false commit-limit failures that are unrelated to code. ### Status / scope Related: #1044 — the `FS:[disp]` read pattern was observed there. The FC27 report that exposed the `fs:[0x28]` pattern was not reproduced locally because no legal PS5 runtime dump was available. No FC27 compatibility milestone is claimed.
Guest binaries address PS5/FreeBSD thread-control-block fields with absolute
FS:[disp] reads such as `mov rax, qword ptr fs:[0x28]`. On Windows the host FS
base is the TEB and cannot be pointed at guest memory, so these reads observe
host thread state instead of the guest TCB and fault or silently read the wrong
value. The existing handling is narrower: it nops one specific fs:[0x28] store
pattern and redirects fs:[0x00] reads with a zero displacement in non-shared
modules only.

Publish the per-thread guest TCB through Windows TLS and rewrite the supported
absolute reads to resolve it from there:

- allocate one process-lifetime Windows TLS key
- publish the current guest TCB for each host thread in its own TLS slot
- initialize it before main guest entry, pthread guest entry and module
  init/fini entry, and clear stale values when a thread or program goes away
- statically rewrite 64-bit absolute FS:[disp] MOV, XOR and CMP accesses for
  displacements 0x00..0x3f in executable and shared modules
- preserve flags, the scratch register and the guest red zone by parking the
  stack pointer below the guest frame for the duration of the rewrite
- handle both normal and expansion Windows TLS slots

The rewrite is Windows-only and leaves other hosts untouched.

Add WindowsGuestTcbStaticPatcher, which executes the patched fixture and checks
MOV/XOR/CMP results, equality and inequality flags, scratch-register
preservation, skipping of non-TCB FS/GS accesses, the normal and expansion TLS
slots, and a two-thread isolation check that each host thread only observes its
own guest TCB. The TCB patch counts are asserted exactly, so the fixture fails
if any access stops being rewritten.

The FS access pattern was reported in #1044. No legal PS5 runtime dump was
available locally, so that report was not reproduced and no game compatibility
milestone is claimed.
A program owns one TLS block per thread that used it, and a guest TCB lives inside
that block. ThreadLocalStorage::~ released every block at once, so destroying a
program unmapped the TLS block of a thread that was still running: that thread's
cached guest TCB pointer, and on Windows the patched FS:[disp] accesses, then read
guest TCB memory that had already been released.

Tie each TLS block's release to the thread that owns it:

- record the owning thread on the block when it is allocated
- only the owning thread releases its own block, which it can do safely because the
  block is reachable solely through that thread's host TLS slot
- park blocks owned by other threads in a process-lifetime deferred list during
  program destruction, instead of freeing them
- release deferred blocks from the owning thread: on guest entry, before a guest
  pthread enters guest code, and when a guest pthread stops
- report a failed deferred release instead of aborting, since a block that outlived
  its image may no longer have a backing range

This also covers the inherited per-thread TCB cache, which held the same raw pointer
into the same block. Non-Windows hosts keep the same behaviour, as the block
ownership rule is platform independent.

Validated on native Windows: focused TCB patcher, base and expansion TLS slots,
two-thread isolation and the full suite all pass (52/52, run serially with -j 1).
Linux/WSL is unchanged at 33/49, with the same 16 known llvmpipe/Vulkan capability
failures and no new regression.
TlsMainGetAddr() caches the guest TCB per thread and keys that cache on the main
Program pointer. A deferred TLS block belongs to the thread that drains it, so
ThreadLocalStorage::~ could park a block that still backed the calling thread's
cached TCB. Releasing it left g_tls_cached_main_tcb pointing at freed guest
memory, and because the cache key is raw Program* equality, a later Program
allocated at the same address matched the stale key and handed the freed TCB
straight back to guest code.

Add InvalidateCachedMainTcb(), which drops the thread's cached TCB and, on
Windows, clears the corresponding host TLS slot. ReleaseDeferredTlsBlocks() now
calls it for any parked block that covers g_tls_cached_main_tcb before releasing
that block. The existing fine-grained invalidations in Clear, DeleteTls and
DeleteProgram now use the same helper, which also removes three copies of it.

Only the owner thread may drain a parked block and the TCB cache is thread
local, so the calling thread is always the one holding the stale value; no other
thread needs to be signalled.

Note: no regression test accompanies this. Populating the cache requires
SetupTlsHandler() to set g_tls_main_program, which is private and needs a loaded
non-shared ELF with a PT_TLS handler, so the stale-cache path is not reachable
from the test binary without adding test-only hooks to the production API.

Validated on native Windows: focused TCB patcher (3x), base and expansion TLS
slots, two-thread isolation and the full suite all pass (52/52, serially with
-j 1). Linux/WSL is unchanged at 33/49 with the same 16 known llvmpipe/Vulkan
capability failures and no new regression.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:42:18 +00:00
github-bot closed this pull request 2026-11-26 09:42:18 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 20:03 UTC · original · edited 2026-10-05 23:00 UTC

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: 547295c6-478b-4e8c-b3f7-512406782006
📥 Commits

Reviewing files that changed from the base of the PR and between 9c8344afac and a16798ec83.

📒 Files selected for processing (1)
  • src/loader/runtimeLinker.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/loader/runtimeLinker.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

Walkthrough

On Windows, the patcher rewrites eligible guest FS-based 64-bit MOV, XOR, and CMP reads within the TCB range to use a selected host GS TLS slot. RuntimeLinker initializes the current thread’s guest TCB slot before guest entry and module callbacks, and clears it in cleanup paths. TLS blocks record their owner thread, and deferred cleanup runs on that thread. Tests cover supported and unsupported instruction forms, thread isolation, and expanded TLS slots.

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to a1679

The Windows guest TCB change keeps each thread's TLS slot valid until the owning thread invalidates it and then frees the block. No open merge-blocking risk remains from the reviewed evidence.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 9c834

Normal entry and same-thread cleanup are covered, but cross-thread teardown can leave a stale thread-state binding. Later thread reuse may then access obsolete memory. The established exposure is within the running process; no additional execution privilege was demonstrated.

Retained concerns

  • Medium · reliability · inferred: Deferred reclamation does not retire the owning thread's cached TCB and Windows TLS binding. After foreign-thread main-program destruction, RunEntry can free the parked block before initialization. If a replacement Program reuses the previous address, the inherited pointer-only cache check returns the obsolete TCB without updating the slot, and newly supported nonzero-offset reads dereference it. This is a conditional memory-lifetime and failure-containment concern; production teardown/reentry timing and actual address reuse remain unverified.
Security review details

Security Blast Radius

  • inferred — The established failure scope is guest-thread state and memory validity within the host process, including executable and shared-module reads. The inspected paths do not demonstrate an additional privilege grant, cross-tenant exposure or external-service attack path.

Security Findings and Attack Paths

  • inferred — A surviving owner thread, foreign-thread main-program destruction, deferred reclamation and Program-address reuse form a conditional stale-read path. The pointer-only cache weakness predates this PR; newly supported TCB reads inherit it through the host slot. No exploit or production reproduction was established.

Trust Boundaries and Controls

  • observed — Guest instruction bytes determine eligible operations and displacements, while the runtime supplies the host slot identity and TCB pointer. Same-thread DeleteTls clears both cache and slot before releasing memory; entry initialization replaces the binding when the cached Program differs.

Resilience and Maintainability Implications

  • observed — Deferring foreign-owner blocks avoids immediate reclamation while another thread may still reference them. Pthread cleanup drains deferred blocks before termination. These controls reduce the inherited teardown hazard, but do not invalidate bindings when the deferred block is finally freed.

Hardening Proposals

  • proposed — Make owner-thread retirement invalidate any cache and host slot referencing the retiring block before reclamation, and distinguish Program generations rather than relying on recycled addresses. Define whether cross-thread teardown permits subsequent guest reentry.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 42 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: patching guest FS TCB accesses through host TLS on Windows.
Description check ✅ Passed The description explains the guest FS access problem, the Windows TLS-based patching approach, its scope, and reported test results.
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.
  • Autopilot · 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-05 20:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#issuecomment-6002013039) · edited 2026-10-05 23:00 UTC <!-- 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/1080?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `547295c6-478b-4e8c-b3f7-512406782006` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 9c8344aface4d8d41bb569cc310dea234ccac416 and a16798ec836f6e6aed25768b587b12216e65258d. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/loader/runtimeLinker.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/loader/runtimeLinker.cpp </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. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough On Windows, the patcher rewrites eligible guest FS-based 64-bit MOV, XOR, and CMP reads within the TCB range to use a selected host GS TLS slot. RuntimeLinker initializes the current thread’s guest TCB slot before guest entry and module callbacks, and clears it in cleanup paths. TLS blocks record their owner thread, and deferred cleanup runs on that thread. Tests cover supported and unsupported instruction forms, thread isolation, and expanded TLS slots. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"a16798ec836f6e6aed25768b587b12216e65258d" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `a1679` <!-- final_review_risk_coverage:{"sourceCommitId":"a16798ec836f6e6aed25768b587b12216e65258d","coveredCommitId":"a16798ec836f6e6aed25768b587b12216e65258d","kind":"reviewed"} --> The Windows guest TCB change keeps each thread's TLS slot valid until the owning thread invalidates it and then frees the block. No open merge-blocking risk remains from the reviewed evidence. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `9c834` Normal entry and same-thread cleanup are covered, but cross-thread teardown can leave a stale thread-state binding. Later thread reuse may then access obsolete memory. The established exposure is within the running process; no additional execution privilege was demonstrated. **Retained concerns** - **Medium · reliability · inferred:** Deferred reclamation does not retire the owning thread's cached TCB and Windows TLS binding. After foreign-thread main-program destruction, RunEntry can free the parked block before initialization. If a replacement Program reuses the previous address, the inherited pointer-only cache check returns the obsolete TCB without updating the slot, and newly supported nonzero-offset reads dereference it. This is a conditional memory-lifetime and failure-containment concern; production teardown/reentry timing and actual address reuse remain unverified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The established failure scope is guest-thread state and memory validity within the host process, including executable and shared-module reads. The inspected paths do not demonstrate an additional privilege grant, cross-tenant exposure or external-service attack path. **Security Findings and Attack Paths** - _inferred_ — A surviving owner thread, foreign-thread main-program destruction, deferred reclamation and Program-address reuse form a conditional stale-read path. The pointer-only cache weakness predates this PR; newly supported TCB reads inherit it through the host slot. No exploit or production reproduction was established. **Trust Boundaries and Controls** - _observed_ — Guest instruction bytes determine eligible operations and displacements, while the runtime supplies the host slot identity and TCB pointer. Same-thread DeleteTls clears both cache and slot before releasing memory; entry initialization replaces the binding when the cached Program differs. **Resilience and Maintainability Implications** - _observed_ — Deferring foreign-owner blocks avoids immediate reclamation while another thread may still reference them. Pthread cleanup drains deferred blocks before termination. These controls reduce the inherited teardown hazard, but do not invalidate bindings when the deferred block is finally freed. **Hardening Proposals** - _proposed_ — Make owner-thread retirement invalidate any cache and host slot referencing the retiring block before reclamation, and distinguish Program generations rather than relying on recycled addresses. Define whether cross-thread teardown permits subsequent guest reentry. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 42 functions across 6 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :----------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: patching guest FS TCB accesses through host TLS on Windows. | | Description check | ✅ Passed | The description explains the guest FS access problem, the Windows TLS-based patching approach, its scope, and reported test results. | | 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. | </details> </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">Autopilot</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=1080)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [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) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 20:03 UTC · original · edited 2026-10-05 22:34 UTC
On src/loader/runtimeLinker.cpp line 1346 (outdated):

@@ -1320,6 +1341,9 @@ void RuntimeLinker::Clear() {
 	g_tls_main_program        = nullptr;
 	g_tls_cached_main_program = nullptr;
 	g_tls_cached_main_tcb     = nullptr;
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+	EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0);
+#endif

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

git diff --unified=50 dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 748897ca1130e0deb48050c4cac5b4ff6a166bec -- src/loader/runtimeLinker.cpp
printf '\n--- TLS symbols and callers ---\n'
rg -n -F -e 'InitializeMainTlsForCurrentThread' -e 'TlsMainGetAddr' -e 'FreeTlsBlock' -e 'DeleteTlss' -e 'RuntimeLinker::Clear' -e 'RuntimeLinker::DeleteProgram' -e 'UnloadProgram' -e 'RunEntry' src/loader
printf '\n--- target regions at reviewed head ---\n'
git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/loader/runtimeLinker.cpp | nl -ba | sed -n '1250,1395p;1870,1950p'

Repository: KytyPS5/KytyPS5

Length of output: 41366


🏁 Script executed:

printf '%s\n' '--- runtimeLinker.cpp TLS/freeing prologue ---'
git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/loader/runtimeLinker.cpp | nl -ba | sed -n '1,110p;900,980p;1110,1175p;1620,1680p;2180,2245p'
printf '%s\n' '--- declarations and lifecycle references ---'
rg -n -F -e 'CleanupThread' -e 'DeleteTlss(' -e 'UnloadProgram(' -e 'Clear(' -e 'TlsGetAddr(' -e 'PthreadDeleteStaticObjects' -e 'PthreadCreate' src | head -200
printf '%s\n' '--- owning lifecycle definitions ---'
rg -n -F 'void RuntimeLinker::UnloadProgram' src/loader/runtimeLinker.cpp
rg -n -F 'void RuntimeLinker::DeleteTlss' src/loader/runtimeLinker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 22956


🏁 Script executed:

printf '%s\n' '--- unload and clear caller ---'
git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/loader/runtimeLinker.cpp | nl -ba | sed -n '1138,1210p'
git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/emulator.cpp | nl -ba | sed -n '1,95p'
printf '%s\n' '--- pthread cleanup and creation ---'
git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/kernel/pthread.cpp | nl -ba | sed -n '3145,3255p'
printf '%s\n' '--- all RunEntry and Clear/Unload callers ---'
rg -n -F -e 'RunEntry(' -e '->Clear()' -e '.Clear()' -e 'UnloadProgram(' src/loader src/kernel src/emulator.cpp src/libs/libKernel.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10889


Prevent guest execution while deleting program TLS.

DeleteProgram destroys Program, and ThreadLocalStorage::~ThreadLocalStorage frees every stored TCB. Clear and DeleteProgram clear g_tls_main_tcb_key only on the calling thread. A live guest thread can retain a pointer to its freed TCB. A later patched TCB access on that thread can use freed memory.

Synchronize Clear and UnloadProgram with all guest threads, or invalidate the Windows TLS slot for every affected thread before destroying the program. Initialization at guest entry does not protect a thread that is already executing when deletion starts.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 20:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#discussion_r4188209642) · edited 2026-10-05 22:34 UTC On `src/loader/runtimeLinker.cpp` line 1346 (outdated): ```diff @@ -1320,6 +1341,9 @@ void RuntimeLinker::Clear() { g_tls_main_program = nullptr; g_tls_cached_main_program = nullptr; g_tls_cached_main_tcb = nullptr; +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0); +#endif ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash git diff --unified=50 dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 748897ca1130e0deb48050c4cac5b4ff6a166bec -- src/loader/runtimeLinker.cpp printf '\n--- TLS symbols and callers ---\n' rg -n -F -e 'InitializeMainTlsForCurrentThread' -e 'TlsMainGetAddr' -e 'FreeTlsBlock' -e 'DeleteTlss' -e 'RuntimeLinker::Clear' -e 'RuntimeLinker::DeleteProgram' -e 'UnloadProgram' -e 'RunEntry' src/loader printf '\n--- target regions at reviewed head ---\n' git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/loader/runtimeLinker.cpp | nl -ba | sed -n '1250,1395p;1870,1950p' ``` Repository: KytyPS5/KytyPS5 Length of output: 41366 --- 🏁 Script executed: ```bash printf '%s\n' '--- runtimeLinker.cpp TLS/freeing prologue ---' git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/loader/runtimeLinker.cpp | nl -ba | sed -n '1,110p;900,980p;1110,1175p;1620,1680p;2180,2245p' printf '%s\n' '--- declarations and lifecycle references ---' rg -n -F -e 'CleanupThread' -e 'DeleteTlss(' -e 'UnloadProgram(' -e 'Clear(' -e 'TlsGetAddr(' -e 'PthreadDeleteStaticObjects' -e 'PthreadCreate' src | head -200 printf '%s\n' '--- owning lifecycle definitions ---' rg -n -F 'void RuntimeLinker::UnloadProgram' src/loader/runtimeLinker.cpp rg -n -F 'void RuntimeLinker::DeleteTlss' src/loader/runtimeLinker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 22956 --- 🏁 Script executed: ```bash printf '%s\n' '--- unload and clear caller ---' git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/loader/runtimeLinker.cpp | nl -ba | sed -n '1138,1210p' git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/emulator.cpp | nl -ba | sed -n '1,95p' printf '%s\n' '--- pthread cleanup and creation ---' git show 748897ca1130e0deb48050c4cac5b4ff6a166bec:src/kernel/pthread.cpp | nl -ba | sed -n '3145,3255p' printf '%s\n' '--- all RunEntry and Clear/Unload callers ---' rg -n -F -e 'RunEntry(' -e '->Clear()' -e '.Clear()' -e 'UnloadProgram(' src/loader src/kernel src/emulator.cpp src/libs/libKernel.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10889 --- </details> **Prevent guest execution while deleting program TLS.** `DeleteProgram` destroys `Program`, and `ThreadLocalStorage::~ThreadLocalStorage` frees every stored TCB. `Clear` and `DeleteProgram` clear `g_tls_main_tcb_key` only on the calling thread. A live guest thread can retain a pointer to its freed TCB. A later patched TCB access on that thread can use freed memory. Synchronize `Clear` and `UnloadProgram` with all guest threads, or invalidate the Windows TLS slot for every affected thread before destroying the program. Initialization at guest entry does not protect a thread that is already executing when deletion starts. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4d9100737fe64234a5e28024 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 20:03 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: defe1426-9d87-4983-9d7f-494280f838e3
📥 Commits

Reviewing files that changed from the base of the PR and between dc3cd2d2c9 and 748897ca11.

📒 Files selected for processing (6)
  • src/kernel/pthread.cpp
  • src/loader/guestInstructionPatcher.cpp
  • src/loader/guestInstructionPatcher.h
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h
  • tests/VirtualMemoryAllocationTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 20:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#pullrequestreview-5419873503) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `defe1426-9d87-4983-9d7f-494280f838e3` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 and 748897ca1130e0deb48050c4cac5b4ff6a166bec. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/kernel/pthread.cpp` * `src/loader/guestInstructionPatcher.cpp` * `src/loader/guestInstructionPatcher.h` * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` * `tests/VirtualMemoryAllocationTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=2cc8dd38-a23f-46eb-8d6b-9eb9731cb5ba attempt=f092dcea-c301-43b3-99bd-2d1d6dfc1276 batch=1/1 -->
Author
Owner

@⁠NabuOX on GitHub · 2026-10-05 22:16 UTC · original
On src/loader/runtimeLinker.cpp line 1346 (outdated):

@@ -1320,6 +1341,9 @@ void RuntimeLinker::Clear() {
 	g_tls_main_program        = nullptr;
 	g_tls_cached_main_program = nullptr;
 	g_tls_cached_main_tcb     = nullptr;
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+	EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0);
+#endif

Finding confirmed. Thanks — this is a real lifetime bug, and it is worse than the Windows TLS slot alone: the pre-existing per-thread TCB cache (g_tls_cached_main_tcb) holds the same raw pointer into the same block, so the defect predates this PR rather than being introduced by it.

Lifecycle path

  • TlsGetAddr() allocates one block per thread in program->tls.tlss[thread_id] and stores the guest TCB inside it. TlsMainGetAddr() caches TlsGetAddr(main) + tls.tcb_offset in g_tls_cached_main_tcb, and the Windows patcher publishes the same address into g_tls_main_tcb_key.
  • Teardown runs from a different thread than the block's owner:
    • RuntimeLinker::Clear() -> DeleteProgram() -> ~Program() -> ThreadLocalStorage::~ThreadLocalStorage() -> freed every block.
    • sceKernelStopUnloadModule -> RuntimeLinker::UnloadProgram() -> DeleteProgram() -> the same.
  • DeleteProgram/Clear cleared the calling thread's slot only. A block belonging to any other live thread was unmapped while that thread could still reach it, and a later patched FS:[disp] access on that thread dereferenced freed guest memory.
  • Reachability: Clear() is off the normal shutdown path (emulator.cpp exits via std::quick_exit(0), which skips both atexit-registered KytyClose and static destructors), so the reachable teardown is sceKernelStopUnloadModule -> UnloadProgram -> DeleteProgram. That path only returns KERNEL_ERROR_EBUSY if the guest registered an at-exit count function (g_get_thread_atexit_count_func), so the hazard is not unconditionally guarded. Yes, program deletion can overlap live guest execution.

Fix (9c8344af)

Chose the ownership rule rather than a barrier: there is no central guest-thread quiescence mechanism to hook (only per-thread PthreadJoin), and Windows TlsSetValue cannot safely invalidate another thread's slot, so per-thread invalidation from the destroying thread is not possible.

  • Record owner_thread_id on each TLS block when it is allocated.
  • ReleaseTlsBlock (called from ThreadLocalStorage::~ThreadLocalStorage and DeleteTls) releases a block immediately only when the caller is its owner; otherwise the block is moved to a process-lifetime deferred list instead of being freed.
  • Deferred blocks are released by their owning thread on guest entry (RunEntry) and when a guest pthread stops (DeleteTlss, reached from CleanupThread), so the TCB stays mapped for as long as any thread can still reach it.
  • Deferred release reports a failed unmap via LOGF rather than aborting, because a block that outlived its image may no longer have a backing range.

This preserves base and expansion TLS slots, MOV/XOR/CMP rewriting, flags, scratch-register and guest red-zone behaviour, avoids any process-global guest TCB pointer, and is platform independent, so non-Windows hosts keep the same semantics.

Tests

  • focused TCB patcher: PASS (tcb key=5 found=6 native=6 skipped=0; expansion key=64 found=1 native=1 skipped=0)
  • existing red-zone patcher: PASS
  • full Windows suite serially (-j 1): 52/52 PASS
  • Linux/WSL: 33/49 before and after, identical 16 known llvmpipe/Vulkan capability failures, no new regression
  • git diff --check: clean

One honest caveat

I did not add a regression test, because I could not build one that fails without this fix. The teardown that creates the hazard (DeleteProgram / ThreadLocalStorage::~) is not reachable from the test binary, and any test-only accessor would have changed the PR surface more than the fix itself. I did verify the pre-fix behaviour empirically from a scratch diagnostic in the same binary: after teardown the destination range reported TestPlaceholderRangeIsFree == 1 and the address was immediately handed out again by AllocateRuntimeMemory — i.e. the block really was released under a live thread, and the fix is what stops the block from being released while its owner can still reach it. I would rather say that plainly than add a test that passes with and without the fix.

Leaving this conversation unresolved for your review of the pushed commit.

**@⁠NabuOX** on GitHub · 2026-10-05 22:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#discussion_r4189422997) On `src/loader/runtimeLinker.cpp` line 1346 (outdated): ```diff @@ -1320,6 +1341,9 @@ void RuntimeLinker::Clear() { g_tls_main_program = nullptr; g_tls_cached_main_program = nullptr; g_tls_cached_main_tcb = nullptr; +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0); +#endif ``` **Finding confirmed.** Thanks — this is a real lifetime bug, and it is worse than the Windows TLS slot alone: the pre-existing per-thread TCB cache (`g_tls_cached_main_tcb`) holds the same raw pointer into the same block, so the defect predates this PR rather than being introduced by it. ### Lifecycle path - `TlsGetAddr()` allocates one block per thread in `program->tls.tlss[thread_id]` and stores the guest TCB inside it. `TlsMainGetAddr()` caches `TlsGetAddr(main) + tls.tcb_offset` in `g_tls_cached_main_tcb`, and the Windows patcher publishes the same address into `g_tls_main_tcb_key`. - Teardown runs from a different thread than the block's owner: - `RuntimeLinker::Clear()` -> `DeleteProgram()` -> `~Program()` -> `ThreadLocalStorage::~ThreadLocalStorage()` -> freed **every** block. - `sceKernelStopUnloadModule` -> `RuntimeLinker::UnloadProgram()` -> `DeleteProgram()` -> the same. - `DeleteProgram`/`Clear` cleared the calling thread's slot only. A block belonging to any other live thread was unmapped while that thread could still reach it, and a later patched `FS:[disp]` access on that thread dereferenced freed guest memory. - Reachability: `Clear()` is off the normal shutdown path (`emulator.cpp` exits via `std::quick_exit(0)`, which skips both `atexit`-registered `KytyClose` and static destructors), so the reachable teardown is `sceKernelStopUnloadModule` -> `UnloadProgram` -> `DeleteProgram`. That path only returns `KERNEL_ERROR_EBUSY` if the guest registered an at-exit count function (`g_get_thread_atexit_count_func`), so the hazard is not unconditionally guarded. **Yes, program deletion can overlap live guest execution.** ### Fix (`9c8344af`) Chose the ownership rule rather than a barrier: there is no central guest-thread quiescence mechanism to hook (only per-thread `PthreadJoin`), and Windows `TlsSetValue` cannot safely invalidate another thread's slot, so per-thread invalidation from the destroying thread is not possible. - Record `owner_thread_id` on each TLS block when it is allocated. - `ReleaseTlsBlock` (called from `ThreadLocalStorage::~ThreadLocalStorage` and `DeleteTls`) releases a block immediately only when the caller **is** its owner; otherwise the block is moved to a process-lifetime deferred list instead of being freed. - Deferred blocks are released by their owning thread on guest entry (`RunEntry`) and when a guest pthread stops (`DeleteTlss`, reached from `CleanupThread`), so the TCB stays mapped for as long as any thread can still reach it. - Deferred release reports a failed unmap via `LOGF` rather than aborting, because a block that outlived its image may no longer have a backing range. This preserves base and expansion TLS slots, MOV/XOR/CMP rewriting, flags, scratch-register and guest red-zone behaviour, avoids any process-global guest TCB pointer, and is platform independent, so non-Windows hosts keep the same semantics. ### Tests - focused TCB patcher: PASS (`tcb key=5 found=6 native=6 skipped=0`; expansion `key=64 found=1 native=1 skipped=0`) - existing red-zone patcher: PASS - full Windows suite serially (`-j 1`): **52/52 PASS** - Linux/WSL: **33/49 before and after**, identical 16 known llvmpipe/Vulkan capability failures, no new regression - `git diff --check`: clean ### One honest caveat I did **not** add a regression test, because I could not build one that fails without this fix. The teardown that creates the hazard (`DeleteProgram` / `ThreadLocalStorage::~`) is not reachable from the test binary, and any test-only accessor would have changed the PR surface more than the fix itself. I did verify the pre-fix behaviour empirically from a scratch diagnostic in the same binary: after teardown the destination range reported `TestPlaceholderRangeIsFree == 1` and the address was immediately handed out again by `AllocateRuntimeMemory` — i.e. the block really was released under a live thread, and the fix is what stops the block from being released while its owner can still reach it. I would rather say that plainly than add a test that passes with and without the fix. Leaving this conversation unresolved for your review of the pushed commit.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 22:25 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 979e0444-6d4e-4620-86c0-f76eed4de543
📥 Commits

Reviewing files that changed from the base of the PR and between 748897ca11 and 9c8344afac.

📒 Files selected for processing (2)
  • src/loader/runtimeLinker.cpp
  • src/loader/runtimeLinker.h

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 22:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#pullrequestreview-5421371986) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `979e0444-6d4e-4620-86c0-f76eed4de543` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 748897ca1130e0deb48050c4cac5b4ff6a166bec and 9c8344aface4d8d41bb569cc310dea234ccac416. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/loader/runtimeLinker.cpp` * `src/loader/runtimeLinker.h` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=879bfcd3-14d4-4ebb-91ed-7a0814499ba6 attempt=b221ef1d-d639-4633-81f9-9a91890e082e batch=1/1 -->
@ -236,1 +315,4 @@
#if defined(__x86_64__) || defined(_M_X64)
// This thread is about to run guest code again, so any block it parked for a program
// that has since been destroyed is no longer reachable.
ReleaseDeferredTlsBlocks();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 22:25 UTC · original · edited 2026-10-05 23:01 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '45,150p' src/loader/runtimeLinker.cpp
sed -n '275,310p' src/loader/runtimeLinker.cpp
sed -n '965,1025p' src/loader/runtimeLinker.cpp
sed -n '1380,1410p' src/loader/runtimeLinker.cpp
sed -n '1690,1725p' src/loader/runtimeLinker.cpp
sed -n '1950,1990p' src/loader/runtimeLinker.cpp
rg -n 'g_tls_cached_main_program|g_tls_cached_main_tcb|g_tls_main_program|ReleaseDeferredTlsBlocks|DeleteProgram' src/loader/runtimeLinker.cpp

Repository: KytyPS5/KytyPS5

Length of output: 12492


🏁 Script executed:

git diff --no-ext-diff --unified=30 dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 9c8344aface4d8d41bb569cc310dea234ccac416 -- src/loader/runtimeLinker.cpp
printf '\n--- focused symbols/callers ---\n'
rg -n -F 'DeleteProgram(' src/loader/runtimeLinker.cpp
rg -n -F 'Clear()' src/loader/runtimeLinker.cpp
rg -n -F 'unique_id' src/loader/runtimeLinker.cpp src/loader
printf '\n--- lifecycle and allocation blocks ---\n'
sed -n '75,130p' src/loader/runtimeLinker.cpp
sed -n '275,325p' src/loader/runtimeLinker.cpp
sed -n '980,1015p' src/loader/runtimeLinker.cpp
sed -n '1360,1410p' src/loader/runtimeLinker.cpp
sed -n '1670,1735p' src/loader/runtimeLinker.cpp
sed -n '1945,2025p' src/loader/runtimeLinker.cpp
sed -n '2220,2295p' src/loader/runtimeLinker.cpp
printf '\n--- block declaration ---\n'
rg -n -F 'struct Block' src/loader

Repository: KytyPS5/KytyPS5

Length of output: 42212


🏁 Script executed:

git diff --no-ext-diff --unified=12 dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 9c8344aface4d8d41bb569cc310dea234ccac416 -- src/loader/runtimeLinker.cpp
printf '\n--- declarations and release ---\n'
nl -ba src/loader/runtimeLinker.cpp | sed -n '80,125p;270,310p;985,1012p;1368,1405p;1690,1720p;1960,2010p;2228,2290p'
printf '\n--- block and thread-local storage declarations ---\n'
rg -n -F 'struct Block' src/loader
rg -n -F 'class ThreadLocalStorage' src/loader
rg -n -F 'unique_id' src/loader || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 32954


🏁 Script executed:

nl -ba src/loader/runtimeLinker.h | sed -n '42,72p;100,122p'
nl -ba src/loader/runtimeLinker.cpp | sed -n '1230,1280p'
nl -ba src/loader/runtimeLinker.cpp | sed -n '60,85p;95,125p;295,303p;990,1006p;1967,1994p

Repository: KytyPS5/KytyPS5

Length of output: 3753


🏁 Script executed:

nl -ba src/loader/runtimeLinker.h | sed -n '112,175p'
nl -ba src/loader/runtimeLinker.cpp | sed -n '120,145p'

Repository: KytyPS5/KytyPS5

Length of output: 3758


🏁 Script executed:

rg -n -C 8 'PatchGuestInstructions|patch_tcb_accesses|TlsGetValue|tls_key|tcb_access' src/loader/guestInstructionPatcher.*

Repository: KytyPS5/KytyPS5

Length of output: 4419


🏁 Script executed:

nl -ba src/loader/guestInstructionPatcher.cpp | sed -n '1617,1698p'
rg -n -F 'tcb_key' src/loader/guestInstructionPatcher.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4743


🏁 Script executed:

nl -ba src/loader/guestInstructionPatcher.cpp | sed -n '1015,1070p;1105,1175p'
rg -n -F 'CollectTcbInstructions' src/loader/guestInstructionPatcher.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6904


Clear the cached TCB before releasing its deferred block.

When DeleteProgram() destroys a program used by another thread, its ThreadLocalStorage destructor parks that thread’s TLS block. At the owner’s next RunEntry(), ReleaseDeferredTlsBlocks() can free the block before InitializeMainTlsForCurrentThread() runs. If reload allocates the new main Program at the old address, TlsMainGetAddr() can return the freed TCB because it checks only raw Program* equality. On Windows, that cache hit skips TlsSetValue, leaving the stale pointer in the host TLS slot used by patched guest reads.

Clear the cache and Windows slot before releasing a deferred block that contains the cached TCB:

🐛 Suggested fix
 static std::mutex                             g_deferred_tls_mutex;
 static std::vector<ThreadLocalStorage::Block> g_deferred_tls_blocks;
+static thread_local Program* g_tls_cached_main_program = nullptr;
+static thread_local uint8_t* g_tls_cached_main_tcb     = nullptr;
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+static const DWORD g_tls_main_tcb_key = [] {
+	const auto key = TlsAlloc();
+	EXIT_IF(key == TLS_OUT_OF_INDEXES);
+	return key;
+}();
+#endif
 
 static void ReleaseDeferredTlsBlocks() {
@@
 	for (auto& block: mine) {
+		if (g_tls_cached_main_tcb != nullptr && g_tls_cached_main_tcb >= block.ptr &&
+		    g_tls_cached_main_tcb < block.ptr + block.alloc_size) {
+			g_tls_cached_main_program = nullptr;
+			g_tls_cached_main_tcb     = nullptr;
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+			EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0);
+#endif
+		}
 		if (!ReleaseTlsBlockMemory(&block)) {
@@
 static Program*              g_tls_main_program        = nullptr;
-static thread_local Program* g_tls_cached_main_program = nullptr;
-static thread_local uint8_t* g_tls_cached_main_tcb     = nullptr;
-#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
-static const DWORD g_tls_main_tcb_key = [] {
-	const auto key = TlsAlloc();
-	EXIT_IF(key == TLS_OUT_OF_INDEXES);
-	return key;
-}();
-#endif

✅ Addressed in commit a16798e

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 22:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#discussion_r4189491340) · edited 2026-10-05 23:01 UTC _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '45,150p' src/loader/runtimeLinker.cpp sed -n '275,310p' src/loader/runtimeLinker.cpp sed -n '965,1025p' src/loader/runtimeLinker.cpp sed -n '1380,1410p' src/loader/runtimeLinker.cpp sed -n '1690,1725p' src/loader/runtimeLinker.cpp sed -n '1950,1990p' src/loader/runtimeLinker.cpp rg -n 'g_tls_cached_main_program|g_tls_cached_main_tcb|g_tls_main_program|ReleaseDeferredTlsBlocks|DeleteProgram' src/loader/runtimeLinker.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 12492 --- 🏁 Script executed: ```bash git diff --no-ext-diff --unified=30 dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 9c8344aface4d8d41bb569cc310dea234ccac416 -- src/loader/runtimeLinker.cpp printf '\n--- focused symbols/callers ---\n' rg -n -F 'DeleteProgram(' src/loader/runtimeLinker.cpp rg -n -F 'Clear()' src/loader/runtimeLinker.cpp rg -n -F 'unique_id' src/loader/runtimeLinker.cpp src/loader printf '\n--- lifecycle and allocation blocks ---\n' sed -n '75,130p' src/loader/runtimeLinker.cpp sed -n '275,325p' src/loader/runtimeLinker.cpp sed -n '980,1015p' src/loader/runtimeLinker.cpp sed -n '1360,1410p' src/loader/runtimeLinker.cpp sed -n '1670,1735p' src/loader/runtimeLinker.cpp sed -n '1945,2025p' src/loader/runtimeLinker.cpp sed -n '2220,2295p' src/loader/runtimeLinker.cpp printf '\n--- block declaration ---\n' rg -n -F 'struct Block' src/loader ``` Repository: KytyPS5/KytyPS5 Length of output: 42212 --- 🏁 Script executed: ```bash git diff --no-ext-diff --unified=12 dc3cd2d2c9d537156894871a91ff22b30ec3a1a8 9c8344aface4d8d41bb569cc310dea234ccac416 -- src/loader/runtimeLinker.cpp printf '\n--- declarations and release ---\n' nl -ba src/loader/runtimeLinker.cpp | sed -n '80,125p;270,310p;985,1012p;1368,1405p;1690,1720p;1960,2010p;2228,2290p' printf '\n--- block and thread-local storage declarations ---\n' rg -n -F 'struct Block' src/loader rg -n -F 'class ThreadLocalStorage' src/loader rg -n -F 'unique_id' src/loader || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 32954 --- 🏁 Script executed: ```bash nl -ba src/loader/runtimeLinker.h | sed -n '42,72p;100,122p' nl -ba src/loader/runtimeLinker.cpp | sed -n '1230,1280p' nl -ba src/loader/runtimeLinker.cpp | sed -n '60,85p;95,125p;295,303p;990,1006p;1967,1994p ``` Repository: KytyPS5/KytyPS5 Length of output: 3753 --- 🏁 Script executed: ```bash nl -ba src/loader/runtimeLinker.h | sed -n '112,175p' nl -ba src/loader/runtimeLinker.cpp | sed -n '120,145p' ``` Repository: KytyPS5/KytyPS5 Length of output: 3758 --- 🏁 Script executed: ```bash rg -n -C 8 'PatchGuestInstructions|patch_tcb_accesses|TlsGetValue|tls_key|tcb_access' src/loader/guestInstructionPatcher.* ``` Repository: KytyPS5/KytyPS5 Length of output: 4419 --- 🏁 Script executed: ```bash nl -ba src/loader/guestInstructionPatcher.cpp | sed -n '1617,1698p' rg -n -F 'tcb_key' src/loader/guestInstructionPatcher.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4743 --- 🏁 Script executed: ```bash nl -ba src/loader/guestInstructionPatcher.cpp | sed -n '1015,1070p;1105,1175p' rg -n -F 'CollectTcbInstructions' src/loader/guestInstructionPatcher.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6904 --- </details> **Clear the cached TCB before releasing its deferred block.** When `DeleteProgram()` destroys a program used by another thread, its `ThreadLocalStorage` destructor parks that thread’s TLS block. At the owner’s next `RunEntry()`, `ReleaseDeferredTlsBlocks()` can free the block before `InitializeMainTlsForCurrentThread()` runs. If reload allocates the new main `Program` at the old address, `TlsMainGetAddr()` can return the freed TCB because it checks only raw `Program*` equality. On Windows, that cache hit skips `TlsSetValue`, leaving the stale pointer in the host TLS slot used by patched guest reads. Clear the cache and Windows slot before releasing a deferred block that contains the cached TCB: <details> <summary>🐛 Suggested fix</summary> ```diff static std::mutex g_deferred_tls_mutex; static std::vector<ThreadLocalStorage::Block> g_deferred_tls_blocks; +static thread_local Program* g_tls_cached_main_program = nullptr; +static thread_local uint8_t* g_tls_cached_main_tcb = nullptr; +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS +static const DWORD g_tls_main_tcb_key = [] { + const auto key = TlsAlloc(); + EXIT_IF(key == TLS_OUT_OF_INDEXES); + return key; +}(); +#endif static void ReleaseDeferredTlsBlocks() { @@ for (auto& block: mine) { + if (g_tls_cached_main_tcb != nullptr && g_tls_cached_main_tcb >= block.ptr && + g_tls_cached_main_tcb < block.ptr + block.alloc_size) { + g_tls_cached_main_program = nullptr; + g_tls_cached_main_tcb = nullptr; +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0); +#endif + } if (!ReleaseTlsBlockMemory(&block)) { @@ static Program* g_tls_main_program = nullptr; -static thread_local Program* g_tls_cached_main_program = nullptr; -static thread_local uint8_t* g_tls_cached_main_tcb = nullptr; -#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS -static const DWORD g_tls_main_tcb_key = [] { - const auto key = TlsAlloc(); - EXIT_IF(key == TLS_OUT_OF_INDEXES); - return key; -}(); -#endif ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:37a663004eb02714f41c3f46 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit a16798e
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 22:35 UTC · original
On src/loader/runtimeLinker.cpp line 1346 (outdated):

@@ -1320,6 +1341,9 @@ void RuntimeLinker::Clear() {
 	g_tls_main_program        = nullptr;
 	g_tls_cached_main_program = nullptr;
 	g_tls_cached_main_tcb     = nullptr;
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+	EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0);
+#endif
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git rev-parse HEAD
ast-grep outline src/loader/runtimeLinker.cpp --match 'ReleaseTlsBlock|ReleaseDeferredTlsBlocks|TlsMainGetAddr|InitializeMainTlsForCurrentThread|RunEntry|DeleteTls|DeleteTlss|DeleteProgram|Clear' --view expanded
ast-grep outline src/kernel/pthread.cpp --match 'CleanupThread|RunOnGuestStack' --view expanded
rg -n -C 5 'ReleaseDeferredTlsBlocks\(|ReleaseTlsBlock\(|TlsMainGetAddr\(|InitializeMainTlsForCurrentThread\(|void RuntimeLinker::DeleteTlss\(|void RuntimeLinker::DeleteTls\(|void RuntimeLinker::DeleteProgram\(' src/loader/runtimeLinker.cpp
rg -n -C 10 'DeleteTlss\(|void CleanupThread\(|RunOnGuestStack\(' src/kernel/pthread.cpp
rg -n -C 4 'GetThreadIdUnique\(|g_tls_cached_main_program|g_tls_cached_main_tcb' src/loader/runtimeLinker.cpp
fd -i '^threads\.(cpp|h)$'

Length of output: 14756


@fawazkh2, thanks for the lifecycle clarification. I inspected commit 9c8344af.

The ownership rule prevents another thread from immediately freeing a live thread’s TLS block. I also confirmed that CleanupThread runs guest destructors before DeleteTlss releases deferred blocks.

One cache-invalidation gap remains before deferred release:

  • ReleaseDeferredTlsBlocks frees the owner’s deferred blocks without clearing g_tls_cached_main_program, g_tls_cached_main_tcb, or the Windows TLS slot.
  • At Line 300, RunEntry releases deferred blocks before initialization.
  • TlsMainGetAddr validates its cache by Program* equality only. If a new main Program reuses the destroyed program’s address, the fast path at Line 995 returns the old TCB pointer after deferred release freed its block. The Windows TLS slot also retains that pointer.

Owner-thread execution makes reclamation possible, but it does not itself invalidate these references.

Before freeing a deferred block that contains the cached TCB, clear the current thread’s cache and Windows TLS slot. Then let guest-entry initialization populate the current TCB. Use an allocation-range check or another reliable identity check; the destroyed Program is no longer available for inspection.

The reported patcher tests do not cover this deferred-reclamation case. I did not run tests in the inspection sandbox. I would keep this finding open until the invalidation step is present.


✏️ Learnings added
Learnt from: fawazkh2
Repo: KytyPS5/KytyPS5 PR: 1080
File: src/loader/runtimeLinker.cpp:1399-1401
Timestamp: 2026-10-05T22:35:02.259Z
Learning: In KytyPS5, src/loader/runtimeLinker.cpp caches the guest main TCB in the pre-existing thread-local g_tls_cached_main_tcb. Windows guest TCB patching publishes the same pointer through g_tls_main_tcb_key. TLS lifetime reviews must account for both references, not only the Windows TLS slot. Windows TlsSetValue updates only the calling thread's slot.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 22:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#discussion_r4189570866) On `src/loader/runtimeLinker.cpp` line 1346 (outdated): ```diff @@ -1320,6 +1341,9 @@ void RuntimeLinker::Clear() { g_tls_main_program = nullptr; g_tls_cached_main_program = nullptr; g_tls_cached_main_tcb = nullptr; +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + EXIT_IF(TlsSetValue(g_tls_main_tcb_key, nullptr) == 0); +#endif ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git rev-parse HEAD ast-grep outline src/loader/runtimeLinker.cpp --match 'ReleaseTlsBlock|ReleaseDeferredTlsBlocks|TlsMainGetAddr|InitializeMainTlsForCurrentThread|RunEntry|DeleteTls|DeleteTlss|DeleteProgram|Clear' --view expanded ast-grep outline src/kernel/pthread.cpp --match 'CleanupThread|RunOnGuestStack' --view expanded rg -n -C 5 'ReleaseDeferredTlsBlocks\(|ReleaseTlsBlock\(|TlsMainGetAddr\(|InitializeMainTlsForCurrentThread\(|void RuntimeLinker::DeleteTlss\(|void RuntimeLinker::DeleteTls\(|void RuntimeLinker::DeleteProgram\(' src/loader/runtimeLinker.cpp rg -n -C 10 'DeleteTlss\(|void CleanupThread\(|RunOnGuestStack\(' src/kernel/pthread.cpp rg -n -C 4 'GetThreadIdUnique\(|g_tls_cached_main_program|g_tls_cached_main_tcb' src/loader/runtimeLinker.cpp fd -i '^threads\.(cpp|h)$' ``` Length of output: 14756 --- </details> `@fawazkh2`, thanks for the lifecycle clarification. I inspected commit `9c8344af`. The ownership rule prevents another thread from immediately freeing a live thread’s TLS block. I also confirmed that `CleanupThread` runs guest destructors before `DeleteTlss` releases deferred blocks. **One cache-invalidation gap remains before deferred release:** - `ReleaseDeferredTlsBlocks` frees the owner’s deferred blocks without clearing `g_tls_cached_main_program`, `g_tls_cached_main_tcb`, or the Windows TLS slot. - At Line 300, `RunEntry` releases deferred blocks before initialization. - `TlsMainGetAddr` validates its cache by `Program*` equality only. If a new main `Program` reuses the destroyed program’s address, the fast path at Line 995 returns the old TCB pointer after deferred release freed its block. The Windows TLS slot also retains that pointer. Owner-thread execution makes reclamation possible, but it does not itself invalidate these references. Before freeing a deferred block that contains the cached TCB, clear the current thread’s cache and Windows TLS slot. Then let guest-entry initialization populate the current TCB. Use an allocation-range check or another reliable identity check; the destroyed `Program` is no longer available for inspection. The reported patcher tests do not cover this deferred-reclamation case. I did not run tests in the inspection sandbox. I would keep this finding open until the invalidation step is present. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: fawazkh2 Repo: KytyPS5/KytyPS5 PR: 1080 File: src/loader/runtimeLinker.cpp:1399-1401 Timestamp: 2026-10-05T22:35:02.259Z Learning: In KytyPS5, src/loader/runtimeLinker.cpp caches the guest main TCB in the pre-existing thread-local g_tls_cached_main_tcb. Windows guest TCB patching publishes the same pointer through g_tls_main_tcb_key. TLS lifetime reviews must account for both references, not only the Windows TLS slot. Windows TlsSetValue updates only the calling thread's slot. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
@ -236,1 +315,4 @@
#if defined(__x86_64__) || defined(_M_X64)
// This thread is about to run guest code again, so any block it parked for a program
// that has since been destroyed is no longer reachable.
ReleaseDeferredTlsBlocks();
Author
Owner

@⁠NabuOX on GitHub · 2026-10-05 22:57 UTC · original

Confirmed and fixed in a16798ec.

I followed the same reasoning you did, and arrived at the same conclusion, but implemented it slightly differently after checking reachability. Details below.

Stale-cache path (verified)

  1. TlsMainGetAddr() caches the guest TCB per thread and validates it with raw Program* equality: g_tls_cached_main_program == g_tls_main_program.
  2. DeleteProgram() / Clear() invalidate that cache only when g_tls_cached_main_program matches on the calling thread. A worker thread that had cached the TCB keeps a stale entry when another thread destroys the program.
  3. That thread's block is parked by ThreadLocalStorage::~ThreadLocalStorage -> ReleaseTlsBlock (different owner, so deferred rather than freed).
  4. RunEntry() drains before InitializeMainTlsForCurrentThread(), and DeleteTlss() drains on the way out, so the parked block is released while the stale cache entry may still refer into it.
  5. If a new main Program is later allocated at the destroyed program's address, the cache key matches, the fast path at TlsMainGetAddr returns the freed TCB, and on Windows it also skips TlsSetValue, so the host TLS slot used by patched guest reads keeps the stale pointer.

So yes: owner-thread reclamation was necessary but not sufficient. The references were never invalidated.

Fix (a16798ec, one file)

  • Added InvalidateCachedMainTcb(), which clears g_tls_cached_main_program, g_tls_cached_main_tcb and, on Windows, the host TLS slot via TlsSetValue(g_tls_main_tcb_key, nullptr).
  • ReleaseDeferredTlsBlocks() now calls it before releasing any parked block.
  • Moved the cache globals and the TLS key above the drain so the helper can reach them (that is the one structural change beyond the invalidation itself), and pointed the three pre-existing inline invalidations in Clear, DeleteTls and DeleteProgram at the same helper, which removes three duplicate copies.

Why I used a coarser guard than your per-block range check

Your suggested [block.ptr, block.ptr + block.alloc_size) test is correct. I ended up with if (!mine.empty()) InvalidateCachedMainTcb(); because the range test is equivalent here by construction:

  • Only the owner thread may drain a parked block (ReleaseDeferredTlsBlocks selects owner_thread_id == GetThreadIdUnique()).
  • The TCB cache is thread_local, and a thread's cached TCB always lies inside its own block: TlsGetAddr keys the block on GetThreadIdUnique(), and TlsMainGetAddr caches that same thread's block plus tls.tcb_offset.
  • Therefore, while draining, the calling thread's cached TCB is always in one of mine. A parked block can never belong to a different thread than the cache owner, and there is no cross-thread case to signal.

Net effect is the same as your patch: no parked block is released while the calling thread can still reach a cached TCB inside it. I am happy to switch to the explicit per-block range form if you prefer it for clarity — it is a four-line difference.

Invariant now: a cached TCB is dropped before any block that can back it is released.

Tests

  • focused TCB patcher (3x): PASS, tcb key=5 found=6 native=6 skipped=0; expansion key=64 found=1 native=1 skipped=0
  • base and expansion TLS slots: PASS; two-thread isolation: PASS
  • full Windows suite serially (-j 1): 52/52 PASS
  • Linux/WSL: 33/49 before and after, same 16 known llvmpipe/Vulkan capability failures, no new regression
  • git diff --check: clean

On test coverage

Agreed that the patcher tests do not cover deferred reclamation. I did not add a regression here, and I want to be explicit about why rather than leave it implied: populating this cache requires SetupTlsHandler() to set g_tls_main_program, and that function is private and EXIT_IFs unless it is handed a loaded, non-shared ELF with a non-zero tls.handler_vaddr. Without a real guest ELF fixture, or a test-only hook into the production API, InitializeMainTlsForCurrentThread() returns early and the cache stays empty, so the stale-cache path is not reachable from virtual_memory_allocation_tests. I would rather say that than add a test that passes with and without the fix. If a test-only entry point is acceptable to the maintainers, I can add a deterministic one.

Leaving this unresolved for your review of a16798ec.

**@⁠NabuOX** on GitHub · 2026-10-05 22:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#discussion_r4189724134) **Confirmed and fixed** in `a16798ec`. I followed the same reasoning you did, and arrived at the same conclusion, but implemented it slightly differently after checking reachability. Details below. ### Stale-cache path (verified) 1. `TlsMainGetAddr()` caches the guest TCB per thread and validates it with raw `Program*` equality: `g_tls_cached_main_program == g_tls_main_program`. 2. `DeleteProgram()` / `Clear()` invalidate that cache only when `g_tls_cached_main_program` matches **on the calling thread**. A worker thread that had cached the TCB keeps a stale entry when another thread destroys the program. 3. That thread's block is parked by `ThreadLocalStorage::~ThreadLocalStorage` -> `ReleaseTlsBlock` (different owner, so deferred rather than freed). 4. `RunEntry()` drains before `InitializeMainTlsForCurrentThread()`, and `DeleteTlss()` drains on the way out, so the parked block is released while the stale cache entry may still refer into it. 5. If a new main `Program` is later allocated at the destroyed program's address, the cache key matches, the fast path at `TlsMainGetAddr` returns the freed TCB, and on Windows it also skips `TlsSetValue`, so the host TLS slot used by patched guest reads keeps the stale pointer. So yes: owner-thread reclamation was necessary but not sufficient. The references were never invalidated. ### Fix (`a16798ec`, one file) - Added `InvalidateCachedMainTcb()`, which clears `g_tls_cached_main_program`, `g_tls_cached_main_tcb` and, on Windows, the host TLS slot via `TlsSetValue(g_tls_main_tcb_key, nullptr)`. - `ReleaseDeferredTlsBlocks()` now calls it before releasing any parked block. - Moved the cache globals and the TLS key above the drain so the helper can reach them (that is the one structural change beyond the invalidation itself), and pointed the three pre-existing inline invalidations in `Clear`, `DeleteTls` and `DeleteProgram` at the same helper, which removes three duplicate copies. ### Why I used a coarser guard than your per-block range check Your suggested `[block.ptr, block.ptr + block.alloc_size)` test is correct. I ended up with `if (!mine.empty()) InvalidateCachedMainTcb();` because the range test is equivalent here by construction: - Only the owner thread may drain a parked block (`ReleaseDeferredTlsBlocks` selects `owner_thread_id == GetThreadIdUnique()`). - The TCB cache is `thread_local`, and a thread's cached TCB always lies inside **its own** block: `TlsGetAddr` keys the block on `GetThreadIdUnique()`, and `TlsMainGetAddr` caches that same thread's block plus `tls.tcb_offset`. - Therefore, while draining, the calling thread's cached TCB is always in one of `mine`. A parked block can never belong to a different thread than the cache owner, and there is no cross-thread case to signal. Net effect is the same as your patch: no parked block is released while the calling thread can still reach a cached TCB inside it. I am happy to switch to the explicit per-block range form if you prefer it for clarity — it is a four-line difference. **Invariant now:** a cached TCB is dropped before any block that can back it is released. ### Tests - focused TCB patcher (3x): PASS, `tcb key=5 found=6 native=6 skipped=0`; expansion `key=64 found=1 native=1 skipped=0` - base and expansion TLS slots: PASS; two-thread isolation: PASS - full Windows suite serially (`-j 1`): **52/52 PASS** - Linux/WSL: **33/49 before and after**, same 16 known llvmpipe/Vulkan capability failures, no new regression - `git diff --check`: clean ### On test coverage Agreed that the patcher tests do not cover deferred reclamation. I did **not** add a regression here, and I want to be explicit about why rather than leave it implied: populating this cache requires `SetupTlsHandler()` to set `g_tls_main_program`, and that function is private and `EXIT_IF`s unless it is handed a loaded, non-shared ELF with a non-zero `tls.handler_vaddr`. Without a real guest ELF fixture, or a test-only hook into the production API, `InitializeMainTlsForCurrentThread()` returns early and the cache stays empty, so the stale-cache path is not reachable from `virtual_memory_allocation_tests`. I would rather say that than add a test that passes with and without the fix. If a test-only entry point is acceptable to the maintainers, I can add a deterministic one. Leaving this unresolved for your review of `a16798ec`.
@ -236,1 +315,4 @@
#if defined(__x86_64__) || defined(_M_X64)
// This thread is about to run guest code again, so any block it parked for a program
// that has since been destroyed is no longer reachable.
ReleaseDeferredTlsBlocks();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 23:01 UTC · original

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git rev-parse HEAD
ast-grep outline src/loader/runtimeLinker.cpp --match 'InvalidateCachedMainTcb|ReleaseDeferredTlsBlocks|ReleaseTlsBlockMemory|TlsMainGetAddr|InitializeMainTlsForCurrentThread|RunEntry|DeleteTlss' --view expanded
rg -n -C 5 'static void InvalidateCachedMainTcb\(|static void ReleaseDeferredTlsBlocks\(|static KYTY_MS_ABI uint8_t\* TlsMainGetAddr\(|void RuntimeLinker::InitializeMainTlsForCurrentThread\(|ReleaseDeferredTlsBlocks\(\);|if \(!mine.empty\(\)\)' src/loader/runtimeLinker.cpp

Length of output: 4109


@fawazkh2, verified the fix in a16798ec.

  • InvalidateCachedMainTcb() clears both cache pointers and the calling thread’s Windows TLS slot.
  • ReleaseDeferredTlsBlocks() calls the helper before freeing any selected block.
  • RunEntry() drains deferred blocks before initializing main TLS.

This closes the reported stale-cache path. No switch to the per-block range check is needed.

One clarification: the guards are not strictly equivalent. A thread can have a deferred block from an old program while its cached TCB belongs to a current program. The coarse guard also invalidates that valid cache. This is conservative and safe for this path; the subsequent initialization restores it.

The existing retrieved learning about both TCB references informed this check. Thanks for explaining the test limitation. The reported patcher tests do not cover deferred reclamation, and I did not run tests during this verification. That coverage gap does not block accepting this fix.


🧠 Learnings used
Learnt from: fawazkh2
Repo: KytyPS5/KytyPS5 PR: 1080
File: src/loader/runtimeLinker.cpp:1399-1401
Timestamp: 2026-10-05T22:35:06.200Z
Learning: In KytyPS5, src/loader/runtimeLinker.cpp caches the guest main TCB in the pre-existing thread-local g_tls_cached_main_tcb. Windows guest TCB patching publishes the same pointer through g_tls_main_tcb_key. TLS lifetime reviews must account for both references, not only the Windows TLS slot. Windows TlsSetValue updates only the calling thread's slot.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 23:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1080#discussion_r4189755391) <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git rev-parse HEAD ast-grep outline src/loader/runtimeLinker.cpp --match 'InvalidateCachedMainTcb|ReleaseDeferredTlsBlocks|ReleaseTlsBlockMemory|TlsMainGetAddr|InitializeMainTlsForCurrentThread|RunEntry|DeleteTlss' --view expanded rg -n -C 5 'static void InvalidateCachedMainTcb\(|static void ReleaseDeferredTlsBlocks\(|static KYTY_MS_ABI uint8_t\* TlsMainGetAddr\(|void RuntimeLinker::InitializeMainTlsForCurrentThread\(|ReleaseDeferredTlsBlocks\(\);|if \(!mine.empty\(\)\)' src/loader/runtimeLinker.cpp ``` Length of output: 4109 --- </details> `@fawazkh2`, verified the fix in `a16798ec`. - `InvalidateCachedMainTcb()` clears both cache pointers and the calling thread’s Windows TLS slot. - `ReleaseDeferredTlsBlocks()` calls the helper before freeing any selected block. - `RunEntry()` drains deferred blocks before initializing main TLS. This closes the reported stale-cache path. No switch to the per-block range check is needed. One clarification: the guards are not strictly equivalent. A thread can have a deferred block from an old program while its cached TCB belongs to a current program. The coarse guard also invalidates that valid cache. This is conservative and safe for this path; the subsequent initialization restores it. The existing retrieved learning about both TCB references informed this check. Thanks for explaining the test limitation. The reported patcher tests do not cover deferred reclamation, and I did not run tests during this verification. That coverage gap does not block accepting this fix. --- <details> <summary>🧠 Learnings used</summary> ``` Learnt from: fawazkh2 Repo: KytyPS5/KytyPS5 PR: 1080 File: src/loader/runtimeLinker.cpp:1399-1401 Timestamp: 2026-10-05T22:35:06.200Z Learning: In KytyPS5, src/loader/runtimeLinker.cpp caches the guest main TCB in the pre-existing thread-local g_tls_cached_main_tcb. Windows guest TCB patching publishes the same pointer through g_tls_main_tcb_key. TLS lifetime reviews must account for both references, not only the Windows TLS slot. Windows TlsSetValue updates only the calling thread's slot. ``` </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=A%20subtle%20TLS%20use-after-free%3A%20invalidate%20cached%20TCBs%20before%20freeing%20deferred%20blocks%2C%20preventing%20stale%20pointers%20after%20reload.%20Sharp%20catch%20by%20%40coderabbitai%E2%80%94try%20it%20on%20your%20next%20PR!%20%F0%9F%90%87%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1080%23discussion_r4189491340)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.