Skip to content

TLS: harden take_slot_zero against TEB UAF and stale MOVED entries - #1083

Merged
Prime1997 merged 1 commit into
xcl-dev:mainfrom
real-alponzo:fix/tls-take-slot-zero-safety
Nov 30, 2026
Merged

Prime1997 merged 1 commit into
xcl-dev:mainfrom
real-alponzo:fix/tls-take-slot-zero-safety

Conversation

@real-alponzo

@real-alponzo real-alponzo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Hardens tls::take_slot_zero and MOVED tracking against two concurrency bugs from #106:

  1. TEB / ThreadLocalStoragePointer UAF during take_slot_zero: previously thread_tebs() closed every thread handle immediately after reading ThreadBasicInformation, then take_slot_zero dereferenced the raw TEBs and wrote *arr = block after Sleep(20) without verifying the thread was still alive. Publishing XCL_SLOT only after the snapshot also left a window where concurrently starting or exiting threads bypassed MOVED serialization.
  2. Stale MOVED entries after TerminateThread: MOVED stored only raw TEB addresses (Vec<usize>). A thread killed without DLL_THREAD_DETACH left its TEB address in MOVED permanently, causing exchange_for_new_thread to skip swapping slot 0 and slot k when Windows later recycled that TEB address for a new thread.

Part of #106. (Disjoint from open TLS PRs #196, #431, and #464: only touches MOVED, take_slot_zero, exchange_for_new_thread, and on_thread_detach, and places new tests in a separate integration test file.)

What is in it

  • crates/xcl/src/tls.rs:
    • Replace MOVED: Mutex<Vec<usize>> with MovedTeb { teb, tid, handle: ThreadHandle } (Drop closes the handle). Keeping the handle open prevents Windows from reusing tid while tracked and lets exchange_for_new_thread and on_thread_detach prune threads that died without DLL_THREAD_DETACH via WaitForSingleObject(handle, 0) == WAIT_TIMEOUT.
    • Publish XCL_SLOT.store(k, Ordering::SeqCst) under MOVED.lock() before snapshotting peer threads so concurrent attach/detach serializes on MOVED.
    • Keep peer thread handles open (THREAD_QUERY_INFORMATION | THREAD_SUSPEND_RESUME | THREAD_SYNCHRONIZE) across both phases of take_slot_zero, suspending each peer individually with a RAII SuspendGuard across only raw syscalls (WaitForSingleObject, NtQueryInformationThread, ReadProcessMemory) and pointer updates (no heap allocations or locks while suspended). Skip threads mid-LdrpAllocateTls (arr == null, arr[0] == 0, or arr[k] == 0) so their upcoming on_thread_attach performs the swap cleanly.
    • Handle the current thread directly without adding it to MOVED.
  • crates/xcl/tests/tls_slot_zero.rs:
    • Process-isolated integration tests with a .CRT$XLY callback forwarding real DLL_THREAD_ATTACH / DLL_THREAD_DETACH events:
      • reused_teb_after_terminate_thread_still_exchanges_slots — verified to fail deterministically on unmodified main (47efa2e) on the first recycled TEB (host TLS corrupted on new thread), and passes with this fix.
      • take_slot_zero_survives_concurrent_thread_exit_and_termination — exercises take_slot_zero under concurrent thread spawn/exit churn and TerminateThread, validating both survivor TLS integrity and HeapValidate.

Regression run

Baseline (main, warm shader/PSO cache):

xcl-smoke v1
commit: 09940bb87fa11bc394fd9e5de570c2b7cfd16323
gpu: AMD Radeon RX 6800
title: YouKnowWho
seconds: 60
exit: 0x0
frames shown: 405 (PresentX 405)
presents per 2 s (last 3): 11 12 11
device removals: 0
crashes: 0
peak commit: 15870 MB

This PR (fix/tls-take-slot-zero-safety, warm shader/PSO cache):

xcl-smoke v1
commit: 39ea43e9d95d706aaa6ec679c7544d63c822a566
gpu: AMD Radeon RX 6800
title: YouKnowWho
seconds: 60
exit: 0x0
frames shown: 489 (PresentX 489)
presents per 2 s (last 3): 17 16 17
device removals: 0
crashes: 0
peak commit: 15868 MB

Tested

