Skip to content

PE loader: bound the TLS callback array walk to the image - #1212

Open
Longno242 wants to merge 1 commit into
xcl-dev:mainfrom
Longno242:pe-loader-tls-callback-bounds
Open

Longno242 wants to merge 1 commit into
xcl-dev:mainfrom
Longno242:pe-loader-tls-callback-bounds

Conversation

@Longno242

@Longno242 Longno242 commented Nov 24, 2026 •

Copy link
Copy Markdown

AddressOfCallbacks was walked with while *cb != 0 and 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 inside SizeOfImage, fail the load otherwise; unit test with AddressOfCallbacks at SizeOfImage - 4

Tested

  • Hardware/OS (full suite by @jennydeth): 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
  • Commit tested: 54ae876d011117193aaf4046a50315439df78ea5 (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)
  • Retail smoke: see Regression run (@Toons29, RX 9070)
  • @DavidM1911 re-checked cargo test -p xcl --lib on RTX 3060 Ti after merging this head with current main locally: all passed, 0 failed, 27 ignored. The PR head itself is unchanged.

Regression run

  • Retail scripts/smoke.ps1 from @Toons29 (RX 9070, 60 s, same title/time; blocks as printed):
xcl-smoke v1
commit: 4178e888c0b5be50a2887eda45cdb832763b68a4
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 14831 MB
xcl-smoke v1
commit: 54ae876d011117193aaf4046a50315439df78ea5
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1634 (PresentX 1634)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14809 MB

Not tested

  • Full cargo test --workspace
  • The 256-entry cap path (only the past-end case is unit-tested)

AI use

  • @jennydeth: Claude Code (Claude Opus 5.5) ran the full workspace suite and reported results in a PR comment
  • Cursor Auto (Composer): found the unbounded walk, implemented the bound and test, opened this draft PR. Exact underlying model name not disclosed to the agent.

AddressOfCallbacks was walked with no length or SizeOfImage check, so a
malformed list could read past the mapping. Cap at 256 entries and refuse
slots that straddle the image end.

Assisted-by: Cursor Auto (Composer)
Co-authored-by: Cursor <cursoragent@cursor.com>
@DavidM1911

Copy link
Copy Markdown
Contributor

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

  • cargo test -p xcl --lib loader: 3 passed, 0 failed.

Note: the full d3d12x lib filter currently aborts with 0xc0000005 on unmodified main too (pre-existing, unrelated to this PR); the PR's own tests were run by name and pass.

@Toons29

Toons29 commented Nov 25, 2026

Copy link
Copy Markdown

Regression run of 54ae876d on the retail title, for this PR's Regression run section. Both blocks are from scripts/smoke.ps1 as printed, not edited: main on 4178e888, this PR on its head commit with no uncommitted changes, same title and time.

xcl-smoke v1
commit: 4178e888c0b5be50a2887eda45cdb832763b68a4
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 14831 MB
xcl-smoke v1
commit: 54ae876d011117193aaf4046a50315439df78ea5
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1634 (PresentX 1634)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14809 MB

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.

@Longno242

Copy link
Copy Markdown
Author

Thanks @Toons29 — pasted both of your xcl-smoke v1 blocks under Regression run so the description check can see them.

@Longno242
Longno242 marked this pull request as ready for review November 25, 2026 12:43
@Longno242

Copy link
Copy Markdown
Author

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.

@jennydeth

Copy link
Copy Markdown

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.

@Longno242

Copy link
Copy Markdown
Author

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)).

@DavidM1911

Copy link
Copy Markdown
Contributor

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

rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
… load (port upstream xcl-dev#1212 + xcl-dev#1208)

Windows loader.rs (cfg(windows)-only, reference-only on Linux): delay_imports
Err arm goes from warn-only to unregister+fail like a broken import table;
TLS AddressOfCallbacks walk is capped at 256 entries and bounded to the
image (va_to_rva outside-image guard + checked_add past-end guard), with
unregister+fail on all three failure legs. Both upstream tests verbatim;
0 tests run on Linux.

Linux loader_linux.rs twin: TLS walk already image-bounded
(checked_rva + at+8>size + per-target va_to_rva, strictly stricter than
the 256-entry cap) so pin test only; delay_imports warn-only mirrored to
unregister+fail with twin retry test. Graft red pre-fix, green post-fix.
@Longno242

Copy link
Copy Markdown
Author

Thanks @DavidM1911 — noted the cargo test -p xcl --lib re-check (passed, 0 failed, 27 ignored) under Tested. Head commit is unchanged.

@coolpersonnn

Copy link
Copy Markdown
Contributor

merge-check claim
head: 54ae876

@github-actions github-actions Bot added area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH needs-1st-check Passes gates; needs first independent merge-check (#3041) labels Nov 30, 2026
@saintwolf

Copy link
Copy Markdown
Contributor

merge-check claim
head: 54ae876

@coolpersonnn

Copy link
Copy Markdown
Contributor

merge-check
base: ff0c364
head: 54ae876
merge: 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 ff0c364 alone, unrelated to loader.rs); new test loader::tests::a_dll_with_tls_callbacks_past_the_image_fails_to_load passed
review: 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 runs VirtualFree(base, 0, MEM_RELEASE), AFTER step 4 (import resolution) and AFTER tls_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 why tls_install returns Err directly rather than calling fail), and introduces a use-after-free when a failing DLL has non-zero template_len: tls_install has already registered template (inside base) in the global static TLS list, so tls::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 calling tls_install (into a local Vec before updating module.tls_callbacks), unregister base, and return Err(...) without calling fail(...). 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 and tls_install violates the post-import memory-retention invariant and causes a use-after-free on TlsImage.template if template_len > 0
hardware / 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)

@github-actions github-actions Bot removed the needs-1st-check Passes gates; needs first independent merge-check (#3041) label Nov 30, 2026
@saintwolf

Copy link
Copy Markdown
Contributor

merge-check
base: ff0c364
head: 54ae876
merge: 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 ff0c364 is three merges — #1230, #1194, #235 — newer than this machine's earlier 2887-count baseline on abec7ce, 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 4178e88 vs 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

@github-actions github-actions Bot added the checks-disagree Merge-checks disagree (safe vs not yet); needs maintainer/3rd look label Nov 30, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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.

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 checks-disagree Merge-checks disagree (safe vs not yet); needs maintainer/3rd look

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants