I think I have found a bug in winpthreads: dll.c:
```
#include <pthread.h>
#include <stdio.h>
static pthread_key_t* dll_key;
__declspec(dllexport)
void
set_dll_pthread_key(pthread_key_t* key)
{
dll_key = key;
}
int
__stdcall
DllMain(void* instance, unsigned long reason, void* reserved)
{
if((reason == 2) && dll_key) {
// DLL_THREAD_ATTACH
pthread_setspecific(*dll_key, (void*) "DllMain");
fprintf(stderr,
"in DllMain: key = %d, str = %s\n",
*dll_key, (char*) pthread_getspecific(*dll_key));
}
return 1;
}
```
exe.c:
```
#include <pthread.h>
#include <stdio.h>
#include <assert.h>
static pthread_key_t exe_key;
__declspec(dllimport)
void
set_dll_pthread_key(pthread_key_t* key);
void*
thread_fn(void* arg)
{
fprintf(stderr,
"in thread_fn 1: key = %d, str = %s\n",
exe_key, (char*) pthread_getspecific(exe_key));
pthread_setspecific(exe_key, (void*) "thread_fn");
fprintf(stderr,
"in thread_fn 2: key = %d, str = %s\n",
exe_key, (char*) pthread_getspecific(exe_key));
return NULL;
}
void
tls_dtor(void* value)
{
fprintf(stderr,
"in tls_dtor: key = %d, str = %s\n",
exe_key, (char*) value);
}
int
main(void)
{
int err = pthread_key_create(&exe_key, tls_dtor);
assert(err == 0);
set_dll_pthread_key(&exe_key);
pthread_t pthread;
err = pthread_create(&pthread, NULL, thread_fn, NULL);
assert(err == 0);
fprintf(stderr, "thread created\n");
err = pthread_join(pthread, NULL);
assert(err == 0);
fprintf(stderr, "thread joined\n");
}
```
This can be compiled like
```
CC=${CC:-"gcc"}
${CC} dll.c -Wall -pthread -shared -o test.dll -Wl,--out-implib,libtest.dll.a
${CC} exe.c -Wall -pthread libtest.dll.a -o test.exe
./test.exe
```
which gives
```
thread created
in DllMain: key = 0, str = DllMain
in thread_fn 1: key = 0, str = (null)
in thread_fn 2: key = 0, str = thread_fn
in tls_dtor: key = 0, str = thread_fn
thread joined
```
The DLL calls `pthread_setspecific()`, which calls `__pthread_self_lite()`, which happens before
`pthread_create_wrapper()` begins execution, so the current thread doesn't have a pthread structure yet.
In this case `__pthread_self_lite()` allocates a blank structure and assigns a pointer to `_pthread_tls`,
which is later overwritten by `pthread_create_wrapper()`. The previous structure leaks, along with the
event handle, the thread handle, and all TLS keys.
The Microsoft threads DLL doesn't seem to be affected; but linking their static CRT causes assertion failures when `tss_set()` is called from `DllMain()`.
-- Best regards, LIU Hao
OpenPGP_signature.asc
Description: OpenPGP digital signature
_______________________________________________ Mingw-w64-public mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/mingw-w64-public
