kernel: fix file/semaphore handle lifetime races #1328

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

@⁠HamsterCL on GitHub · 2026-10-09 20:44 UTC · original
HamsterCL:fix/kernel-handle-lifetime → main · +351 −44 · 5 files · 4 commits · closed without merging

Split out of #1313 (closed) as a smaller, reviewable change.

  • fileSystem: ref-count File objects so a concurrent KernelClose cannot free a file another thread is reading/writing; close the host handle under the per-file mutex; keep the registry and mount points alive on shutdown while calls are in flight.
  • semaphore: pin handles in a registry so KernelDeleteSema defers destruction until in-flight Wait/Signal/Poll/Cancel return, and wake blocked waiters on deletion.
  • memory / sys*FileIO: validate PRT aperture arguments and clamp memory-backed seeks.

Known gap: an operation that passed the opened check but has not yet taken the file mutex can still see a closed handle.

Built and ran all 53 ctest tests locally (Windows, clang-cl).

**@⁠HamsterCL** on GitHub · 2026-10-09 20:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328) `HamsterCL:fix/kernel-handle-lifetime` → `main` · +351 −44 · 5 files · 4 commits · closed without merging Split out of #1313 (closed) as a smaller, reviewable change. - **fileSystem**: ref-count `File` objects so a concurrent `KernelClose` cannot free a file another thread is reading/writing; close the host handle under the per-file mutex; keep the registry and mount points alive on shutdown while calls are in flight. - **semaphore**: pin handles in a registry so `KernelDeleteSema` defers destruction until in-flight Wait/Signal/Poll/Cancel return, and wake blocked waiters on deletion. - **memory / sys*FileIO**: validate PRT aperture arguments and clamp memory-backed seeks. Known gap: an operation that passed the `opened` check but has not yet taken the file mutex can still see a closed handle. Built and ran all 53 ctest tests locally (Windows, clang-cl).
- fileSystem: ref-count File objects so a concurrent KernelClose cannot free a
  File another thread is reading/writing; close the host handle under the
  per-file mutex; keep the registry and mount points alive on shutdown while
  calls are in flight.
- semaphore: pin handles in a registry so KernelDeleteSema defers destruction
  until in-flight Wait/Signal/Poll/Cancel calls return, and wake blocked
  waiters on deletion.
- memory/sys*FileIO: validate PRT aperture arguments and memory-backed seeks.
Read, write, pread, pwrite, lseek, fstat and getdirentries pinned the File
and then asserted it was still open. A concurrent KernelClose() could flip
opened in between and trip the assertion; return EBADF instead.
KernelClose() closes the host handle while holding file->mutex, but the
read/write/seek/stat/truncate paths checked file->opened before taking it, so
a close landing in between left them operating on a closed handle and
returning EIO instead of EBADF. Repeat the check once the mutex is held in
KernelRead, KernelWrite, KernelPread, KernelPreadv, KernelPwrite,
KernelPwritev, KernelLseek, KernelFstat and KernelFtruncate.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:53:14 +00:00
github-bot closed this pull request 2026-11-26 09:53:15 +00:00
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-09 20:45 UTC · original

@⁠coderabbitai review

**@⁠HamsterCL** on GitHub · 2026-10-09 20:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6088956145) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 20:53 UTC · original · edited 2026-10-10 14:58 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: 9cc0ee25-66a3-4c11-93b7-33ee6ab8f134


📥 Commits

Reviewing files that changed from the base of the PR and between 4bab4a5946 and b2a8ee518f.



📒 Files selected for processing (1)
  • src/kernel/fileSystem.cpp


🚧 Files skipped from review as they are similar to previous changes (1)
  • src/kernel/fileSystem.cpp


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




📝 Walkthrough
📝 Walkthrough

Walkthrough

Linux and Windows memory-backed file seeks now clamp positions to the buffer size. File descriptor lookups pin files, and deletion and shutdown defer cleanup while references remain. Kernel file operations release pins and return EBADF when a file is no longer open. Semaphore calls pin registered handles; deletion marks the semaphore, wakes waiters, and defers freeing until active calls release their pins. KernelSetPrtAperture rejects nonzero addresses above PRT_APERTURE_END.



Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to b2a8e

