Skip to content

runtime/shims: add offline ws2_32.dll Winsock2 shim for mapped EXE - #6943

Open
emirhan-karaca wants to merge 3 commits into
ItsNotRexed:mainfrom
emirhan-karaca:fix/ws2-32-offline-shim
Open

emirhan-karaca wants to merge 3 commits into
ItsNotRexed:mainfrom
emirhan-karaca:fix/ws2-32-offline-shim

Conversation

@emirhan-karaca

Copy link
Copy Markdown
Contributor

@ItsNotRexed pinging as requested for an EXE/runtime PR.

Claim: #6750 (comment)
Context: #6715 (game_scarlett_master.exe maps under gta6rt --dry-run and imports 25 functions from ws2_32.dll — 23 by classic Winsock ordinal plus getaddrinfo and freeaddrinfo).

Problem

While gta6rt already owns winhttp.dll (runtime/shims/winhttp_offline.cpp) so mapped titles cannot make live HTTP requests, ws2_32.dll had no shim table. Every ws2_32.dll import — both static IAT/delay-load imports (including ordinal imports formatted as #<ordinal> by pe_loader.cpp) and dynamic LoadLibrary/GetProcAddress lookups via library_loader.cpp — fell straight through to the host's ws2_32.dll, allowing live DNS queries, real TCP/UDP sockets, and blocking network timeouts.

Changes

  • runtime/shims/ws2_32_offline.cpp (new):
    • Registers 89 Winsock2 functions under both export name and official Windows ws2_32.dll ordinal (178 SHIM_TABLE entries), giving rt::shims::owns_dll("ws2_32.dll") == true and covering all classic Winsock 1.1 ordinals (#1–#23, #51–#57, #111–#116, #151), getaddrinfo/freeaddrinfo (#192/#191), GetAddrInfoW/FreeAddrInfoW, GetAddrInfoEx*/FreeAddrInfoEx*, getnameinfo/GetNameInfoW, GetHostNameW, inet_pton/inet_ntop/InetPtonW/InetNtopW, WSAAddressToString*/WSAStringToAddress*, WSASocketA/W, WSAConnect*, WSAAccept, WSASend*/WSARecv*, WSAPoll, WSAIoctl (including SIO_UDP_CONNRESET = 0x9800000C / FIONREAD / FIONBIO), WSAEventSelect/WSAEnumNetworkEvents/WSA*Event, WSAAsyncSelect, WSAHton*/WSANtoh*, WSAEnumProtocolsA/W, and WSAGetOverlappedResult.
    • Zero host ws2_32.dll calls or linkage — answers every operation in-process.
    • Offline wall: connect / WSAConnect / WSAConnectByNameA/W / WSAConnectByList / sendto / WSASendTo / WSASendMsg fail immediately with WSAENETUNREACH, record SO_ERROR, fire FD_CONNECT on registered WSAEventSelect events, and log each unique target once to stderr ([rt] ws2_32: offline, refused <kind> <target>). Stream send/recv/getpeername return WSAENOTCONN; bound non-blocking UDP recvfrom/WSARecvFrom return WSAEWOULDBLOCK.
    • Offline DNS & local state: WSAStartup/WSACleanup maintain a lock-protected refcount; local synthetic SOCKET handles support bind (with ephemeral ports), getsockname, listen, setsockopt/getsockopt, ioctlsocket, WSAIoctl, and bounded select/WSAPoll (capped to 10 ms / 1 ms for infinite waits). getaddrinfo/GetAddrInfoW/GetAddrInfoEx* resolve numeric IPv4/IPv6 literals, AI_PASSIVE wildcards, and localhost (with AI_CANONNAME) in-process; any remote hostname is logged once and fails immediately with WSAHOST_NOT_FOUND.
    • Wine/guest-thread safe globals: uses constant-initialized SRWLOCK + InitOnceExecuteOnce, Win32 FlsAlloc for per-thread inet_ntoa buffers, and file-scope POD tables for gethostbyname/getprotoby* — zero _tls_index and zero function-local static init guards (__cxa_guard_acquire / _Init_thread_header).
  • runtime/test/ws2_32_offline_test.cpp (new):
    • Self-contained synthetic test resolving all 89 functions by name and #ordinal through rt::shims::find (using RFC 2606 .invalid and RFC 5737/3849 documentation addresses; zero network traffic, zero host ws2_32.dll imports).
  • runtime/CMakeLists.txt & scripts/build_runtime.ps1:
    • Adds shims/ws2_32_offline.cpp to gta6rt in both runtime/CMakeLists.txt and scripts/build_runtime.ps1 (keeping tests/test_build_runtime_fallback.py in sync), and registers ws2_32_offline_test (ctest name ws2_32_offline).

Verification

  • Compiler: MinGW-w64 g++ 16.2.0 (-std=c++20 -O2 -Wall -Wextra -Wconversion -Wsign-conversion -Werror on ws2_32_offline.cpp and ws2_32_offline_test.cpp in both ANSI and -DUNICODE -D_UNICODE modes: 0 warnings).
  • RED negative control (ws2_32_offline_test.cpp + registry.cpp without ws2_32_offline.cpp, representing origin/main 1cc6e3c12):
    • exit=1 | 10 checks, 8 failed (FAIL shim registry owns ws2_32.dll, FAIL all 89 ws2_32 exports resolve identically by name and Windows ordinal, plus 6 null-resolution guards).
  • GREEN runs:
    • ANSI build: 3/3 consecutive PASS (exit=0 | 147 checks, 0 failed, including PASS all 89 ws2_32 exports resolve identically by name and Windows ordinal).
    • UNICODE build (matching gta6rt): PASS (exit=0 | 147 checks, 0 failed).
  • Co-link check (winhttp_offline_test.cpp + winhttp_offline.cpp + ws2_32_offline.cpp + registry.cpp):
    • PASS (exit=0 | 83 check(s), 0 failure(s)), proving zero symbol collisions or regressions when both offline network shims are linked together.
  • Static binary/symbol checks:
    • objdump -p ws2_32_offline_test.exe DLL imports: only KERNEL32.dll and msvcrt.dll (zero ws2_32.dll import).
    • nm -u ws2_32_unicode.o: zero _tls_index, zero __cxa_guard_*, zero host ws2_32 symbols.
    • Verified CMake add_executable(gta6rt ...) .cpp set matches scripts/build_runtime.ps1 $files (missing=0).
    • git diff --check: exit 0 (CRLF=0 on all new files and runtime/CMakeLists.txt).

Disclosures

  • AI-assisted: Implementation and test authoring were AI-assisted; every line, ordinal mapping (cross-checked against Windows ws2_32.dll), and test run was locally verified.
  • No game files: Zero game binaries, keys, shaders, or copyrighted data touched or included.
  • Local environment note: Local machine has MinGW-w64 g++ 16.2.0 (linked untouched registry.cpp with a scratch _AddressOfReturnAddress intrinsic stub) and no local MSVC cl.exe, CMake, or Python; full MSVC /W4 /permissive- /utf-8 + ctest + test_build_runtime_fallback.py verification will run in CI.

@Hiiva Hiiva left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Native Windows review of exact head 59fbf52. The unchanged synthetic fixture builds and passes under MSVC.

  • ANSI: 147 checks, 0 failed.
  • UNICODE: 147 checks, 0 failed.
  • Same fixture linked with registry.cpp but without ws2_32_offline.cpp: 10 checks, 8 expected failures.
  • test_build_runtime_fallback.py: 8 methods passed.
  • test_ctest_registration.py: 4 methods passed.

Each fixture executable's direct DLL dependency list was inspected before execution: only KERNEL32.dll, with no host Winsock import. Source inspection found no host socket/DNS calls or LoadLibrary/GetProcAddress path in the new shim. The local socket/refusal/event/query implementation also received a separate source review. MSVC emitted 28 C4996 warnings in each positive build for SDK-deprecated ANSI Winsock fields; there were no compile or link errors. These were direct focused MSVC builds, not a full runtime CTest run.

I also compiled one binding-only probe against unchanged main 1cc6e3c and this exact head, using actual production loader, registry, library-loader, and Winsock sources. Both runs passed 688 expected-observation checks across 53 map-only import cases. All mapped synthetic images have zero entry points and are never initialized.

Control Main 1cc6e3c This head
#1 through #23, getaddrinfo and freeaddrinfo, direct imports Host Shim
Same 25 public API spellings through PE forwarders Host Shim
All 89 registered named/ordinal pairs through the dynamic module handle Host Shim
Registered names through a real System32 HMODULE Host Shim
Registered ordinals through that real HMODULE Host Host
Unregistered WSALookupServiceBeginW, static and forwarded Host Host
Unregistered WSALookupServiceBeginW through the owned dynamic handle Host NULL / ERROR_PROC_NOT_FOUND
Same unregistered export through a real HMODULE Host Host
Bare ws2_32 module name importing socket Host Host

The ordinal oracle independently checks each of the 89 mappings against actual System32 export addresses. Registry/IAT/dynamic results are compared with those addresses; no returned host Winsock pointer is called. The positive stock fixture executes only the local shim.

The remaining Host rows are existing loader limitations, separate from the implemented functions. #5731 at c4fcea0 covers the missing static/forwarder guard and bare-module normalization. Source inspection of #4861 at c190750 shows coverage of registered ordinals on real host handles, but retains unregistered-export fallback. Neither PR was combined into these #6943 runs. This supports the covered offline import surface; it is not a claim of complete host-network containment.

Environment: Windows 11 build 26200, MSVC toolset 14.44.35207, Windows SDK 10.0.26100.0. Synthetic inputs only; no title execution, game access, GPU, firewall changes, or production edits. AI-assisted.

@wasonidas

Copy link
Copy Markdown

Independent CPU-only check of 59fbf52dce3fc1c104b5982b366d862e70bab9fd on Windows 11. The runtime and ws2_32_offline_test built. All 147 synthetic checks passed, CTest ws2_32_offline passed 1/1, and the fallback-build tests passed 8/8.

The table registers 89 functions by name and ordinal. dumpbin /imports showed no host ws2_32.dll import in either executable. The synthetic suite exercised the shim's in-memory socket state, local resolution and refusal paths without outbound traffic. No retail executable or game files were used. This verifies the shim contract, not retail boot progress. AI-assisted.

@emirhan-karaca

Copy link
Copy Markdown
Contributor Author

Thanks @Hiiva for the thorough native Windows/MSVC verification, the 688-check loader/ordinal oracle cross-check, and catching the 28 MSVC C4996 warnings on the SDK-deprecated ANSI Winsock types!

Fixed in fcf3fc1a3: defined _WINSOCK_DEPRECATED_NO_WARNINGS before <winsock2.h> in both runtime/shims/ws2_32_offline.cpp and runtime/test/ws2_32_offline_test.cpp. Re-verified locally with g++ 16.2.0 (-Werror, 3/3 ANSI + 1/1 UNICODE, 147 checks, 0 failed).

@hiddenblur

Copy link
Copy Markdown

Reviewed fcf3fc1a3 on Windows 11 with MSVC (VS 18, /std:c++20 /W4 /permissive- /utf-8, same files as the CMake target). ANSI and UNICODE both build with 0 warnings (the _WINSOCK_DEPRECATED_NO_WARNINGS fix works) and pass 147/147 checks. dumpbin /dependents shows no ws2_32.dll in the test executable.

I also read the whole shim and ran a small probe through rt::shims::find for behaviour the suite doesn't pin. Synthetic, no network, no game files:

  1. Blocking recvfrom / accept return at once. A bound blocking UDP socket's recvfrom and a listening blocking TCP socket's accept fail immediately with WSAENETUNREACH: about 5 million calls in 200 ms each. Real Winsock blocks there, so a dedicated network thread that loops on either call would spin a core at 100%. select/WSAPoll already sleep up to 10 ms; the same for blocking recv*/accept (or honouring SO_RCVTIMEO, then WSAETIMEDOUT) would avoid it. Non-blocking sockets correctly get WSAEWOULDBLOCK.
  2. select never reports a socket writable. It clears writefds too, so a bound UDP socket (writable at once on Windows) never shows as writable; a "wait until writable, then sendto" loop never gets to its sendto. WSAEventSelect with FD_WRITE likewise never signals.
  3. Socket handles step by 1 (0x4c450000, 0x4c450001, …). Real SOCKETs are kernel handles and in practice multiples of 4, and some code uses the low bits; stepping by 4 is cheap insurance.
  4. Numeric strings: gethostbyname("192.0.2.7") is logged as refused DNS and fails with WSAHOST_NOT_FOUND, but Windows returns a numeric literal without DNS. gethostbyname("127.0.0.1") reports h_name leonida-offline (Windows gives 127.0.0.1). inet_addr("127.1") returns INADDR_NONE (Windows accepts the short forms, 0x0100007f).
  5. Docs: docs/boot.md:8 and docs/runtime_imports.md:143 still say the executable's ws2_32.dll imports bind to the host's; they'd be stale once this lands.

Items 1 and 5 are the ones I'd fix before merging; 2–4 are smaller fidelity gaps that only matter if the title hits those paths.

AI-assisted. Synthetic inputs only, no game files.

@oVolkra

oVolkra commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested fcf3fc1a3 merged on main 4da521de3 on RTX 3060, driver 617.14, Windows 11 (MSVC 14.44, RelWithDebInfo): pass, with the retail 1.0.2.1 executable (SHA-256 e95020b2…a08993), static only.

gta6rt --dry-run on game_scarlett_master.exe main main + this PR
ws2_32.dll imports bound to a shim 0 25
imports bound to a shim, all DLLs 54 79
imports bound to the host 432 407
unimplemented 29 29
exit code 0 0
  • All 25 ws2_32 imports move from the host to the shim, and the 25 removed from the host column match. The four package DLLs' counts don't change.
  • The trace has 5 map events, 1 exit, no exception.
  • ws2_32_offline_test: 147 checks, 0 failed.

Not covered: --init and --run were not run, so this shows how the imports bind, not what the title does with them. The full ctest was not run. The GPU plays no part in a dry run.

AI-assisted: built, run and written with Claude Code (Claude Opus 5.5); the numbers above are its unedited output.

@AirKyzzZ

Copy link
Copy Markdown
Contributor

Tested fcf3fc1a3 on RTX 2060 (NVIDIA 566.14), Windows 10 22H2, clang-cl 23.1.6 + lld-link, SDK 10.0.26100: pass

Built gta6rt, ws2_32_offline_test and winhttp_offline_test at the head as is, no clang-cl warnings from ws2_32_offline.cpp or its test. ctest -R "^(ws2_32_offline|winhttp_offline)$": 2/2 pass, ws2_32_offline_test 147 checks, 0 failed. The same test linked without shims/ws2_32_offline.cpp (registry only, as on main): 10 checks, 8 failed, so it is not model-only. No game files. AI-assisted (Claude Code).

@emirhan-karaca
emirhan-karaca force-pushed the fix/ws2-32-offline-shim branch from fcf3fc1 to 32b235b Compare November 23, 2026 16:39
@emirhan-karaca

Copy link
Copy Markdown
Contributor Author

Thanks @hiddenblur for the thorough code review and edge-case probes, @oVolkra for confirming all 25 retail game_scarlett_master.exe ws2_32.dll imports move from host to shim in --dry-run, and @AirKyzzZ for the clang-cl 23.1.6 verification!

Rebased cleanly onto main (8575d36ed, which includes #6715) and addressed all five items from @hiddenblur in 32b235b37:

  1. Prevent blocking spin in recv* / accept: blocking bound UDP recv/recvfrom/WSARecv/WSARecvFrom release the lock before sleeping — honouring capped SO_RCVTIMEO (up to 10 ms) with WSAETIMEDOUT, or sleeping 1 ms with WSAENETUNREACH when no timeout is set; blocking listening accept/WSAAccept sleep 1 ms before WSAENETUNREACH. Non-blocking calls still return WSAEWOULDBLOCK immediately.
  2. Bound UDP writability: select (writefds), WSAPoll (POLLWRNORM), and WSAEventSelect (FD_WRITE, both bind-then-select and select-then-bind) now report bound SOCK_DGRAM sockets as writable while keeping unconnected SOCK_STREAM non-writable.
  3. 4-aligned SOCKET handles: synthetic handles now step by 4 (0x4C450000, 0x4C450004, …) to match Windows kernel handle alignment.
  4. Numeric gethostbyname & short inet_addr forms: ws_inet_addr accepts Windows/BSD 1–4 part decimal/hex/octal forms (e.g. 127.1 → 127.0.0.1) while inet_pton remains strict dotted-quad; ws_gethostbyname resolves numeric IPv4 literals (e.g. 192.0.2.7, 127.0.0.1) in-process via per-thread FLS hostent storage with the literal in h_name and zero refused-DNS logging.
  5. Docs updated: updated docs/boot.md and docs/runtime_imports.md (including a new Winsock2 offline section alongside WinHTTP offline).

Re-verified locally (g++ 16.2.0, -Wall -Wextra -Wconversion -Wsign-conversion -Werror):

  • GREEN: ANSI 3/3 PASS (158 checks, 0 failed) and UNICODE 1/1 PASS (158 checks, 0 failed).
  • RED control (without ws2_32_offline.cpp): exit=1 (10 checks, 8 failed).
  • Static checks: nm -u ws2_32_unicode.o shows 0 __cxa_guard_*, 0 _tls_index, 0 host ws2_32 symbols; objdump -p shows only KERNEL32.dll and msvcrt.dll.

@dcastell1

Copy link
Copy Markdown
Contributor

Tested on RTX 5090, 621.24, Windows 11: pass. ws2_32_offline → 1/1 passed (0.10 s), and the real image shows exactly what the shim claims:

              shim  host  module  unimplemented
before         53   432     72         30
with #6943     78   407     72         30

+25 shim, −25 host, and grep finds 25 WS2_32/ws2_32 lines of the shim kind, so it is those 25 imports moving off the generic host fallback and nothing else. Exit 0, empty stderr.

@Roberto0953

Copy link
Copy Markdown
Contributor

Tested fcf3fc1a3 merged on main 8575d36ed with the retail 1.0.2.1 executable (own copy, SHA-256 e95020b2…a08993), Windows 11 Pro (build 26300), Intel i7-14700K, MSVC 14.44 RelWithDebInfo: pass, including under --run.

What this does not show: these runs stop at an asset-loading assert soon after WSAStartup, before the title tries to connect, so they show that no host socket opens at startup, not the refusal paths under real traffic. It does make --run safe here without turning the network off, which docs/boot.md and docs/runtime_imports.md still ask for. Once this lands, both could say so.

No game files in this comment. AI-assisted (Claude Code).

MKonline08 pushed a commit to MKonline08/Leonida that referenced this pull request Nov 23, 2026
Integrates upstream PR ItsNotRexed#6943 through 32b235b. Routes mapped Winsock imports to the offline implementation before further boot attempts, matching the repository's no-online rule. Includes its synthetic API tests in the Windows integration build. AI-assisted integration; local fallback-build tests and no-game-data check pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants