fix(libkernel): serialize Windows ftruncate with file transfers #6302

Merged
Ondra97 merged 2 commits from upstream-pr/6302 into main 2026-10-18 22:16:07 +00:00
Ondra97 commented 2026-10-15 10:22:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Ondra97 on 2026-10-15T10:22:36Z.


What

Concurrent positioned reads and ftruncate can permanently overwrite existing file data on Windows. The resize path calls _chsize_s outside the position lock used by the read's save/transfer/restore sequence, although both operate on the same native file pointer. In the new regression, every resize requests either 8 MiB or 8 MiB + 4096, yet an independent host read after both descriptors are closed finds 8,355,051 changed bytes inside the protected original 8 MiB.

Hold the existing File::LockPositionedTransfer while resizing an ordinary Windows file. The lock is already shared across duplicated descriptors and used by positioned transfers, scalar transfers and seeks. The shared-memory resize path returns before this lock is acquired, preserving its existing locking order.

guest_truncate_race exercises kernel APIs on one descriptor and POSIX APIs through a dup alias. Each case performs four rounds, with 32 full-prefix reads and 256 alternating resizes per round. It checks transfer results, read contents, both aliases' cursor, the following ordinary read, final file size and the persisted prefix through std::ifstream after close. Descriptor lifetime stays outside the race. The test has a 20-second timeout.

Tested

I tested on Windows 11 Pro 10.0.26300, WinLibs MinGW-w64 GCC 15.2.0 r7, Release/Ninja, with BUILD_TESTING=ON, outside the sandbox.

Hardware: AMD Ryzen 9 7900X, 32 GB RAM, NVIDIA GeForce RTX 4070 Ti SUPER.

The following are my captured runs of the same registered regression against main a08de6827f217115078660b9f47201edae59668b and this fix. I subsequently rebased onto main e49ec591dc93c9e4dfaad8b6dbc0b995dd7830a0; all libkernel/libc and regression Git blobs are identical to the measured fixed tree. Final head: b062366e5022798c256ae02377588e5b82807557.

Each cell lists kernel/direct; POSIX/dup. Both runs attempt 128 reads and 1,024 resizes per case. These are correctness observations, not performance measurements.

Measurement Main This change
Incorrect persisted prefix bytes 8,355,051; 8,355,051 0; 0
Reads with an incorrect returned count 116; 31 0; 0
Full-count reads with incorrect contents 12; 64 0; 0
Failed cursor checks, out of 4 1; 3 0; 0
Incorrect following ordinary reads, out of 4 4; 4 0; 0
Resize calls returning an error 0; 0 0; 0
  • The new regression fails against main's production code and passes with the one-line production fix. Its captured passing run took 0.30 seconds, with a 20-second timeout.
  • Full default Windows build passed on the final rebased head, including patched libraries.
  • 32 related filesystem, positioned I/O, descriptor, stream, AIO and shared-memory CTest cases passed on the final head, with no CTest skips (0.66 seconds total).
  • The new regression passed 50 additional consecutive executions, 0.28-0.40 seconds each. Every run exercised both the direct descriptor and the duplicate.
  • Test registration passed on the final head: 880 test executables, none built without a recorded CTest invocation. Conventions and whitespace checks passed.

I checked the complete file inventories of 576 open PRs on the final refresh, including pinned-head diffs for all 29 sharing Stdio.cpp. The 19 older AOT diffs are identical in this file and change other platform paths. I compared the implementations, tests and discussions of #5980 (invalid descriptors), #5938 (close lifetime), #5833 (whole-vector serialization), #5831 (kernel append), #6287 (stream append), #6228 (directory identity) and #6234 (GPU write coherence). None adds ordinary-file resize serialization. #5835's archive rejection is in the public wrapper and does not implement this fix.

The official overlap check flags one adjacent insertion with my #6228. This change inserts the position lock after the shared-memory return, while #6228 inserts the directory-descriptor rejection there. Both lines must remain when the second PR is rebased: keep the position lock before native handle access and retain the directory check. The fixes are independent; neither needs the other to function. The checker reports no other overlap.

