The standard says that destructors of thread local objects should be
invoked before any other destructors. Since the destructors are called
by the CRT via what has been registered via atexit (ordered so that the
function registered last will be executed first), we need to use this
API from UCRT to request a function to be executed before any other
atexit callback.

Signed-off-by: Martin Storsjö <mar...@martin.st>
---
 mingw-w64-crt/crt/cxa_atexit.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/mingw-w64-crt/crt/cxa_atexit.c b/mingw-w64-crt/crt/cxa_atexit.c
index 1cd042b..77762eb 100644
--- a/mingw-w64-crt/crt/cxa_atexit.c
+++ b/mingw-w64-crt/crt/cxa_atexit.c
@@ -14,6 +14,7 @@
 #include <assert.h>
 #include <stdio.h>
 #include <corecrt_startup.h>
+#include <process.h>
 
 
 typedef void (__thiscall * dtor)(void*);
@@ -34,6 +35,7 @@ struct thread_dtors {
 };
 
 HANDLE __dso_handle;
+extern char __mingw_module_is_dll;
 
 static CRITICAL_SECTION lock;
 static int inited = 0;
@@ -125,6 +127,16 @@ static void WINAPI tls_callback(HANDLE hDllHandle, DWORD 
dwReason, LPVOID __UNUS
     if (inited == 0) {
       InitializeCriticalSection(&lock);
       __dso_handle = hDllHandle;
+      // We can only call _register_thread_local_exe_atexit_callback once
+      // in a thread; if we call it a second time the process terminates.
+      // When DLLs are unloaded, this callback is invoked before we run the
+      // _onexit tables, but for exes, we need to ask this to be called before
+      // all other registered atexit functions.
+      // Since we are registered as a normal TLS callback, we will be called
+      // another time later as well, but that doesn't matter, it's safe to
+      // invoke this with DLL_PROCESS_DETACH twice.
+      if (!__mingw_module_is_dll)
+        _register_thread_local_exe_atexit_callback(tls_callback);
     }
     inited = 1;
     break;
-- 
2.7.4


------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot
_______________________________________________
Mingw-w64-public mailing list
Mingw-w64-public@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to