Repository navigation
Loader: the mapped game executable owns module TLS index 0 (RT-259, takeover of #4313) - #8379
KevinPratap wants to merge 9 commits into
Conversation
Windows gives the process executable module TLS index 0, and MSVC code built with /GA reads TEB->ThreadLocalStoragePointer[0] without loading _tls_index. The loader gave a mapped EXE a gta6rt_tls_host.dll clone's index instead, so a thread_local int v = 42 EXE built /O2 /GA /MD printed tls_index=6 value=0 under gta6rt --run (natively tls_index=0 value=42). Index 0 belongs to gta6rt.exe itself (and to each test EXE that links pe_loader.cpp): measured through _tls_index == 0 before any mapping and the new tls_index0 trace event. All of its own TLS reads go through _tls_index, so the first time an executable is mapped the loader loads one more helper clone (leonida_tls_host_<pid>_home.dll), stops the other threads, swaps slots 0 and the clone's index on every thread and writes that index into the owner's _tls_index. Threads started later swap their own slots first thing in the helper's DLL_THREAD_ATTACH. Both pointers are OS-allocated blocks of that thread and the OS frees every slot at thread exit, so the swap is permanent and nothing is restored. The executable then takes slot 0 (kMainImageSlot) through the existing per-thread install, thread events and ~Loader paths; DLLs keep the helper indices. A second executable mapped while one is live, or a move that cannot be made (a thread kept running in the owner's code for 250 ms), gets a helper index and a stderr note. Measured on Windows 11 26300 to make the swap safe: a new thread publishes its TLS array in the TEB only once it is filled (LdrpAllocateTls), an ending one clears it before freeing the blocks (LdrpFreeTls), LoadLibrary of a TLS DLL updates other threads in one NtSetInformationProcess call, and an EXE's TLS callbacks run after every DllMain for thread attach and detach. Tests: loader_tls_index0 maps tiny_tls_ga.exe (built /GA, code shape checked) next to tiny_tls.dll: 42 on the loading thread, a pre-existing thread and new threads, this EXE's own TLS intact on all of them, two runs in a row, a second executable at once, and a busy thread holding the move off. run_tiny_tls_ga runs it under gta6rt --run and --init and checks the trace names gta6rt.exe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s the EXE's Fixes from the review of the index-0 change: - The lazy move at the first executable map stopped other threads and swapped their slots, guarded by a "thread is inside gta6rt.exe" check. That is not enough: MSVC keeps &ThreadLocalStoragePointer[_tls_index] across calls (zlib_inflate saves it at [rbp-80h] across memset, push_back and inflate_codes, then reads _Init_thread_epoch through it), so a thread stopped in the heap or memset still reads the wrong slot afterwards. The move is now rt::reserve_tls_index0(), done once at process start: gta6rt calls it from a .CRT$XCT initializer, before its own static initializers and before any of its threads; the CRT startup frames above it hold no TLS slot address (checked in the disassembly). It swaps slots 0 and home on the calling thread only; no thread enumeration, suspension, TEB writes or TlsAlloc mark are left. - The home clone's block was the helper's 514 bytes, smaller than gta6rt.exe's 1398-byte TLS. The home clone is now written from gta6rt_tls_host.dll with its TLS directory pointed at a new 16 KiB export, gta6rt_tls_home_template, filled with a copy of the EXE's template and its alignment (LdrpAllocateTls copies End - Start and ignores SizeOfZeroFill, so the zero fill is part of the range). Every new thread then has a fresh copy of gta6rt.exe's TLS at the home index from its first instruction, so no adoption step or window before the helper's DLL_THREAD_ATTACH is left. The mapped template is checked against the EXE's after the load. - The owner is GetModuleHandleW(nullptr) with _tls_index 0, not any module whose index reads 0. - A primary helper without gta6rt_tls_host_set_thread_event is refused. - An executable that does not get index 0 (no reservation, or another executable holds it) is refused by --run and --init with an error; its /GA code would read and write another module's TLS through slot 0. The README no longer says it "reads the first one's slot 0". - Thread attach installs every module's copy before any TLS callback runs, as Windows allocates all blocks before the first DllMain. - Tests: loader_tls_index0 (runs) checks this EXE's block moving from slot 0 to the home index by identity, the home template's size and content, and that the getter reads slot 0 with its _tls_index pointing elsewhere (fails for a non-/GA build of the fixture); loader_tls_index0_threads reserves while threads are being created, with one suspended thread that has no TLS array yet and tiny_thread_hook.dll running test code before the helper's DLL_THREAD_ATTACH; loader_tls_index0_noreserve maps without the reservation. The tiny_tls_ga.cpp comment names the real test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ils cleanly From the second review of 89cec3b8: - The first load_tls_host_clone call is now the home clone, from .CRT$XCT, and it registered cleanup_tls_clones_at_exit with atexit before g_tls_clones was dynamically initialized in .CRT$XCU. The vector's destructor then ran first and the cleanup walked a destroyed vector, so --dry-run, --init and every return-1 path left the slot clones' leonida_tls_host_<pid>_<slot>.dll files in %TEMP%. g_tls_clones is now allocated with the first record and never destroyed, and the atexit handler is registered there. The home clone cannot be deleted while it is mapped (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED), so it is left for the next run's sweep, as the README says. - process_alive() took an ended process as alive while another process still held a handle to it (CMake's execute_process does), so the next run's sweep skipped its files; it now reads the exit code. - reserve_tls_index0 catches what reserve_index0 throws (for example std::filesystem::temp_directory_path) and stores it as the reason, so the reservation fails before main with a message instead of ending gta6rt. The owner's file name is taken before the move, so nothing can throw between the move and recording it. - Tests: run_tiny_tls_clone_cleanup runs gta6rt --dry-run, --init and --dry-run on tiny_tls_clones.exe (three TLS modules, so one slot clone) and checks that each run's PID leaves no clone file but its home clone and that the next run deletes that one; it fails with the old cleanup. run_tiny_tls_ga also runs with TMP and TEMP naming a missing folder: the reservation fails, --run and --init refuse the image with the reason and run none of it, --dry-run maps it with the note. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # runtime/src/main.cpp
…5f378 # Conflicts: # runtime/CMakeLists.txt # runtime/README.md # runtime/src/pe_loader.cpp
…block too After ItsNotRexed#3671 a thread that was already running when load() ran gets each module's TLS block from load() itself, and install_tls_for_thread is a no-op there. install_on_existing_threads stopped at kMaxMappedTlsModules, so the executable in kMainImageSlot (ItsNotRexed#4313) was skipped: such a thread, a thread-pool worker for instance, kept slot 0 as it was and /GA code on it read the wrong block. The check now covers kTlsSlotCount. loader_tls_index0's early thread checks the new contract; without the change it fails (reads no 42 in slot 0 before any install call). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…p the missing-TMP case under Wine - Merged Roberto0953's rebase (main 042c5f3 + install_on_existing_threads covering kMainImageSlot, so a thread already running at load() gets the executable's slot-0 block like every other module's) and then the newest main (clean). - runtime/README.md: the index-0 paragraph said older threads get the copy through install_tls_for_thread(); since main's existing-thread install they get it from load() itself, as the limits section already says. - check_tls_index0.cmake: Wine's GetTempPathW falls back to the user's Temp folder when TMP and TEMP name a missing one, so the reservation cannot fail there; the refusal part is skipped under an emulator (jlric, isfcrctfs). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Independent Windows Sandbox check of head
Only counts and error classes are shared; traces remain local. AI-assisted. |
|
Tested a9085b6 on Arch Linux + clang-cl 23.1/xwin cross build, Wine 11.22: all three loader_tls_index0 scenarios pass — runs 40 checks, threads 6, noreserve 3, 0 failures. This is the exact environment where the unpatched loader dies in the TLS path, so the reservation + existing-thread copy hold up where it matters. Negative control note: the new test links only against the new reserve_tls_index0 symbol, so it cannot run on base code at all (link error) — which itself pins the test to the fix. Reviewed the mechanism: executable owns index 0 at reserve time, already-running threads get every module's block including the exe's, and the early-thread check asserts the new contract. Relevant to the Wine boot stop I reported (null read right after TLS callbacks + XMemVirtualAlloc burst): this is the stop-4-shaped candidate to try once the run gets past it. No game files, synthetic fixtures only. AI-assisted. |
tupacfan04
left a comment
There was a problem hiding this comment.
Real defect: thread detach frees a module's TLS block before the remaining detach callbacks.
runtime/src/pe_loader.cpp:1067-1084 walks slots in reverse and, for each slot, runs run_callbacks(*m, DLL_THREAD_DETACH) and then immediately calls uninstall_thread_block(*m) / release_thread_slot(i). The executable is kMainImageSlot (16) and deliberately runs last, so by the time its TLS callbacks/destructors run, every mapped DLL's block at slots 15..0 has already been freed and each helper's one-byte block restored. A mapped executable TLS destructor that calls into a mapped DLL with static TLS therefore reads the helper's small block (or nothing) instead of the DLL's copy, and can write past it. Windows keeps every module's TLS block alive until all DLL_THREAD_DETACH notifications complete, and frees them afterwards with LdrpFreeTls.
The existing-thread path has the same ordering problem: release_existing_blocks_of_this_thread (:985-1011) removes the blocks installed for threads that predate load() before the main slot loop. If the executable was loaded after the thread, its existing block is handled there rather than last.
Fix: make detach two-pass, mirroring attach — (1) run all callbacks only, DLL slots in reverse and the executable last (existing-thread blocks in the same order), then (2) uninstall/release every slot after all callbacks have returned.
Test gap: runtime/test/loader_tls_index0_test.cpp's EarlyThread (:213-262) covers existing-thread data and the install/uninstall no-op, but has no TLS callbacks; tiny_tls_cb_only is not used, and no test has an executable/DLL detach callback call into another mapped module with TLS. The install path is covered, and install_on_existing_threads uses kTlsSlotCount (:857), so the earlier kMainImageSlot omission is fixed. Synthetic only; no game files. AI-assisted (OpenCode).
|
Tested
|
|
Wine check of this head ( Setup: Linux (Arch), Wine 11.22, RTX 5060 Ti with NVIDIA 620.70.06. Cross build with clang-cl 23.1.5 and xwin SDK 10.0.26100 (RelWithDebInfo). Own Xbox Series 1.0.2.1 copy.
So under Wine 11.22 on NVIDIA this head does what the description measured on Windows: stop 4 is gone and the next stop is AI-assisted (Claude Code). I read the full diff before building it. |
|
checked: #8379 — the Reported by #8452 as 5/5 with a different faulting address each
Result: 5/5 reach the same place and none fault at
The The stop each run reaches is the one #8452's comment predicts next:
Nothing changed in the tree for this check beyond the merge; I am not touching the PR. Outcome detail only, no game data (RVAs of the host runtime and the two stop addresses are the ones already in the |
…gainst main Update docs/retail_boot_chain.md "What clears it" column against current main: - Stops 1, 2, 6, 10, 11 landed on main (ItsNotRexed#6919, 042c5f3: physical pages, 2 MiB pages, and placeholder reservations). - Stop 3 landed on main (e417570: XErrorReport in runtime/shims/xgameruntime.cpp). - Replace closed unmerged PR ItsNotRexed#4313 (Stop 4) with tracking open PRs ItsNotRexed#8379, ItsNotRexed#7524. - Replace closed unmerged PR ItsNotRexed#4348 (Stop 5) with active takeover PR ItsNotRexed#8461, ItsNotRexed#7784. - Link open tracking PRs for Stops 7, 9, 12 (ItsNotRexed#8851, ItsNotRexed#9061, ItsNotRexed#2490, ItsNotRexed#9045, ItsNotRexed#8414). Addresses agulerman's finding in ItsNotRexed#8868.
Loader: the mapped game executable owns module TLS index 0 (RT-259, takeover of ItsNotRexed#4313) Fork integration. AI-assisted (Codex).
|
checked: #8379 | independent run on the retail executable, own 1.0.2.1 copy | on: Windows 11, RX 9060 XT (RDNA4), MSVC 19.44, Vulkan backend | base: main 867d922 + this diff applied cleanly (git apply, 13 files) Result, same command shape as the boot-chain runs (
Same stop offset (+0x5a91c21) as the RTX 5070 verification in #8452, so the handover holds on RDNA4 as well. Next blocker after this is the XErrorReport lookup / whatever asserts into +0x5a91c21. AI-assisted check (Devin). No game data in this comment: offsets and event kinds only. |
Hold the TLS slot-zero change pending resolution of the thread-detach review. An executable callback can run after DLL TLS blocks have been released, a case the passing slot-zero tests do not exercise. Fork integration. AI-assisted (Codex).
|
Tested
Outcomes only; no game data. AI-assisted. |
|
Tested this PR's head (a9085b6) with the retail exe (SHA-256 e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993) on RTX 5080, Windows 11, LEONIDA_D3D12=vulkan, on main 867d922 + #6582.
It merges cleanly onto current main (6312c05). |
|
Heads-up: part of this landed directly on AI-assisted (Claude Code). agent: yes |
|
Code review of What is right
What is still wrong / unhandled at
|
|
Closing: the retail boot no longer needs this. On today's Thanks to everyone who tested this branch, and to the reviewers. Before this approach comes back, the open review points would need to be addressed:
The branch stays at |
LaugeM
left a comment
There was a problem hiding this comment.
Read against main 5d74c27, which now has b7a3fed (the gs:[58h] rewrite to a TlsSlots view). The branch still merges without a text conflict, but the two mechanisms disagree in the merged tree, and this branch has to pick one before it lands.
Conflict with b7a3fed
runtime/src/main.cpp:174refuses--runand--initwhenever the executable has TLS andtls_index != 0. Onmainthat case is served:Loader::initialize_tls(mainpe_loader.cpp:1512) rewrites the reads and the image runs. Merged, a failed reservation exits 1 wheremainruns the title today. The failure can be a missing or unwritable TMP, whichcheck_tls_index0.cmakeexercises, or a host TLS over 16 KiB. Either keep the rewrite as the fallback and refuse only whenmain_module.tls_index != 0 && main_module.tls_ga_slot == rt::kNoTlsIndex, or remove the rewrite in this PR. Keeping both as they are leaves dead code on the normal path and a refusal that contradicts it.- If the rewrite stays as the fallback, three more things change with it. The stderr note at
pe_loader.cpp:1724("its code built with /GA would use another module's TLS") is no longer true for a rewritten image. Theruntime/README.mdparagraph saying such an executable is refused needs the same correction. The missing-TMP half ofcheck_tls_index0.cmakewould then expect a run, not exit 1. - In the merged
initialize_tls, this PR declaresntat the top of the function and main's block declaresconst auto* ntagain inside its braces. That is C4456 at/W4, not an error. Reuseexecutablethere.
Why this should still land instead of being closed
The rewrite on main has two gaps that this branch does not have:
- Threads that were already running when
load()was called get no view.install_on_existing_threads(mainpe_loader.cpp:656-746) writes the block intoslots[tls_index]only, andTlsSlots[ga_slot]stays null on those threads. Rewritten code running there (the comment at main:558-561names thread-pool workers that run the task queue's callbacks) loads a null view and faults. This branch's existing-thread path covers slot 0 (pe_loader.cpp:855,kTlsSlotCount). ga_slotis a singlestatic const DWORD ga_slot = TlsAlloc()(mainpe_loader.cpp:1513) shared by every executable. A second rewritten executable'sTlsSetValuereplaces the first one's view on every thread it installs on.
Both are confirmed from the code. Whether retail reaches either one is unmeasured.
Still open at a9085b66
The detach ordering (pe_loader.cpp:1067-1084, @tupacfan04) and process_alive with exit code 259 (:245-256, @isfcrctfs) are both unaddressed. The retail runs above were made on bases before b7a3fed, so a rebase and one retail re-run would show what the branch adds on top of main.
AI-assisted review (Opus 5.5). Read the diff against main; not built (checked the merge with git merge-tree against upstream main 5d74c27 and read the merged pe_loader.cpp and main.cpp).
Takeover of #4313 by @mariuslozo-boop, who closed it today while stepping away and invited anyone to take it over (closing note). Claimed in the coordination issue: takeover claim. Item: RT-259 (originally claimed here).
This branch is their last head,
a9085b66, unchanged: every commit keeps its original author. That head already contains @Roberto0953's rebase ontomain(withinstall_on_existing_threadscoveringkMainImageSlot) and a clean merge ofmaindde82f27. The design, the measurements behind it and the known limits are in #4313's description and inruntime/README.md. In short: MSVC/GAcode reads its TLS from module index 0 without loading_tls_index. Undergta6rt, index 0 belonged togta6rt.exeitself, so the mapped game read and wrote gta6rt's block.reserve_tls_index0()moves gta6rt's own TLS to a helper clone at process start and gives slot 0 to the mapped executable.Why it matters now
It is retail boot stop 4 in
docs/retail_boot_chain.md. On currentmainit is the first stop ofgta6rt --runon the retail executable. Measured on my own 1.0.2.1 copy (outbound network blocked,LEONIDA_D3D12=vulkan, RTX 4050 Laptop, NVIDIA 592.82, Windows 11):maindde82f27e: after the startupXMemVirtualAlloccalls, an access violation in the title reading0xffffffffffffffff.tls_index0event, that fault is gone, and the run reaches xgameruntime's startup, where it stops onXErrorReport(xgameruntime: serve XErrorReport (rebase of #5312) #6582).Tested on this head
Windows 11, RTX 4050 Laptop (NVIDIA 592.82), MSVC 14.44, RelWithDebInfo + Ninja, head
a9085b66:ctest -R "loader_tls|tls|run_tiny": 22/22 pass, includingloader_tls_index0,_threads,_noreserve,run_tiny_tls_gaandrun_tiny_tls_clone_cleanup.ctest -j 8: 260 of 267 pass (22 of those are the usual skips for game data, SDL3 or GPU tools), 7 fail. All 7 are D3D12-layer tests, and this branch changes no D3D12 file (its 13 files are the loader,main.cpp,tls_host.cpp, the startup trace header, CMake, the README and the TLS tests and fixtures).mainbuild (8575d36e):d3d12_vulkan_device,d3d12_texture_tiles,d3d12_method_variants,d3d12_indirect_dispatch_count,d3d12_heap_propertiesandd3d12_indirect_rt.d3d12_indirect_dispatch_countandd3d12_indirect_rtare two of the four failures TEST-1698 already lists for NVIDIA.d3d12_depth_resolvepasses on8575d36e, but on this branch it fails under ctest withExecuteCommandLists: list 0 is invalid; refusing batch, the check d3d12: reject null arrays and invalid lists in ExecuteCommandLists #6610 added onmainafter8575d36e. It fails the same way run by hand (exit 1). The test executes a list whoseClosefailed and expects the list's valid commands to run, which d3d12: reject null arrays and invalid lists in ExecuteCommandLists #6610 now refuses. It is not from this branch, and d3d12_depth_resolve: check refused resolves against a destination cleared in its own list (#6610 follow-up) #7905 and d3d12_depth_resolve: read a refused resolve's destination through a list of its own #7930 fix the test.tls_index0event, stop 4 gone, next stopXErrorReport.Open
AI-assisted (Claude Code). No game data: the boot results above are outcomes only.
🤖 Generated with Claude Code