Report the shader stage and hash in CFG build failures #799

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

@⁠theantipopau on GitHub · 2026-09-24 06:21 UTC · original
theantipopau:shader-cfg-error-context → main · +27 −26 · 3 files · 2 commits · closed without merging

What

CFG::BuildGraph reports structural problems with EXIT, which halts the emulator. Before
this change the resulting line identified the pc but not which shader failed:

shader CFG build failed: branch at pc 0x000000a4 targets invalid pc 0x000000ff

With hundreds of shaders in flight there is no way to act on that. BuildGraph now takes an
optional context string that is prefixed to every build-failure diagnostic, and
TranslateProgram passes the stage name and shader hash:

shader CFG build failed: CS hash=0x0123456789abcdef: branch at pc 0x000000a4 targets invalid pc 0x000000ff

BuildGraph's many ExitBuildFailure call sites are routed through a single local fail
lambda so the prefix cannot be forgotten at one of them. The default argument is empty, so
every existing caller is unchanged and the unprefixed form is still available.

Scope

This replaces the branch with the same 3-file, +27/−26 footprint it had before. The previous
revision of this PR also carried a copy of the Windows socket work from #797 at an older
revision; that duplication is gone, and #797 is now the only carrier of it.

Testing

shader_cfg_tests builds clean and passes.

There is deliberately no unit test for the new prefix. Every BuildGraph failure path runs
through ExitBuildFailure, which is [[noreturn]] and calls EXIT — it records the reason
into the graph and then halts the process, so there is no way to observe the formatted string
from inside the test binary. Common::DbgExitHandler is a strong symbol in common, so the
test executable cannot substitute it either. Verifying this needs either a subprocess harness
or a refactor that separates message construction from the halt, and neither seems worth the
machinery for a diagnostic prefix.

The non-fatal sibling path is already covered: LogDispatcherFallback prints stage= and
hash= on its own line for structurize failures, which is why this change is scoped to the
fatal build path only.

**@⁠theantipopau** on GitHub · 2026-09-24 06:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799) `theantipopau:shader-cfg-error-context` → `main` · +27 −26 · 3 files · 2 commits · closed without merging ## What `CFG::BuildGraph` reports structural problems with `EXIT`, which halts the emulator. Before this change the resulting line identified the pc but not *which* shader failed: ``` shader CFG build failed: branch at pc 0x000000a4 targets invalid pc 0x000000ff ``` With hundreds of shaders in flight there is no way to act on that. `BuildGraph` now takes an optional context string that is prefixed to every build-failure diagnostic, and `TranslateProgram` passes the stage name and shader hash: ``` shader CFG build failed: CS hash=0x0123456789abcdef: branch at pc 0x000000a4 targets invalid pc 0x000000ff ``` `BuildGraph`'s many `ExitBuildFailure` call sites are routed through a single local `fail` lambda so the prefix cannot be forgotten at one of them. The default argument is empty, so every existing caller is unchanged and the unprefixed form is still available. ## Scope This replaces the branch with the same 3-file, +27/−26 footprint it had before. The previous revision of this PR also carried a copy of the Windows socket work from #797 at an older revision; that duplication is gone, and #797 is now the only carrier of it. ## Testing `shader_cfg_tests` builds clean and passes. There is deliberately **no unit test for the new prefix.** Every `BuildGraph` failure path runs through `ExitBuildFailure`, which is `[[noreturn]]` and calls `EXIT` — it records the reason into the graph and then halts the process, so there is no way to observe the formatted string from inside the test binary. `Common::DbgExitHandler` is a strong symbol in `common`, so the test executable cannot substitute it either. Verifying this needs either a subprocess harness or a refactor that separates message construction from the halt, and neither seems worth the machinery for a diagnostic prefix. The non-fatal sibling path is already covered: `LogDispatcherFallback` prints `stage=` and `hash=` on its own line for structurize failures, which is why this change is scoped to the fatal build path only.
Upstream's Structurize no longer mutates its input, so BuildGraph is
reapplied on top of the current CFG API instead of the old one.

Co-Authored-By: Codebuff <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:32:51 +00:00
github-bot closed this pull request 2026-11-26 09:32:51 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 06:26 UTC · original · edited 2026-10-06 04:32 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 78d6a4c0-4064-4789-b80f-0ce383d17683

📥 Commits

Reviewing files that changed from the base of the PR and between a599ad42b926e408653a1f075855f178b4472ab1 and ddcefb3ea143ffa30c3f4f7492f1b2689cdd2625.

📒 Files selected for processing (2)
  • src/libs/network.cpp
  • tests/KernelFileSystemTests.cpp

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


📝 Walkthrough

Walkthrough

Windows socket transports now track guest nonblocking mode and add a peek-and-wait-all receive path. Tests cover stream and datagram receives, EOF, and accepted sockets. BuildGraph accepts optional diagnostic context and prefixes it to CFG failure messages. TranslateProgram supplies shader stage and hash context.

Suggested reviewers: nmzik

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to ddcef

No confirmed issue remains that should block merging after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to ddcef

A Windows guest receive can now wait on an incomplete message while repeatedly reading its buffered prefix. A network peer can prolong that work, and concurrent socket close or mode changes have unresolved behavior. The identified exposure is limited to a guest call using the affected flags; broader impact has not been established.

Retained concerns

  • Medium · security · inferred: On a blocking stream, a peer that supplies a large prefix but withholds the remaining bytes can keep the new Windows receive loop repeatedly copying buffered data. The guest must request PEEK|WAITALL; resource impact and production reachability have not been measured.
  • Low · reliability · inferred: Receive obtains a raw native socket and subsequently looks up nonblocking mode by guest descriptor. Concurrent close, reuse, or mode changes can make those observations disagree during the new multi-step wait. The base code already used a raw socket, and the Windows outcome of an in-flight close is unverified.
Security review details

Security Blast Radius

  • inferred — The identified resource exposure is an emulator receive call on a validated guest socket, rather than a demonstrated cross-socket or global-lock effect. Concurrent calls could add work, but their scale is unmeasured.

Security Findings and Attack Paths

  • inferred — If a guest requests blocking PEEK|WAITALL on a stream, a peer can send less than the requested length and remain open. Each retry peeks at the buffered prefix, potentially sustaining CPU and receive-thread use; no measured exploit or broader exposure is established.

Trust Boundaries and Controls

  • observed — Guest descriptors are resolved to socket transports before receiving, unsupported flags are rejected, and nonblocking, DONTWAIT, EOF, and terminal-event paths constrain the specialized wait.

Resilience and Maintainability Implications

  • inferred — Atomic mode storage protects the stored value, but does not make descriptor lookup, mode selection, close, and the repeated receive one atomic lifetime transition. The effect of a concurrent Windows close on an in-flight wait remains unknown.

Hardening Proposals

  • proposed — Consider a wait strategy that avoids repeatedly copying the entire prefix and coordinates cancellation and mode decisions with a retained transport, while preserving the guest's WAITALL semantics.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 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: adding the shader stage and hash to CFG build failure diagnostics.
Description check ✅ Passed The description directly explains the diagnostic change, implementation approach, scope, and testing results. It is fully related to the changeset.

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-09-24 06:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#issuecomment-5808930629) · edited 2026-10-06 04:32 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/799"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `78d6a4c0-4064-4789-b80f-0ce383d17683` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between a599ad42b926e408653a1f075855f178b4472ab1 and ddcefb3ea143ffa30c3f4f7492f1b2689cdd2625. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/libs/network.cpp` * `tests/KernelFileSystemTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Windows socket transports now track guest nonblocking mode and add a peek-and-wait-all receive path. Tests cover stream and datagram receives, EOF, and accepted sockets. `BuildGraph` accepts optional diagnostic context and prefixes it to CFG failure messages. `TranslateProgram` supplies shader stage and hash context. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"ddcefb3ea143ffa30c3f4f7492f1b2689cdd2625" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `ddcef` <!-- final_review_risk_coverage:{"sourceCommitId":"ddcefb3ea143ffa30c3f4f7492f1b2689cdd2625","coveredCommitId":"ddcefb3ea143ffa30c3f4f7492f1b2689cdd2625","kind":"reviewed"} --> No confirmed issue remains that should block merging after normal checks. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `ddcef` A Windows guest receive can now wait on an incomplete message while repeatedly reading its buffered prefix. A network peer can prolong that work, and concurrent socket close or mode changes have unresolved behavior. The identified exposure is limited to a guest call using the affected flags; broader impact has not been established. **Retained concerns** - **Medium · security · inferred:** On a blocking stream, a peer that supplies a large prefix but withholds the remaining bytes can keep the new Windows receive loop repeatedly copying buffered data. The guest must request PEEK|WAITALL; resource impact and production reachability have not been measured. - **Low · reliability · inferred:** Receive obtains a raw native socket and subsequently looks up nonblocking mode by guest descriptor. Concurrent close, reuse, or mode changes can make those observations disagree during the new multi-step wait. The base code already used a raw socket, and the Windows outcome of an in-flight close is unverified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The identified resource exposure is an emulator receive call on a validated guest socket, rather than a demonstrated cross-socket or global-lock effect. Concurrent calls could add work, but their scale is unmeasured. **Security Findings and Attack Paths** - _inferred_ — If a guest requests blocking PEEK|WAITALL on a stream, a peer can send less than the requested length and remain open. Each retry peeks at the buffered prefix, potentially sustaining CPU and receive-thread use; no measured exploit or broader exposure is established. **Trust Boundaries and Controls** - _observed_ — Guest descriptors are resolved to socket transports before receiving, unsupported flags are rejected, and nonblocking, DONTWAIT, EOF, and terminal-event paths constrain the specialized wait. **Resilience and Maintainability Implications** - _inferred_ — Atomic mode storage protects the stored value, but does not make descriptor lookup, mode selection, close, and the repeated receive one atomic lifetime transition. The effect of a concurrent Windows close on an in-flight wait remains unknown. **Hardening Proposals** - _proposed_ — Consider a wait strategy that avoids repeatedly copying the entire prefix and coordinates cancellation and mode decisions with a retained transport, while preserving the guest's WAITALL semantics. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 5 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | 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: adding the shader stage and hash to CFG build failure diagnostics. | | Description check | ✅ Passed | The description directly explains the diagnostic change, implementation approach, scope, and testing results. It is fully related to the changeset. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=799)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 09:27 UTC · original · edited 2026-09-26 02:09 UTC
On src/libs/network.cpp line 1169 (outdated):

@@ -1076,6 +1081,98 @@ static int ConvertMessageFlags(int flags) {
 	return host_flags;
 }
 
+static int64_t RecvHost(NativeSocket socket, char* buf, SocketIoLength host_len, int host_flags,
+                        sockaddr_storage* host_addr, SocketLength* host_addrlen) {
+	if (host_addr == nullptr) {
+		return ::recv(socket, buf, host_len, host_flags);
+	}
+	return ::recvfrom(socket, buf, host_len, host_flags, reinterpret_cast<sockaddr*>(host_addr),
+	                  host_addrlen);
+}
+
+#if defined(_WIN32)
+static bool IsSocketNonBlocking(int guest_fd) {
+	Common::LockGuard lock(g_socket_mutex);
+	if (guest_fd < 0 || guest_fd >= SOCKET_FD_MAX) {
+		return false;
+	}
+	const auto& slot = g_sockets[static_cast<size_t>(guest_fd)];
+	return slot.transport != nullptr && slot.transport->nonblocking;
+}
+
+static bool SocketIsStream(NativeSocket socket) {
+	int          type = 0;
+	SocketLength len  = sizeof(type);
+	return getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type), &len) == 0 &&
+	       type == SOCK_STREAM;
+}
+
+// A peek never consumes, so the buffered prefix keeps the socket readable and a poll would
+// return immediately. The retries are paced instead, and the poll is only used to notice a
+// closed or reset peer, which ends the wait with the short read the guest expects. A blocking
+// MSG_WAITALL may otherwise wait indefinitely: that is the requested semantics when a peer
+// stays open but sends only a prefix, so imposing an arbitrary timeout would truncate it.
+static short PollSocket(NativeSocket socket) {
+	WSAPOLLFD event {};
+	event.fd     = socket;
+	event.events = POLLRDNORM;
+	return WSAPoll(&event, 1, 0) > 0 ? event.revents : 0;
+}
+
+static bool WaitForPeekedBytes(NativeSocket socket) {
+	std::this_thread::sleep_for(std::chrono::milliseconds(1));
+	constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL;
+	return (PollSocket(socket) & terminal_events) != 0;
+}
+
+// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP, so the requested length is
+// waited for by peeking until it is buffered. Datagram sockets ignore MSG_WAITALL and
+// non-blocking sockets hand back whatever arrived, matching the guest (FreeBSD) behaviour.
+static int64_t RecvPeekWaitAll(NativeSocket socket, bool nonblocking, bool no_wait, char* buf,
+                               SocketIoLength host_len, sockaddr_storage* host_addr,
+                               SocketLength* host_addrlen) {
+	if (host_len == 0 && (host_addr == nullptr || SocketIsStream(socket))) {
+		// Winsock blocks on a zero length receive from an empty stream socket, while the
+		// guest expects an immediate zero. Datagram peeks still report the source address.
+		return 0;
+	}
+	if (no_wait && !nonblocking) {
+		// Winsock has no MSG_DONTWAIT, so readiness decides whether a peek may run at all.
+		constexpr short input_events = POLLRDNORM | POLLHUP | POLLERR;
+		if ((PollSocket(socket) & input_events) == 0) {
+			return SetGuestSocketError(Posix::POSIX_EWOULDBLOCK);
+		}
+	}
+	bool peer_closed = false;
+	for (;;) {
+		char                 scratch = 0;
+		char*                peek_buf = buf;
+		SocketIoLength       peek_len = host_len;
+		if (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) {
+			// Winsock may reject a zero-length datagram peek before filling from. A
+			// one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source.
+			peek_buf = &scratch;
+			peek_len = 1;
+		}
+		const int64_t peeked =
+		    RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen);
+		if (peeked < 0) {
+			if (WSAGetLastError() == WSAEMSGSIZE) {
+				// Winsock copied a truncated datagram prefix, but a zero-length peek can also
+				// report the non-empty message this way. The outer receive maps both to len.
+				return host_len;
+			}
+			return SetHostSocketError();
+		}
+		if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
+		    !SocketIsStream(socket)) {
+			return peeked;

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clamp the peek result to the requested length when the scratch buffer is used.

This path applies to a zero-length peek on a datagram socket that asks for the source address. In that case, RecvPeekWaitAll peeks into a 1-byte scratch buffer. If the pending datagram is exactly 1 byte, Winsock returns peeked == 1 without WSAEMSGSIZE. The check peeked >= host_len is then true, and the function returns 1. Recvfrom passes 1 to the guest, even though the guest requested 0 bytes and nothing was written to buf. The guest-side (FreeBSD) behavior is a return value of 0. For datagrams of 2 bytes or more, the WSAEMSGSIZE branch already returns host_len (0). Only the 1-byte case gives the wrong count.

🐛 Proposed fix
 		if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
 		    !SocketIsStream(socket)) {
-			return peeked;
+			return std::min<int64_t>(peeked, static_cast<int64_t>(host_len));
 		}
