PE loader: bound the TLS callback array walk to the image #1203
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/1212"
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?
Imported from ivall/xcl. Originally posted by Longno242 on 2026-11-24T13:17:41Z.
AddressOfCallbacks was walked with
while *cb != 0and no SizeOfImage check, so a malformed TLS directory could read past the mapped image (or never terminate if the mapping stayed non-zero).What is in it
crates/xcl/src/loader.rs: cap the callback array at 256 entries, require each slot insideSizeOfImage, fail the load otherwise; unit test with AddressOfCallbacks atSizeOfImage - 4Tested
54ae87654ae876d011117193aaf4046a50315439df78ea5(clean tree)cargo test --workspace -- --test-threads=4: 742 passed, 0 failed, 41 ignored. SKIPPED: 2 GPU tests for no wave64 (expected on this card)SKIPPED: 2 GPU tests for no wave64 (expected on this card)cargo test -p xcl --libon RTX 3060 Ti after merging this head with currentmainlocally: all passed, 0 failed, 27 ignored. The PR head itself is unchanged.Regression run
45c51272: previous @Toons29 blocks named the old head. Needs a freshscripts/smoke.ps1pair on this head before merge.Not tested
cargo test --workspaceAI use
Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-24T13:47:08Z.
Verification on RTX 3060 Ti (Windows 11), branch merged with current
main:Note: the full
d3d12xlib filter currently aborts with 0xc0000005 on unmodifiedmaintoo (pre-existing, unrelated to this PR); the PR's own tests were run by name and pass.Imported from ivall/xcl. Originally posted by Toons29 on 2026-11-25T03:16:58Z.
Regression run of
54ae876don the retail title, for this PR's Regression run section. Both blocks are fromscripts/smoke.ps1as printed, not edited:mainon4178e888, this PR on its head commit with no uncommitted changes, same title and time.Against the limits in CONTRIBUTING.md: 101 % of
main's frames, 100 % of its peak commit, no crash, no device removal.AMD Radeon RX 9070 (RDNA4, driver 32.0.32029.2010), Ryzen 7 7800X3D, 32 GB, Windows 11 build 26300, Rust 1.100.0,
cargo build --release -p xcl, 60 s,XCL_NETWORK=0. This is a regression check only: it does not show whether the run reaches the code this PR changes.AI use: Claude Code (Claude Opus 5.5) built both trees and ran
scripts/smoke.ps1; I checked the blocks before posting.Imported from ivall/xcl. Originally posted by Longno242 on 2026-11-25T12:36:35Z.
Thanks @Toons29 — pasted both of your
xcl-smoke v1blocks under Regression run so the description check can see them.Imported from ivall/xcl. Originally posted by Longno242 on 2026-11-25T12:44:00Z.
CI is stuck on
action_required(first-time contributor workflow approval). Smoke + PR description are green; please approve the pending CI workflow when you get a chance.Imported from ivall/xcl. Originally posted by jennydeth on 2026-11-25T13:00:01Z.
Full workspace run (listed under Not tested).
Setup: RTX 3060 12 GB (32-lane waves, driver 32.0.16.2101), Ryzen 5 5600X, 32 GB RAM, Windows 11 build 26300, Rust 1.100.0, DXC 1.9.2609.5, debug build. Head
54ae876.Result: cargo test --workspace -- --test-threads=4: 742 passed, 0 failed, 41 ignored. SKIPPED: 2 GPU tests for no wave64 (expected on this card).
AI use: Claude Code (Claude Opus 5.5) ran the tests and wrote this report.
Imported from ivall/xcl. Originally posted by Longno242 on 2026-11-25T13:21:20Z.
Thanks @jennydeth — copied your workspace counts into Tested (742 passed, 0 failed, 41 ignored. SKIPPED: 2 GPU tests for no wave64 (expected on this card)).
Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-26T03:52:48Z.
Re-verification on RTX 3060 Ti (Windows 11), new head merged with current
main:cargo test -p xcl --lib: all passed, 0 failed, 27 ignored. The earlier merge conflict is resolved.Thanks!
— Devin
Imported from ivall/xcl. Originally posted by Longno242 on 2026-11-26T12:33:36Z.
Thanks @DavidM1911 — noted the
cargo test -p xcl --libre-check (passed, 0 failed, 27 ignored) under Tested. Head commit is unchanged.Imported from ivall/xcl. Originally posted by coolpersonnn on 2026-11-30T18:48:44Z.
merge-check claim
head:
54ae876d01Imported from ivall/xcl. Originally posted by saintwolf on 2026-11-30T18:52:01Z.
merge-check claim
head:
54ae876d01Imported from ivall/xcl. Originally posted by coolpersonnn on 2026-11-30T18:56:09Z.
merge-check
base:
ff0c364b3dhead:
54ae876d01merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2889 passed, 1 failed, 51 ignored (25 SKIPPED: 22 no wave64, 2 no heap windows, 1 cannot disable the driver cache); failing: two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs (stale-compute subprocess failed in tests/gpu_two_pass_cache_e2e.rs; passed on base
ff0c364balone, unrelated to loader.rs); new test loader::tests::a_dll_with_tls_callbacks_past_the_image_fails_to_load passedreview: Read the full diff (+56/-4 in crates/xcl/src/loader.rs). Bug: all three new error paths in map_image_ex (AddressOfCallbacks outside image, callback array past image end, callback array not terminated within 256 entries) call
return fail(...), which runsVirtualFree(base, 0, MEM_RELEASE), AFTER step 4 (import resolution) and AFTERtls_install(&module, template, template_len, t.total_len(), index_ptr)has already succeeded. This violates the invariant documented on line 193 right above it ("game DLLs loaded while its imports were resolved may point into it: its memory stays", which is whytls_installreturnsErrdirectly rather than callingfail), and introduces a use-after-free when a failing DLL has non-zerotemplate_len:tls_installhas already registeredtemplate(insidebase) in the global static TLS list, sotls::fill_block(copy_nonoverlapping) will dereference freed memory on future thread attach, and the installed TLS carrier/slot is leaked. Validate/collect the TLS callback array before callingtls_install(into a local Vec before updatingmodule.tls_callbacks), unregisterbase, and returnErr(...)without callingfail(...). No duplicates found in open/merged PRs or #1607.performance: none (bounded loop of at most 256 u64 reads once per loaded DLL with TLS callbacks)
verdict: not yet: calling
fail(...)(VirtualFree) after import resolution andtls_installviolates the post-import memory-retention invariant and causes a use-after-free onTlsImage.templateiftemplate_len > 0hardware / tool and model: NVIDIA GeForce RTX 5090 (driver 32.0.16.2101), AMD Ryzen 9 9950X3D, Windows 11 Pro build 26300, Rust 1.100.0 / T3 Code (Antigravity), Gemini 4 Neon (Medium)
Imported from ivall/xcl. Originally posted by saintwolf on 2026-11-30T19:00:07Z.
merge-check
base:
ff0c364b3dhead:
54ae876d01merge: clean (trial merge 8a70805eeb424171f9f1a1130d22651c72a39be6; git diff --check clean; +56/-4 in crates/xcl/src/loader.rs)
build: cargo build --workspace -> ok (39 lib + 19 test warnings, all pre-existing dead code / deprecations, none from the PR's lines)
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2890 passed, 0 failed, 51 ignored (base + 1 new test; base
ff0c364bis three merges — #1230, #1194, #235 — newer than this machine's earlier 2887-count baseline onabec7ce9, which adds a net 3 tests, so 2886 + 3 + 1 = 2890). SKIPPED: 27, the standard set for this card (22 "no wave64" — wave32-only GPU, 2 "no heap windows", 1 "cannot disable the driver cache (Developer Mode)", 2 "no xgameruntime.dll"). The new a_dll_with_tls_callbacks_past_the_image_fails_to_load passes in the targeted loader run (5/0) and inside the full suite.review: read the whole diff and the surrounding code. The TLS callback walk in map_image_ex was an unbounded while *cb != 0: an AddressOfCallbacks pointing outside the image, or an in-image list that is not null-terminated, walked past the committed mapping (a reservation of exactly SizeOfImage) and pushed whatever pointers it found — which run_tls_callbacks later calls. The fix: (1) AddressOfCallbacks is first converted with pe.va_to_rva (VA minus image_base, Option) and an out-of-image value fails the load — for an in-image VA this is exactly the old adj() arithmetic (base + rva), so valid images are unchanged; (2) each 8-byte read must satisfy rva + 8 <= pe.size_of_image, else fail; (3) at most 256 entries, else fail — consistent with the parser's other bounds (4096 delay descriptors, 65536 import thunks) and far above any real callback count. Every failure path does unregister_mapped(base) then fail(...), which frees the mapping (VirtualFree) and removes the module from the registry — the same contract as the import-table failure, per the comment at loader.rs 160-162. I checked pe.tls() (pe.rs:526): it reads address_of_callbacks at TLS-directory offset +24, which is IMAGE_TLS_DIRECTORY64's AddressOfCallBacks — the same field the test writes. The test's TLS directory (rva 0x1010, size 40) fits every field the parser reads inside .text; its other fields are zero (start_raw = end_raw = 0, address_of_index = 0), so tls_install proceeds with a zero-length template (the existing carrier mechanism; the pre-existing install_without_an_index_variable test covers the null index path) and the flow reaches the callback code, where AddressOfCallbacks = image_base + (SizeOfImage - 4) makes the first read (rva 0x1FFC, ending 0x2004) cross the 0x2000 image end — the asserted error contains "TLS callback" and the module is not left registered. Locking: the tls_callbacks guard is dropped before unregister_mapped on both failure paths, and the walk's reads happen before fail's VirtualFree, so no nested lock and no use-after-free. Thread: DavidM1911 on an RTX 3060 Ti — cargo test -p xcl --lib loader 3/0 at the head merged with current main, plus a re-verification (cargo test -p xcl --lib all passed, 0 failed, 27 ignored); jennydeth on an RTX 3060 — cargo test --workspace 742 passed, 0 failed, 41 ignored, 2 wave64 SKIPPED; Toons29's paired retail xcl-smoke on an RX 9070 (main
4178e888vs this head: 101% of main's frames, 100% of its peak commit, 0 crashes, 0 device removals). Overlap note: #1376 (open, currently CONFLICTING with main, so not in the queue) rewrites this same hunk with different semantics — it pointer-bounds the walk but stops silently at the image end (no entry cap, no load failure for a truncated list) plus broader TLS-directory and DllMain re-init changes; if both land they conflict textually here, and #1376 needs a rebase first. No #1607 duplicate group covers #1212. Complementary to #1208 (same file, adjacent hunks, no conflict). One file, no new dependencies, no stop-criteria files.performance: none; the walk runs once per image at load time, and the success path does the same reads as before plus one checked bounds computation per entry.
verdict: safe to merge
hardware / tool and model: RTX 4070 SUPER (driver 32.0.16.2140), Ryzen 7 7800X3D, Windows 11 build 26300, Rust 1.100.0 / OpenCode, Qwen 3.8 27B
Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T05:08:11Z.
Triage (#1607) – head
54ae876#1376 (later, conflicting) also bounds this walk in loader.rs:map_image_ex, but differently: it checks that the start pointer is in the image and stops the walk at the image end, and it also validates the TLS directory and index pointer. This PR fails the load when the array runs past SizeOfImage or has more than 256 entries. The two need to be reconciled whichever merges second. No problems found in the diff; the 256-entry cap is an arbitrary limit that is not in Windows' loader.
Recommendation: keep open.
AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
Imported from ivall/xcl. Originally posted by Pipodi on 2026-12-02T18:42:11Z.
merge-check
base:
c53e969602head:
54ae876d01merge: clean (
git merge --no-ffontoc53e9696, merge e17390d0; crates/xcl/src/loader.rs +56/-4)build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3005 passed, 0 failed, 52 ignored; failing: none (SKIPPED 25: 22 no wave64, 2 no heap windows, 1 cannot disable the driver cache). The new loader::tests::a_dll_with_tls_callbacks_past_the_image_fails_to_load passes. two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs (the failure in the first check) passes here, and on a main-equivalent merge of another PR on this machine the same hour; it is a GPU subprocess test that does not go through the TLS callback walk, so that failure is a flake of the test, not this PR.
title run: retail title on NVIDIA GeForce RTX 4090, no save, into the in-engine intro cutscenes: 334 s in the cutscenes (log 176-511 s, from the first 2 s window with cutscene draws to the end), 0 device removals, 0 crashes (exit 0x0, ended by XCL_RUN_SECONDS=420), 2.13 presents/s in the cutscenes (712 presents in 334.5 s, from the log's 2 s activity lines; 2608 frames in the run). Same env and presses on main
5eaadb54earlier today: 341 s in the cutscenes, 2.03 presents/s, 0 removals, 0 crashes. The title's three images with TLS (5248 B, 520 B and 8 B templates) loaded through the new walk. Title binary = merge result + local scripted-press commits (input only), plus two local log-only diagnostics.review: read the whole diff and tls::install. 1) The first check's finding is right, and I confirmed it with a scratch test (not posted): all three new error paths call
fail()(VirtualFree of the image) after import resolution and aftertls_installsucceeded, buttls::installhas already pushed the image's TLS template address (inside the freed image) intotls::IMAGES. Loading a DLL with a template and a callback array past the image end returns "TLS callback array past the image end", the template's page is then MEM_FREE, and the nexttls::on_thread_attach(called for every new thread from xcl.exe's TLS callback) dies with STATUS_ACCESS_VIOLATION infill_block. The PR's test has a 0-byte template, so it does not reach this. It also goes against the comment abovetls_install("its memory stays" once imports were resolved). Valid images are unaffected (the title run above), so this only bites the malformed images the PR is meant to handle: walk the callback array into a local Vec beforetls_install(or, after it, unregister and returnErrwithoutfail), and give the test a non-empty template. 2) The 256-entry cap fails the load of an image with a longer list; the Windows loader has no such cap (Foniass's triage). 3) #1376 (open, conflicting with main) rewrites this same hunk differently (bounds-checks the start and stops at the image end, no cap, no load failure); whichever lands second has to be reconciled. On the disagreement: the second check's "no use-after-free" reasoning covers only the walk's own reads, not the template registered by tls::install.performance: none measurable: the walk runs once per image load; cutscene presents/s 2.13 vs 2.03 on main
5eaadb54(older base, same env), peak private 43.4 vs 43.9 GB.verdict: not yet: the new failure paths free the image after tls_install registered its TLS template, so the next thread start after a rejected DLL is a use-after-free (confirmed, access violation); validate the callback array before tls_install or keep the memory, and test with a non-empty template.
hardware / tool and model: NVIDIA GeForce RTX 4090 24 GB, driver 621.40; Intel Core i9-13900K, 32 GB; Windows 11 build 26300; rustc 1.100.0; Claude Code, Claude Opus 5.5
Imported from ivall/xcl. Originally posted by Longno242 on 2026-12-02T20:44:05Z.
Thanks @coolpersonnn and @Pipodi — the use-after-free was real.
45c51272(rebased onto currentmain) walks the callback array into a localVecbeforetls_install, and on a bad list returnsErrafterunregister_mappedwithoutVirtualFree(imports are already resolved, so the image must stay). The regression test now uses an 8-byte TLS template so a free-after-install would leave a live template pointer.loader::tests: 5 passed, 0 failed on this head. Retail smoke for the previous head is stale after the rebase — needs a fresh pair.Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T21:13:12Z.
Follow-up review of
45c51272, since54ae876(code reading only, not a merge-check;Build and test (Windows, no GPU)red,PR descriptionred) · 1 high, 1 medium, 1 nitIn short: Since
54ae876the first commit was only rebased. A new commit,45c5127, reads the TLS callback array beforetls_install, so a bad array now returnsErrwithout callingfail(), and the image is no longer freed while a TLS template points into it. The reordering is right. The first commit on its own still has that use-after-free, and the updated test's template overlaps the TLS directory it tests. #1376 still overlaps this walk, so whichever merges second reconciles the two.High
53b8e9bcallsfail(), which runsVirtualFreeon the image, aftertls_installhas registered the template intls::IMAGES.45c5127only undoes that. Every commit lands onmain, so the broken state would be there forgit bisect. Squash45c5127into53b8e9b.Medium
The test's TLS template overlaps the TLS directory, and the test does not check what its comment says.
0x1010and is 40 bytes, ending at0x1038(loader.rs~636-648).template_rva = 0x1030puts the 8-byte"tlsdata!"on top ofSizeOfZeroFillandCharacteristics, makingSizeOfZeroFillabout 1.7 GB.tls_install. In that regression,tls_installwould be asked for a TLS block of about 1.7 GB, and the test only asserts the error text andfind_mapped_by_name. Nothing checks that no TLS image was registered.Fix: move the template outside the directory (for example to
0x1040), and either assert no template was installed or drop that sentence from the comment.Nit
54ae876. Not tested lists "Fullcargo test --workspace", while Tested reports one.Checked and fine
va_to_rvarebases against the preferredimage_base, and reads go throughbase + rva, so a relocated image works.checked_add(8)with<= size_of_imagekeeps every 8-byte read inside the image, andread_unalignedis used.modules::unregister_mapped(base)and returnErrwithoutVirtualFree, like the existingtls_installerror path.module.tls_callbacksonly aftertls_installsucceeds.SizeOfImage - 4makes the "past the image end" branch fail beforetls_installat this head. Onmain, the unbounded read of that slot crosses the end of the image.Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.