Concurrent file close and shutdown can terminate the process. Resolve that race before merging; shutdown can also still outlive calls that have not yet pinned a file.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 70.37% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 54 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 and concisely identifies the main change: fixing file and semaphore handle lifetime races.
Description check Passed The description directly explains the file, semaphore, memory, and file I/O changes, including the known gap and local test results.

  • Autofix · 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-09 20:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089075007) · edited 2026-10-10 14:58 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/1328?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> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `9cc0ee25-66a3-4c11-93b7-33ee6ab8f134` <hr> </dd> </dl> <hr> </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> <dl> <dd> Reviewing files that changed from the base of the PR and between 4bab4a5946092af45ab9a6c0234e0ff4c020f7ca and b2a8ee518f6565efe3cae17c21bf0e39114b7328. <hr> </dd> </dl> <hr> </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (1)</strong></summary> <dl> <dd> <dl> <dd> * `src/kernel/fileSystem.cpp` <hr> </dd> </dl> <hr> </dd> </dl> </details> <details> <summary><strong>🚧 Files skipped from review as they are similar to previous changes (1)</strong></summary> <dl> <dd> <dl> <dd> * src/kernel/fileSystem.cpp <hr> </dd> </dl> <hr> </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review. <hr> </dd> </dl> <hr> </dd> </dl> </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough Linux and Windows memory-backed file seeks now clamp positions to the buffer size. File descriptor lookups pin files, and deletion and shutdown defer cleanup while references remain. Kernel file operations release pins and return `EBADF` when a file is no longer open. Semaphore calls pin registered handles; deletion marks the semaphore, wakes waiters, and defers freeing until active calls release their pins. `KernelSetPrtAperture` rejects nonzero addresses above `PRT_APERTURE_END`. <hr> </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"b2a8ee518f6565efe3cae17c21bf0e39114b7328" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟡 Moderate** · up to `b2a8e` <!-- final_review_risk_coverage:{"sourceCommitId":"b2a8ee518f6565efe3cae17c21bf0e39114b7328","coveredCommitId":"b2a8ee518f6565efe3cae17c21bf0e39114b7328","kind":"reviewed"} --> Concurrent file close and shutdown can terminate the process. Resolve that race before merging; shutdown can also still outlive calls that have not yet pinned a file. <!-- final_review_risk_end --> <!-- 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-v1.svg" width="14" height="17" 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-v1.svg" width="14" height="17" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 70.37% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 54 functions across 5 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ 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 and concisely identifies the main change: fixing file and semaphore handle lifetime races. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the file, semaphore, memory, and file I/O changes, including the known gap and local test results. | </dd> </dl> </details> <hr> </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">Autofix</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=1328)! 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) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -579,1 +688,4 @@
}
file->opened = false;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 20:53 UTC · original · edited 2026-10-09 21:00 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '225,300p' src/kernel/fileSystem.cpp
sed -n '650,700p' src/kernel/fileSystem.cpp
rg -n '#define EXIT_IF|KernelClose\\(' src/kernel src/common

Repository: KytyPS5/KytyPS5

Length of output: 3391


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- EXIT_IF and FileGuard declarations ---'
rg -n -F -- 'EXIT_IF' src/kernel src/common || test "$?" -eq 1
rg -n -F -- 'class FileGuard' src/kernel src/common || test "$?" -eq 1
rg -n -F -- 'struct FileGuard' src/kernel src/common || test "$?" -eq 1
printf '%s\n' '--- file descriptor declarations and guard implementation ---'
sed -n '1,245p' src/kernel/fileSystem.cpp
printf '%s\n' '--- KernelClose callers and close-related paths ---'
rg -n -F -- 'KernelClose(' src || test "$?" -eq 1
rg -n -F -- 'Close(' src/kernel/fileSystem.cpp
printf '%s\n' '--- relevant declarations ---'
rg -n -F -- 'KernelClose' src/kernel
rg -n -F -- 'DeleteDescriptor' src/kernel/fileSystem.cpp

Repository: KytyPS5/KytyPS5

Length of output: 22476


🏁 Script executed:

printf '%s\n' '--- EXIT_IF definition ---'
sed -n '25,45p' src/common/assert.h
printf '%s\n' '--- public close forwarding ---'
sed -n '1398,1425p' src/libs/libKernel.cpp
printf '%s\n' '--- close-related descriptor cleanup ---'
sed -n '535,655p' src/kernel/fileSystem.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5658


🏁 Script executed:

printf '%s\n' '--- assertion handler implementations ---'
rg -n -F -- 'DbgExitIfHandler' src || test "$?" -eq 1
rg -n -F -- 'void DbgExit' src || test "$?" -eq 1
printf '%s\n' '--- KYTY_FINAL definitions ---'
rg -n -F -- 'KYTY_FINAL' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 1223


🏁 Script executed:

sed -n '15,55p' src/common/assert.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1389


Return EBADF for concurrent closes.

Both calls can pin the same File and pass the unlocked opened check. After one call sets opened to false, the other call can trigger EXIT_IF(!file->opened). If both calls pass that check before the first close completes, the second call can reach DeleteDescriptor after pending_delete is set and trigger its EXIT_IF.

In non-final builds, either assertion calls DbgExit, which invokes _Exit(321). Final builds disable these assertions, but the losing close still does not return EBADF.

Return KERNEL_ERROR_EBADF when the mutex-protected check finds that another call already closed the file. Call DeleteDescriptor only from the call that changes opened from true to false.

Suggested fix
--- "a/src/kernel/fileSystem.cpp"
+++ "b/src/kernel/fileSystem.cpp"
@@ -672,16 +672,17 @@
 		return KERNEL_ERROR_EBADF;
 	}
 
-	EXIT_IF(!file->opened);
-
 	{
 		// Read/write/seek hold file->mutex while using file->f, so closing the
 		// host handle under the same mutex waits for any in-flight operation.
 		Common::LockGuard lock(file->mutex);
+		if (!file->opened) {
+			return KERNEL_ERROR_EBADF;
+		}
 
 		if (!file->directory && file->special == SpecialFile::None) {
 			file->f.Close();
 		}
 
 		file->opened = false;
 	}

✅ Addressed in commit 3b2ca4a

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 20:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#discussion_r4234462959) · edited 2026-10-09 21:00 UTC **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '225,300p' src/kernel/fileSystem.cpp sed -n '650,700p' src/kernel/fileSystem.cpp rg -n '#define EXIT_IF|KernelClose\\(' src/kernel src/common ``` Repository: KytyPS5/KytyPS5 Length of output: 3391 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- EXIT_IF and FileGuard declarations ---' rg -n -F -- 'EXIT_IF' src/kernel src/common || test "$?" -eq 1 rg -n -F -- 'class FileGuard' src/kernel src/common || test "$?" -eq 1 rg -n -F -- 'struct FileGuard' src/kernel src/common || test "$?" -eq 1 printf '%s\n' '--- file descriptor declarations and guard implementation ---' sed -n '1,245p' src/kernel/fileSystem.cpp printf '%s\n' '--- KernelClose callers and close-related paths ---' rg -n -F -- 'KernelClose(' src || test "$?" -eq 1 rg -n -F -- 'Close(' src/kernel/fileSystem.cpp printf '%s\n' '--- relevant declarations ---' rg -n -F -- 'KernelClose' src/kernel rg -n -F -- 'DeleteDescriptor' src/kernel/fileSystem.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 22476 --- 🏁 Script executed: ```bash printf '%s\n' '--- EXIT_IF definition ---' sed -n '25,45p' src/common/assert.h printf '%s\n' '--- public close forwarding ---' sed -n '1398,1425p' src/libs/libKernel.cpp printf '%s\n' '--- close-related descriptor cleanup ---' sed -n '535,655p' src/kernel/fileSystem.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5658 --- 🏁 Script executed: ```bash printf '%s\n' '--- assertion handler implementations ---' rg -n -F -- 'DbgExitIfHandler' src || test "$?" -eq 1 rg -n -F -- 'void DbgExit' src || test "$?" -eq 1 printf '%s\n' '--- KYTY_FINAL definitions ---' rg -n -F -- 'KYTY_FINAL' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 1223 --- 🏁 Script executed: ```bash sed -n '15,55p' src/common/assert.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1389 --- </details> **Return `EBADF` for concurrent closes.** Both calls can pin the same `File` and pass the unlocked `opened` check. After one call sets `opened` to `false`, the other call can trigger `EXIT_IF(!file->opened)`. If both calls pass that check before the first close completes, the second call can reach `DeleteDescriptor` after `pending_delete` is set and trigger its `EXIT_IF`. In non-final builds, either assertion calls `DbgExit`, which invokes `_Exit(321)`. Final builds disable these assertions, but the losing close still does not return `EBADF`. Return `KERNEL_ERROR_EBADF` when the mutex-protected check finds that another call already closed the file. Call `DeleteDescriptor` only from the call that changes `opened` from `true` to `false`. <details> <summary>Suggested fix</summary> ```diff --- "a/src/kernel/fileSystem.cpp" +++ "b/src/kernel/fileSystem.cpp" @@ -672,16 +672,17 @@ return KERNEL_ERROR_EBADF; } - EXIT_IF(!file->opened); - { // Read/write/seek hold file->mutex while using file->f, so closing the // host handle under the same mutex waits for any in-flight operation. Common::LockGuard lock(file->mutex); + if (!file->opened) { + return KERNEL_ERROR_EBADF; + } if (!file->directory && file->special == SpecialFile::None) { file->f.Close(); } file->opened = false; } ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3ef3637045753807153a3292 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 3b2ca4a
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 20:53 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: 47baac6f-5a05-4bfa-993c-26a9814d2f19
📥 Commits

Reviewing files that changed from the base of the PR and between 59183dbfa8 and 42e3b957e1c17e73516a04efca2b00cb0765d572.

📒 Files selected for processing (5)
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/memory.cpp
  • src/kernel/semaphore.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-09 20:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#pullrequestreview-5475255885) · **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**: `47baac6f-5a05-4bfa-993c-26a9814d2f19` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 59183dbfa81ed7efdff6069177fed50de0552725 and 42e3b957e1c17e73516a04efca2b00cb0765d572. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/memory.cpp` * `src/kernel/semaphore.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=a238afac-c08c-4bdf-b104-7183a3127b9f attempt=79aeecf0-fbd0-4b68-89fc-355b3a14c361 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 20:56 UTC · original

⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 20:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089115561) <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:b9e11d14da01d1972c8a54c2c0475eac35b463e6c36ee080c4a31f9ad4f92943 --> <details> <summary>⚠️ Action not completed</summary> Already reviewed the last commit. Use `@coderabbitai full review` to rerun a review of the entire changeset. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-09 20:58 UTC · original

@⁠coderabbitai review

**@⁠HamsterCL** on GitHub · 2026-10-09 20:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089139636) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 20:58 UTC · original

⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 20:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089141512) <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:41b89a87be06d0857c7a41926fb42cd04a5e93a65d884b09b8e73d3b2d72eeb8 --> <details> <summary>⚠️ Action not completed</summary> Already reviewed the last commit. Use `@coderabbitai full review` to rerun a review of the entire changeset. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-09 21:00 UTC · original

@⁠coderabbitai full review

**@⁠HamsterCL** on GitHub · 2026-10-09 21:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089177982) @⁠coderabbitai full review
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-09 21:05 UTC · original

@⁠coderabbitai review

**@⁠HamsterCL** on GitHub · 2026-10-09 21:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089240313) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 21:12 UTC · original · edited 2026-10-09 21:14 UTC

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089338906) · edited 2026-10-09 21:14 UTC <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:09b3b3527d2615b1167489bc500904904517bd8b30ebe97b5ad58e662a8c129f --> <details> <summary>✅ Action performed</summary> Review finished. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>
@ -633,1 +747,3 @@
EXIT_IF(!file->opened);
// A concurrent KernelClose() may already have closed this descriptor.
if (!file->opened) {
return KERNEL_ERROR_EBADF;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 21:14 UTC · original · edited 2026-10-10 13:04 UTC

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Check opened under the file mutex before using the host handle.

KernelClose() can close the host handle after this check but before KernelRead() acquires file->mutex. KernelRead() then calls Tell(), Size(), and Read() on the closed handle and can return EIO instead of EBADF. The same check-before-lock pattern affects KernelWrite(), KernelPread(), KernelPwrite(), KernelLseek(), and KernelFstat(); the pinned vectored I/O and truncate paths also use the handle after an unlocked check. Check opened while holding the mutex, before each host-handle operation.

✅ Addressed in commit b2a8ee5

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 21:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#discussion_r4234607123) · edited 2026-10-10 13:04 UTC **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** **Check `opened` under the file mutex before using the host handle.** `KernelClose()` can close the host handle after this check but before `KernelRead()` acquires `file->mutex`. `KernelRead()` then calls `Tell()`, `Size()`, and `Read()` on the closed handle and can return `EIO` instead of `EBADF`. The same check-before-lock pattern affects `KernelWrite()`, `KernelPread()`, `KernelPwrite()`, `KernelLseek()`, and `KernelFstat()`; the pinned vectored I/O and truncate paths also use the handle after an unlocked check. Check `opened` while holding the mutex, before each host-handle operation. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3637c8fb00a1a6f550395aca --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit b2a8ee5
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 21:14 UTC · original · reviewed

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 Major · Allow deletion after shutdown marks a pinned file pending. · fileSystem.cpp:237

src/kernel/fileSystem.cpp:237
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Allow deletion after shutdown marks a pinned file pending.

If CloseAll() marks a pinned file pending_delete, KernelClose() can close that file and then call DeleteDescriptor(). This assertion then terminates the process instead of letting the existing pin defer destruction. A failing KernelOpen() setup can reach the same assertion. Make DeleteDescriptor() handle a file already marked pending by shutdown.

🟠 Major · Do not treat zero file pins as proof that no file-system call is active. · fileSystem.cpp:478-482

src/kernel/fileSystem.cpp:478-482
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Do not treat zero file pins as proof that no file-system call is active.

KernelStat() can be inside MountPoints::ResolvePath() without a file pin. KernelOpen() also has a gap between CreateDescriptor() and its pinned GetFile() lookup. If shutdown runs during either call, CloseAllFiles() can report success and Shutdown() can delete state that the call still uses; the open path can instead reach its EXIT_IF(file == nullptr). Coordinate shutdown with admission and completion of all file-system calls, not only calls that already hold a File pin.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cbd9cf0a-d0bd-4db8-b0f3-13dcfb7ea6ea
📥 Commits

Reviewing files that changed from the base of the PR and between 42e3b957e1c17e73516a04efca2b00cb0765d572 and 7c6534c33136a5a55ad0f740d273f80fe95809bb.

📒 Files selected for processing (1)
  • src/kernel/fileSystem.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 21:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#pullrequestreview-5475420971) · **reviewed** **Actionable comments posted: 1** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (2)** > > <details> > <summary><strong>🟠 Major</strong> · Allow deletion after shutdown marks a pinned file pending. · <code>fileSystem.cpp:237</code></summary><blockquote> > > `src/kernel/fileSystem.cpp:237` > **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** > > **Allow deletion after shutdown marks a pinned file pending.** > > If `CloseAll()` marks a pinned file `pending_delete`, `KernelClose()` can close that file and then call `DeleteDescriptor()`. This assertion then terminates the process instead of letting the existing pin defer destruction. A failing `KernelOpen()` setup can reach the same assertion. Make `DeleteDescriptor()` handle a file already marked pending by shutdown. > > <!-- cr-comment:v1:5be1b11eaf5132a26d7bdd77 --> > > </blockquote></details> > <details> > <summary><strong>🟠 Major</strong> · Do not treat zero file pins as proof that no file-system call is active. · <code>fileSystem.cpp:478-482</code></summary><blockquote> > > `src/kernel/fileSystem.cpp:478-482` > **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** > > **Do not treat zero file pins as proof that no file-system call is active.** > > `KernelStat()` can be inside `MountPoints::ResolvePath()` without a file pin. `KernelOpen()` also has a gap between `CreateDescriptor()` and its pinned `GetFile()` lookup. If shutdown runs during either call, `CloseAllFiles()` can report success and `Shutdown()` can delete state that the call still uses; the open path can instead reach its `EXIT_IF(file == nullptr)`. Coordinate shutdown with admission and completion of all file-system calls, not only calls that already hold a `File` pin. > > <!-- cr-comment:v1:ab493033a55a99bfb38dbe3a --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `cbd9cf0a-d0bd-4db8-b0f3-13dcfb7ea6ea` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 42e3b957e1c17e73516a04efca2b00cb0765d572 and 7c6534c33136a5a55ad0f740d273f80fe95809bb. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/kernel/fileSystem.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=17c1eed7-3e5b-49dd-8855-01f5e0722a6f attempt=8772e04f-8ab0-4e9e-851e-35b36a5f2ced batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 21:16 UTC · original

⚠️ Action not completed

Review rate limited.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 27 minutes.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 21:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6089404509) <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:085b6096e8dfbe28dc66238e27c74012799aa377b6457cdfd0fbfea568cfa631 --> <details> <summary>⚠️ Action not completed</summary> Review rate limited. --- Your included review limit is currently reached under our [Fair Usage Limits Policy](https://docs.coderabbit.ai/management/plans#fair-usage-limits-policy). This review may still proceed through usage-based billing if eligible. Your next included review will be available in 27 minutes. </details>
Author
Owner

@⁠theantipopau on GitHub · 2026-10-10 01:46 UTC · original

Evidence from a Windows fork build (AMD Ryzen, clang-cl, 42e3b957+3b2ca4ac+7c6534c3 cherry-picked onto current main): all three commits apply with only mechanical conflicts in fileSystem.cpp (the fork carries std::shared_ptr<File> descriptor handles plus test bodies from the #1140-adjacent work; the shared_ptr registry already provides much of commit 1's File lifetime fix there, and commits 2-3 applied as intended).

  • Full build passes with zero errors; kernel_file_system, controller_settings, memory_tracker, page_manager, archive_file, windows_file_read all green (6/6) on Windows.
  • The concurrent-close race the series targets is exercised by our fork's CheckConcurrentCloseDuringRead case and passes on this build.
  • Real-game smoke: Hollow Knight: Silksong, Terminator 2D: No Fate and Paw Patrol World each survive a 120-180s timeout run (exit 124) with no faults in the log.

Lighting up kernel_file_system in the CI ctest subsets (.github/workflows/build.yml) would keep this race covered on every PR — happy to see that land.

**@⁠theantipopau** on GitHub · 2026-10-10 01:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6092339540) Evidence from a Windows fork build (AMD Ryzen, clang-cl, `42e3b957`+`3b2ca4ac`+`7c6534c3` cherry-picked onto current main): all three commits apply with only mechanical conflicts in `fileSystem.cpp` (the fork carries `std::shared_ptr<File>` descriptor handles plus test bodies from the #1140-adjacent work; the shared_ptr registry already provides much of commit 1's File lifetime fix there, and commits 2-3 applied as intended). - Full build passes with zero errors; `kernel_file_system`, `controller_settings`, `memory_tracker`, `page_manager`, `archive_file`, `windows_file_read` all green (6/6) on Windows. - The concurrent-close race the series targets is exercised by our fork's `CheckConcurrentCloseDuringRead` case and passes on this build. - Real-game smoke: Hollow Knight: Silksong, Terminator 2D: No Fate and Paw Patrol World each survive a 120-180s timeout run (exit 124) with no faults in the log. Lighting up `kernel_file_system` in the CI ctest subsets (`.github/workflows/build.yml`) would keep this race covered on every PR — happy to see that land.
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-10 02:28 UTC · original

Thanks for cherry-picking this and for the detailed evidence: the passing build, the six ctest suites, your concurrent close-during-read test and the 120-180s smoke runs on three games are all useful. Understood on the shared_ptr overlap. If your fork already holds descriptors that way, part of the first commit is likely redundant there. This PR mainly targets main, which still uses raw File* with a ref_count. On CI: a kernel_file_system ctest target already exists on main (kernel_file_system_tests), but it is not in the -R subsets in build.yml for Windows, macOS or Linux. Adding it would be a reasonable separate change, so I will keep it out of this PR.

**@⁠HamsterCL** on GitHub · 2026-10-10 02:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6092745100) Thanks for cherry-picking this and for the detailed evidence: the passing build, the six ctest suites, your concurrent close-during-read test and the 120-180s smoke runs on three games are all useful. Understood on the shared_ptr<File> overlap. If your fork already holds descriptors that way, part of the first commit is likely redundant there. This PR mainly targets main, which still uses raw File* with a ref_count. On CI: a kernel_file_system ctest target already exists on main (kernel_file_system_tests), but it is not in the -R subsets in build.yml for Windows, macOS or Linux. Adding it would be a reasonable separate change, so I will keep it out of this PR.
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-10 02:30 UTC · original

Rebased onto current main. @⁠coderabbitai review

**@⁠HamsterCL** on GitHub · 2026-10-10 02:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6092760783) Rebased onto current main. @⁠coderabbitai review
Author
Owner

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

