libkernel: flush files in fsync and export chmod, fchmod and rmdir #1177

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

@⁠overlordxrz-source on GitHub · 2026-10-08 01:14 UTC · original
overlordxrz-source:libkernel/fsync-chmod-exports → main · +291 −21 · 4 files · 2 commits · closed without merging

sceKernelFsync (fTx66l5iWIA) is a stub that returns 0 without touching the file. The POSIX fsync (juWbTNM+8hw), fdatasync (KIbJFQ0I1Cg), fchmod (n01yNbQO5W4) and rmdir (c7ZnT7V1B98), and sceKernelFdatasync (30Rh4ixbKy4), sceKernelChmod (fgIsQ10xYVA) and sceKernelFchmod (UtszJWHrDcA) are not registered at all, so games that import them get the unresolved-import stub.

This adds them next to the other libkernel file calls:

  • KernelFsync moves to fileSystem.cpp and flushes the host file of a writable descriptor. It backs sceKernelFsync, sceKernelFdatasync, fsync and fdatasync. Errors: EBADF for a bad descriptor, EINVAL for a socket, EIO if the flush fails. Read-only, directory and special descriptors and the standard streams return 0.
  • KernelChmod and KernelFchmod check the path or descriptor: EFAULT for a null path, ENOENT for a missing or unmapped file, EBADF for a bad descriptor, EROFS on archive mounts. Guest permissions aren't emulated (stat reports 0777), so they don't change host permissions. The existing POSIX chmod export (z0dtnPxYgtg) was a plain stub and now uses the same checks.
  • KernelRmdir returns ENOTEMPTY for a non-empty directory (it returned EIO) and ENOTDIR for a regular file (it returned ENOENT)

Evidence

  • #1131 Marvel's Wolverine (PPSA03671, v0.3.0): Unresolved import stub called: juWbTNM+8hw[Posix_v1][libkernel_v1.1][Func]. I'm not claiming this makes Wolverine boot.
  • #953 South of Midnight (PPSA29642): Unresolved import stub called: fgIsQ10xYVA[libkernel_v1][libkernel_v1.1][Func], repeated many times
  • the bundled libc.prx imports sceKernelChmod and rmdir in all 43 game logs I scanned

Testing

tests/KernelFileSystemTests.cpp:

  • new TestFsyncChmod: resolves all of the new NIDs through InitLibKernel_1. It checks that sceKernelFsync puts buffered writes in the host file, that the fsync variants accept writable, read-only and standard-stream descriptors and reject bad ones, that chmod/fchmod accept existing files and directories and reject missing, null and unmapped paths and bad descriptors (with the POSIX errno), and that rmdir keeps a non-empty directory, rejects a file, removes an empty directory and reports a missing one.
  • CheckArchiveMount also expects EROFS from KernelChmod and KernelFchmod on an archive member, and 0 from KernelFsync

I couldn't run kernel_file_system_tests itself. It needs a Vulkan device and the full emulator, and my machine is aarch64 Linux. Here is what I did instead:

  • compiled the changed fileSystem.cpp and libKernel.cpp for x86_64-linux-gnu and x86_64-windows-gnu (mingw), and the updated test file for x86_64-linux-gnu, with clang (zig c++) at -Wall -Wextra. The changed lines add no warnings.
  • built a small native harness from fileSystem.cpp plus src/common, with stubs for network, memory and ZArchive. It runs the same checks as TestFsyncChmod against a temporary /savedata0 mount, calling the Kernel* functions directly, and all 18 pass. 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 macOS. This touches the same test function as #1170 (sceKernelTruncate), but the two merge cleanly in either order.

AI assistance

An AI assistant helped me find the missing exports in the issue logs, write the change and the test, and run the builds above. I reviewed the code and the results.

