net: resolve guest PEEK and WAITALL flags on Windows #751

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

@⁠rudy-07 on GitHub · 2026-09-21 15:19 UTC · original
fix/win32-msg-peek-waitall-505 → main · +164 −2 · 2 files · 4 commits · closed without merging

Closes #505

Summary

Resolves the Windows linker failure and test failure in KernelFileSystemTests (guest PEEK and WAITALL preserve the wake bytes, exit code 0xc0000409).

Root Cause

  1. Linker Failure: #include "SDL.h" without SDL_MAIN_HANDLED redirects main to SDL_main, causing lld-link to fail with undefined symbol: main when building kernel_file_system_tests on Windows.
  2. Winsock Flag Incompatibility: In FreeBSD / POSIX, combining MSG_PEEK and MSG_WAITALL is valid. However, on Windows Winsock, passing both flags to ::recv() causes Winsock to return WSAEOPNOTSUPP (10045).

Solution

  1. SDL_MAIN_HANDLED: Defined ahead of #include "SDL.h" in KernelFileSystemTests.cpp so the test binary links without rewriting main.
  2. Flag Mapping (ConvertMessageFlags): On Windows, masks out MSG_WAITALL when MSG_PEEK is active to prevent Winsock from rejecting the call with WSAEOPNOTSUPP.
  3. MSG_WAITALL Emulation (Recvfrom):
    • For blocking stream sockets on Windows, emulates MSG_WAITALL semantics when peeking: awaits host_len bytes via ioctlsocket(FIONREAD) / select / WSAPoll before peeking, avoiding short reads on chunked arrivals.
    • Preserves POSIX EOF behavior: breaks on peer close (POLLHUP) or error (POLLERR) and returns partial data.
    • Honors SO_RCVTIMEO if configured on the socket.
    • Non-blocking sockets (tracked via ORBIS_SO_NBIO or MSG_DONTWAIT) bypass the wait loop and delegate to native recv to return immediately or fail with WSAEWOULDBLOCK.
    • Propagates SOCKET_ERROR from WSAPoll.
  4. Docstring Coverage: Added Doxygen documentation to touched functions.
  5. Test Coverage: Added test assertions in KernelFileSystemTests.cpp verifying both non-blocking EWOULDBLOCK and chunked partial-arrival behavior.

Testing

  • Independently verified on Windows with clang-cl: clean build passes full test suite (40/40).
**@⁠rudy-07** on GitHub · 2026-09-21 15:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751) `fix/win32-msg-peek-waitall-505` → `main` · +164 −2 · 2 files · 4 commits · closed without merging Closes #505 ### Summary Resolves the Windows linker failure and test failure in `KernelFileSystemTests` (`guest PEEK and WAITALL preserve the wake bytes`, exit code `0xc0000409`). ### Root Cause 1. **Linker Failure**: `#include "SDL.h"` without `SDL_MAIN_HANDLED` redirects `main` to `SDL_main`, causing `lld-link` to fail with `undefined symbol: main` when building `kernel_file_system_tests` on Windows. 2. **Winsock Flag Incompatibility**: In FreeBSD / POSIX, combining `MSG_PEEK` and `MSG_WAITALL` is valid. However, on Windows Winsock, passing both flags to `::recv()` causes Winsock to return `WSAEOPNOTSUPP` (10045). ### Solution 1. **`SDL_MAIN_HANDLED`**: Defined ahead of `#include "SDL.h"` in `KernelFileSystemTests.cpp` so the test binary links without rewriting `main`. 2. **Flag Mapping (`ConvertMessageFlags`)**: On Windows, masks out `MSG_WAITALL` when `MSG_PEEK` is active to prevent Winsock from rejecting the call with `WSAEOPNOTSUPP`. 3. **`MSG_WAITALL` Emulation (`Recvfrom`)**: - For blocking stream sockets on Windows, emulates `MSG_WAITALL` semantics when peeking: awaits `host_len` bytes via `ioctlsocket(FIONREAD)` / `select` / `WSAPoll` before peeking, avoiding short reads on chunked arrivals. - Preserves POSIX EOF behavior: breaks on peer close (`POLLHUP`) or error (`POLLERR`) and returns partial data. - Honors `SO_RCVTIMEO` if configured on the socket. - Non-blocking sockets (tracked via `ORBIS_SO_NBIO` or `MSG_DONTWAIT`) bypass the wait loop and delegate to native `recv` to return immediately or fail with `WSAEWOULDBLOCK`. - Propagates `SOCKET_ERROR` from `WSAPoll`. 4. **Docstring Coverage**: Added Doxygen documentation to touched functions. 5. **Test Coverage**: Added test assertions in `KernelFileSystemTests.cpp` verifying both non-blocking `EWOULDBLOCK` and chunked partial-arrival behavior. ### Testing - Independently verified on Windows with `clang-cl`: clean build passes full test suite (40/40).
Closes #505