Hardware: Windows 11 Pro for Workstations (Build 26300), Intel Core i9-9900K, 32 GB RAM, AMD Radeon RX 6800 (16337 MiB VRAM, Driver 32.0.21045.29003), rustc 1.100.0 (0ef1bc386 2026-11-09).

  • cargo test -p xcl --test tls_slot_zero (5 consecutive runs): 2 passed; 0 failed; 0 ignored; 0 skipped each run (on unmodified 47efa2e, reused_teb_after_terminate_thread_still_exchanges_slots failed with host TLS was corrupted on new thread (iter=234, reused=1)).
  • cargo test -p xcl --lib tls::: 4 passed; 0 failed; 1 ignored; 0 skipped.
  • cargo test -p xcl --test e2e: 3 passed; 0 failed; 0 ignored; 0 skipped.
  • XCL_REQUIRE_GPU=wave64,mesh cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4: 740 passed; 3 failed; 41 ignored; 0 skipped. All 3 failures are the pre-existing RDNA2 placed_title_textures_share_vram_and_preserve_pixels + 2 VRAM_TEST_LOCK PoisonError cascades on unmodified main (tracked in D3D12.X: map a one-slice title texture's packed mips where D3D12 addresses them #470).
  • .\scripts\smoke.ps1 -Game '<game folder>\YouKnowWho' on 39ea43e9d95d706aaa6ec679c7544d63c822a566 (see Regression run above).

Not tested

  • MinGW / gnu target builds (MSVC toolchain only).
  • Non-AMD GPUs and Linux / Wine.

AI use

Antigravity (Gemini 4 Neon) audited crates/xcl/src/tls.rs, wrote the fix and process-isolated regression tests, and ran the local test suite and smoke runs.

Keep peer thread handles open across both phases of take_slot_zero, suspend each peer across raw TEB/TLS-array syscalls and pointer swaps with WaitForSingleObject + ReadProcessMemory liveness checks, and publish XCL_SLOT before snapshotting threads so concurrent attach/detach serializes on MOVED.

Track MOVED entries by (teb, tid, open thread handle) and prune signaled handles in exchange_for_new_thread and on_thread_detach so threads terminated without DLL_THREAD_DETACH (e.g. TerminateThread) cannot poison a recycled TEB address and skip the slot 0 / slot k swap on future threads.

Part of #106.

Assisted-by: Antigravity (Gemini 4 Neon)
@futurepro62

Copy link
Copy Markdown

Full-suite run, since this PR has no test report yet. Tested exact head 39ea43e (on its base 47efa2e).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 616.64, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, debug, D3D12 debug layer installed.
  • cargo build --workspace, then XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4: 743 passed, 0 failed, 41 ignored. SKIPPED (no wave64): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware.
  • The new tests ran and passed: reused_teb_after_terminate_thread_still_exchanges_slots, take_slot_zero_survives_concurrent_thread_exit_and_termination.

Not tested

  • AMD, a release build, a game (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.

@DavidM1911

Copy link
Copy Markdown
Contributor

Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

Thanks!

@upipibi

upipibi commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

NVIDIA test report for 39ea43e (head as is, base 47efa2e), for #1607's "one more test report" list. RTX 3070 8 GB (Ampere, 32-lane waves), driver 616.56, Windows 11, debug, after cargo build --workspace:

  • cargo test --workspace --no-fail-fast -- --test-threads=4 --skip hle::xaudio2: 734 passed, 0 failed, 41 ignored. The end-to-end title tests pass, and so does the new reused_teb_after_terminate_thread_still_exchanges_slots (tests/tls_slot_zero.rs).
  • Skipped hle::xaudio2, because its tests fail or hang on this machine on main too. The PR doesn't touch it.
  • SKIPPED lines: 2, both no wave64 on this card.

AI-assisted (Claude Code, Claude Opus 5.5). Synthetic tests only; no title run.

@github-actions github-actions Bot added area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH area:tests Unit, integration, e2e tests, or testtitle needs-1st-check Passes gates; needs first independent merge-check (#3041) labels Nov 28, 2026
@throny

throny commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

merge-check claim
head: 39ea43e

@throny

throny commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: fa20459
head: 39ea43e
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2610 passed, 0 failed, 49 ignored (27 SKIPPED lines). Base alone at fa20459: 2608 passed, 0 failed, 49 ignored.
review: no blocking finding; all hunks read with care for lifetimes and lock order. main's tls.rs is still the file this PR was written against. The stale entries are the thread blocks of threads ended by TerminateThread, which never run their detach; matching on block address plus thread id and keeping the thread's handle open (so its id cannot be reused) closes that. Other threads' blocks are now read through ReadProcessMemory, so such a read cannot fault; nothing allocates or takes a lock while a thread is suspended; the lock order is the one main has. Worth a follow-up, none worse than main: SuspendThread returns before the thread has really stopped (a GetThreadContext after it would make that certain); the two writes into another thread's TLS array are plain writes; and when suspending a live thread fails, that thread is skipped, which in the second phase would lose the title's block for it, where main would have written anyway (needs a failing suspend, which is rare). Costs: each thread attach and detach now does one wait per tracked entry. One of the new tests relies on Windows reusing a thread block within 2048 spawns, which could be flaky on some system. It will conflict textually with the open #464 on the same file.
performance: negligible (the slot work runs once per title; a short wait per tracked entry at thread attach and detach). No translator source.
verdict: safe to merge
hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite).

@github-actions github-actions Bot added needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) and removed needs-1st-check Passes gates; needs first independent merge-check (#3041) labels Nov 29, 2026
@relativespace2K

relativespace2K commented Nov 30, 2026 •

Copy link
Copy Markdown

merge-check
base: 53e85fb
head: 39ea43e
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2790 passed, 6 failed, 49 ignored; failing: gpu::dxil::compact_tests::gpu_compact_form_with_micro_blocks_and_literal_table_runs_as_the_plain_form, gpu::recomp::pso::shader_cache_tests::console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk, hle::d3d12x::standin::tests::concurrent_shell_miss_reuses_winner_and_releases_loser_pipeline, ram_budget::tests::windows_takes_a_working_set_maximum_and_lifts_it, and two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs (in --test gpu_two_pass_cache_e2e, so 5 failing tests give 6 failures). The same five fail on base 53e85fb alone (2788 passed, 6 failed, 49 ignored there), so none comes from this PR; its two new tests in crates/xcl/tests/tls_slot_zero.rs passed, and they run in a child copy of the test binary so _tls_index really starts at 0 and the .CRT$XLY callback sees real attach/detach. 13 SKIPPED lines, all environmental: no D3D12 debug layer / d3d12SDKLayers.dll, no heap windows, no GPU_UPLOAD, per-lane f16/f32 forms refused.
review: no blocking finding; two files, every hunk read. The exchange now holds an open handle per peer, so a TID or TEB cannot be recycled under a stale MOVED entry, matches entries on TEB and tid, and prunes dead ones; SuspendThread/ResumeThread bracket only raw syscalls and ReadProcessMemory pointer reads, with no allocation or lock taken while a peer is suspended, so the "suspend then allocate" deadlock is not re-introduced; a peer that is mid-LdrpAllocateTls with empty slots is skipped and left to its own attach. XCL_SLOT is published before the snapshot now, which is the right order for threads attaching during the swap. read_own_ptr going through ReadProcessMemory rather than dereferencing is what makes a peer dying mid-read a None instead of an access violation. The tests are aggressive on purpose (TerminateThread, TEB reuse, churn) but they are process-isolated and they assert host TLS isolation and heap validity afterwards, which is the invariant the fix is about. Notes, not blocking: MOVED keeps handles for moved threads until they detach or are pruned, and the test helper spawns a child copy of the test binary (guarded by XCL_TLS_SLOT_ZERO_CHILD) which is the only process it starts. No duplicate: nothing else changes take_slot_zero; #431 and #196 touch other TLS paths.
performance: once per process, at start-up: one handle per thread, two short suspensions each, and the same 20 ms sleep as before; nothing per frame or per thread creation beyond a WaitForSingleObject(0) when MOVED is touched.
verdict: safe to merge
hardware / tool and model: AMD Radeon RX 6800 XT 16 GB (RDNA2, wave64), driver 32.0.21045.29003; Ryzen 5 5600, 32 GB RAM; Windows 10 IoT Enterprise LTSC 2024, 10.0.26100 build 26100.9974; Rust 1.100.0; DXC 1.9.2602.17; debug build. DeepSeek Harness coding agent, model DeepSeek V4.1 Flash.

@github-actions github-actions Bot added ready-to-merge Has 2 independent safe merge-checks on current head (#3041) and removed needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) labels Nov 30, 2026
@Prime1997
Prime1997 merged commit 7ed11d0 into xcl-dev:main Nov 30, 2026
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH area:tests Unit, integration, e2e tests, or testtitle ready-to-merge Has 2 independent safe merge-checks on current head (#3041)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants