Fix Windows MSG_PEEK and MSG_WAITALL receive handling #797

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

@⁠theantipopau on GitHub · 2026-09-24 05:59 UTC · original
theantipopau:windows-peek-waitall → main · +352 −18 · 2 files · 8 commits · closed without merging

Problem

On Windows, a guest recv/recvfrom that combines MSG_PEEK | MSG_WAITALL fails
outright. Winsock rejects the pair with WSAEOPNOTSUPP (10045) on stream sockets,
datagram sockets, non-blocking sockets, at end of file and for zero-length requests,
so any title that uses this (very common) way of waiting for a complete message sees an
error instead of data. The existing regression test for it
(tests/KernelFileSystemTests.cpp::CheckSocketWakeup) could not even be built after
the SDL3 migration, because SDL3/SDL_main.h renames main to SDL_main and the
target links as a console app.

Changes

  • tests/KernelFileSystemTests.cpp — define SDL_MAIN_HANDLED before the SDL includes
    so the test provides its own entry point and links on Windows again.

  • src/libs/network.cpp — on Windows only, intercept the MSG_PEEK | MSG_WAITALL
    combination in Recvfrom and reproduce the guest (FreeBSD) behaviour:

    • peek until the requested length is buffered, returning the bytes without consuming
      them, so a following receive still sees the whole message;
    • a peer that closes or resets first ends the wait with the short read (and 0 at
      end of file);
    • MSG_DONTWAIT and non-blocking sockets return what is buffered, or
      EWOULDBLOCK when nothing is, without waiting;
    • datagram sockets ignore MSG_WAITALL, as on FreeBSD;
    • a zero-length receive returns 0 immediately (Winsock otherwise blocks).

    POSIX keeps the existing recv/recvfrom behaviour; the only change there is that
    the call is factored into a small RecvHost helper.

Why the wait is paced instead of polled

MSG_PEEK does not consume, so a partially delivered message keeps the socket
readable: WSAPoll(POLLRDNORM) returns in 0 ms in that state and a select/poll loop
would spin. The implementation therefore sleeps 1 ms between peeks and uses the poll
only to observe POLLHUP/POLLERR/POLLNVAL, i.e. the "stop waiting" signal. A
blocking guest call still blocks exactly as long as the data takes, and the fast path
(no data missing) performs a single recv(MSG_PEEK) with no sleeping at all.

The guest non-blocking mode is tracked in SocketTransport because
ioctlsocket(FIONBIO) can only set the mode, never report it.

Testing

Built with the documented Windows toolchain (clang-cl + Ninja, Release) and verified
locally on Windows 11 / Ryzen 7 9800X3D / Radeon RX 9070 XT (driver 26.8.1):

  • kernel_file_system_tests passes, 15/15 consecutive runs, including new coverage for
    fragmented delivery, bytes surviving a peek, zero-length receive, MSG_DONTWAIT,
    a non-blocking socket and end-of-file short reads;
  • full build of all targets plus the launcher: clean;
  • ctest: 22/40 pass. The 17 failures are the pre-existing local Vulkan limitation
    (production rasterization features are not supported — this driver does not expose
    VK_EXT_attachment_feedback_loop_dynamic_state), and save_data_memory is reported
    "Not Run" because its target is not part of the kyty_tests aggregate; both are
    unrelated to this change.

Risk

Low and Windows-only. Previously the intercepted combination always failed, so blocking
callers now block as the guest expects, with at most 1 ms of extra latency for a
trailing fragment. Non-blocking and MSG_DONTWAIT callers return immediately. The
2 MiB-scale P2P logical sockets are rejected before this path and are unaffected.

**@⁠theantipopau** on GitHub · 2026-09-24 05:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797) `theantipopau:windows-peek-waitall` → `main` · +352 −18 · 2 files · 8 commits · closed without merging ## Problem On Windows, a guest `recv`/`recvfrom` that combines `MSG_PEEK | MSG_WAITALL` fails outright. Winsock rejects the pair with `WSAEOPNOTSUPP` (10045) on stream sockets, datagram sockets, non-blocking sockets, at end of file and for zero-length requests, so any title that uses this (very common) way of waiting for a complete message sees an error instead of data. The existing regression test for it (`tests/KernelFileSystemTests.cpp::CheckSocketWakeup`) could not even be built after the SDL3 migration, because `SDL3/SDL_main.h` renames `main` to `SDL_main` and the target links as a console app. ## Changes * `tests/KernelFileSystemTests.cpp` — define `SDL_MAIN_HANDLED` before the SDL includes so the test provides its own entry point and links on Windows again. * `src/libs/network.cpp` — on Windows only, intercept the `MSG_PEEK | MSG_WAITALL` combination in `Recvfrom` and reproduce the guest (FreeBSD) behaviour: * peek until the requested length is buffered, returning the bytes without consuming them, so a following receive still sees the whole message; * a peer that closes or resets first ends the wait with the short read (and `0` at end of file); * `MSG_DONTWAIT` and non-blocking sockets return what is buffered, or `EWOULDBLOCK` when nothing is, without waiting; * datagram sockets ignore `MSG_WAITALL`, as on FreeBSD; * a zero-length receive returns `0` immediately (Winsock otherwise blocks). POSIX keeps the existing `recv`/`recvfrom` behaviour; the only change there is that the call is factored into a small `RecvHost` helper. ### Why the wait is paced instead of polled `MSG_PEEK` does not consume, so a partially delivered message keeps the socket readable: `WSAPoll(POLLRDNORM)` returns in 0 ms in that state and a select/poll loop would spin. The implementation therefore sleeps 1 ms between peeks and uses the poll only to observe `POLLHUP`/`POLLERR`/`POLLNVAL`, i.e. the "stop waiting" signal. A blocking guest call still blocks exactly as long as the data takes, and the fast path (no data missing) performs a single `recv(MSG_PEEK)` with no sleeping at all. The guest non-blocking mode is tracked in `SocketTransport` because `ioctlsocket(FIONBIO)` can only set the mode, never report it. ## Testing Built with the documented Windows toolchain (clang-cl + Ninja, Release) and verified locally on Windows 11 / Ryzen 7 9800X3D / Radeon RX 9070 XT (driver 26.8.1): * `kernel_file_system_tests` passes, 15/15 consecutive runs, including new coverage for fragmented delivery, bytes surviving a peek, zero-length receive, `MSG_DONTWAIT`, a non-blocking socket and end-of-file short reads; * full build of all targets plus the launcher: clean; * `ctest`: 22/40 pass. The 17 failures are the pre-existing local Vulkan limitation (`production rasterization features are not supported` — this driver does not expose `VK_EXT_attachment_feedback_loop_dynamic_state`), and `save_data_memory` is reported "Not Run" because its target is not part of the `kyty_tests` aggregate; both are unrelated to this change. ## Risk Low and Windows-only. Previously the intercepted combination always failed, so blocking callers now block as the guest expects, with at most 1 ms of extra latency for a trailing fragment. Non-blocking and `MSG_DONTWAIT` callers return immediately. The 2 MiB-scale P2P logical sockets are rejected before this path and are unaffected.
Keep Windows accepted sockets aligned with FreeBSD nonblocking semantics and preserve source addresses for zero-length datagram peeks.

Generated with Codebuff 🤖
Co-Authored-By: Codebuff <[email protected]>
Allow the asynchronous receive worker enough time to start before checking the inherited nonblocking behavior, while retaining the suffix fallback for a blocking implementation.

Generated with Codebuff 🤖
Co-Authored-By: Codebuff <[email protected]>
Keep the Winsock scratch byte out of zero-length guest receives and reject accept before it reaches a shared P2P transport. Add regressions for both behaviors.

🤖 Generated with Codebuff

Co-Authored-By: Codebuff <[email protected]>
Ensure loopback bytes are buffered before exercising nonblocking PEEK
so scheduler timing cannot flake the Windows regression.

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

@⁠coderabbitai[bot] on GitHub · 2026-09-24 06:13 UTC · original · edited 2026-10-02 23:53 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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
📝 Walkthrough

Walkthrough

Windows socket transports now track guest nonblocking mode, including on accepted sockets. Receive dispatch uses shared host receive logic, with a Windows-specific path for MSG_PEEK | MSG_WAITALL. Socket tests cover fragmented data, zero-length receives, nonblocking behavior, peer closure, accepted sockets, and datagram peeks. P2P socket acceptance now returns EOPNOTSUPP.

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: 🔵 Low · up to c834b

A peer reset during a fragmented receive can return an error instead of the buffered bytes. This is a narrow remaining issue; the accepted-socket and datagram fixes appear ready.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: fixing Windows handling of combined MSG_PEEK and MSG_WAITALL receives.
Description check ✅ Passed The description is directly related to the changeset and explains the Windows receive-path fix, test updates, behavior, and validation results.
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.

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:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#issuecomment-5808767255) · edited 2026-10-02 23:53 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/797"><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> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- 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 --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Windows socket transports now track guest nonblocking mode, including on accepted sockets. Receive dispatch uses shared host receive logic, with a Windows-specific path for `MSG_PEEK | MSG_WAITALL`. Socket tests cover fragmented data, zero-length receives, nonblocking behavior, peer closure, accepted sockets, and datagram peeks. P2P socket acceptance now returns `EOPNOTSUPP`. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"c834baf88dbf9ef6033859ec0841fa090218048e" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `c834b` <!-- final_review_risk_coverage:{"sourceCommitId":"c834baf88dbf9ef6033859ec0841fa090218048e","coveredCommitId":"c834baf88dbf9ef6033859ec0841fa090218048e","kind":"reviewed"} --> A peer reset during a fragmented receive can return an error instead of the buffered bytes. This is a narrow remaining issue; the accepted-socket and datagram fixes appear ready. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 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 | | :------------------------: | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly and concisely describes the main change: fixing Windows handling of combined MSG_PEEK and MSG_WAITALL receives. | | Description check | ✅ Passed | The description is directly related to the changeset and explains the Windows receive-path fix, test updates, behavior, and validation results. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=797)! 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 -->
@ -866,0 +867,4 @@
#if defined(_WIN32)
// Winsock cannot report the current mode, so the guest blocking mode is tracked here.
std::atomic_bool nonblocking {false};
#endif
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 06:13 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n 'Accept\(|nonblocking|FIONBIO|RecvPeekWaitAll|IsSocketNonBlocking' src/libs/network.cpp
sed -n '1970,2035p' src/libs/network.cpp
sed -n '2160,2205p' src/libs/network.cpp

Repository: KytyPS5/KytyPS5

Length of output: 3993


🏁 Script executed:

sed -n '1060,1185p' src/libs/network.cpp
sed -n '2260,2320p' src/libs/network.cpp
rg -n -C 4 'Accept|accept|SO_NBIO|nonblocking|MSG_WAITALL|MSG_DONTWAIT|RecvPeekWaitAll' --glob '!src/libs/network.cpp' .

Repository: KytyPS5/KytyPS5

Length of output: 42172


🌐 Web query:

Microsoft Winsock accept FIONBIO nonblocking mode accepted socket inheritance official documentation

💡 Result:

<source_evidence>

https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept layout: Conceptual ... title: accept ... (winsock2.h) - Win3 ... canonicalUrl: https://learn.microsoft ... com/en-us/windows/win32/ ... /winsock2/nf-wins ... breadcrumb_path ... UID: NF:wins ... The accept function permits an incoming ... attempt on a socket. ... The **accept** function permits an incoming connection attempt on a socket. ## Syntax ```cpp SOCKET WSAAPI accept( [in] SOCKET s, [out] sockaddr *addr, [in, out] int *addrlen ); ``` ## Parameters `[in] s` A descriptor that identifies a socket that has been placed in a listening state with the listen function. The connection is actually made with the socket that is returned by **accept**. `[out] addr` An optional pointer to a buffer that receives the address of the connecting entity, as known to the communications layer. The exact format of the *addr* parameter is determined by the address family that was established when the socket from the sockaddr structure was created. `[in, out] addrlen` An optional pointer to an integer that contains the length of structure pointed to by the *addr* parameter. ## Return value If no error occurs, **accept** returns a value of type **SOCKET** that is a descriptor for the new socket. This returned value is a handle for the socket on which the actual connection is made. Otherwise, a value of **INVALID\_SOCKET** is returned, and a specific error code can be retrieved by calling WSAGetLastError. The integer referred to by *addrlen* initially contains the amount of space pointed to by *addr*. On return it will contain the actual length in bytes of the address returned. | Error code | Meaning | | --- | --- | | - **WSANOTINITIALISED** | A successful WSAStartup call must occur before using this function. | | - **WSAECONNRESET** | An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call. | | - **WSAEFAULT** | The *addrlen* parameter is too small or *addr* is not a valid part of the user address space. | ... | - ** ... SAEINTR ... | A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall. ... prior to accept ... | - **WSAEMFILE** | The queue is nonempty upon entry to accept and there are no descriptors available. | | - **WSAENETDOWN** | The network subsystem has failed. | | - **WSAENOBUFS** | No buffer space is available. | | - **WSAENOTSOCK** | The descriptor is not a socket. | | - **WSAEOPNOTSUPP** | The referenced socket is not a type that supports connection-oriented service. | | - **WSAEWOULDBLOCK** | The socket is marked as nonblocking and no connections are present to be accepted. | ## Remarks The **accept** function extracts the first connection on the queue of pending connections on socket *s*. It then creates and returns a handle to the new socket. The newly created socket is the socket that will handle the actual connection; it has the same properties as socket *s*, including the asynchronous events registered with the WSAAsyncSelect or WSAEventSelect functions. The **accept** function can block the caller until a connection is present if no pending connections are present on the queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on the queue, **accept** returns an error as described in the following. After the successful completion of **accept** returns a new socket handle, the accepted socket cannot be used to accept more connections. The original socket remains open and listens for new connection requests. The parameter *addr* is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the *addr* parameter is determined by the address family in which the communication is occurring. The *addrlen* is a value-result parameter; it should initially contain the amount of space pointed to by *addr*; on return it will contain the actual length (in bytes) of the address returned. The **accept** function... https://learn.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls ### FIONBIO ... Enable or disable non-blocking mode on socket s. The lpvInBuffer parameter points at an unsigned long (QoS), which is nonzero if non-blocking mode is to be enabled and zero if it is to be disabled. When a socket is created, it operates in blocking mode (that is, non-blocking mode is disabled). This is consistent with BSD sockets. ... The WSAAsyncSelect or WSAEventSelect routine automatically sets a socket to non-blocking mode. If WSAAsyncSelect or WSAEventSelect has been issued on a socket, then any attempt to use WSAIoctl to set the socket back to blocking mode will fail with WSAEINVAL. To set the socket back to blocking mode, an application must first disable WSAAsyncSelect by calling WSAAsyncSelect with the lEvent parameter equal to zero, or disable WSAEventSelect by calling WSAEventSelect with the lNetworkEvents parameter equal to zero. https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaaccept # WSAAccept function (winsock2.h) - Win32 apps | Microsoft Learn ... The WSAAccept function conditionally accepts a connection based on the return value of a condition function, provides quality of service flow specifications, and allows the transfer of connection data. ... | - WSAEWOULDBLOCK | A non-blocking socket operation could not be completed immediately. This error is returned if the socket is marked as nonblocking and no connections are present to be accepted. | ... The WSAAccept function extracts the first connection on the queue of pending connections on socket s, and checks it against the condition function, provided the condition function is specified (that is, not NULL). If the condition function returns CF_ACCEPT, WSAAccept creates a new socket. The newly created socket has the same properties as socket s including asynchronous events registered with WSAAsyncSelect or with WSAEventSelect. If the condition function returns CF_REJECT, WSAAccept rejects the connection request. The condition function runs in the same thread as this function does, and should return as soon as possible. If the decision cannot be made immediately, the condition function should return CF_DEFER to indicate that no decision has been made, and no action about this connection request should be taken by the service provider. When the application is ready to take action on the connection request, it will invoke WSAAccept again and return either CF_ACCEPT or CF_REJECT as a return value from the condition function. ... A socket in default mode (blocking) will block until a connection is present when an application calls WSAAccept and no connections are pending on the queue. ... A socket in nonblocking mode (blocking) fails with the error WSAEWOULDBLOCK when an application calls WSAAccept and no connections are pending on the queue. After WSAAccept succeeds and returns a new socket handle, the accepted socket cannot be used to accept any more connections. The original socket remains open and listens for new connection requests. ... The g parameter is assigned within the condition function to indicate any of the following actions: ... - If g is an existing socket group identifier, add s to this group, provided all the requirements set by this group are met. - If g = SG_UNCONSTRAINED_GROUP, create an unconstrained socket group and have s as the first member. - If g = SG_CONSTRAINED_GROUP, create a constrained socket group and have s as the first member. - If g = zero, no group operation is performed. ... For unconstrained ... , any set of sockets can be grouped together ... supported by a ... service provider. ... connection-oriented sockets, ... connections on all grouped sockets be to the same address on ... same host. For newly ... groups, the new group identifier can be retrieved by using getsock ... parameter set to SOL_SOCKET and the optname parameter set ... _ID. A ... remain valid until the last socket ... to this socket group is closed. ... IDs are unique across all processes for a given ... provider. A ... remain valid until the last socket belonging to this socket group is closed. Socket group identifiers are unique across all processes for a given service provider. For more information on socket groups, see ... Remarks for the WSASocket functions. ... Note To protect use of the WSAAccept function from SYN attacks, applications must perform full TCP handshakes (SYN-SYNACK-ACK) before reporting the connection request. Protecting against SYN attacks in this manner results in the SO_CONDITIONAL_ACCEPT socket option becoming inoperative; the conditional function is still called, and the WSAAccept function operates properly, but server applications that rely on clients being unable to perform the handshake will not operate properly. Note When issuing a blocking Winsock call such as WSAAccept, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interru... https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex The **AcceptEx** function accepts a new connection, returns the local and remote address, and receives the first block of data sent by the client application. **Note** This function is a Microsoft-specific extension to the Windows Sockets specification. ## Syntax ```cpp BOOL AcceptEx( ... [in] SOCKET sListenSocket, [in] SOCKET sAcceptSocket ... [in] PVOID lpOutputBuffer, [in] DWORD dwReceiveDataLength, ... [in] DWORD dwLocalAddressLength, [in] DWORD dwRemoteAddressLength, ... [out] LPDWORD lpdwBytesReceived, [in] LPOVERLAPPED lpOverlapped ); ... ## Parameters `[in] sListenSocket` ... A descriptor identifying a socket that has already been called with ... connect on this socket ... `[in] sAcceptSocket` ... A descriptor identifying a socket on which to accept ... . This socket must not be bound or connected. ... `[in] lpOutput ... ## Return value If no error occurs, the **AcceptEx** function completed successfully and a value of **TRUE** is returned. If the function fails, **AcceptEx** returns **FALSE**. The WSAGetLastError function can then be called to return extended error information. If **WSAGetLastError** returns **ERROR\_IO ... PENDING**, then the operation was successfully initiated and is still in progress. If the error is WSAECONNRESET, an incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call. ## Remarks The **AcceptEx** function combines several socket functions into a single API/kernel transition. The **AcceptEx** function, when successful, performs three tasks: - A new connection is accepted. - Both the local and remote addresses for the connection are returned. - The first block of data sent by the remote is received. **Note** The function pointer for the **AcceptEx** function must be obtained at run time by making a call to the WSAIoctl function with the **SIO\_GET\_EXTENSION\_FUNCTION\_POINTER** opcode specified. The input buffer passed to the **WSAIoctl** function must contain **WSAID\_ACCEPTEX**, a globally unique identifier (GUID) whose value identifies the **AcceptEx** extension function. On success, the output returned by the **WSAIoctl** function contains a pointer to the **AcceptEx** function. The **WSAID\_ACCEPTEX** GUID is defined in the *Mswsock.h* header file. A program can make a connection to a socket more quickly using **AcceptEx** instead of the accept function. A single output buffer receives the data, the local socket address (the server), and the remote socket address (the client). Using a single buffer improves performance. When using **AcceptEx**, the GetAcceptExSockaddrs function must be called to parse the buffer into its three distinct parts (data, local socket address, and remote socket address). On Windows XP and later, once the **AcceptEx** function completes and the **SO\_UPDATE\_ACCEPT\_CONTEXT** option is set on the accepted socket, the local address associated with the accepted socket can also be retrieved using the getsockname function. Likewise, the remote address associated with the accepted socket can be retrieved using the getpeername function. The buffer size for the local and remote address must be 16 bytes more than the size of the sockaddr structure for the transport protocol in use because the addresses are written in an internal format. For example, the size of a **sockaddr\_in** (the address structure for TCP/IP) is 16 bytes. Therefore, a buffer size of at least 32 bytes must be specified for the local and remote addresses. The **AcceptEx** function uses overlapped I/O, unlike the accept function. If your application uses **AcceptEx**, it can service a large number of clients with a relatively small number of threads. As with all overlapped Windows functions, either Windows events or completion ports can be used as a completion notification mechanism. Another key difference between the **AcceptEx** function and the accept function is that **AcceptEx** requires the caller to already have two sockets: - One that... https://learn.microsoft.com/en-us/windows/win32/winsock/winsock-socket-state-notifications tcpAcceptSocket = accept(serverContext->listenerSocket, NULL, NULL); if (tcpAcceptSocket == INVALID_SOCKET) { errorCode = GetLastError(); goto Exit; } if (ioctlsocket(tcpAcceptSocket, FIONBIO, &nonBlocking) != 0) { errorCode = GetLastError(); goto Exit; } ... // Register the accepted connection. registration.completionKey = (PVOID)tcpAcceptSocket; registration.eventFilter = SOCK_NOTIFY_REGISTER_EVENT_IN | SOCK_NOTIFY_REGISTER_EVENT_HANGUP; registration.operation = SOCK_NOTIFY_OP_ENABLE; registration.triggerFlags = SOCK_NOTIFY_TRIGGER_LEVEL; registration.socket = tcpAcceptSocket; errorCode = ProcessSocketNotifications(serverContext->ioCompletionPort, 1, &registration, 0, 0, NULL, NULL); // Make sure all registrations were processed. if (errorCode != ERROR_SUCCESS) { goto Exit; } ... // Make sure each registration was successful. ... if (registration.registration ... SUCCESS) { errorCode = registration.registrationResult; goto ... // Use non-blocking sockets with edge-triggered notifications, since the data must be // drained before a rising edge can be observed again. errorCode = ioctlsocket(serverSocket, FIONBIO, &nonBlocking); if (errorCode != ERROR_SUCCESS) { goto Exit; } ... SOCKET_CONTEXT ... socketContextOut) { DWORD errorCode; ... SOCKET_CONTEXT ... NULL; ... socketContext = ... SOCKET_CONTEXT*)malloc(sizeof(*socketContext)); if (socketContext == NULL) { errorCode = ERROR_NOT_ ... OUGH_MEMORY; goto Exit; ... } ... ZeroMemory(socketContext, sizeof(*socketContext)); socketContext->socketType = SOCKET_TYPE ... ACCEPT; socketContext->socket = accept(listenSocket, NULL, NULL); ... if (socketContext->socket == INVALID_SOCKET) { errorCode ... goto Exit ... *socketContextOut = socketContext; ... socketContext = NULL ... ThreadRoutine(_In ... CONTEXT* server ... Context; HANDLE io ... Port; ... registrations: one to re-enable the listening ... // notification, and one to register the newly- ... . SOCK_NOTIFY_REGISTRATION registrationBuffer[SERVER_DEQUEUE_COUNT * 2]; UINT32 registrationCount; SOCK_NOTIFY_REGISTRATION* registration; OVERLAPPED_ENTRY notifications[SERVER_DEQUEUE_COUNT]; UINT32 notificationCount; UINT32 events; SOCKET_CONTEXT* ... Context; SOCKET_CONTEXT* acceptedContext; BOOLEAN shouldExit; CHAR dataBuffer[512]; ... // Process the socket notification, taking socket-specific actions. switch (socketContext->socketType) { case SOCKET_TYPE_LISTENER: // Accepting connections in response to notifications implicitly throttles // the rate at which incoming connections are accepted, and limits scale-out for // new connection acceptance. Consider using AcceptEx if greater scaling of //connection acceptance is desired. // Perform an accept regardless of the notification. The only possible notifications // are for available connections or error conditions. Any possible error conditions // will be processed as part of the accept. errorCode = AcceptConnection(socketContext->socket, &acceptedContext); if (errorCode == ERROR_SUCCESS) { // Register the accepted connection. registration = &registrationBuffer[registrationCount]; registration->socket = acceptedContext->socket; registration->completionKey = acceptedContext; registration->eventFilter = SOCK_NOTIFY_EVENT_IN | SOCK_NOTIFY_EVENT_HANGUP; registration->operation = SOCK_NOTIFY_OP_ENABLE; registration->triggerFlags = SOCK_NOTIFY_TRIGGER_ONESHOT | SOCK_NOTIFY_TRIGGER_LEVEL; registrationCount += 1; } // Re-arm the existing listening socket registration. registration = &registrationBuffer[registrationCount]; registration->socket = socketContext->socket; registration->completionKey = socketContext; registration->eventFilter = SOCK_NOTIFY_EVENT_IN; registration->operation = SOCK_NOTIFY_OP_ENABLE; registration->triggerFlags = SOCK_NOTIFY_TRIGGER_ONESHOT | SOCK_NOTIFY_TRIGGER_LEVEL; registrationCount += 1; break; ... case SOCKET_TYPE_ACCEPT: // The registration was removed. Clean up the contex…[truncated]

Citations:


🏁 Script executed:

sed -n '390,525p' tests/KernelFileSystemTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 7744


Copy the listener mode to the accepted transport.

Winsock preserves the listener's FIONBIO mode on the socket returned by accept, but SocketTransport(accepted) initializes nonblocking to false. RecvPeekWaitAll then treats the accepted socket as blocking and can wait indefinitely for the remaining bytes of a partial MSG_WAITALL receive.

🐛 Suggested fix in Accept
 	auto transport = std::make_shared<SocketTransport>(accepted);
+#if defined(_WIN32)
+	transport->nonblocking = IsSocketNonBlocking(s);
+#endif
 	const int fd = AllocSocketFd(transport);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 06:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4090498439) _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash rg -n 'Accept\(|nonblocking|FIONBIO|RecvPeekWaitAll|IsSocketNonBlocking' src/libs/network.cpp sed -n '1970,2035p' src/libs/network.cpp sed -n '2160,2205p' src/libs/network.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 3993 --- 🏁 Script executed: ```bash sed -n '1060,1185p' src/libs/network.cpp sed -n '2260,2320p' src/libs/network.cpp rg -n -C 4 'Accept|accept|SO_NBIO|nonblocking|MSG_WAITALL|MSG_DONTWAIT|RecvPeekWaitAll' --glob '!src/libs/network.cpp' . ``` Repository: KytyPS5/KytyPS5 Length of output: 42172 --- 🌐 Web query: `Microsoft Winsock accept FIONBIO nonblocking mode accepted socket inheritance official documentation` 💡 Result: <source_evidence> <source> <title>Result 1</title> <location>https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept</location> <excerpt>layout: Conceptual ... title: accept ... (winsock2.h) - Win3 ... canonicalUrl: https://learn.microsoft ... com/en-us/windows/win32/ ... /winsock2/nf-wins ... breadcrumb_path ... UID: NF:wins ... The accept function permits an incoming ... attempt on a socket. ... The **accept** function permits an incoming connection attempt on a socket. ## Syntax ```cpp SOCKET WSAAPI accept( [in] SOCKET s, [out] sockaddr *addr, [in, out] int *addrlen ); ``` ## Parameters `[in] s` A descriptor that identifies a socket that has been placed in a listening state with the listen function. The connection is actually made with the socket that is returned by **accept**. `[out] addr` An optional pointer to a buffer that receives the address of the connecting entity, as known to the communications layer. The exact format of the *addr* parameter is determined by the address family that was established when the socket from the sockaddr structure was created. `[in, out] addrlen` An optional pointer to an integer that contains the length of structure pointed to by the *addr* parameter. ## Return value If no error occurs, **accept** returns a value of type **SOCKET** that is a descriptor for the new socket. This returned value is a handle for the socket on which the actual connection is made. Otherwise, a value of **INVALID\_SOCKET** is returned, and a specific error code can be retrieved by calling WSAGetLastError. The integer referred to by *addrlen* initially contains the amount of space pointed to by *addr*. On return it will contain the actual length in bytes of the address returned. | Error code | Meaning | | --- | --- | | - **WSANOTINITIALISED** | A successful WSAStartup call must occur before using this function. | | - **WSAECONNRESET** | An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call. | | - **WSAEFAULT** | The *addrlen* parameter is too small or *addr* is not a valid part of the user address space. | ... | - ** ... SAEINTR ... | A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall. ... prior to accept ... | - **WSAEMFILE** | The queue is nonempty upon entry to accept and there are no descriptors available. | | - **WSAENETDOWN** | The network subsystem has failed. | | - **WSAENOBUFS** | No buffer space is available. | | - **WSAENOTSOCK** | The descriptor is not a socket. | | - **WSAEOPNOTSUPP** | The referenced socket is not a type that supports connection-oriented service. | | - **WSAEWOULDBLOCK** | The socket is marked as nonblocking and no connections are present to be accepted. | ## Remarks The **accept** function extracts the first connection on the queue of pending connections on socket *s*. It then creates and returns a handle to the new socket. The newly created socket is the socket that will handle the actual connection; it has the same properties as socket *s*, including the asynchronous events registered with the WSAAsyncSelect or WSAEventSelect functions. The **accept** function can block the caller until a connection is present if no pending connections are present on the queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on the queue, **accept** returns an error as described in the following. After the successful completion of **accept** returns a new socket handle, the accepted socket cannot be used to accept more connections. The original socket remains open and listens for new connection requests. The parameter *addr* is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the *addr* parameter is determined by the address family in which the communication is occurring. The *addrlen* is a value-result parameter; it should initially contain the amount of space pointed to by *addr*; on return it will contain the actual length (in bytes) of the address returned. The **accept** function...</excerpt> </source> <source> <title>Winsock IOCTLs (Winsock2.h) - Win32 apps | Microsoft Learn</title> <location>https://learn.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls</location> <excerpt>### FIONBIO ... Enable or disable non-blocking mode on socket s. The lpvInBuffer parameter points at an unsigned long (QoS), which is nonzero if non-blocking mode is to be enabled and zero if it is to be disabled. When a socket is created, it operates in blocking mode (that is, non-blocking mode is disabled). This is consistent with BSD sockets. ... The WSAAsyncSelect or WSAEventSelect routine automatically sets a socket to non-blocking mode. If WSAAsyncSelect or WSAEventSelect has been issued on a socket, then any attempt to use WSAIoctl to set the socket back to blocking mode will fail with WSAEINVAL. To set the socket back to blocking mode, an application must first disable WSAAsyncSelect by calling WSAAsyncSelect with the lEvent parameter equal to zero, or disable WSAEventSelect by calling WSAEventSelect with the lNetworkEvents parameter equal to zero.</excerpt> </source> <source> <title>Result 3</title> <location>https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaaccept</location> <excerpt># WSAAccept function (winsock2.h) - Win32 apps | Microsoft Learn ... The WSAAccept function conditionally accepts a connection based on the return value of a condition function, provides quality of service flow specifications, and allows the transfer of connection data. ... | - WSAEWOULDBLOCK | A non-blocking socket operation could not be completed immediately. This error is returned if the socket is marked as nonblocking and no connections are present to be accepted. | ... The WSAAccept function extracts the first connection on the queue of pending connections on socket s, and checks it against the condition function, provided the condition function is specified (that is, not NULL). If the condition function returns CF_ACCEPT, WSAAccept creates a new socket. The newly created socket has the same properties as socket s including asynchronous events registered with WSAAsyncSelect or with WSAEventSelect. If the condition function returns CF_REJECT, WSAAccept rejects the connection request. The condition function runs in the same thread as this function does, and should return as soon as possible. If the decision cannot be made immediately, the condition function should return CF_DEFER to indicate that no decision has been made, and no action about this connection request should be taken by the service provider. When the application is ready to take action on the connection request, it will invoke WSAAccept again and return either CF_ACCEPT or CF_REJECT as a return value from the condition function. ... A socket in default mode (blocking) will block until a connection is present when an application calls WSAAccept and no connections are pending on the queue. ... A socket in nonblocking mode (blocking) fails with the error WSAEWOULDBLOCK when an application calls WSAAccept and no connections are pending on the queue. After WSAAccept succeeds and returns a new socket handle, the accepted socket cannot be used to accept any more connections. The original socket remains open and listens for new connection requests. ... The g parameter is assigned within the condition function to indicate any of the following actions: ... - If g is an existing socket group identifier, add s to this group, provided all the requirements set by this group are met. - If g = SG_UNCONSTRAINED_GROUP, create an unconstrained socket group and have s as the first member. - If g = SG_CONSTRAINED_GROUP, create a constrained socket group and have s as the first member. - If g = zero, no group operation is performed. ... For unconstrained ... , any set of sockets can be grouped together ... supported by a ... service provider. ... connection-oriented sockets, ... connections on all grouped sockets be to the same address on ... same host. For newly ... groups, the new group identifier can be retrieved by using getsock ... parameter set to SOL_SOCKET and the optname parameter set ... _ID. A ... remain valid until the last socket ... to this socket group is closed. ... IDs are unique across all processes for a given ... provider. A ... remain valid until the last socket belonging to this socket group is closed. Socket group identifiers are unique across all processes for a given service provider. For more information on socket groups, see ... Remarks for the WSASocket functions. ... Note To protect use of the WSAAccept function from SYN attacks, applications must perform full TCP handshakes (SYN-SYNACK-ACK) before reporting the connection request. Protecting against SYN attacks in this manner results in the SO_CONDITIONAL_ACCEPT socket option becoming inoperative; the conditional function is still called, and the WSAAccept function operates properly, but server applications that rely on clients being unable to perform the handshake will not operate properly. Note When issuing a blocking Winsock call such as WSAAccept, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interru...</excerpt> </source> <source> <title>nf-mswsock-acceptex</title> <location>https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex</location> <excerpt>The **AcceptEx** function accepts a new connection, returns the local and remote address, and receives the first block of data sent by the client application. **Note** This function is a Microsoft-specific extension to the Windows Sockets specification. ## Syntax ```cpp BOOL AcceptEx( ... [in] SOCKET sListenSocket, [in] SOCKET sAcceptSocket ... [in] PVOID lpOutputBuffer, [in] DWORD dwReceiveDataLength, ... [in] DWORD dwLocalAddressLength, [in] DWORD dwRemoteAddressLength, ... [out] LPDWORD lpdwBytesReceived, [in] LPOVERLAPPED lpOverlapped ); ... ## Parameters `[in] sListenSocket` ... A descriptor identifying a socket that has already been called with ... connect on this socket ... `[in] sAcceptSocket` ... A descriptor identifying a socket on which to accept ... . This socket must not be bound or connected. ... `[in] lpOutput ... ## Return value If no error occurs, the **AcceptEx** function completed successfully and a value of **TRUE** is returned. If the function fails, **AcceptEx** returns **FALSE**. The WSAGetLastError function can then be called to return extended error information. If **WSAGetLastError** returns **ERROR\_IO ... PENDING**, then the operation was successfully initiated and is still in progress. If the error is WSAECONNRESET, an incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call. ## Remarks The **AcceptEx** function combines several socket functions into a single API/kernel transition. The **AcceptEx** function, when successful, performs three tasks: - A new connection is accepted. - Both the local and remote addresses for the connection are returned. - The first block of data sent by the remote is received. **Note** The function pointer for the **AcceptEx** function must be obtained at run time by making a call to the WSAIoctl function with the **SIO\_GET\_EXTENSION\_FUNCTION\_POINTER** opcode specified. The input buffer passed to the **WSAIoctl** function must contain **WSAID\_ACCEPTEX**, a globally unique identifier (GUID) whose value identifies the **AcceptEx** extension function. On success, the output returned by the **WSAIoctl** function contains a pointer to the **AcceptEx** function. The **WSAID\_ACCEPTEX** GUID is defined in the *Mswsock.h* header file. A program can make a connection to a socket more quickly using **AcceptEx** instead of the accept function. A single output buffer receives the data, the local socket address (the server), and the remote socket address (the client). Using a single buffer improves performance. When using **AcceptEx**, the GetAcceptExSockaddrs function must be called to parse the buffer into its three distinct parts (data, local socket address, and remote socket address). On Windows XP and later, once the **AcceptEx** function completes and the **SO\_UPDATE\_ACCEPT\_CONTEXT** option is set on the accepted socket, the local address associated with the accepted socket can also be retrieved using the getsockname function. Likewise, the remote address associated with the accepted socket can be retrieved using the getpeername function. The buffer size for the local and remote address must be 16 bytes more than the size of the sockaddr structure for the transport protocol in use because the addresses are written in an internal format. For example, the size of a **sockaddr\_in** (the address structure for TCP/IP) is 16 bytes. Therefore, a buffer size of at least 32 bytes must be specified for the local and remote addresses. The **AcceptEx** function uses overlapped I/O, unlike the accept function. If your application uses **AcceptEx**, it can service a large number of clients with a relatively small number of threads. As with all overlapped Windows functions, either Windows events or completion ports can be used as a completion notification mechanism. Another key difference between the **AcceptEx** function and the accept function is that **AcceptEx** requires the caller to already have two sockets: - One that...</excerpt> </source> <source> <title>winsock-socket-state-notifications</title> <location>https://learn.microsoft.com/en-us/windows/win32/winsock/winsock-socket-state-notifications</location> <excerpt>tcpAcceptSocket = accept(serverContext-&gt;listenerSocket, NULL, NULL); if (tcpAcceptSocket == INVALID_SOCKET) { errorCode = GetLastError(); goto Exit; } if (ioctlsocket(tcpAcceptSocket, FIONBIO, &amp;nonBlocking) != 0) { errorCode = GetLastError(); goto Exit; } ... // Register the accepted connection. registration.completionKey = (PVOID)tcpAcceptSocket; registration.eventFilter = SOCK_NOTIFY_REGISTER_EVENT_IN | SOCK_NOTIFY_REGISTER_EVENT_HANGUP; registration.operation = SOCK_NOTIFY_OP_ENABLE; registration.triggerFlags = SOCK_NOTIFY_TRIGGER_LEVEL; registration.socket = tcpAcceptSocket; errorCode = ProcessSocketNotifications(serverContext-&gt;ioCompletionPort, 1, &amp;registration, 0, 0, NULL, NULL); // Make sure all registrations were processed. if (errorCode != ERROR_SUCCESS) { goto Exit; } ... // Make sure each registration was successful. ... if (registration.registration ... SUCCESS) { errorCode = registration.registrationResult; goto ... // Use non-blocking sockets with edge-triggered notifications, since the data must be // drained before a rising edge can be observed again. errorCode = ioctlsocket(serverSocket, FIONBIO, &amp;nonBlocking); if (errorCode != ERROR_SUCCESS) { goto Exit; } ... SOCKET_CONTEXT ... socketContextOut) { DWORD errorCode; ... SOCKET_CONTEXT ... NULL; ... socketContext = ... SOCKET_CONTEXT*)malloc(sizeof(*socketContext)); if (socketContext == NULL) { errorCode = ERROR_NOT_ ... OUGH_MEMORY; goto Exit; ... } ... ZeroMemory(socketContext, sizeof(*socketContext)); socketContext-&gt;socketType = SOCKET_TYPE ... ACCEPT; socketContext-&gt;socket = accept(listenSocket, NULL, NULL); ... if (socketContext-&gt;socket == INVALID_SOCKET) { errorCode ... goto Exit ... *socketContextOut = socketContext; ... socketContext = NULL ... ThreadRoutine(_In ... CONTEXT* server ... Context; HANDLE io ... Port; ... registrations: one to re-enable the listening ... // notification, and one to register the newly- ... . SOCK_NOTIFY_REGISTRATION registrationBuffer[SERVER_DEQUEUE_COUNT * 2]; UINT32 registrationCount; SOCK_NOTIFY_REGISTRATION* registration; OVERLAPPED_ENTRY notifications[SERVER_DEQUEUE_COUNT]; UINT32 notificationCount; UINT32 events; SOCKET_CONTEXT* ... Context; SOCKET_CONTEXT* acceptedContext; BOOLEAN shouldExit; CHAR dataBuffer[512]; ... // Process the socket notification, taking socket-specific actions. switch (socketContext-&gt;socketType) { case SOCKET_TYPE_LISTENER: // Accepting connections in response to notifications implicitly throttles // the rate at which incoming connections are accepted, and limits scale-out for // new connection acceptance. Consider using AcceptEx if greater scaling of //connection acceptance is desired. // Perform an accept regardless of the notification. The only possible notifications // are for available connections or error conditions. Any possible error conditions // will be processed as part of the accept. errorCode = AcceptConnection(socketContext-&gt;socket, &amp;acceptedContext); if (errorCode == ERROR_SUCCESS) { // Register the accepted connection. registration = &amp;registrationBuffer[registrationCount]; registration-&gt;socket = acceptedContext-&gt;socket; registration-&gt;completionKey = acceptedContext; registration-&gt;eventFilter = SOCK_NOTIFY_EVENT_IN | SOCK_NOTIFY_EVENT_HANGUP; registration-&gt;operation = SOCK_NOTIFY_OP_ENABLE; registration-&gt;triggerFlags = SOCK_NOTIFY_TRIGGER_ONESHOT | SOCK_NOTIFY_TRIGGER_LEVEL; registrationCount += 1; } // Re-arm the existing listening socket registration. registration = &amp;registrationBuffer[registrationCount]; registration-&gt;socket = socketContext-&gt;socket; registration-&gt;completionKey = socketContext; registration-&gt;eventFilter = SOCK_NOTIFY_EVENT_IN; registration-&gt;operation = SOCK_NOTIFY_OP_ENABLE; registration-&gt;triggerFlags = SOCK_NOTIFY_TRIGGER_ONESHOT | SOCK_NOTIFY_TRIGGER_LEVEL; registrationCount += 1; break; ... case SOCKET_TYPE_ACCEPT: // The registration was removed. Clean up the contex…[truncated]</excerpt> </source> </source_evidence> Citations: - 1: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept - 2: https://learn.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls - 3: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaaccept - 4: https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex - 5: https://learn.microsoft.com/en-us/windows/win32/winsock/winsock-socket-state-notifications --- 🏁 Script executed: ```bash sed -n '390,525p' tests/KernelFileSystemTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 7744 --- </details> **Copy the listener mode to the accepted transport.** Winsock preserves the listener's `FIONBIO` mode on the socket returned by `accept`, but `SocketTransport(accepted)` initializes `nonblocking` to `false`. `RecvPeekWaitAll` then treats the accepted socket as blocking and can wait indefinitely for the remaining bytes of a partial `MSG_WAITALL` receive. <details> <summary>🐛 Suggested fix in <code>Accept</code></summary> ```diff auto transport = std::make_shared<SocketTransport>(accepted); +#if defined(_WIN32) + transport->nonblocking = IsSocketNonBlocking(s); +#endif const int fd = AllocSocketFd(transport); ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f5ee7d168d1434a9226a15cb --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1097,0 +1181,4 @@
return host_len;
}
return SetHostSocketError();
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 06:13 UTC · original · edited 2026-09-26 01:43 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Datagram peeks fail with EMSGSIZE instead of returning truncated data.

Winsock fails a datagram recv/recvfrom with WSAEMSGSIZE when the buffer is smaller than the datagram. It still fills the buffer. Recvfrom (Lines 2315-2318) turns this case into success with host_len. RecvPeekWaitAll handles every negative result with SetHostSocketError(). Line 2304 then returns -1, so the guest gets POSIX_EMSGSIZE. FreeBSD returns the truncated length.

Zero-length receives with a source address hit this every time. Line 1132 sends the datagram case to RecvHost with length 0. A non-empty datagram then fails with WSAEMSGSIZE. The comment at Line 1134 says this case should report the source address.

🐛 Proposed fix
 		const int64_t peeked = RecvHost(socket, buf, host_len, MSG_PEEK, host_addr, host_addrlen);
 		if (peeked < 0) {
+			if (WSAGetLastError() == WSAEMSGSIZE) {
+				// Winsock copied the datagram prefix; POSIX reports its length as success.
+				return host_len;
+			}
 			return SetHostSocketError();
 		}
📝 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 (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 (;;) {
		const int64_t peeked = RecvHost(socket, buf, host_len, MSG_PEEK, host_addr, host_addrlen);
		if (peeked < 0) {
			if (WSAGetLastError() == WSAEMSGSIZE) {
				// Winsock copied the datagram prefix; POSIX reports its length as success.
				return host_len;
			}
			return SetHostSocketError();
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 06:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4090498448) · edited 2026-09-26 01:43 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Datagram peeks fail with EMSGSIZE instead of returning truncated data.** Winsock fails a datagram `recv`/`recvfrom` with WSAEMSGSIZE when the buffer is smaller than the datagram. It still fills the buffer. `Recvfrom` (Lines 2315-2318) turns this case into success with `host_len`. `RecvPeekWaitAll` handles every negative result with `SetHostSocketError()`. Line 2304 then returns -1, so the guest gets `POSIX_EMSGSIZE`. FreeBSD returns the truncated length. Zero-length receives with a source address hit this every time. Line 1132 sends the datagram case to `RecvHost` with length 0. A non-empty datagram then fails with WSAEMSGSIZE. The comment at Line 1134 says this case should report the source address. <details> <summary>🐛 Proposed fix</summary> ```diff const int64_t peeked = RecvHost(socket, buf, host_len, MSG_PEEK, host_addr, host_addrlen); if (peeked < 0) { + if (WSAGetLastError() == WSAEMSGSIZE) { + // Winsock copied the datagram prefix; POSIX reports its length as success. + return host_len; + } return SetHostSocketError(); } ``` </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 (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 (;;) { const int64_t peeked = RecvHost(socket, buf, host_len, MSG_PEEK, host_addr, host_addrlen); if (peeked < 0) { if (WSAGetLastError() == WSAEMSGSIZE) { // Winsock copied the datagram prefix; POSIX reports its length as success. return host_len; } return SetHostSocketError(); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:174aaa6778324cead2e1d9e6 --> <!-- This is an auto-generated reply by CodeRabbit -->
@ -1097,0 +1194,4 @@
// Preserve the already-buffered prefix instead of turning it into WSAECONNRESET.
return peeked;
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 06:13 UTC · original · edited 2026-09-24 08:48 UTC

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1090,1165p' src/libs/network.cpp
sed -n '450,535p' tests/KernelFileSystemTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8140


Bound the blocking peek without removing fragmented-read waiting.

A short MSG_PEEK | MSG_WAITALL result is expected while the remaining fragment can still arrive. Returning that result immediately would break the fragmented-data contract: the test sends a short prefix, delays the remainder, and expects the receive to return the complete message.

The current non-consuming retry can still wait indefinitely when the prefix fills the receive window. Keep waiting for fragments, but add a bounded wait or another capacity-independent termination condition. Do not use SO_RCVBUF as an exact receive-window limit; Windows may auto-tune the effective TCP receive window.

✅ Addressed in commit 3727d67

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 06:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4090498474) · edited 2026-09-24 08:48 UTC _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '1090,1165p' src/libs/network.cpp sed -n '450,535p' tests/KernelFileSystemTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8140 --- </details> **Bound the blocking peek without removing fragmented-read waiting.** A short `MSG_PEEK | MSG_WAITALL` result is expected while the remaining fragment can still arrive. Returning that result immediately would break the fragmented-data contract: the test sends a short prefix, delays the remainder, and expects the receive to return the complete message. The current non-consuming retry can still wait indefinitely when the prefix fills the receive window. Keep waiting for fragments, but add a bounded wait or another capacity-independent termination condition. Do not use `SO_RCVBUF` as an exact receive-window limit; Windows may auto-tune the effective TCP receive window. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:18dad24fc74343bdcf15e9c4 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 3727d67
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 06:13 UTC · original · reviewed

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 6228e009-5411-425f-831d-1ff2809729f3

📥 Commits

Reviewing files that changed from the base of the PR and between 3dc3fd0197 and dcc2de2468.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 06:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#pullrequestreview-5300503237) · **reviewed** **Actionable comments posted: 3** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `6228e009-5411-425f-831d-1ff2809729f3` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 3dc3fd0197ae361add9007f5cddeb552246c3d10 and dcc2de246812f6b65d9663516f73c9bc7353191e. </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; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-24 08:42 UTC · original

Updated the head to include the validated follow-up commit and current upstream/main.

Addressed the review findings:

  • accepted sockets now mirror the listener guest nonblocking mode in Winsock and in the transport bookkeeping;
  • zero-length datagram peeks use a one-byte MSG_PEEK scratch path and translate Winsock WSAEMSGSIZE while preserving the source address;
  • blocking MSG_WAITALL remains intentionally blocking until the requested bytes arrive or the peer closes, matching FreeBSD semantics rather than imposing an arbitrary timeout.

Validation after the upstream merge:

  • kernel_file_system_tests build: passed;
  • kernel_file_system: passed;
  • virtual_memory_allocation: passed;
  • kyty_tests aggregate build: passed;
  • git diff --check: passed.

The local AMD Vulkan harness limitation remains separate: production rasterization tests cannot start without VK_EXT_attachment_feedback_loop_dynamic_state.

**@⁠theantipopau** on GitHub · 2026-09-24 08:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#issuecomment-5810819885) Updated the head to include the validated follow-up commit and current upstream/main. Addressed the review findings: - accepted sockets now mirror the listener guest nonblocking mode in Winsock and in the transport bookkeeping; - zero-length datagram peeks use a one-byte MSG_PEEK scratch path and translate Winsock WSAEMSGSIZE while preserving the source address; - blocking MSG_WAITALL remains intentionally blocking until the requested bytes arrive or the peer closes, matching FreeBSD semantics rather than imposing an arbitrary timeout. Validation after the upstream merge: - kernel_file_system_tests build: passed; - kernel_file_system: passed; - virtual_memory_allocation: passed; - kyty_tests aggregate build: passed; - git diff --check: passed. The local AMD Vulkan harness limitation remains separate: production rasterization tests cannot start without VK_EXT_attachment_feedback_loop_dynamic_state.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 08:45 UTC · original · edited 2026-09-24 08:48 UTC
On tests/KernelFileSystemTests.cpp line 569 (outdated):

@@ -454,19 +458,172 @@ 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);
+  });
+  std::array<char, text_length> message {};
+  Check(Net::Recv(reader, message.data(), message.size(), 0x42) == message.size() &&
+            std::memcmp(message.data(), text, text_length) == 0,
+        "guest PEEK and WAITALL waits for a fragmented message");
+  peer.join();
+  Check(Net::Recv(reader, message.data(), message.size(), 0) == message.size() &&
+            std::memcmp(message.data(), text, text_length) == 0,
+        "peeked bytes stay available for the following receive");
+  Check(Net::Recv(reader, message.data(), 0, 0x42) == 0,
+        "zero length guest PEEK and WAITALL succeeds");
+
+  // MSG_DONTWAIT must never wait for the rest of the message.
+  Check(Net::Send(writer, text, prefix_length, 0) == prefix_length,
+        "send bytes for the non-waiting peek");
+  Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == prefix_length,
+        "guest MSG_DONTWAIT PEEK and WAITALL returns the buffered prefix");
+  Check(Net::Recv(reader, message.data(), prefix_length, 0) == prefix_length,
+        "consume the non-waiting peek prefix");
+  Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == -1 &&
+            *Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EWOULDBLOCK,
+        "empty guest MSG_DONTWAIT PEEK and WAITALL translates guest errno");
+#if defined(_WIN32)
+  const int nonblocking = 1;
+  Check(Net::Setsockopt(reader, 0xffff, 0x1200, &nonblocking, sizeof(nonblocking)) == 0,
+        "enable the guest non-blocking socket");
+  Check(Net::Send(writer, text, prefix_length, 0) == prefix_length,
+        "send bytes for the non-blocking socket peek");
+  Check(Net::Recv(reader, message.data(), message.size(), 0x42) == prefix_length,
+        "non-blocking socket PEEK and WAITALL returns the buffered prefix");
+  Check(Net::Recv(reader, message.data(), prefix_length, 0) == prefix_length,
+        "consume the non-blocking socket peek prefix");
+  const int blocking = 0;
+  Check(Net::Setsockopt(reader, 0xffff, 0x1200, &blocking, sizeof(blocking)) == 0,
+        "restore the guest blocking socket");
+#endif
 #if !defined(_WIN32)
   Check(Net::Recv(reader, received.data(), received.size(), 0x80) == -1 &&
             *Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EWOULDBLOCK,
         "empty nonblocking receive translates guest errno");
 #endif
-  Check(Net::SocketClose(reader) == 0 && Net::SocketClose(writer) == 0,
-        "close wake sockets");
+  // A peer that closes before the requested length ends the wait with the buffered bytes.
+  Check(Net::Send(writer, text, prefix_length, 0) == prefix_length,
+        "send the final message");
+  Check(Net::SocketClose(writer) == 0, "close the writer to signal end of file");
+  std::array<char, 16> tail {};
+  Check(Net::Recv(reader, tail.data(), tail.size(), 0x42) == prefix_length &&
+            std::memcmp(tail.data(), text, prefix_length) == 0,
+        "guest PEEK and WAITALL returns a short read at end of file");
+  Check(Net::Recv(reader, tail.data(), tail.size(), 0x42) == prefix_length,
+        "short peek at end of file keeps the bytes queued");
+  Check(Net::Recv(reader, tail.data(), tail.size(), 0) == prefix_length,
+        "consume the end of file bytes");
+  Check(Net::Recv(reader, tail.data(), tail.size(), 0x42) == 0,
+        "guest PEEK and WAITALL reports end of file");
+  Check(Net::SocketClose(reader) == 0, "close the wake reader");
   readable[reader / 64] = bit;
   Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr,
                     immediate.data()) == -1 &&
             *Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EBADF &&
             readable[reader / 64] == bit,
         "closed descriptor fails without clearing input fd_set");
