]> sourceware.org Git - newlib-cygwin.git/blobdiff - winsup/cygwin/thread.cc
* cygwin.din (pthread_attr_getstack): Export.
[newlib-cygwin.git] / winsup / cygwin / thread.cc
index 53a4f8c31c5666bdde7c87a5f3bbd7fdeac825a9..0085320ade95da9363c4a246c011e4b94b00ebdf 100644 (file)
@@ -1,7 +1,7 @@
 /* thread.cc: Locking and threading module functions
 
    Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
-   2006, 2007, 2008, 2009, 2010 Red Hat, Inc.
+   2006, 2007, 2008, 2009, 2010, 2011 Red Hat, Inc.
 
 This file is part of Cygwin.
 
@@ -16,7 +16,7 @@ details. */
    the constraints we either pretend to be conformant, or return an error
    code.
 
-   Some caveats: PROCESS_SHARED objects while they pretend to be process
+   Some caveats: PROCESS_SHARED objects, while they pretend to be process
    shared, may not actually work.  Some test cases are needed to determine
    win32's behaviour.  My suspicion is that the win32 handle needs to be
    opened with different flags for proper operation.
@@ -37,9 +37,12 @@ details. */
 #include "fhandler.h"
 #include "dtable.h"
 #include "cygheap.h"
+#include "ntdll.h"
 
 extern "C" void __fp_lock_all ();
 extern "C" void __fp_unlock_all ();