📝 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 (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) {
			// Winsock may reject a zero-length datagram peek before filling from. A
			// one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source.
			peek_buf = &scratch;
			peek_len = 1;
		}
		const int64_t peeked =
		    RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen);
		if (peeked < 0) {
			if (WSAGetLastError() == WSAEMSGSIZE) {
				// Winsock copied a truncated datagram prefix, but a zero-length peek can also
				// report the non-empty message this way. The outer receive maps both to len.
				return host_len;
			}
			return SetHostSocketError();
		}
		if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
		    !SocketIsStream(socket)) {
			return std::min<int64_t>(peeked, static_cast<int64_t>(host_len));

✅ Confirmed as addressed by @⁠theantipopau

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 09:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4092020675) · edited 2026-09-26 02:09 UTC On `src/libs/network.cpp` line 1169 (outdated): ```diff @@ -1076,6 +1081,98 @@ static int ConvertMessageFlags(int flags) { return host_flags; } +static int64_t RecvHost(NativeSocket socket, char* buf, SocketIoLength host_len, int host_flags, + sockaddr_storage* host_addr, SocketLength* host_addrlen) { + if (host_addr == nullptr) { + return ::recv(socket, buf, host_len, host_flags); + } + return ::recvfrom(socket, buf, host_len, host_flags, reinterpret_cast<sockaddr*>(host_addr), + host_addrlen); +} + +#if defined(_WIN32) +static bool IsSocketNonBlocking(int guest_fd) { + Common::LockGuard lock(g_socket_mutex); + if (guest_fd < 0 || guest_fd >= SOCKET_FD_MAX) { + return false; + } + const auto& slot = g_sockets[static_cast<size_t>(guest_fd)]; + return slot.transport != nullptr && slot.transport->nonblocking; +} + +static bool SocketIsStream(NativeSocket socket) { + int type = 0; + SocketLength len = sizeof(type); + return getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type), &len) == 0 && + type == SOCK_STREAM; +} + +// A peek never consumes, so the buffered prefix keeps the socket readable and a poll would +// return immediately. The retries are paced instead, and the poll is only used to notice a +// closed or reset peer, which ends the wait with the short read the guest expects. A blocking +// MSG_WAITALL may otherwise wait indefinitely: that is the requested semantics when a peer +// stays open but sends only a prefix, so imposing an arbitrary timeout would truncate it. +static short PollSocket(NativeSocket socket) { + WSAPOLLFD event {}; + event.fd = socket; + event.events = POLLRDNORM; + return WSAPoll(&event, 1, 0) > 0 ? event.revents : 0; +} + +static bool WaitForPeekedBytes(NativeSocket socket) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL; + return (PollSocket(socket) & terminal_events) != 0; +} + +// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP, so the requested length is +// waited for by peeking until it is buffered. Datagram sockets ignore MSG_WAITALL and +// non-blocking sockets hand back whatever arrived, matching the guest (FreeBSD) behaviour. +static int64_t RecvPeekWaitAll(NativeSocket socket, bool nonblocking, bool no_wait, char* buf, + SocketIoLength host_len, sockaddr_storage* host_addr, + SocketLength* host_addrlen) { + if (host_len == 0 && (host_addr == nullptr || SocketIsStream(socket))) { + // Winsock blocks on a zero length receive from an empty stream socket, while the + // guest expects an immediate zero. Datagram peeks still report the source address. + return 0; + } + if (no_wait && !nonblocking) { + // Winsock has no MSG_DONTWAIT, so readiness decides whether a peek may run at all. + constexpr short input_events = POLLRDNORM | POLLHUP | POLLERR; + if ((PollSocket(socket) & input_events) == 0) { + return SetGuestSocketError(Posix::POSIX_EWOULDBLOCK); + } + } + bool peer_closed = false; + for (;;) { + char scratch = 0; + char* peek_buf = buf; + SocketIoLength peek_len = host_len; + if (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) { + // Winsock may reject a zero-length datagram peek before filling from. A + // one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source. + peek_buf = &scratch; + peek_len = 1; + } + const int64_t peeked = + RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen); + if (peeked < 0) { + if (WSAGetLastError() == WSAEMSGSIZE) { + // Winsock copied a truncated datagram prefix, but a zero-length peek can also + // report the non-empty message this way. The outer receive maps both to len. + return host_len; + } + return SetHostSocketError(); + } + if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || + !SocketIsStream(socket)) { + return peeked; ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Clamp the peek result to the requested length when the scratch buffer is used.** This path applies to a zero-length peek on a datagram socket that asks for the source address. In that case, `RecvPeekWaitAll` peeks into a 1-byte `scratch` buffer. If the pending datagram is exactly 1 byte, Winsock returns `peeked == 1` without `WSAEMSGSIZE`. The check `peeked >= host_len` is then true, and the function returns 1. `Recvfrom` passes 1 to the guest, even though the guest requested 0 bytes and nothing was written to `buf`. The guest-side (FreeBSD) behavior is a return value of 0. For datagrams of 2 bytes or more, the `WSAEMSGSIZE` branch already returns `host_len` (0). Only the 1-byte case gives the wrong count. <details> <summary>🐛 Proposed fix</summary> ```diff if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || !SocketIsStream(socket)) { - return peeked; + return std::min<int64_t>(peeked, static_cast<int64_t>(host_len)); } ``` </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 (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) { // Winsock may reject a zero-length datagram peek before filling from. A // one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source. peek_buf = &scratch; peek_len = 1; } const int64_t peeked = RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen); if (peeked < 0) { if (WSAGetLastError() == WSAEMSGSIZE) { // Winsock copied a truncated datagram prefix, but a zero-length peek can also // report the non-empty message this way. The outer receive maps both to len. return host_len; } return SetHostSocketError(); } if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || !SocketIsStream(socket)) { return std::min<int64_t>(peeked, static_cast<int64_t>(host_len)); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fa11164ea6def43bc35ea734 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠theantipopau <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 09:27 UTC · original · edited 2026-09-26 03:31 UTC
On tests/KernelFileSystemTests.cpp line 473 (outdated):

@@ -454,19 +458,171 @@ void CheckSocketWakeup() {
         "guest PEEK and WAITALL preserve the wake bytes");
   Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload),
         "consume wake bytes with guest WAITALL");
+
+  // A full message split across writes must still complete a WAITALL receive, and the
+  // peeked bytes have to survive for the following receive.
+  const char text[] = "fragment";
+  constexpr std::size_t text_length = 8;    // without the terminator
+  constexpr std::size_t prefix_length = 5;  // deliberately short of text_length
+  Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2,
+        "send the first fragment");
+  const char* const second_fragment = text + text_length / 2;
+  const std::size_t second_length   = text_length - text_length / 2;
+  std::thread peer([&writer, second_fragment, second_length] {
+    std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    Net::Send(writer, second_fragment, second_length, 0);

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Check the second send before waiting for the full message.

If this send fails or sends fewer than second_length bytes, the blocking PEEK|WAITALL receive can wait indefinitely because the writer stays open. Check the send result in the peer thread so the test fails instead of hanging. Winsock permits short sends. (learn.microsoft.com)

✅ Addressed in commit a599ad4

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 09:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4092020699) · edited 2026-09-26 03:31 UTC On `tests/KernelFileSystemTests.cpp` line 473 (outdated): ```diff @@ -454,19 +458,171 @@ void CheckSocketWakeup() { "guest PEEK and WAITALL preserve the wake bytes"); Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload), "consume wake bytes with guest WAITALL"); + + // A full message split across writes must still complete a WAITALL receive, and the + // peeked bytes have to survive for the following receive. + const char text[] = "fragment"; + constexpr std::size_t text_length = 8; // without the terminator + constexpr std::size_t prefix_length = 5; // deliberately short of text_length + Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2, + "send the first fragment"); + const char* const second_fragment = text + text_length / 2; + const std::size_t second_length = text_length - text_length / 2; + std::thread peer([&writer, second_fragment, second_length] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + Net::Send(writer, second_fragment, second_length, 0); ``` _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ **Check the second send before waiting for the full message.** If this send fails or sends fewer than `second_length` bytes, the blocking `PEEK|WAITALL` receive can wait indefinitely because the writer stays open. Check the send result in the peer thread so the test fails instead of hanging. Winsock permits short sends. ([learn.microsoft.com](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send?utm_source=openai)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5488f36904b7290dd7dd721a --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit a599ad4 <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 09:27 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: c57153ad-1a1b-4ebc-982a-2313efa2cf25

📥 Commits

Reviewing files that changed from the base of the PR and between 31cdf2524498caa0392e58fb29835ca0e5d0a614 and 71eafce3dd0bc452bbc157465b3c059404bc6ae1.

📒 Files selected for processing (2)
  • src/libs/network.cpp
  • tests/KernelFileSystemTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 09:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#pullrequestreview-5302491835) · **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**: `c57153ad-1a1b-4ebc-982a-2313efa2cf25` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 31cdf2524498caa0392e58fb29835ca0e5d0a614 and 71eafce3dd0bc452bbc157465b3c059404bc6ae1. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/libs/network.cpp` * `tests/KernelFileSystemTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 01:43 UTC · original
On src/libs/network.cpp line 1169 (outdated):

@@ -1076,6 +1081,98 @@ static int ConvertMessageFlags(int flags) {
 	return host_flags;
 }
 
+static int64_t RecvHost(NativeSocket socket, char* buf, SocketIoLength host_len, int host_flags,
+                        sockaddr_storage* host_addr, SocketLength* host_addrlen) {
+	if (host_addr == nullptr) {
+		return ::recv(socket, buf, host_len, host_flags);
+	}
+	return ::recvfrom(socket, buf, host_len, host_flags, reinterpret_cast<sockaddr*>(host_addr),
+	                  host_addrlen);
+}
+
+#if defined(_WIN32)
+static bool IsSocketNonBlocking(int guest_fd) {
+	Common::LockGuard lock(g_socket_mutex);
+	if (guest_fd < 0 || guest_fd >= SOCKET_FD_MAX) {
+		return false;
+	}
+	const auto& slot = g_sockets[static_cast<size_t>(guest_fd)];
+	return slot.transport != nullptr && slot.transport->nonblocking;
+}
+
+static bool SocketIsStream(NativeSocket socket) {
+	int          type = 0;
+	SocketLength len  = sizeof(type);
+	return getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type), &len) == 0 &&
+	       type == SOCK_STREAM;
+}
+
+// A peek never consumes, so the buffered prefix keeps the socket readable and a poll would
+// return immediately. The retries are paced instead, and the poll is only used to notice a
+// closed or reset peer, which ends the wait with the short read the guest expects. A blocking
+// MSG_WAITALL may otherwise wait indefinitely: that is the requested semantics when a peer
+// stays open but sends only a prefix, so imposing an arbitrary timeout would truncate it.
+static short PollSocket(NativeSocket socket) {
+	WSAPOLLFD event {};
+	event.fd     = socket;
+	event.events = POLLRDNORM;
+	return WSAPoll(&event, 1, 0) > 0 ? event.revents : 0;
+}
+
+static bool WaitForPeekedBytes(NativeSocket socket) {
+	std::this_thread::sleep_for(std::chrono::milliseconds(1));
+	constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL;
+	return (PollSocket(socket) & terminal_events) != 0;
+}
+
+// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP, so the requested length is
+// waited for by peeking until it is buffered. Datagram sockets ignore MSG_WAITALL and
+// non-blocking sockets hand back whatever arrived, matching the guest (FreeBSD) behaviour.
+static int64_t RecvPeekWaitAll(NativeSocket socket, bool nonblocking, bool no_wait, char* buf,
+                               SocketIoLength host_len, sockaddr_storage* host_addr,
+                               SocketLength* host_addrlen) {
+	if (host_len == 0 && (host_addr == nullptr || SocketIsStream(socket))) {
+		// Winsock blocks on a zero length receive from an empty stream socket, while the
+		// guest expects an immediate zero. Datagram peeks still report the source address.
+		return 0;
+	}
+	if (no_wait && !nonblocking) {
+		// Winsock has no MSG_DONTWAIT, so readiness decides whether a peek may run at all.
+		constexpr short input_events = POLLRDNORM | POLLHUP | POLLERR;
+		if ((PollSocket(socket) & input_events) == 0) {
+			return SetGuestSocketError(Posix::POSIX_EWOULDBLOCK);
+		}
+	}
+	bool peer_closed = false;
+	for (;;) {
+		char                 scratch = 0;
+		char*                peek_buf = buf;
+		SocketIoLength       peek_len = host_len;
+		if (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) {
+			// Winsock may reject a zero-length datagram peek before filling from. A
+			// one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source.
+			peek_buf = &scratch;
+			peek_len = 1;
+		}
+		const int64_t peeked =
+		    RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen);
+		if (peeked < 0) {
+			if (WSAGetLastError() == WSAEMSGSIZE) {
+				// Winsock copied a truncated datagram prefix, but a zero-length peek can also
+				// report the non-empty message this way. The outer receive maps both to len.
+				return host_len;
+			}
+			return SetHostSocketError();
+		}
+		if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
+		    !SocketIsStream(socket)) {
+			return peeked;

Fixed in c2f3df6d, using the clamp you suggested:

if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
    !SocketIsStream(socket)) {
    return std::min<int64_t>(peeked, static_cast<int64_t>(host_len));
}

so the one-byte scratch byte can never be reported as guest data. I also took the chance to make it std::min rather than a host_len == 0 special case, since that also keeps a short non-blocking or datagram result from exceeding what was requested.

Covered by a new test in a4bd1c02: a queued one-byte datagram followed by a zero-length Recvfrom that asks for the source address must return 0, report the sender, and leave the datagram readable afterwards. I confirmed the assertion is load-bearing by inverting it and watching the suite fail with zero-length peek does not report scratch data, then restoring it.

The short-send finding on the same PR is also in a4bd1c02: the peer thread now records Net::Send for the second fragment and the main thread asserts it returned second_length after the join, so a short or failed send fails the test instead of hanging in the blocking PEEK|WAITALL receive.