Under FreeBSD / POSIX, combining MSG_PEEK and MSG_WAITALL is valid. On Windows Winsock, passing both MSG_PEEK and MSG_WAITALL to recv() fails with error WSAEOPNOTSUPP (10045).

In ConvertMessageFlags(), when peeking on Windows, clear MSG_WAITALL so that host recv()/recvfrom() peeks at the socket buffer without error, preserving the wake bytes as asserted in KernelFileSystemTests.

Also define SDL_MAIN_HANDLED ahead of SDL.h in KernelFileSystemTests.cpp so the test executable links on Windows without SDL_main rewriting.
- Emulate MSG_WAITALL semantics on Windows when combined with MSG_PEEK on stream sockets by awaiting requested byte count before executing the peek.

- Handle partial arrivals, remote peer EOF (POLLHUP), errors (POLLERR), and SO_RCVTIMEO.

- Add Doxygen documentation to ConvertMessageFlags and Recvfrom to satisfy docstring coverage.
- Track socket nonblocking state in SocketSlot when updated via Setsockopt(ORBIS_SO_NBIO).

- Skip the Windows MSG_WAITALL emulation loop for nonblocking sockets, allowing native recv() to return available data or WSAEWOULDBLOCK.

- Propagate SOCKET_ERROR from WSAPoll via SetHostSocketError() instead of ignoring it.
- Verify that nonblocking sockets with guest PEEK and WAITALL return EWOULDBLOCK on empty reads.

- Verify that stream sockets correctly await chunked partial arrivals under guest PEEK and WAITALL before consuming them.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:31:35 +00:00
github-bot closed this pull request 2026-11-26 09:31:35 +00:00
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-09-21 15:21 UTC · original · reviewed

Copilot review overview

Windows peeks must preserve MSG_WAITALL semantics for partial arrivals.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
What changed in this PR

This PR fixes Windows handling of MSG_PEEK | MSG_WAITALL and SDL entry-point rewriting in the filesystem test.

Changes:

  • Adjusts Windows socket message flags for peeking.
  • Defines SDL_MAIN_HANDLED before including SDL headers.
