Repository navigation
Loader: the mapped game executable owns module TLS index 0 (RT-259) - #4313
mariuslozo-boop 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>
|
Independent code read + build/hygiene check at
AI-assisted review. |
Kam471
left a comment
There was a problem hiding this comment.
Built the new fixtures and ran the TLS suite at 9366e54f on Windows 11, RTX 5070 Ti:
loader_tls_index0-> passed;loader_tls_index0_threads-> passed;loader_tls_index0_noreserve-> passed.run_tiny_game_tls-> passed (after building thetiny_gamefixture);run_tiny_tls_ga-> passed;run_tiny_tls_clone_cleanup-> passed.ctest -R tls-> 7/7 passed, 0.80 s total.loader_tls_index0_test.exeneeds its fixture arguments, as documented; the CTest entries supply them.
No blocking issue.
|
Native Windows/MSVC verification at All eight focused CTests passed: I then repeated the thread-index, AI-assisted. |
|
Windows + GPU check (complements the Linux code-read above; this is the Windows/MSVC + GPU dimension). NVIDIA GeForce RTX 5080 (driver 621.01) + AMD Radeon 610M iGPU (driver 32.0.13018.6), Windows 11, MSVC (VS BuildTools 18) + Ninja, RelWithDebInfo, Vulkan SDK headers fetched. Tested head Build: clean (a transient Targeted,
Full suite (
The PR's unstable CI state did not reproduce locally. Synthetic fixtures only, no game files. AI-assisted (opencode); runs on my machine. |
|
Tested
Cause: the test's "live" owner isn't alive. It's Fix in the test (not in the purge): create the live child suspended, so it's alive until the destructor terminates it, whatever its input: diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp
index 6d5a06dd..4fcedf98 100644
--- a/runtime/test/loader_tls_test.cpp
+++ b/runtime/test/loader_tls_test.cpp
@@ -492,17 +492,20 @@ void test_orphan_slot_generation_reuse(const fs::path& dll) {
check(td() == 0, "orphaned worker exit does not dispatch DLL_THREAD_DETACH to the new generation's module");
}
-// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks.
+// Spawns cmd.exe to obtain one guaranteed-dead PID and one guaranteed-live one for the purge-ownership checks. The
+// live one is created suspended: it stays alive until the destructor ends it, whatever its standard input is. (A
+// `timeout /t 30` child is not: timeout.exe exits at once, "input redirection is not supported", when ctest runs the
+// test with redirected input, as it does under -j, so the "live" owner was already dead.)
struct ChildProcess {
HANDLE process = nullptr;
DWORD pid = 0;
- explicit ChildProcess(const wchar_t* args) {
+ explicit ChildProcess(const wchar_t* args, bool suspended = false) {
STARTUPINFOW si{};
si.cb = sizeof(si);
PROCESS_INFORMATION pi{};
std::wstring cmd = std::wstring(L"cmd.exe ") + args;
- if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si,
- &pi))
+ if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE,
+ CREATE_NO_WINDOW | (suspended ? CREATE_SUSPENDED : 0), nullptr, nullptr, &si, &pi))
throw std::runtime_error("CreateProcessW for cmd.exe failed");
CloseHandle(pi.hThread);
process = pi.hProcess;
@@ -546,7 +549,7 @@ void test_purge_ownership_scoping(const fs::path& dll, const fs::path& temp) {
std::printf("\n-- startup purge deletes only ownerless clones --\n");
ChildProcess dead(L"/c exit 0");
dead.wait_exit();
- ChildProcess live(L"/c timeout /t 30 /nobreak > nul");
+ ChildProcess live(L"/c exit 0", true); // suspended: alive until the end of the test
const fs::path clone_root = fs::temp_directory_path();
// An own-PID name stands in for a leftover of a dead run whose PID this process reused: the sweep runs beforeWith it, Everything else in the full run passed (the usual skips: AI-assisted (Claude Code). |
|
I checked whether the existing TEST-899 fixture fix (#4091) also works with RT-259 on native Windows 11 (26200), MSVC 19.44.35227, and the VS 2022 generator (RelWithDebInfo).
This confirms that the already-open #4091 fixture change is compatible with the process-liveness check in RT-259 on this MSVC setup. Native Windows and synthetic fixtures only. AI-assisted. |
|
Tested Clean worktree at
The PR's negative control (the new test failing against main's loader) was not reproduced here because that needs a main-loader build of the test binary; the new tests pass on this one. No game data is involved; the fixtures are the checked-in synthetic AI-assisted. |
# Conflicts: # runtime/src/main.cpp
|
Thanks for the test reports.
AI-assisted (Claude Code). |
|
Tested 28ea6b9 on Windows 10.0.26200, MSVC 14.52 (Visual Studio 18 2026, x64, RelWithDebInfo): pass. No GPU path in these targets. Built That is 5/5 on three consecutive runs of the same set (the reservation is once per process, so the |
|
Tested Worktree at the PR head, runtime built with Commands and results:
|
|
Additional executable-startup validation, AI-assisted with Codex. Tested snapshot
The minimal local adaptation used in subsequent tests was a named export forwarding to the existing error-report implementation: HRESULT WINAPI XErrorReport(HRESULT hr, const char* message) {
return error_report(nullptr, hr, message);
}plus Combining that with the reviewed module-identity changes from #2075 let the title progress to a strict stop at Environment: Windows 11 build 26200, MSVC 14.51, Ninja RelWithDebInfo, Vulkan SDK 1.4.363.0, NVIDIA RTX 5070 Ti / driver 617.14. Offline functional tests only; no GPU performance measurement. Disposable local inputs and diagnostics remain outside git; no game artifacts are attached. |
|
Tested The game's allocator reads its per-thread state from TLS slot 0 directly ( The PR conflicts with Windows 11 26200, AMD RX 9070 XT, MSVC 14.44, Windows SDK 10.0.26100, own Xbox 1.0.2.1 package (with AI-assisted (Claude Code). |
|
Retail boot test (RT-5): own 1.0.2.1 copy, Windows 11, i9-12900KF, RTX 3070 (NVIDIA 617.42), MSVC 2022 RelWithDebInfo, Result: clears stop 4 (the allocator's /GA TLS access violation; the trace now shows Merge note: conflicts with current AI-assisted test run. |
…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>
…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).
… module TLS index 0 (RT-259) Squashed from ItsNotRexed#4313 by mariuslozo-boop, head 28ea6b9 (security scan PASS). Taken instead of ItsNotRexed#7524 for the TLS index 0 fix: ItsNotRexed#7524's head moved past its scanned sha (and grew a DirectStorage bundle), and its mirror scheme keeps two copies of the title's TLS and misses threads that already exist (review on ItsNotRexed#7524). Conflicts: pe_loader.cpp on_host_thread_event keeps main's forget_ended_thread_id / release_existing_blocks_of_this_thread first, then the PR's two-pass kTlsSlotCount loops (so the executable's slot is covered; the off-by-one reported on the PR comes from taking main's bounds). install_on_existing_threads is bounded by kTlsSlotCount too, so threads already running at load() (thread-pool workers) get the executable's slot-0 copy, as main does for every other module; loader_tls_index0_test now checks that load() gave the early thread its copy and that install/uninstall are no-ops there. CMakeLists.txt keeps both test sets; README keeps main's already-running-thread text plus the PR's ordering sentence and index-0 limits.
…oad, not in a function-local static on the title's thread Squashed from ItsNotRexed#7794 by Spacecer2, head 596a207 (security scan PASS). Clean merge. Appended after ItsNotRexed#4313 (the TLS fix it depends on); the branch's other xmem commits do not touch placeholder_api().
Claimed in the coordination issue as: RT-259 (claim).
What and why
Code built with MSVC
/GA(optimised for an executable) reads its thread-local storage asgs:[58h]→[0], without loading_tls_index. That is correct on Windows, because the process executable always gets module TLS index 0. Undergta6rt, though, index 0 belongs togta6rt.exeitself, and the mapped game executable got a helper index./GAcode in the game then read and wrote gta6rt's own block.Reproduced with a 20-line
/GAprogram that sets athread_localto 42:tls_index=0 value=42;gta6rt --runon main:tls_index=6 value=0, exit code 1;tls_index=0 value=42, exit code 0.The change (
runtime/src/pe_loader.cpp,main.cpp,tls_host.cpp):rt::reserve_tls_index0()runs once, from a.CRT$XCTinitializer inmain.cpp. That is before any of gta6rt's own static initializers and threads; checked against the map file and the disassembly.gta6rt_tls_host.dll. The clone's TLS directory points at a 16 KiB export,gta6rt_tls_home_template, filled with a copy ofgta6rt.exe's TLS template.gta6rt.exe's_tls_indexto the home index.kMainImageSlot), through the existing install, thread-event and~Loaderpaths.--runand--initwith the reason, and--dry-runprints a note. Before, such a/GAexecutable silently corrupted gta6rt's own block.gta6rt_tls_host_set_thread_eventexport is refused.Measured facts this relies on are in the comments and in
runtime/README.md:SizeOfZeroFill, hence the 16 KiB array instead of a zero-fill;DllMainruns before the executable's TLS callbacks.Known limits (in the README):
Loadermust callreserve_tls_index0()at process start.%TEMP%until the next run's sweep.run_tiny_game, whose image has TLS.Tested
Windows 11 (build 26300), RTX 5070 Ti (driver 616.92), MSVC 19.44, Vulkan SDK 1.4.363.0, RelWithDebInfo, on
main03b09a08.ctest: 142/142 passed, both serial and-j 8. The skips are the usual ones that need game data, SDL3 or GPU tools.-R "loader_tls|run_tiny" --repeat until-fail:30: all 30 rounds passed.loader_tls_index0: a real/GA /MDfixture,tiny_tls_ga.dll, checked from its machine code. It reads 42 at slot 0 on the loading thread, an older thread and new threads. It also checks that the EXE's own block moved by pointer identity, and the home template's size and content.loader_tls_index0_threads: a reservation while another thread keeps creating threads, a thread with no TLS array yet, and code that runs before the helper's thread attach (tiny_thread_hook.dll).loader_tls_index0_noreserve: a map without the reservation gets a helper index.run_tiny_tls_ga:--runand--initon the fixture, and the refusal path (TMP and TEMP naming a missing folder).run_tiny_tls_clone_cleanup: no clone files are left after--dry-runand--init, and the next run sweeps the home clone.tests/test_*.pythat CI runs passed, except 5 that fail identically on cleanmainon this machine (Wine,llvm-mc, the game-data scan, saves and the progress dashboard).Reviewed twice by an independent reviewer before this PR.
zlib_inflate, which made the original lazy move unsafe. That led to the startup reservation.Checklist
docs/design.md, with how it was confirmed. (Not applicable: no translator change.)AI-assisted (Claude Code). No game files.
🤖 Generated with Claude Code