Limits: the existing guest_kernel_sys symbolic-link success branches reported that links were unavailable and were not covered. No retail title, Linux runtime, console or GPU execution was tested for this change. Full hosted Windows/Linux builds require collaborator dispatch under CONTRIBUTING.md; skipped jobs are not validation passes.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source; none added
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes - Codex. I am responsible for the change.
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4871753382 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6302). Originally posted by [Ondra97](https://github.com/Ondra97) on 2026-10-15T10:22:36Z. --- ### What Concurrent positioned reads and `ftruncate` can permanently overwrite existing file data on Windows. The resize path calls `_chsize_s` outside the position lock used by the read's save/transfer/restore sequence, although both operate on the same native file pointer. In the new regression, every resize requests either 8 MiB or 8 MiB + 4096, yet an independent host read after both descriptors are closed finds 8,355,051 changed bytes inside the protected original 8 MiB. Hold the existing `File::LockPositionedTransfer` while resizing an ordinary Windows file. The lock is already shared across duplicated descriptors and used by positioned transfers, scalar transfers and seeks. The shared-memory resize path returns before this lock is acquired, preserving its existing locking order. `guest_truncate_race` exercises kernel APIs on one descriptor and POSIX APIs through a `dup` alias. Each case performs four rounds, with 32 full-prefix reads and 256 alternating resizes per round. It checks transfer results, read contents, both aliases' cursor, the following ordinary read, final file size and the persisted prefix through `std::ifstream` after close. Descriptor lifetime stays outside the race. The test has a 20-second timeout. ### Tested I tested on Windows 11 Pro 10.0.26300, WinLibs MinGW-w64 GCC 15.2.0 r7, Release/Ninja, with `BUILD_TESTING=ON`, outside the sandbox. Hardware: AMD Ryzen 9 7900X, 32 GB RAM, NVIDIA GeForce RTX 4070 Ti SUPER. The following are my captured runs of the same registered regression against main `a08de6827f217115078660b9f47201edae59668b` and this fix. I subsequently rebased onto main `e49ec591dc93c9e4dfaad8b6dbc0b995dd7830a0`; all libkernel/libc and regression Git blobs are identical to the measured fixed tree. Final head: `b062366e5022798c256ae02377588e5b82807557`. Each cell lists **kernel/direct; POSIX/dup**. Both runs attempt 128 reads and 1,024 resizes per case. These are correctness observations, not performance measurements. | Measurement | Main | This change | |---|---:|---:| | Incorrect persisted prefix bytes | 8,355,051; 8,355,051 | 0; 0 | | Reads with an incorrect returned count | 116; 31 | 0; 0 | | Full-count reads with incorrect contents | 12; 64 | 0; 0 | | Failed cursor checks, out of 4 | 1; 3 | 0; 0 | | Incorrect following ordinary reads, out of 4 | 4; 4 | 0; 0 | | Resize calls returning an error | 0; 0 | 0; 0 | - The new regression fails against main's production code and passes with the one-line production fix. Its captured passing run took 0.30 seconds, with a 20-second timeout. - Full default Windows build passed on the final rebased head, including patched libraries. - 32 related filesystem, positioned I/O, descriptor, stream, AIO and shared-memory CTest cases passed on the final head, with no CTest skips (0.66 seconds total). - The new regression passed 50 additional consecutive executions, 0.28-0.40 seconds each. Every run exercised both the direct descriptor and the duplicate. - Test registration passed on the final head: 880 test executables, none built without a recorded CTest invocation. Conventions and whitespace checks passed. I checked the complete file inventories of 576 open PRs on the final refresh, including pinned-head diffs for all 29 sharing `Stdio.cpp`. The 19 older AOT diffs are identical in this file and change other platform paths. I compared the implementations, tests and discussions of #5980 (invalid descriptors), #5938 (close lifetime), #5833 (whole-vector serialization), #5831 (kernel append), #6287 (stream append), #6228 (directory identity) and #6234 (GPU write coherence). None adds ordinary-file resize serialization. #5835's archive rejection is in the public wrapper and does not implement this fix. The official overlap check flags one adjacent insertion with my #6228. This change inserts the position lock after the shared-memory return, while #6228 inserts the directory-descriptor rejection there. Both lines must remain when the second PR is rebased: keep the position lock before native handle access and retain the directory check. The fixes are independent; neither needs the other to function. The checker reports no other overlap. Limits: the existing `guest_kernel_sys` symbolic-link success branches reported that links were unavailable and were not covered. No retail title, Linux runtime, console or GPU execution was tested for this change. Full hosted Windows/Linux builds require collaborator dispatch under `CONTRIBUTING.md`; skipped jobs are not validation passes. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source; none added - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes - Codex. I am responsible for the change.
github-actions[bot] commented 2026-10-15 12:18:21 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-15T12:18:21Z.


Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 4972 core/libs/prx/libkernel/CMakeLists.txt
PR 5021 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/File/src/Stdio.cpp
PR 6044 core/libs/prx/libkernel/CMakeLists.txt
PR 6226 core/libs/prx/libkernel/CMakeLists.txt
PR 6879 core/libs/prx/libkernel/File/src/Stdio.cpp
PR 6908 core/libs/prx/libkernel/CMakeLists.txt
PR 6936 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/File/src/Stdio.cpp
PR 6977 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/File/src/Stdio.cpp
PR 7192 core/libs/prx/libkernel/CMakeLists.txt
PR 7201 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/File/src/Stdio.cpp
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6191863283 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6302#issuecomment-6191863283). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-15T12:18:21Z. --- <!-- pr-overlap --> Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap. | Pull request | Shared files not compared | |---|---| | [PR 4972](https://www.github.com/boykopovar/AnyPS5/pull/4972) | `core/libs/prx/libkernel/CMakeLists.txt` | | [PR 5021](https://www.github.com/boykopovar/AnyPS5/pull/5021) | `core/libs/prx/libkernel/CMakeLists.txt`<br>`core/libs/prx/libkernel/File/src/Stdio.cpp` | | [PR 6044](https://www.github.com/boykopovar/AnyPS5/pull/6044) | `core/libs/prx/libkernel/CMakeLists.txt` | | [PR 6226](https://www.github.com/boykopovar/AnyPS5/pull/6226) | `core/libs/prx/libkernel/CMakeLists.txt` | | [PR 6879](https://www.github.com/boykopovar/AnyPS5/pull/6879) | `core/libs/prx/libkernel/File/src/Stdio.cpp` | | [PR 6908](https://www.github.com/boykopovar/AnyPS5/pull/6908) | `core/libs/prx/libkernel/CMakeLists.txt` | | [PR 6936](https://www.github.com/boykopovar/AnyPS5/pull/6936) | `core/libs/prx/libkernel/CMakeLists.txt`<br>`core/libs/prx/libkernel/File/src/Stdio.cpp` | | [PR 6977](https://www.github.com/boykopovar/AnyPS5/pull/6977) | `core/libs/prx/libkernel/CMakeLists.txt`<br>`core/libs/prx/libkernel/File/src/Stdio.cpp` | | [PR 7192](https://www.github.com/boykopovar/AnyPS5/pull/7192) | `core/libs/prx/libkernel/CMakeLists.txt` | | [PR 7201](https://www.github.com/boykopovar/AnyPS5/pull/7201) | `core/libs/prx/libkernel/CMakeLists.txt`<br>`core/libs/prx/libkernel/File/src/Stdio.cpp` |
screamm commented 2026-10-17 12:07:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by screamm on 2026-10-17T12:07:30Z.


Windows run of head b062366e5, merged onto main 673f7406c together with #6311 (no shared file; both merges clean).

  • Host: Windows 11 Pro 26220, Ryzen 7 5700X, RTX 4070 (driver 596.21), WinLibs MinGW-w64 GCC 15.2.0 r7, Ninja, Release.
  • Build: full build and libs pass, with no warnings in Stdio.cpp or GuestTruncateRace.cpp.
  • --repeat until-fail:3: guest_truncate_race and guest_truncate pass 3/3. I also ran the test executable directly 10 times (0.7-1.3 s each) and it passed 10/10.
  • Negative control: with Stdio.cpp from main and the test kept, guest_truncate_race fails 3 of 3. The first run printed kernel-direct ... pread_count_failures=32 pread_data_failures=96 cursor_failures=3 read_failures=4 ... wrong_bytes=8355051 and posix-dup ... pread_count_failures=31 pread_data_failures=96 cursor_failures=2 read_failures=4 wrong_bytes=8355051. wrong_bytes=8355051 matches the number in the description. With the source restored it passes again.
  • Non-GPU suite (ctest -j8 --timeout 120 -E '^agc_driver_|^video_out_flip'): 865 of 878 pass and 2 are skipped. Eleven tests failed in the first pass (six conventions_function_bodies*, hardware_oracle_compare, guest_none_relocations, tls_function_coverage_register_address_loads and windows_diagnostic_fixture_isolation timed out, and guest_select aborted with 0xc0000409 while the host was loaded). All eleven pass on serial reruns. I did not run the suite on plain main.
  • tools/check_conventions.py --base 673f7406c and git diff --check pass. There are no new exports.

Titles. In the relinked titles I have, ftruncate is imported by 28 (sceKernelFtruncate by PPSA28319). I ran six of them for 45 s with a local diagnostic libkernel that logs the Windows ftruncate calls: PPSA99169, PPSA85300, PPSA99109, PPSA99997, PPSA99039 and PPSA99920 made no call at all, so I cannot show a title reaching the changed path. PPSA99169 RetroArch for 60 s, three runs on main and two on this stack: no stop line on any run. Four of the five were killed at 60 s with 3311, 4596 (main) and 5444, 3135 (this PR) frames. The fifth, a main run, ended at 34 s after the picker logged VkResult is ERROR_DEVICE_LOST while the host was busy with other work. Frame counts vary too much between runs of the same build to compare.

Notes on the diff, none blocking:

  • #6228 changes the same NativeFtruncate lines and conflicts with this PR in Stdio.cpp (I checked with git merge-tree); both lines must stay when the second one is rebased.
  • NativeTruncate (the path-based truncate) now takes the lock of its private descriptor, which does not serialize against guest descriptors and does no harm.

Not checked: Linux, macOS, and any title that resizes a file while reading it.

Written with Claude Code assistance (validation by a subagent, reviewed in this session).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6233697284 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6302#issuecomment-6233697284). Originally posted by [screamm](https://github.com/screamm) on 2026-10-17T12:07:30Z. --- Windows run of head `b062366e5`, merged onto `main` `673f7406c` together with #6311 (no shared file; both merges clean). - Host: Windows 11 Pro 26220, Ryzen 7 5700X, RTX 4070 (driver 596.21), WinLibs MinGW-w64 GCC 15.2.0 r7, Ninja, Release. - Build: full build and `libs` pass, with no warnings in `Stdio.cpp` or `GuestTruncateRace.cpp`. - `--repeat until-fail:3`: `guest_truncate_race` and `guest_truncate` pass 3/3. I also ran the test executable directly 10 times (0.7-1.3 s each) and it passed 10/10. - Negative control: with `Stdio.cpp` from `main` and the test kept, `guest_truncate_race` fails 3 of 3. The first run printed `kernel-direct ... pread_count_failures=32 pread_data_failures=96 cursor_failures=3 read_failures=4 ... wrong_bytes=8355051` and `posix-dup ... pread_count_failures=31 pread_data_failures=96 cursor_failures=2 read_failures=4 wrong_bytes=8355051`. `wrong_bytes=8355051` matches the number in the description. With the source restored it passes again. - Non-GPU suite (`ctest -j8 --timeout 120 -E '^agc_driver_|^video_out_flip'`): 865 of 878 pass and 2 are skipped. Eleven tests failed in the first pass (six `conventions_function_bodies*`, `hardware_oracle_compare`, `guest_none_relocations`, `tls_function_coverage_register_address_loads` and `windows_diagnostic_fixture_isolation` timed out, and `guest_select` aborted with 0xc0000409 while the host was loaded). All eleven pass on serial reruns. I did not run the suite on plain `main`. - `tools/check_conventions.py --base 673f7406c` and `git diff --check` pass. There are no new exports. Titles. In the relinked titles I have, `ftruncate` is imported by 28 (`sceKernelFtruncate` by PPSA28319). I ran six of them for 45 s with a local diagnostic `libkernel` that logs the Windows `ftruncate` calls: PPSA99169, PPSA85300, PPSA99109, PPSA99997, PPSA99039 and PPSA99920 made no call at all, so I cannot show a title reaching the changed path. PPSA99169 RetroArch for 60 s, three runs on `main` and two on this stack: no stop line on any run. Four of the five were killed at 60 s with 3311, 4596 (`main`) and 5444, 3135 (this PR) frames. The fifth, a `main` run, ended at 34 s after the picker logged `VkResult is ERROR_DEVICE_LOST` while the host was busy with other work. Frame counts vary too much between runs of the same build to compare. Notes on the diff, none blocking: - #6228 changes the same `NativeFtruncate` lines and conflicts with this PR in `Stdio.cpp` (I checked with `git merge-tree`); both lines must stay when the second one is rebased. - `NativeTruncate` (the path-based `truncate`) now takes the lock of its private descriptor, which does not serialize against guest descriptors and does no harm. Not checked: Linux, macOS, and any title that resizes a file while reading it. Written with Claude Code assistance (validation by a subagent, reviewed in this session).
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
boykopovar/AnyPS5!6302
No description provided.