**@⁠theantipopau** on GitHub · 2026-09-26 01:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4109767815) On `src/libs/network.cpp` line 1169 (outdated): ```diff @@ -1076,6 +1081,98 @@ static int ConvertMessageFlags(int flags) { return host_flags; } +static int64_t RecvHost(NativeSocket socket, char* buf, SocketIoLength host_len, int host_flags, + sockaddr_storage* host_addr, SocketLength* host_addrlen) { + if (host_addr == nullptr) { + return ::recv(socket, buf, host_len, host_flags); + } + return ::recvfrom(socket, buf, host_len, host_flags, reinterpret_cast<sockaddr*>(host_addr), + host_addrlen); +} + +#if defined(_WIN32) +static bool IsSocketNonBlocking(int guest_fd) { + Common::LockGuard lock(g_socket_mutex); + if (guest_fd < 0 || guest_fd >= SOCKET_FD_MAX) { + return false; + } + const auto& slot = g_sockets[static_cast<size_t>(guest_fd)]; + return slot.transport != nullptr && slot.transport->nonblocking; +} + +static bool SocketIsStream(NativeSocket socket) { + int type = 0; + SocketLength len = sizeof(type); + return getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type), &len) == 0 && + type == SOCK_STREAM; +} + +// A peek never consumes, so the buffered prefix keeps the socket readable and a poll would +// return immediately. The retries are paced instead, and the poll is only used to notice a +// closed or reset peer, which ends the wait with the short read the guest expects. A blocking +// MSG_WAITALL may otherwise wait indefinitely: that is the requested semantics when a peer +// stays open but sends only a prefix, so imposing an arbitrary timeout would truncate it. +static short PollSocket(NativeSocket socket) { + WSAPOLLFD event {}; + event.fd = socket; + event.events = POLLRDNORM; + return WSAPoll(&event, 1, 0) > 0 ? event.revents : 0; +} + +static bool WaitForPeekedBytes(NativeSocket socket) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL; + return (PollSocket(socket) & terminal_events) != 0; +} + +// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP, so the requested length is +// waited for by peeking until it is buffered. Datagram sockets ignore MSG_WAITALL and +// non-blocking sockets hand back whatever arrived, matching the guest (FreeBSD) behaviour. +static int64_t RecvPeekWaitAll(NativeSocket socket, bool nonblocking, bool no_wait, char* buf, + SocketIoLength host_len, sockaddr_storage* host_addr, + SocketLength* host_addrlen) { + if (host_len == 0 && (host_addr == nullptr || SocketIsStream(socket))) { + // Winsock blocks on a zero length receive from an empty stream socket, while the + // guest expects an immediate zero. Datagram peeks still report the source address. + return 0; + } + if (no_wait && !nonblocking) { + // Winsock has no MSG_DONTWAIT, so readiness decides whether a peek may run at all. + constexpr short input_events = POLLRDNORM | POLLHUP | POLLERR; + if ((PollSocket(socket) & input_events) == 0) { + return SetGuestSocketError(Posix::POSIX_EWOULDBLOCK); + } + } + bool peer_closed = false; + for (;;) { + char scratch = 0; + char* peek_buf = buf; + SocketIoLength peek_len = host_len; + if (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) { + // Winsock may reject a zero-length datagram peek before filling from. A + // one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source. + peek_buf = &scratch; + peek_len = 1; + } + const int64_t peeked = + RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen); + if (peeked < 0) { + if (WSAGetLastError() == WSAEMSGSIZE) { + // Winsock copied a truncated datagram prefix, but a zero-length peek can also + // report the non-empty message this way. The outer receive maps both to len. + return host_len; + } + return SetHostSocketError(); + } + if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || + !SocketIsStream(socket)) { + return peeked; ``` Fixed in `c2f3df6d`, using the clamp you suggested: ```c if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || !SocketIsStream(socket)) { return std::min<int64_t>(peeked, static_cast<int64_t>(host_len)); } ``` so the one-byte scratch byte can never be reported as guest data. I also took the chance to make it `std::min` rather than a `host_len == 0` special case, since that also keeps a short non-blocking or datagram result from exceeding what was requested. Covered by a new test in `a4bd1c02`: a queued one-byte datagram followed by a zero-length `Recvfrom` that asks for the source address must return 0, report the sender, and leave the datagram readable afterwards. I confirmed the assertion is load-bearing by inverting it and watching the suite fail with `zero-length peek does not report scratch data`, then restoring it. The short-send finding on the same PR is also in `a4bd1c02`: the peer thread now records `Net::Send` for the second fragment and the main thread asserts it returned `second_length` after the join, so a short or failed send fails the test instead of hanging in the blocking `PEEK|WAITALL` receive.
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 01:43 UTC · original
On tests/KernelFileSystemTests.cpp line 473 (outdated):

@@ -454,19 +458,171 @@ void CheckSocketWakeup() {
         "guest PEEK and WAITALL preserve the wake bytes");
   Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload),
         "consume wake bytes with guest WAITALL");
+
+  // A full message split across writes must still complete a WAITALL receive, and the
+  // peeked bytes have to survive for the following receive.
+  const char text[] = "fragment";
+  constexpr std::size_t text_length = 8;    // without the terminator
+  constexpr std::size_t prefix_length = 5;  // deliberately short of text_length
+  Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2,
+        "send the first fragment");
+  const char* const second_fragment = text + text_length / 2;
+  const std::size_t second_length   = text_length - text_length / 2;
+  std::thread peer([&writer, second_fragment, second_length] {
+    std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    Net::Send(writer, second_fragment, second_length, 0);

Fixed in c2f3df6d, using the clamp you suggested:

if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
    !SocketIsStream(socket)) {
    return std::min<int64_t>(peeked, static_cast<int64_t>(host_len));
}

so the one-byte scratch byte can never be reported as guest data. I also took the chance to make it std::min rather than a host_len == 0 special case, since that also keeps a short non-blocking or datagram result from exceeding what was requested.

Covered by a new test in a4bd1c02: a queued one-byte datagram followed by a zero-length Recvfrom that asks for the source address must return 0, report the sender, and leave the datagram readable afterwards. I confirmed the assertion is load-bearing by inverting it and watching the suite fail with zero-length peek does not report scratch data, then restoring it.

The short-send finding on the same PR is also in a4bd1c02: the peer thread now records Net::Send for the second fragment and the main thread asserts it returned second_length after the join, so a short or failed send fails the test instead of hanging in the blocking PEEK|WAITALL receive.

**@⁠theantipopau** on GitHub · 2026-09-26 01:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4109767905) On `tests/KernelFileSystemTests.cpp` line 473 (outdated): ```diff @@ -454,19 +458,171 @@ void CheckSocketWakeup() { "guest PEEK and WAITALL preserve the wake bytes"); Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload), "consume wake bytes with guest WAITALL"); + + // A full message split across writes must still complete a WAITALL receive, and the + // peeked bytes have to survive for the following receive. + const char text[] = "fragment"; + constexpr std::size_t text_length = 8; // without the terminator + constexpr std::size_t prefix_length = 5; // deliberately short of text_length + Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2, + "send the first fragment"); + const char* const second_fragment = text + text_length / 2; + const std::size_t second_length = text_length - text_length / 2; + std::thread peer([&writer, second_fragment, second_length] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + Net::Send(writer, second_fragment, second_length, 0); ``` Fixed in `c2f3df6d`, using the clamp you suggested: ```c if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || !SocketIsStream(socket)) { return std::min<int64_t>(peeked, static_cast<int64_t>(host_len)); } ``` so the one-byte scratch byte can never be reported as guest data. I also took the chance to make it `std::min` rather than a `host_len == 0` special case, since that also keeps a short non-blocking or datagram result from exceeding what was requested. Covered by a new test in `a4bd1c02`: a queued one-byte datagram followed by a zero-length `Recvfrom` that asks for the source address must return 0, report the sender, and leave the datagram readable afterwards. I confirmed the assertion is load-bearing by inverting it and watching the suite fail with `zero-length peek does not report scratch data`, then restoring it. The short-send finding on the same PR is also in `a4bd1c02`: the peer thread now records `Net::Send` for the second fragment and the main thread asserts it returned `second_length` after the join, so a short or failed send fails the test instead of hanging in the blocking `PEEK|WAITALL` receive.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:09 UTC · original
On src/libs/network.cpp line 1169 (outdated):

@@ -1076,6 +1081,98 @@ static int ConvertMessageFlags(int flags) {
 	return host_flags;
 }
 