File Summary
tests/​KernelFileSystemTests.cpp Prevents SDL from rewriting the test executable’s main.
src/​libs/​network.cpp Clears MSG_WAITALL for Windows peeks, but may lose wait-all behavior for partial arrivals.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-09-21 15:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#pullrequestreview-5268417795) · **reviewed** <!-- ccr-overview-v2 --> ## Copilot review overview ### 🟡 Changes recommended Windows peeks must preserve `MSG_WAITALL` semantics for partial arrivals. *Get a fresh assessment by requesting another Copilot review.* **Review effort:** Lite **Findings:** 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> <details open> <summary><strong>Open (1)</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Preserve MSG_WAITALL semantics when peeking on Windows](#discussion_r4063575622) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> This PR fixes Windows handling of `MSG_PEEK | MSG_WAITALL` and SDL entry-point rewriting in the filesystem test. **Changes:** - Adjusts Windows socket message flags for peeking. - Defines `SDL_MAIN_HANDLED` before including SDL headers. | File | Summary | |---|---| | `tests/​KernelFileSystemTests.cpp` | Prevents SDL from rewriting the test executable’s `main`. | | `src/​libs/​network.cpp` | Clears `MSG_WAITALL` for Windows peeks, but may lose wait-all behavior for partial arrivals. | </details> --- 💡 <a href="/KytyPS5/KytyPS5/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a `code-review` agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>
@ -1076,0 +1090,4 @@
// Winsock fails with WSAEOPNOTSUPP if MSG_PEEK and MSG_WAITALL are combined.
// When peeking on Windows, clear MSG_WAITALL so host recv/recvfrom succeeds while preserving socket data.
if ((host_flags & MSG_PEEK) != 0) {
host_flags &= ~MSG_WAITALL;
Author
Owner

@⁠Copilot on GitHub · 2026-09-21 15:21 UTC · original

This drops the guest MSG_WAITALL semantic whenever MSG_PEEK is present: on Windows a peek for len bytes can now return as soon as any bytes are available, whereas POSIX waits for the requested length (subject to its normal interruption/EOF rules). The current regression test sends the complete payload before receiving, so it does not expose this partial-arrival case. Please preserve WAITALL behavior by emulating the wait before peeking, rather than silently returning short reads.

**@⁠Copilot** on GitHub · 2026-09-21 15:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#discussion_r4063575622) This drops the guest `MSG_WAITALL` semantic whenever `MSG_PEEK` is present: on Windows a peek for `len` bytes can now return as soon as any bytes are available, whereas POSIX waits for the requested length (subject to its normal interruption/EOF rules). The current regression test sends the complete payload before receiving, so it does not expose this partial-arrival case. Please preserve `WAITALL` behavior by emulating the wait before peeking, rather than silently returning short reads.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-21 15:23 UTC · original · edited 2026-09-21 19:24 UTC

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

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: b02c990d-f1c1-44eb-aabd-5b9e56b0c1c1

📥 Commits

Reviewing files that changed from the base of the PR and between 1ce0fc8550 and 007c68ca4a.

📒 Files selected for processing (1)
  • tests/KernelFileSystemTests.cpp

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


📝 Walkthrough

Walkthrough

On Windows, stream receives with guest MSG_PEEK and MSG_WAITALL skip wait emulation for nonblocking sockets and MSG_DONTWAIT. Blocking sockets still wait for data, EOF, timeout, or error. WSAPoll failures now return converted host errors. The kernel file system test configures SDL entry-point handling and verifies delayed two-part payload delivery.

Suggested reviewers: defektu

Priority: ➖ Normal

Change: Bug fix

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 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 Issue [#505] requires Windows guest PEEK | WAITALL to preserve wake bytes and allow kernel_file_system to pass. ConvertMessageFlags clears unsupported Windows MSG_WAITALL for peeks. Recvfrom…
Out of Scope Changes check ✅ Passed The changes stay within [#505]. The socket changes fix the reported Windows flag combination. The test changes provide regression coverage and required Windows SDL linkage. The nonblocking state track…
Title check ✅ Passed The title clearly and concisely describes the main change: Windows handling for guest PEEK and WAITALL flags.
Description check ✅ Passed The description directly explains the Windows linker fix, socket flag handling, MSG_WAITALL emulation, nonblocking behavior, and test coverage.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-21 15:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#issuecomment-5762967810) · edited 2026-09-21 19:24 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/751#gh-light-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg" alt="Review Change Stack" width="202" height="32"></a><a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/751#gh-dark-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg" alt="Review Change Stack" width="202" height="32"></a> **Understand this PR’s impact** Explore downstream dependencies and potential security impact with Blast Radius. [View blast radius →](<https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/751?view=blast-radius>) <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `b02c990d-f1c1-44eb-aabd-5b9e56b0c1c1` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 1ce0fc8550f55942d75e564fe425d2a1e3c275ef and 007c68ca4a43aeb2751f09fa0120fdb9eea2acb6. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `tests/KernelFileSystemTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough On Windows, stream receives with guest `MSG_PEEK` and `MSG_WAITALL` skip wait emulation for nonblocking sockets and `MSG_DONTWAIT`. Blocking sockets still wait for data, EOF, timeout, or error. `WSAPoll` failures now return converted host errors. The kernel file system test configures SDL entry-point handling and verifies delayed two-part payload delivery. **Suggested reviewers:** `defektu` <!-- <fixed_issue_severity>Medium</fixed_issue_severity> --> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"007c68ca4a43aeb2751f09fa0120fdb9eea2acb6" --> **Change:** Bug fix <!-- change_assessment_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 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 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 | Issue [`#505`] requires Windows guest `PEEK \| WAITALL` to preserve wake bytes and allow `kernel_file_system` to pass. `ConvertMessageFlags` clears unsupported Windows `MSG_WAITALL` for peeks. `Recvfrom`… | | Out of Scope Changes check | ✅ Passed | The changes stay within [`#505`]. The socket changes fix the reported Windows flag combination. The test changes provide regression coverage and required Windows SDL linkage. The nonblocking state track… | | Title check | ✅ Passed | The title clearly and concisely describes the main change: Windows handling for guest PEEK and WAITALL flags. | | Description check | ✅ Passed | The description directly explains the Windows linker fix, socket flag handling, MSG_WAITALL emulation, nonblocking behavior, and test coverage. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠rudy-07 on GitHub · 2026-09-21 15:38 UTC · original

Thanks for the feedback! I have updated the PR (commit 1361216):

  1. MSG_WAITALL Emulation on Windows: Rather than returning short reads on partial arrivals, Recvfrom now emulates MSG_WAITALL when combined with MSG_PEEK on stream sockets by awaiting host_len pending bytes via FIONREAD / select / WSAPoll. It also properly handles remote peer disconnection (POLLHUP / EOF) by returning partial accumulated data per POSIX semantics, and respects SO_RCVTIMEO.

  2. Docstrings: Added Doxygen documentation for ConvertMessageFlags and Recvfrom to satisfy docstring coverage checks.

**@⁠rudy-07** on GitHub · 2026-09-21 15:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#issuecomment-5763179973) Thanks for the feedback! I have updated the PR (commit 1361216): 1. MSG_WAITALL Emulation on Windows: Rather than returning short reads on partial arrivals, Recvfrom now emulates MSG_WAITALL when combined with MSG_PEEK on stream sockets by awaiting host_len pending bytes via FIONREAD / select / WSAPoll. It also properly handles remote peer disconnection (POLLHUP / EOF) by returning partial accumulated data per POSIX semantics, and respects SO_RCVTIMEO. 2. Docstrings: Added Doxygen documentation for ConvertMessageFlags and Recvfrom to satisfy docstring coverage checks.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-21 15:44 UTC · original · edited 2026-09-21 15:54 UTC
On src/libs/network.cpp line 2257 (outdated):

@@ -2210,6 +2245,85 @@ int64_t KYTY_SYSV_ABI Recvfrom(int s, void* buf, uint64_t len, int flags, void*
 
 	const auto host_len = static_cast<SocketIoLength>(
 	    std::min<uint64_t>(len, std::numeric_limits<SocketIoLength>::max()));
+
+#if defined(_WIN32)
+	// Emulate MSG_WAITALL when combined with MSG_PEEK on stream sockets:
+	// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP.
+	// ConvertMessageFlags clears MSG_WAITALL when MSG_PEEK is set on Windows.
+	// To preserve POSIX MSG_WAITALL semantics, wait until host_len bytes are pending
+	// (or until EOF / timeout / error) before issuing the native MSG_PEEK receive.
+	constexpr int guest_msg_peek    = 0x00000002;
+	constexpr int guest_msg_waitall = 0x00000040;
+	if ((flags & guest_msg_peek) != 0 && (flags & guest_msg_waitall) != 0 && host_len > 0) {

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '2070,2145p' src/libs/network.cpp
sed -n '2235,2335p' src/libs/network.cpp
rg -n 'SO_NBIO|FIONBIO|nonblock|SO_RCVTIMEO' src/libs/network.cpp src/libs/network.h

Repository: KytyPS5/KytyPS5

Length of output: 6598


🏁 Script executed:

set -e
printf '%s\n' '--- SocketSlot and nearby declarations ---'
sed -n '130,215p' src/libs/network.cpp
printf '%s\n' '--- SocketSlot initialization and nonblock-related code ---'
sed -n '430,475p' src/libs/network.cpp
sed -n '640,690p' src/libs/network.cpp
sed -n '1725,1790p' src/libs/network.cpp
printf '%s\n' '--- socket backend helpers and receive entry ---'
rg -n -A45 -B15 'GetSocketBackend|SocketSlot|Recvfrom|Recv\(' src/libs/network.cpp

Repository: KytyPS5/KytyPS5

Length of output: 36657


🏁 Script executed:

set -e
sed -n '130,215p' src/libs/network.cpp
sed -n '430,475p' src/libs/network.cpp
sed -n '640,690p' src/libs/network.cpp
sed -n '1725,1790p' src/libs/network.cpp
rg -n -A45 -B15 'GetSocketBackend|SocketSlot|Recvfrom|Recv\(' src/libs/network.cpp

Repository: KytyPS5/KytyPS5

Length of output: 36505


Skip MSG_WAITALL emulation for nonblocking sockets.

When ORBIS_SO_NBIO enables FIONBIO, Recvfrom still enters this Windows stream branch for MSG_PEEK|MSG_WAITALL. If fewer than host_len bytes are available and SO_RCVTIMEO is zero, the loop can block indefinitely in select or keep sleeping and retrying. Track the native nonblocking state in SocketSlot when Setsockopt changes it, and run this emulation only for blocking sockets. Native recv can then return available data or WSAEWOULDBLOCK.

✅ Addressed in commit 1ce0fc8

**@⁠coderabbitai[bot]** on GitHub · 2026-09-21 15:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#discussion_r4063784042) · edited 2026-09-21 15:54 UTC On `src/libs/network.cpp` line 2257 (outdated): ```diff @@ -2210,6 +2245,85 @@ int64_t KYTY_SYSV_ABI Recvfrom(int s, void* buf, uint64_t len, int flags, void* const auto host_len = static_cast<SocketIoLength>( std::min<uint64_t>(len, std::numeric_limits<SocketIoLength>::max())); + +#if defined(_WIN32) + // Emulate MSG_WAITALL when combined with MSG_PEEK on stream sockets: + // Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP. + // ConvertMessageFlags clears MSG_WAITALL when MSG_PEEK is set on Windows. + // To preserve POSIX MSG_WAITALL semantics, wait until host_len bytes are pending + // (or until EOF / timeout / error) before issuing the native MSG_PEEK receive. + constexpr int guest_msg_peek = 0x00000002; + constexpr int guest_msg_waitall = 0x00000040; + if ((flags & guest_msg_peek) != 0 && (flags & guest_msg_waitall) != 0 && host_len > 0) { ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '2070,2145p' src/libs/network.cpp sed -n '2235,2335p' src/libs/network.cpp rg -n 'SO_NBIO|FIONBIO|nonblock|SO_RCVTIMEO' src/libs/network.cpp src/libs/network.h ``` Repository: KytyPS5/KytyPS5 Length of output: 6598 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- SocketSlot and nearby declarations ---' sed -n '130,215p' src/libs/network.cpp printf '%s\n' '--- SocketSlot initialization and nonblock-related code ---' sed -n '430,475p' src/libs/network.cpp sed -n '640,690p' src/libs/network.cpp sed -n '1725,1790p' src/libs/network.cpp printf '%s\n' '--- socket backend helpers and receive entry ---' rg -n -A45 -B15 'GetSocketBackend|SocketSlot|Recvfrom|Recv\(' src/libs/network.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 36657 --- 🏁 Script executed: ```bash set -e sed -n '130,215p' src/libs/network.cpp sed -n '430,475p' src/libs/network.cpp sed -n '640,690p' src/libs/network.cpp sed -n '1725,1790p' src/libs/network.cpp rg -n -A45 -B15 'GetSocketBackend|SocketSlot|Recvfrom|Recv\(' src/libs/network.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 36505 --- </details> **Skip `MSG_WAITALL` emulation for nonblocking sockets.** When `ORBIS_SO_NBIO` enables `FIONBIO`, `Recvfrom` still enters this Windows stream branch for `MSG_PEEK|MSG_WAITALL`. If fewer than `host_len` bytes are available and `SO_RCVTIMEO` is zero, the loop can block indefinitely in `select` or keep sleeping and retrying. Track the native nonblocking state in `SocketSlot` when `Setsockopt` changes it, and run this emulation only for blocking sockets. Native `recv` can then return available data or `WSAEWOULDBLOCK`. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7a040b66d87d73e6260f94b2 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1ce0fc8
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-21 15:44 UTC · original · edited 2026-09-21 15:54 UTC
On src/libs/network.cpp line 2282 (outdated):

@@ -2210,6 +2245,85 @@ int64_t KYTY_SYSV_ABI Recvfrom(int s, void* buf, uint64_t len, int flags, void*
 
 	const auto host_len = static_cast<SocketIoLength>(
 	    std::min<uint64_t>(len, std::numeric_limits<SocketIoLength>::max()));
+
+#if defined(_WIN32)
+	// Emulate MSG_WAITALL when combined with MSG_PEEK on stream sockets:
+	// Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP.
+	// ConvertMessageFlags clears MSG_WAITALL when MSG_PEEK is set on Windows.
+	// To preserve POSIX MSG_WAITALL semantics, wait until host_len bytes are pending
+	// (or until EOF / timeout / error) before issuing the native MSG_PEEK receive.
+	constexpr int guest_msg_peek    = 0x00000002;
+	constexpr int guest_msg_waitall = 0x00000040;
+	if ((flags & guest_msg_peek) != 0 && (flags & guest_msg_waitall) != 0 && host_len > 0) {
+		int          socket_type = 0;
+		SocketLength optlen      = sizeof(socket_type);
+		if (::getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&socket_type),
+		                 &optlen) == 0 &&
+		    socket_type == SOCK_STREAM) {
+			DWORD timeout_ms = 0;
+			int   timeo_len  = sizeof(timeout_ms);
+			if (::getsockopt(socket, SOL_SOCKET, SO_RCVTIMEO,
+			                 reinterpret_cast<char*>(&timeout_ms), &timeo_len) != 0) {
+				timeout_ms = 0;
+			}
+			const auto start_time = std::chrono::steady_clock::now();
+			while (true) {
+				u_long available = 0;
+				if (::ioctlsocket(socket, FIONREAD, &available) != 0) {
+					return SetHostSocketError();
+				}
+				if (available >= static_cast<u_long>(host_len)) {
+					break;
+				}
+
+				WSAPOLLFD pfd {};
+				pfd.fd     = socket;
+				pfd.events = POLLRDNORM;
+				if (::WSAPoll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) {

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '2240,2335p' src/libs/network.cpp
rg -n 'SetHostSocketError|WSAPoll' src/libs/network.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4285


🏁 Script executed:

sed -n '990,1030p' src/libs/network.cpp
sed -n '2325,2365p' src/libs/network.cpp
sed -n '2160,2210p' src/libs/network.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4423


Propagate WSAPoll errors.

WSAPoll returns SOCKET_ERROR when polling fails. The > 0 condition ignores that result. The loop can then enter select, sleep, or return a timeout instead of propagating the poll error.

Proposed fix
-				if (::WSAPoll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) {
+				const int poll_result = ::WSAPoll(&pfd, 1, 0);
+				if (poll_result == SOCKET_ERROR) {
+					return SetHostSocketError();
+				}
+				if (poll_result > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) {
 					break;
 				}
📝 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.

				const int poll_result = ::WSAPoll(&pfd, 1, 0);
				if (poll_result == SOCKET_ERROR) {
					return SetHostSocketError();
				}
				if (poll_result > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) {

✅ Addressed in commit 1ce0fc8

**@⁠coderabbitai[bot]** on GitHub · 2026-09-21 15:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#discussion_r4063784049) · edited 2026-09-21 15:54 UTC On `src/libs/network.cpp` line 2282 (outdated): ```diff @@ -2210,6 +2245,85 @@ int64_t KYTY_SYSV_ABI Recvfrom(int s, void* buf, uint64_t len, int flags, void* const auto host_len = static_cast<SocketIoLength>( std::min<uint64_t>(len, std::numeric_limits<SocketIoLength>::max())); + +#if defined(_WIN32) + // Emulate MSG_WAITALL when combined with MSG_PEEK on stream sockets: + // Winsock rejects MSG_PEEK | MSG_WAITALL with WSAEOPNOTSUPP. + // ConvertMessageFlags clears MSG_WAITALL when MSG_PEEK is set on Windows. + // To preserve POSIX MSG_WAITALL semantics, wait until host_len bytes are pending + // (or until EOF / timeout / error) before issuing the native MSG_PEEK receive. + constexpr int guest_msg_peek = 0x00000002; + constexpr int guest_msg_waitall = 0x00000040; + if ((flags & guest_msg_peek) != 0 && (flags & guest_msg_waitall) != 0 && host_len > 0) { + int socket_type = 0; + SocketLength optlen = sizeof(socket_type); + if (::getsockopt(socket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&socket_type), + &optlen) == 0 && + socket_type == SOCK_STREAM) { + DWORD timeout_ms = 0; + int timeo_len = sizeof(timeout_ms); + if (::getsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast<char*>(&timeout_ms), &timeo_len) != 0) { + timeout_ms = 0; + } + const auto start_time = std::chrono::steady_clock::now(); + while (true) { + u_long available = 0; + if (::ioctlsocket(socket, FIONREAD, &available) != 0) { + return SetHostSocketError(); + } + if (available >= static_cast<u_long>(host_len)) { + break; + } + + WSAPOLLFD pfd {}; + pfd.fd = socket; + pfd.events = POLLRDNORM; + if (::WSAPoll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) { ``` _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '2240,2335p' src/libs/network.cpp rg -n 'SetHostSocketError|WSAPoll' src/libs/network.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4285 --- 🏁 Script executed: ```bash sed -n '990,1030p' src/libs/network.cpp sed -n '2325,2365p' src/libs/network.cpp sed -n '2160,2210p' src/libs/network.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4423 --- </details> **Propagate `WSAPoll` errors.** `WSAPoll` returns `SOCKET_ERROR` when polling fails. The `> 0` condition ignores that result. The loop can then enter `select`, sleep, or return a timeout instead of propagating the poll error. <details> <summary>Proposed fix</summary> ```diff - if (::WSAPoll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) { + const int poll_result = ::WSAPoll(&pfd, 1, 0); + if (poll_result == SOCKET_ERROR) { + return SetHostSocketError(); + } + if (poll_result > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) { break; } ``` </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 const int poll_result = ::WSAPoll(&pfd, 1, 0); if (poll_result == SOCKET_ERROR) { return SetHostSocketError(); } if (poll_result > 0 && (pfd.revents & (POLLHUP | POLLERR)) != 0) { ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ac55f46e300183315fff9acc --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1ce0fc8
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-21 15:44 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: bc81aa0a-53f8-4401-b9f6-fc8ce09f0805

📥 Commits

Reviewing files that changed from the base of the PR and between 97bb9baf90 and 136121615b.

📒 Files selected for processing (1)
  • src/libs/network.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-21 15:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#pullrequestreview-5268674586) · **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**: `bc81aa0a-53f8-4401-b9f6-fc8ce09f0805` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 97bb9baf90346328bf11d66d566f92462db507e7 and 136121615b3d8e8830a5233e47977638812d6f54. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/libs/network.cpp` </details> **Included review availability:** 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

@⁠francoisatt on GitHub · 2026-09-21 19:10 UTC · original

Tested on Windows (native build, clang-cl, full clean build), as the reporter of #505. Since the CI workflow is still awaiting approval, this may be the only Windows run so far.

Same base for all three builds (ba55ba5, the merge-base of this PR):

Build kernel_file_system
main does not link (undefined symbol: main, SDL)
main + only the SDL_MAIN_HANDLED change from this PR fails: 0xc0000409, "guest PEEK and WAITALL preserve the wake bytes" (the #505 failure)
this PR (1ce0fc8) passes

So both parts are needed: the SDL define makes the test link, and the network.cpp change fixes the actual PEEK+WAITALL failure.

Full suite on this PR: 39/40 as run, the 40th (save_data_memory) was only missing from my local build script; built separately, it passes.

Not verified: the regression test sends the whole payload before receiving, so it does not exercise the WAITALL emulation added in 1361216 (partial arrival, peer close, SO_RCVTIMEO), nor the nonblocking skip from 1ce0fc8. That is the case Copilot raised. Also, the PR description still describes the first approach (clearing MSG_WAITALL), which may be worth updating for reviewers.

**@⁠francoisatt** on GitHub · 2026-09-21 19:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#issuecomment-5766029370) Tested on Windows (native build, clang-cl, full clean build), as the reporter of #505. Since the CI workflow is still awaiting approval, this may be the only Windows run so far. Same base for all three builds (ba55ba5, the merge-base of this PR): | Build | kernel_file_system | |---|---| | main | does not link (`undefined symbol: main`, SDL) | | main + only the SDL_MAIN_HANDLED change from this PR | fails: `0xc0000409`, "guest PEEK and WAITALL preserve the wake bytes" (the #505 failure) | | this PR (1ce0fc8) | passes | So both parts are needed: the SDL define makes the test link, and the network.cpp change fixes the actual PEEK+WAITALL failure. Full suite on this PR: 39/40 as run, the 40th (save_data_memory) was only missing from my local build script; built separately, it passes. Not verified: the regression test sends the whole payload before receiving, so it does not exercise the WAITALL emulation added in 1361216 (partial arrival, peer close, SO_RCVTIMEO), nor the nonblocking skip from 1ce0fc8. That is the case Copilot raised. Also, the PR description still describes the first approach (clearing MSG_WAITALL), which may be worth updating for reviewers.
Author
Owner

@⁠rudy-07 on GitHub · 2026-09-21 19:22 UTC · original

Thank you so much for taking the time to test all three configurations natively with clang-cl and confirming the fix! That validation is super helpful.

Regarding your observations:

  1. Regression Test Coverage: I've pushed commit 007c68c, adding explicit test assertions in KernelFileSystemTests.cpp for both:

    • Non-blocking sockets: Verifies that empty receive with 0x42 returns EWOULDBLOCK immediately when ORBIS_SO_NBIO is set.
    • Chunked partial arrival: Verifies that a stream socket receiving payload in chunks ("wa" followed by "ke\0") waits for the full length before returning under 0x42.
  2. PR Description: Updated the PR description to accurately detail the MSG_WAITALL emulation, non-blocking bypass, error handling, and test coverage for reviewers.

**@⁠rudy-07** on GitHub · 2026-09-21 19:22 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#issuecomment-5766178101) Thank you so much for taking the time to test all three configurations natively with clang-cl and confirming the fix! That validation is super helpful. Regarding your observations: 1. Regression Test Coverage: I've pushed commit 007c68c, adding explicit test assertions in KernelFileSystemTests.cpp for both: - Non-blocking sockets: Verifies that empty receive with 0x42 returns EWOULDBLOCK immediately when ORBIS_SO_NBIO is set. - Chunked partial arrival: Verifies that a stream socket receiving payload in chunks ("wa" followed by "ke\0") waits for the full length before returning under 0x42. 2. PR Description: Updated the PR description to accurately detail the MSG_WAITALL emulation, non-blocking bypass, error handling, and test coverage for reviewers.
Author
Owner

@⁠francoisatt on GitHub · 2026-09-24 18:40 UTC · original

Heads-up: #797 (theantipopau) covers the same Winsock MSG_PEEK | MSG_WAITALL limitation and the same SDL_MAIN_HANDLED fix, with a broader implementation (accepted sockets, datagrams, MSG_DONTWAIT, EOF) that also handles the partial-arrival case Copilot raised above. Both are open and neither references the other. My test results above still stand for this PR; posting this so it gets resolved rather than both stalling.

**@⁠francoisatt** on GitHub · 2026-09-24 18:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#issuecomment-5820020927) Heads-up: #797 (theantipopau) covers the same Winsock MSG_PEEK | MSG_WAITALL limitation and the same SDL_MAIN_HANDLED fix, with a broader implementation (accepted sockets, datagrams, MSG_DONTWAIT, EOF) that also handles the partial-arrival case Copilot raised above. Both are open and neither references the other. My test results above still stand for this PR; posting this so it gets resolved rather than both stalling.
Author
Owner

@⁠Nmzik on GitHub · 2026-10-03 17:16 UTC · original

Credited

**@⁠Nmzik** on GitHub · 2026-10-03 17:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/751#issuecomment-5971560634) Credited

Pull request closed

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