+extern "C" int valid_sched_parameters(const struct sched_param *);
+extern "C" int sched_set_thread_priority(HANDLE thread, int priority);
 static inline verifyable_object_state
   verifyable_object_isvalid (void const * objectptr, thread_magic_t magic,
                             void *static_ptr1 = NULL,
@@ -48,6 +51,31 @@ static inline verifyable_object_state
 
 extern int threadsafe;
 
+const pthread_t pthread_mutex::_new_mutex = (pthread_t) 1;
+const pthread_t pthread_mutex::_unlocked_mutex = (pthread_t) 2;
+const pthread_t pthread_mutex::_destroyed_mutex = (pthread_t) 3;
+
+inline bool
+pthread_mutex::no_owner()
+{
+    int res;
+    if (!owner)
+      {
+       debug_printf ("NULL owner value");
+       res = 1;
+      }
+    else if (owner == _destroyed_mutex)
+      {
+       paranoid_printf ("attempt to use destroyed mutex");
+       res = 1;
+      }
+    else if (owner == _new_mutex || owner == _unlocked_mutex)
+      res = 1;
+    else
+      res = 0;
+    return res;
+}
+
 #undef __getreent
 extern "C" struct _reent *
 __getreent ()
@@ -99,9 +127,7 @@ verifyable_object_isvalid (void const *objectptr, thread_magic_t magic, void *st
                           void *static_ptr2, void *static_ptr3)
 {
   myfault efault;
-  /* Check for NULL pointer specifically since it is a cheap test and avoids the
-     overhead of setting up the fault handler.  */
-  if (!objectptr || efault.faulted ())
+  if (efault.faulted (objectptr))
     return INVALID_OBJECT;
 
   verifyable_object **object = (verifyable_object **) objectptr;
@@ -148,6 +174,14 @@ pthread_key::is_good_object (pthread_key_t const *key)
   return true;
 }
 
+inline bool
+pthread_spinlock::is_good_object (pthread_spinlock_t const *mutex)
+{
+  if (verifyable_object_isvalid (mutex, PTHREAD_SPINLOCK_MAGIC) != VALID_OBJECT)
+    return false;
+  return true;
+}
+
 inline bool
 pthread_mutex::is_good_object (pthread_mutex_t const *mutex)
 {
@@ -157,7 +191,7 @@ pthread_mutex::is_good_object (pthread_mutex_t const *mutex)
 }
 
 inline bool
-pthread_mutex::is_good_initializer (pthread_mutex_t const *mutex)
+pthread_mutex::is_initializer (pthread_mutex_t const *mutex)
 {
   if (verifyable_object_isvalid (mutex, PTHREAD_MUTEX_MAGIC,
                                 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
@@ -168,7 +202,7 @@ pthread_mutex::is_good_initializer (pthread_mutex_t const *mutex)
 }
 
 inline bool
-pthread_mutex::is_good_initializer_or_object (pthread_mutex_t const *mutex)
+pthread_mutex::is_initializer_or_object (pthread_mutex_t const *mutex)
 {
   if (verifyable_object_isvalid (mutex, PTHREAD_MUTEX_MAGIC,
                                 PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
@@ -178,17 +212,17 @@ pthread_mutex::is_good_initializer_or_object (pthread_mutex_t const *mutex)
   return true;
 }
 
+/* FIXME: Accommodate PTHREAD_MUTEX_ERRORCHECK */
 inline bool
-pthread_mutex::can_be_unlocked (pthread_mutex_t const *mutex)
+pthread_mutex::can_be_unlocked ()
 {
   pthread_t self = pthread::self ();
-
-  if (!is_good_object (mutex))
-    return false;
   /* Check if the mutex is owned by the current thread and can be unlocked.
    * Also check for the ANONYMOUS owner to cover NORMAL mutexes as well. */
-  return (*mutex)->recursion_counter == 1
-        && pthread::equal ((*mutex)->owner, self);
+  bool res = type == PTHREAD_MUTEX_NORMAL || no_owner ()
+            || (recursion_counter == 1 && pthread::equal (owner, self));
+  pthread_printf ("recursion_counter %d res %d", recursion_counter, res);
+  return res;
 }
 
 inline bool
@@ -217,7 +251,7 @@ pthread_cond::is_good_object (pthread_cond_t const *cond)
 }
 
 inline bool
-pthread_cond::is_good_initializer (pthread_cond_t const *cond)
+pthread_cond::is_initializer (pthread_cond_t const *cond)
 {
   if (verifyable_object_isvalid (cond, PTHREAD_COND_MAGIC, PTHREAD_COND_INITIALIZER) != VALID_STATIC_OBJECT)
     return false;
@@ -225,7 +259,7 @@ pthread_cond::is_good_initializer (pthread_cond_t const *cond)
 }
 
 inline bool
-pthread_cond::is_good_initializer_or_object (pthread_cond_t const *cond)
+pthread_cond::is_initializer_or_object (pthread_cond_t const *cond)
 {
   if (verifyable_object_isvalid (cond, PTHREAD_COND_MAGIC, PTHREAD_COND_INITIALIZER) == INVALID_OBJECT)
     return false;
@@ -242,7 +276,7 @@ pthread_rwlock::is_good_object (pthread_rwlock_t const *rwlock)
 }
 
 inline bool
-pthread_rwlock::is_good_initializer (pthread_rwlock_t const *rwlock)
+pthread_rwlock::is_initializer (pthread_rwlock_t const *rwlock)
 {
   if (verifyable_object_isvalid (rwlock, PTHREAD_RWLOCK_MAGIC, PTHREAD_RWLOCK_INITIALIZER) != VALID_STATIC_OBJECT)
     return false;
@@ -250,7 +284,7 @@ pthread_rwlock::is_good_initializer (pthread_rwlock_t const *rwlock)
 }
 
 inline bool
-pthread_rwlock::is_good_initializer_or_object (pthread_rwlock_t const *rwlock)
+pthread_rwlock::is_initializer_or_object (pthread_rwlock_t const *rwlock)
 {
   if (verifyable_object_isvalid (rwlock, PTHREAD_RWLOCK_MAGIC, PTHREAD_RWLOCK_INITIALIZER) == INVALID_OBJECT)
     return false;
@@ -344,7 +378,7 @@ List<pthread> pthread::threads;
 
 /* member methods */
 pthread::pthread ():verifyable_object (PTHREAD_MAGIC), win32_obj_id (0),
-                   valid (false), suspended (false),
+                   valid (false), suspended (false), canceled (false),
                    cancelstate (0), canceltype (0), cancel_event (0),
                    joiner (NULL), next (NULL), cleanup_stack (NULL)
 {
@@ -367,7 +401,7 @@ pthread::~pthread ()
 bool
 pthread::create_cancel_event ()
 {
-  cancel_event = ::CreateEvent (&sec_none_nih, TRUE, FALSE, NULL);
+  cancel_event = ::CreateEvent (&sec_none_nih, true, false, NULL);
   if (!cancel_event)
     {
       system_printf ("couldn't create cancel event, %E");
@@ -402,7 +436,7 @@ pthread::precreate (pthread_attr *newattr)
       return;
     }
   /* Change the mutex type to NORMAL to speed up mutex operations */
-  mutex.type = PTHREAD_MUTEX_NORMAL;
+  mutex.set_type (PTHREAD_MUTEX_NORMAL);
   if (!create_cancel_event ())
     magic = 0;
 }
@@ -433,7 +467,7 @@ pthread::create (void *(*func) (void *), pthread_attr *newattr,
     {
       postcreate ();
       while (!cygtls)
-       low_priority_sleep (0);
+       yield ();
     }
   retval = magic;
   mutex.unlock ();
@@ -504,6 +538,7 @@ pthread::cancel ()
     {
       // cancel deferred
       mutex.unlock ();
+      canceled = true;
       SetEvent (cancel_event);
       return 0;
     }
@@ -528,189 +563,339 @@ pthread::cancel ()
   ResumeThread (win32_obj_id);
 
   return 0;
-/*
-  TODO: insert  pthread_testcancel into the required functions
-  the required function list is: *indicates done, X indicates not present in cygwin.
-aio_suspend ()
-*close ()
-*creat ()
-fcntl ()
-fsync ()
-getmsg ()
-getpmsg ()
-lockf ()
-mq_receive ()
-mq_send ()
-msgrcv ()
-msgsnd ()
-msync ()
-nanosleep ()
-open ()
-*pause ()
-poll ()
-pread ()
-*pthread_cond_timedwait ()
-*pthread_cond_wait ()
-*pthread_join ()
-*pthread_testcancel ()
-putmsg ()
-putpmsg ()
-pwrite ()
-read ()
-readv ()
-select ()
-*sem_wait ()
-*sigpause ()
-*sigsuspend ()
-sigtimedwait ()
-sigwait ()
-sigwaitinfo ()
-*sleep ()
-*system ()
-tcdrain ()
-*usleep ()
-*wait ()
-*wait3()
-waitid ()
-*waitpid ()
-write ()
-writev ()
-
-the optional list is:
-catclose ()
-catgets ()
-catopen ()
-closedir ()
-closelog ()
-ctermid ()
-dbm_close ()
-dbm_delete ()
-dbm_fetch ()
-dbm_nextkey ()
-dbm_open ()
-dbm_store ()
-dlclose ()
-dlopen ()
-endgrent ()
-endpwent ()
-endutxent ()
-fclose ()
-fcntl ()
-fflush ()
-fgetc ()
-fgetpos ()
-fgets ()
-fgetwc ()
-fgetws ()
-fopen ()
-fprintf ()
-fputc ()
-fputs ()
-fputwc ()
-fputws ()
-fread ()
-freopen ()
-fscanf ()
-fseek ()
-fseeko ()
-fsetpos ()
-ftell ()
-ftello ()
-ftw ()
-fwprintf ()
-fwrite ()
-fwscanf ()
-getc ()
-getc_unlocked ()
-getchar ()
-getchar_unlocked ()
-getcwd ()
-getdate ()
-getgrent ()
-getgrgid ()
-getgrgid_r ()
-getgrnam ()
-getgrnam_r ()
-getlogin ()
-getlogin_r ()
-getpwent ()
-*getpwnam ()
-*getpwnam_r ()
-*getpwuid ()
-*getpwuid_r ()
-gets ()
-getutxent ()
-getutxid ()
-getutxline ()
-getw ()
-getwc ()
-getwchar ()
-getwd ()
-glob ()
-iconv_close ()
-iconv_open ()
-ioctl ()
-lseek ()
-mkstemp ()
-nftw ()
-opendir ()
-openlog ()
-pclose ()
-perror ()
-popen ()
-printf ()
-putc ()
-putc_unlocked ()
-putchar ()
-putchar_unlocked ()
-puts ()
-pututxline ()
-putw ()
-putwc ()
-putwchar ()
-readdir ()
-readdir_r ()
-remove ()
-rename ()
-rewind ()
-rewinddir ()
-scanf ()
-seekdir ()
-semop ()
-setgrent ()
-setpwent ()
-setutxent ()
-strerror ()
-syslog ()
-tmpfile ()
-tmpnam ()
-ttyname ()
-ttyname_r ()
-ungetc ()
-ungetwc ()
-unlink ()
-vfprintf ()
-vfwprintf ()
-vprintf ()
-vwprintf ()
-wprintf ()
-wscanf ()
-
-Note, that for fcntl (), for any value of the cmd argument.
-
-And we must not introduce cancellation points anywhere else that's part of the posix or
-opengroup specs.
- */
 }
 
+/* TODO: Insert pthread_testcancel into the required functions.
+
+   Here are the lists of required and optional functions per POSIX.1-2001
+   and POSIX.1-2008. A star (*) indicates that the Cygwin function already
+   is a cancellation point (aka "calls pthread_testcancel"), an o (o)
+   indicates that the function is not implemented in Cygwin.
+
+   Required cancellation points:
+
+    * accept ()
+    o aio_suspend ()
+    o clock_nanosleep ()
+    * close ()
+    * connect ()
+    * creat ()
+    * fcntl () F_SETLKW
+    * fdatasync ()
+    * fsync ()
+    o getmsg ()
+    o getpmsg ()
+    * lockf () F_LOCK
+    * mq_receive ()
+    * mq_send ()
+    * mq_timedreceive ()
+    * mq_timedsend ()
+      msgrcv ()
+      msgsnd ()
+    * msync ()
+    * nanosleep ()
+    * open ()
+    * openat ()
+    * pause ()
+      poll ()
+    * pread ()
+      pselect ()
+    * pthread_cond_timedwait ()
+    * pthread_cond_wait ()
+    * pthread_join ()
+    * pthread_testcancel ()
+    o putmsg ()
+    o putpmsg ()
+    * pwrite ()
+    * read ()
+    * readv ()
+    * recv ()
+    * recvfrom ()
+    * recvmsg ()
+      select ()
+    * sem_timedwait ()
+    * sem_wait ()
+    * send ()
+    * sendmsg ()
+    * sendto ()
+    * sigpause ()
+    * sigsuspend ()
+    o sigtimedwait ()
+    * sigwait ()
+    * sigwaitinfo ()
+    * sleep ()
+    * system ()
+    * tcdrain ()
+    * usleep ()
+    * wait ()
+    * wait3()
+    o waitid ()
+    * waitpid ()
+    * write ()
+    * writev ()
+
+   Optional cancellation points:
+
+      access ()
+      asctime ()
+      asctime_r ()
+      catclose ()      Implemented externally: libcatgets
+      catgets ()       Implemented externally: libcatgets
+      catopen ()       Implemented externally: libcatgets
+      chmod ()
+      chown ()
+      closedir ()
+      closelog ()
+      ctermid ()
+      ctime ()
+      ctime_r ()
+      dbm_close ()     Implemented externally: libgdbm
+      dbm_delete ()    Implemented externally: libgdbm
+      dbm_fetch ()     Implemented externally: libgdbm
+      dbm_nextkey ()   Implemented externally: libgdbm
+      dbm_open ()      Implemented externally: libgdbm
+      dbm_store ()     Implemented externally: libgdbm
+      dlclose ()
+      dlopen ()
+      dprintf ()
+      endgrent ()
+      endhostent ()
+    o endnetent ()
+      endprotoent ()
+      endpwent ()
+      endservent ()
+      endutxent ()
+      faccessat ()
+      fchmod ()
+      fchmodat ()
+      fchown ()
+      fchownat ()
+    * fclose ()
+    * fcntl () (any value)
+      fflush ()
+      fgetc ()
+      fgetpos ()
+      fgets ()
+      fgetwc ()
+      fgetws ()
+    o fmtmsg ()
+      fopen ()
+      fpathconf ()
+      fprintf ()
+      fputc ()
+      fputs ()
+      fputwc ()
+      fputws ()
+      fread ()
+      freopen ()
+      fscanf ()
+      fseek ()
+      fseeko ()
+      fsetpos ()
+      fstat ()
+      fstatat ()
+      ftell ()
+      ftello ()
+      ftw ()
+      futimens ()
+      fwprintf ()
+      fwrite ()
+      fwscanf ()
+      getaddrinfo ()
+      getc ()
+      getc_unlocked ()
+      getchar ()
+      getchar_unlocked ()
+      getcwd ()
+    o getdate ()
+      getdelim ()
+      getgrent ()
+      getgrgid ()
+      getgrgid_r ()
+      getgrnam ()
+      getgrnam_r ()
+      gethostbyaddr ()
+      gethostbyname ()
+      gethostent ()
+      gethostid ()
+      gethostname ()
+      getline ()
+      getlogin ()
+      getlogin_r ()
+      getnameinfo ()
+    o getnetbyaddr ()
+    o getnetbyname ()
+    o getnetent ()
+      getopt () (if opterr is nonzero)
+      getprotobyname ()
+      getprotobynumber ()
+      getprotoent ()
+      getpwent ()
+    * getpwnam ()
+    * getpwnam_r ()
+    * getpwuid ()
+    * getpwuid_r ()
+      gets ()
+      getservbyname ()
+      getservbyport ()
+      getservent ()
+      getutxent ()
+      getutxid ()
+      getutxline ()
+      getwc ()
+      getwchar ()
+      getwd ()
+      glob ()
+      iconv_close ()   Implemented externally: libiconv
+      iconv_open ()    Implemented externally: libiconv
+      ioctl ()
+      link ()
+      linkat ()
+    o lio_listio ()
+      localtime ()
+      localtime_r ()
+    * lockf ()
+      lseek ()
+      lstat ()
+      mkdir ()
+      mkdirat ()
+      mkdtemp ()
+      mkfifo ()
+      mkfifoat ()
+      mknod ()
+      mknodat ()
+      mkstemp ()
+      mktime ()
+      nftw ()
+      opendir ()
+      openlog ()
+      pathconf ()
+      pclose ()
+      perror ()
+      popen ()
+      posix_fadvise ()
+      posix_fallocate ()
+      posix_madvise ()
+      posix_openpt ()
+    o posix_spawn ()
+    o posix_spawnp ()
+    o posix_trace_clear ()
+    o posix_trace_close ()
+    o posix_trace_create ()
+    o posix_trace_create_withlog ()
+    o posix_trace_eventtypelist_getnext_id ()
+    o posix_trace_eventtypelist_rewind ()
+    o posix_trace_flush ()
+    o posix_trace_get_attr ()
+    o posix_trace_get_filter ()
+    o posix_trace_get_status ()
+    o posix_trace_getnext_event ()
+    o posix_trace_open ()
+    o posix_trace_rewind ()
+    o posix_trace_set_filter ()
+    o posix_trace_shutdown ()
+    o posix_trace_timedgetnext_event ()
+    o posix_typed_mem_open ()
+      printf ()
+    o psiginfo ()
+    o psignal ()
+      pthread_rwlock_rdlock ()
+      pthread_rwlock_timedrdlock ()
+      pthread_rwlock_timedwrlock ()
+      pthread_rwlock_wrlock ()
+      putc ()
+      putc_unlocked ()
+      putchar ()
+      putchar_unlocked ()
+      puts ()
+      pututxline ()
+      putwc ()
+      putwchar ()
+      readdir ()
+      readdir_r ()
+      readlink ()
+      readlinkat ()
+      remove ()
+      rename ()
+      renameat ()
+      rewind ()
+      rewinddir ()
+      scandir ()
+      scanf ()
+      seekdir ()
+      semop ()
+      setgrent ()
+      sethostent ()
+    o setnetent ()
+      setprotoent ()
+      setpwent ()
+      setservent ()
+      setutxent ()
+      sigpause ()
+      stat ()
+      strerror ()
+      strerror_r ()
+      strftime ()
+      symlink ()
+      symlinkat ()
+      sync ()
+      syslog ()
+      tmpfile ()
+      tmpnam ()
+      ttyname ()
+      ttyname_r ()
+      tzset ()
+      ungetc ()
+      ungetwc ()
+      unlink ()
+      unlinkat ()
+      utime ()
+      utimensat ()
+      utimes ()
+      vdprintf ()
+      vfprintf ()
+      vfwprintf ()
+      vprintf ()
+      vwprintf ()
+      wcsftime ()
+      wordexp ()
+      wprintf ()
+      wscanf ()
+
+   An implementation may also mark other functions not specified in the
+   standard as cancellation points.  In particular, an implementation is
+   likely to mark any nonstandard function that may block as a
+   cancellation point. */
+
 void
 pthread::testcancel ()
 {
   if (cancelstate == PTHREAD_CANCEL_DISABLE)
     return;
 
-  if (WaitForSingleObject (cancel_event, 0) == WAIT_OBJECT_0)
-    cancel_self ();
+  /* We check for the canceled flag first.  This allows to use the
+     pthread_testcancel function a lot without adding the overhead of
+     an OS call.  Only if the thread is marked as canceled, we wait for
+     cancel_event being really set, on the off-chance that pthread_cancel
+     gets interrupted before calling SetEvent. */
+  if (canceled)
+    {
+      WaitForSingleObject (cancel_event, INFINITE);
+      cancel_self ();
+    }
+}
+
+/* Return cancel event handle if it exists *and* cancel is not disabled.
+   This function is supposed to be used from other functions which are
+   cancelable and need the cancel event in a WFMO call. */
+HANDLE
+pthread::get_cancel_event ()
+{
+  pthread_t thread = pthread::self ();
+
+  return (thread && thread->cancel_event
+         && thread->cancelstate != PTHREAD_CANCEL_DISABLE)
+         ? thread->cancel_event : NULL;
 }
 
 void
@@ -737,7 +922,7 @@ cancelable_wait (HANDLE object, DWORD timeout,
   DWORD cancel_n;
   if (cancel_action == cw_no_cancel || !pthread::is_good_object (&thread) ||
       thread->cancelstate == PTHREAD_CANCEL_DISABLE)
-    cancel_n = (DWORD) -1;
+    cancel_n = WAIT_TIMEOUT + 1;
   else
     {
       cancel_n = WAIT_OBJECT_0 + num++;
@@ -745,8 +930,8 @@ cancelable_wait (HANDLE object, DWORD timeout,
     }
 
   DWORD sig_n;
-  if (sig_wait == cw_sig_nosig || &_my_tls != _main_tls)
-    sig_n = (DWORD) -1;
+  if (sig_wait == cw_sig_nosig)
+    sig_n = WAIT_TIMEOUT + 1;
   else
     {
       sig_n = WAIT_OBJECT_0 + num++;
@@ -877,6 +1062,7 @@ pthread::_fixup_after_fork ()
       magic = 0;
       valid = false;
       win32_obj_id = NULL;
+      canceled = false;
       cancel_event = NULL;
     }
 }
@@ -899,7 +1085,7 @@ pthread::resume ()
 
 pthread_attr::pthread_attr ():verifyable_object (PTHREAD_ATTR_MAGIC),
 joinable (PTHREAD_CREATE_JOINABLE), contentionscope (PTHREAD_SCOPE_PROCESS),
-inheritsched (PTHREAD_INHERIT_SCHED), stacksize (0)
+inheritsched (PTHREAD_INHERIT_SCHED), stackaddr (NULL), stacksize (0)
 {
   schedparam.sched_priority = 0;
 }
@@ -957,7 +1143,7 @@ pthread_cond::pthread_cond (pthread_condattr *attr) :
    * Change the mutex type to NORMAL.
    * This mutex MUST be of type normal
   */
-  mtx_in.type = PTHREAD_MUTEX_NORMAL;
+  mtx_in.set_type (PTHREAD_MUTEX_NORMAL);
 
   verifyable_mutex_obj = &mtx_out;
   if (!pthread_mutex::is_good_object (&verifyable_mutex_obj))
@@ -967,12 +1153,12 @@ pthread_cond::pthread_cond (pthread_condattr *attr) :
       return;
     }
   /* Change the mutex type to NORMAL to speed up mutex operations */
-  mtx_out.type = PTHREAD_MUTEX_NORMAL;
+  mtx_out.set_type (PTHREAD_MUTEX_NORMAL);
 
   sem_wait = ::CreateSemaphore (&sec_none_nih, 0, LONG_MAX, NULL);
   if (!sem_wait)
     {
-      debug_printf ("CreateSemaphore failed. %E");
+      pthread_printf ("CreateSemaphore failed. %E");
       magic = 0;
       return;
     }
@@ -1171,7 +1357,7 @@ pthread_rwlock::pthread_rwlock (pthread_rwlockattr *attr) :
       return;
     }
   /* Change the mutex type to NORMAL to speed up mutex operations */
-  mtx.type = PTHREAD_MUTEX_NORMAL;
+  mtx.set_type (PTHREAD_MUTEX_NORMAL);
 
   verifyable_cond_obj = &cond_readers;
   if (!pthread_cond::is_good_object (&verifyable_cond_obj))
@@ -1522,11 +1708,11 @@ pthread_mutex::init_mutex ()
 pthread_mutex::pthread_mutex (pthread_mutexattr *attr) :
   verifyable_object (0),       /* set magic to zero initially */
   lock_counter (0),
-  win32_obj_id (NULL), recursion_counter (0),
-  condwaits (0), owner (NULL),
+  win32_obj_id (NULL), owner (_new_mutex),
 #ifdef DEBUGGING
   tid (0),
 #endif
+  recursion_counter (0), condwaits (0),
   type (PTHREAD_MUTEX_ERRORCHECK),
   pshared (PTHREAD_PROCESS_PRIVATE)
 {
@@ -1548,9 +1734,14 @@ pthread_mutex::pthread_mutex (pthread_mutexattr *attr) :
 pthread_mutex::~pthread_mutex ()
 {
   if (win32_obj_id)
-    CloseHandle (win32_obj_id);
+    {
+      CloseHandle (win32_obj_id);
+      win32_obj_id = NULL;
+    }
 
   mutexes.remove (this);
+  owner = _destroyed_mutex;
+  magic = 0;
 }
 
 int
@@ -1559,9 +1750,10 @@ pthread_mutex::lock ()
   pthread_t self = ::pthread_self ();
   int result = 0;
 
-  if (InterlockedIncrement ((long *)&lock_counter) == 1)
+  if (InterlockedIncrement ((long *) &lock_counter) == 1)
     set_owner (self);
-  else if (type == PTHREAD_MUTEX_NORMAL || !pthread::equal (owner, self))
+  else if (type == PTHREAD_MUTEX_NORMAL /* potentially causes deadlock */
+          || !pthread::equal (owner, self))
     {
       cancelable_wait (win32_obj_id, INFINITE, cw_no_cancel, cw_sig_resume);
       set_owner (self);
@@ -1575,29 +1767,38 @@ pthread_mutex::lock ()
        result = EDEADLK;
     }
 
+  pthread_printf ("mutex %p, self %p, owner %p, lock_counter %d, recursion_counter %d",
+                 this, self, owner, lock_counter, recursion_counter);
   return result;
 }
 
 int
 pthread_mutex::unlock ()
 {
+  int res = 0;
   pthread_t self = ::pthread_self ();
-  if (!pthread::equal (owner, self))
-    return EPERM;
-
-  /* Don't try to unlock anything if recursion_counter == 0 initially.
-     That means that we've forked. */
-  if (recursion_counter > 0 && --recursion_counter == 0)
-    {
-      owner = NULL;
+  if (type == PTHREAD_MUTEX_NORMAL)
+    /* no error checking */;
+  else if (no_owner ())
+    res = type == PTHREAD_MUTEX_ERRORCHECK ? EINVAL : 0;
+  else if (!pthread::equal (owner, self))
+    res = EPERM;
+  if (!res && recursion_counter > 0 && --recursion_counter == 0)
+    /* Don't try to unlock anything if recursion_counter == 0.
+       This means the mutex was never locked or that we've forked. */
+    {
+      owner = (pthread_t) _unlocked_mutex;
 #ifdef DEBUGGING
       tid = 0;
 #endif
       if (InterlockedDecrement ((long *) &lock_counter))
        ::SetEvent (win32_obj_id); // Another thread is waiting
+      res = 0;
     }
 
-  return 0;
+  pthread_printf ("mutex %p, owner %p, self %p, lock_counter %d, recursion_counter %d, type %d, res %d",
+                 this, owner, self, lock_counter, recursion_counter, type, res);
+  return res;
 }
 
 int
@@ -1636,7 +1837,7 @@ pthread_mutex::destroy ()
 void
 pthread_mutex::_fixup_after_fork ()
 {
-  debug_printf ("mutex %p in _fixup_after_fork", this);
+  pthread_printf ("mutex %p", this);
   if (pshared != PTHREAD_PROCESS_PRIVATE)
     api_fatal ("pthread_mutex::_fixup_after_fork () doesn't understand PROCESS_SHARED mutex's");
 
@@ -1649,7 +1850,7 @@ pthread_mutex::_fixup_after_fork ()
 #endif
   win32_obj_id = ::CreateEvent (&sec_none_nih, false, false, NULL);
   if (!win32_obj_id)
-    api_fatal ("pthread_mutex::_fixup_after_fork () failed to recreate win32 semaphore for mutex");
+    api_fatal ("pthread_mutex::_fixup_after_fork () failed to recreate win32 event for mutex");
 }
 
 pthread_mutexattr::pthread_mutexattr ():verifyable_object (PTHREAD_MUTEXATTR_MAGIC),
@@ -1661,6 +1862,65 @@ pthread_mutexattr::~pthread_mutexattr ()
 {
 }
 
+/* pshared spinlocks
+
+   The infrastructure is provided by the underlying pthread_mutex class.
+   The rest is a simplification implementing spin locking. */
+
+pthread_spinlock::pthread_spinlock (int pshared) :
+  pthread_mutex (NULL)
+{
+  magic = PTHREAD_SPINLOCK_MAGIC;
+  set_type (PTHREAD_MUTEX_NORMAL);
+  set_shared (pshared);
+}
+
+int
+pthread_spinlock::lock ()
+{
+  pthread_t self = ::pthread_self ();
+  int result = -1;
+
+  do
+    {
+      if (InterlockedExchange ((long *) &lock_counter, 1) == 0)
+       {
+         set_owner (self);
+         result = 0;
+       }
+      else if (pthread::equal (owner, self))
+       result = EDEADLK;
+      else /* Minimal timeout to minimize CPU usage while still spinning. */
+       cancelable_wait (win32_obj_id, 1L, cw_no_cancel, cw_sig_resume);
+    }
+  while (result == -1);
+  pthread_printf ("spinlock %p, self %p, owner %p", this, self, owner);
+  return result;
+}
+
+int
+pthread_spinlock::unlock ()
+{
+  pthread_t self = ::pthread_self ();
+  int result = 0;
+
+  if (!pthread::equal (owner, self))
+    result = EPERM;
+  else
+    {
+      owner = (pthread_t) _unlocked_mutex;
+#ifdef DEBUGGING
+      tid = 0;
+#endif
+      InterlockedExchange ((long *) &lock_counter, 0);
+      ::SetEvent (win32_obj_id);
+      result = 0;
+    }
+  pthread_printf ("spinlock %p, owner %p, self %p, res %d",
+                 this, owner, self, result);
+  return result;
+}
+
 DWORD WINAPI
 pthread::thread_init_wrapper (void *arg)
 {
@@ -1977,11 +2237,35 @@ pthread_attr_setscope (pthread_attr_t *attr, int contentionscope)
   return 0;
 }
 
+extern "C" int
+pthread_attr_getstack (const pthread_attr_t *attr, void **addr, size_t *size)
+{
+  if (!pthread_attr::is_good_object (attr))
+    return EINVAL;
+  /* uses lowest address of stack on all platforms */
+  *addr = (void *)((int)(*attr)->stackaddr - (*attr)->stacksize);
+  *size = (*attr)->stacksize;
+  return 0;
+}
+
+extern "C" int
+pthread_attr_getstackaddr (const pthread_attr_t *attr, void **addr)
+{
+  if (!pthread_attr::is_good_object (attr))
+    return EINVAL;
+  /* uses stack address, which is the higher address on platforms
+     where the stack grows downwards, such as x86 */
+  *addr = (*attr)->stackaddr;
+  return 0;
+}
+
 extern "C" int
 pthread_attr_setstacksize (pthread_attr_t *attr, size_t size)
 {
   if (!pthread_attr::is_good_object (attr))
     return EINVAL;
+  if (size < PTHREAD_STACK_MIN)
+    return EINVAL;    
   (*attr)->stacksize = size;
   return 0;
 }
@@ -2121,6 +2405,51 @@ pthread::resume (pthread_t *thread)
   return 0;
 }
 
+extern "C" int
+pthread_getattr_np (pthread_t thread, pthread_attr_t *attr)
+{
+  const size_t sizeof_tbi = sizeof (THREAD_BASIC_INFORMATION);
+  PTHREAD_BASIC_INFORMATION tbi;
+  NTSTATUS ret;
+
+  if (!pthread::is_good_object (&thread))
+    return ESRCH;
+
+  /* attr may not be pre-initialized */
+  if (!pthread_attr::is_good_object (attr))
+  {
+    int rv = pthread_attr_init (attr);
+    if (rv != 0)
+      return rv;
+  }
+
+  (*attr)->joinable = thread->attr.joinable;
+  (*attr)->contentionscope = thread->attr.contentionscope;
+  (*attr)->inheritsched = thread->attr.inheritsched;
+  (*attr)->schedparam = thread->attr.schedparam;
+
+  tbi = (PTHREAD_BASIC_INFORMATION) malloc (sizeof_tbi);
+  ret = NtQueryInformationThread (thread->win32_obj_id, ThreadBasicInformation,
+                                  tbi, sizeof_tbi, NULL);
+
+  if (NT_SUCCESS (ret))
+    {
+      PNT_TIB tib = tbi->TebBaseAddress;
+      (*attr)->stackaddr = tib->StackBase;
+      /* stack grows downwards on x86 systems */
+      (*attr)->stacksize = (int)tib->StackBase - (int)tib->StackLimit;
+    }
+  else
+    {
+      debug_printf ("NtQueryInformationThread(ThreadBasicInformation), "
+                    "status %p", ret);
+      (*attr)->stackaddr = thread->attr.stackaddr;
+      (*attr)->stacksize = thread->attr.stacksize;
+    }
+
+  return 0;
+}
+
 /* provided for source level compatability.
    See http://www.opengroup.org/onlinepubs/007908799/xsh/pthread_getconcurrency.html
 */
@@ -2199,6 +2528,17 @@ pthread_setschedparam (pthread_t thread, int policy,
   return rv;
 }
 
+extern "C" int
+pthread_setschedprio (pthread_t thread, int priority)
+{
+  if (!pthread::is_good_object (&thread))
+    return ESRCH;
+  int rv =
+    sched_set_thread_priority (thread->win32_obj_id, priority);
+  if (!rv)
+    thread->attr.schedparam.sched_priority = priority;
+  return rv;
+}
 
 extern "C" int
 pthread_setspecific (pthread_key_t key, const void *value)
@@ -2222,7 +2562,7 @@ pthread_getspecific (pthread_key_t key)
 extern "C" int
 pthread_cond_destroy (pthread_cond_t *cond)
 {
-  if (pthread_cond::is_good_initializer (cond))
+  if (pthread_cond::is_initializer (cond))
     return 0;
   if (!pthread_cond::is_good_object (cond))
     return EINVAL;
@@ -2272,7 +2612,7 @@ pthread_cond::init (pthread_cond_t *cond, const pthread_condattr_t *attr)
 extern "C" int
 pthread_cond_broadcast (pthread_cond_t *cond)
 {
-  if (pthread_cond::is_good_initializer (cond))
+  if (pthread_cond::is_initializer (cond))
     return 0;
   if (!pthread_cond::is_good_object (cond))
     return EINVAL;
@@ -2285,7 +2625,7 @@ pthread_cond_broadcast (pthread_cond_t *cond)
 extern "C" int
 pthread_cond_signal (pthread_cond_t *cond)
 {
-  if (pthread_cond::is_good_initializer (cond))
+  if (pthread_cond::is_initializer (cond))
     return 0;
   if (!pthread_cond::is_good_object (cond))
     return EINVAL;
@@ -2301,10 +2641,10 @@ __pthread_cond_dowait (pthread_cond_t *cond, pthread_mutex_t *mutex,
 {
   if (!pthread_mutex::is_good_object (mutex))
     return EINVAL;
-  if (!pthread_mutex::can_be_unlocked (mutex))
+  if (!(*mutex)->can_be_unlocked ())
     return EPERM;
 
-  if (pthread_cond::is_good_initializer (cond))
+  if (pthread_cond::is_initializer (cond))
     pthread_cond::init (cond, NULL);
   if (!pthread_cond::is_good_object (cond))
     return EINVAL;
@@ -2405,7 +2745,7 @@ pthread_condattr_destroy (pthread_condattr_t *condattr)
 extern "C" int
 pthread_rwlock_destroy (pthread_rwlock_t *rwlock)
 {
-  if (pthread_rwlock::is_good_initializer (rwlock))
+  if (pthread_rwlock::is_initializer (rwlock))
     return 0;
   if (!pthread_rwlock::is_good_object (rwlock))
     return EINVAL;
@@ -2457,7 +2797,7 @@ pthread_rwlock_rdlock (pthread_rwlock_t *rwlock)
 {
   pthread_testcancel ();
 
-  if (pthread_rwlock::is_good_initializer (rwlock))
+  if (pthread_rwlock::is_initializer (rwlock))
     pthread_rwlock::init (rwlock, NULL);
   if (!pthread_rwlock::is_good_object (rwlock))
     return EINVAL;
@@ -2468,7 +2808,7 @@ pthread_rwlock_rdlock (pthread_rwlock_t *rwlock)
 extern "C" int
 pthread_rwlock_tryrdlock (pthread_rwlock_t *rwlock)
 {
-  if (pthread_rwlock::is_good_initializer (rwlock))
+  if (pthread_rwlock::is_initializer (rwlock))
     pthread_rwlock::init (rwlock, NULL);
   if (!pthread_rwlock::is_good_object (rwlock))
     return EINVAL;
@@ -2481,7 +2821,7 @@ pthread_rwlock_wrlock (pthread_rwlock_t *rwlock)
 {
   pthread_testcancel ();
 
-  if (pthread_rwlock::is_good_initializer (rwlock))
+  if (pthread_rwlock::is_initializer (rwlock))
     pthread_rwlock::init (rwlock, NULL);
   if (!pthread_rwlock::is_good_object (rwlock))
     return EINVAL;
@@ -2492,7 +2832,7 @@ pthread_rwlock_wrlock (pthread_rwlock_t *rwlock)
 extern "C" int
 pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock)
 {
-  if (pthread_rwlock::is_good_initializer (rwlock))
+  if (pthread_rwlock::is_initializer (rwlock))
     pthread_rwlock::init (rwlock, NULL);
   if (!pthread_rwlock::is_good_object (rwlock))
     return EINVAL;
@@ -2503,7 +2843,7 @@ pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock)
 extern "C" int
 pthread_rwlock_unlock (pthread_rwlock_t *rwlock)
 {
-  if (pthread_rwlock::is_good_initializer (rwlock))
+  if (pthread_rwlock::is_initializer (rwlock))
     return 0;
   if (!pthread_rwlock::is_good_object (rwlock))
     return EINVAL;
@@ -2623,7 +2963,7 @@ pthread_mutex::init (pthread_mutex_t *mutex,
     return EINVAL;
 
   mutex_initialization_lock.lock ();
-  if (initializer == NULL || pthread_mutex::is_good_initializer (mutex))
+  if (initializer == NULL || pthread_mutex::is_initializer (mutex))
     {
       pthread_mutex_t new_mutex = new pthread_mutex (attr ? (*attr) : NULL);
       if (!is_good_object (&new_mutex))
@@ -2654,6 +2994,7 @@ pthread_mutex::init (pthread_mutex_t *mutex,
       *mutex = new_mutex;
     }
   mutex_initialization_lock.unlock ();
+  pthread_printf ("*mutex %p, attr %p, initializer %p", *mutex, attr, initializer);
 
   return 0;
 }
@@ -2675,7 +3016,7 @@ pthread_mutex_getprioceiling (const pthread_mutex_t *mutex,
 extern "C" int
 pthread_mutex_lock (pthread_mutex_t *mutex)
 {
-  if (pthread_mutex::is_good_initializer (mutex))
+  if (pthread_mutex::is_initializer (mutex))
     pthread_mutex::init (mutex, NULL, *mutex);
   if (!pthread_mutex::is_good_object (mutex))
     return EINVAL;
@@ -2685,7 +3026,7 @@ pthread_mutex_lock (pthread_mutex_t *mutex)
 extern "C" int
 pthread_mutex_trylock (pthread_mutex_t *mutex)
 {
-  if (pthread_mutex::is_good_initializer (mutex))
+  if (pthread_mutex::is_initializer (mutex))
     pthread_mutex::init (mutex, NULL, *mutex);
   if (!pthread_mutex::is_good_object (mutex))
     return EINVAL;
@@ -2695,7 +3036,7 @@ pthread_mutex_trylock (pthread_mutex_t *mutex)
 extern "C" int
 pthread_mutex_unlock (pthread_mutex_t *mutex)
 {
-  if (pthread_mutex::is_good_initializer (mutex))
+  if (pthread_mutex::is_initializer (mutex))
     return EPERM;
   if (!pthread_mutex::is_good_object (mutex))
     return EINVAL;
@@ -2707,7 +3048,7 @@ pthread_mutex_destroy (pthread_mutex_t *mutex)
 {
   int rv;
 
-  if (pthread_mutex::is_good_initializer (mutex))
+  if (pthread_mutex::is_initializer (mutex))
     return 0;
   if (!pthread_mutex::is_good_object (mutex))
     return EINVAL;
@@ -2727,6 +3068,63 @@ pthread_mutex_setprioceiling (pthread_mutex_t *mutex, int prioceiling,
   return ENOSYS;
 }
 
+/* Spinlocks  */
+
+int
+pthread_spinlock::init (pthread_spinlock_t *spinlock, int pshared)
+{
+  pthread_spinlock_t new_spinlock = new pthread_spinlock (pshared);
+  if (!is_good_object (&new_spinlock))
+    {
+      delete new_spinlock;
+      return EAGAIN;
+    }
+
+  myfault efault;
+  if (efault.faulted ())
+    {
+      delete new_spinlock;
+      return EINVAL;
+    }
+
+  *spinlock = new_spinlock;
+  pthread_printf ("*spinlock %p, pshared %d", *spinlock, pshared);
+
+  return 0;
+}
+
+extern "C" int
+pthread_spin_lock (pthread_spinlock_t *spinlock)
+{
+  if (!pthread_spinlock::is_good_object (spinlock))
+    return EINVAL;
+  return (*spinlock)->lock ();
+}
+
+extern "C" int
+pthread_spin_trylock (pthread_spinlock_t *spinlock)
+{
+  if (!pthread_spinlock::is_good_object (spinlock))
+    return EINVAL;
+  return (*spinlock)->trylock ();
+}
+
+extern "C" int
+pthread_spin_unlock (pthread_spinlock_t *spinlock)
+{
+  if (!pthread_spinlock::is_good_object (spinlock))
+    return EINVAL;
+  return (*spinlock)->unlock ();
+}
+
+extern "C" int
+pthread_spin_destroy (pthread_spinlock_t *spinlock)
+{
+  if (!pthread_spinlock::is_good_object (spinlock))
+    return EINVAL;
+  return (*spinlock)->destroy ();
+}
+
 /* Win32 doesn't support mutex priorities - see __pthread_mutex_getprioceiling
    for more detail */
 extern "C" int
@@ -2980,7 +3378,7 @@ semaphore::_timedwait (const struct timespec *abstime)
       set_errno (ETIMEDOUT);
       return -1;
     default:
-      debug_printf ("cancelable_wait failed. %E");
+      pthread_printf ("cancelable_wait failed. %E");
       __seterrno ();
       return -1;
     }
@@ -2999,7 +3397,7 @@ semaphore::_wait ()
       set_errno (EINTR);
       return -1;
     default:
-      debug_printf ("cancelable_wait failed. %E");
+      pthread_printf ("cancelable_wait failed. %E");
       break;
     }
   return 0;
@@ -3010,7 +3408,7 @@ semaphore::_fixup_after_fork ()
 {
   if (shared == PTHREAD_PROCESS_PRIVATE)
     {
-      debug_printf ("sem %x in _fixup_after_fork", this);
+      pthread_printf ("sem %x", this);
       /* FIXME: duplicate code here and in the constructor. */
       this->win32_obj_id = ::CreateSemaphore (&sec_none_nih, currentvalue,
                                              LONG_MAX, NULL);
@@ -3033,12 +3431,21 @@ semaphore::_terminate ()
 int
 semaphore::init (sem_t *sem, int pshared, unsigned int value)
 {
-  /* opengroup calls this undefined */
+  /*
+     We can't tell the difference between reinitialising an
+     existing semaphore and initialising a semaphore who's
+     contents happen to be a valid pointer
+   */
   if (is_good_object (sem))
-    return EBUSY;
+    {
+      paranoid_printf ("potential attempt to reinitialise a semaphore");
+    }
 
   if (value > SEM_VALUE_MAX)
-    return EINVAL;
+    {
+      set_errno(EINVAL);
+      return -1;
+    }
 
   *sem = new semaphore (pshared, value);
 
@@ -3046,7 +3453,8 @@ semaphore::init (sem_t *sem, int pshared, unsigned int value)
     {
       delete (*sem);
       *sem = NULL;
-      return EAGAIN;
+      set_errno(EAGAIN);
+      return -1;
     }
   return 0;
 }
@@ -3055,11 +3463,17 @@ int
 semaphore::destroy (sem_t *sem)
 {
   if (!is_good_object (sem))
-    return EINVAL;
+    {
+      set_errno(EINVAL);
+      return -1;
+    }
 
   /* It's invalid to destroy a semaphore not opened with sem_init. */
   if ((*sem)->fd != -1)
-    return EINVAL;
+    {
+      set_errno(EINVAL);
+      return -1;
+    }
 
   /* FIXME - new feature - test for busy against threads... */
 
@@ -3072,11 +3486,17 @@ int
 semaphore::close (sem_t *sem)
 {
   if (!is_good_object (sem))
-    return EINVAL;
+    {
+      set_errno(EINVAL);
+      return -1;
+    }
 
   /* It's invalid to close a semaphore not opened with sem_open. */
   if ((*sem)->fd == -1)
-    return EINVAL;
+    {
+      set_errno(EINVAL);
+      return -1;
+    }
 
   delete (*sem);
   delete sem;
This page took 0.050259 seconds and 5 git commands to generate.