From 338dc11ea622cb3ab0406cafd9af3f08a3740e50 Mon Sep 17 00:00:00 2001 From: ZroFreaks <42916282+ZroIsHere@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:52:38 +0100 Subject: runtime: own the executable TLS exit callback --- runtime/shims/process.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'runtime/shims/process.cpp') diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 08023ea78..2a0331194 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -11,8 +11,7 @@ // shares with gta6rt. exit() runs it newest first, as the CRT does, before the run ends; _exit(), _Exit(), // quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second // thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the -// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none) and the thread-local -// destructor callback (_register_thread_local_exe_atexit_callback); both still reach the host CRT. +// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none). // Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and // msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. // The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a @@ -157,7 +156,10 @@ bool take_exit_lock() { } // exit(): the game's handlers and static destructors, then the end of the run. void __cdecl game_exit(int code) { - if (take_exit_lock()) run_atexit_handlers(); + if (take_exit_lock()) { + run_atexit_handlers(); + run_thread_local_exe_atexit_callback(); + } end_run(code); } // _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers. @@ -252,6 +254,10 @@ void __cdecl game_abort() { end_run(3); // the CRT's abort exit code } +void __cdecl game_register_thread_local_exe_atexit_callback(ThreadLocalExeAtexitCallback callback) { + register_thread_local_exe_atexit_callback(callback); +} + // ---- arguments int* __cdecl game_p_argc() { return &g_argc; } char*** __cdecl game_p_argv() { return &g_argv_ptr; } @@ -415,6 +421,7 @@ DWORD WINAPI game_thread(void* p) { // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. auto entry = reinterpret_cast(call->entry); const DWORD code = entry(nullptr); + run_thread_local_exe_atexit_callback(); end_run(static_cast(code)); // returning from the entry point is an exit too } @@ -493,6 +500,8 @@ using namespace rt::process; {dll, "_crt_atexit", reinterpret_cast(&game_crt_atexit)}, \ {dll, "_cexit", reinterpret_cast(&game_cexit)}, {dll, "_c_exit", reinterpret_cast(&game_c_exit)}, \ {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ + {dll, "_register_thread_local_exe_atexit_callback", \ + reinterpret_cast(&game_register_thread_local_exe_atexit_callback)}, \ {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_narrow_argv)}, \ -- cgit v1.2.3 From 48f87a9c9bea054b0072364ebf0e51e2d59f354d Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Thu, 26 Nov 2026 13:15:17 -0500 Subject: process: call the EXE's thread-local destructor callback with its real signature, before the atexit handlers (maintainer fix on #2315) #2315 kept `_register_thread_local_exe_atexit_callback` away from the host UCRT, which fast-fails a second registration in the process (gta6rt's own startup makes the first). Review points fixed on top: - The callback is a `_tls_callback_type` (UCRT process.h: `void (__stdcall*)(void*, unsigned long, void*)`), not `void (*)()`: vcruntime's TLS destructor callback reads its reason argument, which was left as whatever rdx held. It is now called as `(nullptr, DLL_PROCESS_DETACH, nullptr)`, as the UCRT does. - `exit` and `_cexit` call it before the atexit table, as the UCRT does: the leaving thread's thread_local objects end before the static ones ([basic.start.term]). #2315 ran it after the static destructors, and not in `_cexit`. - The extra call on every thread detach is dropped, with the per-thread flag and the loader's include of the process shim: the loader already calls the same function from the executable's TLS directory with DLL_THREAD_DETACH, and the UCRT never calls the registered one there. The call after a returning entry point is dropped too (MSVC's mainCRTStartup calls exit itself). - run_tiny_atexit gains thread_local_exit and thread_local_cexit: a thread_local object of the main thread must end before the handlers and destructors. On main the --run path never ends it (Wine) or stops at the second registration (Windows). Co-Authored-By: Claude Opus 5.5 --- runtime/README.md | 11 +++++++---- runtime/shims/process.cpp | 32 ++++++++++++++++++++++++++------ runtime/shims/process_shim.h | 21 --------------------- runtime/src/pe_loader.cpp | 10 ---------- runtime/test/check_atexit.cmake | 10 ++++++++-- runtime/test/fixtures/tiny_atexit.cpp | 13 +++++++++++++ 6 files changed, 54 insertions(+), 43 deletions(-) (limited to 'runtime/shims/process.cpp') diff --git a/runtime/README.md b/runtime/README.md index 2abc06815..a21dd8447 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -583,10 +583,13 @@ shared with gta6rt): `exit` and a return from `main` run them newest first befor returns, and `_exit`, `quick_exit`, `ExitProcess` and `abort` skip them, as natively. `run_tiny_atexit` runs a stand-in program natively and through `--run` for each of those paths (and for `_exit` from a second thread during `exit`) and holds both to the Windows sequence (under Wine, whose CRT differs, a native difference is only reported). The -executable's `_register_thread_local_exe_atexit_callback` is kept by the runtime and called on guest thread detach, -after that thread's executable TLS callbacks. `exit` also runs it before the game thread parks for host shutdown; -`_cexit`, `_exit`, `quick_exit`, `ExitProcess` and `abort` do not. `at_quick_exit` handlers are not covered (`quick_exit` -runs none). +executable's thread-local destructor callback (`_register_thread_local_exe_atexit_callback`) is kept by the run too: +the host UCRT accepts one per process and fast-fails the second, and gta6rt's own startup registers the first. `exit` +and `_cexit` call it once, as `(nullptr, DLL_PROCESS_DETACH, nullptr)`, before the atexit handlers, as the UCRT does, +so the leaving thread's `thread_local` objects end before the static ones; `_exit`, `quick_exit`, `ExitProcess` and +`abort` do not. Other threads' `thread_local` objects end through the loader's thread-detach notification, which calls +the same function from the executable's TLS directory. `run_tiny_atexit` covers `exit` and `_cexit` with a +`thread_local` object. `at_quick_exit` handlers are not covered (`quick_exit` runs none). `run_tiny_frame` does it with a stand-in that imports `d3d12_xs.dll!D3D12XboxCreateDevice` and, with `LEONIDA_D3D12=vulkan`, clears a render target and reads it back on the Vulkan device: the loader, the game thread, the Xbox-ABI proxies and the device in one process (`test/fixtures/tiny_frame.cpp`; `test/check_tiny_frame.py` checks diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 2a0331194..2c37292e2 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -12,6 +12,8 @@ // quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second // thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the // CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none). +// - the EXE's thread-local destructor callback (_register_thread_local_exe_atexit_callback) is kept here too: +// exit() and _cexit() call it before the atexit handlers, as the UCRT does (see game_exit below). // Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and // msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. // The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a @@ -141,6 +143,28 @@ OnexitFn __cdecl game_onexit(OnexitFn fn) { return fn && register_atexit(reinterpret_cast(fn)) ? fn : nullptr; } +// ---- the EXE's thread-local destructors +// An MSVC EXE's startup passes vcruntime's TLS destructor callback, which its TLS directory also lists, to +// _register_thread_local_exe_atexit_callback (UCRT process.h: void __cdecl (_tls_callback_type), where +// _tls_callback_type is void (__stdcall*)(void*, unsigned long, void*)). The UCRT calls it as +// (nullptr, DLL_PROCESS_DETACH, nullptr) when exit() or _cexit() starts, before the atexit table: the leaving thread's +// thread_local objects end before the static ones, as C++ requires. Other threads' end through the loader's +// thread-detach notification, which calls the same function from the TLS directory, so it is not called here then. +// The host CRT cannot take it: the UCRT accepts one per process and fast-fails the second (gta6rt's own startup +// registers the first, so the title stopped at boot on Windows), and Wine's ucrtbase replaces gta6rt's own and never +// calls the title's, because the run ends through end_run. +using TlsCallback = void(__stdcall*)(void*, unsigned long, void*); +std::atomic g_thread_local_exit_callback{nullptr}; + +void __cdecl game_register_thread_local_exe_atexit_callback(TlsCallback callback) { + g_thread_local_exit_callback.store(callback); +} +// Once per run, like the UCRT's exit path: a later exit() after _cexit() finds nothing left to run. +void run_thread_local_exe_atexit_callback() { + if (const TlsCallback callback = g_thread_local_exit_callback.exchange(nullptr)) + callback(nullptr, DLL_PROCESS_DETACH, nullptr); +} + // ---- the way out // The CRT's exit lock, which exit(), _exit(), _Exit() and quick_exit() all take: the first thread to leave owns it // and ends the run; any other thread that tries to leave waits forever. The owner may leave again from a handler @@ -157,8 +181,8 @@ bool take_exit_lock() { // exit(): the game's handlers and static destructors, then the end of the run. void __cdecl game_exit(int code) { if (take_exit_lock()) { - run_atexit_handlers(); run_thread_local_exe_atexit_callback(); + run_atexit_handlers(); } end_run(code); } @@ -169,6 +193,7 @@ void __cdecl game_quick_exit(int code) { } // _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns. void __cdecl game_cexit() { + run_thread_local_exe_atexit_callback(); run_atexit_handlers(); std::fflush(nullptr); } @@ -254,10 +279,6 @@ void __cdecl game_abort() { end_run(3); // the CRT's abort exit code } -void __cdecl game_register_thread_local_exe_atexit_callback(ThreadLocalExeAtexitCallback callback) { - register_thread_local_exe_atexit_callback(callback); -} - // ---- arguments int* __cdecl game_p_argc() { return &g_argc; } char*** __cdecl game_p_argv() { return &g_argv_ptr; } @@ -421,7 +442,6 @@ DWORD WINAPI game_thread(void* p) { // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. auto entry = reinterpret_cast(call->entry); const DWORD code = entry(nullptr); - run_thread_local_exe_atexit_callback(); end_run(static_cast(code)); // returning from the entry point is an exit too } diff --git a/runtime/shims/process_shim.h b/runtime/shims/process_shim.h index c49425927..f6946719b 100644 --- a/runtime/shims/process_shim.h +++ b/runtime/shims/process_shim.h @@ -1,32 +1,11 @@ // The game's command line and exit, for `gta6rt --run` (shims/process.cpp). #pragma once -#include #include #include #include namespace rt::process { -using ThreadLocalExeAtexitCallback = void(__cdecl*)(); - -// The mapped executable's CRT registers one callback for its thread-local destructors. The host CRT cannot own -// this callback: it belongs to an image the Windows loader did not load. Keep it for the loader's thread-detach -// notification, and run it at most once on each guest thread. -inline std::atomic g_thread_local_exe_atexit_callback{nullptr}; -inline thread_local bool g_thread_local_exe_atexit_callback_ran = false; - -inline void register_thread_local_exe_atexit_callback(ThreadLocalExeAtexitCallback callback) noexcept { - g_thread_local_exe_atexit_callback.store(callback, std::memory_order_release); -} - -inline void run_thread_local_exe_atexit_callback() { - if (g_thread_local_exe_atexit_callback_ran) return; - const auto callback = g_thread_local_exe_atexit_callback.load(std::memory_order_acquire); - if (!callback) return; - g_thread_local_exe_atexit_callback_ran = true; - callback(); -} - // Set GetCommandLine to `program` then `args`, quoted where needed, before process-attach callbacks. The wide text // holds the arguments exactly; the narrow text uses the ANSI code page (RT-84). Reset CRT argv to argc=0/null: // its startup configuration selects no arguments, the original arguments, or wildcard expansion for each width. diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 81d2e208a..fc73f37f5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -17,7 +17,6 @@ #include #include "../shims/shims.h" -#include "../shims/process_shim.h" #include "../shims/startup_trace.h" #include "base_reservation.h" #include "clzero_patch.h" @@ -1199,15 +1198,6 @@ void __cdecl on_host_thread_event(DWORD reason) { std::fprintf(stderr, "[rt] loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(), e.what()); } - if (i == kMainImageSlot) { - try { - process::run_thread_local_exe_atexit_callback(); - } catch (const std::exception& e) { - std::fprintf(stderr, "[rt] loader: executable thread-local destructors: %s\n", e.what()); - } catch (...) { - std::fprintf(stderr, "[rt] loader: executable thread-local destructors threw an unknown exception\n"); - } - } // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the // helper's own TLS block and freed with it at thread exit. uninstall_thread_block(*m); diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake index 255bb3a4f..6b34c9d81 100644 --- a/runtime/test/check_atexit.cmake +++ b/runtime/test/check_atexit.cmake @@ -26,6 +26,12 @@ set(code_c_exit 12) # exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back. set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}") set(code_concurrent_exit 7) +# The main thread's thread_local object ends before the atexit handlers and static destructors ([basic.start.term]): +# the UCRT calls the EXE's thread-local destructor callback first in exit() and _cexit(). +set(expect_thread_local_exit "${ctors};ctor thread_local;dtor thread_local;${handlers}") +set(code_thread_local_exit 13) +set(expect_thread_local_cexit "${ctors};ctor thread_local;dtor thread_local;${handlers};after _cexit") +set(code_thread_local_cexit 14) # The program's own lines, in order, without the prefix; everything gta6rt prints is dropped. function(guest_lines output result) @@ -42,7 +48,7 @@ function(guest_lines output result) endfunction() set(failures "") -foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit) +foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit thread_local_exit thread_local_cexit) execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode} WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err) @@ -68,4 +74,4 @@ endforeach() if(failures) message(FATAL_ERROR "atexit/termination differences:${failures}") endif() -message(STATUS "tiny_atexit: 8 termination paths match the Windows sequence") +message(STATUS "tiny_atexit: 10 termination paths match the Windows sequence") diff --git a/runtime/test/fixtures/tiny_atexit.cpp b/runtime/test/fixtures/tiny_atexit.cpp index fbe071e7f..2719f98f4 100644 --- a/runtime/test/fixtures/tiny_atexit.cpp +++ b/runtime/test/fixtures/tiny_atexit.cpp @@ -9,6 +9,10 @@ // cexit _cexit() runs every handler and returns; main then returns 11 // c_exit _c_exit() runs none and returns; main then returns 12, and exit runs them all // concurrent_exit a second thread calls _exit(7) while exit(7) runs a handler: it waits for them all +// thread_local_exit a thread_local object of the main thread, then exit(13): it ends first, then the handlers +// thread_local_cexit the same object, then _cexit(): the same order, and main then returns 14 +// The thread_local destructor reaches the CRT through _register_thread_local_exe_atexit_callback, which the EXE's +// startup calls only when the image has one (this program has one in every mode, constructed only in the last two). // One handler registers another while the handlers run: it must still run, next. #include #include // _cexit, _c_exit @@ -74,6 +78,15 @@ int main(int argc, char** argv) { CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr)); std::exit(7); } + if (!std::strncmp(mode, "thread_local_", 13)) { + thread_local Tracer main_thread_local("thread_local"); // constructed here, on the main thread only + if (!std::strcmp(mode, "thread_local_exit")) std::exit(13); + if (!std::strcmp(mode, "thread_local_cexit")) { + _cexit(); + say("after _cexit"); + return 14; + } + } if (!std::strcmp(mode, "exit")) std::exit(7); if (!std::strcmp(mode, "_exit")) _exit(8); if (!std::strcmp(mode, "quick_exit")) std::quick_exit(9); -- cgit v1.2.3