Skip to content

TLS: installing an image leaves other threads' blocks to the loader - #431

Open
Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:fix/tls-fill-live-threads
Open

Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:fix/tls-fill-live-threads

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

cargo test -p xcl --lib sometimes dies with 0xC0000005 before any test fails (only with several test threads). The crash is in tls::install. After loading the carrier DLL, it filled every other thread's new TLS slot itself: a toolhelp snapshot, then each thread's TEB read and its TLS block written. A thread that exits in between has its TEB unmapped, which is the read AV, or its TLS block freed by LdrShutdownThread, which means heap corruption. Nothing outside the loader can hold a thread's TEB or TLS in place, so the walk can't be made safe:

  • a handle keeps only the thread object;
  • STILL_ACTIVE holds while the blocks are freed;
  • suspending doesn't stop a thread already exiting in the kernel.

The carrier now carries the image's template, so the loader fills every thread's block itself, under its own lock.

What is in it

  • build_carrier_dll_holding: the carrier's TLS initial data is the image's template (clamped to [16, MAX_CARRIER_TEMPLATE] to preserve TLS: clamp carrier template size before rounding to prevent u64/u32 overflow #1403's overflow guard), with zeros after it. install uses it and build_carrier_dll_with delegates to it.
  • fill_existing_threads is removed, and the module docs say who fills the blocks now.
  • Nothing else changes: on_thread_attach still fills new threads (now with the same bytes), and take_slot_zero is untouched.
  • Tests:
    • carrier_holds_the_template;
    • a_thread_running_during_install_gets_the_template: a thread started before install finds the template in its own block, and nothing in XCL writes into it;
    • install_while_threads_exit: 200 installs while 8 threads keep starting and ending short threads. Its carriers go to one folder, %TEMP%\xcl_tls_test_churn, cleared of earlier runs' carriers at the start (cleanup_cache).

Tested

  • Rebased head 30378b241ece56458ce639e1e3a8bc33ffa03d1a on main 5ad98adbc360225ac8a57ad9661e16fe8df9d8dd:
    • Hardware & toolchain: NVIDIA GeForce RTX 5070 Ti (driver 610.74), AMD Ryzen 9 9950X, Windows 11 Pro 26200, rustc 1.99.0 (b940084d7 2026-09-28), DXC 1.9.2609.5, debug + release.
    • cargo build --release -p xcl: clean, 39 warnings (0 new vs main 5ad98adbc baseline of 39 warnings; 0 warnings in crates/xcl/src/tls.rs).
    • scripts/test.ps1 (cargo build --workspace, cargo bench -p xcl --bench '*' -- --test, cargo test --workspace -- --test-threads=4): 3008 passed, 0 failed, 52 ignored across 43 test targets + doc-tests (xcl lib: 2856 passed, 0 failed, 32 ignored; tls::tests: 8 passed, 0 failed, 1 ignored including all 3 new tests and carrier_size_and_build_clamp_without_overflow; tests/tls_slot_zero.rs: 2 passed, 0 failed). SKIPPED GPU tests: 24 (22 no wave64, 2 no heap windows).
    • title run: 60 s retail title smoke (title ea3b5e4d), 1511 frames shown (PresentX 1511), presents per 2 s 61 61 60, peak commit 14632 MB, 0 device removals, 0 crashes (exit 0x0).
  • Earlier verification on 940f7cb (same TLS logic):
    • The crash, named. On main 6da33fa, cargo test -p xcl --lib crashed in run 2 of 2 on tls::tests::install_without_an_index_variable reading TEB+0x58 in tls_block_of ← fill_existing_threads ← install; with --test-threads=1 it passed 6 of 6.
    • The churn test (install_while_threads_exit, debugger, CPU only): main d4f17ca with the test crashed 19 of 20 runs at the same read; this change passed 30 of 30.
    • Mutation check (carrier without template and no walk): fails install_without_an_index_variable, windows_loads_carrier_and_allocates_full_block_for_all_threads, and a_thread_running_during_install_gets_the_template.
    • Wine 11.21 Staging (windows-gnu, CPU only): tls:: and pe:: pass, and both new thread tests pass 10 of 10.
    • Independent AMD runs on earlier heads by @MesshM (RX 9060 XT, 3/3 crash on main vs 3/3 pass with this PR) and @srcamarda (RX 7800 XT, 90 s smoke pair clean).

Regression run

Release builds on RTX 5070 Ti (main 5ad98adbc vs rebased head 30378b241), no uncommitted changes.

main:

xcl-smoke v1
commit: 5ad98adbc360225ac8a57ad9661e16fe8df9d8dd
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1460 (PresentX 1460)
presents per 2 s (last 3): 60 60 61
device removals: 0
crashes: 0
peak commit: 15067 MB

PR:

xcl-smoke v1
commit: 30378b241ece56458ce639e1e3a8bc33ffa03d1a
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1511 (PresentX 1511)
presents per 2 s (last 3): 61 61 60
device removals: 0
crashes: 0
peak commit: 14632 MB

Not tested

  • AMD / Intel GPUs on rebased head 30378b241, native wave64 GPU tests (22 skipped on RTX 5070 Ti), and opt-in XCL_HEAP_WINDOWS=1 GPU tests (2 skipped).
  • Sample-gated tests (XCL_SAMPLE_* unset).
  • take_slot_zero is not changed here.
  • macOS / Linux: not built.

AI use

  • Claude Code (Claude Opus 5.5): diagnosed the crash via debugger capture, wrote the original change, tests, and earlier runs.
  • Antigravity (Gemini 4 Neon): rebased onto main 5ad98adbc (preserving TLS: clamp carrier template size before rounding to prevent u64/u32 overflow #1403's MAX_CARRIER_TEMPLATE clamp in build_carrier_dll_holding), ran the release build comparison, scripts/test.ps1, 60 s smoke pair, and scripts/pr_check.py --local, and updated this description.

@MesshM

MesshM commented Nov 24, 2026

Copy link
Copy Markdown

Test run of 526a17661f22431342f4a89c4f8925eb68fedd18 on AMD (RDNA4); the PR was tested on NVIDIA only. The branch is based on 9ab7d76, so I merged it onto current main a6f5f7a locally (clean merge, only tls.rs) and tested that tree.

Tested

  • AMD Radeon RX 9060 XT 16 GB (RDNA4), driver 32.0.32029.2010; Ryzen 7 5700X (8C/16T), 64 GB RAM, Windows 11 Pro build 26200, Rust 1.100.0 stable-x86_64-pc-windows-msvc, debug
  • .\scripts\test.ps1 (cargo build --workspace + cargo test --workspace -- --test-threads=4) on the merge: 679 passed, 0 failed, 41 ignored, exit code 0; xcl lib tests 639 passed, 0 failed, 21 ignored (main on this machine: 636 / 676, the difference is the 3 new tests)
  • 0 SKIPPED; all tls::tests pass, including a_thread_running_during_install_gets_the_template and install_while_threads_exit
  • install_while_threads_exit copied unchanged into main's tls.rs (nothing else changed), cargo test -p xcl --lib tls::tests::install_while_threads_exit, 3 runs: 3 of 3 crashed with 0xc0000005, STATUS_ACCESS_VIOLATION
  • the same test on the merge, 3 runs: 3 of 3 passed (1.95–2.04 s)

So on this 16-thread machine the race reproduces every time, not 1 run in 3.

Review of the change: install runs in step 5 of loader::map, after relocations (step 3), so the template the carrier now carries is the relocated one, the same bytes fill_block used to copy; past template_len the block is zeros, as before. on_thread_attach still fills new threads from the image's live template, so that path is unchanged. I found nothing to change.

Not tested: no retail title or regression run (I have no unpacked game), no XCL_SAMPLE_* tests, release build; the PR's head on its old base was not run, only its merge onto main; the overlap with #196 was not checked.

Run and report by Claude Code (Claude Opus 5.5) on this machine; the review points were checked against the code.

@QemmHD

QemmHD commented Nov 24, 2026

Copy link
Copy Markdown

NVIDIA run (only an AMD run so far) plus a short review.

Tested 526a17661 merged onto main a6f5f7a74 on Windows 11 Home 26200, RTX 4070 SUPER (driver 621.24, wave32), Rust 1.98, DXC 1.8.2502.11: pass.

  • cargo test --workspace -- --test-threads=4: 679 passed, 0 failed, 41 ignored (main: 676 / 0 / 41). SKIPPED: only the 2 no wave64 tests.
  • carrier_holds_the_template, a_thread_running_during_install_gets_the_template and install_while_threads_exit ran and passed; no TLS crash.
  • Not run: smoke.ps1 (no retail title on this machine), Wine.

Review – letting the loader seed every block from the carrier's template looks right; the template bytes sit outside the carrier's four DIR64 relocations (tls.rs:163-165), and the template_len == 0 branch avoids from_raw_parts(null).

  1. tls.rs:11-15 (module docs) still say existing threads are filled "right after the carrier is loaded (via their TEB)". The loader now does that from the template; could the paragraph be updated?
  2. Minor, tls.rs:601-614: each run writes 200 carrier DLLs to %TEMP%\xcl_tls_test_churn_<pid>\ and loads them into the shared --lib process, so they can't be deleted and pile up across runs. Fewer installs, or a fixed directory cleared at the start, would avoid that.

AI-assisted review (Claude Code, Claude Opus 5.5).
Discord: bigpeppa.

@Kalmarv
Kalmarv force-pushed the fix/tls-fill-live-threads branch from 526a176 to da285ce Compare November 24, 2026 01:49
@Kalmarv

Kalmarv commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @QemmHD. Both points were right, and both are fixed in da285ce (squashed into the PR's commit).

  1. The module docs (tls.rs:7-16) now say what the code does: the carrier's template is the game's, and ntdll starts every thread's block from it, both the threads running when the carrier loads and later ones. on_thread_attach copies it again for new threads.
  2. install_while_threads_exit now uses one folder, %TEMP%\xcl_tls_test_churn. It clears earlier runs' carriers at the start with the existing cleanup_cache, and the file names keep the process id, so runs at the same time don't clash. After each of 3 runs here the folder held 200 files, all from that run.

🤖 Claude Opus 5.5

@srcamarda

Copy link
Copy Markdown
Contributor

Regression run on a retail title, as asked under Regression run.

Tested

  • AMD Radeon RX 7800 XT (RDNA3), driver 32.0.32029.2010; Ryzen 5 5600G, 32 GB; Windows 11 Pro 26300; release builds
  • scripts/smoke.ps1 -Seconds 90, no input (the title stays on its account screen at 30 fps). Each binary was built from a clean checkout of its commit and run twice; the first run of each has a cold translation cache. Blocks below are from the second run.
  • main 508a0c7: 2343 / 2361 frames, peak 15764 / 15674 MB. This PR (da285ce): 2322 / 2359 frames, peak 16486 / 16414 MB. No crash or device removal in any run.
  • The changed path runs in this title: its log shows a TLS install for three images with other threads alive, e.g. TLS: game_scarlett_master.exe: template 5248 B, block 5248 B, index 18, threads initialized: 3 (also xboxbvhbuilder.dll and libhttpclient.gdk.dll), and the title then runs normally.
  • This head is based on 9ab7d76, 60 commits behind main. Its peak commit is ~0.7 GB above main's here, most likely from the base: main's memory changes since then aren't in it. D3D12.X: the sparse state is replaced outside its lock #443 and D3D12.X: map a one-slice title texture's packed mips where D3D12 addresses them #470, both close to main, match main. A rebase would settle it.

Regression run

main:

xcl-smoke v1
commit: 508a0c74d7c0625d6d2de8d24494e69dc2e1926f
gpu: AMD Radeon RX 7800 XT
title: RetailGame_Dump
seconds: 90
exit: 0x0
frames shown: 2361 (PresentX 2361)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15674 MB

this PR's head:

xcl-smoke v1
commit: da285ce79cbfc485e2a284da694c0d6dd41801b5
gpu: SudoMaker Virtual Display Adapter
title: RetailGame_Dump
seconds: 90
exit: 0x0
frames shown: 2359 (PresentX 2360)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16414 MB

gpu: in this PR's block names a virtual display adapter: the head predates 97dc49c, which reads the adapter from report.json. XCL ran on the RX 7800 XT in every run.

Not tested

  • Anything past the account screen.
  • The whole test suite at this head (only the title runs).

AI use

  • Claude Code with Claude Opus 5.5 built both commits, ran the smoke runs and wrote this report; the runs are from my machine.

@raylitebull

Copy link
Copy Markdown
Member

Code/CI review only (not independently runtime-tested by me): clean merge with both checks green (Build and test + PR description). Cleanly fixes the intermittent tls::install crash by leaving other threads' TLS blocks to the loader. Recommend merging, @ivall.

@DavidM1911

Copy link
Copy Markdown
Contributor

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

Thanks!

@github-actions

Copy link
Copy Markdown

Nothing has happened on this PR for 3 days, so it is marked stale and will be closed in 4 days. A push or a comment takes the mark off: rebase it onto main if it conflicts, and say in one line what it still fixes. If it only waits for a maintainer, a comment saying so is enough.

@github-actions github-actions Bot added the stale No activity for 3 days; closed 4 days later unless something happens label Nov 29, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 7d86c5d
head: 940f7cb
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2899 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read the whole diff. Still needed: main still fills existing threads by walking them (fill_existing_threads, tls.rs ~553-602, called from install ~653), and the only TLS change since this base (39ea43e) is in take_slot_zero. Findings: (1) crates/xcl/tests/tls_slot_zero.rs, added after this PR, calls install with 16 parked threads and asserts their slot-0 template (~122, ~176); with this change those blocks come from ntdll instead of the walk, so that test was the one to watch: both its tests (take_slot_zero_survives_concurrent_thread_exit_and_termination, reused_teb_after_terminate_thread_still_exchanges_slots) pass in the run above. (2) a_thread_running_during_install_gets_the_template can also pass without the fix if the thread's attach runs after LoadLibrary (on_thread_attach then fills it), so it's weaker than described, though it won't fail by mistake. (3) install_while_threads_exit leaves 200 carriers loaded for the rest of the lib test process. Fine: the carrier layout change (raw size of .data, template copied at OFF_TEMPLATE after the index sentinel), build_carrier_dll_with kept as a wrapper, the PE accessors the new test uses still exist on main, and nothing outside tls.rs reads the removed log line. #196 overlaps, as the author notes.
performance: 60 s smoke of a retail title, main 7d86c5d vs this merge (d83eb0b4): 1663 -> 1670 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 17153 -> 17818 MB, 0 device removals, 0 crashes.
verdict: safe to merge (the new carrier test can also pass without the fix if the thread's attach runs after LoadLibrary, so it's weaker than described)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@github-actions github-actions Bot added area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) labels Dec 1, 2026
@Decodere

Decodere commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

merge-check
base: 1c8b551
head: 940f7cb
merge: clean (trial-merge commit 065990dd2a2baf7ffa6b2f29be4e09b91bb73fbe, git diff --check clean)
build: cargo build --workspace ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 --nocapture (43 targets): 2912 passed, 0 failed, 51 ignored (+3 new tests vs main baseline). Targeted tls::tests passed 7/7 (1 pre-existing ignored carrier_variants_probe), including all 3 new tests (carrier_holds_the_template, a_thread_running_during_install_gets_the_template, install_while_threads_exit) with 0 skips, and tests/tls_slot_zero.rs passed 2/2. 28 SKIPPED emissions (host environment only: 22 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 2 no heap windows, 1 cannot disable the driver cache (Windows Developer Mode required)).
review: Read the full merged diff (+88/-69 in crates/xcl/src/tls.rs). Embeds the image's TLS template bytes directly into the synthesized carrier DLL's .data section via build_carrier_dll_holding (sizing SizeOfRawData and SizeOfInitializedData to data_raw = (OFF_TEMPLATE + template.len()).next_multiple_of(FILE_ALIGN) while keeping virtual .data size at OFF_TEMPLATE + template_size), so ntdll initializes every existing and future thread's TLS block under the loader lock during LoadLibraryW. Removes the racy fill_existing_threads Toolhelp/TEB walk that dereferenced TEBs/TLS blocks of concurrently exiting threads without loader synchronization, while preserving on_thread_attach and template_len == 0 handling. The three new unit tests verify carrier PE template layout, live-thread initialization on install, and 200 installs under 8-thread churn. No scope creep or UB.
performance: not applicable (Tier 1 — PE loader / TLS carrier initialization only, runs once per loaded image; no hot runtime or GPU path changed).
verdict: safe to merge
hardware / tool and model: NVIDIA GeForce RTX 4060 8 GB (driver 621.40), Intel Core i5-11400F, 32 GB RAM, Windows 11 Build 26200, Rust 1.100.1 MSVC, DXC 1.9.2602.17 / Antigravity (Gemini 4 Neon)

@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 Dec 2, 2026
tls::install filled the new slot of every other thread itself: a
toolhelp snapshot, then each thread's TEB and TLS block read and
written. A thread that exited in between had its TEB or block freed
under the access: the access violation that ends cargo test -p xcl --lib
now and then (tls_block_of <- fill_existing_threads <- install, from
install_without_an_index_variable).

The carrier DLL now holds the image's template, so the loader starts
every thread's block as it - the threads running at LoadLibrary under
its own lock, later ones as they start - and the walk goes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@throny throny added needs-rebase Has merge conflicts with its base branch and removed ready-to-merge Has 2 independent safe merge-checks on current head (#3041) labels Dec 2, 2026
@Kalmarv
Kalmarv force-pushed the fix/tls-fill-live-threads branch from 940f7cb to 30378b2 Compare December 2, 2026 20:19
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (5ad98adbc) as 30378b241 to resolve the crates/xcl/src/tls.rs conflict with #1403 (ce99e53ac, MAX_CARRIER_TEMPLATE clamp), preserving the [16, MAX_CARRIER_TEMPLATE] clamp inside build_carrier_dll_holding and keeping the TLS behavior and tests unchanged.

Still needed: main still walks existing threads' TEBs in fill_existing_threads, which races with thread exit in tls::install.

Verification at 30378b241 (RTX 5070 Ti, driver 610.74, rustc 1.99.0, DXC 1.9.2609.5):

  • cargo build --release -p xcl: clean, 39 warnings (0 new vs main 5ad98adbc).
  • scripts/test.ps1: 3008 passed, 0 failed, 52 ignored, 24 SKIPPED GPU tests (22 no wave64, 2 no heap windows); tls::tests 8/8 passed (1 ignored) and tests/tls_slot_zero.rs 2/2 passed.
  • title run: 60 s retail title smoke (title ea3b5e4d), 1511 frames shown (PresentX 1511), presents per 2 s 61 61 60, peak commit 14632 MB, 0 device removals, 0 crashes (exit 0x0; main 5ad98adbc baseline: 1460 frames, peak commit 15067 MB).
  • scripts/pr_check.py --local: clean (description ok).

Updated the PR description with the new head SHA and fresh xcl-smoke blocks. Ready for re-check on 30378b241.

@github-actions github-actions Bot added the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Dec 2, 2026
@github-actions github-actions Bot added needs-1st-check Passes gates; needs first independent merge-check (#3041) and removed needs-rebase Has merge conflicts with its base branch needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Dec 2, 2026
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 needs-1st-check Passes gates; needs first independent merge-check (#3041) stale No activity for 3 days; closed 4 days later unless something happens

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants