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

Closed
JGonzalezRodriguez wants to merge 3 commits from upstream-pr/197 into main
JGonzalezRodriguez commented 2026-11-23 20:20:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by JGonzalezRodriguez on 2026-11-23T20:20:52Z.


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.
<!-- greyfinch-sync:ivall/xcl:issue:6568047340 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/197). Originally posted by [JGonzalezRodriguez](https://github.com/JGonzalezRodriguez) on 2026-11-23T20:20:52Z. --- 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.
Kalmarv commented 2026-11-24 07:04:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-11-23T20:38:21Z.


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

<!-- greyfinch-sync:ivall/xcl:comment:7113346740 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/197#issuecomment-7113346740). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-11-23T20:38:21Z. --- 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](https://doc.rust-lang.org/nomicon/ffi.html#ffi-and-unwinding)
JGonzalezRodriguez commented 2026-11-24 07:04:19 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by JGonzalezRodriguez on 2026-11-23T20:58:29Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7113822231 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/197#issuecomment-7113822231). Originally posted by [JGonzalezRodriguez](https://github.com/JGonzalezRodriguez) on 2026-11-23T20:58:29Z. --- 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.
ersinhf commented 2026-11-24 07:04:41 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by ersinhf on 2026-11-23T23:27:16Z.


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.
<!-- greyfinch-sync:ivall/xcl:comment:7116972809 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/197#issuecomment-7116972809). Originally posted by [ersinhf](https://github.com/ersinhf) on 2026-11-23T23:27:16Z. --- 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.
upstream-sync closed this pull request 2026-11-24 11:04:37 +00:00
raylitebull commented 2026-11-24 11:05:56 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by raylitebull on 2026-11-24T10:43:31Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7129160787 --> Imported from [ivall/xcl](https://github.com/ivall/xcl/pull/197#issuecomment-7129160787). Originally posted by [raylitebull](https://github.com/raylitebull) on 2026-11-24T10:43:31Z. --- 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`.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!194
No description provided.