Skip to content
Merged
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
2 changes: 1 addition & 1 deletion runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1148,7 +1148,7 @@ if(BUILD_TESTING)
endif()
add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp)
target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8)
target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8 /EHsc) # a handler that throws
set_target_properties(tiny_atexit PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
)
Expand Down
24 changes: 14 additions & 10 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -594,16 +594,20 @@ It prints counts only; on the 1.0.2.1 corpus all 26,503 containers resolve.
own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game.
The game's `atexit` handlers and static destructors go to a table of the run's own (the CRT's process-wide one is
shared with gta6rt): `exit` and a return from `main` run them newest first before the run ends, `_cexit` runs them and
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 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).
returns, and `_exit`, `quick_exit`, `ExitProcess` and `abort` skip them, as natively. The game's `at_quick_exit`
handlers (`_crt_at_quick_exit`) go to a second table of the run's own, which `quick_exit` runs newest first, and its
thread-local destructor callback (`_register_thread_local_exe_atexit_callback`) is the run's too: `exit` and `_cexit`
call it for the exiting thread before the `atexit` handlers, as the UCRT does. Registration and the cleanup of `exit`,
`quick_exit` and `_cexit` (the thread-local callback, the table's drain and `_cexit`'s stream flush) hold one lock of
the run's own, as the UCRT's exit lock: a second thread in `_cexit`, or registering during a drain, waits for it. A handler that lets a C++ exception escape ends the run as the UCRT's `terminate` would (exit code 3).
`run_tiny_atexit` runs a stand-in program natively and through `--run` for each of those paths (and for `_exit`,
`_cexit` and `at_quick_exit` from a second thread during a drain, and a handler that throws) and holds both to the
Windows sequence (under Wine, whose CRT differs, a native difference is only reported). The thread-local destructor
callback cannot stay with the host CRT: 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 as `(nullptr, DLL_PROCESS_DETACH, nullptr)`, 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_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
Expand Down
177 changes: 126 additions & 51 deletions runtime/shims/process.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,18 @@
// 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).
// - 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).
// CRT's exit lock. Registration and the cleanup of exit(), quick_exit() and _cexit() (the thread-local
// callback, the table's drain and, for _cexit(), the stream flush) hold one lock of the run's own, as the UCRT's
// exit lock serializes them: a second thread in _cexit(), or registering while a drain runs, waits for that
// cleanup; the exiting thread may register from a handler (the lock is recursive). The lock is released before
// the run ends. A handler that lets a C++ exception escape terminates the run as the UCRT's terminate() would:
// abort(), exit code 3;
// - the game's at_quick_exit registrations (_crt_at_quick_exit) go to a second table of the run's own, which
// quick_exit() runs newest first; exit(), _exit() and _Exit() do not;
// - the EXE's thread-local destructor callback (_register_thread_local_exe_atexit_callback, which the EXE's CRT
// startup registers when the EXE has a thread_local with a destructor) is the run's own too: exit() and _cexit()
// call it for the exiting thread before the atexit handlers, as the UCRT does (see
// game_register_thread_local_exe_atexit_callback below). A second registration terminates, as in the UCRT.
// 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
Expand Down Expand Up @@ -84,7 +93,12 @@ std::string narrow(const std::wstring& w) {
return s;
}

void release_cleanup_lock();

[[noreturn]] void end_run(int code) {
// A handler may end the run from inside a drain: the cleanup lock it holds is released before the thread parks,
// so the host (and a later run_entry) can take it.
release_cleanup_lock();
// Read before signalling: once g_done is set, run_entry can return and clear g_running while the host is still
// finishing the run (main.cpp's "game exited" line and cleanup), which this thread must not cut short.
const bool running = g_running;
Expand All @@ -104,67 +118,98 @@ std::string narrow(const std::wstring& w) {
// ---- the game's atexit table
using AtexitFn = void(__cdecl*)();
using OnexitFn = int(__cdecl*)();
std::mutex g_atexit_lock;
using TlsCallback = void(NTAPI*)(PVOID, DWORD, PVOID); // _tls_callback_type
// The run's cleanup lock, as the UCRT's exit lock: registration takes it, and a cleanup (exit, quick_exit, _cexit)
// holds it from before the thread-local callback through the table's drain, so two threads never clean up at once
// and a registration from another thread waits for the drain. Recursive, so the exiting thread may register from a
// handler. t_cleanup_held counts this thread's holds: end_run releases them all before the thread parks.
std::recursive_mutex g_cleanup_lock;
thread_local unsigned t_cleanup_held = 0;
std::vector<AtexitFn> g_atexit;
std::vector<AtexitFn> g_at_quick_exit;
std::atomic<TlsCallback> g_thread_local_exit{nullptr};
std::atomic<DWORD> g_exiting_thread{0};

bool register_atexit(AtexitFn fn) {
std::lock_guard<std::mutex> lock(g_atexit_lock);
struct CleanupLock {
CleanupLock() {
g_cleanup_lock.lock();
++t_cleanup_held;
}
~CleanupLock() {
--t_cleanup_held;
g_cleanup_lock.unlock();
}
CleanupLock(const CleanupLock&) = delete;
CleanupLock& operator=(const CleanupLock&) = delete;
};
void release_cleanup_lock() {
while (t_cleanup_held) {
--t_cleanup_held;
g_cleanup_lock.unlock();
}
}

bool register_in(std::vector<AtexitFn>& table, AtexitFn fn) {
CleanupLock lock;
try {
g_atexit.push_back(fn);
table.push_back(fn);
} catch (const std::bad_alloc&) {
return false; // the CRT reports a full table as a failed registration
}
return true;
}
bool register_atexit(AtexitFn fn) { return register_in(g_atexit, fn); }

// Newest first. A handler registered while the handlers run goes on the end and so runs next, as in the UCRT.
void run_atexit_handlers() {
void __cdecl game_abort();

// A guest cleanup callback. A C++ exception it lets escape would unwind into the runtime; the UCRT's exit calls
// terminate() if one throws, and its default handler aborts: exit code 3, and the remaining handlers do not run.
// A thread_local destructor is noexcept, so one that throws reaches the game's own terminate() before this catch;
// that abort() is the game's import, game_abort, and ends the run with the same code.
template <typename Call>
void guarded(const char* what, Call&& call) {
try {
call();
} catch (...) {
std::fprintf(stderr, "[rt] process: a %s threw a C++ exception; terminating as the UCRT does\n", what);
game_abort();
}
}

// Newest first, with the cleanup lock held throughout (the caller took it). A handler registered while the handlers
// run goes on the end and so runs next, as in the UCRT.
void run_handlers(std::vector<AtexitFn>& table, const char* what) {
for (;;) {
AtexitFn fn;
{
std::lock_guard<std::mutex> lock(g_atexit_lock);
if (g_atexit.empty()) return;
fn = g_atexit.back();
g_atexit.pop_back();
}
fn();
if (table.empty()) return;
const AtexitFn fn = table.back();
table.pop_back();
guarded(what, fn);
}
}
// exit() and _cexit(): the exiting thread's thread_local destructors first (the UCRT calls the registered callback
// with DLL_PROCESS_DETACH; a second call finds the thread's list empty), then the atexit handlers and static
// destructors. The caller holds the cleanup lock.
void run_atexit_handlers() {
if (const TlsCallback callback = g_thread_local_exit.load())
guarded("thread-local destructor", [&] { callback(nullptr, DLL_PROCESS_DETACH, nullptr); });
run_handlers(g_atexit, "atexit handler");
}

// UCRT: int _crt_atexit(_PVFV), 0 on success. MSVC's atexit() and the static destructors of an EXE reach it.
int __cdecl game_crt_atexit(AtexitFn fn) {
return fn && register_atexit(fn) ? 0 : -1;
}
// UCRT: int _crt_at_quick_exit(_PVFV), 0 on success. An EXE's at_quick_exit() reaches it.
int __cdecl game_crt_at_quick_exit(AtexitFn fn) {
return fn && register_in(g_at_quick_exit, fn) ? 0 : -1;
}
// msvcrt.dll (MinGW): int atexit(void (*)(void)) and _onexit_t _onexit(_onexit_t).
int __cdecl game_msvcrt_atexit(AtexitFn fn) { return game_crt_atexit(fn); }
OnexitFn __cdecl game_onexit(OnexitFn fn) {
// its int result is ignored, as the CRT ignores it
return fn && register_atexit(reinterpret_cast<AtexitFn>(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<TlsCallback> 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
Expand All @@ -174,26 +219,38 @@ bool take_exit_lock() {
DWORD owner = 0;
if (g_exiting_thread.compare_exchange_strong(owner, self)) return true;
if (owner != self) {
release_cleanup_lock(); // parked for good: a drain it was in must not keep the owner waiting
for (;;) Sleep(INFINITE);
}
return false;
}
// exit(): the game's handlers and static destructors, then the end of the run.
// exit(): the game's handlers and static destructors, then the end of the run. The cleanup lock is taken after the
// exit lock (a thread parked by the latter holds nothing) and released by end_run.
void __cdecl game_exit(int code) {
if (take_exit_lock()) {
run_thread_local_exe_atexit_callback();
CleanupLock lock;
run_atexit_handlers();
}
end_run(code);
}
// _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers.
void __cdecl game_quick_exit(int code) {
// _exit(), _Exit(): the end of the run without any handler.
void __cdecl game_underscore_exit(int code) {
take_exit_lock();
end_run(code);
}
// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns.
// quick_exit(): the at_quick_exit handlers, newest first, then the end of the run without the atexit handlers.
void __cdecl game_quick_exit(int code) {
if (take_exit_lock()) {
CleanupLock lock;
run_handlers(g_at_quick_exit, "quick_exit handler");
}
end_run(code);
}
// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns. The flush is inside the
// cleanup lock, as the UCRT's _cexit flushes under its exit lock. A second thread's _cexit() waits for the first's
// cleanup, then finds the table empty.
void __cdecl game_cexit() {
run_thread_local_exe_atexit_callback();
CleanupLock lock;
run_atexit_handlers();
std::fflush(nullptr);
}
Expand Down Expand Up @@ -278,6 +335,21 @@ void __cdecl game_abort() {
}
end_run(3); // the CRT's abort exit code
}
// UCRT: void _register_thread_local_exe_atexit_callback(_tls_callback_type). An MSVC EXE's startup passes
// vcruntime's TLS destructor callback, which its TLS directory also lists; run_atexit_handlers calls it as
// (nullptr, DLL_PROCESS_DETACH, nullptr) for the exiting thread. Other threads' thread_local objects end through the
// loader's thread-detach notification, which calls the same function from the TLS directory. 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. Here too the callback can be set once; a second registration calls
// terminate(), which aborts.
void __cdecl game_register_thread_local_exe_atexit_callback(TlsCallback callback) {
TlsCallback expected = nullptr;
if (!g_thread_local_exit.compare_exchange_strong(expected, callback)) {
std::fprintf(stderr, "[rt] process: the thread-local exit callback was registered twice\n");
game_abort();
}
}

// ---- arguments
int* __cdecl game_p_argc() { return &g_argc; }
Expand Down Expand Up @@ -471,9 +543,11 @@ void set_command_line(const std::wstring& program, const std::vector<std::wstrin

int run_entry(void* entry, size_t stack_bytes) {
{
std::lock_guard<std::mutex> lock(g_atexit_lock);
CleanupLock lock;
g_atexit.clear(); // a run never sees the handlers of an earlier one
g_at_quick_exit.clear();
}
g_thread_local_exit = nullptr;
g_exiting_thread = 0;
g_exited = false;
g_exit_code = 0;
Expand Down Expand Up @@ -514,14 +588,15 @@ int run_entry(void* entry, size_t stack_bytes) {
namespace {
using namespace rt::process;
#define UCRT(dll) \
{dll, "exit", reinterpret_cast<void*>(&game_exit)}, {dll, "_exit", reinterpret_cast<void*>(&game_quick_exit)}, \
{dll, "_Exit", reinterpret_cast<void*>(&game_quick_exit)}, \
{dll, "exit", reinterpret_cast<void*>(&game_exit)}, {dll, "_exit", reinterpret_cast<void*>(&game_underscore_exit)}, \
{dll, "_Exit", reinterpret_cast<void*>(&game_underscore_exit)}, \
{dll, "quick_exit", reinterpret_cast<void*>(&game_quick_exit)}, \
{dll, "_crt_atexit", reinterpret_cast<void*>(&game_crt_atexit)}, \
{dll, "_cexit", reinterpret_cast<void*>(&game_cexit)}, {dll, "_c_exit", reinterpret_cast<void*>(&game_c_exit)}, \
{dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \
{dll, "_crt_at_quick_exit", reinterpret_cast<void*>(&game_crt_at_quick_exit)}, \
{dll, "_register_thread_local_exe_atexit_callback", \
reinterpret_cast<void*>(&game_register_thread_local_exe_atexit_callback)}, \
{dll, "_cexit", reinterpret_cast<void*>(&game_cexit)}, {dll, "_c_exit", reinterpret_cast<void*>(&game_c_exit)}, \
{dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \
{dll, "__p___argv", reinterpret_cast<void*>(&game_p_argv)}, \
{dll, "__p___wargv", reinterpret_cast<void*>(&game_p_wargv)}, \
{dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_narrow_argv)}, \
Expand All @@ -546,7 +621,7 @@ SHIM_TABLE(process,
UCRT("ucrtbase.dll"),
UCRT("ucrtbased.dll"), // the Debug UCRT: a Debug build of the stand-in game (run_tiny_game) links it
{"msvcrt.dll", "exit", reinterpret_cast<void*>(&game_exit)},
{"msvcrt.dll", "_exit", reinterpret_cast<void*>(&game_quick_exit)},
{"msvcrt.dll", "_exit", reinterpret_cast<void*>(&game_underscore_exit)},
{"msvcrt.dll", "atexit", reinterpret_cast<void*>(&game_msvcrt_atexit)},
{"msvcrt.dll", "_onexit", reinterpret_cast<void*>(&game_onexit)},
{"msvcrt.dll", "_cexit", reinterpret_cast<void*>(&game_cexit)},
Expand Down
Loading