HLE: keep KernelWrite leases across pending overlapped and scatter reads #3229
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3231"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 withERROR_NOACCESS(998) unless opened ahead of time withvictory_gpu::kernel_will_write.On
main(63bcca4), three gaps remain on the Win32 file-read path incrates/victory-hle/src/modules/files.rs:ReadFileScatterandReadFileExare not wrapped at all: title imports fromapi-ms-win-core-file-*/kernel32.dll/kernelbase.dllgo 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 withERROR_NOACCESS.ReadFile(ERROR_IO_PENDING) drops itsKernelWritelease on return (noted on #723): as soon asReadFilereturns0withERROR_IO_PENDING,_writingdrops 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.LastErrorclobbering onKernelWritedrop:Writing::dropcallsVirtualProtectafter the hostReadFile/freadcall returns, which can overwriteGetLastError()(such asERROR_IO_PENDINGorERROR_HANDLE_EOF) before returning to title code.What this change does
Adds
crates/victory-hle/src/modules/files/reads.rsand wires the file, I/O, handle, and wait API-set exports infiles::module():ReadFile,ReadFileEx, andReadFileScatter:ReadFile(lpOverlapped == null) andfreadskip zero-length/null ranges and preserve threadLastErroracrossKernelWritedrop.ReadFileScatterwalks theFILE_SEGMENT_ELEMENTarray (sized byGetSystemInfo().dwPageSize, stopping early on the terminating null element) and coalesces adjacent/overlapping 64 KiB tracked page spans so multi-segment reads acquire minimalKernelWriteleases.ReadFile/ReadFileScatter(ERROR_IO_PENDING) and queuedReadFileExkeep theirKernelWriteleases inPENDING(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).AtomicUsizefast path when no overlappedKernelWriteis active; raw volatile reads ofOVERLAPPED::Internalavoid forming&Overlappedwhile the kernel owns the IRP):GetOverlappedResultandGetOverlappedResultEx: release leases onceOVERLAPPED::Internal != STATUS_PENDING(covering bothTRUEcompletions and terminal errors likeERROR_HANDLE_EOF/ERROR_OPERATION_ABORTED, while keepingERROR_IO_INCOMPLETE/WAIT_TIMEOUTleases open).GetQueuedCompletionStatusandGetQueuedCompletionStatusEx: release leases for dequeuedOVERLAPPEDpackets (including failed packets dequeued withok == 0and*lpOverlapped != null).ReadFileExcompletion routine trampoline: releases theKernelWritelease before invoking the title'sLPOVERLAPPED_COMPLETION_ROUTINE(and leavesOVERLAPPED::hEventuntouched for caller context, per Win32ReadFileExrules).WaitForSingleObject(Ex) andWaitForMultipleObjects(Ex): when a wait succeeds on the completion event (with low-order IOCP-skip bit(uintptr_t)hEvent & ~1stripped) or file handle, harvest completed entries (Internal != STATUS_PENDING) so callers that wait on the event without callingGetOverlappedResultnever leak busy pages.CancelIoandCancelIoEx: release only entries whose IRP has already leftSTATUS_PENDING, keeping leases alive while the storage driver finishes aborting in-flight DMA.OVERLAPPEDreuse andCloseHandle: reusing anOVERLAPPEDafterHasOverlappedIoCompletedpolling releases the prior lease after acquiring the new one;CloseHandleclears matchingwait_handleslots (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 realwatch::GuardsPAGE_READONLYpage protection through a placed shader-visible descriptor heap (GuardRig):io_handle_and_wait_api_sets_resolve_to_hle— verifiesapi-ms-win-core-file-*,api-ms-win-core-io-*,api-ms-win-core-handle-*, andapi-ms-win-core-synch-*bind to HLE.pending_overlapped_read_keeps_guarded_view_open_across_refresh— pending overlappedReadFile(ERROR_IO_PENDING), mid-flight GPU refresh (PAGE_READWRITEretained),GetOverlappedResult(..., 0)(ERROR_IO_INCOMPLETE),GetOverlappedResultExharvest, post-harvest refresh re-guarding toPAGE_READONLY, plus negative control showing raw hostReadFilefails withERROR_NOACCESS(998).read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait— unbuffered overlappedReadFileScatter(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 viaWaitForSingleObject, plus negative control showing raw hostReadFileScatterfails withERROR_NOACCESS(998).iocp_read_file_ex_cancellation_and_eof_preserve_semantics—GetQueuedCompletionStatus,GetQueuedCompletionStatusEx,ReadFileExalertable APC with non-handle user context inOVERLAPPED::hEvent,CancelIoEx+GetOverlappedResult, andERROR_HANDLE_EOFpreservation.multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases—WaitForMultipleObjects,HasOverlappedIoCompletedpolling +OVERLAPPEDreuse on a guarded view, andCloseHandlecleanup.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 failedcargo test -p victory-gpu --locked watch::: 15 passed, 0 failedcargo clippy --workspace --all-targets --locked -- -D warnings: cleancargo clippy --workspace --all-targets --all-features --locked -- -D warnings: cleancargo run -p xtask --locked -- policy: 192 files okNot tested: a retail title run. AI-assisted (Gemini).
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/scatterKernelWritelease tests pass).cargo clippy -p victory-hle --all-targets -- -D warnings: clean.cargo xtask policy: 192 files ok.Cleanly keeps
KernelWriteleases 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).
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 (unpatched63bcca4here: 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.Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-27T00:35:56Z.
Review: CHANGES_REQUESTED
Tested
9b79cde578ceed1372917425df9c409b1b57c423withcargo 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:Use-after-free /
0xC0000005crash dereferencing freedOVERLAPPEDpointers (crates/victory-hle/src/modules/files/reads.rs:546, 650, 283-288)HasOverlappedIoCompletedpolling (explicitly covered in the PR's tests) and then frees itsOVERLAPPEDmemory (VirtualFree,HeapFree, or stack return) without reusing the exact same address, thePendingentry remains inPENDINGholding a danglingp.overlapped.CancelIo(file)/CancelIoEx(file, NULL)(reads.rs:650) orWaitForSingleObject*/WaitForMultipleObjects*on the file handle or a shared event (reads.rs:546) callsunsafe { overlapped_done(p.overlapped) }on the freed pointer.VirtualAllocanOVERLAPPED->ReadFile(ERROR_IO_PENDING) -> write pipe -> polloverlapped_doneuntil complete ->VirtualFree(ov)->CancelIo(client)-> process immediately terminates with0xc0000005 (STATUS_ACCESS_VIOLATION).submit_overlapped(reads.rs:283-288):entry.wait_handleis still0andstartedisfalseuntil aftercall()returns, so another thread waiting onov.hEventcan wake on fast completion, skipharvest_waited_handles(which checksp.started && p.wait_handle != 0), and legally freeovbeforesubmit_overlappedexecutes(&raw const (*overlapped).internal).read_volatile()at line 285. Readingov.hEventbeforecall()and avoiding raw dereferences of caller-ownedOVERLAPPEDpointers that were not passed into the current API call (or validating viaVirtualQuery/ not assumingp.overlappedstays mapped once completed) is needed.Queued
ReadFileExAPC completion callback is silently dropped (or misrouted) onOVERLAPPEDreuse (crates/victory-hle/src/modules/files/reads.rs:245-246, 215)take_entry_writes(reads.rs:197-199) intentionally leavesReadFileExentries inPENDING(withwritesempty androutine: Some(cb)) afterGetOverlappedResult/CloseHandleso the pending kernel APC delivered toread_ex_donecan still invoke the title's completion routine.submit_overlapped(reads.rs:245-246) andrelease_stale_overlapped(reads.rs:215) unconditionally calllist.swap_remove(i)for anystartedentry matchingov_addr, even whenlist[i].routine.is_some().ReadFileEx(..., &ov, Some(cb1))-> write pipe ->GetOverlappedResult(client, &mut ov, &mut n, 1)(non-alertable, so the APC stays queued) -> reuse&ovinReadFile-> callSleepEx(50, 1)->cb1is never called (0invocations instead of1). If&ovis instead reused for a secondReadFileEx(..., &ov, Some(cb2)), the first APC matches the new entry inread_ex_done(reads.rs:312-319), invokingcb2withcb1's arguments and prematurely dropping the second in-flight read'sKernelWritelease. (Also noteReadFileExatreads.rs:372-374returns early whenwrites.is_empty()without callingrelease_stale_overlapped.)CloseHandledropsKernelWriteleases unconditionally while an IRP is stillSTATUS_PENDING(crates/victory-hle/src/modules/files/reads.rs:691-695)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.DuplicateHandle(client -> dup)->ReadFile(client)(ERROR_IO_PENDING) ->CloseHandle(client)->PENDING_COUNTdrops1 -> 0whileoverlapped_done(&ov)is stillfalse(irp_still_pending = true), prematurely releasing theKernelWritelease so a concurrent GPU refresh can re-guard the destination pagesPAGE_READONLYmid-transfer.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 base63bcca4).Tested
dxil.dllfrom Windows SDK 10.0.26100 (the loader's default), debug.cargo build --workspace --locked, thencargo 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.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.--skipleaves out tests that fail on main63bcca4on this card too, not because of this PR:heap_direct_texture_reads_mark_their_heap_indexends thevictory-shadertest process with0xc0000005(#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_viewsand the twostride_testshit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317);gathers_at_a_level_match_the_hardwarefails on lane 0 (#1744).Not tested
AI use
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.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.