Linux: a native runtime, no Wine #526

Closed
spidercraft wants to merge 71 commits from upstream-pr/526 into main
spidercraft commented 2026-11-24 04:27:56 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by spidercraft on 2026-11-24T04:27:56Z.


What

A native Linux build of the runtime: victory run <exe> --execute runs the title as an ELF program, with no Wine and no Windows DLL. The title's x86-64 code still runs unchanged in our process; on Linux we also supply what the Windows loader, kernel and system DLLs supply on Windows. The Windows build is unchanged (it type-checks with no diagnostics after every commit here). The design, the rules each part follows and the status are in docs/linux.md.

Builds on #523 and #524 (their commits are the first two here) and includes #177's commits, the fix for image atomics on float-read textures that NVIDIA's compiler crashed on (with the test from #226).

Where things live

Part Where
PE mapper, TEB at the GS base, static TLS, guest threads, entry victory-loader/src/linux/{image,teb,tls,thread}.rs
SEH: signals to EXCEPTION_RECORD/CONTEXT, .pdata dispatcher and unwinder, host frames between title frames, crash report victory-loader/src/linux/{seh,signals,unwind,context,asm}.rs
Region table behind VirtualAlloc (64 KiB granularity, guard pages, placeholders, memfd physical pool) victory-loader/src/linux/vm.rs
Our implementation of the DLLs HostPolicy passes through on Windows: kernel32/ntdll (handle table, waits, locks, threads, thread pool, time, memory, heap, files, text), the UCRT, ws2_32/winhttp (offline), bcrypt, crypt32, advapi32, COM, user32, XAudio2, Spatial Audio, Media Foundation stubs victory-hle/src/linux/<dll>_<slice>.rs, found by host::imp::resolve on Linux
The Windows-only HLE modules, now on both: xmem, files, storage, lifecycle, xsystem, apu, dstorage victory-hle/src/modules/* (per-OS host functions only where they differ)
Host D3D12: vkd3d-proton built as native libraries and loaded at run time; window, keyboard and gamepads from SDL3 (loaded at run time); D3D12/DXGI bindings generated at build time (windows 0.62 does not build on Linux) victory-gpu, victory-shader, crates/victory-windows

The title-facing ABI is win64 everywhere (#524); the CRT-style exports (exit, the CRT file functions) were extern "C" and are fixed here too.

How to run

docs/linux.md: build vkd3d-proton natively (meson), point VICTORY_VKD3D at it; optionally Microsoft's DXC Linux release for VICTORY_DXIL/VICTORY_DXCOMPILER (Arch's directx-shader-compiler 1.10.2605 asserts on every shader). SDL3 and the Vulkan loader come from the distribution.

Tested

Linux (CachyOS, Ryzen 9 7950X3D, RTX 5090, NVIDIA 620.73):

  • cargo test --workspace: 416 passed, 0 failed, 12 ignored, without game data. Guest code under test is PE fixtures we build with lld-link against an xwin SDK (skipped without it): the loader probe, an SEH fixture (__try/__except around real faults, C++ throw/catch/rethrow across threads, unhandled-fault report), and device tests with VICTORY_VKD3D (compute, clear and readback, pipelines from translated shaders, 120 frames to a window).
  • cargo check --workspace --all-targets --all-features --target x86_64-pc-windows-msvc: no diagnostics.
  • With the title: it boots at its 30 fps, shows the start-up screens and the first-boot flow (settings, legal, terms) with scripted keys, keeps its profile and saves, loads the story and reaches the world (game state running, player and population placed): 3 of 3 runs stayed there for 200 s at 1.1-1.8 fps (the world itself still draws dark, as the README says for Windows).
  • victory translate --validate over the title's shaders on Linux: the same validated counts as the validator reports there; every emitted vertex, pixel and mesh program makes a pipeline.

Two fixes found on Linux that also concern Windows

  • Write watching now exists on Linux too (victory-loader/src/linux/{vm,watch}.rs, the GPU journal in victory-gpu/src/watch.rs shared): world copies of title memory fell from 6-11 GB to 0.2-0.4 GB a frame (0.6 to 1.1-1.8 fps). Overlaps the Windows-side work in #464 and #490 only in victory-gpu/src/watch.rs.
  • Raw buffer offsets are bounded (victory-shader/src/emit/lower.rs): a compute program in the world load computes raw offsets that wrap to near 2^32; the console reads 0 there, while on vkd3d-proton/NVIDIA the access hit an MMU fault (kernel Xid 13), the channel stopped and the submission's fence never signalled, which is what stalled most world loads (before: 4 of 5 runs ended by the title's watchdog; after: none in 9). Offsets are now kept at or below 0x7FFF_FFF0 (still past any view: reads give 0, writes drop). The same commit bounds root SRV reads by their host buffer's length, which overlaps #493 (root SRVs as bounded one-view tables); if #493 lands first this part can go.
  • DXC's LLVM replaced our fault handlers on its first compile (title SEH then died silently on Linux); ours are restored after it.

Not done yet

  • World frames are GPU-bound now (200-520 ms of GPU time), plus about 100-150 ms of write-watch bookkeeping that checking runs instead of blocks would cut.
  • B5G5R5A1/B4G4R4A4 render targets of that size are refused by the host here; wave64-only compute pipelines are refused (as on Windows with such GPUs).
  • Locales other than en-US data, share modes on files, waitable timers, APCs, and the DLL functions the title does not import, are left out on purpose.

No game data in the repository, the tests or this description.

🤖 Generated with Claude Code

<!-- greyfinch-sync:Marvisak/VIctory:issue:6574618448 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526). Originally posted by [spidercraft](https://github.com/spidercraft) on 2026-11-24T04:27:56Z. --- ## What A native Linux build of the runtime: `victory run <exe> --execute` runs the title as an ELF program, with no Wine and no Windows DLL. The title's x86-64 code still runs unchanged in our process; on Linux we also supply what the Windows loader, kernel and system DLLs supply on Windows. The Windows build is unchanged (it type-checks with no diagnostics after every commit here). The design, the rules each part follows and the status are in `docs/linux.md`. Builds on #523 and #524 (their commits are the first two here) and includes #177's commits, the fix for image atomics on float-read textures that NVIDIA's compiler crashed on (with the test from #226). **Where things live** | Part | Where | |------|-------| | PE mapper, TEB at the GS base, static TLS, guest threads, entry | `victory-loader/src/linux/{image,teb,tls,thread}.rs` | | SEH: signals to `EXCEPTION_RECORD`/`CONTEXT`, `.pdata` dispatcher and unwinder, host frames between title frames, crash report | `victory-loader/src/linux/{seh,signals,unwind,context,asm}.rs` | | Region table behind `VirtualAlloc` (64 KiB granularity, guard pages, placeholders, memfd physical pool) | `victory-loader/src/linux/vm.rs` | | Our implementation of the DLLs `HostPolicy` passes through on Windows: kernel32/ntdll (handle table, waits, locks, threads, thread pool, time, memory, heap, files, text), the UCRT, ws2_32/winhttp (offline), bcrypt, crypt32, advapi32, COM, user32, XAudio2, Spatial Audio, Media Foundation stubs | `victory-hle/src/linux/<dll>_<slice>.rs`, found by `host::imp::resolve` on Linux | | The Windows-only HLE modules, now on both: xmem, files, storage, lifecycle, xsystem, apu, dstorage | `victory-hle/src/modules/*` (per-OS host functions only where they differ) | | Host D3D12: vkd3d-proton built as native libraries and loaded at run time; window, keyboard and gamepads from SDL3 (loaded at run time); D3D12/DXGI bindings generated at build time (`windows` 0.62 does not build on Linux) | `victory-gpu`, `victory-shader`, `crates/victory-windows` | The title-facing ABI is `win64` everywhere (#524); the CRT-style exports (`exit`, the CRT file functions) were `extern "C"` and are fixed here too. ## How to run `docs/linux.md`: build vkd3d-proton natively (meson), point `VICTORY_VKD3D` at it; optionally Microsoft's DXC Linux release for `VICTORY_DXIL`/`VICTORY_DXCOMPILER` (Arch's `directx-shader-compiler` 1.10.2605 asserts on every shader). SDL3 and the Vulkan loader come from the distribution. ## Tested Linux (CachyOS, Ryzen 9 7950X3D, RTX 5090, NVIDIA 620.73): - `cargo test --workspace`: 416 passed, 0 failed, 12 ignored, without game data. Guest code under test is PE fixtures we build with `lld-link` against an xwin SDK (skipped without it): the loader probe, an SEH fixture (`__try`/`__except` around real faults, C++ throw/catch/rethrow across threads, unhandled-fault report), and device tests with `VICTORY_VKD3D` (compute, clear and readback, pipelines from translated shaders, 120 frames to a window). - `cargo check --workspace --all-targets --all-features --target x86_64-pc-windows-msvc`: no diagnostics. - With the title: it boots at its 30 fps, shows the start-up screens and the first-boot flow (settings, legal, terms) with scripted keys, keeps its profile and saves, loads the story and reaches the world (game state running, player and population placed): 3 of 3 runs stayed there for 200 s at 1.1-1.8 fps (the world itself still draws dark, as the README says for Windows). - `victory translate --validate` over the title's shaders on Linux: the same validated counts as the validator reports there; every emitted vertex, pixel and mesh program makes a pipeline. ## Two fixes found on Linux that also concern Windows - **Write watching** now exists on Linux too (`victory-loader/src/linux/{vm,watch}.rs`, the GPU journal in `victory-gpu/src/watch.rs` shared): world copies of title memory fell from 6-11 GB to 0.2-0.4 GB a frame (0.6 to 1.1-1.8 fps). Overlaps the Windows-side work in #464 and #490 only in `victory-gpu/src/watch.rs`. - **Raw buffer offsets are bounded** (`victory-shader/src/emit/lower.rs`): a compute program in the world load computes raw offsets that wrap to near 2^32; the console reads 0 there, while on vkd3d-proton/NVIDIA the access hit an MMU fault (kernel `Xid 13`), the channel stopped and the submission's fence never signalled, which is what stalled most world loads (before: 4 of 5 runs ended by the title's watchdog; after: none in 9). Offsets are now kept at or below `0x7FFF_FFF0` (still past any view: reads give 0, writes drop). The same commit bounds root SRV reads by their host buffer's length, which overlaps #493 (root SRVs as bounded one-view tables); if #493 lands first this part can go. - DXC's LLVM replaced our fault handlers on its first compile (title SEH then died silently on Linux); ours are restored after it. ## Not done yet - World frames are GPU-bound now (200-520 ms of GPU time), plus about 100-150 ms of write-watch bookkeeping that checking runs instead of blocks would cut. - B5G5R5A1/B4G4R4A4 render targets of that size are refused by the host here; wave64-only compute pipelines are refused (as on Windows with such GPUs). - Locales other than en-US data, share modes on files, waitable timers, APCs, and the DLL functions the title does not import, are left out on purpose. No game data in the repository, the tests or this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
KoLolX3 commented 2026-11-24 06:56:04 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by KoLolX3 on 2026-11-24T05:35:02Z.


Check on Linux, not Windows: pass. Head 323168050 merged onto main d2a4bae1f (clean merge).

  • Native tests of the seven crates that build on Linux (core, formats, game, loader, pe, pipeline, shader): PR 140 passed, 0 failed, main 92 passed, 7 failed. The 7 tests that fail on main no longer fail.
  • Whole workspace, native Linux (what this PR is for): cargo check --workspace --all-targets ok and cargo test --workspace ok: 412 passed, 0 failed, 12 ignored. On main the same check fails to build (3 errors). Only the test run, not the new native runtime itself (no game, no GPU host).
  • Windows cross type-check of the whole workspace (cargo xwin check --workspace --target x86_64-pc-windows-msvc, covers victory-gpu, victory-hle and the app): PR ok, main ok.
  • Tests this PR adds: 192, of which 41 ran in the native run (the pass count rose by 41); the other 151 are in code this run does not execute (cfg(windows) modules, the victory-gpu and victory-hle crates, or ignored tests), and were not run.
  • rustfmt: unformatted hunks, PR 756, main 168.
  • Failing on main here as well (not this PR): 7 tests in victory-loader and victory-pe that parse their own test binary as a PE image, which is an ELF file on Linux.
  • Not run: victory-gpu / victory-hle tests and the game itself.

On: AMD Ryzen 7 5700, 62 GB RAM, Artix Linux 7.3.4-artix1-2, rustc 1.98.1 (the repo's pinned toolchain), cargo-xwin 0.24.1. No game data. Automated check only: the code itself was not reviewed.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7123083141 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#issuecomment-7123083141). Originally posted by [KoLolX3](https://github.com/KoLolX3) on 2026-11-24T05:35:02Z. --- Check on Linux, not Windows: **pass**. Head `323168050` merged onto `main` `d2a4bae1f` (clean merge). - Native tests of the seven crates that build on Linux (`core`, `formats`, `game`, `loader`, `pe`, `pipeline`, `shader`): PR `140 passed, 0 failed`, `main` `92 passed, 7 failed`. The 7 tests that fail on `main` no longer fail. - **Whole workspace, native Linux** (what this PR is for): `cargo check --workspace --all-targets` ok and `cargo test --workspace` ok: **412 passed, 0 failed, 12 ignored**. On `main` the same check fails to build (3 errors). Only the test run, not the new native runtime itself (no game, no GPU host). - Windows cross type-check of the whole workspace (`cargo xwin check --workspace --target x86_64-pc-windows-msvc`, covers `victory-gpu`, `victory-hle` and the app): PR ok, `main` ok. - Tests this PR adds: 192, of which 41 ran in the native run (the pass count rose by 41); the other 151 are in code this run does not execute (`cfg(windows)` modules, the `victory-gpu` and `victory-hle` crates, or ignored tests), and were **not run**. - rustfmt: unformatted hunks, PR 756, `main` 168. - Failing on `main` here as well (not this PR): 7 tests in `victory-loader` and `victory-pe` that parse their own test binary as a PE image, which is an ELF file on Linux. - Not run: `victory-gpu` / `victory-hle` tests and the game itself. On: AMD Ryzen 7 5700, 62 GB RAM, Artix Linux 7.3.4-artix1-2, rustc 1.98.1 (the repo's pinned toolchain), cargo-xwin 0.24.1. No game data. Automated check only: the code itself was not reviewed.
cobrabm12 commented 2026-11-24 11:04:13 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by cobrabm12 on 2026-11-24T10:10:09Z.


Linux hardware test on an 8 GB Radeon RX 7600 (Navi 33), Mesa RADV 26.2.5, SDL 3.4.18. I built the Linux runtime at d46727f, native vkd3d-proton at 30b0eb9bc12d and used Microsoft's Linux DXC v1.9.2609. I used the default Series X profile and a local save that had completed first-boot setup. The native runtime used its own storage implementation.

The account picker responded to keyboard input. The illustrated load advanced to the “Vice City, Two Years Ago” chapter card. The runtime logged 240 successful mesh pipeline creations before I stopped the run. In four successive intervals during the transition it reported 0.9, 0.5, 0.9 and 1.0 fps. The final visible frame was black. Player movement and a visible world remain unverified.

On the same PC, the Windows runtime at ffe310e under Wine 11.21 exited at the first mesh pipeline, both with the default storage implementation and with a Leonida provider. Across these tests the graphics software versions also differ, so this comparison identifies a working route to the chapter card without establishing the cause of the difference.

CPU validation of the shaders used in this run

I matched all 1,257 distinct shader containers seen during startup, loading and the first scene to the local installation. For each build I called the same translator as the native runtime and checked every emitted module with Microsoft's Linux DXIL validator (DXC v1.9.2609).

Linux build Validated Unsupported by translator Rejected by validator
#526 at d46727f 958 288 11
With #180 987 269 1
With #193 973 273 11
With #180 and #193 1,002 254 1
With #180, #704 (includes #193), and the stable signature ordering from #306 1,003 254 0

All 958 baseline successes still validated. Of the 45 additional successes, 37 were compute, six pixel and two mesh shaders. On the #180 + #193 build, applying the signature ordering change alone cleared the remaining mesh output-signature error. The #704 integration also includes its descriptor-heap prerequisites cbb50b8, 3c81420 and e8d3b64 and builds natively. Rendering and frame rate on that build are still unverified.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7128409191 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#issuecomment-7128409191). Originally posted by [cobrabm12](https://github.com/cobrabm12) on 2026-11-24T10:10:09Z. --- Linux hardware test on an 8 GB Radeon RX 7600 (Navi 33), Mesa RADV 26.2.5, SDL 3.4.18. I built the Linux runtime at d46727f, native vkd3d-proton at 30b0eb9bc12d and used Microsoft's Linux DXC v1.9.2609. I used the default Series X profile and a local save that had completed first-boot setup. The native runtime used its own storage implementation. The account picker responded to keyboard input. The illustrated load advanced to the “Vice City, Two Years Ago” chapter card. The runtime logged 240 successful mesh pipeline creations before I stopped the run. In four successive intervals during the transition it reported 0.9, 0.5, 0.9 and 1.0 fps. The final visible frame was black. Player movement and a visible world remain unverified. On the same PC, the Windows runtime at ffe310e under Wine 11.21 exited at the first mesh pipeline, both with the default storage implementation and with a Leonida provider. Across these tests the graphics software versions also differ, so this comparison identifies a working route to the chapter card without establishing the cause of the difference. ### CPU validation of the shaders used in this run I matched all 1,257 distinct shader containers seen during startup, loading and the first scene to the local installation. For each build I called the same translator as the native runtime and checked every emitted module with Microsoft's Linux DXIL validator (DXC v1.9.2609). | Linux build | Validated | Unsupported by translator | Rejected by validator | | --- | ---: | ---: | ---: | | #526 at d46727f | 958 | 288 | 11 | | With #180 | 987 | 269 | 1 | | With #193 | 973 | 273 | 11 | | With #180 and #193 | 1,002 | 254 | 1 | | With #180, #704 (includes #193), and the stable signature ordering from #306 | 1,003 | 254 | 0 | All 958 baseline successes still validated. Of the 45 additional successes, 37 were compute, six pixel and two mesh shaders. On the #180 + #193 build, applying the signature ordering change alone cleared the remaining mesh output-signature error. The #704 integration also includes its descriptor-heap prerequisites cbb50b8, 3c81420 and e8d3b64 and builds natively. Rendering and frame rate on that build are still unverified.
toothpaste011 commented 2026-11-24 16:05:27 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by toothpaste011 on 2026-11-24T15:57:28Z.


Tested linux-native-runtime (d46727f) on Gentoo (kernel 7.0.10, Niri/Wayland, Intel Core Ultra 7 265K, RTX 5070 Ti, native vkd3d-proton ec20719452e916b, Microsoft Linux DXC v1.9.2609).

Intel CPU boot crash (0xc000001d / SIGILL)

On Intel CPUs, boot traps immediately with an unhandled 0xc000001d (SIGILL) on clzero (0f 01 fc) because crash.rs::emulate_amd_only (clzero, monitorx/mwaitx, clwb, SSE4a extrq/insertq) isn't ported to victory_loader::linux::signals yet.

Opened a fix against linux-native-runtime in spidercraft/VIctory#3 (handles SIGILL directly on ucontext_t, collapses clzero loops, updates XSAVE xstate_bv bit 1 for SSE4a, and adds synthetic ucontext_t unit tests so AMD hosts and CI exercise every branch alongside the live-execution test).

Hardware results after the fix (RTX 5070 Ti, Wayland/Niri)

  • Boot, first-boot setup screens, menus, and loading run at a locked 30.0 fps (1.2–2.6 ms GPU; DXC indirect argument clamp compiles and runs).
  • Reaches the world loop at 1.2–2.6 fps (~2,000–3,900 draws/frame, ~1,558 translated shaders / 1,039 cached pipelines), with no crashes or NVIDIA driver hangs.
  • World-stage host notes on RTX 5070 Ti:
    • 116 host pipelines refused by vkd3d-proton (Required WaveSize range [64, 64], but supported range is [32, 32]).
    • 1x WARN victory_gpu::descriptor::host: no free dynamic descriptor slots: a table is not made n=7 on world entry.
<!-- greyfinch-sync:Marvisak/VIctory:comment:7136891985 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#issuecomment-7136891985). Originally posted by [toothpaste011](https://github.com/toothpaste011) on 2026-11-24T15:57:28Z. --- Tested `linux-native-runtime` (`d46727f`) on Gentoo (kernel 7.0.10, Niri/Wayland, Intel Core Ultra 7 265K, RTX 5070 Ti, native vkd3d-proton `ec20719452e916b`, Microsoft Linux DXC v1.9.2609). ### Intel CPU boot crash (`0xc000001d` / `SIGILL`) On Intel CPUs, boot traps immediately with an unhandled `0xc000001d` (`SIGILL`) on `clzero` (`0f 01 fc`) because `crash.rs::emulate_amd_only` (`clzero`, `monitorx`/`mwaitx`, `clwb`, SSE4a `extrq`/`insertq`) isn't ported to `victory_loader::linux::signals` yet. Opened a fix against `linux-native-runtime` in spidercraft/VIctory#3 (handles `SIGILL` directly on `ucontext_t`, collapses `clzero` loops, updates XSAVE `xstate_bv` bit 1 for SSE4a, and adds synthetic `ucontext_t` unit tests so AMD hosts and CI exercise every branch alongside the live-execution test). ### Hardware results after the fix (RTX 5070 Ti, Wayland/Niri) - Boot, first-boot setup screens, menus, and loading run at a locked **30.0 fps** (`1.2–2.6 ms` GPU; DXC indirect argument clamp compiles and runs). - Reaches the world loop at **1.2–2.6 fps** (~2,000–3,900 draws/frame, ~1,558 translated shaders / 1,039 cached pipelines), with no crashes or NVIDIA driver hangs. - World-stage host notes on RTX 5070 Ti: - `116` host pipelines refused by vkd3d-proton (`Required WaveSize range [64, 64], but supported range is [32, 32]`). - `1x` `WARN victory_gpu::descriptor::host: no free dynamic descriptor slots: a table is not made n=7` on world entry.
x3ero0 commented 2026-11-24 16:05:31 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by x3ero0 on 2026-11-24T16:04:12Z.

Code review location: crates/victory-hle/src/linux/ws2_32.rs; line 417

@@ -0,0 +1,1239 @@
+//! Winsock (`ws2_32`) on Linux sockets, with the policy of
+//! `modules::net` on Windows: a console without a network cable.
+//!
+//! * Sockets are real, so the title can talk to itself over loopback
+//!   (its debug listener binds a TCP port). A `SOCKET` is the descriptor.
+//! * Connects and datagram sends to anything but 127.0.0.0/8 and ::1 fail
+//!   with `WSAENETUNREACH`; a bind to all interfaces is narrowed to
+//!   loopback, a bind to any other address fails.
+//! * Name lookups answer `localhost` and address literals only; the rest
+//!   fail with `WSAHOST_NOT_FOUND`.
+//!
+//! Windows layouts are translated both ways: `sockaddr` families
+//! (`AF_INET6` is 23), `fd_set` (a count and an array), `hostent` and
+//! `addrinfo` (fields in another order), socket options and error codes.
+//! Titles import most of this by ordinal (the Winsock 1.1 numbers).
+#![allow(non_snake_case)]
+#![allow(clippy::not_unsafe_ptr_arg_deref)]
+
+use std::cell::RefCell;
+use std::collections::HashSet;
+use std::ffi::{CStr, CString, c_char, c_int, c_void};
+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicU32, Ordering};
+
+use victory_loader::linux::teb;
+
+use crate::{HleExport, HleModule, hle_export};
+
+type Socket = usize;
+
+const INVALID_SOCKET: Socket = !0;
+const SOCKET_ERROR: i32 = -1;
+
+const WSAEINTR: i32 = 10004;
+const WSAEACCES: i32 = 10013;
+const WSAEFAULT: i32 = 10014;
+const WSAEINVAL: i32 = 10022;
+const WSAEMFILE: i32 = 10024;
+const WSAEWOULDBLOCK: i32 = 10035;
+const WSAEALREADY: i32 = 10037;
+const WSAENOTSOCK: i32 = 10038;
+const WSAEDESTADDRREQ: i32 = 10039;
+const WSAEMSGSIZE: i32 = 10040;
+const WSAEPROTOTYPE: i32 = 10041;
+const WSAENOPROTOOPT: i32 = 10042;
+const WSAEPROTONOSUPPORT: i32 = 10043;
+const WSAEOPNOTSUPP: i32 = 10045;
+const WSAEAFNOSUPPORT: i32 = 10047;
+const WSAEADDRINUSE: i32 = 10048;
+const WSAEADDRNOTAVAIL: i32 = 10049;
+const WSAENETDOWN: i32 = 10050;
+const WSAENETUNREACH: i32 = 10051;
+const WSAECONNABORTED: i32 = 10053;
+const WSAECONNRESET: i32 = 10054;
+const WSAENOBUFS: i32 = 10055;
+const WSAEISCONN: i32 = 10056;
+const WSAENOTCONN: i32 = 10057;
+const WSAESHUTDOWN: i32 = 10058;
+const WSAETIMEDOUT: i32 = 10060;
+const WSAECONNREFUSED: i32 = 10061;
+const WSAEHOSTUNREACH: i32 = 10065;
+const WSAVERNOTSUPPORTED: i32 = 10092;
+const WSANOTINITIALISED: i32 = 10093;
+const WSATYPE_NOT_FOUND: i32 = 10109;
+const WSAHOST_NOT_FOUND: i32 = 11001;
+
+const AF_UNSPEC: i32 = 0;
+const AF_INET: i32 = 2;
+const AF_INET6: i32 = 23;
+
+fn fail(code: i32) -> i32 {
+    teb::set_last_error(code as u32);
+    SOCKET_ERROR
+}
+
+/// The Winsock code for an errno.
+fn wsa(errno: i32) -> i32 {
+    match errno {
+        libc::EINTR => WSAEINTR,
+        libc::EBADF => WSAENOTSOCK,
+        libc::EACCES | libc::EPERM => WSAEACCES,
+        libc::EFAULT => WSAEFAULT,
+        libc::EINVAL => WSAEINVAL,
+        libc::EMFILE | libc::ENFILE => WSAEMFILE,
+        libc::EAGAIN | libc::EINPROGRESS => WSAEWOULDBLOCK,
+        libc::EALREADY => WSAEALREADY,
+        libc::ENOTSOCK => WSAENOTSOCK,
+        libc::EDESTADDRREQ => WSAEDESTADDRREQ,
+        libc::EMSGSIZE => WSAEMSGSIZE,
+        libc::EPROTOTYPE => WSAEPROTOTYPE,
+        libc::ENOPROTOOPT => WSAENOPROTOOPT,
+        libc::EPROTONOSUPPORT | libc::ESOCKTNOSUPPORT => WSAEPROTONOSUPPORT,
+        libc::EOPNOTSUPP => WSAEOPNOTSUPP,
+        libc::EAFNOSUPPORT => WSAEAFNOSUPPORT,
+        libc::EADDRINUSE => WSAEADDRINUSE,
+        libc::EADDRNOTAVAIL => WSAEADDRNOTAVAIL,
+        libc::ENETDOWN => WSAENETDOWN,
+        libc::ENETUNREACH => WSAENETUNREACH,
+        libc::ECONNABORTED => WSAECONNABORTED,
+        libc::ECONNRESET => WSAECONNRESET,
+        libc::ENOBUFS | libc::ENOMEM => WSAENOBUFS,
+        libc::EISCONN => WSAEISCONN,
+        libc::ENOTCONN => WSAENOTCONN,
+        libc::EPIPE | libc::ESHUTDOWN => WSAESHUTDOWN,
+        libc::ETIMEDOUT => WSAETIMEDOUT,
+        libc::ECONNREFUSED => WSAECONNREFUSED,
+        libc::EHOSTUNREACH => WSAEHOSTUNREACH,
+        _ => WSAEINVAL,
+    }
+}
+
+fn errno() -> i32 {
+    std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
+}
+
+/// `SOCKET_ERROR` with the last OS error as the Winsock error.
+fn os_fail() -> i32 {
+    fail(wsa(errno()))
+}
+
+// ---- start-up and the socket set ----
+
+static STARTED: AtomicU32 = AtomicU32::new(0);
+static SOCKETS: Mutex<Option<HashSet<i32>>> = Mutex::new(None);
+
+fn sockets<R>(f: impl FnOnce(&mut HashSet<i32>) -> R) -> R {
+    let mut s = SOCKETS.lock().unwrap_or_else(|e| e.into_inner());
+    f(s.get_or_insert_with(HashSet::new))
+}
+
+/// The descriptor of `s`, or the Winsock error for it.
+fn fd(s: Socket) -> Result<i32, i32> {
+    if STARTED.load(Ordering::Acquire) == 0 {
+        return Err(WSANOTINITIALISED);
+    }
+    let fd = i32::try_from(s).map_err(|_| WSAENOTSOCK)?;
+    if sockets(|set| set.contains(&fd)) { Ok(fd) } else { Err(WSAENOTSOCK) }
+}
+
+macro_rules! fd_or_fail {
+    ($s:expr) => {
+        match fd($s) {
+            Ok(fd) => fd,
+            Err(code) => return fail(code),
+        }
+    };
+}
+
+/// `WSADATA` (64-bit order).
+#[repr(C)]
+pub struct WsaData {
+    version: u16,
+    high_version: u16,
+    max_sockets: u16,
+    max_udp: u16,
+    vendor: *const c_char,
+    description: [u8; 257],
+    status: [u8; 129],
+}
+
+pub extern "win64" fn WSAStartup(version: u16, data: *mut WsaData) -> i32 {
+    if data.is_null() {
+        return WSAEFAULT;
+    }
+    let (major, minor) = (version & 0xFF, version >> 8);
+    if major < 1 || (major == 1 && minor < 1) {
+        return WSAVERNOTSUPPORTED;
+    }
+    let mut d = WsaData {
+        version: if major > 2 { 0x0202 } else { version },
+        high_version: 0x0202,
+        max_sockets: 0,
+        max_udp: 0,
+        vendor: std::ptr::null(),
+        description: [0; 257],
+        status: [0; 129],
+    };
+    d.description[..11].copy_from_slice(b"WinSock 2.0");
+    d.status[..7].copy_from_slice(b"Running");
+    // SAFETY: checked non-null; the title's WSADATA.
+    unsafe { data.write(d) };
+    STARTED.fetch_add(1, Ordering::AcqRel);
+    0
+}
+
+pub extern "win64" fn WSACleanup() -> i32 {
+    let ok = STARTED
+        .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1))
+        .is_ok();
+    if ok { 0 } else { fail(WSANOTINITIALISED) }
+}
+
+pub extern "win64" fn WSAGetLastError() -> i32 {
+    teb::last_error() as i32
+}
+
+pub extern "win64" fn WSASetLastError(code: i32) {
+    teb::set_last_error(code as u32);
+}
+
+// ---- addresses ----
+
+/// A Linux `sockaddr` and its length.
+struct HostAddr(libc::sockaddr_storage, libc::socklen_t);
+
+/// The address a title's `sockaddr` names.
+fn guest_addr(addr: *const u8, len: i32) -> Result<SocketAddr, i32> {
+    let len = usize::try_from(len).map_err(|_| WSAEFAULT)?;
+    if addr.is_null() || len < 4 {
+        return Err(WSAEFAULT);
+    }
+    // SAFETY: the title passes `len` readable bytes.
+    let b = unsafe { std::slice::from_raw_parts(addr, len) };
+    let port = u16::from_be_bytes([b[2], b[3]]);
+    match i32::from(u16::from_le_bytes([b[0], b[1]])) {
+        AF_INET if len >= 16 => {
+            let ip: [u8; 4] = b[4..8].try_into().expect("4 bytes");
+            Ok((ip, port).into())
+        }
+        AF_INET6 if len >= 28 => {
+            let ip: [u8; 16] = b[8..24].try_into().expect("16 bytes");
+            let flow = u32::from_be_bytes(b[4..8].try_into().expect("4 bytes"));
+            let scope = u32::from_le_bytes(b[24..28].try_into().expect("4 bytes"));
+            Ok(SocketAddr::V6(std::net::SocketAddrV6::new(ip.into(), port, flow, scope)))
+        }
+        AF_INET | AF_INET6 => Err(WSAEFAULT),
+        _ => Err(WSAEAFNOSUPPORT),
+    }
+}
+
+fn host_addr(a: &SocketAddr) -> HostAddr {
+    // SAFETY: all-zero is a valid sockaddr_storage.
+    let mut s: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
+    let len = match a {
+        SocketAddr::V4(v4) => {
+            // SAFETY: sockaddr_storage is large and aligned enough.
+            let sin = unsafe { &mut *(&mut s as *mut _ as *mut libc::sockaddr_in) };
+            sin.sin_family = libc::AF_INET as u16;
+            sin.sin_port = v4.port().to_be();
+            sin.sin_addr.s_addr = u32::from_ne_bytes(v4.ip().octets());
+            size_of::<libc::sockaddr_in>()
+        }
+        SocketAddr::V6(v6) => {
+            // SAFETY: as above.
+            let sin6 = unsafe { &mut *(&mut s as *mut _ as *mut libc::sockaddr_in6) };
+            sin6.sin6_family = libc::AF_INET6 as u16;
+            sin6.sin6_port = v6.port().to_be();
+            sin6.sin6_flowinfo = v6.flowinfo().to_be();
+            sin6.sin6_addr.s6_addr = v6.ip().octets();
+            sin6.sin6_scope_id = v6.scope_id();
+            size_of::<libc::sockaddr_in6>()
+        }
+    };
+    HostAddr(s, len as libc::socklen_t)
+}
+
+fn from_host(s: &libc::sockaddr_storage) -> Option<SocketAddr> {
+    match i32::from(s.ss_family) {
+        libc::AF_INET => {
+            // SAFETY: the family says this is a sockaddr_in.
+            let sin = unsafe { &*(s as *const _ as *const libc::sockaddr_in) };
+            Some((sin.sin_addr.s_addr.to_ne_bytes(), u16::from_be(sin.sin_port)).into())
+        }
+        libc::AF_INET6 => {
+            // SAFETY: the family says this is a sockaddr_in6.
+            let sin6 = unsafe { &*(s as *const _ as *const libc::sockaddr_in6) };
+            Some(SocketAddr::V6(std::net::SocketAddrV6::new(
+                sin6.sin6_addr.s6_addr.into(),
+                u16::from_be(sin6.sin6_port),
+                u32::from_be(sin6.sin6_flowinfo),
+                sin6.sin6_scope_id,
+            )))
+        }
+        _ => None,
+    }
+}
+
+/// `a` in Windows layout.
+fn guest_bytes(a: &SocketAddr) -> Vec<u8> {
+    let mut b = Vec::with_capacity(28);
+    match a {
+        SocketAddr::V4(v4) => {
+            b.extend((AF_INET as u16).to_le_bytes());
+            b.extend(v4.port().to_be_bytes());
+            b.extend(v4.ip().octets());
+            b.extend([0; 8]);
+        }
+        SocketAddr::V6(v6) => {
+            b.extend((AF_INET6 as u16).to_le_bytes());
+            b.extend(v6.port().to_be_bytes());
+            b.extend(v6.flowinfo().to_be_bytes());
+            b.extend(v6.ip().octets());
+            b.extend(v6.scope_id().to_le_bytes());
+        }
+    }
+    b
+}
+
+/// Writes `a` to a title's `sockaddr` and length, as `accept` and
+/// `getsockname` do; false (`WSAEFAULT`) if it does not fit.
+fn put_guest_addr(a: Option<SocketAddr>, out: *mut u8, len: *mut i32) -> bool {
+    if out.is_null() || len.is_null() {
+        return true;
+    }
+    let bytes = a.map(|a| guest_bytes(&a)).unwrap_or_default();
+    // SAFETY: the title's length and a buffer of that many bytes.
+    unsafe {
+        if (*len as usize) < bytes.len() || *len < 0 {
+            return false;
+        }
+        std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());
+        *len = bytes.len() as i32;
+    }
+    true
+}
+
+fn loopback(ip: IpAddr) -> bool {
+    ip.to_canonical().is_loopback()
+}
+
+fn once(what: &'static str, to: SocketAddr) {
+    static SEEN: Mutex<Vec<(&str, SocketAddr)>> = Mutex::new(Vec::new());
+    let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
+    if !seen.contains(&(what, to)) {
+        tracing::info!(%to, "{what}");
+        seen.push((what, to));
+    }
+}
+
+/// Only loopback is reachable.
+fn reachable(what: &'static str, to: SocketAddr) -> Result<(), i32> {
+    if loopback(to.ip()) {
+        return Ok(());
+    }
+    once(what, to);
+    Err(WSAENETUNREACH)
+}
+
+// ---- sockets ----
+
+pub extern "win64" fn socket(family: i32, kind: i32, protocol: i32) -> Socket {
+    if STARTED.load(Ordering::Acquire) == 0 {
+        fail(WSANOTINITIALISED);
+        return INVALID_SOCKET;
+    }
+    let family = match family {
+        AF_INET => libc::AF_INET,
+        AF_INET6 => libc::AF_INET6,
+        _ => {
+            fail(WSAEAFNOSUPPORT);
+            return INVALID_SOCKET;
+        }
+    };
+    if !matches!(kind, libc::SOCK_STREAM | libc::SOCK_DGRAM) {
+        fail(WSAEPROTONOSUPPORT);
+        return INVALID_SOCKET;
+    }
+    // SAFETY: plain socket creation.
+    let fd = unsafe { libc::socket(family, kind | libc::SOCK_CLOEXEC, protocol) };
+    if fd < 0 {
+        os_fail();
+        return INVALID_SOCKET;
+    }
+    sockets(|s| s.insert(fd));
+    fd as Socket
+}
+
+pub extern "win64" fn closesocket(s: Socket) -> i32 {
+    let fd = fd_or_fail!(s);
+    sockets(|set| set.remove(&fd));
+    // SAFETY: a descriptor we opened, no longer in the set.
+    if unsafe { libc::close(fd) } != 0 { os_fail() } else { 0 }
+}
+
+pub extern "win64" fn bind(s: Socket, addr: *const u8, len: i32) -> i32 {
+    let fd = fd_or_fail!(s);
+    let mut to = match guest_addr(addr, len) {
+        Ok(a) => a,
+        Err(code) => return fail(code),
+    };
+    // All interfaces means loopback: nothing on the network may connect in.
+    if to.ip().is_unspecified() {
+        to.set_ip(match to {
+            SocketAddr::V4(_) => Ipv4Addr::LOCALHOST.into(),
+            SocketAddr::V6(_) => Ipv6Addr::LOCALHOST.into(),
+        });
+    } else if !loopback(to.ip()) {
+        return fail(WSAEADDRNOTAVAIL);
+    }
+    let a = host_addr(&to);
+    // SAFETY: a valid sockaddr and its length.
+    if unsafe { libc::bind(fd, &a.0 as *const _ as *const libc::sockaddr, a.1) } != 0 {
+        return os_fail();
+    }
+    0
+}
+
+pub extern "win64" fn connect(s: Socket, addr: *const u8, len: i32) -> i32 {
+    let fd = fd_or_fail!(s);
+    let to = match guest_addr(addr, len).and_then(|a| reachable("connect refused: no network", a).map(|_| a)) {
+        Ok(a) => a,
+        Err(code) => return fail(code),
+    };
+    let a = host_addr(&to);
+    // SAFETY: a valid sockaddr and its length.
+    if unsafe { libc::connect(fd, &a.0 as *const _ as *const libc::sockaddr, a.1) } != 0 {
+        return os_fail();
+    }
+    0
+}
+
+pub extern "win64" fn listen(s: Socket, backlog: i32) -> i32 {
+    let fd = fd_or_fail!(s);
+    // SAFETY: plain call on our descriptor.
+    if unsafe { libc::listen(fd, backlog) } != 0 { os_fail() } else { 0 }
+}

listen goes straight to the kernel, and Linux binds an unbound socket to all interfaces at that point (0.0.0.0 and a port it chooses), so other machines can connect in. That gets around the narrowing bind does. Winsock returns WSAEINVAL for listen on an unbound socket, so refusing it here matches Windows.

The same happens with a first sendto from an unbound datagram socket: it is bound to 0.0.0.0 and can then receive datagrams from the network.

spidercraft/VIctory#1 fixes both against this branch, with a test: listen fails with WSAEINVAL unless the socket has a loopback address, and sendto binds an unbound datagram socket to loopback first.

<!-- greyfinch-sync:Marvisak/VIctory:review-comment:4682841863 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#discussion_r4682841863). Originally posted by [x3ero0](https://github.com/x3ero0) on 2026-11-24T16:04:12Z. **Code review location:** `crates/victory-hle/src/linux/ws2_32.rs`; line 417 ~~~~diff @@ -0,0 +1,1239 @@ +//! Winsock (`ws2_32`) on Linux sockets, with the policy of +//! `modules::net` on Windows: a console without a network cable. +//! +//! * Sockets are real, so the title can talk to itself over loopback +//! (its debug listener binds a TCP port). A `SOCKET` is the descriptor. +//! * Connects and datagram sends to anything but 127.0.0.0/8 and ::1 fail +//! with `WSAENETUNREACH`; a bind to all interfaces is narrowed to +//! loopback, a bind to any other address fails. +//! * Name lookups answer `localhost` and address literals only; the rest +//! fail with `WSAHOST_NOT_FOUND`. +//! +//! Windows layouts are translated both ways: `sockaddr` families +//! (`AF_INET6` is 23), `fd_set` (a count and an array), `hostent` and +//! `addrinfo` (fields in another order), socket options and error codes. +//! Titles import most of this by ordinal (the Winsock 1.1 numbers). +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::cell::RefCell; +use std::collections::HashSet; +use std::ffi::{CStr, CString, c_char, c_int, c_void}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; + +use victory_loader::linux::teb; + +use crate::{HleExport, HleModule, hle_export}; + +type Socket = usize; + +const INVALID_SOCKET: Socket = !0; +const SOCKET_ERROR: i32 = -1; + +const WSAEINTR: i32 = 10004; +const WSAEACCES: i32 = 10013; +const WSAEFAULT: i32 = 10014; +const WSAEINVAL: i32 = 10022; +const WSAEMFILE: i32 = 10024; +const WSAEWOULDBLOCK: i32 = 10035; +const WSAEALREADY: i32 = 10037; +const WSAENOTSOCK: i32 = 10038; +const WSAEDESTADDRREQ: i32 = 10039; +const WSAEMSGSIZE: i32 = 10040; +const WSAEPROTOTYPE: i32 = 10041; +const WSAENOPROTOOPT: i32 = 10042; +const WSAEPROTONOSUPPORT: i32 = 10043; +const WSAEOPNOTSUPP: i32 = 10045; +const WSAEAFNOSUPPORT: i32 = 10047; +const WSAEADDRINUSE: i32 = 10048; +const WSAEADDRNOTAVAIL: i32 = 10049; +const WSAENETDOWN: i32 = 10050; +const WSAENETUNREACH: i32 = 10051; +const WSAECONNABORTED: i32 = 10053; +const WSAECONNRESET: i32 = 10054; +const WSAENOBUFS: i32 = 10055; +const WSAEISCONN: i32 = 10056; +const WSAENOTCONN: i32 = 10057; +const WSAESHUTDOWN: i32 = 10058; +const WSAETIMEDOUT: i32 = 10060; +const WSAECONNREFUSED: i32 = 10061; +const WSAEHOSTUNREACH: i32 = 10065; +const WSAVERNOTSUPPORTED: i32 = 10092; +const WSANOTINITIALISED: i32 = 10093; +const WSATYPE_NOT_FOUND: i32 = 10109; +const WSAHOST_NOT_FOUND: i32 = 11001; + +const AF_UNSPEC: i32 = 0; +const AF_INET: i32 = 2; +const AF_INET6: i32 = 23; + +fn fail(code: i32) -> i32 { + teb::set_last_error(code as u32); + SOCKET_ERROR +} + +/// The Winsock code for an errno. +fn wsa(errno: i32) -> i32 { + match errno { + libc::EINTR => WSAEINTR, + libc::EBADF => WSAENOTSOCK, + libc::EACCES | libc::EPERM => WSAEACCES, + libc::EFAULT => WSAEFAULT, + libc::EINVAL => WSAEINVAL, + libc::EMFILE | libc::ENFILE => WSAEMFILE, + libc::EAGAIN | libc::EINPROGRESS => WSAEWOULDBLOCK, + libc::EALREADY => WSAEALREADY, + libc::ENOTSOCK => WSAENOTSOCK, + libc::EDESTADDRREQ => WSAEDESTADDRREQ, + libc::EMSGSIZE => WSAEMSGSIZE, + libc::EPROTOTYPE => WSAEPROTOTYPE, + libc::ENOPROTOOPT => WSAENOPROTOOPT, + libc::EPROTONOSUPPORT | libc::ESOCKTNOSUPPORT => WSAEPROTONOSUPPORT, + libc::EOPNOTSUPP => WSAEOPNOTSUPP, + libc::EAFNOSUPPORT => WSAEAFNOSUPPORT, + libc::EADDRINUSE => WSAEADDRINUSE, + libc::EADDRNOTAVAIL => WSAEADDRNOTAVAIL, + libc::ENETDOWN => WSAENETDOWN, + libc::ENETUNREACH => WSAENETUNREACH, + libc::ECONNABORTED => WSAECONNABORTED, + libc::ECONNRESET => WSAECONNRESET, + libc::ENOBUFS | libc::ENOMEM => WSAENOBUFS, + libc::EISCONN => WSAEISCONN, + libc::ENOTCONN => WSAENOTCONN, + libc::EPIPE | libc::ESHUTDOWN => WSAESHUTDOWN, + libc::ETIMEDOUT => WSAETIMEDOUT, + libc::ECONNREFUSED => WSAECONNREFUSED, + libc::EHOSTUNREACH => WSAEHOSTUNREACH, + _ => WSAEINVAL, + } +} + +fn errno() -> i32 { + std::io::Error::last_os_error().raw_os_error().unwrap_or(0) +} + +/// `SOCKET_ERROR` with the last OS error as the Winsock error. +fn os_fail() -> i32 { + fail(wsa(errno())) +} + +// ---- start-up and the socket set ---- + +static STARTED: AtomicU32 = AtomicU32::new(0); +static SOCKETS: Mutex<Option<HashSet<i32>>> = Mutex::new(None); + +fn sockets<R>(f: impl FnOnce(&mut HashSet<i32>) -> R) -> R { + let mut s = SOCKETS.lock().unwrap_or_else(|e| e.into_inner()); + f(s.get_or_insert_with(HashSet::new)) +} + +/// The descriptor of `s`, or the Winsock error for it. +fn fd(s: Socket) -> Result<i32, i32> { + if STARTED.load(Ordering::Acquire) == 0 { + return Err(WSANOTINITIALISED); + } + let fd = i32::try_from(s).map_err(|_| WSAENOTSOCK)?; + if sockets(|set| set.contains(&fd)) { Ok(fd) } else { Err(WSAENOTSOCK) } +} + +macro_rules! fd_or_fail { + ($s:expr) => { + match fd($s) { + Ok(fd) => fd, + Err(code) => return fail(code), + } + }; +} + +/// `WSADATA` (64-bit order). +#[repr(C)] +pub struct WsaData { + version: u16, + high_version: u16, + max_sockets: u16, + max_udp: u16, + vendor: *const c_char, + description: [u8; 257], + status: [u8; 129], +} + +pub extern "win64" fn WSAStartup(version: u16, data: *mut WsaData) -> i32 { + if data.is_null() { + return WSAEFAULT; + } + let (major, minor) = (version & 0xFF, version >> 8); + if major < 1 || (major == 1 && minor < 1) { + return WSAVERNOTSUPPORTED; + } + let mut d = WsaData { + version: if major > 2 { 0x0202 } else { version }, + high_version: 0x0202, + max_sockets: 0, + max_udp: 0, + vendor: std::ptr::null(), + description: [0; 257], + status: [0; 129], + }; + d.description[..11].copy_from_slice(b"WinSock 2.0"); + d.status[..7].copy_from_slice(b"Running"); + // SAFETY: checked non-null; the title's WSADATA. + unsafe { data.write(d) }; + STARTED.fetch_add(1, Ordering::AcqRel); + 0 +} + +pub extern "win64" fn WSACleanup() -> i32 { + let ok = STARTED + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) + .is_ok(); + if ok { 0 } else { fail(WSANOTINITIALISED) } +} + +pub extern "win64" fn WSAGetLastError() -> i32 { + teb::last_error() as i32 +} + +pub extern "win64" fn WSASetLastError(code: i32) { + teb::set_last_error(code as u32); +} + +// ---- addresses ---- + +/// A Linux `sockaddr` and its length. +struct HostAddr(libc::sockaddr_storage, libc::socklen_t); + +/// The address a title's `sockaddr` names. +fn guest_addr(addr: *const u8, len: i32) -> Result<SocketAddr, i32> { + let len = usize::try_from(len).map_err(|_| WSAEFAULT)?; + if addr.is_null() || len < 4 { + return Err(WSAEFAULT); + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr, len) }; + let port = u16::from_be_bytes([b[2], b[3]]); + match i32::from(u16::from_le_bytes([b[0], b[1]])) { + AF_INET if len >= 16 => { + let ip: [u8; 4] = b[4..8].try_into().expect("4 bytes"); + Ok((ip, port).into()) + } + AF_INET6 if len >= 28 => { + let ip: [u8; 16] = b[8..24].try_into().expect("16 bytes"); + let flow = u32::from_be_bytes(b[4..8].try_into().expect("4 bytes")); + let scope = u32::from_le_bytes(b[24..28].try_into().expect("4 bytes")); + Ok(SocketAddr::V6(std::net::SocketAddrV6::new(ip.into(), port, flow, scope))) + } + AF_INET | AF_INET6 => Err(WSAEFAULT), + _ => Err(WSAEAFNOSUPPORT), + } +} + +fn host_addr(a: &SocketAddr) -> HostAddr { + // SAFETY: all-zero is a valid sockaddr_storage. + let mut s: libc::sockaddr_storage = unsafe { std::mem::zeroed() }; + let len = match a { + SocketAddr::V4(v4) => { + // SAFETY: sockaddr_storage is large and aligned enough. + let sin = unsafe { &mut *(&mut s as *mut _ as *mut libc::sockaddr_in) }; + sin.sin_family = libc::AF_INET as u16; + sin.sin_port = v4.port().to_be(); + sin.sin_addr.s_addr = u32::from_ne_bytes(v4.ip().octets()); + size_of::<libc::sockaddr_in>() + } + SocketAddr::V6(v6) => { + // SAFETY: as above. + let sin6 = unsafe { &mut *(&mut s as *mut _ as *mut libc::sockaddr_in6) }; + sin6.sin6_family = libc::AF_INET6 as u16; + sin6.sin6_port = v6.port().to_be(); + sin6.sin6_flowinfo = v6.flowinfo().to_be(); + sin6.sin6_addr.s6_addr = v6.ip().octets(); + sin6.sin6_scope_id = v6.scope_id(); + size_of::<libc::sockaddr_in6>() + } + }; + HostAddr(s, len as libc::socklen_t) +} + +fn from_host(s: &libc::sockaddr_storage) -> Option<SocketAddr> { + match i32::from(s.ss_family) { + libc::AF_INET => { + // SAFETY: the family says this is a sockaddr_in. + let sin = unsafe { &*(s as *const _ as *const libc::sockaddr_in) }; + Some((sin.sin_addr.s_addr.to_ne_bytes(), u16::from_be(sin.sin_port)).into()) + } + libc::AF_INET6 => { + // SAFETY: the family says this is a sockaddr_in6. + let sin6 = unsafe { &*(s as *const _ as *const libc::sockaddr_in6) }; + Some(SocketAddr::V6(std::net::SocketAddrV6::new( + sin6.sin6_addr.s6_addr.into(), + u16::from_be(sin6.sin6_port), + u32::from_be(sin6.sin6_flowinfo), + sin6.sin6_scope_id, + ))) + } + _ => None, + } +} + +/// `a` in Windows layout. +fn guest_bytes(a: &SocketAddr) -> Vec<u8> { + let mut b = Vec::with_capacity(28); + match a { + SocketAddr::V4(v4) => { + b.extend((AF_INET as u16).to_le_bytes()); + b.extend(v4.port().to_be_bytes()); + b.extend(v4.ip().octets()); + b.extend([0; 8]); + } + SocketAddr::V6(v6) => { + b.extend((AF_INET6 as u16).to_le_bytes()); + b.extend(v6.port().to_be_bytes()); + b.extend(v6.flowinfo().to_be_bytes()); + b.extend(v6.ip().octets()); + b.extend(v6.scope_id().to_le_bytes()); + } + } + b +} + +/// Writes `a` to a title's `sockaddr` and length, as `accept` and +/// `getsockname` do; false (`WSAEFAULT`) if it does not fit. +fn put_guest_addr(a: Option<SocketAddr>, out: *mut u8, len: *mut i32) -> bool { + if out.is_null() || len.is_null() { + return true; + } + let bytes = a.map(|a| guest_bytes(&a)).unwrap_or_default(); + // SAFETY: the title's length and a buffer of that many bytes. + unsafe { + if (*len as usize) < bytes.len() || *len < 0 { + return false; + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len()); + *len = bytes.len() as i32; + } + true +} + +fn loopback(ip: IpAddr) -> bool { + ip.to_canonical().is_loopback() +} + +fn once(what: &'static str, to: SocketAddr) { + static SEEN: Mutex<Vec<(&str, SocketAddr)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&(what, to)) { + tracing::info!(%to, "{what}"); + seen.push((what, to)); + } +} + +/// Only loopback is reachable. +fn reachable(what: &'static str, to: SocketAddr) -> Result<(), i32> { + if loopback(to.ip()) { + return Ok(()); + } + once(what, to); + Err(WSAENETUNREACH) +} + +// ---- sockets ---- + +pub extern "win64" fn socket(family: i32, kind: i32, protocol: i32) -> Socket { + if STARTED.load(Ordering::Acquire) == 0 { + fail(WSANOTINITIALISED); + return INVALID_SOCKET; + } + let family = match family { + AF_INET => libc::AF_INET, + AF_INET6 => libc::AF_INET6, + _ => { + fail(WSAEAFNOSUPPORT); + return INVALID_SOCKET; + } + }; + if !matches!(kind, libc::SOCK_STREAM | libc::SOCK_DGRAM) { + fail(WSAEPROTONOSUPPORT); + return INVALID_SOCKET; + } + // SAFETY: plain socket creation. + let fd = unsafe { libc::socket(family, kind | libc::SOCK_CLOEXEC, protocol) }; + if fd < 0 { + os_fail(); + return INVALID_SOCKET; + } + sockets(|s| s.insert(fd)); + fd as Socket +} + +pub extern "win64" fn closesocket(s: Socket) -> i32 { + let fd = fd_or_fail!(s); + sockets(|set| set.remove(&fd)); + // SAFETY: a descriptor we opened, no longer in the set. + if unsafe { libc::close(fd) } != 0 { os_fail() } else { 0 } +} + +pub extern "win64" fn bind(s: Socket, addr: *const u8, len: i32) -> i32 { + let fd = fd_or_fail!(s); + let mut to = match guest_addr(addr, len) { + Ok(a) => a, + Err(code) => return fail(code), + }; + // All interfaces means loopback: nothing on the network may connect in. + if to.ip().is_unspecified() { + to.set_ip(match to { + SocketAddr::V4(_) => Ipv4Addr::LOCALHOST.into(), + SocketAddr::V6(_) => Ipv6Addr::LOCALHOST.into(), + }); + } else if !loopback(to.ip()) { + return fail(WSAEADDRNOTAVAIL); + } + let a = host_addr(&to); + // SAFETY: a valid sockaddr and its length. + if unsafe { libc::bind(fd, &a.0 as *const _ as *const libc::sockaddr, a.1) } != 0 { + return os_fail(); + } + 0 +} + +pub extern "win64" fn connect(s: Socket, addr: *const u8, len: i32) -> i32 { + let fd = fd_or_fail!(s); + let to = match guest_addr(addr, len).and_then(|a| reachable("connect refused: no network", a).map(|_| a)) { + Ok(a) => a, + Err(code) => return fail(code), + }; + let a = host_addr(&to); + // SAFETY: a valid sockaddr and its length. + if unsafe { libc::connect(fd, &a.0 as *const _ as *const libc::sockaddr, a.1) } != 0 { + return os_fail(); + } + 0 +} + +pub extern "win64" fn listen(s: Socket, backlog: i32) -> i32 { + let fd = fd_or_fail!(s); + // SAFETY: plain call on our descriptor. + if unsafe { libc::listen(fd, backlog) } != 0 { os_fail() } else { 0 } +} ~~~~ --- `listen` goes straight to the kernel, and Linux binds an unbound socket to all interfaces at that point (`0.0.0.0` and a port it chooses), so other machines can connect in. That gets around the narrowing `bind` does. Winsock returns `WSAEINVAL` for `listen` on an unbound socket, so refusing it here matches Windows. The same happens with a first `sendto` from an unbound datagram socket: it is bound to `0.0.0.0` and can then receive datagrams from the network. spidercraft/VIctory#1 fixes both against this branch, with a test: `listen` fails with `WSAEINVAL` unless the socket has a loopback address, and `sendto` binds an unbound datagram socket to loopback first.
x3ero0 commented 2026-11-24 17:02:41 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by x3ero0 on 2026-11-24T16:04:12Z.

Review: COMMENTED


One gap in the offline socket policy on Linux, with a fix in spidercraft/VIctory#1. Reviewed and tested at d46727f on Linux x86-64 (NVIDIA): cargo test --workspace passes there.

<!-- greyfinch-sync:Marvisak/VIctory:review:6042857396 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#pullrequestreview-6042857396). Originally posted by [x3ero0](https://github.com/x3ero0) on 2026-11-24T16:04:12Z. **Review:** COMMENTED --- One gap in the offline socket policy on Linux, with a fix in spidercraft/VIctory#1. Reviewed and tested at `d46727f` on Linux x86-64 (NVIDIA): `cargo test --workspace` passes there.
onpeek commented 2026-11-24 17:04:46 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by onpeek on 2026-11-24T16:58:26Z.


Ran GTA VI on this branch natively (RTX 4070, Arch) and hit three bugs. Fixes against linux-native-runtime are in spidercraft/VIctory#2:

  • GetProcAddress returned null for title DLLs mapped by our PE loader. GTA VI's FidelityFX loader looks up ffxCreateContext in amd_fidelityfx_upscaler_xbox.dll and calls it, so the game crashed about 4 s in (call to 0x0). With the fix it gets past the menus to the world load.
  • cas16 (cmpxchg16b) could get rbx as an in(reg) operand, which the manual rbx swap then clobbered. The SList tests segfaulted. Fixed registers now.
  • host_and_guest_blocks_mix was flaky under parallel tests (it read an uninitialized malloc byte and used a wrong upper bound).
<!-- greyfinch-sync:Marvisak/VIctory:comment:7138491584 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#issuecomment-7138491584). Originally posted by [onpeek](https://github.com/onpeek) on 2026-11-24T16:58:26Z. --- Ran GTA VI on this branch natively (RTX 4070, Arch) and hit three bugs. Fixes against `linux-native-runtime` are in spidercraft/VIctory#2: - **`GetProcAddress` returned null for title DLLs mapped by our PE loader.** GTA VI's FidelityFX loader looks up `ffxCreateContext` in `amd_fidelityfx_upscaler_xbox.dll` and calls it, so the game crashed about 4 s in (call to 0x0). With the fix it gets past the menus to the world load. - **`cas16` (`cmpxchg16b`) could get rbx as an `in(reg)` operand,** which the manual rbx swap then clobbered. The SList tests segfaulted. Fixed registers now. - **`host_and_guest_blocks_mix` was flaky under parallel tests** (it read an uninitialized `malloc` byte and used a wrong upper bound).
x3ero0 commented 2026-11-24 20:03:10 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by x3ero0 on 2026-11-24T19:27:12Z.


Test report for d46727f on NVIDIA, with every run inside a bubblewrap sandbox. (I left the review comment about listen earlier; the fix for that is spidercraft/VIctory#1.)

Setup: RTX 5080, driver 620.70, Ryzen 7 9800X3D, CachyOS (kernel 7.3.5), KDE Wayland, SDL3 on Wayland. Native vkd3d-proton built from 30b0eb9. Diagnostics build, Series X 1.0.2.1, an existing local save, menus driven by VICTORY_KEYS.

Sandbox: bwrap --unshare-all --clearenv, no network namespace beyond loopback, no home directory, the game folder read-only, only the cache and data folders writable, the Wayland socket and the NVIDIA device nodes bound. The runtime needs nothing else. Audio was not exposed, so pa_simple_new fails and it plays silently, as designed.

Build and tests

  • Builds natively; run maps and binds with 0 missing imports.
  • cargo test --workspace: 416 passed, 0 failed.
  • linux::vm::tests::physical_pages_map_alias_and_free failed once in five full-workspace runs (region_size 65536, expected 196608 at vm.rs:1875) and passed alone six times in a row. It looks order- or parallelism-dependent; I have not looked into it.

Title runs

Run Length Last frame Result
1 95 s 1376 0xc0000005 at game_scarlett_master.exe+0xc4b94e (write 0x670fc04), in the world
2 260 s 1715 ran to the time limit
3 260 s 1686 ran to the time limit
4 430 s 2121 ran to the time limit
5 430 s 1569 ran to the time limit; with DXC v1.9.2609 (VICTORY_DXCOMPILER)
  • Boot, the intro video, the start screen and the loading art run at 30 fps.
  • In the opening sequence the frame rate is 0.5 to 14 fps (mean 3 to 4.6 across runs). The illustrated credit cards draw correctly; the 3D scene behind them is black apart from the credit text.
  • The crash in run 1 did not come back in four further runs.
  • For comparison, the Windows build of main + #177 + #259 under GE-Proton on the same machine stops about a minute into the world at the title's +0x23cf683 (#1118). None of the native runs hit that in up to six minutes of world time.

What the log gives as causes

Message Runs 1 to 4 Run 5 (DXC)
Indirect execution dropped, not bounded (no clamp...) several hundred draws and dispatches per world frame none
Compute pipelines refused, Required WaveSize range [64, 64], but supported range is [32, 32] 79 to 99 142
Shaders that do not translate 95 to 142 523
no host texture (2560x1440, formats 86 and 115) 2 2
host view heap capped at 1000000, asked 1245184 1 1
Device methods not implemented, slots 0x1c8 and 0x218 1 each 1 each

With DXC the indirect draws run, more of the title's pipelines get requested (hence the higher counts), frames get slower (mean 2.2 fps against 3.2 in run 4), and the scene is still dark. So on this card the missing picture is not the dropped indirect execution.

On the DXC dependency: without VICTORY_DXCOMPILER every indirect execution is dropped, and Arch's package is unusable as docs/linux.md says. #190 builds the same clamp with the shader crate's own writer, so merging or rebasing onto it would remove the need for a compiler here too. I tried that design on this branch: with the clamp emitted that way and no DXC, a run reaches the world with zero not bounded drops.

Single machine, one GPU, runs of a few minutes; I did not play past the opening sequence.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7142117866 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#issuecomment-7142117866). Originally posted by [x3ero0](https://github.com/x3ero0) on 2026-11-24T19:27:12Z. --- Test report for `d46727f` on NVIDIA, with every run inside a bubblewrap sandbox. (I left the review comment about `listen` earlier; the fix for that is spidercraft/VIctory#1.) **Setup:** RTX 5080, driver 620.70, Ryzen 7 9800X3D, CachyOS (kernel 7.3.5), KDE Wayland, SDL3 on Wayland. Native vkd3d-proton built from `30b0eb9`. Diagnostics build, Series X 1.0.2.1, an existing local save, menus driven by `VICTORY_KEYS`. **Sandbox:** `bwrap --unshare-all --clearenv`, no network namespace beyond loopback, no home directory, the game folder read-only, only the cache and data folders writable, the Wayland socket and the NVIDIA device nodes bound. The runtime needs nothing else. Audio was not exposed, so `pa_simple_new` fails and it plays silently, as designed. ### Build and tests - Builds natively; `run` maps and binds with 0 missing imports. - `cargo test --workspace`: 416 passed, 0 failed. - `linux::vm::tests::physical_pages_map_alias_and_free` failed once in five full-workspace runs (`region_size` 65536, expected 196608 at `vm.rs:1875`) and passed alone six times in a row. It looks order- or parallelism-dependent; I have not looked into it. ### Title runs | Run | Length | Last frame | Result | |---|---|---|---| | 1 | 95 s | 1376 | `0xc0000005` at `game_scarlett_master.exe+0xc4b94e` (write `0x670fc04`), in the world | | 2 | 260 s | 1715 | ran to the time limit | | 3 | 260 s | 1686 | ran to the time limit | | 4 | 430 s | 2121 | ran to the time limit | | 5 | 430 s | 1569 | ran to the time limit; with DXC v1.9.2609 (`VICTORY_DXCOMPILER`) | - Boot, the intro video, the start screen and the loading art run at 30 fps. - In the opening sequence the frame rate is 0.5 to 14 fps (mean 3 to 4.6 across runs). The illustrated credit cards draw correctly; the 3D scene behind them is black apart from the credit text. - The crash in run 1 did not come back in four further runs. - For comparison, the Windows build of `main` + #177 + #259 under GE-Proton on the same machine stops about a minute into the world at the title's `+0x23cf683` (#1118). None of the native runs hit that in up to six minutes of world time. ### What the log gives as causes | Message | Runs 1 to 4 | Run 5 (DXC) | |---|---|---| | Indirect execution dropped, `not bounded (no clamp...)` | several hundred draws and dispatches per world frame | none | | Compute pipelines refused, `Required WaveSize range [64, 64], but supported range is [32, 32]` | 79 to 99 | 142 | | Shaders that do not translate | 95 to 142 | 523 | | `no host texture` (2560x1440, formats 86 and 115) | 2 | 2 | | `host view heap capped at 1000000`, asked 1245184 | 1 | 1 | | Device methods not implemented, slots `0x1c8` and `0x218` | 1 each | 1 each | With DXC the indirect draws run, more of the title's pipelines get requested (hence the higher counts), frames get slower (mean 2.2 fps against 3.2 in run 4), and the scene is still dark. So on this card the missing picture is not the dropped indirect execution. On the DXC dependency: without `VICTORY_DXCOMPILER` every indirect execution is dropped, and Arch's package is unusable as `docs/linux.md` says. #190 builds the same clamp with the shader crate's own writer, so merging or rebasing onto it would remove the need for a compiler here too. I tried that design on this branch: with the clamp emitted that way and no DXC, a run reaches the world with zero `not bounded` drops. Single machine, one GPU, runs of a few minutes; I did not play past the opening sequence.
upstream-sync closed this pull request 2026-11-25 00:05:34 +00:00
Marvisak commented 2026-11-25 00:06:58 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-25T00:03:45Z.


Automated triage for the maintainers. Closing because it is outside the project's scope (VIctory targets Windows hosts; ports, launchers and tooling for other platforms are not being taken).

Native Linux runtime, 38,000 lines over 155 files (own loader, SEH, a new crate with a build script, libc and serde_json, a docs/linux.md design document, an edit to xtask/src/policy.rs): a port, out of scope.

If this is mistaken, reply here with what was missed (or push a change and say so) and it will be looked at again. Thank you for the contribution.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7148095178 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/526#issuecomment-7148095178). Originally posted by [Marvisak](https://github.com/Marvisak) on 2026-11-25T00:03:45Z. --- Automated triage for the maintainers. Closing because it is outside the project's scope (VIctory targets Windows hosts; ports, launchers and tooling for other platforms are not being taken). Native Linux runtime, 38,000 lines over 155 files (own loader, SEH, a new crate with a build script, libc and serde_json, a docs/linux.md design document, an edit to xtask/src/policy.rs): a port, out of scope. If this is mistaken, reply here with what was missed (or push a change and say so) and it will be looked at again. Thank you for the contribution.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Marvisak/VIctory!526
No description provided.