HLE: keep KernelWrite leases across pending overlapped and scatter reads #3229

Open
kilvynsilveira-tech wants to merge 1 commit from upstream-pr/3231 into main
kilvynsilveira-tech commented 2026-11-26 13:53:27 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by kilvynsilveira-tech on 2026-11-26T13:53:27Z.


Refs #723
Coordination task: NEW-345 (#1633)

What's wrong

Tracked title GPU memory and physical-page views are marked PAGE_READONLY (watch::Guards) so CPU writes fault into the vectored handler. Kernel writes into read-only pages do not trigger user-mode exception handlers—they fail with ERROR_NOACCESS (998) unless opened ahead of time with victory_gpu::kernel_will_write.

On main (63bcca4), three gaps remain on the Win32 file-read path in crates/victory-hle/src/modules/files.rs:

  1. ReadFileScatter and ReadFileEx are not wrapped at all: title imports from api-ms-win-core-file-* / kernel32.dll / kernelbase.dll go straight to the host, so scatter/gather pack reads (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) or APC reads into guarded 64 KiB physical-page views fail with ERROR_NOACCESS.
  2. Pending overlapped ReadFile (ERROR_IO_PENDING) drops its KernelWrite lease on return (noted on #723): as soon as ReadFile returns 0 with ERROR_IO_PENDING, _writing drops before the driver's read lands. Any concurrent GPU refresh (Tracked::take) can re-guard the destination pages (PAGE_READONLY) mid-flight—failing the async read—or copy zeros before completion without seeing a dirty mark once the bytes arrive.
  3. LastError clobbering on KernelWrite drop: Writing::drop calls VirtualProtect after the host ReadFile / fread call returns, which can overwrite GetLastError() (such as ERROR_IO_PENDING or ERROR_HANDLE_EOF) before returning to title code.

What this change does

Adds crates/victory-hle/src/modules/files/reads.rs and wires the file, I/O, handle, and wait API-set exports in files::module():

  • ReadFile, ReadFileEx, and ReadFileScatter:
    • Synchronous ReadFile (lpOverlapped == null) and fread skip zero-length/null ranges and preserve thread LastError across KernelWrite drop.
    • ReadFileScatter walks the FILE_SEGMENT_ELEMENT array (sized by GetSystemInfo().dwPageSize, stopping early on the terminating null element) and coalesces adjacent/overlapping 64 KiB tracked page spans so multi-segment reads acquire minimal KernelWrite leases.
    • Overlapped ReadFile / ReadFileScatter (ERROR_IO_PENDING) and queued ReadFileEx keep their KernelWrite leases in PENDING (inserted with a unique monotonic ID before the host call so a fast IOCP worker waking on another core before the submitting thread returns still harvests cleanly).
  • Completion and cancellation harvesting (lock-free AtomicUsize fast path when no overlapped KernelWrite is active; raw volatile reads of OVERLAPPED::Internal avoid forming &Overlapped while the kernel owns the IRP):
    • GetOverlappedResult and GetOverlappedResultEx: release leases once OVERLAPPED::Internal != STATUS_PENDING (covering both TRUE completions and terminal errors like ERROR_HANDLE_EOF / ERROR_OPERATION_ABORTED, while keeping ERROR_IO_INCOMPLETE / WAIT_TIMEOUT leases open).
    • GetQueuedCompletionStatus and GetQueuedCompletionStatusEx: release leases for dequeued OVERLAPPED packets (including failed packets dequeued with ok == 0 and *lpOverlapped != null).
    • ReadFileEx completion routine trampoline: releases the KernelWrite lease before invoking the title's LPOVERLAPPED_COMPLETION_ROUTINE (and leaves OVERLAPPED::hEvent untouched for caller context, per Win32 ReadFileEx rules).
    • WaitForSingleObject(Ex) and WaitForMultipleObjects(Ex): when a wait succeeds on the completion event (with low-order IOCP-skip bit (uintptr_t)hEvent & ~1 stripped) or file handle, harvest completed entries (Internal != STATUS_PENDING) so callers that wait on the event without calling GetOverlappedResult never leak busy pages.
    • CancelIo and CancelIoEx: release only entries whose IRP has already left STATUS_PENDING, keeping leases alive while the storage driver finishes aborting in-flight DMA.
    • OVERLAPPED reuse and CloseHandle: reusing an OVERLAPPED after HasOverlappedIoCompleted polling releases the prior lease after acquiring the new one; CloseHandle clears matching wait_handle slots (preventing recycled-handle collisions) and releases remaining leases on closed file handles.

Tests

Synthetic Windows tests in modules::files::reads::tests (no game files used), driving real watch::Guards PAGE_READONLY page protection through a placed shader-visible descriptor heap (GuardRig):

  1. io_handle_and_wait_api_sets_resolve_to_hle — verifies api-ms-win-core-file-*, api-ms-win-core-io-*, api-ms-win-core-handle-*, and api-ms-win-core-synch-* bind to HLE.
  2. pending_overlapped_read_keeps_guarded_view_open_across_refresh — pending overlapped ReadFile (ERROR_IO_PENDING), mid-flight GPU refresh (PAGE_READWRITE retained), GetOverlappedResult(..., 0) (ERROR_IO_INCOMPLETE), GetOverlappedResultEx harvest, post-harvest refresh re-guarding to PAGE_READONLY, plus negative control showing raw host ReadFile fails with ERROR_NOACCESS (998).
  3. read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait — unbuffered overlapped ReadFileScatter (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) across scattered 4 KiB segments in two guarded views with a low-bit-tagged event (hEvent | 1) harvested via WaitForSingleObject, plus negative control showing raw host ReadFileScatter fails with ERROR_NOACCESS (998).
  4. iocp_read_file_ex_cancellation_and_eof_preserve_semantics — GetQueuedCompletionStatus, GetQueuedCompletionStatusEx, ReadFileEx alertable APC with non-handle user context in OVERLAPPED::hEvent, CancelIoEx + GetOverlappedResult, and ERROR_HANDLE_EOF preservation.
  5. multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases — WaitForMultipleObjects, HasOverlappedIoCompleted polling + OVERLAPPED reuse on a guarded view, and CloseHandle cleanup.

Verified on Windows 10 x64 (19045), Ryzen 7 5700X, Radeon RX 580 2048SP:

  • cargo test -p victory-hle --locked (single-threaded and parallel): 159 passed, 0 failed
  • cargo test -p victory-gpu --locked watch::: 15 passed, 0 failed
  • cargo clippy --workspace --all-targets --locked -- -D warnings: clean
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean
  • cargo run -p xtask --locked -- policy: 192 files ok

Not tested: a retail title run. AI-assisted (Gemini).

<!-- greyfinch-sync:Marvisak/VIctory:issue:5511284529 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3231). Originally posted by [kilvynsilveira-tech](https://github.com/kilvynsilveira-tech) on 2026-11-26T13:53:27Z. --- Refs #723 Coordination task: `NEW-345` (#1633) ## What's wrong Tracked title GPU memory and physical-page views are marked `PAGE_READONLY` (`watch::Guards`) so CPU writes fault into the vectored handler. Kernel writes into read-only pages do not trigger user-mode exception handlers—they fail with `ERROR_NOACCESS` (`998`) unless opened ahead of time with `victory_gpu::kernel_will_write`. On `main` (`63bcca4`), three gaps remain on the Win32 file-read path in `crates/victory-hle/src/modules/files.rs`: 1. **`ReadFileScatter` and `ReadFileEx` are not wrapped at all**: title imports from `api-ms-win-core-file-*` / `kernel32.dll` / `kernelbase.dll` go straight to the host, so scatter/gather pack reads (`FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING`) or APC reads into guarded 64 KiB physical-page views fail with `ERROR_NOACCESS`. 2. **Pending overlapped `ReadFile` (`ERROR_IO_PENDING`) drops its `KernelWrite` lease on return** (noted on #723): as soon as `ReadFile` returns `0` with `ERROR_IO_PENDING`, `_writing` drops before the driver's read lands. Any concurrent GPU refresh (`Tracked::take`) can re-guard the destination pages (`PAGE_READONLY`) mid-flight—failing the async read—or copy zeros before completion without seeing a dirty mark once the bytes arrive. 3. **`LastError` clobbering on `KernelWrite` drop**: `Writing::drop` calls `VirtualProtect` after the host `ReadFile` / `fread` call returns, which can overwrite `GetLastError()` (such as `ERROR_IO_PENDING` or `ERROR_HANDLE_EOF`) before returning to title code. ## What this change does Adds `crates/victory-hle/src/modules/files/reads.rs` and wires the file, I/O, handle, and wait API-set exports in `files::module()`: - **`ReadFile`, `ReadFileEx`, and `ReadFileScatter`**: - Synchronous `ReadFile` (`lpOverlapped == null`) and `fread` skip zero-length/null ranges and preserve thread `LastError` across `KernelWrite` drop. - `ReadFileScatter` walks the `FILE_SEGMENT_ELEMENT` array (sized by `GetSystemInfo().dwPageSize`, stopping early on the terminating null element) and coalesces adjacent/overlapping 64 KiB tracked page spans so multi-segment reads acquire minimal `KernelWrite` leases. - Overlapped `ReadFile` / `ReadFileScatter` (`ERROR_IO_PENDING`) and queued `ReadFileEx` keep their `KernelWrite` leases in `PENDING` (inserted with a unique monotonic ID *before* the host call so a fast IOCP worker waking on another core before the submitting thread returns still harvests cleanly). - **Completion and cancellation harvesting** (lock-free `AtomicUsize` fast path when no overlapped `KernelWrite` is active; raw volatile reads of `OVERLAPPED::Internal` avoid forming `&Overlapped` while the kernel owns the IRP): - `GetOverlappedResult` and `GetOverlappedResultEx`: release leases once `OVERLAPPED::Internal != STATUS_PENDING` (covering both `TRUE` completions and terminal errors like `ERROR_HANDLE_EOF` / `ERROR_OPERATION_ABORTED`, while keeping `ERROR_IO_INCOMPLETE` / `WAIT_TIMEOUT` leases open). - `GetQueuedCompletionStatus` and `GetQueuedCompletionStatusEx`: release leases for dequeued `OVERLAPPED` packets (including failed packets dequeued with `ok == 0` and `*lpOverlapped != null`). - `ReadFileEx` completion routine trampoline: releases the `KernelWrite` lease *before* invoking the title's `LPOVERLAPPED_COMPLETION_ROUTINE` (and leaves `OVERLAPPED::hEvent` untouched for caller context, per Win32 `ReadFileEx` rules). - `WaitForSingleObject`(`Ex`) and `WaitForMultipleObjects`(`Ex`): when a wait succeeds on the completion event (with low-order IOCP-skip bit `(uintptr_t)hEvent & ~1` stripped) or file handle, harvest completed entries (`Internal != STATUS_PENDING`) so callers that wait on the event without calling `GetOverlappedResult` never leak busy pages. - `CancelIo` and `CancelIoEx`: release only entries whose IRP has already left `STATUS_PENDING`, keeping leases alive while the storage driver finishes aborting in-flight DMA. - `OVERLAPPED` reuse and `CloseHandle`: reusing an `OVERLAPPED` after `HasOverlappedIoCompleted` polling releases the prior lease after acquiring the new one; `CloseHandle` clears matching `wait_handle` slots (preventing recycled-handle collisions) and releases remaining leases on closed file handles. ## Tests Synthetic Windows tests in `modules::files::reads::tests` (no game files used), driving real `watch::Guards` `PAGE_READONLY` page protection through a placed shader-visible descriptor heap (`GuardRig`): 1. `io_handle_and_wait_api_sets_resolve_to_hle` — verifies `api-ms-win-core-file-*`, `api-ms-win-core-io-*`, `api-ms-win-core-handle-*`, and `api-ms-win-core-synch-*` bind to HLE. 2. `pending_overlapped_read_keeps_guarded_view_open_across_refresh` — pending overlapped `ReadFile` (`ERROR_IO_PENDING`), mid-flight GPU refresh (`PAGE_READWRITE` retained), `GetOverlappedResult(..., 0)` (`ERROR_IO_INCOMPLETE`), `GetOverlappedResultEx` harvest, post-harvest refresh re-guarding to `PAGE_READONLY`, plus negative control showing raw host `ReadFile` fails with `ERROR_NOACCESS` (`998`). 3. `read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait` — unbuffered overlapped `ReadFileScatter` (`FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING`) across scattered 4 KiB segments in two guarded views with a low-bit-tagged event (`hEvent | 1`) harvested via `WaitForSingleObject`, plus negative control showing raw host `ReadFileScatter` fails with `ERROR_NOACCESS` (`998`). 4. `iocp_read_file_ex_cancellation_and_eof_preserve_semantics` — `GetQueuedCompletionStatus`, `GetQueuedCompletionStatusEx`, `ReadFileEx` alertable APC with non-handle user context in `OVERLAPPED::hEvent`, `CancelIoEx` + `GetOverlappedResult`, and `ERROR_HANDLE_EOF` preservation. 5. `multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases` — `WaitForMultipleObjects`, `HasOverlappedIoCompleted` polling + `OVERLAPPED` reuse on a guarded view, and `CloseHandle` cleanup. Verified on Windows 10 x64 (19045), Ryzen 7 5700X, Radeon RX 580 2048SP: - `cargo test -p victory-hle --locked` (single-threaded and parallel): 159 passed, 0 failed - `cargo test -p victory-gpu --locked watch::`: 15 passed, 0 failed - `cargo clippy --workspace --all-targets --locked -- -D warnings`: clean - `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`: clean - `cargo run -p xtask --locked -- policy`: 192 files ok Not tested: a retail title run. AI-assisted (Gemini).
Dukestar69 commented 2026-11-26 14:11:18 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T14:11:18Z.

Review: APPROVED


Verified against origin/main (63bcca4):

  • cargo test -p victory-hle --lib modules::files:: -- --test-threads=1: 11/11 passed (all 5 new overlapped/scatter KernelWrite lease tests pass).
  • cargo clippy -p victory-hle --all-targets -- -D warnings: clean.
  • cargo xtask policy: 192 files ok.

Cleanly keeps KernelWrite leases alive across pending overlapped and scatter reads and harvests them on completion/cancellation/close.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

<!-- greyfinch-sync:Marvisak/VIctory:review:6075566770 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3231#pullrequestreview-6075566770). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T14:11:18Z. **Review:** APPROVED --- Verified against `origin/main` (`63bcca4`): - `cargo test -p victory-hle --lib modules::files:: -- --test-threads=1`: 11/11 passed (all 5 new overlapped/scatter `KernelWrite` lease tests pass). - `cargo clippy -p victory-hle --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 192 files ok. Cleanly keeps `KernelWrite` leases alive across pending overlapped and scatter reads and harvests them on completion/cancellation/close. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Jackster commented 2026-11-26 22:52:31 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T22:52:31Z.


Windows 11, 63bcca4 + this PR:

  • cargo test -p victory-hle: lib 157 passed / 0 failed (unpatched 63bcca4 here: 152 passed; +5), plus the integration suite (1 passed).
  • cargo clippy -p victory-hle --all-targets -- -D warnings: clean.

The five new tests are the KernelWrite/overlapped ones: io_handle_and_wait_api_sets_resolve_to_hle, pending_overlapped_read_keeps_guarded_view_open_across_refresh, read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait, iocp_read_file_ex_cancellation_and_eof_preserve_semantics, multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases. They run against the real Windows handle/wait APIs on this machine. Synthetic only. AI-assisted.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7205059419 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3231#issuecomment-7205059419). Originally posted by [Jackster](https://github.com/Jackster) on 2026-11-26T22:52:31Z. --- Windows 11, `63bcca4` + this PR: - `cargo test -p victory-hle`: lib **157 passed / 0 failed** (unpatched `63bcca4` here: 152 passed; +5), plus the integration suite (1 passed). - `cargo clippy -p victory-hle --all-targets -- -D warnings`: clean. The five new tests are the `KernelWrite`/overlapped ones: `io_handle_and_wait_api_sets_resolve_to_hle`, `pending_overlapped_read_keeps_guarded_view_open_across_refresh`, `read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait`, `iocp_read_file_ex_cancellation_and_eof_preserve_semantics`, `multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases`. They run against the real Windows handle/wait APIs on this machine. Synthetic only. AI-assisted.
fuzeofficlal commented 2026-11-27 00:35:56 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-27T00:35:56Z.

Review: CHANGES_REQUESTED


Tested 9b79cde578ceed1372917425df9c409b1b57c423 with cargo xtask policy, cargo clippy --tests -p victory-hle -- -D warnings, cargo test --locked -p victory-hle (159/159 pass), and live Win32 overlapped I/O adversarial probes on Windows 11.

The overall tracking structure and test coverage are thorough, and there are no export conflicts with other HLE modules. However, live Win32 testing reproduced three memory-safety / lease-lifetime bugs in crates/victory-hle/src/modules/files/reads.rs:

  1. Use-after-free / 0xC0000005 crash dereferencing freed OVERLAPPED pointers (crates/victory-hle/src/modules/files/reads.rs:546, 650, 283-288)

    • When a caller completes an overlapped read via HasOverlappedIoCompleted polling (explicitly covered in the PR's tests) and then frees its OVERLAPPED memory (VirtualFree, HeapFree, or stack return) without reusing the exact same address, the Pending entry remains in PENDING holding a dangling p.overlapped.
    • Any later CancelIo(file) / CancelIoEx(file, NULL) (reads.rs:650) or WaitForSingleObject* / WaitForMultipleObjects* on the file handle or a shared event (reads.rs:546) calls unsafe { overlapped_done(p.overlapped) } on the freed pointer.
    • Live reproduction: VirtualAlloc an OVERLAPPED -> ReadFile (ERROR_IO_PENDING) -> write pipe -> poll overlapped_done until complete -> VirtualFree(ov) -> CancelIo(client) -> process immediately terminates with 0xc0000005 (STATUS_ACCESS_VIOLATION).
    • A related UAF race exists in submit_overlapped (reads.rs:283-288): entry.wait_handle is still 0 and started is false until after call() returns, so another thread waiting on ov.hEvent can wake on fast completion, skip harvest_waited_handles (which checks p.started && p.wait_handle != 0), and legally free ov before submit_overlapped executes (&raw const (*overlapped).internal).read_volatile() at line 285. Reading ov.hEvent before call() and avoiding raw dereferences of caller-owned OVERLAPPED pointers that were not passed into the current API call (or validating via VirtualQuery / not assuming p.overlapped stays mapped once completed) is needed.
  2. Queued ReadFileEx APC completion callback is silently dropped (or misrouted) on OVERLAPPED reuse (crates/victory-hle/src/modules/files/reads.rs:245-246, 215)

    • take_entry_writes (reads.rs:197-199) intentionally leaves ReadFileEx entries in PENDING (with writes empty and routine: Some(cb)) after GetOverlappedResult / CloseHandle so the pending kernel APC delivered to read_ex_done can still invoke the title's completion routine.
    • However, submit_overlapped (reads.rs:245-246) and release_stale_overlapped (reads.rs:215) unconditionally call list.swap_remove(i) for any started entry matching ov_addr, even when list[i].routine.is_some().
    • Live reproduction: issue ReadFileEx(..., &ov, Some(cb1)) -> write pipe -> GetOverlappedResult(client, &mut ov, &mut n, 1) (non-alertable, so the APC stays queued) -> reuse &ov in ReadFile -> call SleepEx(50, 1) -> cb1 is never called (0 invocations instead of 1). If &ov is instead reused for a second ReadFileEx(..., &ov, Some(cb2)), the first APC matches the new entry in read_ex_done (reads.rs:312-319), invoking cb2 with cb1's arguments and prematurely dropping the second in-flight read's KernelWrite lease. (Also note ReadFileEx at reads.rs:372-374 returns early when writes.is_empty() without calling release_stale_overlapped.)
  3. CloseHandle drops KernelWrite leases unconditionally while an IRP is still STATUS_PENDING (crates/victory-hle/src/modules/files/reads.rs:691-695)

    • When a file handle has been duplicated (DuplicateHandle), closing one handle does not cancel pending I/O on the underlying file object; the kernel can still DMA into the destination pages afterward.
    • Live reproduction: DuplicateHandle(client -> dup) -> ReadFile(client) (ERROR_IO_PENDING) -> CloseHandle(client) -> PENDING_COUNT drops 1 -> 0 while overlapped_done(&ov) is still false (irp_still_pending = true), prematurely releasing the KernelWrite lease so a concurrent GPU refresh can re-guard the destination pages PAGE_READONLY mid-transfer.
<!-- greyfinch-sync:Marvisak/VIctory:review:6081999101 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3231#pullrequestreview-6081999101). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-27T00:35:56Z. **Review:** CHANGES_REQUESTED --- Tested `9b79cde578ceed1372917425df9c409b1b57c423` with `cargo xtask policy`, `cargo clippy --tests -p victory-hle -- -D warnings`, `cargo test --locked -p victory-hle` (159/159 pass), and live Win32 overlapped I/O adversarial probes on Windows 11. The overall tracking structure and test coverage are thorough, and there are no export conflicts with other HLE modules. However, live Win32 testing reproduced three memory-safety / lease-lifetime bugs in `crates/victory-hle/src/modules/files/reads.rs`: 1. **Use-after-free / `0xC0000005` crash dereferencing freed `OVERLAPPED` pointers (`crates/victory-hle/src/modules/files/reads.rs:546, 650, 283-288`)** - When a caller completes an overlapped read via `HasOverlappedIoCompleted` polling (explicitly covered in the PR's tests) and then frees its `OVERLAPPED` memory (`VirtualFree`, `HeapFree`, or stack return) without reusing the exact same address, the `Pending` entry remains in `PENDING` holding a dangling `p.overlapped`. - Any later `CancelIo(file)` / `CancelIoEx(file, NULL)` (`reads.rs:650`) or `WaitForSingleObject*` / `WaitForMultipleObjects*` on the file handle or a shared event (`reads.rs:546`) calls `unsafe { overlapped_done(p.overlapped) }` on the freed pointer. - **Live reproduction**: `VirtualAlloc` an `OVERLAPPED` -> `ReadFile` (`ERROR_IO_PENDING`) -> write pipe -> poll `overlapped_done` until complete -> `VirtualFree(ov)` -> `CancelIo(client)` -> process immediately terminates with **`0xc0000005 (STATUS_ACCESS_VIOLATION)`**. - A related UAF race exists in `submit_overlapped` (`reads.rs:283-288`): `entry.wait_handle` is still `0` and `started` is `false` until after `call()` returns, so another thread waiting on `ov.hEvent` can wake on fast completion, skip `harvest_waited_handles` (which checks `p.started && p.wait_handle != 0`), and legally free `ov` before `submit_overlapped` executes `(&raw const (*overlapped).internal).read_volatile()` at line 285. Reading `ov.hEvent` before `call()` and avoiding raw dereferences of caller-owned `OVERLAPPED` pointers that were not passed into the current API call (or validating via `VirtualQuery` / not assuming `p.overlapped` stays mapped once completed) is needed. 2. **Queued `ReadFileEx` APC completion callback is silently dropped (or misrouted) on `OVERLAPPED` reuse (`crates/victory-hle/src/modules/files/reads.rs:245-246, 215`)** - `take_entry_writes` (`reads.rs:197-199`) intentionally leaves `ReadFileEx` entries in `PENDING` (with `writes` empty and `routine: Some(cb)`) after `GetOverlappedResult` / `CloseHandle` so the pending kernel APC delivered to `read_ex_done` can still invoke the title's completion routine. - However, `submit_overlapped` (`reads.rs:245-246`) and `release_stale_overlapped` (`reads.rs:215`) unconditionally call `list.swap_remove(i)` for any `started` entry matching `ov_addr`, even when `list[i].routine.is_some()`. - **Live reproduction**: issue `ReadFileEx(..., &ov, Some(cb1))` -> write pipe -> `GetOverlappedResult(client, &mut ov, &mut n, 1)` (non-alertable, so the APC stays queued) -> reuse `&ov` in `ReadFile` -> call `SleepEx(50, 1)` -> **`cb1` is never called (`0` invocations instead of `1`)**. If `&ov` is instead reused for a second `ReadFileEx(..., &ov, Some(cb2))`, the first APC matches the new entry in `read_ex_done` (`reads.rs:312-319`), invoking `cb2` with `cb1`'s arguments and prematurely dropping the second in-flight read's `KernelWrite` lease. (Also note `ReadFileEx` at `reads.rs:372-374` returns early when `writes.is_empty()` without calling `release_stale_overlapped`.) 3. **`CloseHandle` drops `KernelWrite` leases unconditionally while an IRP is still `STATUS_PENDING` (`crates/victory-hle/src/modules/files/reads.rs:691-695`)** - When a file handle has been duplicated (`DuplicateHandle`), closing one handle does not cancel pending I/O on the underlying file object; the kernel can still DMA into the destination pages afterward. - **Live reproduction**: `DuplicateHandle(client -> dup)` -> `ReadFile(client)` (`ERROR_IO_PENDING`) -> `CloseHandle(client)` -> `PENDING_COUNT` drops `1 -> 0` while `overlapped_done(&ov)` is still `false` (`irp_still_pending = true`), prematurely releasing the `KernelWrite` lease so a concurrent GPU refresh can re-guard the destination pages `PAGE_READONLY` mid-transfer.
futurepro62 commented 2026-11-27 22:59:53 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by futurepro62 on 2026-11-27T22:59:53Z.


NVIDIA full-suite run, to go with the reports above by Dukestar69, Jackster, since none of them names a GPU run. Tested exact head 9b79cde (on its base 63bcca4).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.98.1 MSVC (pinned), dxil.dll from Windows SDK 10.0.26100 (the loader's default), debug.
  • cargo build --workspace --locked, then cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --skip emit::memory_tests::heap_direct_texture_reads_mark_their_heap_index --skip descriptor::host::tests::dynamic_slots_are_held_until_released --skip memory::tests::lists_share_a_table_and_copies_keep_their_views --skip emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride --skip emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros --skip emit::synthetic_tests::gathers_at_a_level_match_the_hardware: 871 passed, 0 failed, 10 ignored.
  • The new tests ran and passed: io_handle_and_wait_api_sets_resolve_to_hle, pending_overlapped_read_keeps_guarded_view_open_across_refresh, read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait, iocp_read_file_ex_cancellation_and_eof_preserve_semantics, multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases.
  • --skip leaves out tests that fail on main 63bcca4 on this card too, not because of this PR: heap_direct_texture_reads_mark_their_heap_index ends the victory-shader test process with 0xc0000005 (#2571), so without the skip the rest of that crate never reports; dynamic_slots_are_held_until_released, lists_share_a_table_and_copies_keep_their_views and the two stride_tests hit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317); gathers_at_a_level_match_the_hardware fails on lane 0 (#1744).

Not tested

  • AMD (the tests take the default adapter), a release build, the title (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
<!-- greyfinch-sync:Marvisak/VIctory:comment:7229787144 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3231#issuecomment-7229787144). Originally posted by [futurepro62](https://github.com/futurepro62) on 2026-11-27T22:59:53Z. --- NVIDIA full-suite run, to go with the reports above by Dukestar69, Jackster, since none of them names a GPU run. Tested exact head `9b79cde` (on its base `63bcca4`). **Tested** - NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.98.1 MSVC (pinned), `dxil.dll` from Windows SDK 10.0.26100 (the loader's default), debug. - `cargo build --workspace --locked`, then `cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --skip emit::memory_tests::heap_direct_texture_reads_mark_their_heap_index --skip descriptor::host::tests::dynamic_slots_are_held_until_released --skip memory::tests::lists_share_a_table_and_copies_keep_their_views --skip emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride --skip emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros --skip emit::synthetic_tests::gathers_at_a_level_match_the_hardware`: **871 passed, 0 failed, 10 ignored**. - The new tests ran and passed: `io_handle_and_wait_api_sets_resolve_to_hle`, `pending_overlapped_read_keeps_guarded_view_open_across_refresh`, `read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait`, `iocp_read_file_ex_cancellation_and_eof_preserve_semantics`, `multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases`. - `--skip` leaves out tests that fail on main `63bcca4` on this card too, not because of this PR: `heap_direct_texture_reads_mark_their_heap_index` ends the `victory-shader` test process with `0xc0000005` (#2571), so without the skip the rest of that crate never reports; `dynamic_slots_are_held_until_released`, `lists_share_a_table_and_copies_keep_their_views` and the two `stride_tests` hit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317); `gathers_at_a_level_match_the_hardware` fails on lane 0 (#1744). **Not tested** - AMD (the tests take the default adapter), a release build, the title (test run only). **AI use** - Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3231:upstream-pr/3231'
git switch 'upstream-pr/3231'

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.

git switch 'main'
git merge --no-ff 'upstream-pr/3231'
git switch 'upstream-pr/3231'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3231'
git switch 'upstream-pr/3231'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3231'
git switch 'main'
git merge --squash 'upstream-pr/3231'
git switch 'main'
git merge --ff-only 'upstream-pr/3231'
git switch 'main'
git merge 'upstream-pr/3231'
git push origin 'main'
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
Marvisak/VIctory!3229
No description provided.