Skip to content

clang-cl cross-build: /Zc:threadSafeInit- for the title's TLS-host thread - #7398

Closed
isfcrctfs wants to merge 1 commit into
ProjectLeonida:mainfrom
isfcrctfs:xbuild/threadsafe-statics
Closed

isfcrctfs wants to merge 1 commit into
ProjectLeonida:mainfrom
isfcrctfs:xbuild/threadsafe-statics

Conversation

@isfcrctfs

Copy link
Copy Markdown

Claimed in the coordination issue (#7231).
Depends on: none.

What and why

The clang-cl cross-built runtime faults inside the host on the title's first two shim calls, while a native MSVC build of the same commit runs past both. Measured on 1.0.2.1 under Wine 11.22, cross-built with clang-cl 23.1.5 + lld-link against an xwin SDK 10.0.26100 and Vulkan-Headers 1.4.363:

library_loader.cpp host_module_name:  `names` is null  -> fault reading 0x0   (first GetProcAddress on the title thread)
xmem.cpp note_attributes:             `seen._Myhead` null -> fault reading 0x8 (first XMemVirtualAlloc)

Cause: Clang's thread-safe-static guard compares a static's guard word with the CRT's per-thread _Init_thread_epoch. The loader runs the title on a thread the TLS host created, which never went through this image's CRT thread-attach, so that epoch is still 0 there — every function-local static first touched on the title's thread reads as already-initialized while its storage is zero. Cl's codegen does not misfire on that thread, which is why only the cross build shows it.

The change

runtime/cmake/clang-cl-xwin.cmake appends /Zc:threadSafeInit- to CMAKE_CXX_FLAGS_INIT for the cross build, dropping the guard comparison. One docs/testing.md Known-problems row records the symptom, the cause and the remedy. CMAKE_C_FLAGS_INIT and the MSVC/Windows path are untouched.

Tested

  • Cross-built gta6rt with the flag; the two host faults above are gone and the boot runs on to the title's own assert inside XMemVirtualAlloc's 2 MiB reservation path — no host fault anywhere.
  • --dry-run exit 0 (5 modules, the title at its preferred base 0x140000000), --init exit 0 (DllMain + both TLS callbacks).
  • No GPU needed for any of this; no game data in the diff (scripts/check_no_game_data.py passes).

AI-assisted: yes.

Checklist

  • No game data, keys or decryption anywhere, including logs and reports.
  • No new translator rule.
  • Cross build only; the Windows/MSVC build is unchanged.

…read

The cross-built runtime faults inside the host on the title's first GetProcAddress
and first XMemVirtualAlloc, while a native MSVC build of the same commit runs past
both. Measured on 1.0.2.1 under Wine 11.22:

  library_loader.cpp host_module_name: `names` is null, fault reading 0x0
  xmem.cpp note_attributes:            `seen._Myhead` is null, fault reading 0x8

Cause: Clang's thread-safe-static guard compares a static's guard word with the
CRT's per-thread _Init_thread_epoch. The loader runs the title on a thread the TLS
host created, which never went through this image's CRT thread-attach, so that
epoch is still 0 there: every function-local static first touched on the title's
thread reads as already initialized while its storage is zero. Cl's codegen does
not misfire on that thread, so only the cross build shows it.

Adding /Zc:threadSafeInit- to the cross build's CMAKE_CXX_FLAGS_INIT drops the
guard comparison. The MSVC/Windows build path is untouched.

Tested: cross-built with clang-cl 23.1.5 + lld-link against an xwin SDK
10.0.26100 and Vulkan-Headers 1.4.363; with the flag the boot passes the two
faults above and runs to the title's own assert in XMemVirtualAlloc's 2 MiB
reservation path, with no host fault. Docs row added to testing.md Known problems.

Co-authored-by: DerpSpears <61290890+DerpSpears@users.noreply.github.com>
@isfcrctfs

Copy link
Copy Markdown
Author

Relationship to #7359, so this does not look like a silent duplicate:

#7359 (tedin7) fixes the same root cause the targeted way — it removes nine function-local static guards in gameinput, dxgi_com and xmem, giving the tables constant-initialized null pointers and allocating them on first use under the existing mutexes. That is the more portable fix: it does not depend on a compiler flag and it is harmless on MSVC.

This PR is the blunt counterpart for the cross build only: one flag in runtime/cmake/clang-cl-xwin.cmake that disables the thread-safe-static guard wholesale. It covers sites #7359 does not touch (today: runtime/shims/library_loader.cpp host_module_name, which is the first one hit — the title faults there on its first GetProcAddress, before it ever reaches xmem) and any site added later, at the cost of applying only when building with this toolchain file.

So they compose rather than compete: #7359 alone leaves the library_loader.cpp fault in the cross build; this PR alone leaves the guards in place for anyone building the Windows target by hand with a different invocation.

If the maintainer would rather land #7359 as the single fix and have this one narrowed to the remaining sites, say so and I will rebase this to whatever is left — or close it, if the per-site work ends up covering library_loader.cpp too. First-to-land-wins is fine by me; I would just rather the overlap be visible than discovered later.

No game data in either diff. AI-assisted.

@ciagnij

ciagnij commented Nov 23, 2026

Copy link
Copy Markdown

I reviewed the scope of /Zc:threadSafeInit- at 57243efd. It applies to every first-use static in the cross-built runtime. Some guest-callable paths depend on the compiler's one-time initialization here. For example, the native D3D12 forwarding shim initializes the host DLL handle and the serializer export via function-local statics with no enclosing lock. Concurrent first calls can then race the initialization. The CopyFile2 shim similarly relies on its static guard. This is from source inspection.

I'd favor the per-site follow-up you mentioned alongside #7359. The failing host_module_name map can be a constant-initialized null pointer, with first allocation under its existing lock. The lock and other library-loader statics also deserve a first-touch audit. The existing run_tiny_gdk_load CTest is a promising synthetic check on the affected cross build: it enters the mapped guest and resolves actual host GetProcAddress shims before touching the offline runtime.

@Davidutz19

Copy link
Copy Markdown

Test result for #7398 on the Linux cross build, retail 1.0.2.1 package (own copy, all package hashes match game/xbox-1.0.2.1.json).

base: main@09a92edab + #739857243ef | on: NixOS, clang-cl/lld-link 21.1.8, xwin 0.10.0 (MSVC 14.44, SDK 10.0.26100), Wine 11.21 Staging, GTX 1060 6GB (Pascal), NVIDIA 580.196.07 | gta6rt --run with LEONIDA_D3D12=vulkan

One note for anyone testing: CMAKE_CXX_FLAGS_INIT only applies on a fresh configure. An existing runtime/build/windows keeps its cached CMAKE_CXX_FLAGS, so the flag is silently missing there (my first run showed no change for that reason). Use a new build folder or delete CMakeCache.txt.

AI-assisted (Claude). No game data (no addresses, RVAs, strings or dumps).

@throny throny 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.

Tested 57243ef merged onto main dde82f2 on Windows 11, RTX 4080 610.88: MSVC build unaffected (pass); the cross-build flag adds an init race

  • MSVC 14.44 Ninja build of the merge: 684/684; --dry-run on retail 1.0.2.1 exit 0 (30 WS2_32/WINHTTP/XCurl imports, all shims); --init exit 0, 5 modules. The clang-cl xwin build itself was not tried (no clang-cl here).
  • Defect: /Zc:threadSafeInit- drops init synchronisation for every function-local static in the cross build, and the comment's "each already under a mutex" doesn't hold. xmem.cpp:55 (note_attributes, the function named in the PR) and d3d12_com.cpp:68/:78 declare static std::set seen; before the lock_guard; MSVC STL's std::set constructor allocates its head node, so two threads first reaching them construct it twice (leak or a torn tree). 33 such function-local statics with dynamic init in runtime/src + runtime/shims on main.
  • The cause looks misattributed: cl emits the same guard > _Init_thread_epoch check as clang-cl (MS ABI magic statics), so a zero epoch would misfire with cl too. An epoch of 0 means that thread's TLS block for gta6rt.exe is zero-filled instead of copied from the template (initial value INT_MIN); the CRT doesn't set it on thread attach. The thread_locals in the runtime all start at 0, so they wouldn't show it.
  • Suggest finding why that block is zero (TLS host / Wine) or moving the affected statics to namespace scope, rather than a global flag.
  • AI-assisted (Claude Code).

@isfcrctfs

Copy link
Copy Markdown
Author

@ciagnij — you are right, and I want to answer this properly rather than defend the patch.

Your objection is correct. /Zc:threadSafeInit- is a build-wide switch. It removes the guard from every function-local static in the cross-built runtime, and the two sites you name are genuinely unsynchronised:

  • d3d12_xs.cpp host() — static HMODULE d3d12 = LoadLibraryExA(...) with no lock
  • d3d12_xs.cpp serialize_root_signature() — static auto fn = reinterpret_cast<SerializeFn>(host(...)) with no lock
  • d3d12_xs.cpp host_serializes_1_2() — static const bool supported = [fn]{...}() with no lock
  • file_system.cpp host_copy_file2() — static const CopyFile2Fn fn = []{...}() with no lock

Two guest threads reaching any of those on first use would now race the initialisation. That is a real regression in the cross build and I am not going to pretend otherwise.

The one nuance worth stating, because it is why the flag looked like a fix: the guard is already non-functional for a static first touched on the title's thread. It compares the guard word against the CRT's per-thread _Init_thread_epoch, and the thread the TLS host creates never went through this image's CRT thread-attach, so that epoch is 0 and the static reads as already initialised while its storage is null. That is the fault in the description, not a side effect. So on that thread the flag removes protection that was not protecting anything — but on every other thread it removes protection that is working, which is exactly your point.

Exposure, measured in this tree: 165 function-local statics across runtime/shims/ and runtime/src/, and only four shim files use std::call_once/std::once_flag at all (d3d12_vulkan_device.cpp, dxgi_com.cpp, winhttp_offline.cpp, xgameruntime_user.cpp). So the cited sites are representative, not exceptional.

So I would rather change the PR than argue. Three options, in the order I would pick them:

  1. Narrow it. Drop the global flag and keep only the sites the boot actually needs — library_loader.cpp host_module_name and xmem.cpp note_attributes, both of which are the first two touched and both of which I can give an unguarded constant-initialised pointer plus an explicit check, no lock needed. That is a handful of lines and touches no guest-callable path.
  2. Defer to runtime/shims: remove function-local static guards in gameinput, dxgi_com and xmem #7359. It is the same root cause done per site, which is the correct shape, and it does not need a compiler flag at all. If it lands, this PR should be closed rather than rebased.
  3. Keep the flag and harden the cited sites with explicit call_once, accepting that the list has to be complete — which, at 165 statics, I cannot honestly claim to have verified.

I lean to (1) or (2). If a maintainer says which, I will do it; otherwise I will prepare (1) as the narrower replacement and leave this open only long enough to compare them.

@Davidutz19 — thank you for the independent cross-build run. Your without/with result matches ours exactly (the host_module_name null read first, then the five XMemVirtualAlloc events once it is gone), on a different clang-cl version and a different host, which is the kind of confirmation this needed.

No game data in any of the above. AI-assisted.

@morodirule

Copy link
Copy Markdown

Measured data point from the Wine side (Arch Linux, clang-cl 23.1 + xwin, RTX 4070, own 1.0.2.1 copy): without the flag, gta6rt dies in host_module_name (null guard storage, loader thread) before the title's TLS callbacks complete; with /Zc:threadSafeInit- the same build maps all 5 modules, runs all DllMains + both TLS callbacks, logs XMemVirtualAlloc calls and reaches the title's first code — so the flag does fix the reported crash, on the only configuration that can show it. On the scope objection: I agree a build-wide switch is broad; the scoped alternative is #8195 (SRWLOCK + lazy pointers in library_loader/d3d12_trace, plus a test that zeroes TLS slot 0 on the calling thread), which I reviewed and ran green here. Either unblocks the Wine boot past this fault. No game data. AI-assisted.

@isfcrctfs

Copy link
Copy Markdown
Author

@throny — you are right on the substance, and your diagnosis is better than the one in the PR description. Taking each point:

1. The "each already under a mutex" line in the comment is wrong. xmem.cpp note_attributes and d3d12_com.cpp both declare static std::set seen; before the lock_guard, so the mutex protects the set's contents but not its construction. Two threads first reaching them can construct it twice — and since MSVC STL's std::set allocates its head node in the constructor, that is a leak at best and a torn tree at worst. That is a real defect in the code our own PR names, and it needs fixing whichever way this goes. I am not going to defend the sentence; I will remove it.

2. Your count is more precise than ours. We grepped indented static in the shims and got 165, which was sloppy — it counted static member functions and static constexpr. Your 33 function-local statics with dynamic initialisation in runtime/src + runtime/shims is the right denominator, because those are the only ones that emit a guard at all. Thank you for the correction.

3. The epoch-zero explanation is the part I had wrong, and your version is better. I attributed the misfire to "clang emits a guard cl does not", which does not survive the fact that cl emits the same guard > _Init_thread_epoch check for MS ABI magic statics. Your reading — that an epoch of 0 means the thread's TLS block for the runtime image is zero-filled instead of copied from the template, whose initial value is INT_MIN — explains the same observation without needing a codegen difference, and it explains why the runtime's own thread_locals never showed it: they all start at 0, so a zero-filled block is indistinguishable from a correctly initialised one for every value we happen to use.

That makes the flag a mask over a TLS-block-initialisation bug rather than a compiler workaround, and the correct fix is at that layer. There is a plausible candidate already in flight: #4313's reserve_tls_index0() loads a home clone whose TLS directory points at a 16 KiB template copied from the runtime's own — i.e. it gives the mapped image a real template to be copied from. If your reading is right, that fix should make the guard work and the flag unnecessary.

So I am running exactly that test rather than narrowing the PR further: TLS-index-0 fix applied, /Zc:threadSafeInit- removed, and the two local per-site workarounds reverted so the guard is genuinely in play. Two outcomes:

Either way the answer goes on this PR.

4. Two things worth your attention while that runs:

For the record on the Windows side: your MSVC run (684/684, --dry-run exit 0, --init exit 0) matches what we see on the cross build for those two phases, so the flag is not needed for anything except the two faults in the description.

I will post the run result here. If it comes back "flag not needed", the PR gets closed and the description's diagnosis gets corrected in a comment so the wrong explanation does not outlive the PR.

No game data in any of this. AI-assisted.

@isfcrctfs

Copy link
Copy Markdown
Author

Closing this PR — @throny was right, and the flag has no job once the TLS fix is in. The experiment he asked for settles it, so I am recording the result here rather than leaving the wrong diagnosis attached to a closed PR.

The test: the TLS-index-0 tree (the #4313 port, 54344cfd) built twice from one source tree, identical configure, differing only in /Zc:threadSafeInit-, with the original unmodified function-local statics — the tree carries none of the zero-init workarounds, so the real compiler guard is in play.

Result: both builds reach an identical 19-event frontier — tls_index0, 5 module maps, 4 DllMain, 2 title TLS callbacks, and the five XMemVirtualAlloc attribute events — then the same int3 beyond them. Seven traced runs and four untraced, both builds, same frontier. The flag changes nothing.

Why, measured rather than argued. In the no-flag binary the statics compile to exactly what cl emits: load guard, load _Init_thread_epoch from TEB->ThreadLocalStoragePointer[_tls_index], cmp, jg → _Init_thread_header → construct → _Init_thread_footer. The runtime's own .tls template holds the epoch's initial value 0x80000000 (INT_MIN). A block copied from that template gives 0 > INT_MIN → initialise. A zero-filled block gives 0 > 0 → false, so null storage is used as if it were already initialised. That is the bug, exactly as @throny described it, and it is why the runtime's own thread_locals never showed it — they all start at 0, so a zero-filled block is indistinguishable from a correct one for every value we happen to use.

The TLS fix moves the runtime's TLS to a home clone whose template is a copy of the runtime's own, epoch included, and rewrites _tls_index; every OS-created thread then gets a real template copy. The guard behaves as it does on native MSVC.

Quantified, which is the part that ends the argument: the flag-less build has 63 guarded static initialisations (_Init_thread_header call sites); the flag build has 0. So the flag was de-guarding 63 sites to work around one broken epoch — precisely @ciagnij's objection, and the reason not to keep it.

Consequences, all of which point the same way:

  • The two zero-init workarounds in this branch are symptoms of the same bug and go with the PR. (The xmem one also had a genuine two-pointer construction race.)
  • @throny's static std::set-before-lock_guard point stands as a real defect in a de-guarded build — with the guard restored the CRT serialises construction, so two threads cannot construct twice. Removing the flag removes that defect. It should be remembered if a de-guard switch is ever reintroduced.
  • The per-site hardening I offered earlier is not needed and is not being applied.

Credit: @throny diagnosed it correctly and asked for the right experiment; @ciagnij identified the class of defect the flag introduces; @Davidutz19 independently reproduced the cross-build fault and its disappearance, which is what made the original symptom trustworthy even though the fix was wrong; @vakaobr and @Roberto0953 did the TLS-side work this depends on.

What remains for whoever lands the TLS fix: re-run against it, because host_module_name first becomes reachable once XErrorReport is served — the fault we originally chased is behind the stop we were stuck at. Our measurement of that site was taken on a tree that serves XErrorReport; the guard is the same and the same thread, so the fix covers it, but it is not directly measured in the flag-less build.

One honest caveat: the exit status after the unhandled int3 is not stable under Wine (it starts Wine's debugger; one run exited 1, the rest 3). The frontier up to and including the stop is identical in every run.

No game data in any of the above. AI-assisted.

@isfcrctfs isfcrctfs closed this Nov 23, 2026
dadnotdaddy pushed a commit to dadnotdaddy/Leonida that referenced this pull request Nov 23, 2026
…Init- for the title's TLS-host thread

Squashed from ProjectLeonida#7398 by isfcrctfs, head 57243ef (security scan 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.

5 participants