On WinNT systems with older CRT DLL library, the printf() crashes when is
called from main EXE's native PE TLS callback for DLL_PROCESS_DETACH event.
Seems that this is because CRT DLL library already deinitialized memory or
stdio handles.

Instead of CRT printf() function in PE TLS callback, use native WinAPI
WriteFile() function, which can be called at anytime of the process
lifetime. Retrieve a copy/duplicate of stdout WinAPI HANDLE needed for
WriteFile() via DuplicateHandle() + _get_osfhandle() functions.
---
 .../testcases/t_tls_exe_native_process_detach.c      | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/mingw-w64-crt/testcases/t_tls_exe_native_process_detach.c 
b/mingw-w64-crt/testcases/t_tls_exe_native_process_detach.c
index e1c02c17d56d..527550a563e4 100644
--- a/mingw-w64-crt/testcases/t_tls_exe_native_process_detach.c
+++ b/mingw-w64-crt/testcases/t_tls_exe_native_process_detach.c
@@ -1,5 +1,6 @@
 #include <stdio.h>
 #include <stdlib.h>
+#include <io.h>
 
 #ifndef WIN32_LEAN_AND_MEAN
 #define WIN32_LEAN_AND_MEAN
@@ -10,6 +11,7 @@
 #include "libtest.h"
 
 static int main_success = 0;
+static HANDLE stdout_handle = NULL;
 
 #if defined(__i386__)
 /* We need to make sure that we align the stack to 16 bytes for the sake of 
SSE */
@@ -18,7 +20,11 @@ __attribute__((force_align_arg_pointer))
 static void WINAPI pe_tls_callback(HANDLE handle __attribute__((unused)), 
DWORD reason, LPVOID reserved __attribute__((unused)))
 {
   if (reason == DLL_PROCESS_DETACH) {
-    printf("SUCCESS: PE TLS callback for DLL_PROCESS_DETACH was called\n");
+    /* Do not CRT functions, at this stage they can be already deinitialized */
+    if (stdout_handle != NULL && stdout_handle != INVALID_HANDLE_VALUE) {
+      static const char buffer[] = "SUCCESS: PE TLS callback for 
DLL_PROCESS_DETACH was called\r\n";
+      WriteFile(stdout_handle, buffer, sizeof(buffer)-1, &(DWORD){0}, NULL);
+    }
     /* exit, _exit, or ExitProcess calls TLS callbacks, so use 
TerminateProcess() which is not calling them */
     TerminateProcess(GetCurrentProcess(), main_success ? 0 : 1);
   }
@@ -42,6 +48,10 @@ int main(void)
   }
 
   printf("Checking if the PE TLS callback for DLL_PROCESS_DETACH would be 
called...\n");
+
+  /* Store copy of the WinAPI stdout HANDLE as CRT stdio functions cannot be 
used in PE TLS callback during DLL_PROCESS_DETACH */
+  DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(STDOUT_FILENO), 
GetCurrentProcess(), &stdout_handle, 0, FALSE, DUPLICATE_SAME_ACCESS);
+
   main_success = 1;
   return 1; /* TLS callback changes return code to 0 */
 }
-- 
2.20.1



_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to