+
+#if !TEST_W32_NO_DLLMAIN
+
+/*
+ * On Windows, DLLs are notified of thread exit via the DllMain entry point.
+ * This works in all versions.
+ */
+#if !DLL_EXPORT
+static
+#endif
+BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID p)
+{
+ if (reason == DLL_THREAD_DETACH && tls_key != TLS_OUT_OF_INDEXES)
+ free(TlsGetValue(tls_key));
+
+ return TRUE;
+}
+
+/*
+ * We can achieve similar behaviour with static linking executables by
+ * putting a pointer to the entry point in a special section.
+ *
+ * I believe this is supported beginning around Windows XP.
+ */
+#if !DLL_EXPORT
+#pragma data_seg(".CRT$XLF")
+#if __GNUC__
+__attribute__((section(".CRT$XLF")))
+#endif
+PIMAGE_TLS_CALLBACK cdecl__tls_hook = (PIMAGE_TLS_CALLBACK)DllMain;
+#pragma data_seg()
+#endif
+
+#endif