+
+#if defined(_WIN32)
+  // FreeBSD accept(2) inherits O_NONBLOCK from the listening socket. Keep the native
+  // accepted socket and the emulator's guest-mode bookkeeping in agreement.
+  std::array<uint8_t, 16> inherited_address {16, 2, 0, 0, 127, 0, 0, 1};
+  const int inherited_listener = Net::Socket(2, 1, 0);
+  Check(inherited_listener >= 0 &&
+            Net::Bind(inherited_listener, inherited_address.data(),
+                      inherited_address.size()) == 0 &&
+            Net::Listen(inherited_listener, 1) == 0,
+        "create listener for accepted-mode test");
+  uint32_t inherited_address_size = inherited_address.size();
+  Check(Net::Getsockname(inherited_listener, inherited_address.data(),
+                         &inherited_address_size) == 0,
+        "get accepted-mode listener port");
+  const int inherited_writer = Net::Socket(2, 1, 0);
+  const int inherited_nonblocking = 1;
+  Check(Net::Setsockopt(inherited_listener, 0xffff, 0x1200, &inherited_nonblocking,
+                        sizeof(inherited_nonblocking)) == 0 &&
+            Net::Connect(inherited_writer, inherited_address.data(),
+                         inherited_address_size) == 0,
+        "connect to nonblocking listener");
+  const int inherited_reader = Net::Accept(inherited_listener, nullptr, nullptr);
+  Check(inherited_reader >= 0, "accept nonblocking listener socket");
+  Check(Net::Send(inherited_writer, text, prefix_length, 0) == prefix_length,
+        "send accepted-mode prefix");
+  std::array<char, text_length> inherited_message {};
+  auto inherited_receive = std::async(std::launch::async, [&] {
+    return Net::Recv(inherited_reader, inherited_message.data(), inherited_message.size(),
+                     0x42);
+  });
+  const bool returned_before_completion =
+      inherited_receive.wait_for(std::chrono::milliseconds(250)) ==
+      std::future_status::ready;

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Avoid a scheduling-dependent failure in the accepted-socket test.

If the async worker starts late or runs slowly, wait_for(250ms) can time out even when Net::Recv correctly returns the prefix before the suffix is sent. The test then fails because returned_before_completion is false. Use a more generous deadline, and keep the suffix send as the fallback that releases a blocking receive. (eel.is)

✅ Addressed in commit 3727d67

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 08:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4091627199) · edited 2026-09-24 08:48 UTC On `tests/KernelFileSystemTests.cpp` line 569 (outdated): ```diff @@ -454,19 +458,172 @@ 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); + }); + std::array<char, text_length> message {}; + Check(Net::Recv(reader, message.data(), message.size(), 0x42) == message.size() && + std::memcmp(message.data(), text, text_length) == 0, + "guest PEEK and WAITALL waits for a fragmented message"); + peer.join(); + Check(Net::Recv(reader, message.data(), message.size(), 0) == message.size() && + std::memcmp(message.data(), text, text_length) == 0, + "peeked bytes stay available for the following receive"); + Check(Net::Recv(reader, message.data(), 0, 0x42) == 0, + "zero length guest PEEK and WAITALL succeeds"); + + // MSG_DONTWAIT must never wait for the rest of the message. + Check(Net::Send(writer, text, prefix_length, 0) == prefix_length, + "send bytes for the non-waiting peek"); + Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == prefix_length, + "guest MSG_DONTWAIT PEEK and WAITALL returns the buffered prefix"); + Check(Net::Recv(reader, message.data(), prefix_length, 0) == prefix_length, + "consume the non-waiting peek prefix"); + Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == -1 && + *Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EWOULDBLOCK, + "empty guest MSG_DONTWAIT PEEK and WAITALL translates guest errno"); +#if defined(_WIN32) + const int nonblocking = 1; + Check(Net::Setsockopt(reader, 0xffff, 0x1200, &nonblocking, sizeof(nonblocking)) == 0, + "enable the guest non-blocking socket"); + Check(Net::Send(writer, text, prefix_length, 0) == prefix_length, + "send bytes for the non-blocking socket peek"); + Check(Net::Recv(reader, message.data(), message.size(), 0x42) == prefix_length, + "non-blocking socket PEEK and WAITALL returns the buffered prefix"); + Check(Net::Recv(reader, message.data(), prefix_length, 0) == prefix_length, + "consume the non-blocking socket peek prefix"); + const int blocking = 0; + Check(Net::Setsockopt(reader, 0xffff, 0x1200, &blocking, sizeof(blocking)) == 0, + "restore the guest blocking socket"); +#endif #if !defined(_WIN32) Check(Net::Recv(reader, received.data(), received.size(), 0x80) == -1 && *Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EWOULDBLOCK, "empty nonblocking receive translates guest errno"); #endif - Check(Net::SocketClose(reader) == 0 && Net::SocketClose(writer) == 0, - "close wake sockets"); + // A peer that closes before the requested length ends the wait with the buffered bytes. + Check(Net::Send(writer, text, prefix_length, 0) == prefix_length, + "send the final message"); + Check(Net::SocketClose(writer) == 0, "close the writer to signal end of file"); + std::array<char, 16> tail {}; + Check(Net::Recv(reader, tail.data(), tail.size(), 0x42) == prefix_length && + std::memcmp(tail.data(), text, prefix_length) == 0, + "guest PEEK and WAITALL returns a short read at end of file"); + Check(Net::Recv(reader, tail.data(), tail.size(), 0x42) == prefix_length, + "short peek at end of file keeps the bytes queued"); + Check(Net::Recv(reader, tail.data(), tail.size(), 0) == prefix_length, + "consume the end of file bytes"); + Check(Net::Recv(reader, tail.data(), tail.size(), 0x42) == 0, + "guest PEEK and WAITALL reports end of file"); + Check(Net::SocketClose(reader) == 0, "close the wake reader"); readable[reader / 64] = bit; Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr, immediate.data()) == -1 && *Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EBADF && readable[reader / 64] == bit, "closed descriptor fails without clearing input fd_set"); + +#if defined(_WIN32) + // FreeBSD accept(2) inherits O_NONBLOCK from the listening socket. Keep the native + // accepted socket and the emulator's guest-mode bookkeeping in agreement. + std::array<uint8_t, 16> inherited_address {16, 2, 0, 0, 127, 0, 0, 1}; + const int inherited_listener = Net::Socket(2, 1, 0); + Check(inherited_listener >= 0 && + Net::Bind(inherited_listener, inherited_address.data(), + inherited_address.size()) == 0 && + Net::Listen(inherited_listener, 1) == 0, + "create listener for accepted-mode test"); + uint32_t inherited_address_size = inherited_address.size(); + Check(Net::Getsockname(inherited_listener, inherited_address.data(), + &inherited_address_size) == 0, + "get accepted-mode listener port"); + const int inherited_writer = Net::Socket(2, 1, 0); + const int inherited_nonblocking = 1; + Check(Net::Setsockopt(inherited_listener, 0xffff, 0x1200, &inherited_nonblocking, + sizeof(inherited_nonblocking)) == 0 && + Net::Connect(inherited_writer, inherited_address.data(), + inherited_address_size) == 0, + "connect to nonblocking listener"); + const int inherited_reader = Net::Accept(inherited_listener, nullptr, nullptr); + Check(inherited_reader >= 0, "accept nonblocking listener socket"); + Check(Net::Send(inherited_writer, text, prefix_length, 0) == prefix_length, + "send accepted-mode prefix"); + std::array<char, text_length> inherited_message {}; + auto inherited_receive = std::async(std::launch::async, [&] { + return Net::Recv(inherited_reader, inherited_message.data(), inherited_message.size(), + 0x42); + }); + const bool returned_before_completion = + inherited_receive.wait_for(std::chrono::milliseconds(250)) == + std::future_status::ready; ``` _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ **Avoid a scheduling-dependent failure in the accepted-socket test.** If the async worker starts late or runs slowly, `wait_for(250ms)` can time out even when `Net::Recv` correctly returns the prefix before the suffix is sent. The test then fails because `returned_before_completion` is false. Use a more generous deadline, and keep the suffix send as the fallback that releases a blocking receive. ([eel.is](https://eel.is/c%2B%2Bdraft/thread?utm_source=openai)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:5f935e2e8e23253e7afc63d5 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 3727d67
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 08:45 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 98e983b5-7a5d-40cc-b363-2f79252bd9ad

📥 Commits

Reviewing files that changed from the base of the PR and between dcc2de2468 and b5dab67f1d.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 08:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#pullrequestreview-5301958564) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `98e983b5-7a5d-40cc-b363-2f79252bd9ad` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between dcc2de246812f6b65d9663516f73c9bc7353191e and b5dab67f1d55f1cd54cc32944eace5d0b01ef27a. </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; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠theantipopau on GitHub · 2026-09-24 08:54 UTC · original

The final review pass is clean. The accepted-socket path now reads the listener transport state, applies the matching FIONBIO mode to the accepted Winsock handle, and records it for later PEEK/WAITALL calls; the regression covers a partial prefix. The datagram path handles WSAEMSGSIZE inside the helper and uses a scratch byte for zero-length source-address peeks; the regression covers both the peek and consume. The blocking WAITALL path intentionally has no arbitrary timeout because FreeBSD permits a blocking WAITALL receive to wait for the remaining fragment; the existing delayed-fragment test protects that contract. The accepted-socket synchronization window is now two seconds to avoid CI scheduling flakes.

**@⁠theantipopau** on GitHub · 2026-09-24 08:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#issuecomment-5810999609) The final review pass is clean. The accepted-socket path now reads the listener transport state, applies the matching FIONBIO mode to the accepted Winsock handle, and records it for later PEEK/WAITALL calls; the regression covers a partial prefix. The datagram path handles WSAEMSGSIZE inside the helper and uses a scratch byte for zero-length source-address peeks; the regression covers both the peek and consume. The blocking WAITALL path intentionally has no arbitrary timeout because FreeBSD permits a blocking WAITALL receive to wait for the remaining fragment; the existing delayed-fragment test protects that contract. The accepted-socket synchronization window is now two seconds to avoid CI scheduling flakes.
Author
Owner

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

Tested 3727d67 on Windows with an NVIDIA GPU (RTX 5080, driver 596.49, clang-cl + Ninja, full clean build), merge-base 02578f3.

Full ctest: 40/40, no failures.

That covers the 17 Vulkan-backed tests your local AMD harness cannot start (no VK_EXT_attachment_feedback_loop_dynamic_state), plus kernel_file_system, which passes here. save_data_memory also passes once its target is built explicitly, which is what your #798 addresses.

One coordination note: this overlaps with #751 (rudy-07), opened three days earlier — same Winsock MSG_PEEK | MSG_WAITALL limitation, same SDL_MAIN_HANDLED fix. I tested that one on Windows as the reporter of #505: it makes kernel_file_system pass too, and I verified the failure is real by building main with only its SDL change (0xc0000409, "guest PEEK and WAITALL preserve the wake bytes"). Yours is the broader implementation (accepted sockets, datagrams, MSG_DONTWAIT, EOF) and addresses the partial-arrival case Copilot raised there. Neither PR references the other, so flagging it here and on #751 so a maintainer can pick one rather than leaving both open.

Not verified: any behaviour in an actual title, and non-Windows platforms.

**@⁠francoisatt** on GitHub · 2026-09-24 18:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#issuecomment-5819988251) Tested 3727d67 on Windows with an NVIDIA GPU (RTX 5080, driver 596.49, clang-cl + Ninja, full clean build), merge-base 02578f3. Full ctest: 40/40, no failures. That covers the 17 Vulkan-backed tests your local AMD harness cannot start (no VK_EXT_attachment_feedback_loop_dynamic_state), plus kernel_file_system, which passes here. save_data_memory also passes once its target is built explicitly, which is what your #798 addresses. One coordination note: this overlaps with #751 (rudy-07), opened three days earlier — same Winsock MSG_PEEK | MSG_WAITALL limitation, same SDL_MAIN_HANDLED fix. I tested that one on Windows as the reporter of #505: it makes kernel_file_system pass too, and I verified the failure is real by building main with only its SDL change (0xc0000409, "guest PEEK and WAITALL preserve the wake bytes"). Yours is the broader implementation (accepted sockets, datagrams, MSG_DONTWAIT, EOF) and addresses the partial-arrival case Copilot raised there. Neither PR references the other, so flagging it here and on #751 so a maintainer can pick one rather than leaving both open. Not verified: any behaviour in an actual title, and non-Windows platforms.
Author
Owner

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: d65a9171-05eb-44fb-96c6-dbb00e72379e

📥 Commits

Reviewing files that changed from the base of the PR and between 3727d67269 and f98551db039f75fe082371552bead0bd1f24683b.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 21:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#pullrequestreview-5310237029) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `d65a9171-05eb-44fb-96c6-dbb00e72379e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 3727d672699f8f18c7685da0abf502e59dd0fd58 and f98551db039f75fe082371552bead0bd1f24683b. </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; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -763,0 +806,4 @@
deadline.data()) == 1,
"non-waiting peek bytes are readable");
Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == prefix_length,
"guest MSG_DONTWAIT PEEK and WAITALL returns the buffered prefix");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 21:07 UTC · original · edited 2026-09-24 22:03 UTC

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Wait for readiness before the non-waiting peeks.

Line 489 sends prefix_length bytes and then calls Net::Recv with 0xc2 (MSG_DONTWAIT | MSG_WAITALL | MSG_PEEK) at once. Line 502 does the same thing on the guest non-blocking socket. Neither call waits for the bytes to arrive. If loopback delivery is late, Net::Recv returns -1 with EWOULDBLOCK and Check aborts the test. TCP_NODELAY controls when the sender transmits. It does not guarantee that the bytes are already in the receive buffer.

Before each non-waiting peek, wait for the reader to become readable with Net::Select and a deadline. This is the same pattern as lines 450-454. The peek still checks the non-waiting behavior because 5 bytes are buffered and 8 are requested.

Proposed fix
   Check(Net::Send(writer, text, prefix_length, 0) == prefix_length,
         "send bytes for the non-waiting peek");
+  readable[reader / 64] = bit;
+  Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr,
+                    deadline.data()) == 1,
+        "non-waiting peek bytes are readable");
   Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == prefix_length,
         "guest MSG_DONTWAIT PEEK and WAITALL returns the buffered prefix");
   Check(Net::Send(writer, text, prefix_length, 0) == prefix_length,
         "send bytes for the non-blocking socket peek");
+  readable[reader / 64] = bit;
+  Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr,
+                    deadline.data()) == 1,
+        "non-blocking socket peek bytes are readable");
   Check(Net::Recv(reader, message.data(), message.size(), 0x42) == prefix_length,
         "non-blocking socket PEEK and WAITALL returns the buffered prefix");

Also applies to: 500-503

✅ Addressed in commit c834baf

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 21:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4098488171) · edited 2026-09-24 22:03 UTC _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ **Wait for readiness before the non-waiting peeks.** Line 489 sends `prefix_length` bytes and then calls `Net::Recv` with `0xc2` (`MSG_DONTWAIT | MSG_WAITALL | MSG_PEEK`) at once. Line 502 does the same thing on the guest non-blocking socket. Neither call waits for the bytes to arrive. If loopback delivery is late, `Net::Recv` returns `-1` with `EWOULDBLOCK` and `Check` aborts the test. `TCP_NODELAY` controls when the sender transmits. It does not guarantee that the bytes are already in the receive buffer. Before each non-waiting peek, wait for the reader to become readable with `Net::Select` and a deadline. This is the same pattern as lines 450-454. The peek still checks the non-waiting behavior because 5 bytes are buffered and 8 are requested. <details> <summary>Proposed fix</summary> ```diff Check(Net::Send(writer, text, prefix_length, 0) == prefix_length, "send bytes for the non-waiting peek"); + readable[reader / 64] = bit; + Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr, + deadline.data()) == 1, + "non-waiting peek bytes are readable"); Check(Net::Recv(reader, message.data(), message.size(), 0xc2) == prefix_length, "guest MSG_DONTWAIT PEEK and WAITALL returns the buffered prefix"); ``` ```diff Check(Net::Send(writer, text, prefix_length, 0) == prefix_length, "send bytes for the non-blocking socket peek"); + readable[reader / 64] = bit; + Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr, + deadline.data()) == 1, + "non-blocking socket peek bytes are readable"); Check(Net::Recv(reader, message.data(), message.size(), 0x42) == prefix_length, "non-blocking socket PEEK and WAITALL returns the buffered prefix"); ``` </details> Also applies to: 500-503 <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7154e92c084edaf938289fa9 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit c834baf
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-24 22:08 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 · 🎯 Functional Correctness · network.cpp:1155-1174

src/libs/network.cpp:1155-1174
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return the buffered prefix after a terminal peer event.

When RecvPeekWaitAll has peeked a short prefix and WaitForPeekedBytes detects POLLHUP, Winsock treats the stream as disconnected or aborted. The next RecvHost call can then fail with WSAECONNRESET, so the guest receives an error instead of the buffered short read. Return peeked at the terminal branch.

Suggested fix
 static bool WaitForPeekedBytes(NativeSocket socket) {
 	std::this_thread::sleep_for(std::chrono::milliseconds(1));
-	constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL;
+	constexpr short terminal_events = POLLHUP | POLLERR;
 	return (PollSocket(socket) & terminal_events) != 0;
 }
 
@@
 		}
 		peer_closed = WaitForPeekedBytes(socket);
+		if (peer_closed) {
+			return peeked;
+		}
 	}
 }

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: f0c98059-6845-49b8-a82c-f4c506882e52

📥 Commits

Reviewing files that changed from the base of the PR and between f98551db039f75fe082371552bead0bd1f24683b and c834baf88dbf9ef6033859ec0841fa090218048e.

📒 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: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-24 22:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#pullrequestreview-5310807942) · **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> · <em>🎯 Functional Correctness</em> · <code>network.cpp:1155-1174</code></summary><blockquote> > > `src/libs/network.cpp:1155-1174` > _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ > > <strong>Return the buffered prefix after a terminal peer event.</strong> > > When `RecvPeekWaitAll` has peeked a short prefix and `WaitForPeekedBytes` detects `POLLHUP`, Winsock treats the stream as disconnected or aborted. The next `RecvHost` call can then fail with `WSAECONNRESET`, so the guest receives an error instead of the buffered short read. Return `peeked` at the terminal branch. > > <details> > <summary>Suggested fix</summary> > > ```diff > static bool WaitForPeekedBytes(NativeSocket socket) { > std::this_thread::sleep_for(std::chrono::milliseconds(1)); > - constexpr short terminal_events = POLLHUP | POLLERR | POLLNVAL; > + constexpr short terminal_events = POLLHUP | POLLERR; > return (PollSocket(socket) & terminal_events) != 0; > } > > @@ > } > peer_closed = WaitForPeekedBytes(socket); > + if (peer_closed) { > + return peeked; > + } > } > } > ``` > > </details> > > <!-- cr-comment:v1:2a6f3fd4ece5549712dc2c3e --> > > </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**: `f0c98059-6845-49b8-a82c-f4c506882e52` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between f98551db039f75fe082371552bead0bd1f24683b and c834baf88dbf9ef6033859ec0841fa090218048e. </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:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -1097,0 +1181,4 @@
return host_len;
}
return SetHostSocketError();
}
Author
Owner

@⁠theantipopau on GitHub · 2026-09-26 01:43 UTC · original

This was already addressed before your review ran, in 52315508 (Preserve accepted socket modes and datagram peeks). The head now has:

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();
}

so a truncated datagram reports the copied length rather than surfacing POSIX_EMSGSIZE to the guest. The zero-length-with-source-address case you flagged takes the one-byte scratch path first, and Winsock copying that byte without error is covered by return host_len == 0 ? 0 : peeked on the line below.

