Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,61 @@ if(BUILD_TESTING)
COMMAND loader_tls_test "$<TARGET_FILE:tiny_tls>"
)

# Module TLS index 0 fixture: an EXE built /GA, so its thread_local reads go straight to
# ThreadLocalStoragePointer[0] as a game executable's can. The loader must give a mapped executable index 0;
# loader_tls_index0_test maps it next to tiny_tls.dll and run_tiny_tls_ga runs it under gta6rt. Ordinary test
# code, no game data. The test checks the /GA code shape only where the compiler is MSVC, which implements /GA.
add_executable(tiny_tls_ga test/fixtures/tiny_tls_ga.cpp)
target_compile_options(tiny_tls_ga PRIVATE /W4 /permissive- /utf-8 /EHsc /GA)
set_target_properties(tiny_tls_ga PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
)
add_executable(loader_tls_index0_test
test/loader_tls_index0_test.cpp
src/pe_loader.cpp
shims/registry.cpp
)
target_include_directories(loader_tls_index0_test PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
target_compile_definitions(loader_tls_index0_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
$<$<CXX_COMPILER_ID:MSVC>:LEONIDA_GA_FIXTURE_IS_GA=1>)
target_compile_options(loader_tls_index0_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
# Loaded by the threads scenario before the TLS helper: its DllMain(DLL_THREAD_ATTACH) runs test code first.
add_library(tiny_thread_hook SHARED test/fixtures/tiny_thread_hook.cpp)
target_compile_definitions(tiny_thread_hook PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(tiny_thread_hook PRIVATE /W4 /permissive- /utf-8 /GS-)
set_target_properties(tiny_thread_hook PROPERTIES
OUTPUT_NAME tiny_thread_hook
PREFIX ""
RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
)
add_dependencies(loader_tls_index0_test tiny_tls_ga tiny_tls tiny_thread_hook gta6rt_tls_host)
# Imports tiny_tls.dll and tiny_tls_cb_only.dll, so gta6rt needs a helper clone for one of them
# (check_tls_clone_cleanup.cmake).
add_executable(tiny_tls_clones test/fixtures/tiny_tls_clones.cpp)
target_link_libraries(tiny_tls_clones PRIVATE tiny_tls tiny_tls_cb_only)
target_compile_options(tiny_tls_clones PRIVATE /W4 /permissive- /utf-8)
set_target_properties(tiny_tls_clones PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
)
# One process per scenario: the reservation is once per process. loader_tls_index0 (runs) reserves at start,
# loader_tls_index0_threads reserves while threads are being created, loader_tls_index0_noreserve never does.
foreach(scenario runs threads noreserve)
if(scenario STREQUAL "runs")
set(name loader_tls_index0)
else()
set(name loader_tls_index0_${scenario})
endif()
add_test(NAME ${name}
COMMAND loader_tls_index0_test ${scenario} "$<TARGET_FILE:tiny_tls_ga>" "$<TARGET_FILE:tiny_tls>"
"$<TARGET_FILE:tiny_thread_hook>"
)
endforeach()

# DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so
# DllMain's only work is that one call. No game files.
add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp)
Expand Down Expand Up @@ -1142,6 +1197,15 @@ if(BUILD_TESTING)
"-DTOOL=$<TARGET_FILE:gta6rt>" "-DWANT=${GTA6RT_STACK}"
-P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake")
add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $<TARGET_FILE:tiny_game> -- hello 42 stack)
# A /GA executable under --run and --init reads its TLS from slot 0, and the trace names gta6rt.exe as the image
# whose index 0 moved.
add_test(NAME run_tiny_tls_ga COMMAND ${CMAKE_COMMAND}
"-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_tls_ga>" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}"
"-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_index0.cmake")
# Clone files are deleted when gta6rt exits normally; only the home clone outlives the run, until the next one.
add_test(NAME run_tiny_tls_clone_cleanup COMMAND ${CMAKE_COMMAND}
"-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_tls_clones>" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}"
"-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_clone_cleanup.cmake")
# GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`.
add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND}
"-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_game>"
Expand Down
34 changes: 33 additions & 1 deletion runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,25 @@ clone of the helper from `%TEMP%\leonida_tls_host_<pid>_<slot>.dll`, so up to 16
once and a further one is rejected with an error instead of sharing a slot. Images without a TLS
directory (or with an all-zero one) load normally.

An executable (an image without `IMAGE_FILE_DLL`, the game's EXE under `--run`, `--init` and `--dry-run`) gets
module TLS index 0 instead, as Windows gives the process EXE. MSVC code built with `/GA` relies on that: it reads
`ThreadLocalStoragePointer[0]` directly and never loads `_tls_index`. A `thread_local int v = 42;` EXE built
`/O2 /GA /MD` printed `tls_index=0 value=42` natively but `tls_index=6 value=0` under `gta6rt --run` when it got a
helper's index. Index 0 belongs to `gta6rt.exe` itself (measured: Windows gives it to the process EXE, the trace event
below names it, and `gta6rt.exe` has a 1398-byte TLS template when measured and no TLS callbacks), and all of its own
TLS reads go through `_tls_index`. So `gta6rt.exe` moves off index 0 once, at start (`rt::reserve_tls_index0()`,
called from a CRT initializer that runs before any of gta6rt's own static initializers): it writes one more clone of the
helper, `leonida_tls_host_<pid>_home.dll`, whose TLS directory covers a copy of `gta6rt.exe`'s template (the
helper carries a 16 KiB array for it), swaps slots 0 and that clone's index on the calling thread and writes the
clone's index into `gta6rt.exe`'s `_tls_index`. Every thread the OS starts from then on has a fresh copy of
`gta6rt.exe`'s TLS at that index from its first instruction, so nothing has to run on a new thread first, including
code that runs in an earlier DLL's `DLL_THREAD_ATTACH`. Slot 0 then holds a block nothing reads, which the executable's
template copy replaces on the loading thread, on threads started later, and, from `load()` itself, on threads that
were already running, exactly as a DLL's copy replaces a helper's; the OS frees both slots at thread exit. The move cannot be made
later: MSVC keeps the address of a TLS slot in a frame across calls (`zlib_inflate` in `shader_library.h` does), so
a thread that already runs gta6rt's code cannot be moved wherever it is stopped. The startup trace records the move at
the first executable (`tls_index0`). DLLs keep the helper indices and work next to the executable as before.

Current limits, by design:

- `load()` runs no image code. Static TLS is data, not code. The TLS index helper is the runtime's own
Expand All @@ -151,7 +170,19 @@ Current limits, by design:
title's callback on, gets its copy from `load()` itself, the way Windows gives one to running threads for a DLL it
loads: a block, no `DLL_THREAD_ATTACH`, `DLL_THREAD_DETACH` when it ends, and `~Loader` takes the block back.
`install_tls_for_thread()` and `uninstall_tls_for_thread()` are no-ops on such a thread. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that
called `load()`.
called `load()`. As on Windows, a new thread gets every module's copy before any TLS callback runs, and the
executable's callbacks come after the DLLs' ones, for attach and for detach.
- One executable holds index 0 at a time, and only after `reserve_tls_index0()` has run at process start. An
executable mapped without it (the reservation failed, the `Loader` is used without it, or another executable
holds index 0) gets a helper index and a `[rt] loader: ... does not get module TLS index 0` line on stderr: its
`/GA` code would read and write the TLS in slot 0, which is `gta6rt.exe`'s own or the other executable's, so
`--run` and `--init` refuse it with an error and exit code 1, and a `Loader` user must not run its code.
- Threads that ran gta6rt's code before the reservation keep nothing of their TLS: they find a fresh copy at the new
index. In gta6rt only the main thread has run its code by then, and its TLS moves with it.
- The home clone stays loaded until the process ends (freeing it would free `gta6rt.exe`'s TLS blocks), and a mapped
image's file cannot be deleted, so its file stays in `%TEMP%` until the next run's clean-up of dead processes'
clones deletes it. The clones for mapped DLLs are deleted at exit as before. A `gta6rt.exe` whose TLS
outgrows the helper's 16 KiB array is refused the move.
- The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE
files and on any images the caller passes it.

Expand Down Expand Up @@ -355,6 +386,7 @@ from the ANSI code page.
| `kind` | When | Fields |
|---|---|---|
| `trace_open` | first line | `pid` |
| `tls_index0` | the first executable is mapped with module TLS index 0, which gta6rt freed at start (once per process) | `owner` (the image that held index 0, `gta6rt.exe`), `moved_to` (the index its block moved to) |
| `map` | a module is mapped, bound and protected | `module`, `base`, `size`, `relocated` |
| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` |
| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
Expand Down
15 changes: 8 additions & 7 deletions runtime/shims/startup_trace.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
// One JSON object per line, flushed per event so the file survives a crash. Off by default; every entry point is a
// single relaxed load when it is off. Events:
// {"seq":1,"t":0.000,"kind":"trace_open"}
// {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false}
// {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1}
// {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1}
// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only)
// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."}
// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0",
// {"seq":2,"t":0.001,"kind":"tls_index0","owner":"gta6rt.exe","moved_to":4} (first executable mapped, once)
// {"seq":3,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false}
// {"seq":4,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1}
// {"seq":5,"t":0.002,"kind":"dllmain","module":"a.dll","result":1}
// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only)
// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."}
// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0",
// "stack":["a.dll+0x4a00","a.dll+0x2210"]}
// {"seq":8,"t":0.030,"kind":"exit","code":0}
// {"seq":9,"t":0.030,"kind":"exit","code":0}
//
// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process
// does (except LEONIDA_SKIP_INT3, below).
Expand Down
24 changes: 24 additions & 0 deletions runtime/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ const char* binding_name(rt::Binding b) {
}
}

// Module TLS index 0 for the game's executable (rt::reserve_tls_index0), from the CRT's initializer table: .CRT$XCT
// runs after the C runtime is set up and before every C++ dynamic initializer of gta6rt (.CRT$XCU), so before any of
// gta6rt's code can have started a thread. The frames above it (wmainCRTStartup, __scrt_common_main_seh, _initterm)
// hold no TLS slot address. The result is read again where an image is run.
void __cdecl reserve_tls_index0_at_start() { rt::reserve_tls_index0(); }
#pragma section(".CRT$XCT", read)
extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_tls_index0)() =
reserve_tls_index0_at_start;
#pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0")

int usage() {
std::fprintf(stderr,
"usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n"
Expand Down Expand Up @@ -156,6 +166,20 @@ int wmain(int argc, wchar_t** argv) {
try {
rt::Loader loader(game_dir);
rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
// An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which
// is gta6rt's own (or another executable's), so no code of it may run.
const auto* main_nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(
main_module.base + reinterpret_cast<const IMAGE_DOS_HEADER*>(main_module.base)->e_lfanew);
const bool main_is_exe = (main_nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0;
if ((init || run) && main_is_exe && main_module.tls_slot != rt::kNoTlsIndex && main_module.tls_index != 0) {
std::string why;
if (rt::reserve_tls_index0(&why)) why = "another mapped executable holds it";
std::fprintf(stderr,
"error: %s cannot have module TLS index 0 (%s); code built with /GA would read and write "
"another module's TLS through slot 0, so it is not run\n",
main_module.name.c_str(), why.c_str());
return 1;
}
// The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA
// for this executable is given. The count of redirected calls shows whether the RVA is the real lookup.
if (view_mode_getter_rva) {
Expand Down
Loading
Loading