+static int64_t RecvHost(NativeSocket socket, char* buf, SocketIoLength host_len, int host_flags,
+                        sockaddr_storage* host_addr, SocketLength* host_addrlen) {
+	if (host_addr == nullptr) {
+		return ::recv(socket, buf, host_len, host_flags);
+	}
+	return ::recvfrom(socket, buf, host_len, host_flags, reinterpret_cast<sockaddr*>(host_addr),
+	                  host_addrlen);
+}
+
+#if defined(_WIN32)
+static bool IsSocketNonBlocking(int guest_fd) {
+	Common::LockGuard lock(g_socket_mutex);
+	if (guest_fd < 0 || guest_fd >= SOCKET_FD_MAX) {
+		return false;
+	}
+	const auto& slot = g_sockets[static_cast<size_t>(guest_fd)];
+	return slot.transport != nullptr && slot.transport->nonblocking;
+}
+
+static bool SocketIsStream(NativeSocket socket) {
+	int          type = 0;
+	SocketLength len  = sizeof(type);
+	return getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type), &len) == 0 &&
+	       type == SOCK_STREAM;
+}
+
+// A peek never consumes, so the buffered prefix keeps the socket readable and a poll would
+// return immediately. The retries are paced instead, and the poll is only used to notice a
+// closed or reset peer, which ends the wait with the short read the guest expects. A blocking
+// MSG_WAITALL may otherwise wait indefinitely: that is the requested semantics when a peer
+// stays open but sends only a prefix, so imposing an arbitrary timeout would truncate it.
+static short PollSocket(NativeSocket socket) {
+	WSAPOLLFD event {};
+	event.fd     = socket;
+	event.events = POLLRDNORM;
+	return WSAPoll(&event, 1, 0) > 0 ? event.revents : 0;
+}
+
+static bool WaitForPeekedBytes(NativeSocket socket) {
+	std::this_thread::sleep_for(std::chrono::milliseconds(1));
+	constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL;
+	return (PollSocket(socket) & terminal_events) != 0;
+}
+
+// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP, so the requested length is
+// waited for by peeking until it is buffered. Datagram sockets ignore MSG_WAITALL and
+// non-blocking sockets hand back whatever arrived, matching the guest (FreeBSD) behaviour.
+static int64_t RecvPeekWaitAll(NativeSocket socket, bool nonblocking, bool no_wait, char* buf,
+                               SocketIoLength host_len, sockaddr_storage* host_addr,
+                               SocketLength* host_addrlen) {
+	if (host_len == 0 && (host_addr == nullptr || SocketIsStream(socket))) {
+		// Winsock blocks on a zero length receive from an empty stream socket, while the
+		// guest expects an immediate zero. Datagram peeks still report the source address.
+		return 0;
+	}
+	if (no_wait && !nonblocking) {
+		// Winsock has no MSG_DONTWAIT, so readiness decides whether a peek may run at all.
+		constexpr short input_events = POLLRDNORM | POLLHUP | POLLERR;
+		if ((PollSocket(socket) & input_events) == 0) {
+			return SetGuestSocketError(Posix::POSIX_EWOULDBLOCK);
+		}
+	}
+	bool peer_closed = false;
+	for (;;) {
+		char                 scratch = 0;
+		char*                peek_buf = buf;
+		SocketIoLength       peek_len = host_len;
+		if (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) {
+			// Winsock may reject a zero-length datagram peek before filling from. A
+			// one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source.
+			peek_buf = &scratch;
+			peek_len = 1;
+		}
+		const int64_t peeked =
+		    RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen);
+		if (peeked < 0) {
+			if (WSAGetLastError() == WSAEMSGSIZE) {
+				// Winsock copied a truncated datagram prefix, but a zero-length peek can also
+				// report the non-empty message this way. The outer receive maps both to len.
+				return host_len;
+			}
+			return SetHostSocketError();
+		}
+		if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait ||
+		    !SocketIsStream(socket)) {
+			return peeked;
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git rev-parse --short HEAD
ast-grep outline src/libs/network.cpp --match 'RecvPeekWaitAll|Recvfrom' --view expanded
ast-grep outline tests/KernelFileSystemTests.cpp --match 'CheckSocketWakeup' --view expanded
rg -n -C 12 'return std::min<int64_t>\(peeked|zero.length peek does not report scratch data|one.byte datagram|second_length' src/libs/network.cpp tests/KernelFileSystemTests.cpp

Length of output: 10254


🏁 Script executed:

#!/bin/bash
set -euo pipefail
git rev-parse --short HEAD
ast-grep outline src/libs/network.cpp --match 'RecvPeekWaitAll|Recvfrom' --view expanded
ast-grep outline tests/KernelFileSystemTests.cpp --match 'CheckSocketWakeup' --view expanded
rg -n -C 12 'return std::min<int64_t>\(peeked|zero.length peek does not report scratch data|one.byte datagram|second_length' src/libs/network.cpp tests/KernelFileSystemTests.cpp

Length of output: 10226


@theantipopau, the repository check is complete. RecvPeekWaitAll now clamps peeked to host_len. The regression test checks that a zero-length peek of a one-byte datagram returns 0, reports the sender, and leaves the datagram available to receive. My earlier reply said the repository check was incomplete; that is no longer the case. I did not run the test suite.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4109834752) On `src/libs/network.cpp` line 1169 (outdated): ```diff @@ -1076,6 +1081,98 @@ static int ConvertMessageFlags(int flags) { return host_flags; } +static int64_t RecvHost(NativeSocket socket, char* buf, SocketIoLength host_len, int host_flags, + sockaddr_storage* host_addr, SocketLength* host_addrlen) { + if (host_addr == nullptr) { + return ::recv(socket, buf, host_len, host_flags); + } + return ::recvfrom(socket, buf, host_len, host_flags, reinterpret_cast<sockaddr*>(host_addr), + host_addrlen); +} + +#if defined(_WIN32) +static bool IsSocketNonBlocking(int guest_fd) { + Common::LockGuard lock(g_socket_mutex); + if (guest_fd < 0 || guest_fd >= SOCKET_FD_MAX) { + return false; + } + const auto& slot = g_sockets[static_cast<size_t>(guest_fd)]; + return slot.transport != nullptr && slot.transport->nonblocking; +} + +static bool SocketIsStream(NativeSocket socket) { + int type = 0; + SocketLength len = sizeof(type); + return getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type), &len) == 0 && + type == SOCK_STREAM; +} + +// A peek never consumes, so the buffered prefix keeps the socket readable and a poll would +// return immediately. The retries are paced instead, and the poll is only used to notice a +// closed or reset peer, which ends the wait with the short read the guest expects. A blocking +// MSG_WAITALL may otherwise wait indefinitely: that is the requested semantics when a peer +// stays open but sends only a prefix, so imposing an arbitrary timeout would truncate it. +static short PollSocket(NativeSocket socket) { + WSAPOLLFD event {}; + event.fd = socket; + event.events = POLLRDNORM; + return WSAPoll(&event, 1, 0) > 0 ? event.revents : 0; +} + +static bool WaitForPeekedBytes(NativeSocket socket) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL; + return (PollSocket(socket) & terminal_events) != 0; +} + +// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP, so the requested length is +// waited for by peeking until it is buffered. Datagram sockets ignore MSG_WAITALL and +// non-blocking sockets hand back whatever arrived, matching the guest (FreeBSD) behaviour. +static int64_t RecvPeekWaitAll(NativeSocket socket, bool nonblocking, bool no_wait, char* buf, + SocketIoLength host_len, sockaddr_storage* host_addr, + SocketLength* host_addrlen) { + if (host_len == 0 && (host_addr == nullptr || SocketIsStream(socket))) { + // Winsock blocks on a zero length receive from an empty stream socket, while the + // guest expects an immediate zero. Datagram peeks still report the source address. + return 0; + } + if (no_wait && !nonblocking) { + // Winsock has no MSG_DONTWAIT, so readiness decides whether a peek may run at all. + constexpr short input_events = POLLRDNORM | POLLHUP | POLLERR; + if ((PollSocket(socket) & input_events) == 0) { + return SetGuestSocketError(Posix::POSIX_EWOULDBLOCK); + } + } + bool peer_closed = false; + for (;;) { + char scratch = 0; + char* peek_buf = buf; + SocketIoLength peek_len = host_len; + if (peek_len == 0 && host_addr != nullptr && !SocketIsStream(socket)) { + // Winsock may reject a zero-length datagram peek before filling from. A + // one-byte scratch buffer keeps MSG_PEEK semantics while obtaining the source. + peek_buf = &scratch; + peek_len = 1; + } + const int64_t peeked = + RecvHost(socket, peek_buf, peek_len, MSG_PEEK, host_addr, host_addrlen); + if (peeked < 0) { + if (WSAGetLastError() == WSAEMSGSIZE) { + // Winsock copied a truncated datagram prefix, but a zero-length peek can also + // report the non-empty message this way. The outer receive maps both to len. + return host_len; + } + return SetHostSocketError(); + } + if (peeked >= host_len || peeked == 0 || peer_closed || nonblocking || no_wait || + !SocketIsStream(socket)) { + return peeked; ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git rev-parse --short HEAD ast-grep outline src/libs/network.cpp --match 'RecvPeekWaitAll|Recvfrom' --view expanded ast-grep outline tests/KernelFileSystemTests.cpp --match 'CheckSocketWakeup' --view expanded rg -n -C 12 'return std::min<int64_t>\(peeked|zero.length peek does not report scratch data|one.byte datagram|second_length' src/libs/network.cpp tests/KernelFileSystemTests.cpp ``` Length of output: 10254 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git rev-parse --short HEAD ast-grep outline src/libs/network.cpp --match 'RecvPeekWaitAll|Recvfrom' --view expanded ast-grep outline tests/KernelFileSystemTests.cpp --match 'CheckSocketWakeup' --view expanded rg -n -C 12 'return std::min<int64_t>\(peeked|zero.length peek does not report scratch data|one.byte datagram|second_length' src/libs/network.cpp tests/KernelFileSystemTests.cpp ``` Length of output: 10226 --- </details> `@theantipopau`, the repository check is complete. `RecvPeekWaitAll` now clamps `peeked` to `host_len`. The regression test checks that a zero-length peek of a one-byte datagram returns 0, reports the sender, and leaves the datagram available to receive. My earlier reply said the repository check was incomplete; that is no longer the case. I did not run the test suite. ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 02:09 UTC · original
On tests/KernelFileSystemTests.cpp line 473 (outdated):

@@ -454,19 +458,171 @@ void CheckSocketWakeup() {
         "guest PEEK and WAITALL preserve the wake bytes");
   Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload),
         "consume wake bytes with guest WAITALL");
+
+  // A full message split across writes must still complete a WAITALL receive, and the
+  // peeked bytes have to survive for the following receive.
+  const char text[] = "fragment";
+  constexpr std::size_t text_length = 8;    // without the terminator
+  constexpr std::size_t prefix_length = 5;  // deliberately short of text_length
+  Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2,
+        "send the first fragment");
+  const char* const second_fragment = text + text_length / 2;
+  const std::size_t second_length   = text_length - text_length / 2;
+  std::thread peer([&writer, second_fragment, second_length] {
+    std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    Net::Send(writer, second_fragment, second_length, 0);
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
ast-grep outline src/libs/network.cpp --match 'Shutdown|Recv|Recvfrom|SocketIsStream' --view expanded
ast-grep outline tests/KernelFileSystemTests.cpp --match CheckSocketWakeup --view expanded
rg -n -C 9 'int(64_t)?\s+Shutdown\s*\(|Shutdown\s*\(|peer_closed|peeked >= host_len|second_send_result|std::thread peer' src/libs/network.cpp tests/KernelFileSystemTests.cpp | head -240

Length of output: 11804


🏁 Script executed:

#!/bin/bash
set -euo pipefail
ast-grep outline src/libs/network.cpp --match 'WaitForPeekedBytes|Shutdown|RecvPeekWaitAll|Receive' --view expanded
rg -n -C 7 '\bWaitForPeekedBytes\s*\(|\bShutdown\s*\(|\bRecvPeekWaitAll\s*\(|\bRecv\s*\(' src/libs/network.cpp | head -215
sed -n '1050,1180p' src/libs/network.cpp
sed -n '2055,2090p' src/libs/network.cpp
sed -n '2230,2310p' src/libs/network.cpp

Length of output: 12713


@theantipopau, I need to correct my earlier reply. I closed this finding too soon.

The half-close can release the receive on Windows. On non-Windows builds, Net::Shutdown(writer, 1) returns POSIX_ENOSYS and leaves the writer open. If the second send is short or fails, the blocking PEEK|WAITALL receive can still wait indefinitely, before the test reaches the result check.

Please close the writer on the non-Windows failure path as well. The finding remains open for that case.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 02:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4109834954) On `tests/KernelFileSystemTests.cpp` line 473 (outdated): ```diff @@ -454,19 +458,171 @@ void CheckSocketWakeup() { "guest PEEK and WAITALL preserve the wake bytes"); Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload), "consume wake bytes with guest WAITALL"); + + // A full message split across writes must still complete a WAITALL receive, and the + // peeked bytes have to survive for the following receive. + const char text[] = "fragment"; + constexpr std::size_t text_length = 8; // without the terminator + constexpr std::size_t prefix_length = 5; // deliberately short of text_length + Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2, + "send the first fragment"); + const char* const second_fragment = text + text_length / 2; + const std::size_t second_length = text_length - text_length / 2; + std::thread peer([&writer, second_fragment, second_length] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + Net::Send(writer, second_fragment, second_length, 0); ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail ast-grep outline src/libs/network.cpp --match 'Shutdown|Recv|Recvfrom|SocketIsStream' --view expanded ast-grep outline tests/KernelFileSystemTests.cpp --match CheckSocketWakeup --view expanded rg -n -C 9 'int(64_t)?\s+Shutdown\s*\(|Shutdown\s*\(|peer_closed|peeked >= host_len|second_send_result|std::thread peer' src/libs/network.cpp tests/KernelFileSystemTests.cpp | head -240 ``` Length of output: 11804 --- 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail ast-grep outline src/libs/network.cpp --match 'WaitForPeekedBytes|Shutdown|RecvPeekWaitAll|Receive' --view expanded rg -n -C 7 '\bWaitForPeekedBytes\s*\(|\bShutdown\s*\(|\bRecvPeekWaitAll\s*\(|\bRecv\s*\(' src/libs/network.cpp | head -215 sed -n '1050,1180p' src/libs/network.cpp sed -n '2055,2090p' src/libs/network.cpp sed -n '2230,2310p' src/libs/network.cpp ``` Length of output: 12713 --- </details> `@theantipopau`, I need to correct my earlier reply. I closed this finding too soon. The half-close can release the receive on Windows. On non-Windows builds, `Net::Shutdown(writer, 1)` returns `POSIX_ENOSYS` and leaves the writer open. If the second send is short or fails, the blocking `PEEK|WAITALL` receive can still wait indefinitely, before the test reaches the result check. Please close the writer on the non-Windows failure path as well. The finding remains open for that case. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 03:24 UTC · original
On tests/KernelFileSystemTests.cpp line 473 (outdated):

