Possiblly bug of cygwin1.dll

Takashi Yano takashi.yano@nifty.ne.jp
Mon Jan 22 03:30:23 GMT 2024


On Sun, 21 Jan 2024 14:30:00 +0100
ASSI wrote:
> Takashi Yano via Cygwin writes:
> > I found the cause. In pthread.h of cygwin, PTHREAD_ONCE_INIT is defined as:
> > #define PTHREAD_ONCE_INIT { PTHREAD_MUTEX_INITIALIZER, 0 }
> > however, libstdc++ initializes non-static pthread_once_t using this macro.
> 
> https://www.ibm.com/docs/en/aix/7.3?topic=p-pthread-once-init-macro
> https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_once.html
> 
> "The behavior of pthread_once() is undefined if once_control has
> automatic storage duration or is not initialized by PTHREAD_ONCE_INIT."
> 
> > I cannot find the POSIX statement that only static pthread_once_t can be
> > initialized using PTHREAD_ONCE_INIT. If I do not overlook something,
> > this is the problem of cygwin side, isn't it?
> 
> You can initialize just about anything with PTHREAD_ONCE_INIT, but you
> cannot expect the resulting structure to work as intended if there is
> more than instance per library / program, so the libstdc++ object should
> be a singleton, not automatic.
> 
> Still looks like ATWIL to me…

Thanks for the information.

Anyway, I confirmed the two patches (one is for gcc, the other is for cygwin)
resolve the issue.

PATCH1: (for gcc)
Do not use PTHREAD_MUTEX_INITIALIZER etc. for non-static pthread_mutex_t.
diff -ur origsrc/gcc-13-20230902/libgcc/gthr-posix.h src/gcc-13-20230902/libgcc/gthr-posix.h
--- origsrc/gcc-13-20230902/libgcc/gthr-posix.h	2023-09-03 07:32:49.000000000 +0900
+++ src/gcc-13-20230902/libgcc/gthr-posix.h	2024-01-22 09:04:54.342189600 +0900
@@ -34,6 +34,12 @@
 
 #include <pthread.h>
 
+#ifdef __CYGWIN__
+#define _GTHREAD_USE_MUTEX_INIT_FUNC 1
+#define _GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC 1
+#define _GTHREAD_USE_COND_INIT_FUNC 1
+#endif
+
 #if ((defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)) \
      || !defined(_GTHREAD_USE_MUTEX_TIMEDLOCK))
 # include <unistd.h>


PATCH2: (for cygwin)
Avoid handle leak caused when non-static pthread_once_t is initialized
with PTHREAD_ONCE_INIT
diff --git a/winsup/cygwin/thread.cc b/winsup/cygwin/thread.cc
index 7bb4f9fc8..127569160 100644
--- a/winsup/cygwin/thread.cc
+++ b/winsup/cygwin/thread.cc
@@ -2060,6 +2060,9 @@ pthread::once (pthread_once_t *once_control, void (*init_routine) (void))
     {
       init_routine ();
       once_control->state = 1;
+      pthread_mutex_unlock (&once_control->mutex);
+      while (pthread_mutex_destroy (&once_control->mutex) == EBUSY);
+      return 0;
     }
   /* Here we must remove our cancellation handler */
   pthread_mutex_unlock (&once_control->mutex);

-- 
Takashi Yano <takashi.yano@nifty.ne.jp>


More information about the Cygwin mailing list