Skip to content

D3D12-LOADER-PROFILE-AND-STACKS-SAFETY: fix handle leaks, CPU underflow, and stderr panics - #2947

Open
bobcatchris wants to merge 2 commits into
ProjectLeonida:mainfrom
bobcatchris:fix/d3d12-loader-profile-stacks-safety
Open

bobcatchris wants to merge 2 commits into
ProjectLeonida:mainfrom
bobcatchris:fix/d3d12-loader-profile-stacks-safety

Conversation

@bobcatchris

Copy link
Copy Markdown
Contributor

Summary

Claimed in the coordination issue as: D3D12-LOADER-PROFILE-AND-STACKS-SAFETY (#2570 (comment)).

Fixes thread-handle leaks, unsigned CPU-time underflow, and closed-stderr panics in leonida-loader's diagnostic sampler and stack dumper:

  1. d3d12/crates/leonida-loader/src/profile.rs:
    • Adds impl Drop for Thread to close every non-null OpenThread handle once on drop (and removes the manual CloseHandle inside write()), so handles are never leaked if File::create / writeln! fails or profile() unwinds.
    • Makes cpu(HANDLE) return Option<u64> checking GetThreadTimes(...) != 0 with saturating_add, keeps t.now monotonic (t.now = now.max(t.now)), and uses saturating_sub for t.now - t.last and t.now - t.first so a failed query cannot panic with subtract underflow in debug builds or wrap to u64::MAX in release builds.
    • Replaces panicking eprintln! calls on the detached LEONIDA_PROFILE thread with fallible let _ = writeln!(std::io::stderr(), ...).
  2. d3d12/crates/leonida-loader/src/stacks.rs:
    • Wraps each OpenThread handle in an RAII ThreadHandle guard, drops it immediately after reading the thread's frames/name/start (before stderr writes), and replaces eprintln! in dump_stacks() with fallible let _ = writeln!(std::io::stderr(), ...).

Tests & Verification

  • Hardware / OS: Windows 11, Rust 1.98.1, no game files or GPU needed.
  • Red -> Green:
    • Added profile::tests::cpu_handles_invalid_handle_and_write_saturates_underflow, profile::tests::profile_writes_file_and_closes_handles_when_stderr_pipe_is_closed, and stacks::tests::dump_stacks_does_not_panic_when_stderr_pipe_is_closed.
    • Reverting saturating_sub and writeln! to t.now - t.first and eprintln!: 3/3 FAIL (RED_EXIT=101, attempt to subtract with overflow + closed-stderr panics).
    • With the fix:
  • python -I tools/d3d12_switches.py --check d3d12/docs/switches.md: exit 0.
  • python -I scripts/check_no_game_data.py d3d12/crates/leonida-loader/src/profile.rs d3d12/crates/leonida-loader/src/stacks.rs: exit 0.

AI Assistance

AI-assisted using Gemini 4 Neon, including a separate read-only independent review pass (APPROVE).

…derr panics (D3D12-LOADER-PROFILE-AND-STACKS-SAFETY)
@merzleckeier

Copy link
Copy Markdown
Contributor

Independent handle ownership and CPU-total checks under Wine on 4b8ae458 merged into 1e3e316c. Both stock closed-stderr fixtures passed 3/3 in isolation and 3/3 in the same build with #2945 and #2946. Restoring the original first eprintln! in each of profile and dump_stacks on the combined tree made the respective child tests exit 101 in all three repeats. The exact profile and stacks groups passed 6/6.

I added the same test-only probe to both trees. It opened a real Windows handle to the test’s own thread and checked it with GetHandleInformation before and after dropping its owner. On main a successful write closed it inside write. After a missing-directory error the main handle remained open even after dropping the owner, so the probe closed it. On the PR the handle stayed open through either write outcome and closed on owner drop. All three repeats per tree agreed.

A separate probe put 50,000 then 10,000 synthetic 100 ns ticks into the report writer. The optimized main build wrote 1844674407370951 ms and the PR wrote 0 ms in all repeats. A naturally failing OS time query was outside the fixture.

MEASURED under Wine 11.22 with OpenAI Codex and a separate read-only review.

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix itself is sound: Thread/ThreadHandle Drop now cover the failure paths (profile.rs:52-61, stacks.rs:100-110), every CPU delta is saturating with a monotonic now (profile.rs:148-153, :191), and stderr writes can no longer panic. Three of the four mutations are caught (now - first, a no-op Thread::drop, and eprintln! in stacks) — good.

One blocker: the regression tests live behind feature = "diagnostics" (lib.rs:40-43), and CI runs cargo test --workspace --exclude xtask --locked with no features (.github/workflows/d3d12.yml:76). So the default --lib run is 84 tests, none of the new ones compile, and the PR body's "83 passed" run proves nothing about this change. Either add a diagnostics test step or the guards can silently regress.

Second: the stacks handle-close guard is untested — making ThreadHandle::drop a no-op leaves all three stacks::tests green, while the equivalent profile mutation is caught. One more assertion would close it.

Minor: if the first cpu() fails, first = 0 makes the reported milliseconds a lifetime total rather than since profiling began — worth a comment or a None state. And #2588 is unrelated: it is the 64 MB GPU worker stack, not this diagnostic stack dumper, so there is no duplication between them.

Merge is clean against current main, and no other open PR touches profile.rs/stacks.rs.

…ard missing first cpu(), and test ThreadHandle drop
@bobcatchris

Copy link
Copy Markdown
Contributor Author

Updated in fast-forward commit $(git rev-parse --short HEAD) to address all three review points from @KelboLive:

  1. Default-feature CI test coverage (lib.rs): Switched mod profile; and mod stacks; to #[cfg(all(windows, any(feature = "diagnostics", test)))] (with #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] on profile_on_schedule / dump_stacks_on_schedule) so all 6 profile::tests and stacks::tests compile and run in CI's default cargo test --workspace --exclude xtask --locked without touching workflow YAML.
  2. stacks handle-close test (stacks.rs): Added an OpenThread + ThreadHandle drop + GetHandleInformation == 0 assertion inside the single-threaded child of dump_stacks_does_not_panic_when_stderr_pipe_is_closed. Confirmed that making ThreadHandle::drop a no-op fails the test (STACKS_DROP_RED_EXIT=101).
  3. Thread.first: Option<u64> (profile.rs): Changed first to Option<u64> so a failed initial cpu() query does not leak a thread's pre-profile lifetime CPU total into the next sample (baseline is initialized on the first successful Some(now), or 0 ms if cpu() never succeeds), and covered first: None in cpu_handles_invalid_handle_and_write_saturates_underflow.

Re-verified locally (Windows 11, Rust 1.98.1):

  • cargo clippy --locked -p leonida-loader --all-targets -- -D warnings: 0 warnings, exit 0.
  • cargo build --locked -p leonida-loader --all-targets: 0 warnings, exit 0.
  • cargo test --locked -p leonida-loader --lib -- profile::tests stacks::tests: 6 passed, 0 failed.
  • cargo test --locked -p leonida-loader --lib --features diagnostics -- profile::tests stacks::tests: 6 passed, 0 failed.
  • tools/d3d12_switches.py --check & scripts/check_no_game_data.py: exit 0.

AI-assisted, including a separate read-only independent review pass (APPROVE).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants