kernel: implement sceKernelWritev #1401

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

@⁠HamsterCL on GitHub · 2026-10-11 03:35 UTC · original
HamsterCL:fix/kernel-writev-truncate → main · +159 −0 · 4 files · 4 commits · closed without merging

Problem

EA SPORTS FC 27 (PPSA34015) imports sceKernelWritev (kAt6VDbHmro, libkernel). It is not implemented, so it falls into the unresolved-import stub, which returns 0 and writes nothing. This is visible in the log as Unresolved import stub called for that NID (3 calls in one run).

The game uses writev() to write the INDEX file of its settings save data. With the stub, the call reports 0 bytes written, so the file stays empty:

_SaveData/PPSA34015/Settings.../DATA   768774 bytes
_SaveData/PPSA34015/Settings.../INDEX       0 bytes

On the next launch the game shows an in-game error, Personal Setting 1 failed to load.

Changes

  • sceKernelWritev(fd, iov, iovcnt) in src/kernel/fileSystem.cpp, registered in libkernel_v1 next to the other file functions. It validates the vectors with the same helper sceKernelPwritev uses (IOV_MAX, overflow-safe total, null base only with zero length, null array is EFAULT), then writes at the descriptor position under the file mutex, honours O_APPEND and sync writes, and stops at the first short write. It returns the total written or a negative kernel error. fd 1 and 2 go to stdout/stderr as in sceKernelWrite. On a socket the vectors are gathered and sent as a single message, so a datagram socket does not turn one writev() into several datagrams. Directories, special files, read-only and unknown descriptors return the usual errors.
  • TestWritev in tests/KernelFileSystemTests.cpp: multi-iovec writes, an empty iovec, iovcnt 0, position advance, O_APPEND, null array and null base, iovcnt of -1 and 1025, a length overflow, and bad and read-only descriptors.

sceKernelTruncate (WlyEA-sLDf0), which FC 27 also imports, is deliberately left out of this PR because #1170 already covers it.

Testing

  • kernel_file_system_tests builds and links on Windows (clang-cl, Release) on top of current main. TestWritev runs before the point where the binary stops.
  • On main that binary still aborts later in the run, in CheckSocketWakeup, with Net unknown socket options return protocol-option errors. That check is unrelated to this change (it is not in the CI test subsets, so it is not exercised there).
  • Manual test with FC 27 on Windows 11, i5-12400F, RTX 3060 Ti, --amd-cpu: after this change INDEX is written with 240 bytes (Writev 240 bytes ... INDEX in the log, next to Writev 768774 bytes ... DATA), kAt6VDbHmro no longer appears as an unresolved import, and the next launch no longer shows Personal Setting 1 failed to load.
  • Not verified: Linux and macOS builds; any other game that uses writev.

Notes

The game still asks for its initial setup again on the next launch in my runs. In the log the settings are written only once, right after the first boot (defaults), and no further save is made while I go through the setup, so I believe that is caused by the setup never completing (the game stops at an online-services message), not by this change.

AI use

I used AI assistance (Claude Code) to track down the missing imports, resolve their NIDs and prepare the implementation and tests at my direction. I reviewed the diff, including the validation, locking and error paths, and I ran the manual FC 27 test described above.

**@⁠HamsterCL** on GitHub · 2026-10-11 03:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401) `HamsterCL:fix/kernel-writev-truncate` → `main` · +159 −0 · 4 files · 4 commits · closed without merging ## Problem EA SPORTS FC 27 (PPSA34015) imports `sceKernelWritev` (`kAt6VDbHmro`, libkernel). It is not implemented, so it falls into the unresolved-import stub, which returns 0 and writes nothing. This is visible in the log as `Unresolved import stub called` for that NID (3 calls in one run). The game uses `writev()` to write the `INDEX` file of its settings save data. With the stub, the call reports 0 bytes written, so the file stays empty: ``` _SaveData/PPSA34015/Settings.../DATA 768774 bytes _SaveData/PPSA34015/Settings.../INDEX 0 bytes ``` On the next launch the game shows an in-game error, `Personal Setting 1 failed to load`. ## Changes - `sceKernelWritev(fd, iov, iovcnt)` in `src/kernel/fileSystem.cpp`, registered in `libkernel_v1` next to the other file functions. It validates the vectors with the same helper `sceKernelPwritev` uses (IOV_MAX, overflow-safe total, null base only with zero length, null array is EFAULT), then writes at the descriptor position under the file mutex, honours `O_APPEND` and sync writes, and stops at the first short write. It returns the total written or a negative kernel error. fd 1 and 2 go to stdout/stderr as in `sceKernelWrite`. On a socket the vectors are gathered and sent as a single message, so a datagram socket does not turn one `writev()` into several datagrams. Directories, special files, read-only and unknown descriptors return the usual errors. - `TestWritev` in `tests/KernelFileSystemTests.cpp`: multi-iovec writes, an empty iovec, `iovcnt` 0, position advance, `O_APPEND`, null array and null base, `iovcnt` of -1 and 1025, a length overflow, and bad and read-only descriptors. `sceKernelTruncate` (`WlyEA-sLDf0`), which FC 27 also imports, is deliberately left out of this PR because #1170 already covers it. ## Testing - `kernel_file_system_tests` builds and links on Windows (clang-cl, Release) on top of current `main`. `TestWritev` runs before the point where the binary stops. - On `main` that binary still aborts later in the run, in `CheckSocketWakeup`, with `Net unknown socket options return protocol-option errors`. That check is unrelated to this change (it is not in the CI test subsets, so it is not exercised there). - Manual test with FC 27 on Windows 11, i5-12400F, RTX 3060 Ti, `--amd-cpu`: after this change `INDEX` is written with 240 bytes (`Writev 240 bytes ... INDEX` in the log, next to `Writev 768774 bytes ... DATA`), `kAt6VDbHmro` no longer appears as an unresolved import, and the next launch no longer shows `Personal Setting 1 failed to load`. - Not verified: Linux and macOS builds; any other game that uses `writev`. ## Notes The game still asks for its initial setup again on the next launch in my runs. In the log the settings are written only once, right after the first boot (defaults), and no further save is made while I go through the setup, so I believe that is caused by the setup never completing (the game stops at an online-services message), not by this change. ## AI use I used AI assistance (Claude Code) to track down the missing imports, resolve their NIDs and prepare the implementation and tests at my direction. I reviewed the diff, including the validation, locking and error paths, and I ran the manual FC 27 test described above.
EA SPORTS FC 27 imports sceKernelWritev (kAt6VDbHmro). It was
unresolved and fell into the unresolved-import stub, which returns 0
without writing anything, so a writev() of the save data INDEX file
reported zero bytes written and the file stayed empty.

sceKernelWritev validates the iovecs like sceKernelPwritev (IOV_MAX,
overflow-safe total, null bases) and writes at the descriptor position
under the file mutex, honouring O_APPEND and sync writes. It stops at
the first short write and returns the total written or a negative
kernel error. Descriptors 1 and 2 are handled like sceKernelWrite. On
a socket the vectors are gathered and sent as a single message, so a
datagram socket does not split one writev() into several datagrams.
The socket path of sceKernelWritev gathers the iovecs into one buffer,
and the validated total can be close to INT_MAX. An allocation failure
would throw std::bad_alloc across the guest ABI boundary. Catch it and
return KERNEL_ERROR_ENOMEM instead.
The project builds with -fno-exceptions, so the try/catch added for allocation failure does not compile on clang. Use a non-throwing allocation instead and keep returning ENOMEM.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:55:49 +00:00
github-bot closed this pull request 2026-11-26 09:55:49 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 03:38 UTC · original · edited 2026-10-11 12:35 UTC

Review in Change Stack →

📝 Walkthrough

Walkthrough

The change adds and exports KernelWritev. The implementation validates iovec entries and writes to standard streams, sockets, or regular files. Tests cover write ordering, byte counts, descriptor position, append behavior, and error cases.

Suggested reviewers: aspenini


Priority: ⬇️ Low

Change: Bug fix

Merge Risk: 🟡 Moderate · up to bd8dd

Concurrent write and close can crash the process. Coordinate file lifetime across those operations before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check Passed The description clearly explains the missing sceKernelWritev implementation, the changes, tests, observed results, and out-of-scope work.
Title check Passed The title clearly and concisely identifies the main change: implementing sceKernelWritev in the kernel.
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.

  • 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-11 03:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#issuecomment-6105092513) · edited 2026-10-11 12:35 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/1401?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 --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough The change adds and exports `KernelWritev`. The implementation validates iovec entries and writes to standard streams, sockets, or regular files. Tests cover write ordering, byte counts, descriptor position, append behavior, and error cases. **Suggested reviewers:** `aspenini` <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"bd8dd6a0d7bad9a4cd65713446c81691658c0d89" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟡 Moderate** · up to `bd8dd` <!-- final_review_risk_coverage:{"sourceCommitId":"bd8dd6a0d7bad9a4cd65713446c81691658c0d89","coveredCommitId":"bd8dd6a0d7bad9a4cd65713446c81691658c0d89","kind":"reviewed"} --> Concurrent write and close can crash the process. Coordinate file lifetime across those operations before merging. <!-- 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 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 4 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 | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------ | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the missing `sceKernelWritev` implementation, the changes, tests, observed results, and out-of-scope work. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: implementing `sceKernelWritev` in the kernel. | | 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. | </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=1401)! 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 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 03:38 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: 944d2c38-e7e7-4c30-9619-ef68e440e02e
📥 Commits

Reviewing files that changed from the base of the PR and between 730e1a3cf3 and 2358b21adcac0781b8ef2e799d170b2cb7dce61b.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 03:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#pullrequestreview-5481754706) · **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**: `944d2c38-e7e7-4c30-9619-ef68e440e02e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 730e1a3cf39d50c787d477e813e0bef92006a063 and 2358b21adcac0781b8ef2e799d170b2cb7dce61b. </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; 4 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=fa20d2d0-a5ac-4891-b5c7-4c157a43fc31 attempt=4d8f5b4f-7f4f-415c-8f8e-0e05a3ca614c batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 03:38 UTC · original · edited 2026-10-11 12:30 UTC
On src/kernel/fileSystem.cpp line 1064 (outdated):

@@ -1022,6 +1022,102 @@ int64_t KYTY_SYSV_ABI KernelPwritev(int d, const KernelIovec* iov, int iovcnt, i
 	return bytes_written;
 }
 
+int64_t KYTY_SYSV_ABI KernelWritev(int d, const KernelIovec* iov, int iovcnt) {
+	PRINT_NAME();
+
+	std::vector<KernelIovec> buffers;
+	size_t                   total = 0;
+	const int                error = ValidateIovecs(iov, iovcnt, 0, &buffers, &total);
+	if (error != OK) {
+		return error;
+	}
+
+	if (d == 1 || d == 2) {
+		auto*   out     = (d == 1 ? stdout : stderr);
+		int64_t written = 0;
+		bool    ok      = true;
+		for (const auto& buffer: buffers) {
+			if (buffer.iov_len == 0) {
+				continue;
+			}
+			const auto count = std::fwrite(buffer.iov_base, 1, buffer.iov_len, out);
+			written += static_cast<int64_t>(count);
+			if (count != buffer.iov_len) {
+				ok = false;
+				break;
+			}
+		}
+		ok = (std::fflush(out) == 0) && ok;
+		return (ok ? written : KERNEL_ERROR_EIO);
+	}
+
+	if (d < DESCRIPTOR_MIN) {
+		return KERNEL_ERROR_EBADF;
+	}
+
+	if (::Libs::Network::Net::IsSocket(d)) {
+		int64_t sent = 0;
+		for (const auto& buffer: buffers) {
+			if (buffer.iov_len == 0) {
+				continue;
+			}
+			const auto result = ::Libs::Network::Net::Send(d, buffer.iov_base, buffer.iov_len, 0);

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

Send all vectors as one socket message.

If d is a datagram socket, each Net::Send call sends a separate datagram. Two nonempty vectors therefore produce two datagrams instead of one gathered message. Use one vectored socket send, or gather the buffers before one send. (man7.org)

✅ Addressed in commit 8ed0812

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 03:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#discussion_r4240129998) · edited 2026-10-11 12:30 UTC On `src/kernel/fileSystem.cpp` line 1064 (outdated): ```diff @@ -1022,6 +1022,102 @@ int64_t KYTY_SYSV_ABI KernelPwritev(int d, const KernelIovec* iov, int iovcnt, i return bytes_written; } +int64_t KYTY_SYSV_ABI KernelWritev(int d, const KernelIovec* iov, int iovcnt) { + PRINT_NAME(); + + std::vector<KernelIovec> buffers; + size_t total = 0; + const int error = ValidateIovecs(iov, iovcnt, 0, &buffers, &total); + if (error != OK) { + return error; + } + + if (d == 1 || d == 2) { + auto* out = (d == 1 ? stdout : stderr); + int64_t written = 0; + bool ok = true; + for (const auto& buffer: buffers) { + if (buffer.iov_len == 0) { + continue; + } + const auto count = std::fwrite(buffer.iov_base, 1, buffer.iov_len, out); + written += static_cast<int64_t>(count); + if (count != buffer.iov_len) { + ok = false; + break; + } + } + ok = (std::fflush(out) == 0) && ok; + return (ok ? written : KERNEL_ERROR_EIO); + } + + if (d < DESCRIPTOR_MIN) { + return KERNEL_ERROR_EBADF; + } + + if (::Libs::Network::Net::IsSocket(d)) { + int64_t sent = 0; + for (const auto& buffer: buffers) { + if (buffer.iov_len == 0) { + continue; + } + const auto result = ::Libs::Network::Net::Send(d, buffer.iov_base, buffer.iov_len, 0); ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **🏗️ Heavy lift** **Send all vectors as one socket message.** If `d` is a datagram socket, each `Net::Send` call sends a separate datagram. Two nonempty vectors therefore produce two datagrams instead of one gathered message. Use one vectored socket send, or gather the buffers before one send. ([man7.org](https://man7.org/linux/man-pages/man3/writev.3p.html?utm_source=openai)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:001b469d0876707238fe9d44 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 8ed0812
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 03:38 UTC · original
On src/kernel/fileSystem.cpp line 1364 (outdated):

@@ -1238,6 +1334,55 @@ 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_EINVAL;
+	}
+
+	if (length < 0) {
+		return KERNEL_ERROR_EINVAL;
+	}
+
+	auto real_file_name = g_mount_points->ResolvePath(path);
+	if (real_file_name.empty()) {
+		return KERNEL_ERROR_ENOENT;
+	}
+	if (Common::IsArchivePath(real_file_name)) {
+		return KERNEL_ERROR_EROFS;
+	}
+	if (Common::File::IsDirectoryExisting(real_file_name)) {
+		return KERNEL_ERROR_EISDIR;
+	}
+	if (!Common::File::IsFileExisting(real_file_name)) {
+		return KERNEL_ERROR_ENOENT;
+	}
+
+	bool ok = false;
+
+	auto* open_file = g_files->GetFile(real_file_name);

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

Keep the selected file alive through truncation.

GetFile(real_file_name) returns a raw pointer after releasing the descriptor-table lock. If another thread closes that descriptor, KernelClose can delete the file before this function checks opened or acquires open_file->mutex. A path-based truncate can then access freed memory. Coordinate lookup, truncation, and close through shared ownership or a descriptor-table lifetime lock.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 03:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#discussion_r4240130001) On `src/kernel/fileSystem.cpp` line 1364 (outdated): ```diff @@ -1238,6 +1334,55 @@ 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_EINVAL; + } + + if (length < 0) { + return KERNEL_ERROR_EINVAL; + } + + auto real_file_name = g_mount_points->ResolvePath(path); + if (real_file_name.empty()) { + return KERNEL_ERROR_ENOENT; + } + if (Common::IsArchivePath(real_file_name)) { + return KERNEL_ERROR_EROFS; + } + if (Common::File::IsDirectoryExisting(real_file_name)) { + return KERNEL_ERROR_EISDIR; + } + if (!Common::File::IsFileExisting(real_file_name)) { + return KERNEL_ERROR_ENOENT; + } + + bool ok = false; + + auto* open_file = g_files->GetFile(real_file_name); ``` **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Keep the selected file alive through truncation.** `GetFile(real_file_name)` returns a raw pointer after releasing the descriptor-table lock. If another thread closes that descriptor, `KernelClose` can delete the file before this function checks `opened` or acquires `open_file->mutex`. A path-based truncate can then access freed memory. Coordinate lookup, truncation, and close through shared ownership or a descriptor-table lifetime lock. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:91eb52bcf630459f19edafd8 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1025,0 +1077,4 @@
}
const auto result = ::Libs::Network::Net::Send(d, gathered.get(), gathered_size, 0);
return (result < 0 ? PosixToKernel(*Posix::GetErrorAddr()) : static_cast<int64_t>(result));
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 03:45 UTC · original · edited 2026-10-11 03:48 UTC

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '990,1125p' src/kernel/fileSystem.cpp
rg -n 'ValidateIovecs|bad_alloc|KernelWritev|Net::Send' src/kernel/fileSystem.cpp src/libs/libKernel.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4920


🏁 Script executed:

set -e
printf '%s\n' '--- validation and ABI definitions ---'
sed -n '760,860p' src/kernel/fileSystem.cpp
printf '%s\n' '--- iovec and error definitions ---'
rg -n -F --glob '*.{h,hpp,cpp}' 'struct KernelIovec|class KernelIovec|using KernelIovec|KERNEL_ERROR_ENOMEM|KERNEL_ERROR_EINVAL|KYTY_SYSV_ABI|DESCRIPTOR_MIN' src include 2>/dev/null || true
printf '%s\n' '--- socket send declarations and implementation references ---'
rg -n -F --glob '*.{h,hpp,cpp}' 'Net::Send|int64_t Send|uint64_t Send|Send(int' src 2>/dev/null || true
printf '%s\n' '--- exception handling around exported kernel calls ---'
rg -n -F --glob '*.{h,hpp,cpp}' 'catch (const std::bad_alloc|std::bad_alloc|catch (...)|try {' src/kernel src/libs include 2>/dev/null || true

Repository: KytyPS5/KytyPS5

Length of output: 3014


🏁 Script executed:

set -e
sed -n '760,860p' src/kernel/fileSystem.cpp
rg -n -F --glob '*.{h,hpp,cpp}' 'struct KernelIovec|class KernelIovec|using KernelIovec|KERNEL_ERROR_ENOMEM|KYTY_SYSV_ABI|DESCRIPTOR_MIN' src include 2>/dev/null || true
rg -n -F --glob '*.{h,hpp,cpp}' 'Net::Send|int64_t Send|uint64_t Send|Send(int' src 2>/dev/null || true
rg -n -F --glob '*.{h,hpp,cpp}' 'catch (const std::bad_alloc|std::bad_alloc|catch (...)|try {' src/kernel src/libs include 2>/dev/null || true

Repository: KytyPS5/KytyPS5

Length of output: 2820


🏁 Script executed:

set -e
printf '%s\n' '--- KernelIovec references and definitions ---'
rg -n -F -- 'KernelIovec' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true
printf '%s\n' '--- ABI macro and ENOMEM definitions ---'
rg -n -F -- 'KYTY_SYSV_ABI' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true
rg -n -F -- 'KERNEL_ERROR_ENOMEM' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true
printf '%s\n' '--- network Send declarations/definitions ---'
rg -n -F -- 'Send(' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -100 || true
printf '%s\n' '--- exception handlers ---'
rg -n --glob '*.cpp' --glob '*.h' --glob '*.hpp' 'std::bad_alloc|catch[[:space:]]*\(|try[[:space:]]*\{' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -200 || true

Repository: KytyPS5/KytyPS5

Length of output: 45669


🏁 Script executed:

set -e
rg -n -F -- 'KernelIovec' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true
rg -n -F -- 'KYTY_SYSV_ABI' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true
rg -n -F -- 'KERNEL_ERROR_ENOMEM' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true
rg -n -F -- 'Send(' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -100 || true
rg -n --glob '*.cpp' --glob '*.h' --glob '*.hpp' 'std::bad_alloc|catch[[:space:]]*\(|try[[:space:]]*\{' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -200 || true

Repository: KytyPS5/KytyPS5

Length of output: 45669


🏁 Script executed:

set -e
printf '%s\n' '--- exact type and ABI definitions ---'
nl -ba src/kernel/fileSystem.h | sed -n '30,45p'
nl -ba src/common/abi.h | sed -n '1,18p'
nl -ba src/libs/errno.h | sed -n '190,204p'
printf '%s\n' '--- socket Send implementation ---'
nl -ba src/libs/network.cpp | sed -n '2308,2348p'
printf '%s\n' '--- guest function dispatch references ---'
rg -n --glob '*.cpp' --glob '*.h' 'module_func_t|UnresolvedImportStub|vaddr|func\\(' src/loader src/libs src/kernel | head -120

Repository: KytyPS5/KytyPS5

Length of output: 4110


🏁 Script executed:

set -e
nl -ba src/kernel/fileSystem.h | sed -n '30,45p'
nl -ba src/common/abi.h | sed -n '1,18p'
nl -ba src/libs/errno.h | sed -n '190,204p'
nl -ba src/libs/network.cpp | sed -n '2308,2348p'
rg -n --glob '*.cpp' --glob '*.h' 'module_func_t|UnresolvedImportStub|vaddr|func\(' src/loader src/libs src/kernel | head -120

Repository: KytyPS5/KytyPS5

Length of output: 14892


🏁 Script executed:

set -e
rg -n -F -- 'RuntimeLinker::StartModule' src/loader/runtimeLinker.cpp
rg -n -F -- 'StartModule(' src/loader/runtimeLinker.cpp src/loader/runtimeLinker.h
rg -n -F -- 'StopModule(' src/loader/runtimeLinker.cpp src/loader/runtimeLinker.h

Repository: KytyPS5/KytyPS5

Length of output: 875


🏁 Script executed:

set -e
nl -ba src/loader/runtimeLinker.cpp | sed -n '1538,1585p'
nl -ba src/loader/runtimeLinker.cpp | sed -n '1268,1285p'

Repository: KytyPS5/KytyPS5

Length of output: 3077


Return KERNEL_ERROR_ENOMEM when socket gathering cannot allocate.

ValidateIovecs accepts a valid total up to INT_MAX. For a socket, reserve(total) and insert can therefore request almost 2 GiB. If allocation fails, std::bad_alloc escapes KernelWritev across its KYTY_SYSV_ABI boundary. Catch the allocation failure locally and return KERNEL_ERROR_ENOMEM. An arbitrary cap would change the accepted iovec contract, and std::nothrow does not handle std::vector allocation.

🐛 Suggested fix
 		// A datagram socket sends one message per call, so gather the vectors and send them together.
 		std::vector<uint8_t> gathered;
-		gathered.reserve(total);
-		for (const auto& buffer: buffers) {
-			if (buffer.iov_len == 0) {
-				continue;
+		try {
+			gathered.reserve(total);
+			for (const auto& buffer: buffers) {
+				if (buffer.iov_len == 0) {
+					continue;
+				}
+				const auto* bytes = static_cast<const uint8_t*>(buffer.iov_base);
+				gathered.insert(gathered.end(), bytes, bytes + buffer.iov_len);
 			}
-			const auto* bytes = static_cast<const uint8_t*>(buffer.iov_base);
-			gathered.insert(gathered.end(), bytes, bytes + buffer.iov_len);
+		} catch (const std::bad_alloc&) {
+			return KERNEL_ERROR_ENOMEM;
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (::Libs::Network::Net::IsSocket(d)) {
		// A datagram socket sends one message per call, so gather the vectors and send them together.
		std::vector<uint8_t> gathered;
		try {
			gathered.reserve(total);
			for (const auto& buffer: buffers) {
				if (buffer.iov_len == 0) {
					continue;
				}
				const auto* bytes = static_cast<const uint8_t*>(buffer.iov_base);
				gathered.insert(gathered.end(), bytes, bytes + buffer.iov_len);
			}
		} catch (const std::bad_alloc&) {
			return KERNEL_ERROR_ENOMEM;
		}
		if (gathered.empty()) {
			return 0;
		}
		const auto result = ::Libs::Network::Net::Send(d, gathered.data(), gathered.size(), 0);
		return (result < 0 ? PosixToKernel(*Posix::GetErrorAddr()) : static_cast<int64_t>(result));
	}

✅ Addressed in commit cabb11c

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 03:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#discussion_r4240144854) · edited 2026-10-11 03:48 UTC **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '990,1125p' src/kernel/fileSystem.cpp rg -n 'ValidateIovecs|bad_alloc|KernelWritev|Net::Send' src/kernel/fileSystem.cpp src/libs/libKernel.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4920 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- validation and ABI definitions ---' sed -n '760,860p' src/kernel/fileSystem.cpp printf '%s\n' '--- iovec and error definitions ---' rg -n -F --glob '*.{h,hpp,cpp}' 'struct KernelIovec|class KernelIovec|using KernelIovec|KERNEL_ERROR_ENOMEM|KERNEL_ERROR_EINVAL|KYTY_SYSV_ABI|DESCRIPTOR_MIN' src include 2>/dev/null || true printf '%s\n' '--- socket send declarations and implementation references ---' rg -n -F --glob '*.{h,hpp,cpp}' 'Net::Send|int64_t Send|uint64_t Send|Send(int' src 2>/dev/null || true printf '%s\n' '--- exception handling around exported kernel calls ---' rg -n -F --glob '*.{h,hpp,cpp}' 'catch (const std::bad_alloc|std::bad_alloc|catch (...)|try {' src/kernel src/libs include 2>/dev/null || true ``` Repository: KytyPS5/KytyPS5 Length of output: 3014 --- 🏁 Script executed: ```bash set -e sed -n '760,860p' src/kernel/fileSystem.cpp rg -n -F --glob '*.{h,hpp,cpp}' 'struct KernelIovec|class KernelIovec|using KernelIovec|KERNEL_ERROR_ENOMEM|KYTY_SYSV_ABI|DESCRIPTOR_MIN' src include 2>/dev/null || true rg -n -F --glob '*.{h,hpp,cpp}' 'Net::Send|int64_t Send|uint64_t Send|Send(int' src 2>/dev/null || true rg -n -F --glob '*.{h,hpp,cpp}' 'catch (const std::bad_alloc|std::bad_alloc|catch (...)|try {' src/kernel src/libs include 2>/dev/null || true ``` Repository: KytyPS5/KytyPS5 Length of output: 2820 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- KernelIovec references and definitions ---' rg -n -F -- 'KernelIovec' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true printf '%s\n' '--- ABI macro and ENOMEM definitions ---' rg -n -F -- 'KYTY_SYSV_ABI' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true rg -n -F -- 'KERNEL_ERROR_ENOMEM' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true printf '%s\n' '--- network Send declarations/definitions ---' rg -n -F -- 'Send(' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -100 || true printf '%s\n' '--- exception handlers ---' rg -n --glob '*.cpp' --glob '*.h' --glob '*.hpp' 'std::bad_alloc|catch[[:space:]]*\(|try[[:space:]]*\{' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -200 || true ``` Repository: KytyPS5/KytyPS5 Length of output: 45669 --- 🏁 Script executed: ```bash set -e rg -n -F -- 'KernelIovec' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true rg -n -F -- 'KYTY_SYSV_ABI' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true rg -n -F -- 'KERNEL_ERROR_ENOMEM' . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' || true rg -n -F -- 'Send(' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -100 || true rg -n --glob '*.cpp' --glob '*.h' --glob '*.hpp' 'std::bad_alloc|catch[[:space:]]*\(|try[[:space:]]*\{' src include . --glob '!build/**' --glob '!dist/**' --glob '!node_modules/**' | head -200 || true ``` Repository: KytyPS5/KytyPS5 Length of output: 45669 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- exact type and ABI definitions ---' nl -ba src/kernel/fileSystem.h | sed -n '30,45p' nl -ba src/common/abi.h | sed -n '1,18p' nl -ba src/libs/errno.h | sed -n '190,204p' printf '%s\n' '--- socket Send implementation ---' nl -ba src/libs/network.cpp | sed -n '2308,2348p' printf '%s\n' '--- guest function dispatch references ---' rg -n --glob '*.cpp' --glob '*.h' 'module_func_t|UnresolvedImportStub|vaddr|func\\(' src/loader src/libs src/kernel | head -120 ``` Repository: KytyPS5/KytyPS5 Length of output: 4110 --- 🏁 Script executed: ```bash set -e nl -ba src/kernel/fileSystem.h | sed -n '30,45p' nl -ba src/common/abi.h | sed -n '1,18p' nl -ba src/libs/errno.h | sed -n '190,204p' nl -ba src/libs/network.cpp | sed -n '2308,2348p' rg -n --glob '*.cpp' --glob '*.h' 'module_func_t|UnresolvedImportStub|vaddr|func\(' src/loader src/libs src/kernel | head -120 ``` Repository: KytyPS5/KytyPS5 Length of output: 14892 --- 🏁 Script executed: ```bash set -e rg -n -F -- 'RuntimeLinker::StartModule' src/loader/runtimeLinker.cpp rg -n -F -- 'StartModule(' src/loader/runtimeLinker.cpp src/loader/runtimeLinker.h rg -n -F -- 'StopModule(' src/loader/runtimeLinker.cpp src/loader/runtimeLinker.h ``` Repository: KytyPS5/KytyPS5 Length of output: 875 --- 🏁 Script executed: ```bash set -e nl -ba src/loader/runtimeLinker.cpp | sed -n '1538,1585p' nl -ba src/loader/runtimeLinker.cpp | sed -n '1268,1285p' ``` Repository: KytyPS5/KytyPS5 Length of output: 3077 --- </details> **Return `KERNEL_ERROR_ENOMEM` when socket gathering cannot allocate.** `ValidateIovecs` accepts a valid total up to `INT_MAX`. For a socket, `reserve(total)` and `insert` can therefore request almost 2 GiB. If allocation fails, `std::bad_alloc` escapes `KernelWritev` across its `KYTY_SYSV_ABI` boundary. Catch the allocation failure locally and return `KERNEL_ERROR_ENOMEM`. An arbitrary cap would change the accepted iovec contract, and `std::nothrow` does not handle `std::vector` allocation. <details> <summary>🐛 Suggested fix</summary> ```diff // A datagram socket sends one message per call, so gather the vectors and send them together. std::vector<uint8_t> gathered; - gathered.reserve(total); - for (const auto& buffer: buffers) { - if (buffer.iov_len == 0) { - continue; + try { + gathered.reserve(total); + for (const auto& buffer: buffers) { + if (buffer.iov_len == 0) { + continue; + } + const auto* bytes = static_cast<const uint8_t*>(buffer.iov_base); + gathered.insert(gathered.end(), bytes, bytes + buffer.iov_len); } - const auto* bytes = static_cast<const uint8_t*>(buffer.iov_base); - gathered.insert(gathered.end(), bytes, bytes + buffer.iov_len); + } catch (const std::bad_alloc&) { + return KERNEL_ERROR_ENOMEM; } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (::Libs::Network::Net::IsSocket(d)) { // A datagram socket sends one message per call, so gather the vectors and send them together. std::vector<uint8_t> gathered; try { gathered.reserve(total); for (const auto& buffer: buffers) { if (buffer.iov_len == 0) { continue; } const auto* bytes = static_cast<const uint8_t*>(buffer.iov_base); gathered.insert(gathered.end(), bytes, bytes + buffer.iov_len); } } catch (const std::bad_alloc&) { return KERNEL_ERROR_ENOMEM; } if (gathered.empty()) { return 0; } const auto result = ::Libs::Network::Net::Send(d, gathered.data(), gathered.size(), 0); return (result < 0 ? PosixToKernel(*Posix::GetErrorAddr()) : static_cast<int64_t>(result)); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c6580928821270087394776b --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit cabb11c
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 03:45 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: 944e743c-9add-4449-9212-a76eaebe1d3f
📥 Commits

Reviewing files that changed from the base of the PR and between 2358b21adcac0781b8ef2e799d170b2cb7dce61b and 6276278957.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 03:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#pullrequestreview-5481769208) · **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**: `944e743c-9add-4449-9212-a76eaebe1d3f` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2358b21adcac0781b8ef2e799d170b2cb7dce61b and 62762789571b8f20feeea2a0b4a83545cce0951d. </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; 4 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=a75c47dd-c680-4aac-9f1e-9d99d42c3766 attempt=8d3c3ad5-6da0-4ae7-a701-d9126ecaa8c3 batch=1/1 -->
Author
Owner

@⁠HamsterCL on GitHub · 2026-10-11 03:49 UTC · original

Thanks for the review. I changed the PR since it was opened, so here is where each finding ended up:

  • Truncate and the lifetime of the selected file (first review): I removed sceKernelTruncate from this PR. #1170 already implements it with the same NID, so the PR is now sceKernelWritev only (retitled accordingly), and that finding no longer applies here.
  • Send all vectors as one socket message: fixed in 62762789. On a socket the vectors are gathered into one buffer and sent with a single Net::Send, so a datagram socket gets one message instead of one datagram per vector. A zero total returns 0, and a send error is translated like before.
  • ENOMEM when gathering fails (second review): fixed in cabb11cd. The gathering is wrapped in a try/catch for std::bad_alloc and returns KERNEL_ERROR_ENOMEM, so the exception does not cross the guest ABI boundary. I did not add a size cap, to keep the accepted iovec contract unchanged. There is no test for the allocation failure itself, because forcing a multi-GiB allocation failure is not practical in the test harness.
**@⁠HamsterCL** on GitHub · 2026-10-11 03:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#issuecomment-6105169128) Thanks for the review. I changed the PR since it was opened, so here is where each finding ended up: - **`Truncate` and the lifetime of the selected file** (first review): I removed `sceKernelTruncate` from this PR. #1170 already implements it with the same NID, so the PR is now `sceKernelWritev` only (retitled accordingly), and that finding no longer applies here. - **Send all vectors as one socket message**: fixed in 62762789. On a socket the vectors are gathered into one buffer and sent with a single `Net::Send`, so a datagram socket gets one message instead of one datagram per vector. A zero total returns 0, and a send error is translated like before. - **`ENOMEM` when gathering fails** (second review): fixed in cabb11cd. The gathering is wrapped in a `try`/`catch` for `std::bad_alloc` and returns `KERNEL_ERROR_ENOMEM`, so the exception does not cross the guest ABI boundary. I did not add a size cap, to keep the accepted iovec contract unchanged. There is no test for the allocation failure itself, because forcing a multi-GiB allocation failure is not practical in the test harness.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 12:35 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: 1c45b902-f56d-4aeb-8859-716039ebe976
📥 Commits

Reviewing files that changed from the base of the PR and between cabb11cd0e and bd8dd6a0d7.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 12:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#pullrequestreview-5483314908) · **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**: `1c45b902-f56d-4aeb-8859-716039ebe976` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cabb11cd0e0d58955a5af653cceaadb33d92b24a and bd8dd6a0d7bad9a4cd65713446c81691658c0d89. </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; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=65c3d6e1-9931-44bd-adbc-ee390c67da98 attempt=b4fc0b4e-b89d-495a-94be-837fe9d35c07 batch=1/1 -->
@ -1025,0 +1102,4 @@
if (file->append && !file->f.Seek(file->f.Size())) {
return KERNEL_ERROR_EIO;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 12:35 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- KernelWritev and nearby functions ---'
nl -ba src/kernel/fileSystem.cpp | sed -n '1010,1155p'
printf '%s\n' '--- FileDescriptors declaration and lifetime methods ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' \
  -e 'class FileDescriptors' -e 'GetFile(int' -e 'DeleteDescriptor' -e 'KernelClose' -e 'Lock' \
  src/kernel
printf '%s\n' '--- FileDescriptors and close definitions ---'
nl -ba src/kernel/fileSystem.cpp | sed -n '150,245p'
nl -ba src/kernel/fileSystem.cpp | sed -n '535,605p'
printf '%s\n' '--- KernelWritev registration and direct references ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' \
  -e 'KernelWritev' -e 'sceKernelWritev' -e 'libkernel_v1' \
  src tests

Repository: KytyPS5/KytyPS5

Length of output: 21918


🏁 Script executed:

set -eu
nl -ba src/kernel/fileSystem.cpp | sed -n '60,115p'
nl -ba src/libs/libKernel.cpp | sed -n '3105,3125p'

Repository: KytyPS5/KytyPS5

Length of output: 3205


Protect the File lifetime in the regular-file KernelWritev path.

GetFile(d) returns a raw pointer after releasing the descriptor-table lock. A concurrent exported KernelClose(d) can delete that File before KernelWritev reads file->opened or acquires file->mutex. This can cause a use-after-free and crash.

Add descriptor-lifetime coordination that covers both KernelWritev and KernelClose. The existing file->mutex is insufficient because KernelWritev dereferences the pointer before locking it, and KernelClose does not use that mutex.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 12:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#discussion_r4241584554) **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- KernelWritev and nearby functions ---' nl -ba src/kernel/fileSystem.cpp | sed -n '1010,1155p' printf '%s\n' '--- FileDescriptors declaration and lifetime methods ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' \ -e 'class FileDescriptors' -e 'GetFile(int' -e 'DeleteDescriptor' -e 'KernelClose' -e 'Lock' \ src/kernel printf '%s\n' '--- FileDescriptors and close definitions ---' nl -ba src/kernel/fileSystem.cpp | sed -n '150,245p' nl -ba src/kernel/fileSystem.cpp | sed -n '535,605p' printf '%s\n' '--- KernelWritev registration and direct references ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' \ -e 'KernelWritev' -e 'sceKernelWritev' -e 'libkernel_v1' \ src tests ``` Repository: KytyPS5/KytyPS5 Length of output: 21918 --- 🏁 Script executed: ```bash set -eu nl -ba src/kernel/fileSystem.cpp | sed -n '60,115p' nl -ba src/libs/libKernel.cpp | sed -n '3105,3125p' ``` Repository: KytyPS5/KytyPS5 Length of output: 3205 --- </details> **Protect the `File` lifetime in the regular-file `KernelWritev` path.** `GetFile(d)` returns a raw pointer after releasing the descriptor-table lock. A concurrent exported `KernelClose(d)` can delete that `File` before `KernelWritev` reads `file->opened` or acquires `file->mutex`. This can cause a use-after-free and crash. Add descriptor-lifetime coordination that covers both `KernelWritev` and `KernelClose`. The existing `file->mutex` is insufficient because `KernelWritev` dereferences the pointer before locking it, and `KernelClose` does not use that mutex. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:99dca6218fa99d3b0cf3b388 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-15 18:20 UTC · original

NHL 27 needs this too. On #1101, pinkton found that NHL 27 writes its save index through sceKernelWritev. With the unresolved-import stub the index stays empty, so the save never loads. It's the same pattern as the FC 27 INDEX file here. The other two calls on that path, sceKernelTruncate and sceKernelFdatasync, are in #1170.

I read through the file-write path and it matches sceKernelWrite and sceKernelPwritev: it writes at the current position, honours O_APPEND and sync writes, and stops at the first short write. It merges cleanly with the rebased #1170. I also ran a native harness on the real fileSystem.cpp from main + #1170 + this PR, with the NHL 27 index pattern: writev two iovecs over a stale, longer file, truncate it to the written length by path, then read it back. It passed.

AI-assisted: yes

**@⁠overlordxrz-source** on GitHub · 2026-10-15 18:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#issuecomment-6199195441) NHL 27 needs this too. On #1101, pinkton found that NHL 27 writes its save index through `sceKernelWritev`. With the unresolved-import stub the index stays empty, so the save never loads. It's the same pattern as the FC 27 `INDEX` file here. The other two calls on that path, `sceKernelTruncate` and `sceKernelFdatasync`, are in #1170. I read through the file-write path and it matches `sceKernelWrite` and `sceKernelPwritev`: it writes at the current position, honours `O_APPEND` and sync writes, and stops at the first short write. It merges cleanly with the rebased #1170. I also ran a native harness on the real `fileSystem.cpp` from main + #1170 + this PR, with the NHL 27 index pattern: writev two iovecs over a stale, longer file, truncate it to the written length by path, then read it back. It passed. AI-assisted: yes
Author
Owner

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

Credited 54abbf48f2

**@⁠Nmzik** on GitHub · 2026-10-15 23:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1401#issuecomment-6204506345) Credited 54abbf48f29e872be7c52a87c26159235f1d58a0

Pull request closed

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