diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 7bcfa9ef62..e37ee2e9f7 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -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/$" ) diff --git a/runtime/README.md b/runtime/README.md index 90c040c05c..9d4209a52e 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -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 diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 2c37292e20..a692a6224a 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -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 @@ -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; @@ -104,38 +118,91 @@ 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 g_atexit; +std::vector g_at_quick_exit; +std::atomic g_thread_local_exit{nullptr}; std::atomic g_exiting_thread{0}; -bool register_atexit(AtexitFn fn) { - std::lock_guard 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& 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 +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& table, const char* what) { for (;;) { - AtexitFn fn; - { - std::lock_guard 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) { @@ -143,28 +210,6 @@ 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 @@ -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); } @@ -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; } @@ -471,9 +543,11 @@ void set_command_line(const std::wstring& program, const std::vector 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; @@ -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(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_quick_exit)}, \ - {dll, "_Exit", reinterpret_cast(&game_quick_exit)}, \ + {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_underscore_exit)}, \ + {dll, "_Exit", reinterpret_cast(&game_underscore_exit)}, \ {dll, "quick_exit", reinterpret_cast(&game_quick_exit)}, \ {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, "_crt_at_quick_exit", reinterpret_cast(&game_crt_at_quick_exit)}, \ {dll, "_register_thread_local_exe_atexit_callback", \ reinterpret_cast(&game_register_thread_local_exe_atexit_callback)}, \ + {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, "__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)}, \ @@ -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(&game_exit)}, - {"msvcrt.dll", "_exit", reinterpret_cast(&game_quick_exit)}, + {"msvcrt.dll", "_exit", reinterpret_cast(&game_underscore_exit)}, {"msvcrt.dll", "atexit", reinterpret_cast(&game_msvcrt_atexit)}, {"msvcrt.dll", "_onexit", reinterpret_cast(&game_onexit)}, {"msvcrt.dll", "_cexit", reinterpret_cast(&game_cexit)}, diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake index 6b34c9d810..5173591649 100644 --- a/runtime/test/check_atexit.cmake +++ b/runtime/test/check_atexit.cmake @@ -32,6 +32,25 @@ set(expect_thread_local_exit "${ctors};ctor thread_local;dtor thread_local;${han 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) +# at_quick_exit handlers: quick_exit runs them newest first and nothing else; exit and _exit do not run them. +set(expect_at_quick_exit "${ctors};at_quick_exit two;at_quick_exit one") +set(code_at_quick_exit 15) +set(expect_at_quick_exit_exit "${ctors};${handlers}") +set(code_at_quick_exit_exit 16) +set(expect_at_quick_exit__exit "${ctors}") +set(code_at_quick_exit__exit 17) +# The exit lock serializes cleanup: a second thread's _cexit waits for main's drain (its own thread_local destructor +# then runs, and the table is empty), and a registration from a second thread during a quick_exit drain waits too, +# so the handler it registers never runs. +set(expect_concurrent_cexit "${ctors};slow handler started;ctor thread_local second;second _cexit entered;slow handler done;${handlers};dtor thread_local second;second _cexit returned;after _cexit") +set(code_concurrent_cexit 18) +set(expect_quick_exit_register "${ctors};quick slow started;second registering;quick slow done;at_quick_exit one") +set(code_quick_exit_register 19) +# A handler that throws: terminate(), so abort() and its exit code 3; the handlers after it do not run. +set(expect_quick_exit_throw "${ctors};quick throw") +set(code_quick_exit_throw 3) +set(expect_exit_throw "${ctors};atexit throw") +set(code_exit_throw 3) # The program's own lines, in order, without the prefix; everything gta6rt prints is dropped. function(guest_lines output result) @@ -48,7 +67,11 @@ function(guest_lines output result) endfunction() set(failures "") -foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit thread_local_exit thread_local_cexit) +set(modes return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit thread_local_exit thread_local_cexit + at_quick_exit at_quick_exit_exit at_quick_exit__exit concurrent_cexit quick_exit_register quick_exit_throw + exit_throw) +list(LENGTH modes mode_count) +foreach(mode IN LISTS modes) execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode} WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err) @@ -74,4 +97,4 @@ endforeach() if(failures) message(FATAL_ERROR "atexit/termination differences:${failures}") endif() -message(STATUS "tiny_atexit: 10 termination paths match the Windows sequence") +message(STATUS "tiny_atexit: ${mode_count} termination paths match the Windows sequence") diff --git a/runtime/test/fixtures/tiny_atexit.cpp b/runtime/test/fixtures/tiny_atexit.cpp index 2719f98f46..c05c1ba477 100644 --- a/runtime/test/fixtures/tiny_atexit.cpp +++ b/runtime/test/fixtures/tiny_atexit.cpp @@ -12,7 +12,16 @@ // 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). +// startup calls only when the image has one (this program has one in every mode, constructed only where used). +// at_quick_exit two at_quick_exit handlers, then quick_exit(15): they run newest first, the atexit ones do not +// at_quick_exit_exit the same handlers, then exit(16): only the atexit handlers run +// at_quick_exit__exit the same handlers, then _exit(17): none runs +// concurrent_cexit a second thread (with a thread_local of its own) calls _cexit() while main's _cexit() runs a +// slow handler: the CRT's exit lock holds it until the drain is done; main then returns 18 +// quick_exit_register a second thread calls at_quick_exit() while quick_exit(19) runs a slow handler: it waits +// for the drain, so its handler never runs +// quick_exit_throw an at_quick_exit handler throws: terminate(), so abort() and exit code 3, nothing else runs +// exit_throw an atexit handler throws: the same // One handler registers another while the handlers run: it must still run, next. #include #include // _cexit, _c_exit @@ -50,20 +59,90 @@ void handler_registers() { std::atexit(handler_late); } +// The concurrent modes: a slow handler on the main thread starts a second thread's call and waits until that thread +// is about to make it (g_second_calling, set just before the call), so every line the second thread prints before +// the call comes before "... done" under any scheduling. With the exit lock, the call then waits for the main +// thread's cleanup, and the sequence is fixed. The Sleep only gives the second thread time to reach the lock: if it +// were held off longer, a missing lock would go unseen (a false pass); a present one can never fail for it. +HANDLE g_slow_started = nullptr; +HANDLE g_second_calling = nullptr; +void wait_for_second_call() { + WaitForSingleObject(g_second_calling, INFINITE); + Sleep(300); +} + // concurrent_exit: while exit() runs this handler on the main thread, a second thread calls _exit(). The CRT lets // it go once the handlers are done, so either call may set the exit code: both use 7. -HANDLE g_slow_started = nullptr; void handler_slow() { say("slow handler started"); SetEvent(g_slow_started); - Sleep(300); + wait_for_second_call(); say("slow handler done"); } DWORD WINAPI quick_exit_thread(void*) { WaitForSingleObject(g_slow_started, INFINITE); + SetEvent(g_second_calling); _exit(7); } +void quick_one() { say("at_quick_exit one"); } +void quick_two() { say("at_quick_exit two"); } +void quick_late() { say("at_quick_exit late"); } + +// A thread_local of a second thread: the CRT's thread-local callback ends it when that thread calls _cexit(). +Tracer& second_thread_tracer() { + thread_local Tracer tracer("thread_local second"); + return tracer; +} + +// concurrent_cexit: main's _cexit() is running the slow handler when a second thread, with a thread_local of its +// own, calls _cexit(). The exit lock holds it until main's drain is done: its thread_local destructor then runs, +// the table is empty, and it returns. main waits for it before its last line, so the order is fixed. +HANDLE g_second_done = nullptr; +DWORD WINAPI cexit_thread(void*) { + WaitForSingleObject(g_slow_started, INFINITE); + (void)second_thread_tracer(); + say("second _cexit entered"); + SetEvent(g_second_calling); + _cexit(); + say("second _cexit returned"); + SetEvent(g_second_done); + return 0; +} + +// quick_exit_register: quick_exit() is running this slow handler when a second thread registers another one. The +// exit lock holds the registration until the drain is done, so the new handler never runs (natively, the process +// is gone before the registration returns). +void quick_slow() { + say("quick slow started"); + SetEvent(g_slow_started); + wait_for_second_call(); + say("quick slow done"); +} +DWORD WINAPI register_thread(void*) { + WaitForSingleObject(g_slow_started, INFINITE); + say("second registering"); + SetEvent(g_second_calling); + std::at_quick_exit(quick_late); + return 0; +} + +// quick_exit_throw, exit_throw: a handler that lets a C++ exception escape. The CRT calls terminate(), whose default +// handler aborts: exit code 3. No error box or fault report for the native run (a headless test). +struct Thrown {}; +void quick_throws() { + say("quick throw"); + throw Thrown{}; +} +void handler_throws() { + say("atexit throw"); + throw Thrown{}; +} +void headless_abort() { + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); +} + } // namespace int main(int argc, char** argv) { @@ -72,8 +151,9 @@ int main(int argc, char** argv) { std::atexit(handler_registers); std::atexit(handler_two); say("main"); + g_slow_started = CreateEventW(nullptr, TRUE, FALSE, nullptr); + g_second_calling = CreateEventW(nullptr, TRUE, FALSE, nullptr); if (!std::strcmp(mode, "concurrent_exit")) { - g_slow_started = CreateEventW(nullptr, TRUE, FALSE, nullptr); std::atexit(handler_slow); CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr)); std::exit(7); @@ -101,5 +181,38 @@ int main(int argc, char** argv) { say("after _c_exit"); return 12; } + if (!std::strncmp(mode, "at_quick_exit", 13)) { + std::at_quick_exit(quick_one); + std::at_quick_exit(quick_two); + if (!std::strcmp(mode, "at_quick_exit")) std::quick_exit(15); + if (!std::strcmp(mode, "at_quick_exit_exit")) std::exit(16); + if (!std::strcmp(mode, "at_quick_exit__exit")) _exit(17); + } + if (!std::strcmp(mode, "concurrent_cexit")) { + g_second_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + std::atexit(handler_slow); + CloseHandle(CreateThread(nullptr, 0, cexit_thread, nullptr, 0, nullptr)); + _cexit(); + WaitForSingleObject(g_second_done, INFINITE); + say("after _cexit"); + return 18; + } + if (!std::strcmp(mode, "quick_exit_register")) { + std::at_quick_exit(quick_one); + std::at_quick_exit(quick_slow); + CloseHandle(CreateThread(nullptr, 0, register_thread, nullptr, 0, nullptr)); + std::quick_exit(19); + } + if (!std::strcmp(mode, "quick_exit_throw")) { + headless_abort(); + std::at_quick_exit(quick_one); + std::at_quick_exit(quick_throws); + std::quick_exit(20); + } + if (!std::strcmp(mode, "exit_throw")) { + headless_abort(); + std::atexit(handler_throws); + std::exit(21); + } return 3; }