Also pushed in 33e8e343: WaitForPeekedBytes no longer treats POLLNVAL as terminal, and a terminal event now returns the already-buffered prefix rather than falling through to a WSAECONNRESET on the next peek.

**@⁠theantipopau** on GitHub · 2026-09-26 01:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4109767704) This was already addressed before your review ran, in `52315508` (Preserve accepted socket modes and datagram peeks). The head now has: ```c 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(); } ``` so a truncated datagram reports the copied length rather than surfacing `POSIX_EMSGSIZE` to the guest. The zero-length-with-source-address case you flagged takes the one-byte `scratch` path first, and Winsock copying that byte without error is covered by `return host_len == 0 ? 0 : peeked` on the line below. Also pushed in `33e8e343`: `WaitForPeekedBytes` no longer treats `POLLNVAL` as terminal, and a terminal event now returns the already-buffered prefix rather than falling through to a `WSAECONNRESET` on the next peek.
@ -1097,0 +1181,4 @@
return host_len;
}
return SetHostSocketError();
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 01:43 UTC · original

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git status --short
git rev-parse --short HEAD
ast-grep outline src/libs/network.cpp --match 'RecvPeekWaitAll|WaitForPeekedBytes|Recvfrom' --view expanded
rg -n -A85 -B12 'static bool WaitForPeekedBytes\(' src/libs/network.cpp | head -110
rg -n -A65 -B8 'int64_t KYTY_SYSV_ABI Recvfrom\(' src/libs/network.cpp | head -78

Length of output: 7935


@theantipopau, I need to correct my earlier reply. The shell check succeeded. At c834baf, RecvPeekWaitAll handles WSAEMSGSIZE and uses the one-byte scratch buffer for zero-length datagram peeks with a source address. My finding was already invalid at that revision, so I withdraw it.

The checked revision still includes POLLNVAL in WaitForPeekedBytes. This check does not verify the later 33e8e343 change.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 01:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#discussion_r4109769067) <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -euo pipefail git status --short git rev-parse --short HEAD ast-grep outline src/libs/network.cpp --match 'RecvPeekWaitAll|WaitForPeekedBytes|Recvfrom' --view expanded rg -n -A85 -B12 'static bool WaitForPeekedBytes\(' src/libs/network.cpp | head -110 rg -n -A65 -B8 'int64_t KYTY_SYSV_ABI Recvfrom\(' src/libs/network.cpp | head -78 ``` Length of output: 7935 --- </details> `@theantipopau`, I need to correct my earlier reply. The shell check succeeded. At `c834baf`, `RecvPeekWaitAll` handles `WSAEMSGSIZE` and uses the one-byte scratch buffer for zero-length datagram peeks with a source address. My finding was already invalid at that revision, so I withdraw it. The checked revision still includes `POLLNVAL` in `WaitForPeekedBytes`. This check does not verify the later `33e8e343` change. ✅ 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/797#issuecomment-5856112596) 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.
Author
Owner

@⁠theantipopau on GitHub · 2026-09-30 22:10 UTC · original

Evidence: upstream main fails this test on Windows, this branch passes it

While chasing #867 (which reports kernel_file_system_tests.exe never being built), I built the
target at plain upstream/main b7a1fac8 and ran it. One sub-test fails on Windows today:

KernelFileSystemTests: failed: Net receive forwards PEEK and WAITALL without consuming bytes
exit 127

That is the MSG_PEEK | MSG_WAITALL (0x42) case in CheckSocketWakeup. Net::Recv does not
translate the Windows flags, so the peeked read does not return the payload the test sent.

Building and running the same target at this branch's head (2b158c179):

[134/137] Linking CXX executable kernel_file_system_tests.exe
BUILD_RC=0

$ kernel_file_system_tests.exe
KernelFileSystemTests: all cases passed     (exit 0)
KernelFileSystemTests: all cases passed     (exit 0)
KernelFileSystemTests: all cases passed     (exit 0)

Three consecutive clean runs, so this is not a flake being papered over — upstream main is
deterministically red here and this branch is deterministically green.

Two things worth noting for reviewers:

  • CI never caught this. .github/workflows/build.yml builds and ctests only
    audio_out2_port_tests, ime_dialog_tests and virtual_memory_allocation_tests;
    kernel_file_system_tests is EXCLUDE_FROM_ALL and is not in the -R filter, so the failure
    is invisible to the workflow.
  • #867 also fails to link on Windows for an unrelated reason (SDL renaming the test's main).
    I split that out into #948 rather than stacking it here, so this PR stays reviewable on its own.

Not asking for anything beyond a look — happy to rebase onto main if that helps.

**@⁠theantipopau** on GitHub · 2026-09-30 22:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#issuecomment-5920611122) ## Evidence: upstream `main` fails this test on Windows, this branch passes it While chasing #867 (which reports `kernel_file_system_tests.exe` never being built), I built the target at plain `upstream/main` `b7a1fac8` and ran it. One sub-test fails on Windows today: ``` KernelFileSystemTests: failed: Net receive forwards PEEK and WAITALL without consuming bytes exit 127 ``` That is the `MSG_PEEK | MSG_WAITALL` (`0x42`) case in `CheckSocketWakeup`. `Net::Recv` does not translate the Windows flags, so the peeked read does not return the payload the test sent. Building and running the same target at this branch's head (`2b158c179`): ``` [134/137] Linking CXX executable kernel_file_system_tests.exe BUILD_RC=0 $ kernel_file_system_tests.exe KernelFileSystemTests: all cases passed (exit 0) KernelFileSystemTests: all cases passed (exit 0) KernelFileSystemTests: all cases passed (exit 0) ``` Three consecutive clean runs, so this is not a flake being papered over — upstream `main` is deterministically red here and this branch is deterministically green. Two things worth noting for reviewers: - CI never caught this. `.github/workflows/build.yml` builds and `ctest`s only `audio_out2_port_tests`, `ime_dialog_tests` and `virtual_memory_allocation_tests`; `kernel_file_system_tests` is `EXCLUDE_FROM_ALL` and is not in the `-R` filter, so the failure is invisible to the workflow. - #867 also fails to *link* on Windows for an unrelated reason (SDL renaming the test's `main`). I split that out into #948 rather than stacking it here, so this PR stays reviewable on its own. Not asking for anything beyond a look — happy to rebase onto `main` if that helps.
Author
Owner

@⁠theantipopau on GitHub · 2026-10-02 23:55 UTC · original

Rebased onto current upstream/main (e317465d)

Two conflicts were resolved by keeping both sides:

  • Setsockopt SO_NBIO (upstream restructured this in #954): the merged code keeps upstream's cross-platform #if defined(_WIN32)/fcntl shape and layers this PR's Windows-only tracking of the guest blocking mode on top (state.transport->nonblocking), which Winsock cannot query.
  • CheckSocketWakeup: upstream's newer error-path checks (EBADF/EFAULT/EOPNOTSUPP and the Linux SIGPIPE block) now run first, then this PR's EOF-tail checks (partial message at close, repeated peeks, EOF), then upstream's errno-preserving EOF check and the reader close. Each check runs exactly once.

Testing (Windows, kernel_file_system_tests)

  • 3/3 consecutive runs green after the rebase — RC=0, KernelFileSystemTests: all cases passed.
  • That includes both upstream's newly added error-path checks and this PR's fragment/MSG_DONTWAIT/SO_NBIO/EOF-tail checks in the same run.

Relation to #981 (same bug, different mechanism)

#981 fixes the same Winsock MSG_PEEK | MSG_WAITALL rejection by introducing a per-transport receive queue that every Recvfrom drains (plus Select/EpollWait changes). This PR instead keeps the kernel socket buffer as the single copy of received data:

  • recv(MSG_PEEK) is paced by poll for the WAITALL length, so a buffered prefix never desynchronizes from what other readers of the socket see;
  • MSG_DONTWAIT maps to a readiness poll, zero-length and WSAEMSGSIZE datagram peeks are handled explicitly, and a peer that closes mid-wait returns the buffered prefix instead of WSAECONNRESET;
  • poll-after-peek keeps epoll/select wakeups correct for data that is still queued.

Because there is no second queue, there is no drift risk with paths that read the socket outside Recvfrom (P2P framing, epoll, other threads), and this PR also covers cases #981 does not: datagram peek edge cases, P2P accept, accepted-socket mode preservation, and the blocking WAITALL short-send hang.

If a queued-emulation layer is ever wanted, it can be layered on top of this later — but with the Winsock rejection handled here, the regression cases do not need it.

**@⁠theantipopau** on GitHub · 2026-10-02 23:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/797#issuecomment-5963319295) ## Rebased onto current upstream/main (`e317465d`) Two conflicts were resolved by keeping both sides: - **`Setsockopt` SO_NBIO** (upstream restructured this in #954): the merged code keeps upstream's cross-platform `#if defined(_WIN32)/fcntl` shape and layers this PR's Windows-only tracking of the guest blocking mode on top (`state.transport->nonblocking`), which Winsock cannot query. - **`CheckSocketWakeup`**: upstream's newer error-path checks (EBADF/EFAULT/EOPNOTSUPP and the Linux SIGPIPE block) now run first, then this PR's EOF-tail checks (partial message at close, repeated peeks, EOF), then upstream's errno-preserving EOF check and the reader close. Each check runs exactly once. ## Testing (Windows, `kernel_file_system_tests`) - 3/3 consecutive runs green after the rebase — `RC=0, KernelFileSystemTests: all cases passed`. - That includes both upstream's newly added error-path checks and this PR's fragment/MSG_DONTWAIT/SO_NBIO/EOF-tail checks in the same run. ## Relation to #981 (same bug, different mechanism) #981 fixes the same Winsock `MSG_PEEK | MSG_WAITALL` rejection by introducing a per-transport receive queue that every `Recvfrom` drains (plus `Select`/`EpollWait` changes). This PR instead keeps the kernel socket buffer as the single copy of received data: - `recv(MSG_PEEK)` is paced by poll for the WAITALL length, so a buffered prefix never desynchronizes from what other readers of the socket see; - `MSG_DONTWAIT` maps to a readiness poll, zero-length and `WSAEMSGSIZE` datagram peeks are handled explicitly, and a peer that closes mid-wait returns the buffered prefix instead of `WSAECONNRESET`; - poll-after-peek keeps epoll/select wakeups correct for data that is still queued. Because there is no second queue, there is no drift risk with paths that read the socket outside `Recvfrom` (P2P framing, epoll, other threads), and this PR also covers cases #981 does not: datagram peek edge cases, P2P accept, accepted-socket mode preservation, and the blocking WAITALL short-send hang. If a queued-emulation layer is ever wanted, it can be layered on top of this later — but with the Winsock rejection handled here, the regression cases do not need it.
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/797#issuecomment-5971562521) Credited

Pull request closed

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