@HamsterCL I’ll request a review of the rebased changes.

⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-10 02:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6092768201) <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:90125122e28b246217c00d5e8e9634b93eb21cbe0f21dd8b0d2e4fdc6fc8a7b7 --> `@HamsterCL` I’ll request a review of the rebased changes. <details> <summary>⚠️ Action not completed</summary> Already reviewed the last commit. Use `@coderabbitai full review` to rerun a review of the entire changeset. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-10 14:46 UTC · original

@⁠theantipopau thanks for testing the series on a Windows fork build and for the CI suggestion.

I opened #1371 to run kernel_file_system in the ctest subsets. To make that possible I had to change the test itself, since it aborted on hosted runners without a Vulkan device:

  • the hidden Vulkan window is now optional, and only the NpCommerce dialog case is skipped without it;
  • Memory::InvalidateMemory returns when no GPU resources are installed;
  • two Net cases were adjusted for host differences (Windows reports EINVAL for unknown socket options, macOS reports the flag value for SO_BROADCAST).

CI is green on Linux, Windows and macOS with kernel_file_system included. I also pushed a follow-up to this PR that re-checks opened under the file mutex in the read/write/seek/stat/truncate paths, per CodeRabbit.

**@⁠HamsterCL** on GitHub · 2026-10-10 14:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6098701817) @⁠theantipopau thanks for testing the series on a Windows fork build and for the CI suggestion. I opened #1371 to run `kernel_file_system` in the ctest subsets. To make that possible I had to change the test itself, since it aborted on hosted runners without a Vulkan device: - the hidden Vulkan window is now optional, and only the NpCommerce dialog case is skipped without it; - `Memory::InvalidateMemory` returns when no GPU resources are installed; - two Net cases were adjusted for host differences (Windows reports `EINVAL` for unknown socket options, macOS reports the flag value for `SO_BROADCAST`). CI is green on Linux, Windows and macOS with `kernel_file_system` included. I also pushed a follow-up to this PR that re-checks `opened` under the file mutex in the read/write/seek/stat/truncate paths, per CodeRabbit.
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-10 14:58 UTC · original

@⁠coderabbitai review

**@⁠HamsterCL** on GitHub · 2026-10-10 14:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6098809637) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-10 14:58 UTC · original

⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-10 14:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1328#issuecomment-6098810781) <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:300c93dd1966f61a8ee3beda3f4a5844afc668f8d557ae0ad1dafd7a176f329f --> <details> <summary>⚠️ Action not completed</summary> Already reviewed the last commit. Use `@coderabbitai full review` to rerun a review of the entire changeset. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>

Pull request closed

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