libkernel: implement sceKernelTruncate and register sceKernelFdatasync #1170

Closed
github-bot wants to merge 4 commits from gh-pr/1170/head into gh-pr/1170/base
Owner

@⁠overlordxrz-source on GitHub · 2026-10-07 22:50 UTC · original
overlordxrz-source:libkernel/truncate → main · +205 −4 · 4 files · 4 commits · closed without merging

sceKernelTruncate (WlyEA-sLDf0) and sceKernelFdatasync (30Rh4ixbKy4) are not registered. Games that import them get the unresolved-import stub, which returns 0 without doing anything.

This is part of why NHL 27 saves never load (#1101). pinkton traced it there: the save index file is written through sceKernelWritev (kAt6VDbHmro), and the same save path also calls sceKernelTruncate and sceKernelFdatasync. All three are unregistered, so every call "succeeds", the index stays empty, and the next boot treats the profile as corrupt. The bulk DATA file goes through sceKernelPwritev, which Kyty implements, so that file looked fine and hid the problem. sceKernelWritev is covered by #1401 (HamsterCL), so it is not part of this PR. With this PR and #1401 merged, all three calls on that path are handled.

Rebased onto current main (9e41d8320). sceKernelFtruncate (VW3TVZiM4-E) was originally part of this PR. main now exports it (048fe9f41), so that registration is dropped here and only its test remains.

Changes

  • sceKernelTruncate is new. It resolves the guest path the same way KernelUnlink does and flushes any writable descriptors open on that path, so buffered guest writes reach the file first. It then resizes the file by path with std::filesystem::resize_file, which only needs write access.
  • errors: EFAULT for a null path, EINVAL for a negative length, EROFS on archive mounts, EISDIR for a directory, ENOENT for a missing or unmapped file, EIO if the flush or resize fails
  • KernelClose now closes the host file and clears opened while holding the file lock, so a flush from sceKernelTruncate can't race a close. The lock order is still table lock, then file lock.
  • sceKernelFdatasync uses the same handler as sceKernelFsync (fTx66l5iWIA). The two only differ in whether metadata is flushed, and the host file layer doesn't make that distinction. This is the same registration as in pinkton's patch on #1101, and that commit credits him with Co-authored-by. If #1478 lands first and moves the fsync handler into kernel/fileSystem.cpp, this line just needs to point at the moved handler.

I compared the rest of pinkton's sceKernelTruncate with this one and kept this version. It returns EFAULT rather than EINVAL for a null path, flushes open writers before resizing, and doesn't need read access to the file.

Evidence

  • #1101 NHL 27 (PPSA34063): pinkton's save investigation above. Before that, Unresolved import stub called ... symbol=WlyEA-sLDf0 showed up right after KernelStat: /temp0/_replay0.bin.
  • #1156 Tokyo Xtreme Racer imports sceKernelTruncate from its eboot and from its bundled libc.prx. I found the same import in the logs of #1121 GTA III DE, #1134 Sonic Racing CrossWorlds, #1053 Saros, #1020 Aliens: Fireteam Elite and about 20 other game-status logs.
  • I checked all four NIDs (sceKernelTruncate, sceKernelFtruncate, sceKernelFsync, sceKernelFdatasync) by hashing the names with the standard NID scheme.

Testing

tests/KernelFileSystemTests.cpp:

  • TestTruncate resolves both truncate NIDs through InitLibKernel_1. It shrinks an open file with sceKernelFtruncate, extends a file that is open for writing with sceKernelTruncate, shrinks a closed file and checks that the leading bytes are kept. It also checks the error codes, a rename followed by a new file at the old path, a truncate racing a concurrent close, and a file the host only lets us write.
  • new TestFdatasync checks that 30Rh4ixbKy4 and fTx66l5iWIA resolve to the same handler, and that sceKernelFdatasync returns OK on a written save file
  • CheckArchiveMount also expects EROFS from KernelTruncate on an archive member

I couldn't run kernel_file_system_tests itself, because it needs a Vulkan device and the full emulator. What I ran instead:

  • compiled fileSystem.cpp, libKernel.cpp and KernelFileSystemTests.cpp for x86_64-linux-gnu with clang (zig c++ 0.17) at -Wall -Wextra, on this branch and on this branch merged with #1401. Both merge cleanly, and the warnings are identical to main's.
  • built a native aarch64 Linux harness from the real src/kernel/fileSystem.cpp and src/common file code, with network, archive, memory and logging stubbed. It runs the TestTruncate sequence plus an open, buffered index truncated by path (23/23 pass, on this branch and on this branch + #1401). On this branch + #1401 it also runs the NHL 27 index pattern: a stale longer INDEX, sceKernelWritev of two iovecs, sceKernelTruncate to the written length, close and read back (6/6 pass). The harness calls the functions directly, so the NID registration is only covered by the test above.
  • the changed src/ lines are clean under src/.clang-format (clang-format 23.1.3)

Not built on Windows or macOS.

AI assistance

An AI assistant helped me rebase this, compare it with pinkton's patch, write the sceKernelFdatasync change and test, and run the builds above. I reviewed the code and the results.

AI-assisted: yes

**@⁠overlordxrz-source** on GitHub · 2026-10-07 22:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170) `overlordxrz-source:libkernel/truncate` → `main` · +205 −4 · 4 files · 4 commits · closed without merging `sceKernelTruncate` (`WlyEA-sLDf0`) and `sceKernelFdatasync` (`30Rh4ixbKy4`) are not registered. Games that import them get the unresolved-import stub, which returns 0 without doing anything. This is part of why NHL 27 saves never load (#1101). pinkton traced it there: the save index file is written through `sceKernelWritev` (`kAt6VDbHmro`), and the same save path also calls `sceKernelTruncate` and `sceKernelFdatasync`. All three are unregistered, so every call "succeeds", the index stays empty, and the next boot treats the profile as corrupt. The bulk `DATA` file goes through `sceKernelPwritev`, which Kyty implements, so that file looked fine and hid the problem. `sceKernelWritev` is covered by #1401 (HamsterCL), so it is not part of this PR. With this PR and #1401 merged, all three calls on that path are handled. Rebased onto current `main` (9e41d8320). `sceKernelFtruncate` (`VW3TVZiM4-E`) was originally part of this PR. `main` now exports it (048fe9f41), so that registration is dropped here and only its test remains. ## Changes - `sceKernelTruncate` is new. It resolves the guest path the same way `KernelUnlink` does and flushes any writable descriptors open on that path, so buffered guest writes reach the file first. It then resizes the file by path with `std::filesystem::resize_file`, which only needs write access. - errors: EFAULT for a null path, EINVAL for a negative length, EROFS on archive mounts, EISDIR for a directory, ENOENT for a missing or unmapped file, EIO if the flush or resize fails - `KernelClose` now closes the host file and clears `opened` while holding the file lock, so a flush from `sceKernelTruncate` can't race a close. The lock order is still table lock, then file lock. - `sceKernelFdatasync` uses the same handler as `sceKernelFsync` (`fTx66l5iWIA`). The two only differ in whether metadata is flushed, and the host file layer doesn't make that distinction. This is the same registration as in pinkton's patch on #1101, and that commit credits him with `Co-authored-by`. If #1478 lands first and moves the fsync handler into `kernel/fileSystem.cpp`, this line just needs to point at the moved handler. I compared the rest of pinkton's `sceKernelTruncate` with this one and kept this version. It returns EFAULT rather than EINVAL for a null path, flushes open writers before resizing, and doesn't need read access to the file. ## Evidence - #1101 NHL 27 (PPSA34063): pinkton's save investigation above. Before that, `Unresolved import stub called ... symbol=WlyEA-sLDf0` showed up right after `KernelStat: /temp0/_replay0.bin`. - #1156 Tokyo Xtreme Racer imports `sceKernelTruncate` from its eboot and from its bundled `libc.prx`. I found the same import in the logs of #1121 GTA III DE, #1134 Sonic Racing CrossWorlds, #1053 Saros, #1020 Aliens: Fireteam Elite and about 20 other game-status logs. - I checked all four NIDs (`sceKernelTruncate`, `sceKernelFtruncate`, `sceKernelFsync`, `sceKernelFdatasync`) by hashing the names with the standard NID scheme. ## Testing `tests/KernelFileSystemTests.cpp`: - `TestTruncate` resolves both truncate NIDs through `InitLibKernel_1`. It shrinks an open file with `sceKernelFtruncate`, extends a file that is open for writing with `sceKernelTruncate`, shrinks a closed file and checks that the leading bytes are kept. It also checks the error codes, a rename followed by a new file at the old path, a truncate racing a concurrent close, and a file the host only lets us write. - new `TestFdatasync` checks that `30Rh4ixbKy4` and `fTx66l5iWIA` resolve to the same handler, and that `sceKernelFdatasync` returns OK on a written save file - `CheckArchiveMount` also expects EROFS from `KernelTruncate` on an archive member I couldn't run `kernel_file_system_tests` itself, because it needs a Vulkan device and the full emulator. What I ran instead: - compiled `fileSystem.cpp`, `libKernel.cpp` and `KernelFileSystemTests.cpp` for `x86_64-linux-gnu` with clang (zig c++ 0.17) at `-Wall -Wextra`, on this branch and on this branch merged with #1401. Both merge cleanly, and the warnings are identical to `main`'s. - built a native aarch64 Linux harness from the real `src/kernel/fileSystem.cpp` and `src/common` file code, with network, archive, memory and logging stubbed. It runs the `TestTruncate` sequence plus an open, buffered index truncated by path (23/23 pass, on this branch and on this branch + #1401). On this branch + #1401 it also runs the NHL 27 index pattern: a stale longer `INDEX`, `sceKernelWritev` of two iovecs, `sceKernelTruncate` to the written length, close and read back (6/6 pass). The harness calls the functions directly, so the NID registration is only covered by the test above. - the changed `src/` lines are clean under `src/.clang-format` (clang-format 23.1.3) Not built on Windows or macOS. ## AI assistance An AI assistant helped me rebase this, compare it with pinkton's patch, write the `sceKernelFdatasync` change and test, and run the builds above. I reviewed the code and the results. AI-assisted: yes
sceKernelTruncate (WlyEA-sLDf0) was not registered, so games that import
it got the unresolved-import stub, which returns 0 without touching the
file. NHL 27 calls sceKernelTruncate on /temp0/_replay0.bin during boot
and then reuses the file as if it had been resized.

sceKernelTruncate resolves the guest path like KernelUnlink, truncates
through the open descriptor when the file is already open for writing
(so buffered writes are flushed first) and otherwise through a temporary
read-write handle. It returns EFAULT for a null path, EINVAL for a
negative length, EROFS on archive mounts, EISDIR for directories and
ENOENT for missing files.

sceKernelFtruncate (VW3TVZiM4-E) was part of this change originally;
main now exports it (048fe9f41), so only the test for it remains here.
Review on #1170 pointed out two problems with reusing an open descriptor
found by real_name. KernelRename does not update real_name, so after a
rename and a new file at the old path the lookup picked the renamed
file. The raw pointer was also used after the table lock was released,
so a concurrent close could free it.

Flush every open writable descriptor for the path while the descriptor
table lock is held, then truncate through a fresh handle opened at the
path. Buffered guest writes still reach the file before it is resized.
The test now covers a rename followed by a replacement at the old path.
Review on #1170 found two problems in sceKernelTruncate.

KernelClose closed the host file without the file lock, while
FlushWritable flushes it under that lock. The descriptor table lock kept
the File from being deleted, but not the host handle from being closed
in the middle of the flush. KernelClose now closes the host file and
clears opened while holding the file lock, so the flush either finishes
first or sees a closed file and skips it. The lock order stays table
lock, then file lock, and KernelClose never holds both at once. This is
the same KernelClose change as in #1177.

KernelTruncate opened the file with Mode::ReadWrite, so a host file with
write access but no read access failed with EIO. Common::File has no
write-only mode that keeps the contents on every host (the POSIX backend
opens Mode::Write with "r+"), so it now resizes the file with
std::filesystem::resize_file. That is truncate(2) on POSIX, and the
MSVC STL used by the clang-cl build opens the file for writing only.
Any failure still returns EIO.

tests: TestTruncate keeps closing and reopening a writable descriptor on
another thread while calling sceKernelTruncate on its path. Every call
must return OK, or ENOENT before the file first exists. It also
truncates a file that only has owner write permission, when the host
really denies reading it (not as root).
sceKernelFdatasync (30Rh4ixbKy4) was not registered, so the call hit
the unresolved-import stub. NHL 27 calls it on its save path next to
sceKernelWritev and sceKernelTruncate (pinkton's log on #1101).

Register it on the same handler as sceKernelFsync (fTx66l5iWIA). Both
only differ in whether file metadata is flushed, which the host file
layer does not distinguish, so one handler serves both. If the fsync
handler moves into kernel/fileSystem.cpp later, this line moves with
it.

tests: TestFdatasync checks that both NIDs resolve to the same handler
and that sceKernelFdatasync returns OK on a written save file.

Co-authored-by: pinkton <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:46:17 +00:00
github-bot closed this pull request 2026-11-26 09:46:17 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 22:54 UTC · original · edited 2026-10-15 18:26 UTC

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 334b306a-6059-4ed9-a027-452cbd58154f
📥 Commits

Reviewing files that changed from the base of the PR and between 427ac3cd66bdde4152c6aa5a9de8456dca29074c and e59f88cd31.

📒 Files selected for processing: 4
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/libs/libKernel.cpp
  • tests/KernelFileSystemTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📝 Walkthrough

The change adds and registers KernelTruncate(path, length). It validates the path and length, rejects archive paths and directories, flushes matching writable descriptors, and truncates the host file. Tests cover shrinking and extending files, content preservation, error cases, renamed paths, concurrent descriptor activity, write-only files, and archive-path rejection. Additional tests check that sceKernelFdatasync resolves to the fsync handler and succeeds on a written file.

Suggested reviewers: neveshenry

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to e59f8

No change-specific issue remains that needs to be fixed before merge; normal build and test checks still apply.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly identifies the two main changes: implementing sceKernelTruncate and registering sceKernelFdatasync.
Description check Passed The description directly explains the implementation, registrations, error handling, concurrency changes, tests, and validation results for the pull request.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#issuecomment-6048506961) · edited 2026-10-15 18:26 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1170?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `334b306a-6059-4ed9-a027-452cbd58154f` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 427ac3cd66bdde4152c6aa5a9de8456dca29074c and e59f88cd31426a54070ccac20f79b4ba4fbe31c5. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing: 4</strong></summary> <dl> <dd> * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/libs/libKernel.cpp` * `tests/KernelFileSystemTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The change adds and registers `KernelTruncate(path, length)`. It validates the path and length, rejects archive paths and directories, flushes matching writable descriptors, and truncates the host file. Tests cover shrinking and extending files, content preservation, error cases, renamed paths, concurrent descriptor activity, write-only files, and archive-path rejection. Additional tests check that `sceKernelFdatasync` resolves to the fsync handler and succeeds on a written file. **Suggested reviewers:** `neveshenry` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"e59f88cd31426a54070ccac20f79b4ba4fbe31c5" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>e59f8</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `e59f8` --> <!-- final_review_risk_coverage:{"sourceCommitId":"e59f88cd31426a54070ccac20f79b4ba4fbe31c5","coveredCommitId":"e59f88cd31426a54070ccac20f79b4ba4fbe31c5","kind":"reviewed"} --> No change-specific issue remains that needs to be fixed before merge; normal build and test checks still apply. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 4 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly identifies the two main changes: implementing `sceKernelTruncate` and registering `sceKernelFdatasync`. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the implementation, registrations, error handling, concurrency changes, tests, and validation results for the pull request. | </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1170)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 22:54 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8318f8c6-3e1f-42e2-a9f3-88fdee463679
📥 Commits

Reviewing files that changed from the base of the PR and between 420bb51d6c and 006ca9c3777dca57a76190c25d38fe586ad9ba37.

📒 Files selected for processing (4)
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/libs/libKernel.cpp
  • tests/KernelFileSystemTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#pullrequestreview-5449396649) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `8318f8c6-3e1f-42e2-a9f3-88fdee463679` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 420bb51d6c0de9ea1cc4a1b065b6dc605f4f030e and 006ca9c3777dca57a76190c25d38fe586ad9ba37. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/libs/libKernel.cpp` * `tests/KernelFileSystemTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=4b14d576-1795-44e2-9572-070a40d3a107 attempt=115ceb29-737e-450d-8977-3109e411d65e batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 22:54 UTC · original · edited 2026-10-07 23:22 UTC
On src/kernel/fileSystem.cpp line 1251 (outdated):

@@ -1223,6 +1223,50 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) {
+	PRINT_NAME();
+
+	if (path == nullptr) {
+		return KERNEL_ERROR_EFAULT;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+
+	if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	bool  ok        = false;
+	auto* open_file = g_files->GetFile(real_file_name);

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Select the file currently at the resolved path.

If a caller renames an open file and creates a replacement at its old path, KernelRename leaves the open descriptor's real_name unchanged. GetFile(real_file_name) selects that older descriptor first. KernelTruncate then reports success after truncating the renamed file, while the replacement keeps its size. Confirm file identity before reusing a descriptor, or truncate the file currently at the resolved path.


🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Keep the selected descriptor alive through truncation.

If another thread calls KernelClose after GetFile(real_file_name) returns, KernelClose can delete open_file before this function reads its fields or takes open_file->mutex. The resulting access can crash the process. Retain descriptor ownership or coordinate lookup, truncation, and close with the same lifetime lock.

✅ Addressed in commit d6886d4

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 22:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4212854691) · edited 2026-10-07 23:22 UTC On `src/kernel/fileSystem.cpp` line 1251 (outdated): ```diff @@ -1223,6 +1223,50 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) { return OK; } +int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) { + PRINT_NAME(); + + if (path == nullptr) { + return KERNEL_ERROR_EFAULT; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + + if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + bool ok = false; + auto* open_file = g_files->GetFile(real_file_name); ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **🏗️ Heavy lift** **Select the file currently at the resolved path.** If a caller renames an open file and creates a replacement at its old path, `KernelRename` leaves the open descriptor's `real_name` unchanged. `GetFile(real_file_name)` selects that older descriptor first. `KernelTruncate` then reports success after truncating the renamed file, while the replacement keeps its size. Confirm file identity before reusing a descriptor, or truncate the file currently at the resolved path. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:9b6b22d4130d58873b706196 --> --- **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Keep the selected descriptor alive through truncation.** If another thread calls `KernelClose` after `GetFile(real_file_name)` returns, `KernelClose` can delete `open_file` before this function reads its fields or takes `open_file->mutex`. The resulting access can crash the process. Retain descriptor ownership or coordinate lookup, truncation, and close with the same lifetime lock. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:be87c1e0d6bc69612ef6c1a7 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit d6886d4
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-07 23:15 UTC · original
On src/kernel/fileSystem.cpp line 1251 (outdated):

@@ -1223,6 +1223,50 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) {
+	PRINT_NAME();
+
+	if (path == nullptr) {
+		return KERNEL_ERROR_EFAULT;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+
+	if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	bool  ok        = false;
+	auto* open_file = g_files->GetFile(real_file_name);

Thanks, both were real. Fixed in the latest commit:

  • KernelTruncate no longer reuses a descriptor found by real_name. It flushes every open writable descriptor for that path while holding the descriptor table lock, then truncates through a fresh handle opened at the path. A renamed open file is no longer chosen over the file now at the path, and buffered guest writes still land before the resize.
  • Because the flush runs under m_mutex, DeleteDescriptor can't free a File mid-call. KernelClose still calls f.Close() without taking file->mutex, the same as read and write, so I left that as it is.
  • TestTruncate now renames an open file, creates a replacement at the old path, truncates the old path, and checks that only the replacement changes size. Without the fix, that check fails.
**@⁠overlordxrz-source** on GitHub · 2026-10-07 23:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4212987745) On `src/kernel/fileSystem.cpp` line 1251 (outdated): ```diff @@ -1223,6 +1223,50 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) { return OK; } +int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) { + PRINT_NAME(); + + if (path == nullptr) { + return KERNEL_ERROR_EFAULT; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + + if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + bool ok = false; + auto* open_file = g_files->GetFile(real_file_name); ``` Thanks, both were real. Fixed in the latest commit: - `KernelTruncate` no longer reuses a descriptor found by `real_name`. It flushes every open writable descriptor for that path while holding the descriptor table lock, then truncates through a fresh handle opened at the path. A renamed open file is no longer chosen over the file now at the path, and buffered guest writes still land before the resize. - Because the flush runs under `m_mutex`, `DeleteDescriptor` can't free a `File` mid-call. `KernelClose` still calls `f.Close()` without taking `file->mutex`, the same as read and write, so I left that as it is. - `TestTruncate` now renames an open file, creates a replacement at the old path, truncates the old path, and checks that only the replacement changes size. Without the fix, that check fails.
@ -242,0 +249,4 @@
Common::LockGuard file_lock(f->mutex);
if (f->opened && f->writable && !f->directory && f->special == SpecialFile::None &&
!f->f.IsInvalid()) {
ok = f->f.Flush() && ok;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 23:18 UTC · original · edited 2026-10-08 02:48 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Synchronize KernelClose with the flush.

If KernelClose runs while FlushWritable holds f->mutex, KernelClose can still call f.Close() without that mutex. The descriptor-table lock prevents deletion, but it does not keep the underlying handle open during f->f.Flush(). Make close and flush use the same per-file synchronization so concurrent truncation cannot flush a closing handle.

✅ Confirmed as addressed by @⁠overlordxrz-source

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 23:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4213006780) · edited 2026-10-08 02:48 UTC **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Synchronize `KernelClose` with the flush.** If `KernelClose` runs while `FlushWritable` holds `f->mutex`, `KernelClose` can still call `f.Close()` without that mutex. The descriptor-table lock prevents deletion, but it does not keep the underlying handle open during `f->f.Flush()`. Make close and flush use the same per-file synchronization so concurrent truncation cannot flush a closing handle. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:9324f7984f5fbbeae52ab973 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠overlordxrz-source <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 23:18 UTC · original · edited 2026-10-08 02:50 UTC
On src/kernel/fileSystem.cpp line 1272 (outdated):

@@ -1223,6 +1241,44 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) {
+	PRINT_NAME();
+
+	if (path == nullptr) {
+		return KERNEL_ERROR_EFAULT;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+
+	if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	if (!g_files->FlushWritable(real_file_name)) {
+		return KERNEL_ERROR_EIO;
+	}
+
+	Common::File file(real_file_name, Common::File::Mode::ReadWrite);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not require read access to truncate a writable file.

If the host file grants write access but not read access, opening it with Mode::ReadWrite can fail even though truncation only needs write access. KernelTruncate then returns EIO without resizing the file. Use a truncation path that preserves existing contents and requires only write access.

✅ Addressed in commit 427ac3c

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 23:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4213006787) · edited 2026-10-08 02:50 UTC On `src/kernel/fileSystem.cpp` line 1272 (outdated): ```diff @@ -1223,6 +1241,44 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) { return OK; } +int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) { + PRINT_NAME(); + + if (path == nullptr) { + return KERNEL_ERROR_EFAULT; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + + if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + if (!g_files->FlushWritable(real_file_name)) { + return KERNEL_ERROR_EIO; + } + + Common::File file(real_file_name, Common::File::Mode::ReadWrite); ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Do not require read access to truncate a writable file.** If the host file grants write access but not read access, opening it with `Mode::ReadWrite` can fail even though truncation only needs write access. `KernelTruncate` then returns `EIO` without resizing the file. Use a truncation path that preserves existing contents and requires only write access. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1769ceb18b8ff358dd703ebc --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 427ac3c
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 23:18 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 21b490e5-7b29-487c-9840-bd4af7a18cb9
📥 Commits

Reviewing files that changed from the base of the PR and between 006ca9c3777dca57a76190c25d38fe586ad9ba37 and d6886d4f22e2957b2af63ef30ca8c861718e5f97.

📒 Files selected for processing (2)
  • src/kernel/fileSystem.cpp
  • tests/KernelFileSystemTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/KernelFileSystemTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 23:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#pullrequestreview-5449570932) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `21b490e5-7b29-487c-9840-bd4af7a18cb9` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 006ca9c3777dca57a76190c25d38fe586ad9ba37 and d6886d4f22e2957b2af63ef30ca8c861718e5f97. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/kernel/fileSystem.cpp` * `tests/KernelFileSystemTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * tests/KernelFileSystemTests.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=e218bae9-3641-4486-8630-c2c99b8563a2 attempt=0b8ab514-918f-4c61-ba7b-6d3c09ab3b0d batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-07 23:22 UTC · original
On src/kernel/fileSystem.cpp line 1251 (outdated):

@@ -1223,6 +1223,50 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) {
+	PRINT_NAME();
+
+	if (path == nullptr) {
+		return KERNEL_ERROR_EFAULT;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+
+	if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	bool  ok        = false;
+	auto* open_file = g_files->GetFile(real_file_name);

@overlordxrz-source Thanks for the fix and clarification. The supplied code addresses both findings:

  • KernelTruncate opens a fresh handle at the resolved path, so it no longer truncates the renamed file through a stale descriptor.
  • FlushWritable holds the descriptor-table lock, so DeleteDescriptor cannot free a File during the flush.

The existing KernelClose synchronization gap remains separate from these fixes. I have not run TestTruncate.


✏️ Learnings added
Learnt from: overlordxrz-source
Repo: KytyPS5/KytyPS5 PR: 1170
File: src/kernel/fileSystem.cpp:0-0
Timestamp: 2026-10-07T23:22:28.651Z
Learning: In src/kernel/fileSystem.cpp, KernelRename does not update open descriptors' File::real_name after a rename. A descriptor's stored real_name therefore does not prove that its host handle refers to the file currently at that path. Path-based filesystem operations must not rely on that lookup alone to establish file identity.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-07 23:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4213028679) On `src/kernel/fileSystem.cpp` line 1251 (outdated): ```diff @@ -1223,6 +1223,50 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) { return OK; } +int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) { + PRINT_NAME(); + + if (path == nullptr) { + return KERNEL_ERROR_EFAULT; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + + if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + bool ok = false; + auto* open_file = g_files->GetFile(real_file_name); ``` `@overlordxrz-source` Thanks for the fix and clarification. The supplied code addresses both findings: - `KernelTruncate` opens a fresh handle at the resolved path, so it no longer truncates the renamed file through a stale descriptor. - `FlushWritable` holds the descriptor-table lock, so `DeleteDescriptor` cannot free a `File` during the flush. The existing `KernelClose` synchronization gap remains separate from these fixes. I have not run `TestTruncate`. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: overlordxrz-source Repo: KytyPS5/KytyPS5 PR: 1170 File: src/kernel/fileSystem.cpp:0-0 Timestamp: 2026-10-07T23:22:28.651Z Learning: In src/kernel/fileSystem.cpp, KernelRename does not update open descriptors' File::real_name after a rename. A descriptor's stored real_name therefore does not prove that its host handle refers to the file currently at that path. Path-based filesystem operations must not rely on that lookup alone to establish file identity. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20stale-descriptor%20truncation%20and%20a%20close%20race.%20Fix%3A%20flush%20under%20the%20table%20lock%2C%20truncate%20via%20a%20fresh%20path%20handle%2C%20and%20test%20replacement-file%20identity.%20Try%20%40coderabbitai%20for%20sharper%20reviews!&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1170%23discussion_r4212854691)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
@ -242,0 +249,4 @@
Common::LockGuard file_lock(f->mutex);
if (f->opened && f->writable && !f->directory && f->special == SpecialFile::None &&
!f->f.IsInvalid()) {
ok = f->f.Flush() && ok;
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-08 02:48 UTC · original

Fixed in "libkernel: close under the file lock and truncate by path".

KernelClose now closes the host file and clears opened while holding file->mutex. FlushWritable checks opened under that same lock, so it either finishes its flush before the close or sees a closed file and skips it. The lock order stays table lock, then file lock, and KernelClose never holds both. The KernelClose change is the same as the one in #1177, so the two merge cleanly in either order.

TestTruncate now closes and reopens a writable descriptor on another thread while calling sceKernelTruncate on its path. I couldn't run the test binary (it needs Vulkan and the full emulator), but in a standalone harness built from fileSystem.cpp the old code flushed a file that was being closed, and once hit the IsInvalid() assert in File::Flush. The new code passes.

**@⁠overlordxrz-source** on GitHub · 2026-10-08 02:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4214092066) Fixed in "libkernel: close under the file lock and truncate by path". `KernelClose` now closes the host file and clears `opened` while holding `file->mutex`. `FlushWritable` checks `opened` under that same lock, so it either finishes its flush before the close or sees a closed file and skips it. The lock order stays table lock, then file lock, and `KernelClose` never holds both. The `KernelClose` change is the same as the one in #1177, so the two merge cleanly in either order. `TestTruncate` now closes and reopens a writable descriptor on another thread while calling `sceKernelTruncate` on its path. I couldn't run the test binary (it needs Vulkan and the full emulator), but in a standalone harness built from `fileSystem.cpp` the old code flushed a file that was being closed, and once hit the `IsInvalid()` assert in `File::Flush`. The new code passes.
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-08 02:48 UTC · original
On src/kernel/fileSystem.cpp line 1272 (outdated):

@@ -1223,6 +1241,44 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) {
+	PRINT_NAME();
+
+	if (path == nullptr) {
+		return KERNEL_ERROR_EFAULT;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+
+	if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	if (!g_files->FlushWritable(real_file_name)) {
+		return KERNEL_ERROR_EIO;
+	}
+
+	Common::File file(real_file_name, Common::File::Mode::ReadWrite);

Fixed in "libkernel: close under the file lock and truncate by path".

KernelTruncate now resizes the file with std::filesystem::resize_file instead of opening it with Mode::ReadWrite. Common::File has no write-only mode that keeps the contents on every host (the POSIX backend opens Mode::Write with "r+"). On POSIX resize_file is truncate(2), and the MSVC STL opens the file for writing only. Any failure still returns EIO, and the other error codes are unchanged.

TestTruncate now truncates a file with only owner write permission, and skips that check where the host can still read it (Windows, or running as root). In a standalone harness on Linux, the old code returned EIO for that file and the new code resizes it. I haven't built it on Windows or macOS.

**@⁠overlordxrz-source** on GitHub · 2026-10-08 02:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4214092222) On `src/kernel/fileSystem.cpp` line 1272 (outdated): ```diff @@ -1223,6 +1241,44 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) { return OK; } +int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) { + PRINT_NAME(); + + if (path == nullptr) { + return KERNEL_ERROR_EFAULT; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + + if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + if (!g_files->FlushWritable(real_file_name)) { + return KERNEL_ERROR_EIO; + } + + Common::File file(real_file_name, Common::File::Mode::ReadWrite); ``` Fixed in "libkernel: close under the file lock and truncate by path". `KernelTruncate` now resizes the file with `std::filesystem::resize_file` instead of opening it with `Mode::ReadWrite`. `Common::File` has no write-only mode that keeps the contents on every host (the POSIX backend opens `Mode::Write` with `"r+"`). On POSIX `resize_file` is `truncate(2)`, and the MSVC STL opens the file for writing only. Any failure still returns `EIO`, and the other error codes are unchanged. `TestTruncate` now truncates a file with only owner write permission, and skips that check where the host can still read it (Windows, or running as root). In a standalone harness on Linux, the old code returned `EIO` for that file and the new code resizes it. I haven't built it on Windows or macOS.
@ -242,0 +249,4 @@
Common::LockGuard file_lock(f->mutex);
if (f->opened && f->writable && !f->directory && f->special == SpecialFile::None &&
!f->f.IsInvalid()) {
ok = f->f.Flush() && ok;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 02:48 UTC · original

@overlordxrz-source Thanks for the fix and the locking explanation.

The supplied code addresses this finding. KernelClose and FlushWritable now use the same per-file mutex for close, the opened check, and flush. KernelClose releases that mutex before deleting the descriptor, so it does not reverse the table-lock-then-file-lock order.

The reported harness result supports the fix. The full test binary remains untested.


✏️ Learnings added
Learnt from: overlordxrz-source
Repo: KytyPS5/KytyPS5 PR: 1170
File: src/kernel/fileSystem.cpp:248-251
Timestamp: 2026-10-08T02:48:50.598Z
Learning: In src/kernel/fileSystem.cpp, FileDescriptors operations that need both locks must acquire the descriptor-table mutex before File::mutex. KernelClose must release File::mutex before calling FileDescriptors::DeleteDescriptor, which acquires the descriptor-table mutex. Close and flush must synchronize through File::mutex.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 02:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4214094414) `@overlordxrz-source` Thanks for the fix and the locking explanation. The supplied code addresses this finding. `KernelClose` and `FlushWritable` now use the same per-file mutex for close, the `opened` check, and flush. `KernelClose` releases that mutex before deleting the descriptor, so it does not reverse the table-lock-then-file-lock order. The reported harness result supports the fix. The full test binary remains untested. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: overlordxrz-source Repo: KytyPS5/KytyPS5 PR: 1170 File: src/kernel/fileSystem.cpp:248-251 Timestamp: 2026-10-08T02:48:50.598Z Learning: In src/kernel/fileSystem.cpp, FileDescriptors operations that need both locks must acquire the descriptor-table mutex before File::mutex. KernelClose must release File::mutex before calling FileDescriptors::DeleteDescriptor, which acquires the descriptor-table mutex. Close and flush must synchronize through File::mutex. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20close%2Fflush%20race%3A%20a%20file%20lock%20now%20synchronizes%20%60KernelClose%60%20and%20%60FlushWritable%60%2C%20preventing%20flushes%20on%20closing%20handles.%20A%20concurrent%20truncate%20test%20covers%20it.%20Try%20%40coderabbitai%20%F0%9F%A9%BA&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1170%23discussion_r4213006780)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 02:50 UTC · original
On src/kernel/fileSystem.cpp line 1272 (outdated):

@@ -1223,6 +1241,44 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) {
+	PRINT_NAME();
+
+	if (path == nullptr) {
+		return KERNEL_ERROR_EFAULT;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+
+	if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	if (!g_files->FlushWritable(real_file_name)) {
+		return KERNEL_ERROR_EIO;
+	}
+
+	Common::File file(real_file_name, Common::File::Mode::ReadWrite);

@overlordxrz-source Thanks for the fix and the backend details. The supplied KernelTruncate implementation uses std::filesystem::resize_file, which removes the unnecessary read-access requirement. The EIO failure mapping remains unchanged.

The write-only-permission test covers this regression where the host enforces the permission restriction. Windows and macOS validation remains untested, as you stated.


✏️ Learnings added
Learnt from: overlordxrz-source
Repo: KytyPS5/KytyPS5 PR: 1170
File: src/kernel/fileSystem.cpp:0-0
Timestamp: 2026-10-08T02:50:39.744Z
Learning: In KytyPS5/KytyPS5, Common::File::Mode::Write uses "r+" in the POSIX backend and therefore requires read access. Common::File has no cross-platform write-only mode that preserves existing contents. For path-based truncation in src/kernel/fileSystem.cpp, do not use Mode::Write or Mode::ReadWrite as a substitute for a truncation API that requires only write access.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: overlordxrz-source
Repo: KytyPS5/KytyPS5 PR: 1170
File: src/kernel/fileSystem.cpp:248-251
Timestamp: 2026-10-08T02:48:52.912Z
Learning: In src/kernel/fileSystem.cpp, FileDescriptors operations that need both locks must acquire the descriptor-table mutex before File::mutex. KernelClose must release File::mutex before calling FileDescriptors::DeleteDescriptor, which acquires the descriptor-table mutex. Close and flush must synchronize through File::mutex.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 02:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#discussion_r4214103358) On `src/kernel/fileSystem.cpp` line 1272 (outdated): ```diff @@ -1223,6 +1241,44 @@ int KYTY_SYSV_ABI KernelFtruncate(int d, int64_t length) { return OK; } +int KYTY_SYSV_ABI KernelTruncate(const char* path, int64_t length) { + PRINT_NAME(); + + if (path == nullptr) { + return KERNEL_ERROR_EFAULT; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + + if (real_file_name.empty() || !Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + if (!g_files->FlushWritable(real_file_name)) { + return KERNEL_ERROR_EIO; + } + + Common::File file(real_file_name, Common::File::Mode::ReadWrite); ``` `@overlordxrz-source` Thanks for the fix and the backend details. The supplied `KernelTruncate` implementation uses `std::filesystem::resize_file`, which removes the unnecessary read-access requirement. The `EIO` failure mapping remains unchanged. The write-only-permission test covers this regression where the host enforces the permission restriction. Windows and macOS validation remains untested, as you stated. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: overlordxrz-source Repo: KytyPS5/KytyPS5 PR: 1170 File: src/kernel/fileSystem.cpp:0-0 Timestamp: 2026-10-08T02:50:39.744Z Learning: In KytyPS5/KytyPS5, Common::File::Mode::Write uses "r+" in the POSIX backend and therefore requires read access. Common::File has no cross-platform write-only mode that preserves existing contents. For path-based truncation in src/kernel/fileSystem.cpp, do not use Mode::Write or Mode::ReadWrite as a substitute for a truncation API that requires only write access. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <details> <summary>🧠 Learnings used</summary> ``` Learnt from: overlordxrz-source Repo: KytyPS5/KytyPS5 PR: 1170 File: src/kernel/fileSystem.cpp:248-251 Timestamp: 2026-10-08T02:48:52.912Z Learning: In src/kernel/fileSystem.cpp, FileDescriptors operations that need both locks must acquire the descriptor-table mutex before File::mutex. KernelClose must release File::mutex before calling FileDescriptors::DeleteDescriptor, which acquires the descriptor-table mutex. Close and flush must synchronize through File::mutex. ``` </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Writable%20but%20unreadable%20files%20should%20still%20truncate%3A%20use%20%60resize_file%60%20instead%20of%20a%20read-write%20open%20to%20avoid%20%60EIO%60.%20%40coderabbitai%20catches%20edge%20cases%20like%20this%E2%80%94try%20it!&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1170%23discussion_r4213006787)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠Friskky1 on GitHub · 2026-10-08 02:55 UTC · original

is it merged yet?

**@⁠Friskky1** on GitHub · 2026-10-08 02:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#issuecomment-6051223714) is it merged yet?
Author
Owner

@⁠Nmzik on GitHub · 2026-10-15 23:34 UTC · original

Sole credited 56d3ce98f0

**@⁠Nmzik** on GitHub · 2026-10-15 23:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1170#issuecomment-6204501399) Sole credited 56d3ce98f00eb31c767152a377a2acfcffaf88b7

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.