@@ -454,19 +458,171 @@ void CheckSocketWakeup() {
         "guest PEEK and WAITALL preserve the wake bytes");
   Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload),
         "consume wake bytes with guest WAITALL");
+
+  // A full message split across writes must still complete a WAITALL receive, and the
+  // peeked bytes have to survive for the following receive.
+  const char text[] = "fragment";
+  constexpr std::size_t text_length = 8;    // without the terminator
+  constexpr std::size_t prefix_length = 5;  // deliberately short of text_length
+  Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2,
+        "send the first fragment");
+  const char* const second_fragment = text + text_length / 2;
+  const std::size_t second_length   = text_length - text_length / 2;
+  std::thread peer([&writer, second_fragment, second_length] {
+    std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    Net::Send(writer, second_fragment, second_length, 0);

Fixed in a599ad42.

You are right about the platform gap: Net::Shutdown with SD_SEND maps to a real half-close only on Windows and returns POSIX_ENOSYS elsewhere, so the guard I added was Windows-only. The failure path now closes the writer too (Net::SocketClose(writer) after Net::Shutdown(writer, 1)), which produces a visible EOF/error on the reader on every platform, so the blocking PEEK|WAITALL receive cannot strand when the second send is short or fails.

kernel_file_system_tests builds clean and passed three consecutive full runs (the suite that previously hung without this class of guard).

**@⁠theantipopau** on GitHub · 2026-09-26 03:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4110017708) On `tests/KernelFileSystemTests.cpp` line 473 (outdated): ```diff @@ -454,19 +458,171 @@ void CheckSocketWakeup() { "guest PEEK and WAITALL preserve the wake bytes"); Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload), "consume wake bytes with guest WAITALL"); + + // A full message split across writes must still complete a WAITALL receive, and the + // peeked bytes have to survive for the following receive. + const char text[] = "fragment"; + constexpr std::size_t text_length = 8; // without the terminator + constexpr std::size_t prefix_length = 5; // deliberately short of text_length + Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2, + "send the first fragment"); + const char* const second_fragment = text + text_length / 2; + const std::size_t second_length = text_length - text_length / 2; + std::thread peer([&writer, second_fragment, second_length] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + Net::Send(writer, second_fragment, second_length, 0); ``` Fixed in a599ad42. You are right about the platform gap: `Net::Shutdown` with `SD_SEND` maps to a real half-close only on Windows and returns `POSIX_ENOSYS` elsewhere, so the guard I added was Windows-only. The failure path now closes the writer too (`Net::SocketClose(writer)` after `Net::Shutdown(writer, 1)`), which produces a visible EOF/error on the reader on every platform, so the blocking `PEEK|WAITALL` receive cannot strand when the second send is short or fails. `kernel_file_system_tests` builds clean and passed three consecutive full runs (the suite that previously hung without this class of guard).
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 03:27 UTC · original · reviewed

Caution

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

⚠️ Outside diff range comments (1)

🟡 Minor · Avoid fixed 1 ms polling in RecvPeekWaitAll. · network.cpp:1139-1171

src/libs/network.cpp:1139-1171
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Avoid fixed 1 ms polling in RecvPeekWaitAll.

Recvfrom routes blocking Windows stream receives with MSG_PEEK|MSG_WAITALL to RecvPeekWaitAll. A short recv(MSG_PEEK) leaves the prefix buffered, so WSAPoll reports POLLRDNORM immediately on each iteration. WaitForPeekedBytes ignores that readiness and checks only terminal events after a 1 ms sleep. An open peer that sends no more data therefore causes repeated wakeups, polls, and peeks until more data arrives. Keep the wait indefinite, but replace the fixed-interval polling with backoff or an event-driven wait.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: e605856b-ed22-4b54-9a71-be43df685b66

📥 Commits

Reviewing files that changed from the base of the PR and between 12647c97336883afa1e60c8a53d174dfc6cbfc06 and a599ad42b926e408653a1f075855f178b4472ab1.

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

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 03:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#pullrequestreview-5324382931) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟡 Minor</em> · Avoid fixed 1 ms polling in <code>RecvPeekWaitAll</code>. · <code>network.cpp:1139-1171</code></summary><blockquote> > > `src/libs/network.cpp:1139-1171` > _🚀 Performance & Scalability_ | _🟡 Minor_ | _⚡ Quick win_ > > **Avoid fixed 1 ms polling in `RecvPeekWaitAll`.** > > `Recvfrom` routes blocking Windows stream receives with `MSG_PEEK|MSG_WAITALL` to `RecvPeekWaitAll`. A short `recv(MSG_PEEK)` leaves the prefix buffered, so `WSAPoll` reports `POLLRDNORM` immediately on each iteration. `WaitForPeekedBytes` ignores that readiness and checks only terminal events after a 1 ms sleep. An open peer that sends no more data therefore causes repeated wakeups, polls, and peeks until more data arrives. Keep the wait indefinite, but replace the fixed-interval polling with backoff or an event-driven wait. > > <!-- cr-comment:v1:d8a12b59a165fdcc7f7c2b38 --> > > </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**: `e605856b-ed22-4b54-9a71-be43df685b66` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 12647c97336883afa1e60c8a53d174dfc6cbfc06 and a599ad42b926e408653a1f075855f178b4472ab1. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `tests/KernelFileSystemTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * tests/KernelFileSystemTests.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 03:32 UTC · original
On tests/KernelFileSystemTests.cpp line 473 (outdated):

@@ -454,19 +458,171 @@ void CheckSocketWakeup() {
         "guest PEEK and WAITALL preserve the wake bytes");
   Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload),
         "consume wake bytes with guest WAITALL");
+
+  // A full message split across writes must still complete a WAITALL receive, and the
+  // peeked bytes have to survive for the following receive.
+  const char text[] = "fragment";
+  constexpr std::size_t text_length = 8;    // without the terminator
+  constexpr std::size_t prefix_length = 5;  // deliberately short of text_length
+  Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2,
+        "send the first fragment");
+  const char* const second_fragment = text + text_length / 2;
+  const std::size_t second_length   = text_length - text_length / 2;
+  std::thread peer([&writer, second_fragment, second_length] {
+    std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    Net::Send(writer, second_fragment, second_length, 0);

@theantipopau, the updated CheckSocketWakeup() failure path calls Net::SocketClose(writer) after Net::Shutdown(writer, 1). That closes the writer on non-Windows builds even when Shutdown is a no-op. The thread also records the second send result for the test assertion. Thanks for the fix and the test results.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 03:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#discussion_r4110038325) On `tests/KernelFileSystemTests.cpp` line 473 (outdated): ```diff @@ -454,19 +458,171 @@ void CheckSocketWakeup() { "guest PEEK and WAITALL preserve the wake bytes"); Check(Net::Recv(reader, received.data(), received.size(), 0x40) == sizeof(payload), "consume wake bytes with guest WAITALL"); + + // A full message split across writes must still complete a WAITALL receive, and the + // peeked bytes have to survive for the following receive. + const char text[] = "fragment"; + constexpr std::size_t text_length = 8; // without the terminator + constexpr std::size_t prefix_length = 5; // deliberately short of text_length + Check(Net::Send(writer, text, text_length / 2, 0) == text_length / 2, + "send the first fragment"); + const char* const second_fragment = text + text_length / 2; + const std::size_t second_length = text_length - text_length / 2; + std::thread peer([&writer, second_fragment, second_length] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + Net::Send(writer, second_fragment, second_length, 0); ``` `@theantipopau`, the updated `CheckSocketWakeup()` failure path calls `Net::SocketClose(writer)` after `Net::Shutdown(writer, 1)`. That closes the writer on non-Windows builds even when `Shutdown` is a no-op. The thread also records the second send result for the test assertion. Thanks for the fix and the test results. ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-27 13:04 UTC · original

Merged current upstream/main (through 025b39c0). One thing worth flagging for
anyone else carrying a branch that touches CheckSocketWakeup:

#851 added a net_recv(..., MSG_WAITALL) consume of the five wake bytes, and
this branch already consumed those same five bytes with
Net::Recv(..., MSG_WAITALL). Both survived the merge, so the second blocking
receive waited for bytes the first had already taken — the test hung instead of
failing, which is the worst shape for CI. The #797 commit already fixed this
class of failure once (f133b246, half-close the writer so a short send
surfaces as a short read rather than a spin); this was the same hazard from the
consumer side.

Resolution, same on both PRs:

  • keep upstream's guest-export consume and its invalid-argument and
    errno-preserving checks, drop the duplicate direct consume, and re-cover the
    direct Net::Recv guest MSG_WAITALL path on a freshly sent whole message;
  • run the invalid-argument checks while both sockets are still open, then the
    end-of-file block closes the writer once, then upstream's errno-preserving EOF
    check and its reader close end the function.

kernel_file_system_tests builds and passes 3x in a row on the merged result on
Windows/clang-cl.

**@⁠theantipopau** on GitHub · 2026-09-27 13:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/799#issuecomment-5856112735) Merged current `upstream/main` (through `025b39c0`). One thing worth flagging for anyone else carrying a branch that touches `CheckSocketWakeup`: `#851` added a `net_recv(..., MSG_WAITALL)` consume of the five wake bytes, and this branch already consumed those same five bytes with `Net::Recv(..., MSG_WAITALL)`. Both survived the merge, so the second blocking receive waited for bytes the first had already taken — the test hung instead of failing, which is the worst shape for CI. The `#797` commit already fixed this class of failure once (`f133b246`, half-close the writer so a short send surfaces as a short read rather than a spin); this was the same hazard from the consumer side. Resolution, same on both PRs: * keep upstream's guest-export consume and its invalid-argument and errno-preserving checks, drop the duplicate direct consume, and re-cover the direct `Net::Recv` guest `MSG_WAITALL` path on a freshly sent whole message; * run the invalid-argument checks while both sockets are still open, then the end-of-file block closes the writer once, then upstream's errno-preserving EOF check and its reader close end the function. `kernel_file_system_tests` builds and passes 3x in a row on the merged result on Windows/clang-cl.

Pull request closed

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