**@⁠overlordxrz-source** on GitHub · 2026-10-08 01:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177) `overlordxrz-source:libkernel/fsync-chmod-exports` → `main` · +291 −21 · 4 files · 2 commits · closed without merging `sceKernelFsync` (`fTx66l5iWIA`) is a stub that returns 0 without touching the file. The POSIX `fsync` (`juWbTNM+8hw`), `fdatasync` (`KIbJFQ0I1Cg`), `fchmod` (`n01yNbQO5W4`) and `rmdir` (`c7ZnT7V1B98`), and `sceKernelFdatasync` (`30Rh4ixbKy4`), `sceKernelChmod` (`fgIsQ10xYVA`) and `sceKernelFchmod` (`UtszJWHrDcA`) are not registered at all, so games that import them get the unresolved-import stub. This adds them next to the other libkernel file calls: - `KernelFsync` moves to `fileSystem.cpp` and flushes the host file of a writable descriptor. It backs `sceKernelFsync`, `sceKernelFdatasync`, `fsync` and `fdatasync`. Errors: EBADF for a bad descriptor, EINVAL for a socket, EIO if the flush fails. Read-only, directory and special descriptors and the standard streams return 0. - `KernelChmod` and `KernelFchmod` check the path or descriptor: EFAULT for a null path, ENOENT for a missing or unmapped file, EBADF for a bad descriptor, EROFS on archive mounts. Guest permissions aren't emulated (`stat` reports 0777), so they don't change host permissions. The existing POSIX `chmod` export (`z0dtnPxYgtg`) was a plain stub and now uses the same checks. - `KernelRmdir` returns ENOTEMPTY for a non-empty directory (it returned EIO) and ENOTDIR for a regular file (it returned ENOENT) ## Evidence - #1131 Marvel's Wolverine (PPSA03671, v0.3.0): `Unresolved import stub called: juWbTNM+8hw[Posix_v1][libkernel_v1.1][Func]`. I'm not claiming this makes Wolverine boot. - #953 South of Midnight (PPSA29642): `Unresolved import stub called: fgIsQ10xYVA[libkernel_v1][libkernel_v1.1][Func]`, repeated many times - the bundled `libc.prx` imports `sceKernelChmod` and `rmdir` in all 43 game logs I scanned ## Testing `tests/KernelFileSystemTests.cpp`: - new `TestFsyncChmod`: resolves all of the new NIDs through `InitLibKernel_1`. It checks that `sceKernelFsync` puts buffered writes in the host file, that the fsync variants accept writable, read-only and standard-stream descriptors and reject bad ones, that chmod/fchmod accept existing files and directories and reject missing, null and unmapped paths and bad descriptors (with the POSIX errno), and that `rmdir` keeps a non-empty directory, rejects a file, removes an empty directory and reports a missing one. - `CheckArchiveMount` also expects EROFS from `KernelChmod` and `KernelFchmod` on an archive member, and 0 from `KernelFsync` I couldn't run `kernel_file_system_tests` itself. It needs a Vulkan device and the full emulator, and my machine is aarch64 Linux. Here is what I did instead: - compiled the changed `fileSystem.cpp` and `libKernel.cpp` for `x86_64-linux-gnu` and `x86_64-windows-gnu` (mingw), and the updated test file for `x86_64-linux-gnu`, with clang (zig c++) at `-Wall -Wextra`. The changed lines add no warnings. - built a small native harness from `fileSystem.cpp` plus `src/common`, with stubs for network, memory and ZArchive. It runs the same checks as `TestFsyncChmod` against a temporary `/savedata0` mount, calling the `Kernel*` functions directly, and all 18 pass. 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 macOS. This touches the same test function as #1170 (`sceKernelTruncate`), but the two merge cleanly in either order. ## AI assistance An AI assistant helped me find the missing exports in the issue logs, write the change and the test, and run the builds above. I reviewed the code and the results.
sceKernelFsync was a stub that returned OK without touching the file, and
the POSIX fsync/fdatasync, fchmod and rmdir, sceKernelFdatasync,
sceKernelChmod and sceKernelFchmod were not registered at all, so callers
got the unresolved-import stub. libc.prx imports sceKernelChmod and rmdir.

- KernelFsync now lives in fileSystem.cpp and flushes the host file of a
  writable descriptor. Bad descriptors give EBADF, sockets EINVAL, and
  read-only, directory and special descriptors succeed without work.
  It backs sceKernelFsync, sceKernelFdatasync, fsync and fdatasync.
- KernelChmod and KernelFchmod validate the path or descriptor and return
  EROFS on archive mounts. Guest permissions are not emulated (stat
  reports 0777), so they do not change host permissions. The existing
  POSIX chmod export (z0dtnPxYgtg) now uses the same checks.
- KernelRmdir returns ENOTEMPTY for a non-empty directory and ENOTDIR for
  a regular file instead of EIO and ENOENT.
- New TestFsyncChmod in KernelFileSystemTests resolves every new NID and
  checks flushing, error codes and rmdir behaviour; CheckArchiveMount
  checks EROFS from chmod/fchmod on archive members.
Review on #1177 pointed out that KernelFsync and KernelFchmod used the
File from GetFile(d) after the descriptor table lock was released, so a
concurrent KernelClose could delete it during the flush or while
real_name was read.

As in #1170, do the work with the descriptor table lock held. The new
FileDescriptors::UseFile runs a callback on the descriptor's File under
that lock, and KernelFsync and KernelFchmod use it. DeleteDescriptor
takes the same lock, so the File cannot be deleted in the meantime.

The table lock alone was not enough for fsync: KernelClose closed the
host file without any lock, so the flush could still race with that
close. KernelClose now closes the host file and clears opened while
holding the file lock. The lock order stays table lock, then file lock,
and KernelClose never holds both at once.

tests: TestFsyncChmod keeps closing and reopening one descriptor on
another thread while calling fsync and fchmod on it. Every call must
return OK or EBADF.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:46:41 +00:00
github-bot closed this pull request 2026-11-26 09:46:41 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 01:18 UTC · original · edited 2026-10-08 01:41 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: 7522c853-e047-43cf-a09a-b968b1335897
📥 Commits

Reviewing files that changed from the base of the PR and between af76dcdb2d and 0ad2c61189.

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

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


📝 Walkthrough

Walkthrough

The change adds kernel implementations for fsync, chmod, and fchmod, and updates rmdir error results. POSIX wrappers and filesystem-library exports now resolve to the filesystem operations. Tests cover operation results for descriptors, paths, directories, and archive-backed files.

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 0ad2c

This change adds fsync, chmod, and fchmod support and refines the rmdir error codes. No concrete merge-blocking risk was identified. The author could not run the full test target, so normal CI should confirm it before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: flushing files through fsync and exporting chmod, fchmod, and rmdir.
Description check ✅ Passed The description directly explains the added filesystem behavior, exports, error handling, tests, and known testing limitations.
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.
  • 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-08 01:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177#issuecomment-6050180657) · edited 2026-10-08 01:41 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/1177?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `7522c853-e047-43cf-a09a-b968b1335897` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between af76dcdb2d8f7c54c614c21159465caa2ef762e4 and 0ad2c6118902acd5d5034a544a02aad53eb5ddb0. </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 (2)</summary> * tests/KernelFileSystemTests.cpp * src/kernel/fileSystem.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change adds kernel implementations for `fsync`, `chmod`, and `fchmod`, and updates `rmdir` error results. POSIX wrappers and filesystem-library exports now resolve to the filesystem operations. Tests cover operation results for descriptors, paths, directories, and archive-backed files. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"0ad2c6118902acd5d5034a544a02aad53eb5ddb0" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **⚪ Minimal** · up to `0ad2c` <!-- final_review_risk_coverage:{"sourceCommitId":"0ad2c6118902acd5d5034a544a02aad53eb5ddb0","coveredCommitId":"0ad2c6118902acd5d5034a544a02aad53eb5ddb0","kind":"reviewed"} --> This change adds fsync, chmod, and fchmod support and refines the rmdir error codes. No concrete merge-blocking risk was identified. The author could not run the full test target, so normal CI should confirm it before merge. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 13.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 4 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------ | | Title check | ✅ Passed | The title clearly summarizes the main changes: flushing files through fsync and exporting chmod, fchmod, and rmdir. | | Description check | ✅ Passed | The description directly explains the added filesystem behavior, exports, error handling, tests, and known testing limitations. | | 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. | </details> </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=1177)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [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) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 01:18 UTC · original · edited 2026-10-08 01:41 UTC
On src/kernel/fileSystem.cpp line 1471 (outdated):

@@ -1445,4 +1450,101 @@ int KYTY_SYSV_ABI KernelCheckReachability(const char* path) {
 	return KERNEL_ERROR_ENOENT;
 }
 
+int KYTY_SYSV_ABI KernelFsync(int d) {
+	PRINT_NAME();
+
+	LOGF("\t fd = %d\n", d);
+
+	if (d < 0) {
+		return KERNEL_ERROR_EBADF;
+	}
+
+	if (d < DESCRIPTOR_MIN) {
+		// The standard streams are terminals, and KernelWrite already flushes them.
+		return OK;
+	}
+
+	if (::Libs::Network::Net::IsSocket(d)) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto* file = g_files->GetFile(d);

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

Keep the descriptor alive during KernelFsync and KernelFchmod.

GetFile(d) releases the descriptor-table lock before these functions use the returned File*. If another thread calls KernelClose(d), close can delete the File while KernelFsync flushes it or KernelFchmod reads real_name. The opened check and File::mutex do not prevent this use-after-free. Pin the descriptor for the full operation, and make close wait for active operations before deletion.

✅ Addressed in commit 0ad2c61

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 01:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177#discussion_r4213656713) · edited 2026-10-08 01:41 UTC On `src/kernel/fileSystem.cpp` line 1471 (outdated): ```diff @@ -1445,4 +1450,101 @@ int KYTY_SYSV_ABI KernelCheckReachability(const char* path) { return KERNEL_ERROR_ENOENT; } +int KYTY_SYSV_ABI KernelFsync(int d) { + PRINT_NAME(); + + LOGF("\t fd = %d\n", d); + + if (d < 0) { + return KERNEL_ERROR_EBADF; + } + + if (d < DESCRIPTOR_MIN) { + // The standard streams are terminals, and KernelWrite already flushes them. + return OK; + } + + if (::Libs::Network::Net::IsSocket(d)) { + return KERNEL_ERROR_EINVAL; + } + + auto* file = g_files->GetFile(d); ``` **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Keep the descriptor alive during `KernelFsync` and `KernelFchmod`.** `GetFile(d)` releases the descriptor-table lock before these functions use the returned `File*`. If another thread calls `KernelClose(d)`, close can delete the `File` while `KernelFsync` flushes it or `KernelFchmod` reads `real_name`. The `opened` check and `File::mutex` do not prevent this use-after-free. Pin the descriptor for the full operation, and make close wait for active operations before deletion. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:65fc8956331c9794495fdac6 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 0ad2c61
Author
Owner

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 86d271bd-f8a4-4c77-9c93-e89472dfe14e
📥 Commits

Reviewing files that changed from the base of the PR and between 5a8808086a and af76dcdb2d.

📒 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; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 01:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177#pullrequestreview-5450288257) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `86d271bd-f8a4-4c77-9c93-e89472dfe14e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 5a8808086a9815b67d4822cd20cf1e8a7a05f002 and af76dcdb2d8f7c54c614c21159465caa2ef762e4. </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; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=6cad7035-5566-45f7-b7e7-5eaef4279f8e attempt=e9247bd7-a29e-4059-bb3d-ae081c269ce0 batch=1/1 -->
Author
Owner

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

@@ -1445,4 +1450,101 @@ int KYTY_SYSV_ABI KernelCheckReachability(const char* path) {
 	return KERNEL_ERROR_ENOENT;
 }
 
+int KYTY_SYSV_ABI KernelFsync(int d) {
+	PRINT_NAME();
+
+	LOGF("\t fd = %d\n", d);
+
+	if (d < 0) {
+		return KERNEL_ERROR_EBADF;
+	}
+
+	if (d < DESCRIPTOR_MIN) {
+		// The standard streams are terminals, and KernelWrite already flushes them.
+		return OK;
+	}
+
+	if (::Libs::Network::Net::IsSocket(d)) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto* file = g_files->GetFile(d);

Agreed, thanks. Fixed in "libkernel: keep the file alive in fsync and fchmod during a close".

KernelFsync and KernelFchmod now do their work with the descriptor table lock held, as in #1170. A new FileDescriptors::UseFile handles that, and since DeleteDescriptor takes the same lock, close can't delete the File mid-call. That alone didn't cover fsync, because KernelClose closed the host file without any lock, so the flush could still race with the close. KernelClose now closes the host file and clears opened under the file lock. The lock order stays table lock then file lock, and close never holds both at once.

The test now keeps closing and reopening one descriptor on another thread while calling fsync and fchmod on it, and expects only OK or EBADF. I also ran the same race in a standalone harness built from fileSystem.cpp. The previous version crashed on every run. With the table lock alone it still crashed, and with this commit it passed 25 runs of 20,000 cycles.

Other descriptor calls (read, write, lseek, fstat) still use GetFile without the table lock. That's older and I left it out of this PR.

**@⁠overlordxrz-source** on GitHub · 2026-10-08 01:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177#discussion_r4213759335) On `src/kernel/fileSystem.cpp` line 1471 (outdated): ```diff @@ -1445,4 +1450,101 @@ int KYTY_SYSV_ABI KernelCheckReachability(const char* path) { return KERNEL_ERROR_ENOENT; } +int KYTY_SYSV_ABI KernelFsync(int d) { + PRINT_NAME(); + + LOGF("\t fd = %d\n", d); + + if (d < 0) { + return KERNEL_ERROR_EBADF; + } + + if (d < DESCRIPTOR_MIN) { + // The standard streams are terminals, and KernelWrite already flushes them. + return OK; + } + + if (::Libs::Network::Net::IsSocket(d)) { + return KERNEL_ERROR_EINVAL; + } + + auto* file = g_files->GetFile(d); ``` Agreed, thanks. Fixed in "libkernel: keep the file alive in fsync and fchmod during a close". KernelFsync and KernelFchmod now do their work with the descriptor table lock held, as in #1170. A new FileDescriptors::UseFile handles that, and since DeleteDescriptor takes the same lock, close can't delete the File mid-call. That alone didn't cover fsync, because KernelClose closed the host file without any lock, so the flush could still race with the close. KernelClose now closes the host file and clears opened under the file lock. The lock order stays table lock then file lock, and close never holds both at once. The test now keeps closing and reopening one descriptor on another thread while calling fsync and fchmod on it, and expects only OK or EBADF. I also ran the same race in a standalone harness built from fileSystem.cpp. The previous version crashed on every run. With the table lock alone it still crashed, and with this commit it passed 25 runs of 20,000 cycles. Other descriptor calls (read, write, lseek, fstat) still use GetFile without the table lock. That's older and I left it out of this PR.
Author
Owner

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

@@ -1445,4 +1450,101 @@ int KYTY_SYSV_ABI KernelCheckReachability(const char* path) {
 	return KERNEL_ERROR_ENOENT;
 }
 
+int KYTY_SYSV_ABI KernelFsync(int d) {
+	PRINT_NAME();
+
+	LOGF("\t fd = %d\n", d);
+
+	if (d < 0) {
+		return KERNEL_ERROR_EBADF;
+	}
+
+	if (d < DESCRIPTOR_MIN) {
+		// The standard streams are terminals, and KernelWrite already flushes them.
+		return OK;
+	}
+
+	if (::Libs::Network::Net::IsSocket(d)) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto* file = g_files->GetFile(d);

@overlordxrz-source, thanks for the fix and the scope clarification. The supplied code addresses both races: UseFile prevents deletion during KernelFsync and KernelFchmod, and the file lock serializes the flush with host-file closure. KernelClose releases the file lock before DeleteDescriptor acquires the descriptor-table lock.

The older GetFile callers can remain outside this PR. Would you like a follow-up issue for descriptor-lifetime protection in read, write, lseek, and fstat?


✏️ Learnings added
Learnt from: overlordxrz-source
Repo: KytyPS5/KytyPS5 PR: 1177
File: src/kernel/fileSystem.cpp:0-0
Timestamp: 2026-10-08T01:42:04.617Z
Learning: In src/kernel/fileSystem.cpp, FileDescriptors::UseFile executes callbacks while holding the descriptor-table lock to protect File lifetime. Callbacks must not re-enter the descriptor table. Operations that need both locks acquire the descriptor-table lock before File::mutex; KernelClose releases File::mutex before calling DeleteDescriptor.

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 01:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177#discussion_r4213769699) On `src/kernel/fileSystem.cpp` line 1471 (outdated): ```diff @@ -1445,4 +1450,101 @@ int KYTY_SYSV_ABI KernelCheckReachability(const char* path) { return KERNEL_ERROR_ENOENT; } +int KYTY_SYSV_ABI KernelFsync(int d) { + PRINT_NAME(); + + LOGF("\t fd = %d\n", d); + + if (d < 0) { + return KERNEL_ERROR_EBADF; + } + + if (d < DESCRIPTOR_MIN) { + // The standard streams are terminals, and KernelWrite already flushes them. + return OK; + } + + if (::Libs::Network::Net::IsSocket(d)) { + return KERNEL_ERROR_EINVAL; + } + + auto* file = g_files->GetFile(d); ``` `@overlordxrz-source`, thanks for the fix and the scope clarification. The supplied code addresses both races: `UseFile` prevents deletion during `KernelFsync` and `KernelFchmod`, and the file lock serializes the flush with host-file closure. `KernelClose` releases the file lock before `DeleteDescriptor` acquires the descriptor-table lock. The older `GetFile` callers can remain outside this PR. Would you like a follow-up issue for descriptor-lifetime protection in read, write, lseek, and fstat? --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: overlordxrz-source Repo: KytyPS5/KytyPS5 PR: 1177 File: src/kernel/fileSystem.cpp:0-0 Timestamp: 2026-10-08T01:42:04.617Z Learning: In src/kernel/fileSystem.cpp, FileDescriptors::UseFile executes callbacks while holding the descriptor-table lock to protect File lifetime. Callbacks must not re-enter the descriptor table. Operations that need both locks acquire the descriptor-table lock before File::mutex; KernelClose releases File::mutex before calling DeleteDescriptor. ``` > 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=CodeRabbit%20caught%20a%20UAF%3A%20fsync%2Ffchmod%20could%20race%20close.%20Pinning%20descriptors%20and%20locking%20host-file%20close%20fixed%20it%E2%80%9425%20runs%20of%2020K%20race%20cycles%20passed.%20Try%20%40coderabbitai%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1177%23discussion_r4213656713)? 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

@⁠Nmzik on GitHub · 2026-10-08 15:01 UTC · original

No games requires proper impl

**@⁠Nmzik** on GitHub · 2026-10-08 15:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1177#issuecomment-6062728099) No games requires proper impl

Pull request closed

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