windows: patch guest FS TCB accesses through host TLS #1080
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1080
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/1080/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@NabuOX on GitHub · 2026-10-05 19:54 UTC · original
NabuOX:windows-tcb-upstream→main· +516 −41 · 6 files · 3 commits · closed without mergingProblem
On Windows, guest binaries can use absolute
FS:[disp]accesses for PS5/FreeBSD thread-control-block fields, for examplemov 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:
fs:[0x28]store byte pattern, andfs:[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
FS:[disp]64-bit MOV, XOR and CMP accesses, for displacements0x00..0x3f.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 thefs:[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:
virtual_memory_allocation_tests --tcb-patcher-only): PASS-j 1: 52/52 PASSThe new
WindowsGuestTcbStaticPatcherexecutes 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):
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 parallelctestrun 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.@coderabbitai[bot] on GitHub · 2026-10-05 20:03 UTC · original · edited 2026-10-05 23:00 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
547295c6-478b-4e8c-b3f7-512406782006📥 Commits
Reviewing files that changed from the base of the PR and between
9c8344afacanda16798ec83.📒 Files selected for processing (1)
src/loader/runtimeLinker.cpp🚧 Files skipped from review as they are similar to previous changes (1)
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
a1679The 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
9c834Normal 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
Security review details
Security Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 helpto get the list of available commands.@coderabbitai[bot] on GitHub · 2026-10-05 20:03 UTC · original · edited 2026-10-05 22:34 UTC
On
src/loader/runtimeLinker.cppline 1346 (outdated):🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 41366
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 22956
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 10889
Prevent guest execution while deleting program TLS.
DeleteProgramdestroysProgram, andThreadLocalStorage::~ThreadLocalStoragefrees every stored TCB.ClearandDeleteProgramclearg_tls_main_tcb_keyonly 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
ClearandUnloadProgramwith 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 · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
defe1426-9d87-4983-9d7f-494280f838e3📥 Commits
Reviewing files that changed from the base of the PR and between
dc3cd2d2c9and748897ca11.📒 Files selected for processing (6)
src/kernel/pthread.cppsrc/loader/guestInstructionPatcher.cppsrc/loader/guestInstructionPatcher.hsrc/loader/runtimeLinker.cppsrc/loader/runtimeLinker.htests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@NabuOX on GitHub · 2026-10-05 22:16 UTC · original
On
src/loader/runtimeLinker.cppline 1346 (outdated):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 inprogram->tls.tlss[thread_id]and stores the guest TCB inside it.TlsMainGetAddr()cachesTlsGetAddr(main) + tls.tcb_offseting_tls_cached_main_tcb, and the Windows patcher publishes the same address intog_tls_main_tcb_key.RuntimeLinker::Clear()->DeleteProgram()->~Program()->ThreadLocalStorage::~ThreadLocalStorage()-> freed every block.sceKernelStopUnloadModule->RuntimeLinker::UnloadProgram()->DeleteProgram()-> the same.DeleteProgram/Clearcleared 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 patchedFS:[disp]access on that thread dereferenced freed guest memory.Clear()is off the normal shutdown path (emulator.cppexits viastd::quick_exit(0), which skips bothatexit-registeredKytyCloseand static destructors), so the reachable teardown issceKernelStopUnloadModule->UnloadProgram->DeleteProgram. That path only returnsKERNEL_ERROR_EBUSYif 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 WindowsTlsSetValuecannot safely invalidate another thread's slot, so per-thread invalidation from the destroying thread is not possible.owner_thread_idon each TLS block when it is allocated.ReleaseTlsBlock(called fromThreadLocalStorage::~ThreadLocalStorageandDeleteTls) 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.RunEntry) and when a guest pthread stops (DeleteTlss, reached fromCleanupThread), so the TCB stays mapped for as long as any thread can still reach it.LOGFrather 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
tcb key=5 found=6 native=6 skipped=0; expansionkey=64 found=1 native=1 skipped=0)-j 1): 52/52 PASSgit diff --check: cleanOne 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 reportedTestPlaceholderRangeIsFree == 1and the address was immediately handed out again byAllocateRuntimeMemory— 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.
@coderabbitai[bot] on GitHub · 2026-10-05 22:25 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
979e0444-6d4e-4620-86c0-f76eed4de543📥 Commits
Reviewing files that changed from the base of the PR and between
748897ca11and9c8344afac.📒 Files selected for processing (2)
src/loader/runtimeLinker.cppsrc/loader/runtimeLinker.hIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@ -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();@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:
Repository: KytyPS5/KytyPS5
Length of output: 12492
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 42212
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 32954
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 3753
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 3758
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 4419
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 4743
🏁 Script executed:
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, itsThreadLocalStoragedestructor parks that thread’s TLS block. At the owner’s nextRunEntry(),ReleaseDeferredTlsBlocks()can free the block beforeInitializeMainTlsForCurrentThread()runs. If reload allocates the new mainProgramat the old address,TlsMainGetAddr()can return the freed TCB because it checks only rawProgram*equality. On Windows, that cache hit skipsTlsSetValue, 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
✅ Addressed in commit
a16798e@coderabbitai[bot] on GitHub · 2026-10-05 22:35 UTC · original
On
src/loader/runtimeLinker.cppline 1346 (outdated):🧩 Analysis chain
🏁 Script executed:
Length of output: 14756
@fawazkh2, thanks for the lifecycle clarification. I inspected commit9c8344af.The ownership rule prevents another thread from immediately freeing a live thread’s TLS block. I also confirmed that
CleanupThreadruns guest destructors beforeDeleteTlssreleases deferred blocks.One cache-invalidation gap remains before deferred release:
ReleaseDeferredTlsBlocksfrees the owner’s deferred blocks without clearingg_tls_cached_main_program,g_tls_cached_main_tcb, or the Windows TLS slot.RunEntryreleases deferred blocks before initialization.TlsMainGetAddrvalidates its cache byProgram*equality only. If a new mainProgramreuses 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
Programis 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
You are interacting with an AI system.
@ -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();@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)
TlsMainGetAddr()caches the guest TCB per thread and validates it with rawProgram*equality:g_tls_cached_main_program == g_tls_main_program.DeleteProgram()/Clear()invalidate that cache only wheng_tls_cached_main_programmatches on the calling thread. A worker thread that had cached the TCB keeps a stale entry when another thread destroys the program.ThreadLocalStorage::~ThreadLocalStorage->ReleaseTlsBlock(different owner, so deferred rather than freed).RunEntry()drains beforeInitializeMainTlsForCurrentThread(), andDeleteTlss()drains on the way out, so the parked block is released while the stale cache entry may still refer into it.Programis later allocated at the destroyed program's address, the cache key matches, the fast path atTlsMainGetAddrreturns the freed TCB, and on Windows it also skipsTlsSetValue, 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)InvalidateCachedMainTcb(), which clearsg_tls_cached_main_program,g_tls_cached_main_tcband, on Windows, the host TLS slot viaTlsSetValue(g_tls_main_tcb_key, nullptr).ReleaseDeferredTlsBlocks()now calls it before releasing any parked block.Clear,DeleteTlsandDeleteProgramat 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 withif (!mine.empty()) InvalidateCachedMainTcb();because the range test is equivalent here by construction:ReleaseDeferredTlsBlocksselectsowner_thread_id == GetThreadIdUnique()).thread_local, and a thread's cached TCB always lies inside its own block:TlsGetAddrkeys the block onGetThreadIdUnique(), andTlsMainGetAddrcaches that same thread's block plustls.tcb_offset.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
tcb key=5 found=6 native=6 skipped=0; expansionkey=64 found=1 native=1 skipped=0-j 1): 52/52 PASSgit diff --check: cleanOn 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 setg_tls_main_program, and that function is private andEXIT_IFs unless it is handed a loaded, non-shared ELF with a non-zerotls.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 fromvirtual_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();@coderabbitai[bot] on GitHub · 2026-10-05 23:01 UTC · original
🧩 Analysis chain
🏁 Script executed:
Length of output: 4109
@fawazkh2, verified the fix ina16798ec.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
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.
Pull request closed