Repository navigation
Loader: the mapped game executable owns module TLS index 0 (RT-259) - #4313
mariuslozo-boop wants to merge 4 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:
|
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