Skip to content

Loader: the mapped executable owns module TLS index 0, including threads that were already running (RT-259) - #8622

Closed
isfcrctfs wants to merge 2 commits into
ItsNotRexed:mainfrom
isfcrctfs:tls-slot0-port
Closed

isfcrctfs wants to merge 2 commits into
ItsNotRexed:mainfrom
isfcrctfs:tls-slot0-port

Conversation

@isfcrctfs

Copy link
Copy Markdown

This is a continuation of #4313 by @mariuslozo-boop, which its author closed unmerged and invited someone to take over. It carries the PR's real intent onto current main and adds the correction @Roberto0953 posted in that discussion. @vakaobr found the divergence that made the correction necessary. The design and the fix are theirs; this branch only carries them forward.

What this covers

reserve_tls_index0() moves gta6rt.exe's own static TLS to a helper "home" index so a mapped game executable can hold module TLS index 0, as a Windows process image does (RT-259). The executable takes kMainImageSlot (kMaxMappedTlsModules), not one of the helper slots.

The correction

install_on_existing_threads() gives the loader's module-TLS block to threads that were already running when load() ran; threads started later get theirs from the helper DLL's DLL_THREAD_ATTACH. Its guard read m.tls_slot >= kMaxMappedTlsModules, which is exactly the executable's slot, so the executable was skipped: a thread-pool worker that was already running when the game was mapped kept whatever was in slot 0, and /GA code on it read the wrong block. The guard now uses kTlsSlotCount, the number of valid slots.

The test change restores the contract main documents: load() itself gives an already-running thread its copy, and install_tls_for_thread() / uninstall_tls_for_thread() are no-ops on such a thread. The early-thread checks were still written for the previous contract and passed only because the guard skipped slot 0.

Contents

  • runtime/src/pe_loader.cpp - the guard covers kTlsSlotCount.
  • runtime/test/loader_tls_index0_test.cpp - the early-thread checks assert the load()-installs-the-copy contract.
  • The rest is Loader: the mapped game executable owns module TLS index 0 (RT-259) #4313 squashed (66a7dbc1, a2542ccd, 9366e54f) onto current main. The PR head 28ea6b97 was not used: its merge carries unrelated mods work.

Testing

  • loader_tls_index0 - 40 checks pass, including the new early-thread checks.
  • A/B with the old guard: the same test fails exactly on the two new checks ("load() gives a thread that was already running its own copy in slot 0" / "install_tls_for_thread is a no-op there"), which is the regression this correction closes.
  • loader_tls, loader_tls_index0_threads, loader_tls_index0_noreserve, run_tiny_tls_clone_cleanup - pass.
  • run_tiny_tls_ga - the TLS phase passes (the /GA fixture reads 42 on its own thread and on a second thread with _tls_index == 0, and the trace records the tls_index0 move). Its missing-TMP subtest fails under Wine: Wine's GetTempPathW falls back to C:\users\...\Temp when TMP/TEMP name a missing folder, so the reservation cannot fail as the check expects. Native Windows returns the missing path. Environmental, not the loader.
  • Boot: the title no longer hits the TLS access violation; the trace records the tls_index0 move, and the first blocking event after it is the title's XGameRuntimeInitialize failure path (an int3; the xgameruntime shim does not serve XErrorReport). That is the same stop the rebased branch reached before this correction, and it sits before any mapped /GA code runs on a worker thread.

Attribution

No game data is included in this PR; the fixtures are ordinary test binaries. AI-assisted.

port and others added 2 commits November 23, 2026 09:55
…table (RT-259)

Squash of 66a7dbc..9366e54 (head 28ea6b9, branch mariuslozo-boop:rt/exe-tls-slot0).
…block too

Continuation of ItsNotRexed#4313 by @mariuslozo-boop, closed unmerged with an invitation to take it over. Carries the PR's
real intent onto current main, plus the correction @Roberto0953 posted in that discussion. @vakaobr found the
divergence that made the correction necessary. The design and the fix are theirs.

install_on_existing_threads() gives the loader's module-TLS block to threads already running when load() ran.
Its guard read `m.tls_slot >= kMaxMappedTlsModules`, which is exactly the executable's slot (kMainImageSlot ==
kMaxMappedTlsModules), so the executable was skipped: a worker already running when the game was mapped kept
whatever was in slot 0 and /GA code on it read the wrong block. The guard now uses kTlsSlotCount, the number of
valid slots.

The test change restores the contract main documents: load() itself gives an already-running thread its copy, and
install_tls_for_thread()/uninstall_tls_for_thread() are no-ops there. The early-thread checks were still written
for the previous contract and passed only because the guard skipped slot 0.

Co-authored-by: mariuslozo-boop <mariuslozo-boop@users.noreply.github.com>
Co-authored-by: Roberto0953 <Roberto0953@users.noreply.github.com>
Co-authored-by: DerpSpears <61290890+DerpSpears@users.noreply.github.com>
@lohant27-netizen

Copy link
Copy Markdown

Tested f2a848a6c on Windows 11 (10.0.26300), NVIDIA GeForce RTX 5070 (driver 32.0.16.2101, subgroup 32), MSVC with SDK 10.0.26100, Release, merged onto main 867d922f0 together with #8599, #8589, #8591, #8620, #8569 and #8622 (no conflicts): pass.

@evilclanker9000

Copy link
Copy Markdown
Contributor

Tested f2a848a6c (this head) on Windows 11 26200, RTX 5080 (NVIDIA 616.92), MSVC 2022 RelWithDebInfo, own retail 1.0.2.1 copy, LEONIDA_D3D12=vulkan, gta6rt --run --trace.

Before (main 867d922f0, same machine and build settings): --run maps 5 modules, runs the title's TLS callbacks and its entry point; the five startup XMemVirtualAlloc reservations record their guest callers, and the run then ends with a read of 0xffffffffffffffff (0xC0000005) straight after the fifth one, i.e. the RT-259 fault.

With this head: that fault is gone, all five startup reservations succeed, and the run goes on into the title's CRT and stops at 0x80000003 right after [rt] loader: GetProcAddress(xgameruntime.dll, XErrorReport): not served. So the next blocker once this lands is the missing XErrorReport export (the row-3 stop, #6582), not TLS.

AI-assisted.

@isfcrctfs

Copy link
Copy Markdown
Author

Closing this in favour of #8379 (@KevinPratap), which @lohant27-netizen is right to flag: it was opened 32 minutes earlier (18:36 vs 19:08), touches the same 13 files, is the same size (+1278/-77 vs +1269/-74), and — checked rather than assumed — it also carries the kTlsSlotCount guard, so it has the existing-thread correction that @Roberto0953 posted. There is no version of this where two identical takeovers of #4313 both land.

@lohant27-netizen and @evilclanker9000 — thank you both for testing it on hardware we do not have. Your two results together are the cleanest confirmation this fix has had: @evilclanker9000's before/after is exactly the mechanism — the read of 0xffffffffffffffff straight after the fifth reservation on main, gone with the branch, and the run continuing into the CRT until XErrorReport stops it. That is what the fix is supposed to do, measured on a second machine.

One thing worth carrying over to #8379. The reason this branch is a correction of #4313 and not just a rebase is a specific defect @vakaobr found and @Roberto0953 fixed: install_on_existing_threads() gated on m.tls_slot >= kMaxMappedTlsModules, which is exactly kMainImageSlot, so an executable at index 0 was skipped on threads already running when load() ran. A rebase that keeps that guard looks correct and passes the old tests, because the old tests were written for the pre-load()-installs-the-copy contract and passed because the guard skipped slot 0.

So the useful evidence is the A/B: with the old guard and the corrected tests, loader_tls_index0 is 40 checks, 2 failures — precisely "load() gives a thread that was already running its own copy in slot 0" and "install_tls_for_thread is a no-op there". With the corrected guard, 40/40. If #8379's tests do not include those two checks, that is the one thing worth taking from here, because without them the correction can be silently reverted and the suite stays green.

Our branch is isfcrctfs/Leonida:tls-slot0-port @ f2a848a6 if anyone wants the two test assertions; take them freely, no attribution needed beyond what the PR already carries.

@mariuslozo-boop wrote the original; @Roberto0953 the correction; @vakaobr found the divergence. None of that changes with which PR carries it.

AI-assisted.

@isfcrctfs isfcrctfs closed this Nov 23, 2026

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

Read the whole TLS path (no Windows here, so this is a code read only). The move is sound on the invariants that matter; two small things at the end.

What I checked

  • Swap and free symmetry. move_index0_on_this_thread swaps the two TEB pointers and then writes home into the owner's _tls_index. The two blocks were allocated with the owner's size (the clone's TLS directory is rewritten to the owner's SizeOfZeroFill before it is loaded, and reserve_index0 refuses the move when the clone's raw+zero-fill does not match), so at thread exit the loader's per-module free takes slots[0] (now the clone's block) for gta6rt.exe and slots[home] (now the owner's live block) for the clone. Both pointers come from the same loader allocation path with the same size, so neither free is a size mismatch.
  • New threads. gta6rt_tls_home_template is a real 16 KiB array in the clone's file, filled with a copy of the owner's raw template by make_home_clone_image, and the clone's TLS directory points at it, so a thread started later gets the owner's initial values, not zeros, at home — which is what the owner then reads from its first instruction.
  • Ordering. The only thread that can have run the owner's code before the move is the one doing it, and move_index0_on_this_thread is noinline with no slot address held across the swap, so the MSVC &ThreadLocalStoragePointer[_tls_index] caching you describe cannot bite on the current thread.
  • No DllMain TLS. tls_host.cpp's DllMain only reads the plain g_thread_event and calls out; loading the home clone runs DLL_PROCESS_ATTACH before any callback is installed, and the DLL creates no threads. That closes the one way a second thread could appear inside reserve_index0.
  • Static init order. g_index0 and the std::array<std::atomic<...>> tables are constant-initialized, and std::mutex/std::atomic have constexpr constructors, so the .CRT$XCT initializer is safe ahead of this TU's dynamic initializers. The g_tls_clones heap allocation and the never-destroyed note are the right call given the atexit ordering.

Two nits

  1. process_alive (pe_loader.cpp, the new GetExitCodeProcess check) is ambiguous for a process that exited with code 259: that is STILL_ACTIVE, so such a clone owner is treated as alive forever and its file is never swept. WaitForSingleObject(p, 0) == WAIT_TIMEOUT answers the question without the collision (and still covers the "handle held by a waiting parent" case the comment describes). Cheap to switch, and it makes the sweep exact.
  2. reserve_tls_index0 can return a reason string on every start where the owner's template does not fit the 16 KiB array, and main.cpp turns that into a hard error for an EXE with TLS that did not get index 0 — correct — but the same string is what a title sees when the process simply was not started through the CRT initializer ("reserve_tls_index0 was not called at process start"). Worth wording the second case as a runtime bug ("the runtime's index-0 reservation did not run") rather than letting it read like the title's fault.

I could not run loader_tls_index0 here (Windows-only), so the above is a read; the test's own assertions (index 0 held by the mapped EXE, clones cleaned up) are the right shape.

AI-assisted. macOS 27.2.1 arm64; no Windows, no game files.

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.

4 participants