From: Jorge Gonzalez <[email protected]>

winpthreads: pthread_detach of an already-ended thread recycles its
_pthread_v while the thread's DLL_THREAD_DETACH still reaches it
through _pthread_tls

Mechanism:

1. `pthread_create_wrapper` (l.1524) runs the thread function. If the
thread is still joinable (`tv->h != NULL`) when the function returns,
i.e. `pthread_detach` has not run yet, the wrapper only sets
`tv->ended = 1` (l.1582) and calls `_endthreadex`. The thread's TLS
slot `_pthread_tls` still points at `tv`.

2. `pthread_detach` (l.1798) sees `tv->ended` and calls
`push_pthread_mem(tv)` (l.1832): `memset` to zero, onto the reuse pool
(l.318-341).

3. The next `pthread_create` (l.1604) pops the same struct and fills
`func`, `ret_arg`, `ended = 0` for the NEW thread;
`std::thread::detach()` then sets PTHREAD_CREATE_DETACHED.

4. The OLD thread's `DLL_THREAD_DETACH` callback `__dyn_tls_pthread`
(l.439, branch l.487-503) runs late (CPU overload, or any delay
between thread exit and the notification), reads the same struct
through its own TLS slot, sees `ended == 0` and DETACHED, takes the
"detached thread ended" branch and calls `push_pthread_mem` on the NEW
thread's struct.

5. The new thread finds `tv->func == NULL` (l.1547) and exits without
running its body (exit code 128, the wrapper's default), or, if the
memset lands between the two reads, calls `func(NULL)` and crashes.

Needs: a thread that ends before `pthread_detach` is called on it,
then another `pthread_create` before the first one's
DLL_THREAD_DETACH. A joined thread cannot trigger it (the join waits
for the handle, signalled after the callbacks).

Link: https://bugzilla.redhat.com/show_bug.cgi?id=2549482
---
 mingw-w64-libraries/winpthreads/src/thread.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/mingw-w64-libraries/winpthreads/src/thread.c 
b/mingw-w64-libraries/winpthreads/src/thread.c
index 29b8af66a..922ab2d7d 100644
--- a/mingw-w64-libraries/winpthreads/src/thread.c
+++ b/mingw-w64-libraries/winpthreads/src/thread.c
@@ -1620,6 +1620,10 @@ pthread_create_wrapper (void *args)
          destroying it again in __dyn_tls_thread later on. */
       tv->p_clock = PTHREAD_MUTEX_INITIALIZER;
       tv->ended = 1;
+      /* GH #328 experiment: once ended, tv belongs to whoever joins or 
detaches
+         us, and may be recycled for a new thread before our DLL_THREAD_DETACH
+         runs -- so that callback must not find it through our TLS slot. */
+      TlsSetValue (_pthread_tls, NULL);
     }
   while (pthread_mutex_unlock (&mtx_pthr_locked) == 0)
    Sleep (0);
-- 
2.55.0



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

Reply via email to