Skip to content

FFI: use extern "system-unwind" across guest-reentry boundaries (#106) - #197

Closed
JGonzalezRodriguez wants to merge 3 commits into
xcl-dev:mainfrom
JGonzalezRodriguez:fix/ffi-unwind-boundaries
Closed

JGonzalezRodriguez wants to merge 3 commits into
xcl-dev:mainfrom
JGonzalezRodriguez:fix/ffi-unwind-boundaries

Conversation

@JGonzalezRodriguez

@JGonzalezRodriguez JGonzalezRodriguez commented Nov 23, 2026 •

Copy link
Copy Markdown

Part of #106. Converts guest-callback function pointer types and re-entrant HLE entrypoints/trampolines/hooks to extern "system-unwind" across 14 files and adds RAII cleanup guards so guest exceptions unwinding through Rust frames do not abort or leave locks/state wedged.

What is in it

  • hle/kernelx.rs: XMemAllocFn/XMemFreeFn, XMemAlloc, XMemFree, LoadLibrary*, LoadPackagedLibrary, GetProcAddress. (hle/d3d12x/real.rs intentionally left untouched.)
  • hle/user.rs: console_wndproc, CreateWindowExA/create_window_ex_w, and CallWindowProcW/SetWindowPos/CreateWindowExW imports.
  • loader.rs & main.rs: TlsCallback, DllMain, ExeEntry, main_thread, xcl_tls_callback.
  • eh.rs: unhandled_filter and TITLE_FILTER invocation (VEH/terminate/gs_failure handlers stay extern "system" / "C").
  • vfs_hooks.rs: MoveFileWithProgressA/W, CopyFileExW, CopyFile2 hooks & orig types so Guard::drop resets IN_HOOK on progress-callback unwind.
  • hle/gameinput.rs: ReadingCallback, DeviceCallback, register_device_callback, plus RAII ReadingGuard / EntryCleanup.
  • hle/xaudio2.rs: VoiceCallbackVtbl (all 7 methods) and decoded_cb_* trampolines.
  • hle/xgameruntime/: taskqueue.rs (callbacks/entrypoints + InflightGuard, CancelInflight, RunningGuard, dual-port Remaining; waiter_fired stays plain extern "system" for RegisterWaitForSingleObject), xasync.rs (callbacks/entrypoints + BeginCleanup, CompleteCleanup, ConsumeCleanup, NotifyGuard, State._owned_payload), api.rs, gamesave.rs, mod.rs, networking.rs.

Tested

  • Cross-compiled on Linux (CachyOS, Ryzen 9 7950X3D, RTX 4090 610.57.4, rustc 1.98.1 x86_64-pc-windows-msvc via clang-cl 23.1.1 + lld-link + xwin SDK 10.0.26100, Proton Experimental + local relaxed vkd3d-proton):
    • cargo build --release --workspace --target x86_64-pc-windows-msvc: 0 errors, 0 warnings.
    • cargo test --no-run --package xcl --lib --target x86_64-pc-windows-msvc: 0 errors, 0 warnings.
    • Unwind regression tests (unwind): 13 passed, 0 failed across eh, hle::gameinput, hle::kernelx, hle::user (through user32!CallWindowProcW), hle::xaudio2, hle::xgameruntime::{api,taskqueue,xasync}, and loader.
    • Affected module suites (hle::kernelx:: hle::gameinput:: hle::user:: loader:: hle::xgameruntime:: eh:: hle::xaudio2:: vfs_hooks::): 139 passed, 1 failed (pre-existing Wine/FAudio-only xma2_source_voice_decodes_and_manages_lifetime).
    • xcl_testtitle.exe: 47/50 passed (all CPU/TLS/exceptions/XGameRuntime/D3D12.X checks pass; 3 known Wine/FAudio diffs).
  • Native Windows 11 (prior commit 202bf56): @Kalmarv built and passed all 10 initial unwind tests on Windows 11 Pro 26200, x64 MSVC, rustc 1.99.0 (and flagged XAsyncComplete/XAsyncGetResult/waiter_fired, all addressed in a82fbfb).

Regression run

  • Not run here (no retail game files on this host); awaiting a scripts/smoke.ps1 run by a tester with a retail title.

Not tested

  • Foreign C++ / SEH exceptions unwinding from a retail title on native Windows; scripts/smoke.ps1 regression run; full native Windows scripts/test.ps1 on head a82fbfb.

AI use

  • Antigravity (Gemini frontier model) assisted with implementation, unwind tests, independent adversarial code review, and PR summary; all builds and tests above were executed locally and verified.

@JGonzalezRodriguez
JGonzalezRodriguez marked this pull request as draft November 23, 2026 20:27
@Kalmarv

Kalmarv commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

One unwind path still leaves XAsync pending indefinitely. In XAsyncComplete, the state becomes Completing before the zero-result call to OP_CLEANUP. If that provider unwinds, control leaves before the terminal phase is published and before NotifyGuard exists. A waiter in XAsyncGetStatus(b, true) can remain asleep, and another completion returns early because the phase already changed. XAsyncGetResult has a related transition to Consuming before invoking the provider. Please define the post-unwind status for those paths and guard the state transition as well as the notification. This finding is from code inspection.

I built PR head 202bf56f1fdba9ab569fe2f6bbacdfdf308efa4e directly on native Windows 11 Pro build 26200, x64 MSVC, rustc 1.99.0. All 10 new unwind tests passed, each in its own process. With the same ten tests carried onto base 956a476bf738a098f39df4f4c8acef682e43030f, the test binary failed to build as expected. Rust rejected two GameInput callback assignments and seven XAudio2 vtable assignments because the base requires plain system callbacks. That control has no runtime count.

The head tests establish Rust panic propagation and cleanup through the exercised call paths. Foreign C++ exceptions and SEH from a title still need their own verification. In particular, casting waiter_fired to the callback type accepted by RegisterWaitForSingleObject preserves the Win64 call layout but does not establish that an exception can leave a Windows thread-pool callback safely. Rust FFI unwinding rules

JGonzalezRodriguez pushed a commit to JGonzalezRodriguez/xcl that referenced this pull request Nov 23, 2026
…gthen tests

Address adversarial review findings on PR xcl-dev#197:

- xasync: make BeginCleanup only remove Phase::Pending blocks (preserving
  synchronously completed payloads), guard XAsyncComplete OP_CLEANUP unwinds
  with CompleteCleanup (writes FLAG_DONE, removes ACTIVE, marks Consumed, wakes
  waiters), guard XAsyncGetResult OP_GET_RESULT/OP_CLEANUP unwinds with
  ConsumeCleanup (without re-entering guest OP_CLEANUP in Drop), guard
  XAsyncRun's XAsyncSchedule with BeginCleanup, and track Payload ownership via
  Arc<Payload> + AtomicBool + PayloadGuard to prevent both leaks and double-free.
- taskqueue: drain both PORT_WORK and PORT_COMPLETION into a single
  Remaining(VecDeque) and notify both ports' condvars before running any
  canceled callbacks in XTaskQueueTerminate (using O(1) pop_front).
- d3d12x/real: revert all 3 lines completely.
- kernelx test: separate throwing_title_alloc/throwing_title_free fallback
  returning null/no-op so concurrent D3D12 tests are undisturbed.
- gameinput test: assert CallbackGuard state directly + from a second thread,
  verify ReadingGuard released the Reading ref via extra AddRef, and guard
  unregister via RAII Drop declared after ctx.
- loader/eh tests: drop flaky global LOAD_LOCK.try_lock() check and serialize
  TITLE_FILTER mutation with a local test mutex.
- tests: add regression tests for BeginCleanup sync-completed payloads,
  Payload ownership on unwind, XAsyncComplete/XAsyncGetResult/XAsyncRun unwinds,
  and XTaskQueueTerminate PORT_WORK unwind draining/waking PORT_COMPLETION.
@JGonzalezRodriguez

Copy link
Copy Markdown
Author

Thanks @Kalmarv for testing on native Windows 11 and for the detailed code review! Both points are addressed in the latest commits (4c6ffb4, 1712e46):

  1. XAsyncComplete (Completing) and XAsyncGetResult (Consuming) unwind paths:
    • Added CompleteCleanup in XAsyncComplete around the zero-result OP_CLEANUP call: if the provider unwinds, it writes BlockHeader { status, flags: FLAG_DONE, id }, removes the block from ACTIVE, transitions phase to Phase::Consumed, and notifies s.cv so waiters in XAsyncGetStatus(b, true) wake up with status instead of sleeping indefinitely.
    • Added ConsumeCleanup in XAsyncGetResult around OP_GET_RESULT + OP_CLEANUP: if either unwinds, it writes BlockHeader { status, flags: FLAG_DONE | FLAG_CONSUMED, id }, removes the block from ACTIVE, and sets Phase::Consumed without re-entering guest OP_CLEANUP during unwind (subsequent XAsyncGetResult returns E_ILLEGAL_METHOD_CALL).
    • Also tightened BeginCleanup (only marks E_ABORT / removes if still Phase::Pending, leaving synchronously completed non-empty ops intact), tied begin_with_fixups Payload lifetime to Arc<State> on the XCL path (eliminating concurrent-worker unwind UAFs), and added regression tests covering these paths (13/13 unwind tests passing).
  2. waiter_fired / RegisterWaitForSingleObject:
    • Agreed — reverted waiter_fired back to plain unsafe extern "system" fn and removed the callback cast, since it is a Windows thread-pool callback that only enqueues onto a TaskQueue port without invoking guest code.
  3. Additional review cleanup:
    • Reverted hle/d3d12x/real.rs to stay orthogonal to active D3D12 PRs, guarded XTaskQueueTerminate across both PORT_WORK and PORT_COMPLETION, and noted in the PR description that unit tests verify Rust panic unwinding + cleanup while foreign C++/SEH unwinding from a title still needs native verification.

AI-assisted.

@JGonzalezRodriguez
JGonzalezRodriguez marked this pull request as ready for review November 23, 2026 20:58
JGonzalezRodriguez pushed a commit to JGonzalezRodriguez/xcl that referenced this pull request Nov 23, 2026
…gthen tests

Address adversarial review findings on PR xcl-dev#197:

- xasync: make BeginCleanup only remove Phase::Pending blocks (preserving
  synchronously completed payloads), guard XAsyncComplete OP_CLEANUP unwinds
  with CompleteCleanup (writes FLAG_DONE, removes ACTIVE, marks Consumed, wakes
  waiters), guard XAsyncGetResult OP_GET_RESULT/OP_CLEANUP unwinds with
  ConsumeCleanup (without re-entering guest OP_CLEANUP in Drop), guard
  XAsyncRun's XAsyncSchedule with BeginCleanup, and track Payload ownership via
  Arc<Payload> + AtomicBool + PayloadGuard to prevent both leaks and double-free.
- taskqueue: drain both PORT_WORK and PORT_COMPLETION into a single
  Remaining(VecDeque) and notify both ports' condvars before running any
  canceled callbacks in XTaskQueueTerminate (using O(1) pop_front).
- d3d12x/real: revert all 3 lines completely.
- kernelx test: separate throwing_title_alloc/throwing_title_free fallback
  returning null/no-op so concurrent D3D12 tests are undisturbed.
- gameinput test: assert CallbackGuard state directly + from a second thread,
  verify ReadingGuard released the Reading ref via extra AddRef, and guard
  unregister via RAII Drop declared after ctx.
- loader/eh tests: drop flaky global LOAD_LOCK.try_lock() check and serialize
  TITLE_FILTER mutation with a local test mutex.
- tests: add regression tests for BeginCleanup sync-completed payloads,
  Payload ownership on unwind, XAsyncComplete/XAsyncGetResult/XAsyncRun unwinds,
  and XTaskQueueTerminate PORT_WORK unwind draining/waking PORT_COMPLETION.
…ies (xcl-dev#106)

Switch guest callback function pointer types and re-entrant HLE entrypoints/
trampolines/hooks from plain `extern "system"` (nounwind in Rust 1.71+) to
`extern "system-unwind"` so guest C++ / SEH exceptions unwind cleanly through
XCL's Rust frames while running Drop guards instead of aborting via
`panic_cannot_unwind` or skipping cleanups:

- kernelx: XMemAllocFn/XMemFreeFn, XMemAlloc, XMemFree, LoadLibrary*,
  LoadPackagedLibrary, GetProcAddress
- d3d12x/real: dev_create_descriptor_heap_x, heap_release,
  dev_create_committed_resource_layout_x (transitive title allocation hooks)
- user: console_wndproc, CreateWindowExA/create_window_ex_w, and
  CallWindowProcW/SetWindowPos/CreateWindowExW imports
- loader & main: TlsCallback, DllMain, ExeEntry, main_thread, xcl_tls_callback
- eh: unhandled_filter and TITLE_FILTER invocation
- vfs_hooks: MoveFileWithProgressA/W, CopyFileExW, CopyFile2 hooks & orig types
- gameinput: ReadingCallback, DeviceCallback, register_device_callback, plus
  RAII ReadingGuard/EntryCleanup guards
- xaudio2: VoiceCallbackVtbl and decoded_cb_* trampolines
- xgameruntime: taskqueue callbacks/entrypoints (with InflightGuard,
  CancelInflight, RunningGuard, and Remaining guards), xasync provider/work/
  completion callbacks & entrypoints (with BeginCleanup and NotifyGuard),
  COM vtable SHIMS/FORWARDS/call_target, XErrorReport, XPackageEnumeratePackages,
  XGameSave enumerators/async entrypoints, XUser/XNetworking async entrypoints

Add 10 unit regression tests exercising unwinding and Drop-guard cleanup across
each boundary (verified on x86_64-pc-windows-msvc under Proton Experimental).
…gthen tests

Address adversarial review findings on PR xcl-dev#197:

- xasync: make BeginCleanup only remove Phase::Pending blocks (preserving
  synchronously completed payloads), guard XAsyncComplete OP_CLEANUP unwinds
  with CompleteCleanup (writes FLAG_DONE, removes ACTIVE, marks Consumed, wakes
  waiters), guard XAsyncGetResult OP_GET_RESULT/OP_CLEANUP unwinds with
  ConsumeCleanup (without re-entering guest OP_CLEANUP in Drop), guard
  XAsyncRun's XAsyncSchedule with BeginCleanup, and track Payload ownership via
  Arc<Payload> + AtomicBool + PayloadGuard to prevent both leaks and double-free.
- taskqueue: drain both PORT_WORK and PORT_COMPLETION into a single
  Remaining(VecDeque) and notify both ports' condvars before running any
  canceled callbacks in XTaskQueueTerminate (using O(1) pop_front).
- d3d12x/real: revert all 3 lines completely.
- kernelx test: separate throwing_title_alloc/throwing_title_free fallback
  returning null/no-op so concurrent D3D12 tests are undisturbed.
- gameinput test: assert CallbackGuard state directly + from a second thread,
  verify ReadingGuard released the Reading ref via extra AddRef, and guard
  unregister via RAII Drop declared after ctx.
- loader/eh tests: drop flaky global LOAD_LOCK.try_lock() check and serialize
  TITLE_FILTER mutation with a local test mutex.
- tests: add regression tests for BeginCleanup sync-completed payloads,
  Payload ownership on unwind, XAsyncComplete/XAsyncGetResult/XAsyncRun unwinds,
  and XTaskQueueTerminate PORT_WORK unwind draining/waking PORT_COMPLETION.
…plain extern "system"

- xasync: replace PayloadGuard with State::_owned_payload (Option<Arc<Payload>>)
  and Payload::owned_by_pc so XCL-managed payloads stay alive across concurrent
  workers/unwinds until every Arc<State> drops (clearing work/result buffers in
  OP_CLEANUP), while PC-runtime-delegated payloads (PC_ASYNC != 0) are only
  reclaimed on synchronous hr < 0 or OP_CLEANUP (eliminating both PC-runtime
  and concurrent-worker UAF paths).
- taskqueue: revert waiter_fired back to plain extern "system" and remove the
  RegisterWaitForSingleObject callback transmute (OS thread-pool callback).
@ersinhf

ersinhf commented Nov 23, 2026

Copy link
Copy Markdown

Native Windows scripts/test.ps1 on head a82fbfbef5e7363232040026237081907ea34a7a (the item under Not tested), clean tree. It merges onto current main 4017f8f without conflicts (git merge-tree).

Tested

  • NVIDIA GeForce RTX 4070 (Ada), driver 621.14 (32.0.16.2114); AMD Ryzen 5 7500F, 32 GB; Windows 11 build 26200; rustc 1.100.0 stable-x86_64-pc-windows-msvc, debug; DXC 1.9.2602.17 (SDK 10.0.26100.0); XGameRuntime 10.0.26100.9656; no XCL_SAMPLE_* set
  • .\scripts\test.ps1: 664 passed, 0 failed, 40 ignored (main 4017f8f with test.ps1 here: 652 / 0 / 40; this head is based on 60565c4); SKIPPED 2 (no wave64): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware
  • The new unwind tests all pass, among them unhandled_filter_unwinds_cleanly_from_title_filter, xmem_allocation_hooks_unwind_cleanly, init_dll_and_tls_callback_unwind_cleanly, the xasync / taskqueue / gameinput / xaudio2 / user ones
  • cargo test -p xcl --lib -- --test-threads=4 three more times on this head: 624 passed, 0 failed, 20 ignored each time

A hang that is not this PR's

My first test.ps1 run of this head stopped in the lib tests: four GPU tests (gpu_typed_buffer_loads_and_stores, gpu_uma_import_check_at_init, gpu_valu_16_and_64_bit, gpu_valu_float_and_int) ran past 60 s with the process at 0 % CPU and every thread waiting, and it had to be killed. Running the lib tests alternately on this head and on main 4017f8f (three times each), main hung the same way once (gpu_typed_buffer_loads_and_stores, gpu_uma_import_check_at_init, gpu_valu_16_and_64_bit, gpu_wave32_and_wave64_src_vccz_execz) and this head did not. So it is an intermittent hang already on main, not caused by this PR.

Not tested

  • Foreign C++ / SEH exceptions from a retail title, scripts/smoke.ps1 (no retail title here)
  • release build

AI use

  • Claude Code with Claude Opus 5.5 ran the builds and tests on this machine and wrote this comment; the person posting it checked each point.

@raylitebull

Copy link
Copy Markdown
Member

Closing as a stale, conflicting ~1,300-line PR failing the PR description check. Feel free to reopen smaller single-purpose PRs rebased on current main per CONTRIBUTING.md.

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.

5 participants