diff --git a/docs/boot.md b/docs/boot.md index 7367dd91d7..ec27b31469 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -114,6 +114,17 @@ Read the startup trace first; the first event that is not the expected one is th TLS index. The summary shows the address and phase of the last observed TLS callback (`last_tls_callback` in JSON). The loader records it before invoking the callback, so the record gives no completion result. The loader's own TLS is checked by `run_tiny_game_tls`. + An access violation in CRT startup before the first D3D12 call can be the TLS index instead: code built with + `/GA` reads its thread-local data at module index 0 without `_tls_index`, and index 0 belongs to `gta6rt.exe` + (stop 4 of [retail_boot_chain.md](retail_boot_chain.md)). `load()` rewrites those reads in a mapped executable + so that they reach the image's own block, and every other mapped module with a TLS directory has an index of + its own ([`runtime/README.md`](../runtime/README.md), "PE loader"). The stderr log has one + `[rt] loader: : index-0 TLS reads` line for the executable; `N` 0 on an image that faults there + means its reads have a shape the rewrite does not know. `LEONIDA_TLS_GA_PATCH=0` turns the rewrite off, to + see the stop without it. `loader_tls` checks both ways with a synthetic `/GA` executable mapped beside a DLL + that has TLS of its own, on the loading thread and on a new one, and `run_tiny_game_ga_tls` runs a `/GA` + build of the stand-in game through `gta6rt --run`. Not confirmed here on the retail executable: that needs + game files. 4. **`exception`** — code, `at`, access/address and the stack frames. The loader's vectored handler only records, so the process behaviour is the same with or without the trace. When the report reaches `--limit`, it reserves the final slot for the last observed exception. The trace also includes handled exceptions, so the last diff --git a/docs/boot_leads.md b/docs/boot_leads.md index e949c0dc16..56ec054361 100644 --- a/docs/boot_leads.md +++ b/docs/boot_leads.md @@ -20,11 +20,19 @@ your own copy or with a synthetic test before you build on it, and record the re - **Finding:** code built with `/GA` reads thread-local storage straight from `ThreadLocalStoragePointer[0]` and assumes the executable's own TLS block sits at index 0. Static TLS has to be set up per mapped module, not once. -- **Where:** the retail run on `main` ends in CRT startup with an access violation and 0 D3D12 calls, "the stop-4 - shape (TLS from module index 0)" ([retail_boot_intel_host.md §1](retail_boot_intel_host.md)). The loader already - keeps one TLS host slot per mapped module (`runtime/src/pe_loader.cpp`, `runtime/src/tls_host.cpp`), and the - integration tree carries a fix for stop 4 that `main` does not - ([retail_boot_chain.md](retail_boot_chain.md), row 4). +- **Where:** a retail run on `main` at `867d922f` ended in CRT startup with an access violation and 0 D3D12 calls, "the + stop-4 shape (TLS from module index 0)" ([retail_boot_intel_host.md §1](retail_boot_intel_host.md)). The loader keeps + one TLS host slot per mapped module (`runtime/src/pe_loader.cpp`, `runtime/src/tls_host.cpp`). The integration tree + clears stop 4 with #4313 ([retail_boot_chain.md](retail_boot_chain.md), row 4). +- **Status:** answered on `main` by `b7a3fed28` and `4710549af`, which the measurement above predates; the retail + confirmation is still pending. `load()` rewrites the executable's `mov r64, gs:[58h]` reads so that they reach a + per-thread view with the image's own block at `[0]`, and each other mapped module with a TLS directory has an index of + its own. `loader_tls` checks it with a `/GA` executable beside a DLL with TLS of its own, on the loading thread and on + a new one, and shows the stop with `LEONIDA_TLS_GA_PATCH=0`; `run_tiny_game_ga_tls` runs a `/GA` build of the stand-in + game through `gta6rt --run`. #4313, which #321 and #64 carry, is an alternative design, not a missing fix: the + runtime's own EXE gives up index 0 at process start, so an index-0 read of any shape works without a rewrite. What is + left of this lead is the retail `--run` on current `main` and, if it still stops here, the read shape the rewrite does + not know. - **Implement:** 1. Find the stop-4 fix on the integration tree and compare it with `Loader::initialize_tls` on `main`. 2. Make the executable's slot resolve at index 0 of the thread's TLS array, and give every other mapped module that diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md index 7fd5eef651..da0605bb05 100644 --- a/docs/retail_boot_chain.md +++ b/docs/retail_boot_chain.md @@ -17,7 +17,7 @@ stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX | 1 | The first `XMemVirtualAlloc` calls: two 64 KiB reserve forms, then 2 MiB pages | #6709, #4531 | | 2 | The 2 MiB reserve+commit calls carry attribute words the shim refuses, and `PAGE_GRAPHICS_*` bits (0x800..0x40000) on top of `PAGE_READWRITE` | Local: accept the attribute word, drop the graphics bits and keep the CPU protection. All seven startup allocations then succeed. #6843 measures the attribute words; no PR changes the check yet | | 3 | `xgameruntime.lib`'s thunk treats a missing `XErrorReport` as fatal | #6582 | -| 4 | Access violation in the title's allocator: its `/GA` code reads its TLS from module index 0 | #4313 | +| 4 | Access violation in the title's allocator: its `/GA` code reads its TLS from module index 0 | #4313 in the measured tree: the runtime's own EXE gives up index 0 at process start. `main` has a different fix since `b7a3fed28` (with `4710549af` for threads that were already running): the loader rewrites the executable's index-0 reads so that they reach the image's own block ([boot.md](boot.md) §3, step 3). Checked on `main` with a synthetic `/GA` executable beside a DLL with TLS of its own (`loader_tls`) and a `/GA` build of the stand-in game under `gta6rt --run` (`run_tiny_game_ga_tls`); the retail run was not repeated for this note, it needs game files | | 4a | Wine only, not reached on Windows: `GameInput.dll` ordinal 1, the executable's `GameInputCreate` import (by ordinal, not by name), which the loader looks up as `gameinput.dll!#1`. When `gta6rt` doesn't serve that name, the import binds to the host's `GameInput.dll`. On Windows the installed one answers; under Wine it is Wine's builtin stub, and the title reads through a null pointer right after the call. Measured by hcristosm after stop 4 with stop 5's fix (old upstream PR 4348) merged, so its order against stop 5 is not measured. #127 reproduced it on Wine 11.21 staging: the title's own `int3` 0.65 s after start, before any D3D12 call | #127 (the `#1` alias in the shim table, `runtime/shims/gameinput.cpp`), but only in a `gta6rt` built with the GameInput shim, that is with SDL3: an installed SDL3 3.2 or newer that CMake finds, `-DLEONIDA_SDL3_FETCH=ON` (`scripts/build_runtime.ps1 -FetchSdl3`) or `-DFETCHCONTENT_SOURCE_DIR_SDL3`. A build without SDL3, one with `-DLEONIDA_SDL3=OFF`, and `build_runtime.ps1`'s `cl.exe` fallback have no `GameInputCreate` at all ([gameinput.md](gameinput.md#building)), so they still stop here under Wine. With the shim and the alias, the Wine run went on to stop 6 in hcristosm's measurement | | 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 | | 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 202aa918bb..1d58edccf0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -836,6 +836,17 @@ if(BUILD_TESTING) set_target_properties(tiny_game_fixed PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" ) + # The same game built with /GA, as a title's executable is: its thread_local reads go to module TLS index 0 + # without _tls_index, and under gta6rt index 0 is gta6rt.exe's own (docs/boot_leads.md, BL-1). + add_executable(tiny_game_ga test/fixtures/tiny_game.cpp) + target_link_libraries(tiny_game_ga PRIVATE xgameruntime_stub) + target_compile_definitions(tiny_game_ga PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(tiny_game_ga PRIVATE /W4 /permissive- /utf-8 /EHsc /GA) + # /GA can remove the _tls_index reference that pulls in the CRT TLS directory. + target_link_options(tiny_game_ga PRIVATE /INCLUDE:_tls_used) + set_target_properties(tiny_game_ga PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) @@ -1384,6 +1395,9 @@ if(BUILD_TESTING) # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image. add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $ -- hello 42 tls) add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $ -- hello 42 eh) + # The /GA build of the same game: thread_local on the entry thread and on a thread it starts, through index-0 + # reads, while index 0 holds gta6rt.exe's own TLS. + add_test(NAME run_tiny_game_ga_tls COMMAND gta6rt --run $ -- hello 42 tls) # BUILD-1457: the stack a game thread gets. gta6rt_stack reads SizeOfStackReserve from the built loader (nothing # is run); run_tiny_game_stack asks Windows, on the entry thread and on a thread created with dwStackSize 0. add_test(NAME gta6rt_stack COMMAND "${CMAKE_COMMAND}" diff --git a/runtime/test/fixtures/tiny_ga_tls.cpp b/runtime/test/fixtures/tiny_ga_tls.cpp index 493ec8b975..01dd03ea69 100644 --- a/runtime/test/fixtures/tiny_ga_tls.cpp +++ b/runtime/test/fixtures/tiny_ga_tls.cpp @@ -7,6 +7,9 @@ __declspec(thread) int g_ga_tls_value = 7; extern "C" __declspec(dllexport) int ga_tls_get() { return g_ga_tls_value; } extern "C" __declspec(dllexport) void ga_tls_set(int value) { g_ga_tls_value = value; } +// Where this code looks for the variable on the calling thread: ThreadLocalStoragePointer[0] plus the variable's +// offset, with no read of the variable itself. The test uses it to tell whose block index 0 resolved to. +extern "C" __declspec(dllexport) void* ga_tls_address() { return &g_ga_tls_value; } int main() { return 0; diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp index c0088eea40..cd456f4979 100644 --- a/runtime/test/fixtures/tiny_game.cpp +++ b/runtime/test/fixtures/tiny_game.cpp @@ -6,6 +6,8 @@ // calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's // run_tiny_game_tls and run_tiny_game_eh): `tls`, thread_local on the game's own threads, which needs the loader's // per-thread TLS (gta6rt starts main on a separate thread); and `eh`, a C++ exception caught inside the image. +// run_tiny_game_ga_tls runs `tls` on tiny_game_ga, this file built with /GA: its thread_local reads then take module +// TLS index 0 without _tls_index, as a title's executable does, and under gta6rt that index is gta6rt.exe's own. // A third, `game-file` (run_tiny_game_dir), reads GAME:\tiny_game_probe.txt after moving the current directory. // A fourth, `stack` (run_tiny_game_stack), checks that the entry thread and a thread created with dwStackSize 0 // both have 8 MB of stack: a driver compiles shaders on the game's threads (BUILD-1457). Only under gta6rt: run diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp index 133b27c819..26d8461472 100644 --- a/runtime/test/loader_tls_test.cpp +++ b/runtime/test/loader_tls_test.cpp @@ -24,6 +24,9 @@ #include "pe_loader.h" +// The CRT's record of the module TLS index Windows gave this EXE. +extern "C" unsigned long _tls_index; + namespace { namespace fs = std::filesystem; @@ -819,6 +822,163 @@ void test_ga_tls_existing_thread(const fs::path& exe) { for (HANDLE h : {first.go, first.done, second.go, second.done, started}) CloseHandle(h); } +// This EXE's TLS template size, from its own TLS directory: the size of the block Windows puts at its index. +uint64_t own_tls_template_size() { + const auto* base = reinterpret_cast(GetModuleHandleW(nullptr)); + const auto* dos = reinterpret_cast(base); + const auto* nt = reinterpret_cast(base + dos->e_lfanew); + const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; + if (!dir.Size || !dir.VirtualAddress) return 0; + const auto* tls = reinterpret_cast(base + dir.VirtualAddress); + return tls->EndAddressOfRawData - tls->StartAddressOfRawData; +} + +// Sets an environment variable for one scope. An empty value removes it. +struct ScopedEnv { + std::string name, previous; + bool had = false; + ScopedEnv(const char* variable, const char* value) : name(variable) { + char buffer[64] = {}; + size_t size = 0; + had = getenv_s(&size, buffer, name.c_str()) == 0 && size > 0; + if (had) previous = buffer; + _putenv_s(name.c_str(), value); + } + ~ScopedEnv() { _putenv_s(name.c_str(), had ? previous.c_str() : ""); } + ScopedEnv(const ScopedEnv&) = delete; + ScopedEnv& operator=(const ScopedEnv&) = delete; +}; + +// BL-1 (docs/boot_leads.md): code built with /GA reads ThreadLocalStoragePointer[0] and takes the block there for +// its own executable's, while a second mapped module has static TLS of its own. Index 0 of the process belongs to +// the EXE Windows started: this test here, gta6rt.exe in a real run. ga_tls_address() says where the fixture's code +// looks for its variable, so the checks name whose block index 0 resolved to. With the rewrite off it is this EXE's +// block, which is stop 4 of docs/retail_boot_chain.md. As load() leaves the image by default, it is the fixture's +// own block, on the loading thread and on a thread started later, with tiny_tls.dll's block at its own index +// beside it and this EXE's block still at index 0 of the thread's TLS array. +void test_ga_exe_beside_tls_module(const fs::path& exe, const fs::path& dll) { + std::printf("\n-- /GA EXE reading index 0 beside a second TLS module --\n"); + const auto offset_in = [](const void* address, const void* block) { + return static_cast(address) - static_cast(block); + }; + void* const host_block = module_tls_slots()[0]; + const ptrdiff_t sentinel_offset = offset_in(&g_host_tls_sentinel, host_block); + check(_tls_index == 0, "this EXE has module TLS index 0, as the process EXE does"); + check(sentinel_offset >= 0 && static_cast(sentinel_offset) + sizeof(int) <= own_tls_template_size(), + "its own thread-local variable is in the block at index 0"); + + // The fixture as built. Only the address is taken: reading or writing there would use this EXE's TLS. + ptrdiff_t offset = -1; // of the fixture's variable in a TLS block + { + ScopedEnv rewrite_off("LEONIDA_TLS_GA_PATCH", "0"); + rt::Loader loader(exe.parent_path()); + rt::Module& game = loader.load(exe); + check(game.tls_ga_slot == rt::kNoTlsIndex && game.tls_index != rt::kNoTlsIndex && game.tls_index != 0, + "with LEONIDA_TLS_GA_PATCH=0 the fixture is left as built, at a module TLS index that is not 0"); + const auto address = find_export(game, "ga_tls_address"); + offset = offset_in(address(), host_block); + check(offset >= 0 && static_cast(offset) + sizeof(int) <= game.tls_block_size, + "as built, its code looks for its variable in the block at index 0, which is this EXE's (stop 4)"); + check(module_tls_slots()[game.tls_index] == game.tls_block && game.tls_block != host_block, + "while its own block sits at its module index, where that code never looks"); + } + + struct Seen { + int host = -1, host_after = -1; + int game = -1, lib = -1, game_after = -1, lib_after = -1; + void* address = nullptr; // where the fixture's code looks for its variable + void* view0 = nullptr; // [0] of the array that code reads + void* at_index0 = nullptr; // the thread's real TLS array: index 0, the fixture's index, the DLL's index + void* at_game = nullptr; + void* at_lib = nullptr; + ptrdiff_t sentinel_offset = -1; + }; + uint32_t ga_slot = rt::kNoTlsIndex; + { + rt::Loader loader(exe.parent_path()); + rt::Module& game = loader.load(exe); + rt::Module& lib = loader.load(dll); + loader.initialise(); // from here on thread events run both images' TLS callbacks + ga_slot = game.tls_ga_slot; + check(game.tls_index != rt::kNoTlsIndex && lib.tls_index != rt::kNoTlsIndex && game.tls_index != 0 && + lib.tls_index != 0 && game.tls_index != lib.tls_index, + "the EXE and the DLL each get a module TLS index of their own, neither of them 0"); + check(ga_slot != rt::kNoTlsIndex, "by default load() rewrites the EXE's index-0 TLS reads"); + if (ga_slot == rt::kNoTlsIndex) return; // nothing below can hold, and this EXE's TLS must not be written + + const auto game_get = find_export(game, "ga_tls_get"); + const auto game_set = find_export(game, "ga_tls_set"); + const auto game_address = find_export(game, "ga_tls_address"); + const auto lib_get = find_export(lib, "tiny_tls_get"); + const auto lib_set = find_export(lib, "tiny_tls_set"); + const auto lib_watch = find_export(lib, "tiny_tls_watch_thread"); + const auto lib_thread_attach = find_export(lib, "tiny_tls_thread_attach_count"); + const auto lib_thread_detach = find_export(lib, "tiny_tls_thread_detach_count"); + const auto lib_value_at_attach = find_export(lib, "tiny_tls_value_at_thread_attach"); + + const auto look = [&](Seen& seen, int game_value, int lib_value) { + seen.host = g_host_tls_sentinel; + seen.game = game_get(); + seen.lib = lib_get(); + game_set(game_value); + lib_set(lib_value); + seen.game_after = game_get(); + seen.lib_after = lib_get(); + seen.address = game_address(); + auto* view = static_cast(TlsGetValue(ga_slot)); + seen.view0 = view ? view[0] : nullptr; + void** slots = module_tls_slots(); + seen.at_index0 = slots[0]; + seen.at_game = slots[game.tls_index]; + seen.at_lib = slots[lib.tls_index]; + seen.sentinel_offset = offset_in(&g_host_tls_sentinel, slots[0]); + seen.host_after = g_host_tls_sentinel; + }; + + Seen here; + look(here, 11, 22); + check(here.game == 7 && here.lib == 7, "the loading thread reads both templates' value 7"); + check(here.game_after == 11 && here.lib_after == 22, "and its writes to the two modules stay apart"); + check(here.address == static_cast(game.tls_block) + offset, + "the EXE's index-0 read resolves to its own block on the loading thread"); + check(here.view0 == game.tls_block && here.at_game == game.tls_block, + "that block is at [0] of the array its code reads and at its module index"); + check(here.at_lib == lib.tls_block && lib.tls_block != game.tls_block, + "the DLL's block is at the DLL's own index"); + check(here.at_index0 == host_block && here.sentinel_offset == sentinel_offset && here.host == 2 && + here.host_after == 2, + "this EXE's block is still at index 0 of the thread's TLS array, its value unchanged"); + + Seen there; + int attach_inside = -1; + auto body = [&] { + attach_inside = lib_thread_attach(); + look(there, 33, 44); + }; + WatchedThread thread(lib_watch, &body); + thread.join(); + check(there.game == 7 && there.lib == 7, + "a thread started after load() reads both templates' value 7, not 11 and 22"); + check(there.game_after == 33 && there.lib_after == 44, "and its writes to the two modules stay apart"); + check(there.view0 != nullptr && there.view0 != game.tls_block && + there.address == static_cast(there.view0) + offset, + "on that thread the EXE's index-0 read resolves to the thread's own copy"); + check(there.at_game == there.view0, "which is also at the EXE's module index there"); + check(there.at_lib != nullptr && there.at_lib != lib.tls_block && there.at_lib != there.view0, + "the DLL has a copy of its own at its own index there"); + check(there.at_index0 != host_block && there.at_index0 != there.view0 && + there.sentinel_offset == sentinel_offset && there.host == 1 && there.host_after == 1, + "index 0 of that thread's TLS array is its copy of this EXE's TLS, its value unchanged"); + check(attach_inside == 1 && lib_thread_detach() == 1 && lib_value_at_attach() == 7, + "the DLL's TLS callback got that thread's attach and detach, with its copy in place"); + check(game_get() == 11 && lib_get() == 22 && g_host_tls_sentinel == 2, + "the loading thread's three values are unchanged by the other thread"); + } + check(module_tls_slots()[0] == host_block && g_host_tls_sentinel == 2, + "~Loader leaves this EXE's block at index 0"); + check(TlsGetValue(ga_slot) == nullptr, "and takes the EXE's view out of the loading thread"); +} + void print_result() { if (g_failures == 0) std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks); @@ -858,6 +1018,7 @@ int main(int argc, char** argv) { const fs::path ga_exe = tls_dll.parent_path() / "tiny_ga_tls.exe"; check(fs::exists(ga_exe), "tiny_ga_tls fixture exists"); if (fs::exists(ga_exe)) test_ga_tls_existing_thread(ga_exe); + if (fs::exists(ga_exe)) test_ga_exe_beside_tls_module(ga_exe, tls_dll); check(g_host_tls_sentinel == 2, "this EXE's own TLS at module index 0 is untouched"); // The --run path calls cleanup_tls_clones() before ExitProcess because atexit never runs there.