From e2984def2223fcdc1897fa51c891d3dd56a12684 Mon Sep 17 00:00:00 2001 From: Robii Aragon <55045932+RobiiAragon@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:21:49 -0800 Subject: [PATCH 1/2] host/net: opt-in nn::socket network mode on the host's own IPv4 sockets DM_NETWORK=lan sends each dm_sk_* call for a network descriptor to hle_net_backend.c, so every enum, plain-argument and C entry point follows without a hook of its own. Without it, main's offline local UDP/EventFd service answers every call unchanged. Network descriptors start at 64, above the service's EventFds, in one 1024-entry fd_set namespace; a mixed Poll/Select alternates the EventFd check with short host waits. The transport translates Horizon's sockaddr, Linux errno numbers, O_NONBLOCK and option numbers, keeps SO_NOSIGPIPE on every native socket, prepares guest output before the kernel's copyout, and ends a blocked call with EBADF when another thread closes its socket. nifm keeps its on-hold sequence, then reports the host interface. Name resolution, TLS, LDN and the online services stay offline. t_net covers the transport on loopback UDP and TCP, including under ASan, UBSan and TSan. --- dm/games/0100152000022000/README.md | 1 + dm/host/hle_net.c | 71 ++++- dm/host/hle_net.h | 6 +- dm/host/hle_net_backend.c | 423 +++++++++++++++++++++++++++ dm/host/hle_offline.c | 7 +- dm/host/net_socket.h | 27 ++ dm/host/tests/Makefile | 17 +- dm/host/tests/t_net.c | 174 +++++++++++ dm/host/tests/t_net_host_stub.c | 4 + dm/host/tests/t_server_environment.c | 3 + docs/agents/symptoms.md | 1 + docs/env_switches.tsv | 1 + docs/reference/services.md | 8 + 13 files changed, 722 insertions(+), 21 deletions(-) create mode 100644 dm/host/hle_net_backend.c create mode 100644 dm/host/net_socket.h create mode 100644 dm/host/tests/t_net.c create mode 100644 dm/host/tests/t_net_host_stub.c diff --git a/dm/games/0100152000022000/README.md b/dm/games/0100152000022000/README.md index 162506d5f2..c23921a49a 100644 --- a/dm/games/0100152000022000/README.md +++ b/dm/games/0100152000022000/README.md @@ -68,6 +68,7 @@ The game builds Mii heads from the console's MiiModel system data, starting at b - **A wired PDP Xbox 360 pad over USB (Mac, hardware retest pending):** macOS has no driver for third-party wired Xbox 360 pads (`0e6f:0301`), so the host reads them via the shared `IOUSBHost` reader: [Wired Xbox 360 controllers from other makers over USB](../../../docs/reference/services.md#wired-xbox-360-controllers-from-other-makers-over-usb). Reported in [PR #2436](https://github.com/seedds/nxnative/pull/2436) on 4.0.1 (Apple M5, macOS 27.2) alongside a Turtle Beach REACT-R (`10f5:7024`); hardware retest on the unified `IOUSBHost` path is pending. - **Sky-High Sundae's sky in red blocks (resolved, Mac):** the blue dome lost its depth test against the sunset panorama under it by one rounding step: [Depth on the far plane](../../../docs/reference/rendering.md#depth-on-the-far-plane). A depth bias with clamping on the course's four dome shaders removed the blocks in an on/off test of the same frame; the fix covers every vertex shader with z = w (a far value above the near one), and the course was checked in play on an M5 MacBook Air. - **Display sleep during controller play on the Mac (resolved, player-confirmed):** [Mac display sleep during controller play](../../../docs/reference/services.md#mac-display-sleep-during-controller-play). +- **LAN play on the host's sockets (`DM_NETWORK=lan`):** [Network mode: the game's sockets on the host's own](../../../docs/reference/services.md#network-mode-the-games-sockets-on-the-hosts-own). In NX Port Studio I completed a Mac–Switch LAN race on 3.0.5 (2026-10-31) with the transport this extracts; I have not run 4.0.1 or this branch in a LAN session. - **Resolved in the sanitizer audit:** [Unaligned command headers during layout probing](../../../docs/reference/audio.md#unaligned-command-headers-during-layout-probing), reproduced with the SDK 4 command-list fixture. - **Audio layout detection after incomplete startup lists (resolved):** [Incomplete startup lists must not select the command layout](../../../docs/reference/audio.md#incomplete-startup-lists-must-not-select-the-command-layout). diff --git a/dm/host/hle_net.c b/dm/host/hle_net.c index 305d8429ae..6e72332cb7 100644 --- a/dm/host/hle_net.c +++ b/dm/host/hle_net.c @@ -1,6 +1,8 @@ -// Network services stay offline. The BSD service additionally supplies process-local UDP and EventFd transports, which offline engines use for their own threads. +// Network services stay offline by default. The BSD service additionally supplies process-local UDP and EventFd transports, which offline engines use for their own threads. +// DM_NETWORK=lan (net_socket.h) puts the game's sockets on the host's own IPv4 TCP/UDP instead (hle_net_backend.c); EventFd stays this service's, and nifm reports the interface. #include "hle.h" #include "hle_net.h" +#include "net_socket.h" #include #include @@ -18,17 +20,24 @@ HLE_FORCE("_ZN2nn4nifm10InitializeEv", "connects to the nifm network management // queries, 2,000 IPCs on the Switch but 0.1 ms here, so it cancelled and submitted again forever (1.17 billion queries a minute, a host core). Its stamp, now_ns() | 1, also read // as settled at once whenever the next query came within the same 42 ns clock tick (30% of Hades' submissions) static _Atomic int g_nifm_hold; // queries the pending request still answers "on hold" (0 = none, or settled) -HLE_FORCE("_ZN2nn4nifm20SubmitNetworkRequestEv", "offline: the request is on hold for the first query, then settles as unavailable", void, h_nifm_Submit, void) { atomic_store(&g_nifm_hold, 1); } -HLE_FORCE("_ZN2nn4nifm20CancelNetworkRequestEv", "offline: drops the pending request", void, h_nifm_Cancel, void) { atomic_store(&g_nifm_hold, 0); } +static _Atomic int g_nifm_submitted; // a request is pending; in network mode it settles as accepted when the host has an interface +HLE_FORCE("_ZN2nn4nifm20SubmitNetworkRequestEv", "the request is on hold for the first query, then settles: unavailable offline, the interface's state in network mode", void, h_nifm_Submit, void) { atomic_store(&g_nifm_submitted, 1); atomic_store(&g_nifm_hold, 1); } +HLE_FORCE("_ZN2nn4nifm20CancelNetworkRequestEv", "drops the pending request", void, h_nifm_Cancel, void) { atomic_store(&g_nifm_submitted, 0); atomic_store(&g_nifm_hold, 0); } HLE_FORCE("_ZN2nn4nifm22IsNetworkRequestOnHoldEv", "offline: on hold for the first query after the submission", int, h_nifm_OnHold, void) { int h = atomic_load(&g_nifm_hold); while (h > 0 && !atomic_compare_exchange_weak(&g_nifm_hold, &h, h - 1)) {} return h > 0; } -HLE_FORCE("_ZN2nn4nifm18IsNetworkAvailableEv", "offline: the network is always unavailable", int, h_nifm_Available, void) { return 0; } +// Network mode answers from the host interface only once the submitted request has settled, so the on-hold sequence above stays the same in both modes +static int nifm_available(void) { return dm_net_enabled() && atomic_load(&g_nifm_submitted) && !atomic_load(&g_nifm_hold) && !dm_net_ipconfig(NULL, NULL); } +HLE_FORCE("_ZN2nn4nifm18IsNetworkAvailableEv", "offline: the network is always unavailable; network mode: the settled request and the host interface", int, h_nifm_Available, void) { return nifm_available(); } // Returns bool (`and w0, w0, #1`, Metroid Dread's sdk+0x336210): whether the system's network screen resolved the error -HLE_FORCE("_ZN2nn4nifm31HandleNetworkRequestErrorResultEv", "offline: not resolved, shows no system network screen", unsigned, h_nifm_HandleErr, void) { return 0; } -HLE_FORCE("_ZN2nn4nifm26GetCurrentPrimaryIpAddressEPNS_6socket6InAddrE", "offline: no IP", Result, h_nifm_GetIp, uint32_t *a) { if (a) *a = 0; return RES_FAIL; } +HLE_FORCE("_ZN2nn4nifm31HandleNetworkRequestErrorResultEv", "not resolved offline, shows no system network screen; network mode: resolved when available", unsigned, h_nifm_HandleErr, void) { return (unsigned)nifm_available(); } +HLE_FORCE("_ZN2nn4nifm26GetCurrentPrimaryIpAddressEPNS_6socket6InAddrE", "offline: no IP; network mode: the host interface's IPv4 address", Result, h_nifm_GetIp, uint32_t *a) { + if (a) *a = 0; + uint32_t ip; if (!a || dm_net_ipconfig(&ip, NULL)) return RES_FAIL; + *a = ip; return RES_OK; +} HLE_FORCE("_ZN2nn4nifm22GetCurrentProxySettingEPNS0_12ProxySettingE", "offline: no proxy setting", Result, h_nifm_GetProxy, void *p) { (void)p; return RES_FAIL; } HLE_FORCE("nnsslInitialize", "connects to the ssl service; the network library's global init needs it to succeed, offline creates no session (cut)", Result, h_ssl_Initialize, void) { return RES_OK; } HLE_FORCE("nnsslFinalize", "pairs with nnsslInitialize (cut)", Result, h_ssl_Finalize, void) { return RES_OK; } @@ -42,6 +51,9 @@ static __thread int t_skerr = SK_ENETDOWN; static int sk_error(int error) { t_skerr = error; return -1; } static int sk_fail(void) { return sk_error(SK_ENETDOWN); } int dm_sk_errno(void) { return t_skerr; } +void dm_sk_set_errno(int error) { t_skerr = error; } +// Network mode owns every descriptor from DM_NET_FD_BASE up; below it are this service's EventFd counters (and, offline, its local UDP sockets) +static int sk_net(int fd) { return dm_net_enabled() && dm_net_owns(fd); } #define SKF(m, cname, ...) HLE_FORCE(m, "local BSD descriptor service; remote networking unavailable", int, cname, __VA_ARGS__) void dm_guest_sleep_ns(int64_t ns); void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns); @@ -78,10 +90,12 @@ static int efd_create(uint64_t v, int flags) { pthread_mutex_unlock(&g_efd_m); return fd; } int dm_sk_socket(int family, int type, int protocol) { + if (dm_net_enabled()) return dm_net_socket(family, type, protocol); if (family != 2 || type != 2 || (protocol && protocol != 17)) return sk_fail(); dm_host_mutex_lock(&g_efd_m); int fd = sk_new_locked(SK_UDP); pthread_mutex_unlock(&g_efd_m); return fd; } int dm_sk_close(int fd) { + if (sk_net(fd)) return dm_net_close(fd); dm_host_mutex_lock(&g_efd_m); if (!sk_used(fd)) { pthread_mutex_unlock(&g_efd_m); return sk_fail(); } sk_packet *p = g_efd[fd].head; @@ -141,10 +155,12 @@ static int sk_bind_locked(int fd, uint32_t addr, uint16_t port) { g_efd[fd].addr = addr; g_efd[fd].port = port; return 0; } int dm_sk_bind(int fd, const void *a, unsigned n) { + if (sk_net(fd)) return dm_net_bind(fd, a, n); uint32_t addr; uint16_t port; if (sk_addr_read(a, n, &addr, &port)) return -1; dm_host_mutex_lock(&g_efd_m); int r = sk_udp_locked(fd) ? sk_bind_locked(fd, addr, port) : sk_error(SK_EBADF); pthread_mutex_unlock(&g_efd_m); return r; } int dm_sk_connect(int fd, const void *a, unsigned n) { + if (sk_net(fd)) return dm_net_connect(fd, a, n); uint32_t addr = 0; uint16_t port = 0; int disconnect = a && n >= 2 && ((const uint8_t *)a)[1] == 0; if (!disconnect && sk_addr_read(a, n, &addr, &port)) return -1; if (!disconnect && !port) return sk_error(SK_EINVAL); @@ -155,6 +171,7 @@ int dm_sk_connect(int fd, const void *a, unsigned n) { pthread_mutex_unlock(&g_efd_m); return r; } int dm_sk_name(int fd, void *a, unsigned *n, int peer) { + if (sk_net(fd)) return dm_net_name(fd, a, n, peer); if (!a || !n) return sk_error(SK_EINVAL); dm_host_mutex_lock(&g_efd_m); int r; if (!sk_udp_locked(fd)) r = sk_error(SK_EBADF); @@ -163,6 +180,7 @@ int dm_sk_name(int fd, void *a, unsigned *n, int peer) { pthread_mutex_unlock(&g_efd_m); return r; } int dm_sk_shutdown(int fd, int how) { + if (sk_net(fd)) return dm_net_shutdown(fd, how); dm_host_mutex_lock(&g_efd_m); int r = 0; if (!sk_udp_locked(fd)) r = sk_error(SK_EBADF); else if (how < 0 || how > 2) r = sk_error(SK_EINVAL); @@ -171,6 +189,7 @@ int dm_sk_shutdown(int fd, int how) { pthread_mutex_unlock(&g_efd_m); return r; } int dm_sk_fcntl(int fd, int cmd, int value) { + if (sk_net(fd)) return dm_net_fcntl(fd, cmd, value); dm_host_mutex_lock(&g_efd_m); int r = 0; if (!sk_used(fd)) r = sk_error(SK_EBADF); else if (cmd == 1) r = g_efd[fd].fdflags; @@ -181,6 +200,7 @@ int dm_sk_fcntl(int fd, int cmd, int value) { pthread_mutex_unlock(&g_efd_m); return r; } int dm_sk_setopt(int fd, int level, int option, const void *value, unsigned size) { + if (sk_net(fd)) return dm_net_sockopt(fd, level, option, (void *)value, &size, 1); if (!value) return sk_error(SK_EINVAL); dm_host_mutex_lock(&g_efd_m); int r = 0; if (!sk_udp_locked(fd)) r = sk_error(SK_EBADF); @@ -201,6 +221,7 @@ int dm_sk_setopt(int fd, int level, int option, const void *value, unsigned size pthread_mutex_unlock(&g_efd_m); return r; } int dm_sk_getopt(int fd, int level, int option, void *value, unsigned *size) { + if (sk_net(fd)) return dm_net_sockopt(fd, level, option, value, size, 0); if (!value || !size) return sk_error(SK_EINVAL); dm_host_mutex_lock(&g_efd_m); int r = 0, v = 0; if (!sk_udp_locked(fd)) r = sk_error(SK_EBADF); @@ -220,6 +241,7 @@ int dm_sk_getopt(int fd, int level, int option, void *value, unsigned *size) { pthread_mutex_unlock(&g_efd_m); return r; } long dm_sk_sendto(int fd, const void *data, unsigned long n, int flags, const void *a, unsigned al) { + if (sk_net(fd)) return dm_net_send(fd, data, n, flags, a, al); if ((!data && n) || n > SK_UDP_MAX) return sk_error(n > SK_UDP_MAX ? SK_EMSGSIZE : SK_EINVAL); if (flags & ~(SK_MSG_DONTWAIT | 4 | 0x20000)) return sk_error(SK_EOPNOTSUPP); uint32_t addr = 0; uint16_t port = 0; if (a && sk_addr_read(a, al, &addr, &port)) return -1; @@ -252,18 +274,21 @@ long dm_sk_sendto(int fd, const void *data, unsigned long n, int flags, const vo pthread_mutex_unlock(&g_efd_m); return r; } long dm_sk_read(int fd, void *data, unsigned long size) { + if (sk_net(fd)) return dm_net_recv(fd, data, size, 0, NULL, NULL); dm_host_mutex_lock(&g_efd_m); int event = efd_used(fd); pthread_mutex_unlock(&g_efd_m); if (!event) return dm_sk_recvfrom(fd, data, size, 0, NULL, NULL); if (!data || size < sizeof(uint64_t)) return sk_error(SK_EINVAL); uint64_t v; if (efd_read(fd, &v)) return -1; memcpy(data, &v, sizeof v); return sizeof v; } long dm_sk_write(int fd, const void *data, unsigned long size) { + if (sk_net(fd)) return dm_net_send(fd, data, size, 0, NULL, 0); dm_host_mutex_lock(&g_efd_m); int event = efd_used(fd); pthread_mutex_unlock(&g_efd_m); if (!event) return dm_sk_sendto(fd, data, size, 0, NULL, 0); if (!data || size < sizeof(uint64_t)) return sk_error(SK_EINVAL); uint64_t v; memcpy(&v, data, sizeof v); return efd_write(fd, v) ? -1 : (long)sizeof v; } long dm_sk_recvfrom(int fd, void *data, unsigned long n, int flags, void *a, unsigned *al) { + if (sk_net(fd)) return dm_net_recv(fd, data, n, flags, a, al); if ((!data && n) || (a && !al)) return sk_error(SK_EINVAL); if (flags & ~(SK_MSG_DONTWAIT | SK_MSG_PEEK)) return sk_error(SK_EOPNOTSUPP); dm_host_mutex_lock(&g_efd_m); long r = -1; @@ -300,7 +325,25 @@ static int efd_ready(sk_pollfd *p, uint64_t n, uint64_t open, const uint64_t gen } return ready; } +static int sk_poll_local(void *fds, uint64_t n, int ms); +// Network mode: network descriptors wait in the host's poll (hle_net_backend.c). A set that also holds this service's EventFds alternates a check of those with short +// host waits (SK_MIXED_MS), so either kind ends the wait; an endless wait returns after 100 ms, as the local one below does +enum { SK_MIXED_MS = 5 }; int dm_sk_poll(void *fds, uint64_t n, int ms) { + sk_pollfd *p = fds; int net = 0, local = 0; + if (dm_net_enabled() && (p || !n)) for (uint64_t i = 0; i < n; i++) { if (dm_net_owns(p[i].fd)) net = 1; else if (p[i].fd >= 0) local = 1; } + if (!net) return sk_poll_local(fds, n, ms); + int64_t limit = ms < 0 ? 100 : ms; uint64_t start = guest_ns(); + if (!local) { for (uint64_t i = 0; i < n; i++) p[i].revents = 0; return dm_net_poll(fds, n, (int)limit); } + for (;;) { + int ready = sk_poll_local(fds, n, 0); // clears every revents first, then sets the EventFds' + int64_t left = limit - (int64_t)((guest_ns() - start) / 1000000); + int more = dm_net_poll(fds, n, ready || left <= 0 ? 0 : (int)(left < SK_MIXED_MS ? left : SK_MIXED_MS)); + if (more < 0) return -1; + if (ready + more || left <= 0) return ready + more; + } +} +static int sk_poll_local(void *fds, uint64_t n, int ms) { sk_pollfd *p = fds; uint64_t open = 0, generation[EFD_MAX] = {0}; if (!p && n) return sk_error(SK_EINVAL); dm_host_mutex_lock(&g_efd_m); @@ -317,10 +360,11 @@ int dm_sk_poll(void *fds, uint64_t n, int ms) { } // fd_set is1024 bits; timeval is {i64 seconds, i64 microseconds}. Only this service's small descriptors can become ready. int dm_sk_select(int nfds, uint64_t *r, uint64_t *w, uint64_t *e, const int64_t *tv) { - uint64_t *sets[3] = {r, w, e}; static const int16_t ask[3] = {SK_POLLIN, SK_POLLOUT, 0}; sk_pollfd p[EFD_MAX]; int np = 0; + uint64_t *sets[3] = {r, w, e}; static const int16_t ask[3] = {SK_POLLIN, SK_POLLOUT, 0}; sk_pollfd p[DM_NET_FD_END]; int np = 0; if (nfds < 0 || (tv && (tv[0] < 0 || tv[1] < 0 || tv[1] >= 1000000))) return sk_error(SK_EINVAL); if (nfds > 1024) nfds = 1024; - for (int fd = 0; fd < nfds && fd < EFD_MAX; fd++) { int in = 0; int16_t ev = 0; + int net = dm_net_enabled(), limit = net ? DM_NET_FD_END : EFD_MAX; // network mode: its descriptors too + for (int fd = 0; fd < nfds && fd < limit; fd++) { int in = 0; int16_t ev = 0; for (int k = 0; k < 3; k++) if (sets[k] && sets[k][fd >> 6] >> (fd & 63) & 1) { in = 1; ev |= ask[k]; } if (in) p[np++] = (sk_pollfd){fd, ev, 0}; } @@ -331,16 +375,19 @@ int dm_sk_select(int nfds, uint64_t *r, uint64_t *w, uint64_t *e, const int64_t int n = 0; for (int i = 0; i < np; i++) { if (p[i].revents & SK_POLLNVAL) return sk_error(SK_EBADF); - if (p[i].revents & (SK_POLLIN | SK_POLLRDNORM) && r) { r[p[i].fd >> 6] |= 1ull << (p[i].fd & 63); n++; } - if (p[i].revents & SK_POLLOUT && w) { w[p[i].fd >> 6] |= 1ull << (p[i].fd & 63); n++; } + int16_t gone = net ? p[i].revents & (8 | 0x10) : 0; // a host socket's error or hangup makes a read or write return at once, so select reports it ready + if ((p[i].revents & (SK_POLLIN | SK_POLLRDNORM) || (gone && p[i].events & SK_POLLIN)) && r) { r[p[i].fd >> 6] |= 1ull << (p[i].fd & 63); n++; } + if ((p[i].revents & SK_POLLOUT || (gone && p[i].events & SK_POLLOUT)) && w) { w[p[i].fd >> 6] |= 1ull << (p[i].fd & 63); n++; } } return n; } SKF("_ZN2nn6socket6SocketENS0_6FamilyENS0_4TypeENS0_8ProtocolE", h_sk_Socket, int a, int b, int c) { return dm_sk_socket(a, b, c); } SKF("_ZN2nn6socket4BindEiPKNS0_8SockAddrEj", h_sk_Bind, int s, const void *a, unsigned n) { return dm_sk_bind(s, a, n); } SKF("_ZN2nn6socket7ConnectEiPKNS0_8SockAddrEj", h_sk_Connect, int s, const void *a, unsigned n) { return dm_sk_connect(s, a, n); } -SKF("_ZN2nn6socket6ListenEii", h_sk_Listen, int s, int n) { (void)s; (void)n; return sk_fail(); } -SKF("_ZN2nn6socket6AcceptEiPNS0_8SockAddrEPj", h_sk_Accept, int s, void *a, unsigned *n) { (void)s; (void)a; (void)n; return sk_fail(); } +int dm_sk_listen(int fd, int backlog) { return sk_net(fd) ? dm_net_listen(fd, backlog) : sk_fail(); } +int dm_sk_accept(int fd, void *a, unsigned *n) { return sk_net(fd) ? dm_net_accept(fd, a, n) : sk_fail(); } +SKF("_ZN2nn6socket6ListenEii", h_sk_Listen, int s, int n) { return dm_sk_listen(s, n); } +SKF("_ZN2nn6socket6AcceptEiPNS0_8SockAddrEPj", h_sk_Accept, int s, void *a, unsigned *n) { return dm_sk_accept(s, a, n); } SKF("_ZN2nn6socket5CloseEi", h_sk_Close, int s) { return dm_sk_close(s); } SKF("_ZN2nn6socket11GetPeerNameEiPNS0_8SockAddrEPj", h_sk_GetPeerName, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 1); } SKF("_ZN2nn6socket11GetSockNameEiPNS0_8SockAddrEPj", h_sk_GetSockName, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 0); } diff --git a/dm/host/hle_net.h b/dm/host/hle_net.h index 2a29d3980d..966a922962 100644 --- a/dm/host/hle_net.h +++ b/dm/host/hle_net.h @@ -1,4 +1,5 @@ -// Offline BSD descriptors: local UDP and EventFd share the service's small fd namespace. +// Offline BSD descriptors: local UDP and EventFd share the service's small fd namespace. In network mode (net_socket.h) every call below goes to the host's sockets +// for the descriptors that transport owns. #pragma once #include int dm_sk_socket(int family, int type, int protocol); @@ -16,4 +17,7 @@ long dm_sk_read(int fd, void *data, unsigned long size); long dm_sk_write(int fd, const void *data, unsigned long size); int dm_sk_poll(void *fds, uint64_t count, int milliseconds); int dm_sk_select(int nfds, uint64_t *read, uint64_t *write, uint64_t *except, const int64_t *timeout); +int dm_sk_listen(int fd, int backlog); // offline: -1, ENETDOWN +int dm_sk_accept(int fd, void *addr, unsigned *size); // offline: -1, ENETDOWN int dm_sk_errno(void); +void dm_sk_set_errno(int error); // the transport in hle_net_backend.c reports through the same per-thread value diff --git a/dm/host/hle_net_backend.c b/dm/host/hle_net_backend.c new file mode 100644 index 0000000000..17980eca3a --- /dev/null +++ b/dm/host/hle_net_backend.c @@ -0,0 +1,423 @@ +// Network-mode nn::socket transport: the guest's BSD socket calls on real Darwin IPv4 TCP/UDP sockets (net_socket.h). Off by default; DM_NETWORK=lan turns it on. +// ABI references: Atmosphere-NX socket_types.hpp / socket_errno.hpp; switchbrew/libnx socket.c. Horizon uses the BSD sockaddr (u8 length, u8 family), Linux errno numbers +// (nn::socket::Errno: EAGAIN 11, as Mario Kart 8 Deluxe's receive loop compares it), O_NONBLOCK 0x800, SOCK_NONBLOCK 0x20000000 and FreeBSD option numbers, some of which Darwin +// numbers differently (SO_NOSIGPIPE is 0x800 on Horizon, 0x1022 here). Guest structures are always copied field by field, never cast to Darwin's. +// Name resolution, TLS, LDN and the online services are not part of this transport: they keep hle_net.c's / hle_offline.c's offline answers. +#include "hle.h" +#include "hle_net.h" +#include "net_socket.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A blocking call waits in slices of this length, so a Close on another thread ends it with EBADF within one slice even when the socket gives no wakeup (UDP) +enum { NET_SLOTS = DM_NET_FD_END - DM_NET_FD_BASE, NX_NONBLOCK = 0x800, NX_SOCK_NONBLOCK = 0x20000000, NX_SOCK_CLOEXEC = 0x10000000, NET_SLICE_MS = 100 }; +enum { NX_MSG_OOB = 1, NX_MSG_PEEK = 2, NX_MSG_DONTROUTE = 4, NX_MSG_WAITALL = 0x40, NX_MSG_DONTWAIT = 0x80, NX_MSG_NOSIGNAL = 0x20000 }; +typedef struct { uint8_t len, family; uint16_t port; uint32_t address; uint8_t zero[8]; } nx_addr; +typedef struct { int64_t sec, usec; } nx_timeval; +typedef struct { int32_t fd; int16_t events, revents; } nx_pollfd; +_Static_assert(sizeof(nx_addr) == 16, "Horizon sockaddr_in"); +_Static_assert(sizeof(nx_pollfd) == 8, "Horizon pollfd"); + +// The native descriptor stays open while a guest slot is used. A call borrows a duplicate under the lock, so a Close on another thread never closes a descriptor that is in use, +// and the slot's generation tells a waiter that its socket was closed (or the slot reused) while it waited +typedef struct { int native, used, nonblock, type; uint64_t generation; int64_t send_ms, recv_ms; } net_slot; +typedef struct { int fd, slot, nonblock, type; uint64_t generation; int64_t send_ms, recv_ms; } net_ref; +static net_slot g_net[NET_SLOTS]; +static pthread_mutex_t g_net_lock = PTHREAD_MUTEX_INITIALIZER; + +static int g_net_on; +static pthread_once_t g_net_once = PTHREAD_ONCE_INIT; +static void net_read_mode(void) { const char *s = getenv("DM_NETWORK"); g_net_on = s && !strcmp(s, "lan"); } +int dm_net_enabled(void) { pthread_once(&g_net_once, net_read_mode); return g_net_on; } + +static int net_error(int e) { dm_sk_set_errno(e); return -1; } +static int net_errno(int e) { // Darwin's errno as Horizon's (Linux's) number + switch (e) { + case 0: return 0; + case EPERM: return 1; case ENOENT: return 2; case EINTR: return 4; case EIO: return 5; + case EBADF: return 9; case EAGAIN: return 11; case ENOMEM: return 12; case EACCES: return 13; + case EFAULT: return 14; case EBUSY: return 16; case EEXIST: return 17; case ENODEV: return 19; + case EINVAL: return 22; case ENFILE: return 23; case EMFILE: return 24; case EPIPE: return 32; + case ENAMETOOLONG: return 36; case ENOSYS: return 38; case EOVERFLOW: return 75; + case ENOTSOCK: return 88; case EDESTADDRREQ: return 89; case EMSGSIZE: return 90; + case EPROTOTYPE: return 91; case ENOPROTOOPT: return 92; case EPROTONOSUPPORT: return 93; + case ESOCKTNOSUPPORT: return 94; case EOPNOTSUPP: return 95; case EPFNOSUPPORT: return 96; + case EAFNOSUPPORT: return 97; case EADDRINUSE: return 98; case EADDRNOTAVAIL: return 99; + case ENETDOWN: return 100; case ENETUNREACH: return 101; case ENETRESET: return 102; + case ECONNABORTED: return 103; case ECONNRESET: return 104; case ENOBUFS: return 105; + case EISCONN: return 106; case ENOTCONN: return 107; case ESHUTDOWN: return 108; + case ETIMEDOUT: return 110; case ECONNREFUSED: return 111; case EHOSTDOWN: return 112; + case EHOSTUNREACH: return 113; case EALREADY: return 114; case EINPROGRESS: return 115; + case ECANCELED: return 125; default: return 5; + } +} +static int net_host_result(int result, int err) { return result < 0 ? net_error(net_errno(err)) : result; } +static uint64_t net_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000; } + +static int net_borrow(int guest, net_ref *r) { + if (!dm_net_owns(guest)) return net_error(9); + int slot = guest - DM_NET_FD_BASE; + dm_host_mutex_lock(&g_net_lock); + if (!g_net[slot].used) { pthread_mutex_unlock(&g_net_lock); return net_error(9); } + net_slot s = g_net[slot]; + int fd = fcntl(s.native, F_DUPFD_CLOEXEC, 0), err = errno; + pthread_mutex_unlock(&g_net_lock); + if (fd < 0) return net_error(net_errno(err)); + *r = (net_ref){fd, slot, s.nonblock, s.type, s.generation, s.send_ms, s.recv_ms}; return 0; +} +static int net_live(const net_ref *r) { + dm_host_mutex_lock(&g_net_lock); + int live = g_net[r->slot].used && g_net[r->slot].generation == r->generation; + pthread_mutex_unlock(&g_net_lock); return live; +} +// The native descriptor is always non-blocking: guest blocking calls wait here, in slices, with the guest core released (dm_thread_native_wait), as main's offline waits do. +// Every socket gets SO_NOSIGPIPE: Darwin has no MSG_NOSIGNAL, and a send to a peer that closed would otherwise raise SIGPIPE and end the process instead of returning EPIPE +static int net_register(int fd, int type, int nonblock) { + int one = 1; + if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0 || fcntl(fd, F_SETFD, FD_CLOEXEC) < 0 || setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one) < 0) { + int e = errno; close(fd); return net_error(net_errno(e)); + } + dm_host_mutex_lock(&g_net_lock); + int i = 0; while (i < NET_SLOTS && g_net[i].used) i++; + if (i < NET_SLOTS) g_net[i] = (net_slot){fd, 1, nonblock, type, g_net[i].generation + 1, -1, -1}; + pthread_mutex_unlock(&g_net_lock); + if (i == NET_SLOTS) { close(fd); return net_error(24); } // EMFILE + return DM_NET_FD_BASE + i; +} +static int net_wait(const net_ref *r, short events, int64_t timeout, uint64_t start) { + for (;;) { + if (!net_live(r)) return net_error(9); + int slice = NET_SLICE_MS; + if (timeout >= 0) { + uint64_t elapsed = net_ms() - start; + if (elapsed >= (uint64_t)timeout) return net_error(11); + if ((uint64_t)slice > (uint64_t)timeout - elapsed) slice = (int)((uint64_t)timeout - elapsed); + } + struct pollfd p = {.fd = r->fd, .events = events}; + dm_thread_native_wait(1); int count = poll(&p, 1, slice), err = errno; dm_thread_native_wait(0); + if (count < 0 && err == EINTR) continue; // the host's pause and lifecycle signals are not the guest's interrupts + if (count < 0) return net_error(net_errno(err)); + if (!net_live(r)) return net_error(9); + if (count) return 0; + } +} + +static int net_addr_in(const void *p, unsigned n, struct sockaddr_in *out) { + if (!p) return net_error(14); + if (n < sizeof(nx_addr)) return net_error(22); + nx_addr a; memcpy(&a, p, sizeof a); + if (a.family != 2) return net_error(97); // EAFNOSUPPORT + if (a.len && a.len != sizeof a) return net_error(22); // hand-written game code may leave sin_len zero + memset(out, 0, sizeof *out); out->sin_len = sizeof *out; out->sin_family = AF_INET; + out->sin_port = a.port; out->sin_addr.s_addr = a.address; return 0; +} +// Copies at most the caller's capacity and returns the full length, as BSD does for a short buffer +static void net_addr_out(void *p, unsigned *n, const struct sockaddr_in *in) { + if (!p || !n) return; + nx_addr a = {.len = sizeof a, .family = 2, .port = in->sin_port, .address = in->sin_addr.s_addr}; + unsigned count = *n < sizeof a ? *n : (unsigned)sizeof a; memcpy(p, &a, count); *n = sizeof a; +} + +int dm_net_socket(int family, int type, int protocol) { + if (family != 2) return net_error(97); + unsigned flags = (unsigned)type & ~0xfu; int base = type & 0xf; + if (flags & ~(unsigned)(NX_SOCK_NONBLOCK | NX_SOCK_CLOEXEC)) return net_error(22); + if (base != 1 && base != 2) return net_error(94); // ESOCKTNOSUPPORT: SOCK_STREAM and SOCK_DGRAM only + if (protocol && protocol != (base == 1 ? 6 : 17)) return net_error(93); + int fd = socket(AF_INET, base == 1 ? SOCK_STREAM : SOCK_DGRAM, protocol), err = errno; + return fd < 0 ? net_error(net_errno(err)) : net_register(fd, base, !!(flags & NX_SOCK_NONBLOCK)); +} +int dm_net_close(int guest) { + if (!dm_net_owns(guest)) return net_error(9); + int slot = guest - DM_NET_FD_BASE; + dm_host_mutex_lock(&g_net_lock); + if (!g_net[slot].used) { pthread_mutex_unlock(&g_net_lock); return net_error(9); } + int fd = g_net[slot].native; g_net[slot].used = 0; + pthread_mutex_unlock(&g_net_lock); + // shutdown reaches the socket under every duplicate: a TCP waiter on another thread wakes now rather than at its next slice + shutdown(fd, SHUT_RDWR); int result = close(fd), err = errno; + return net_host_result(result, err); +} +int dm_net_bind(int guest, const void *addr, unsigned len) { + struct sockaddr_in a; if (net_addr_in(addr, len, &a)) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + int result = bind(r.fd, (struct sockaddr *)&a, sizeof a), err = errno; close(r.fd); + return net_host_result(result, err); +} +int dm_net_connect(int guest, const void *addr, unsigned len) { + struct sockaddr_in a; if (net_addr_in(addr, len, &a)) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + uint64_t start = net_ms(); int result = connect(r.fd, (struct sockaddr *)&a, sizeof a), err = errno; + if (result < 0 && err == EINPROGRESS && !r.nonblock) { // a blocking connect: wait for the handshake, then report its own result + result = net_wait(&r, POLLOUT, r.send_ms, start); + if (!result) { + socklen_t n = sizeof err; if (getsockopt(r.fd, SOL_SOCKET, SO_ERROR, &err, &n) < 0) err = errno; + if (err) result = net_error(net_errno(err)); + } + } else result = net_host_result(result, err); + close(r.fd); return result; +} +int dm_net_listen(int guest, int backlog) { + net_ref r; if (net_borrow(guest, &r)) return -1; + int result = listen(r.fd, backlog), err = errno; close(r.fd); return net_host_result(result, err); +} +int dm_net_accept(int guest, void *addr, unsigned *len) { + if (addr && !len) return net_error(14); + net_ref r; if (net_borrow(guest, &r)) return -1; + uint64_t start = net_ms(); int fd; struct sockaddr_in a; + for (;;) { + socklen_t n = sizeof a; fd = accept(r.fd, (struct sockaddr *)&a, &n); int err = errno; + if (fd >= 0) break; + if (err != EAGAIN || r.nonblock) { net_error(net_errno(err)); break; } + if (net_wait(&r, POLLIN, r.recv_ms, start)) break; + } + close(r.fd); + if (fd < 0) return -1; + int result = net_register(fd, 1, r.nonblock); // FreeBSD's accept (Horizon's bsd service): the new socket inherits the listener's O_NONBLOCK + if (result >= 0) net_addr_out(addr, len, &a); + return result; +} +int dm_net_name(int guest, void *addr, unsigned *len, int peer) { + if (!addr || !len) return net_error(14); + net_ref r; if (net_borrow(guest, &r)) return -1; + struct sockaddr_in a; socklen_t n = sizeof a; + int result = peer ? getpeername(r.fd, (struct sockaddr *)&a, &n) : getsockname(r.fd, (struct sockaddr *)&a, &n), err = errno; close(r.fd); + if (result >= 0) net_addr_out(addr, len, &a); + return net_host_result(result, err); +} +int dm_net_shutdown(int guest, int how) { + if (how < 0 || how > 2) return net_error(22); + net_ref r; if (net_borrow(guest, &r)) return -1; + static const int methods[] = {SHUT_RD, SHUT_WR, SHUT_RDWR}; + int result = shutdown(r.fd, methods[how]), err = errno; close(r.fd); return net_host_result(result, err); +} +// Commands as in main's offline service: 1 F_GETFD, 2 F_SETFD, 3 F_GETFL, 4 F_SETFL. Only O_NONBLOCK is a status flag here; the access-mode bits a caller carries over +// from F_GETFL (NEX passes O_RDWR | O_NONBLOCK, 0x802) are accepted and ignored +int dm_net_fcntl(int guest, int cmd, int value) { + net_ref r; if (net_borrow(guest, &r)) return -1; + close(r.fd); + if (cmd == 1) return 1; // FD_CLOEXEC + if (cmd == 2) return 0; + if (cmd == 3) return r.nonblock ? NX_NONBLOCK | 2 : 2; // O_RDWR + if (cmd != 4) return net_error(22); + if ((unsigned)value & ~(unsigned)(NX_NONBLOCK | 3)) return net_error(22); + dm_host_mutex_lock(&g_net_lock); + int live = g_net[r.slot].used && g_net[r.slot].generation == r.generation; + if (live) g_net[r.slot].nonblock = !!(value & NX_NONBLOCK); + pthread_mutex_unlock(&g_net_lock); return live ? 0 : net_error(9); +} +static int net_message_flags(int flags, int sending) { + if ((unsigned)flags & ~(unsigned)(NX_MSG_OOB | NX_MSG_PEEK | NX_MSG_DONTROUTE | NX_MSG_WAITALL | NX_MSG_DONTWAIT | (sending ? NX_MSG_NOSIGNAL : 0))) return net_error(95); + if (sending && (flags & (NX_MSG_PEEK | NX_MSG_WAITALL))) return net_error(95); + if ((flags & NX_MSG_PEEK) && (flags & NX_MSG_WAITALL)) return net_error(95); + int out = 0; + if (flags & NX_MSG_OOB) out |= MSG_OOB; + if (flags & NX_MSG_PEEK) out |= MSG_PEEK; + if (flags & NX_MSG_DONTROUTE) out |= MSG_DONTROUTE; + return out; // DONTWAIT, WAITALL and blocking are handled around the non-blocking native call; NOSIGNAL always holds (SO_NOSIGPIPE) +} +long dm_net_recv(int guest, void *buf, unsigned long len, int flags, void *addr, unsigned *addrlen) { + if ((!buf && len) || (addr && !addrlen)) return net_error(14); + if (len > SSIZE_MAX) return net_error(22); + int hostflags = net_message_flags(flags, 0); if (hostflags < 0) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + uint64_t start = net_ms(); long result = -1; size_t total = 0; struct sockaddr_in a; + for (;;) { + // The kernel's copyout into a write-protected guest page fails with EFAULT instead of reaching the dirty-page fault hook (crash.c), so prepare the span first, + // again after every wait: the renderer may protect it again meanwhile + dm_guest_write_prepare(buf ? (char *)buf + total : NULL, len - total); + socklen_t n = sizeof a; + ssize_t got = recvfrom(r.fd, buf ? (char *)buf + total : NULL, len - total, hostflags, addr ? (struct sockaddr *)&a : NULL, addr ? &n : NULL); int err = errno; + if (got >= 0) { + total += (size_t)got; result = (long)total; + if (addr) net_addr_out(addr, addrlen, &a); + if (!got || r.type != 1 || !(flags & NX_MSG_WAITALL) || r.nonblock || (flags & NX_MSG_DONTWAIT) || total == len) break; + continue; + } + if (err != EAGAIN || r.nonblock || (flags & NX_MSG_DONTWAIT)) { if (!total) result = net_error(net_errno(err)); break; } + if (net_wait(&r, POLLIN, r.recv_ms, start)) { if (!total) result = -1; break; } + } + close(r.fd); return result; +} +long dm_net_send(int guest, const void *buf, unsigned long len, int flags, const void *addr, unsigned addrlen) { + if (!buf && len) return net_error(14); + if (len > SSIZE_MAX) return net_error(22); + struct sockaddr_in a; if (addr && net_addr_in(addr, addrlen, &a)) return -1; + int hostflags = net_message_flags(flags, 1); if (hostflags < 0) return -1; + net_ref r; if (net_borrow(guest, &r)) return -1; + uint64_t start = net_ms(); long result; + for (;;) { + result = addr ? sendto(r.fd, buf, len, hostflags, (struct sockaddr *)&a, sizeof a) : send(r.fd, buf, len, hostflags); int err = errno; + if (result >= 0) break; + if (err != EAGAIN || r.nonblock || (flags & NX_MSG_DONTWAIT)) { result = net_error(net_errno(err)); break; } + if (net_wait(&r, POLLOUT, r.send_ms, start)) { result = -1; break; } + } + close(r.fd); return result; +} + +// Horizon's (FreeBSD's) level and option numbers to Darwin's. Unlisted options fail with ENOPROTOOPT rather than reach Darwin under a number that means something else there +static int net_option(int level, int option, int *hostlevel, int *hostoption, unsigned *size) { + *size = sizeof(int); + if (level == 0xffff) { + *hostlevel = SOL_SOCKET; + switch (option) { + case 1: *hostoption = SO_DEBUG; break; case 2: *hostoption = SO_ACCEPTCONN; break; + case 4: *hostoption = SO_REUSEADDR; break; case 8: *hostoption = SO_KEEPALIVE; break; + case 16: *hostoption = SO_DONTROUTE; break; case 32: *hostoption = SO_BROADCAST; break; + case 128: *hostoption = SO_LINGER; *size = sizeof(struct linger); break; + case 256: *hostoption = SO_OOBINLINE; break; case 512: *hostoption = SO_REUSEPORT; break; + case 0x800: *hostoption = SO_NOSIGPIPE; break; + case 0x1001: *hostoption = SO_SNDBUF; break; case 0x1002: *hostoption = SO_RCVBUF; break; + case 0x1003: *hostoption = SO_SNDLOWAT; break; case 0x1004: *hostoption = SO_RCVLOWAT; break; + case 0x1007: *hostoption = SO_ERROR; break; case 0x1008: *hostoption = SO_TYPE; break; + default: return net_error(92); + } + } else if (level == 6) { + *hostlevel = IPPROTO_TCP; + if (option == 1) *hostoption = TCP_NODELAY; + else if (option == 2) *hostoption = TCP_MAXSEG; + else return net_error(92); + } else if (level == 0) { + *hostlevel = IPPROTO_IP; + switch (option) { + case 3: *hostoption = IP_TOS; break; case 4: *hostoption = IP_TTL; break; + case 9: *hostoption = IP_MULTICAST_IF; *size = 4; break; + case 10: *hostoption = IP_MULTICAST_TTL; *size = 1; break; + case 11: *hostoption = IP_MULTICAST_LOOP; *size = 1; break; + case 12: *hostoption = IP_ADD_MEMBERSHIP; *size = 8; break; + case 13: *hostoption = IP_DROP_MEMBERSHIP; *size = 8; break; + default: return net_error(92); + } + } else return net_error(92); + return 0; +} +int dm_net_sockopt(int guest, int level, int option, void *value, unsigned *len, int set) { + if (!value || !len) return net_error(14); + net_ref r; if (net_borrow(guest, &r)) return -1; + if (level == 0xffff && (option == 0x1005 || option == 0x1006)) { + // SO_SNDTIMEO / SO_RCVTIMEO bound this transport's own waits (the native socket never blocks). Horizon's service takes a u32 of milliseconds; the SDK also passes + // its 16-byte TimeVal. Zero means no timeout + int64_t ms; + if (set) { + if (*len == 4) { uint32_t v; memcpy(&v, value, 4); ms = v ? (int64_t)v : -1; } + else if (*len == sizeof(nx_timeval)) { + nx_timeval v; memcpy(&v, value, sizeof v); + if (v.sec < 0 || v.usec < 0 || v.usec >= 1000000 || v.sec > INT_MAX / 1000) { close(r.fd); return net_error(22); } + ms = v.sec * 1000 + (v.usec + 999) / 1000; if (!ms) ms = -1; + } else { close(r.fd); return net_error(22); } + dm_host_mutex_lock(&g_net_lock); + int live = g_net[r.slot].used && g_net[r.slot].generation == r.generation; + if (live) { if (option == 0x1005) g_net[r.slot].send_ms = ms; else g_net[r.slot].recv_ms = ms; } + pthread_mutex_unlock(&g_net_lock); close(r.fd); return live ? 0 : net_error(9); + } + ms = option == 0x1005 ? r.send_ms : r.recv_ms; if (ms < 0) ms = 0; + if (*len >= sizeof(nx_timeval)) { nx_timeval v = {ms / 1000, ms % 1000 * 1000}; memcpy(value, &v, sizeof v); *len = sizeof v; } + else if (*len >= 4) { uint32_t v = (uint32_t)ms; memcpy(value, &v, 4); *len = 4; } + else { close(r.fd); return net_error(22); } + close(r.fd); return 0; + } + int hl, ho; unsigned size; + if (net_option(level, option, &hl, &ho, &size)) { close(r.fd); return -1; } + if (set && level == 0xffff && (option == 2 || option == 0x1007 || option == 0x1008)) { close(r.fd); return net_error(92); } // read-only + if (*len < size || (set && *len != size)) { close(r.fd); return net_error(22); } + // The transport keeps SO_NOSIGPIPE on: a guest that clears it gets EPIPE as Horizon gives, not a host signal that ends the process + int one = 1; void *hostvalue = level == 0xffff && option == 0x800 ? &one : value; + socklen_t n = size; + if (!set) dm_guest_write_prepare(value, n); // getsockopt's copyout is the kernel's too + int result = set ? setsockopt(r.fd, hl, ho, hostvalue, n) : getsockopt(r.fd, hl, ho, value, &n), err = errno; + if (!set && result >= 0) { + *len = n; + if (level == 0xffff && option == 0x1007 && n == 4) { int e; memcpy(&e, value, 4); e = net_errno(e); memcpy(value, &e, 4); } // SO_ERROR is an errno too + if (level == 0xffff && option == 0x1008 && n == 4) { int t; memcpy(&t, value, 4); t = t == SOCK_STREAM ? 1 : t == SOCK_DGRAM ? 2 : t; memcpy(value, &t, 4); } + } + close(r.fd); return net_host_result(result, err); +} + +// Horizon's poll bits: POLLIN 1, PRI 2, OUT 4, ERR 8, HUP 0x10, NVAL 0x20, RDNORM 0x40, RDBAND 0x80, WRBAND 0x100 (WRNORM = OUT) +static short net_poll_events(uint16_t e) { + short h = 0; + if (e & 1) h |= POLLIN; if (e & 2) h |= POLLPRI; if (e & 4) h |= POLLOUT; + if (e & 0x40) h |= POLLRDNORM; if (e & 0x80) h |= POLLRDBAND; if (e & 0x100) h |= POLLWRBAND; + return h; +} +static int16_t net_poll_revents(short h) { + int16_t e = 0; + if (h & POLLIN) e |= 1; if (h & POLLPRI) e |= 2; if (h & POLLOUT) e |= 4; + if (h & POLLERR) e |= 8; if (h & POLLHUP) e |= 0x10; if (h & POLLNVAL) e |= 0x20; + if (h & POLLRDNORM) e |= 0x40; if (h & POLLRDBAND) e |= 0x80; if (h & POLLWRBAND) e |= 0x100; + return e; +} +int dm_net_poll(void *fds, uint64_t count, int timeout_ms) { + if (count > DM_NET_FD_END) return net_error(22); + if (count && !fds) return net_error(14); + nx_pollfd *guest = fds; size_t cap = count ? (size_t)count : 1; + struct pollfd *host = calloc(cap, sizeof *host); net_ref *refs = calloc(cap, sizeof *refs); + if (!host || !refs) { free(host); free(refs); return net_error(12); } + int result = 0, invalid = 0; + for (uint64_t i = 0; i < count; i++) { + // The game's own array: snapshot fd and events once, so a concurrent edit cannot change which descriptor a borrowed duplicate stands for + refs[i].fd = host[i].fd = -1; + int fd = guest[i].fd; uint16_t events = (uint16_t)guest[i].events; + if (!dm_net_owns(fd)) continue; + guest[i].revents = 0; + if (net_borrow(fd, &refs[i])) { refs[i].fd = -1; guest[i].revents = 0x20; invalid++; continue; } // POLLNVAL + host[i].fd = refs[i].fd; host[i].events = net_poll_events(events); + } + uint64_t start = net_ms(); + for (;;) { + int wait = invalid ? 0 : NET_SLICE_MS; + if (timeout_ms >= 0) { uint64_t elapsed = net_ms() - start, left = elapsed < (uint64_t)timeout_ms ? (uint64_t)timeout_ms - elapsed : 0; if ((uint64_t)wait > left) wait = (int)left; } + dm_thread_native_wait(1); int ready = poll(host, (nfds_t)count, wait), err = errno; dm_thread_native_wait(0); + if (ready < 0 && err == EINTR) continue; + if (ready < 0) { result = net_error(net_errno(err)); break; } + result = invalid; + for (uint64_t i = 0; i < count; i++) if (refs[i].fd >= 0) { + int16_t revents = net_live(&refs[i]) ? net_poll_revents(host[i].revents) : 0x20; // closed during the wait + guest[i].revents = revents; if (revents) result++; + } + if (result || timeout_ms == 0 || (timeout_ms > 0 && net_ms() - start >= (uint64_t)timeout_ms)) break; + } + for (uint64_t i = 0; i < count; i++) if (refs[i].fd >= 0) close(refs[i].fd); + free(host); free(refs); return result; +} + +// Read again at most once a second: games ask nifm in loops (Hades queries about once a millisecond), and getifaddrs walks every interface +static pthread_mutex_t g_ip_lock = PTHREAD_MUTEX_INITIALIZER; +static uint64_t g_ip_at; static int g_ip_found = -1; static uint32_t g_ip_address, g_ip_mask; +static int net_ip_scan(uint32_t *address, uint32_t *mask) { + struct ifaddrs *list = NULL; if (getifaddrs(&list)) return -1; + int found = -1; + for (struct ifaddrs *p = list; p; p = p->ifa_next) { + unsigned need = IFF_UP | IFF_RUNNING | IFF_BROADCAST; + if (!p->ifa_addr || p->ifa_addr->sa_family != AF_INET || (p->ifa_flags & need) != need || (p->ifa_flags & (IFF_LOOPBACK | IFF_POINTOPOINT))) continue; + *address = ((struct sockaddr_in *)p->ifa_addr)->sin_addr.s_addr; + *mask = p->ifa_netmask && p->ifa_netmask->sa_family == AF_INET ? ((struct sockaddr_in *)p->ifa_netmask)->sin_addr.s_addr : 0; + found = 0; break; + } + freeifaddrs(list); return found; +} +int dm_net_ipconfig(uint32_t *address, uint32_t *mask) { + if (address) *address = 0; + if (mask) *mask = 0; + if (!dm_net_enabled()) return -1; + dm_host_mutex_lock(&g_ip_lock); + uint64_t now = net_ms(); + if (!g_ip_at || now - g_ip_at >= 1000) { g_ip_address = g_ip_mask = 0; g_ip_found = net_ip_scan(&g_ip_address, &g_ip_mask); g_ip_at = now ? now : 1; } + int found = g_ip_found; + if (!found && address) *address = g_ip_address; + if (!found && mask) *mask = g_ip_mask; + pthread_mutex_unlock(&g_ip_lock); return found; +} diff --git a/dm/host/hle_offline.c b/dm/host/hle_offline.c index d5da34e9c1..aeb3c77d94 100644 --- a/dm/host/hle_offline.c +++ b/dm/host/hle_offline.c @@ -3,6 +3,7 @@ // Return convention as in hle_friends.c: Result returns RES_FAIL ("saved / submitted" kinds return RES_OK so the game does not retry); bool returns false; events get a bound SystemEvent that never fires. #include "hle.h" #include "hle_net.h" +#include "net_socket.h" static _Alignas(16) uint8_t g_ev_ldn[0x100]; @@ -93,7 +94,7 @@ HLE_FORCE("_ZN2nn6socket12FreeAddrInfoEP8addrinfo", "pairs with GetAddrInfo (cut HLE_FORCE("_ZN2nn6socket11GAIStrErrorENS0_7AiErrnoE", "resolver error text", const char *, h_sk_GaiStr, int e) { (void)e; return "network unavailable"; } // SDK 11's overloads with plain sockaddr / int arguments (Big Brain Academy: Brain vs. Brain, through Pia) HLE_FORCE("_ZN2nn6socket7ConnectEiPK8sockaddrj", "local UDP (offline BSD service)", int, h_sk_Connect2, int s, const void *a, unsigned n) { return dm_sk_connect(s, a, n); } -HLE_FORCE("_ZN2nn6socket6AcceptEiP8sockaddrPj", "offline (cut)", int, h_sk_Accept2, int s, void *a, unsigned *n) { (void)s; (void)a; (void)n; return -1; } +HLE_FORCE("_ZN2nn6socket6AcceptEiP8sockaddrPj", "offline (cut); network mode: the host's TCP accept", int, h_sk_Accept2, int s, void *a, unsigned *n) { return dm_net_enabled() ? dm_sk_accept(s, a, n) : -1; } HLE_FORCE("_ZN2nn6socket11GetSockNameEiP8sockaddrPj", "local UDP (offline BSD service)", int, h_sk_GetSockName2, int s, void *a, unsigned *n) { return dm_sk_name(s, a, n, 0); } HLE_FORCE("_ZN2nn6socket10GetSockOptEiiiPvPj", "local UDP (offline BSD service)", int, h_sk_GetSockOpt2, int s, int l, int o, void *v, unsigned *n) { return dm_sk_getopt(s, l, o, v, n); } HLE_FORCE("_ZN2nn6socket10SetSockOptEiiiPKvj", "local UDP (offline BSD service)", int, h_sk_SetSockOpt2, int s, int l, int o, const void *v, unsigned n) { return dm_sk_setopt(s, l, o, v, n); } @@ -224,8 +225,8 @@ HLE_FORCE("_ZN2nn3web11ShowWebPageEPNS0_18WebPageReturnValueERKNS0_14ShowWebPage // Octopath Traveler 0 imports the offline HTML page applet too (pages shipped in the game's HTML document NCA, which the host does not extract) // ---------- C interface (nnsocket* / nnssl*): offline as well. The arguments are all in registers and the host does not look at them ---------- -HLE_FORCE("nnsocketAccept", "offline (cut)", int, h_c_sk_Accept, void) { return -1; } -HLE_FORCE("nnsocketListen", "offline (cut)", int, h_c_sk_Listen, void) { return -1; } +HLE_FORCE("nnsocketAccept", "offline (cut); network mode: the host's TCP accept", int, h_c_sk_Accept, int s, void *a, unsigned *n) { return dm_net_enabled() ? dm_sk_accept(s, a, n) : -1; } +HLE_FORCE("nnsocketListen", "offline (cut); network mode: the host's TCP listen", int, h_c_sk_Listen, int s, int n) { return dm_net_enabled() ? dm_sk_listen(s, n) : -1; } HLE_FORCE("nnsocketRecvMsg", "offline (cut)", int, h_c_sk_RecvMsg, void) { return -1; } HLE_FORCE("nnsocketSendMsg", "offline (cut)", int, h_c_sk_SendMsg, void) { return -1; } HLE_FORCE("nnsocketShutdown", "local UDP (offline BSD service)", int, h_c_sk_Shutdown, int s, int h) { return dm_sk_shutdown(s, h); } diff --git a/dm/host/net_socket.h b/dm/host/net_socket.h new file mode 100644 index 0000000000..c1c3e40ab6 --- /dev/null +++ b/dm/host/net_socket.h @@ -0,0 +1,27 @@ +// Network-mode nn::socket transport (hle_net_backend.c): real Darwin IPv4 TCP/UDP sockets behind the guest's BSD ABI. +// Off by default. DM_NETWORK=lan turns it on; with it off, hle_net.c's offline local UDP/EventFd service answers every call exactly as before. +// The guest's descriptors here start at DM_NET_FD_BASE, above the offline service's EventFd range (0..63), so both share one fd_set namespace. +#pragma once +#include + +enum { DM_NET_FD_BASE = 64, DM_NET_FD_END = 1024 }; // fd_set holds 1024 descriptors +int dm_net_enabled(void); // DM_NETWORK=lan, read once +static inline int dm_net_owns(int fd) { return fd >= DM_NET_FD_BASE && fd < DM_NET_FD_END; } + +// Each call sets the guest's last socket error (Horizon's Linux errno numbers) through dm_sk_set_errno on failure. +int dm_net_socket(int family, int type, int protocol); +int dm_net_close(int fd); +int dm_net_bind(int fd, const void *addr, unsigned len); +int dm_net_connect(int fd, const void *addr, unsigned len); +int dm_net_listen(int fd, int backlog); +int dm_net_accept(int fd, void *addr, unsigned *len); +int dm_net_name(int fd, void *addr, unsigned *len, int peer); +int dm_net_shutdown(int fd, int how); +int dm_net_fcntl(int fd, int cmd, int value); +int dm_net_sockopt(int fd, int level, int option, void *value, unsigned *len, int set); +long dm_net_recv(int fd, void *buf, unsigned long len, int flags, void *addr, unsigned *addrlen); +long dm_net_send(int fd, const void *buf, unsigned long len, int flags, const void *addr, unsigned addrlen); +// Readiness of network descriptors only: entries outside this transport's range are left untouched (revents 0); the caller merges offline ones +int dm_net_poll(void *fds, uint64_t count, int timeout_ms); +// nifm: the IPv4 address and mask of the first up, running, broadcast-capable non-loopback interface. 0 on success +int dm_net_ipconfig(uint32_t *address, uint32_t *mask); diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile index 7f6aa7f723..055172d851 100644 --- a/dm/host/tests/Makefile +++ b/dm/host/tests/Makefile @@ -54,6 +54,7 @@ run: $(B)/t_mii $(B)/t_net_eventfd $(B)/t_language $(B)/t_motion $(B)/t_heap_siz $(B)/t_pctl $(B)/t_net_eventfd $(B)/t_net_loopback + $(B)/t_net $(B)/t_sf $(B)/t_audren_sv $(B)/t_time @@ -288,11 +289,16 @@ $(B)/t_crash_diag: t_crash_diag.m t_altstack_stub.c ../crash.c ../memstat.m ../d $(CLANG) -O1 -fobjc-arc -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_crash_diag.m t_altstack_stub.c ../crash.c ../memstat.m -framework Foundation -framework Metal $(B)/t_memstat: t_memstat.m ../memstat.m ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -fobjc-arc -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_memstat.m ../memstat.m -framework Foundation -framework Metal -$(B)/t_net_eventfd: t_net_eventfd.c ../hle_net.c ../hle_net.h ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_eventfd.c +NET_SRC = ../hle_net.c ../hle_net.h ../hle_net_backend.c ../net_socket.h ../hle.h ../dm.h $(GAME_H) +$(B)/t_net_eventfd: t_net_eventfd.c t_net_host_stub.c $(NET_SRC) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_eventfd.c ../hle_net_backend.c t_net_host_stub.c run: $(B)/t_net_loopback -$(B)/t_net_loopback: t_net_loopback.c ../hle_net.c ../hle_net.h ../hle.h ../dm.h $(GAME_H) | $(B) - $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_loopback.c +$(B)/t_net_loopback: t_net_loopback.c t_net_host_stub.c $(NET_SRC) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net_loopback.c ../hle_net_backend.c t_net_host_stub.c +# Network mode (DM_NETWORK=lan): the guest's sockets on real loopback host sockets +run: $(B)/t_net +$(B)/t_net: t_net.c $(NET_SRC) | $(B) + $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function $(if $(findstring -fsanitize,$(SAN)),,-fsanitize=address,undefined) -I.. $(GINC) -o $@ t_net.c ../hle_net_backend.c $(B)/t_pctl: t_pctl.c ../hle_misc.c ../hle.h ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_pctl.c @@ -531,7 +537,7 @@ asan: @$(call san_fresh,$(B)/asan,$(ASAN_FLAGS)) $(ASAN_ENV) $(MAKE) B=$(B)/asan SAN="$(ASAN_FLAGS)" run TSAN_T = t_audio t_audio_stats t_audio_device t_thread_leak t_oe t_fs_commit_list t_fs_case t_save_sync t_condvar t_condvar_old t_preempt t_system_event t_notify_sched t_handoff_wait t_altstack t_sync_wait t_ue_heap_span -TSAN_T += t_net_eventfd t_net_loopback t_account +TSAN_T += t_net_eventfd t_net_loopback t_net t_account tsan-threads: @$(call san_fresh,$(B)/tsan,$(TSAN_FLAGS)) $(TSAN_ENV) $(MAKE) B=$(B)/tsan SAN="$(TSAN_FLAGS)" tsan-threads-run @@ -539,6 +545,7 @@ tsan-threads-run: $(addprefix $(B)/,$(TSAN_T)) $(B)/t_account $(B)/t_net_eventfd $(B)/t_net_loopback + $(B)/t_net $(B)/t_audio $(B)/t_audio_stats $(B)/t_audio_device diff --git a/dm/host/tests/t_net.c b/dm/host/tests/t_net.c new file mode 100644 index 0000000000..032b1fae29 --- /dev/null +++ b/dm/host/tests/t_net.c @@ -0,0 +1,174 @@ +// Network-mode nn::socket transport (DM_NETWORK=lan, hle_net_backend.c) through the game's own entry points in hle_net.c, on real loopback sockets. +// Offline behaviour without DM_NETWORK is t_net_loopback's and t_net_eventfd's, unchanged. +#include "../hle_net.c" +__thread _Atomic int dm_host_work; +#include +#include +#include +#include +#include + +void dm_guest_sleep_ns(int64_t ns) { struct timespec ts = {ns / 1000000000, ns % 1000000000}; nanosleep(&ts, NULL); } +void dm_guest_cond_wait_ns(pthread_cond_t *c, pthread_mutex_t *m, int64_t ns) { struct timespec ts = {ns / 1000000000, ns % 1000000000}; pthread_cond_timedwait_relative_np(c, m, &ts); } +uint64_t guest_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec; } +int dm_detclock_enabled(void) { return 0; } +// The guest core is released around every host wait, and the calls balance +static _Atomic int g_wait_depth, g_wait_entries; +void dm_thread_native_wait(int entering) { + if (entering) { atomic_fetch_add(&g_wait_depth, 1); atomic_fetch_add(&g_wait_entries, 1); } + else assert(atomic_fetch_sub(&g_wait_depth, 1) > 0); +} +// Records the spans the transport prepares before the kernel writes guest memory +static _Atomic(void *) g_prep_addr; static _Atomic size_t g_prep_len; static _Atomic int g_prep_count; +void dm_guest_write_prepare(void *addr, size_t len) { atomic_store(&g_prep_addr, addr); atomic_store(&g_prep_len, len); atomic_fetch_add(&g_prep_count, 1); } + +static int checks, failed; +#define CHECK(c, what) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, what); } } while (0) +static void address(uint8_t out[16], uint32_t ip, unsigned port) { // Horizon's sockaddr_in: {u8 len, u8 family, u16 port, u32 address}, network order + uint8_t b[16] = {16, 2, (uint8_t)(port >> 8), (uint8_t)port, (uint8_t)(ip >> 24), (uint8_t)(ip >> 16), (uint8_t)(ip >> 8), (uint8_t)ip}; memcpy(out, b, sizeof b); +} +static unsigned port_of(const uint8_t a[16]) { return (unsigned)a[2] << 8 | a[3]; } +static uint64_t ms_now(void) { return guest_ns() / 1000000; } +static int bound(int type, uint8_t a[16]) { + int s = h_sk_Socket(2, type, 0); address(a, 0x7f000001, 0); + unsigned n = 16; + if (s < 0 || h_sk_Bind(s, a, 16) || h_sk_GetSockName(s, a, &n) || n != 16) return -1; + return s; +} +typedef struct { int fd; long result; int error; uint64_t took; } wait_arg; +static void *blocked_recv(void *p) { + wait_arg *a = p; char b[8]; uint64_t t0 = ms_now(); + a->result = h_sk_Recv(a->fd, b, sizeof b, 0); a->error = h_sk_GetLastError(); a->took = ms_now() - t0; return NULL; +} +static void *late_event(void *p) { dm_guest_sleep_ns(30000000); h_sk_EventFdWrite((int)(intptr_t)p, 1); return NULL; } + +int main(void) { + setenv("DM_NETWORK", "lan", 1); + CHECK(dm_net_enabled(), "DM_NETWORK=lan turns the transport on"); + uint8_t a[16], b[16], from[16]; char data[64]; unsigned n; + + // EventFd stays the offline service's, below the transport's range + int event = h_sk_EventFd(0, 6); + CHECK(event >= 0 && event < DM_NET_FD_BASE, "EventFd keeps a small offline descriptor"); + + // UDP: Horizon's address layout both ways, data and source, and Linux errno numbers + int u = bound(2, a), v = bound(2, b); + CHECK(u >= DM_NET_FD_BASE && v >= DM_NET_FD_BASE && u != v, "network sockets start at DM_NET_FD_BASE"); + CHECK(a[0] == 16 && a[1] == 2 && a[4] == 127 && port_of(a), "GetSockName writes {16, AF_INET, port, 127.0.0.1}"); + CHECK(h_nsk_SendTo(u, "ping", 4, 0, b, 16) == 4, "SendTo another loopback socket"); + n = sizeof from; memset(data, 0, sizeof data); atomic_store(&g_prep_count, 0); + long got = h_sk_RecvFrom(v, data, sizeof data, 0, from, &n); + CHECK(got == 4 && !memcmp(data, "ping", 4), "RecvFrom gets the datagram"); + CHECK(n == 16 && from[0] == 16 && from[1] == 2 && port_of(from) == port_of(a), "RecvFrom reports the sender in Horizon's layout"); + CHECK(atomic_load(&g_prep_count) >= 1 && atomic_load(&g_prep_addr) == data && atomic_load(&g_prep_len) == sizeof data, "the receive buffer is prepared before the kernel writes it"); + uint8_t short_from[4]; n = sizeof short_from; h_nsk_SendTo(u, "x", 1, 0, b, 16); + CHECK(h_sk_RecvFrom(v, data, sizeof data, 0, short_from, &n) == 1 && n == 16 && short_from[1] == 2, "a short address buffer gets its capacity and the full length"); + CHECK(h_sk_Recv(v, data, sizeof data, 0x80) == -1 && h_sk_GetLastError() == 11 && dm_sk_errno() == 11, "an empty MSG_DONTWAIT receive is EAGAIN 11 (Horizon's number, not Darwin's 35)"); + uint8_t bad[16]; address(bad, 0x7f000001, 1); bad[1] = 0; + CHECK(h_nsk_SendTo(u, "x", 1, 0, bad, 16) == -1 && h_sk_GetLastError() == 97, "a family other than AF_INET is EAFNOSUPPORT 97"); + uint8_t zero_len[16]; memcpy(zero_len, b, 16); zero_len[0] = 0; + CHECK(h_nsk_SendTo(u, "z", 1, 0, zero_len, 16) == 1, "sin_len 0 is accepted, as hand-written game code leaves it"); + CHECK(h_sk_Recv(v, data, sizeof data, 0) == 1, "and arrives"); + + // Socket options: Horizon's numbers translated, SO_NOSIGPIPE kept on, SO_TYPE / SO_ERROR in Horizon's values, getsockopt output prepared + int one = 1, zero = 0, value = -1; unsigned len = sizeof value; + CHECK(h_sk_SetSockOpt(u, 0xffff, 0x20, &one, sizeof one) == 0, "SO_BROADCAST (0x20)"); + CHECK(h_sk_SetSockOpt(u, 0xffff, 0x800, &zero, sizeof zero) == 0, "SO_NOSIGPIPE (Horizon 0x800) is accepted"); + len = sizeof value; atomic_store(&g_prep_count, 0); + CHECK(h_sk_GetSockOpt(u, 0xffff, 0x800, &value, &len) == 0 && value != 0, "SO_NOSIGPIPE stays on after the guest clears it"); + CHECK(atomic_load(&g_prep_count) == 1 && atomic_load(&g_prep_addr) == &value, "the option output is prepared before getsockopt writes it"); + len = sizeof value; CHECK(h_sk_GetSockOpt(u, 0xffff, 0x1008, &value, &len) == 0 && value == 2, "SO_TYPE is SOCK_DGRAM 2"); + len = sizeof value; CHECK(h_sk_GetSockOpt(u, 0xffff, 0x1007, &value, &len) == 0 && value == 0, "SO_ERROR 0"); + CHECK(h_sk_SetSockOpt(u, 0xffff, 0x9999, &one, sizeof one) == -1 && h_sk_GetLastError() == 92, "an unknown option is ENOPROTOOPT 92"); + CHECK(h_sk_SetSockOpt(u, 0xffff, 0x1007, &one, sizeof one) == -1 && h_sk_GetLastError() == 92, "SO_ERROR is read-only"); + + // SO_RCVTIMEO bounds a blocking receive (u32 milliseconds, then the 16-byte TimeVal) + uint32_t timeout = 60; uint64_t t0 = ms_now(); + CHECK(h_sk_SetSockOpt(v, 0xffff, 0x1006, &timeout, sizeof timeout) == 0, "SO_RCVTIMEO as u32 milliseconds"); + CHECK(h_sk_Recv(v, data, sizeof data, 0) == -1 && h_sk_GetLastError() == 11 && ms_now() - t0 >= 50, "a timed-out receive is EAGAIN 11 after the timeout"); + int64_t tv[2] = {0, 0}; len = sizeof tv; + CHECK(h_sk_GetSockOpt(v, 0xffff, 0x1006, tv, &len) == 0 && len == 16 && tv[0] == 0 && tv[1] == 60000, "SO_RCVTIMEO reads back as a TimeVal"); + int64_t none[2] = {0, 0}; + CHECK(h_sk_SetSockOpt(v, 0xffff, 0x1006, none, sizeof none) == 0, "a zero TimeVal clears the timeout"); + + // Fcntl: O_NONBLOCK is Horizon's 0x800 + CHECK(h_sk_Fcntl(v, 4, 0x802) == 0 && (h_sk_Fcntl(v, 3, 0) & 0x800), "F_SETFL O_RDWR | O_NONBLOCK, F_GETFL reports 0x800"); + CHECK(h_sk_Recv(v, data, sizeof data, 0) == -1 && h_sk_GetLastError() == 11, "a non-blocking socket's empty receive is EAGAIN"); + CHECK(h_sk_Fcntl(v, 4, 0) == 0 && !(h_sk_Fcntl(v, 3, 0) & 0x800), "F_SETFL 0 makes it blocking again"); + + // Close on another thread ends a blocked receive with EBADF, without waiting for data + wait_arg w = {.fd = v}; pthread_t th; atomic_store(&g_wait_entries, 0); + pthread_create(&th, NULL, blocked_recv, &w); dm_guest_sleep_ns(50000000); + CHECK(h_sk_Close(v) == 0, "Close while another thread receives"); + pthread_join(th, NULL); + CHECK(w.result == -1 && w.error == 9 && w.took < 1000, "the blocked receive ends with EBADF 9 within a slice"); + CHECK(atomic_load(&g_wait_entries) > 0 && atomic_load(&g_wait_depth) == 0, "the wait released the guest core and balanced it"); + CHECK(h_sk_Recv(v, data, sizeof data, 0x80) == -1 && h_sk_GetLastError() == 9, "a closed descriptor is EBADF"); + + // Poll and Select: network descriptors, POLLNVAL for a closed one, and a set mixing an EventFd with a socket wakes on either + v = bound(2, b); h_nsk_SendTo(u, "p", 1, 0, b, 16); + sk_pollfd p[3] = {{v, 1, 0}, {u, 1, 0}, {event, 1, 0}}; + CHECK(h_sk_Poll(p, 3, 1000) == 1 && (p[0].revents & 1) && !p[1].revents && !p[2].revents, "Poll: the socket with data is readable, nothing else"); + uint64_t rs[16] = {0}; rs[v >> 6] |= 1ull << (v & 63); rs[u >> 6] |= 1ull << (u & 63); int64_t stv[2] = {1, 0}; + CHECK(h_sk_Select(1024, rs, NULL, NULL, stv) == 1 && (rs[v >> 6] >> (v & 63) & 1) && !(rs[u >> 6] >> (u & 63) & 1), "Select: the same answer in an fd_set"); + h_sk_Recv(v, data, sizeof data, 0); + pthread_create(&th, NULL, late_event, (void *)(intptr_t)event); t0 = ms_now(); + p[0] = (sk_pollfd){v, 1, 0}; p[1] = (sk_pollfd){event, 1, 0}; + int ready = h_sk_Poll(p, 2, 2000); pthread_join(th, NULL); + CHECK(ready == 1 && (p[1].revents & 1) && !p[0].revents && ms_now() - t0 < 1000, "a mixed Poll wakes for the EventFd"); + unsigned long counter; h_sk_EventFdRead(event, &counter); + int dead = h_sk_Socket(2, 2, 0); h_sk_Close(dead); + p[0] = (sk_pollfd){dead, 1, 0}; + CHECK(h_sk_Poll(p, 1, 0) == 1 && p[0].revents == 0x20, "a closed descriptor polls POLLNVAL"); + t0 = ms_now(); p[0] = (sk_pollfd){v, 1, 0}; + CHECK(h_sk_Poll(p, 1, -1) == 0 && ms_now() - t0 < 1000, "an endless Poll returns periodically, as the offline service's does"); + + // TCP: listen, a blocking connect, accept, data both ways, a peer that closed gives EPIPE 32 instead of a process-ending SIGPIPE + uint8_t la[16]; int l = bound(1, la); + CHECK(l >= DM_NET_FD_BASE && h_sk_Listen(l, 4) == 0, "TCP listen"); + int c = h_sk_Socket(2, 1, 0); + CHECK(h_sk_Connect(c, la, 16) == 0, "a blocking connect completes"); + n = sizeof from; int s = h_sk_Accept(l, from, &n); + CHECK(s >= DM_NET_FD_BASE && n == 16 && from[1] == 2 && from[4] == 127, "Accept reports the peer in Horizon's layout"); + len = sizeof value; CHECK(h_sk_GetSockOpt(s, 0xffff, 0x1008, &value, &len) == 0 && value == 1, "SO_TYPE is SOCK_STREAM 1"); + CHECK(h_sk_SetSockOpt(c, 6, 1, &one, sizeof one) == 0, "TCP_NODELAY at IPPROTO_TCP (6)"); + CHECK(h_sk_Send(c, "hello", 5, 0) == 5, "TCP send"); + CHECK(h_sk_Recv(s, data, 5, 0x40) == 5 && !memcmp(data, "hello", 5), "MSG_WAITALL gets the whole message"); + n = sizeof from; CHECK(h_sk_GetPeerName(c, from, &n) == 0 && port_of(from) == port_of(la), "GetPeerName"); + CHECK(h_sk_Close(s) == 0, "the server closes"); + dm_guest_sleep_ns(20000000); + long r1 = h_sk_Send(c, "a", 1, 0); dm_guest_sleep_ns(20000000); long r2 = h_sk_Send(c, "b", 1, 0); int e2 = h_sk_GetLastError(); + CHECK(r1 == 1 || r1 == -1, "a send after the peer closed returns"); + CHECK(r2 == -1 && (e2 == 32 || e2 == 104), "the next is EPIPE 32 (or ECONNRESET 104), and the process lives"); + uint8_t refused[16]; memcpy(refused, la, 16); h_sk_Close(l); h_sk_Close(c); + c = h_sk_Socket(2, 1, 0); + CHECK(h_sk_Connect(c, refused, 16) == -1 && h_sk_GetLastError() == 111, "a refused connect is ECONNREFUSED 111"); + h_sk_Close(c); + int nb = h_sk_Socket(2, 1 | 0x20000000, 0); + CHECK(nb >= DM_NET_FD_BASE && (h_sk_Fcntl(nb, 3, 0) & 0x800), "SOCK_NONBLOCK makes a non-blocking socket"); + uint8_t na[16]; address(na, 0x7f000001, 0); n = 16; + CHECK(!h_sk_Bind(nb, na, 16) && !h_sk_GetSockName(nb, na, &n) && !h_sk_Listen(nb, 1), "a non-blocking listener"); + c = h_sk_Socket(2, 1, 0); CHECK(h_sk_Connect(c, na, 16) == 0, "connect to it"); + sk_pollfd lp = {nb, 1, 0}; h_sk_Poll(&lp, 1, 1000); // a non-blocking accept waits for the connection to reach the queue + n = sizeof from; s = h_sk_Accept(nb, from, &n); + CHECK(s >= DM_NET_FD_BASE && (h_sk_Fcntl(s, 3, 0) & 0x800), "the accepted socket inherits O_NONBLOCK, as FreeBSD gives"); + h_sk_Close(s); h_sk_Close(c); + h_sk_Close(nb); + CHECK(h_sk_Socket(2, 3, 0) == -1 && h_sk_GetLastError() == 94, "SOCK_RAW is ESOCKTNOSUPPORT 94"); + + // nifm: the on-hold sequence is the offline one; the answer then follows the host interface + h_nifm_Submit(); + CHECK(!h_nifm_Available(), "unavailable while the request is on hold"); + CHECK(h_nifm_OnHold(), "the request is on hold at the first query"); + CHECK(!h_nifm_OnHold(), "and settled at the next"); + uint32_t ip = 0, want = 0; int have = !dm_net_ipconfig(&want, NULL); + CHECK(h_nifm_Available() == have, "available exactly when the host has an interface"); + CHECK((h_nifm_GetIp(&ip) == RES_OK) == have && ip == want, "GetCurrentPrimaryIpAddress is that interface's address"); + h_nifm_Cancel(); + CHECK(!h_nifm_Available(), "a cancelled request is unavailable"); + + h_sk_Close(u); h_sk_Close(v); h_sk_Close(event); + CHECK(atomic_load(&g_wait_depth) == 0, "no wait left the guest core released"); + printf("t_net: %d checks, %d failed\n", checks, failed); + return failed != 0; +} diff --git a/dm/host/tests/t_net_host_stub.c b/dm/host/tests/t_net_host_stub.c new file mode 100644 index 0000000000..3d6d0b6d9d --- /dev/null +++ b/dm/host/tests/t_net_host_stub.c @@ -0,0 +1,4 @@ +// The two host services hle_net_backend.c calls, for tests that link it without the thread and fault layers (hle_thread.c, crash.c) +#include +void dm_thread_native_wait(int entering) { (void)entering; } +void dm_guest_write_prepare(void *addr, size_t len) { (void)addr; (void)len; } diff --git a/dm/host/tests/t_server_environment.c b/dm/host/tests/t_server_environment.c index bfdf877039..3cabbbbe32 100644 --- a/dm/host/tests/t_server_environment.c +++ b/dm/host/tests/t_server_environment.c @@ -28,6 +28,9 @@ long dm_sk_recvfrom(int fd, void *d, unsigned long n, int f, void *a, unsigned * long dm_sk_sendto(int fd, const void *d, unsigned long n, int f, const void *a, unsigned an) { (void)fd; (void)d; (void)n; (void)f; (void)a; (void)an; unexpected++; return -1; } int dm_sk_poll(void *fds, uint64_t n, int ms) { (void)fds; (void)n; (void)ms; unexpected++; return -1; } int dm_sk_select(int n, uint64_t *r, uint64_t *w, uint64_t *e, const int64_t *tv) { (void)n; (void)r; (void)w; (void)e; (void)tv; unexpected++; return -1; } +int dm_sk_listen(int fd, int n) { (void)fd; (void)n; unexpected++; return -1; } +int dm_sk_accept(int fd, void *a, unsigned *n) { (void)fd; (void)a; (void)n; unexpected++; return -1; } +int dm_net_enabled(void) { return 0; } // offline: the Accept / Listen overloads answer -1 themselves int dm_sk_errno(void) { unexpected++; return 0; } extern const struct mach_header_64 _mh_execute_header; #define CHECK(c, msg) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s\n", msg); } } while (0) diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index ac2633876b..ee090fd997 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -515,6 +515,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - `abort` under `grpc_init` at startup, with no red line: `game called nn::diag abort: Result 0, call site sdk+0xb8fe8`, backtrace `sdk+0xba138 sdk+0x7bd670 sdk+0x777f30 main+0x21f0c80`, just after `fs mount _npln:` (Ocarina of Time). → [`EventFd` needs no network](../reference/services.md#eventfd-needs-no-network) - `CRASH sig=10` (SIGBUS) in a network thread right after start (Minecraft's `NetherNet Network`, `main+0x18b2ae8`, `x0=0x4000`), at a load from its own stack. → [Event descriptors in an `fd_set`](../reference/services.md#event-descriptors-in-an-fd_set) - New Game stays on the loading artwork with an empty progress bar while rendering and loading tips continue (Divinity: Original Sin 2). Both `nn::socket::Socket(AF_INET, SOCK_DGRAM, 0)` calls fail, so RakNet never completes initialization. → [UDP loopback works offline](../reference/services.md#udp-loopback-works-offline) +- with every socket served inside the process, a game's LAN mode finds no other console: `Socket` works, but nothing it sends leaves the Mac, and `nifm` reports no network, so a LAN menu stays empty or refuses to open. → [Network mode: the game's sockets on the host's own](../reference/services.md#network-mode-the-games-sockets-on-the-hosts-own) - `Break#1 reason=0 Result=0` right after the first save is created, then exit 42; the stack has `nn::diag::detail::OnAssertionFailure` under `nn::image::JpegDecoder::Decode` (`sdk+0x394e4`), called from the game (Burnout Paradise Remastered, SDK 9.3). → [The local user's profile image](../reference/services.md#the-local-users-profile-image) - `[RED] sf: the game connects to service mii:e … mii:u itself`, then an abort. → [Mii database answered by the host](../reference/services.md#mii-database-answered-by-the-host) - `mii: AppendMii (the host has no Mii editor: cancelled)` at each press, and the game goes back to where it asked for a Mii (Mario Golf: Super Rush's Golf Adventure: its save slots). → [A Mii made in the editor's place](../reference/services.md#a-mii-made-in-the-editors-place) diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index 7535625e90..555df5be05 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -147,6 +147,7 @@ DM_MOVIE_TRACE diagnostic When set, the movie decoder logs every call with its t DM_MSL_DIR path Parent folder of the shader libraries: NVN loads from `b-/` or the one file `b-.img` beneath it, Vulkan from `vk/`, GL from `gl/`; the app and the Mac launcher set it DM_MSL_LIB_COPY diagnostic `1` copies every `.metallib` mapping into allocator-owned `dispatch_data` on the Mac as iOS does (`nvn_mtl.m` `lib_from_map`); `0` borrows the file mapping on iOS as the Mac does by default DM_NDVE_ENGINE switch `0` runs nn::ndve's movie network (Ocarina of Time's title and opening movies) as the game's 12 translated dispatches after its colour conversion instead of the host's kernels (dm/gfx/msl/ndve_engine.metal, on by default: the same output, about half the frame's GPU time on an M4 Pro); `ab` alternates with DM_AB; `check` runs the game's dispatches and the host's network beside them and logs every 300 frames how many texels of the two differ. The host's kernels take only the model they were written for, bound by its shaders' keys and its weights' layout (docs/reference/shaders.md, The NDVE movie network by the host) +DM_NETWORK switch `lan` puts the game's `nn::socket` sockets on the host's own IPv4 TCP/UDP sockets and has nifm report the host interface (dm/host/hle_net_backend.c; off by default: the offline local UDP/EventFd service answers). Name resolution, TLS, local wireless and the online services stay offline DM_NICK switch The account nickname the game sees (default `Player`) DM_NRO switch `0` turns off loading of the NRO modules the game's NRR files register (on by default): every `nn::ro::LoadModule` then fails DM_NRO_CAPTURE diagnostic folder: a `nn::ro::LoadModule` with no rewritten copy writes the image to `/.nro` and ends the run (the NSP script's capture of an NRO the game decodes at run time) diff --git a/docs/reference/services.md b/docs/reference/services.md index 7638908b34..9eb5aac99c 100644 --- a/docs/reference/services.md +++ b/docs/reference/services.md @@ -1392,6 +1392,14 @@ Most service calls can be found before they crash, before the first boot or the - **Check:** `t_net_loopback` exercises the four-byte startup test, two-endpoint exchange, connected filtering, peek/truncation, nonblocking and timed receive, remote rejection, mixed EventFd readiness, and close/reuse during waits; `t_net_eventfd` retains the existing event-descriptor checks. - **Found on:** [Divinity: Original Sin 2 - Definitive Edition](../../dm/games/010027400CDC6000/README.md) (update 1.0.12, SDK 9.3.0). +### Network mode: the game's sockets on the host's own + +- **Symptom:** with every socket served inside the process, a game's LAN mode finds no other console: `Socket` works, but nothing it sends leaves the Mac, and `nifm` reports no network, so a LAN menu stays empty or refuses to open. +- **Cause:** the offline BSD service ([UDP loopback works offline](#udp-loopback-works-offline)) is deliberately local; remote traffic needs the host's own sockets, behind the guest's BSD ABI: the `{u8 length, u8 family}` sockaddr, Horizon's Linux errno numbers (an empty non-blocking receive is EAGAIN 11, which Mario Kart 8 Deluxe's receive loop compares), O_NONBLOCK 0x800, SOCK_NONBLOCK 0x20000000 and FreeBSD option numbers that Darwin numbers differently (SO_NOSIGPIPE 0x800 there, 0x1022 here). Three host facts decide correctness beyond the ABI: Darwin has no MSG_NOSIGNAL, so a send to a TCP peer that closed raises SIGPIPE and ends the process; the kernel's copyout into a write-protected guest page fails with EFAULT instead of reaching the dirty-page fault hook; and a Close on one thread must end another thread's blocking call on that socket. +- **Fix:** `DM_NETWORK=lan` (off by default) sends each `dm_sk_*` call for a network descriptor to `hle_net_backend.c` (`net_socket.h`), so every entry point (the enum, plain-argument and C overloads) follows without a hook of its own. Network descriptors are numbered from 64, above the service's EventFds, in one 1024-entry fd namespace, so `Select`'s `fd_set` and a `Poll` that mixes both kinds keep working (a mixed set alternates the EventFd check with 5 ms host waits; an endless wait comes back after 100 ms, as the offline one does). Native sockets are always non-blocking and carry SO_NOSIGPIPE (a guest that clears it keeps it on, and gets EPIPE 32 as Horizon gives); guest blocking, SO_RCVTIMEO / SO_SNDTIMEO (u32 milliseconds or the 16-byte TimeVal) and MSG_WAITALL are waits in 100 ms slices with the guest core released (`dm_thread_native_wait`). A call borrows a duplicate of the native descriptor, and the slot's generation ends a wait whose socket was closed with EBADF; Close also shuts the socket down, which wakes a TCP waiter at once. Every receive and `GetSockOpt` calls `dm_guest_write_prepare` on its output before the kernel writes it, again after each wait. `nifm` keeps its on-hold sequence and then reports the first up, running, broadcast-capable IPv4 interface. Name resolution, TLS, local wireless and the online services keep their offline answers. +- **Check:** `t_net` (`make -C dm/host/tests GAME= run`, also under ASan/UBSan and TSan) runs loopback UDP and TCP through the game's entry points: the address layout both ways and a short address buffer, Linux errno numbers, option translation, SO_NOSIGPIPE kept on, timeouts, O_NONBLOCK, a Close that ends a blocked receive on another thread, Poll/Select including a mixed EventFd set and POLLNVAL, a refused connect, EPIPE after the peer closed with the process alive, and nifm. `t_net_loopback` and `t_net_eventfd` check that the offline service is unchanged without `DM_NETWORK`. +- **Found on:** [Mario Kart 8 Deluxe](../../dm/games/0100152000022000/README.md): this is the transport I first wrote in NX Port Studio, where it carried my completed Mac–Switch LAN race on 3.0.5 (2026-10-31); this slice of it is checked by the tests above and not yet in a game on this branch. + ### The local user's profile image - **Symptom:** `Break#1 reason=0 Result=0` right after the first save is created, then exit 42; the stack has `nn::diag::detail::OnAssertionFailure` under `nn::image::JpegDecoder::Decode` (`sdk+0x394e4`), called from the game (Burnout Paradise Remastered, SDK 9.3). From 2ceec60bbcbcbdc2c515b07501b58f3e469a0ff0 Mon Sep 17 00:00:00 2001 From: Robii Aragon <55045932+RobiiAragon@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:02:14 -0800 Subject: [PATCH 2/2] host/net tests: t_net initializes its address buffers and asserts its descriptors clang-tidy's analyzer could not see that the sockets t_net indexes fd_sets with are valid, or that RecvFrom filled the source address before it is compared. The test now starts the address buffers at zero and asserts both descriptors are the transport's before using them as fd_set indexes. --- dm/host/tests/t_net.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dm/host/tests/t_net.c b/dm/host/tests/t_net.c index 032b1fae29..188646db16 100644 --- a/dm/host/tests/t_net.c +++ b/dm/host/tests/t_net.c @@ -45,7 +45,7 @@ static void *late_event(void *p) { dm_guest_sleep_ns(30000000); h_sk_EventFdWrit int main(void) { setenv("DM_NETWORK", "lan", 1); CHECK(dm_net_enabled(), "DM_NETWORK=lan turns the transport on"); - uint8_t a[16], b[16], from[16]; char data[64]; unsigned n; + uint8_t a[16] = {0}, b[16] = {0}, from[16] = {0}; char data[64]; unsigned n; // EventFd stays the offline service's, below the transport's range int event = h_sk_EventFd(0, 6); @@ -53,6 +53,7 @@ int main(void) { // UDP: Horizon's address layout both ways, data and source, and Linux errno numbers int u = bound(2, a), v = bound(2, b); + assert(dm_net_owns(u) && dm_net_owns(v)); // the rest indexes fd_sets with them CHECK(u >= DM_NET_FD_BASE && v >= DM_NET_FD_BASE && u != v, "network sockets start at DM_NET_FD_BASE"); CHECK(a[0] == 16 && a[1] == 2 && a[4] == 127 && port_of(a), "GetSockName writes {16, AF_INET, port, 127.0.0.1}"); CHECK(h_nsk_SendTo(u, "ping", 4, 0, b, 16) == 4, "SendTo another loopback socket"); @@ -106,7 +107,7 @@ int main(void) { CHECK(h_sk_Recv(v, data, sizeof data, 0x80) == -1 && h_sk_GetLastError() == 9, "a closed descriptor is EBADF"); // Poll and Select: network descriptors, POLLNVAL for a closed one, and a set mixing an EventFd with a socket wakes on either - v = bound(2, b); h_nsk_SendTo(u, "p", 1, 0, b, 16); + v = bound(2, b); assert(dm_net_owns(v)); h_nsk_SendTo(u, "p", 1, 0, b, 16); sk_pollfd p[3] = {{v, 1, 0}, {u, 1, 0}, {event, 1, 0}}; CHECK(h_sk_Poll(p, 3, 1000) == 1 && (p[0].revents & 1) && !p[1].revents && !p[2].revents, "Poll: the socket with data is readable, nothing else"); uint64_t rs[16] = {0}; rs[v >> 6] |= 1ull << (v & 63); rs[u >> 6] |= 1ull << (u & 63); int64_t stv[2] = {1, 0};