winxp threads: detect SRWLock emulation reentrancy
[platform/upstream/glib.git] / glib / gthread-win32.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gthread.c: solaris thread system implementation
5  * Copyright 1998-2001 Sebastian Wilhelmi; University of Karlsruhe
6  * Copyright 2001 Hans Breuer
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /*
25  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
26  * file for a list of people on the GLib Team.  See the ChangeLog
27  * files for a list of changes.  These files are distributed with
28  * GLib at ftp://ftp.gtk.org/pub/gtk/.
29  */
30
31 /* The GMutex and GCond implementations in this file are some of the
32  * lowest-level code in GLib.  All other parts of GLib (messages,
33  * memory, slices, etc) assume that they can freely use these facilities
34  * without risking recursion.
35  *
36  * As such, these functions are NOT permitted to call any other part of
37  * GLib.
38  *
39  * The thread manipulation functions (create, exit, join, etc.) have
40  * more freedom -- they can do as they please.
41  */
42
43 #include "config.h"
44
45 #include "gthread.h"
46 #include "gthreadprivate.h"
47 #include "gslice.h"
48
49 #include <windows.h>
50
51 #include <process.h>
52 #include <stdlib.h>
53 #include <stdio.h>
54
55 static void
56 g_thread_abort (gint         status,
57                 const gchar *function)
58 {
59   fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
60            strerror (status), function);
61   abort ();
62 }
63
64 /* Starting with Vista and Windows 2008, we have access to the
65  * CONDITION_VARIABLE and SRWLock primatives on Windows, which are
66  * pretty reasonable approximations of the primatives specified in
67  * POSIX 2001 (pthread_cond_t and pthread_mutex_t respectively).
68  *
69  * Both of these types are structs containing a single pointer.  That
70  * pointer is used as an atomic bitfield to support user-space mutexes
71  * that only get the kernel involved in cases of contention (similar
72  * to how futex()-based mutexes work on Linux).  The biggest advantage
73  * of these new types is that they can be statically initialised to
74  * zero.  This allows us to use them directly and still support:
75  *
76  *   GMutex mutex = G_MUTEX_INIT;
77  *
78  * and
79  *
80  *   GCond cond = G_COND_INIT;
81  *
82  * Unfortunately, Windows XP lacks these facilities and GLib still
83  * needs to support Windows XP.  Our approach here is as follows:
84  *
85  *   - avoid depending on structure declarations at compile-time by
86  *     declaring our own GMutex and GCond strutures to be
87  *     ABI-compatible with SRWLock and CONDITION_VARIABLE and using
88  *     those instead
89  *
90  *   - avoid a hard dependency on the symbols used to manipulate these
91  *     structures by doing a dynamic lookup of those symbols at
92  *     runtime
93  *
94  *   - if the symbols are not available, emulate them using other
95  *     primatives
96  *
97  * Using this approach also allows us to easily build a GLib that lacks
98  * support for Windows XP or to remove this code entirely when XP is no
99  * longer supported (end of line is currently April 8, 2014).
100  */
101 typedef struct
102 {
103   void     (__stdcall * CallThisOnThreadExit)        (void);              /* fake */
104
105   void     (__stdcall * InitializeSRWLock)           (gpointer lock);
106   void     (__stdcall * DeleteSRWLock)               (gpointer lock);     /* fake */
107   void     (__stdcall * AcquireSRWLockExclusive)     (gpointer lock);
108   BOOLEAN  (__stdcall * TryAcquireSRWLockExclusive)  (gpointer lock);
109   void     (__stdcall * ReleaseSRWLockExclusive)     (gpointer lock);
110   void     (__stdcall * AcquireSRWLockShared)        (gpointer lock);
111   BOOLEAN  (__stdcall * TryAcquireSRWLockShared)     (gpointer lock);
112   void     (__stdcall * ReleaseSRWLockShared)        (gpointer lock);
113
114   void     (__stdcall * InitializeConditionVariable) (gpointer cond);
115   void     (__stdcall * DeleteConditionVariable)     (gpointer cond);     /* fake */
116   BOOL     (__stdcall * SleepConditionVariableSRW)   (gpointer cond,
117                                                       gpointer lock,
118                                                       DWORD    timeout,
119                                                       ULONG    flags);
120   void     (__stdcall * WakeAllConditionVariable)    (gpointer cond);
121   void     (__stdcall * WakeConditionVariable)       (gpointer cond);
122 } GThreadImplVtable;
123
124 static GThreadImplVtable g_thread_impl_vtable;
125
126 /* {{{1 GMutex */
127 void
128 g_mutex_init (GMutex *mutex)
129 {
130   g_thread_impl_vtable.InitializeSRWLock (mutex);
131 }
132
133 void
134 g_mutex_clear (GMutex *mutex)
135 {
136   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
137     g_thread_impl_vtable.DeleteSRWLock (mutex);
138 }
139
140 void
141 g_mutex_lock (GMutex *mutex)
142 {
143   g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
144 }
145
146 gboolean
147 g_mutex_trylock (GMutex *mutex)
148 {
149   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
150 }
151
152 void
153 g_mutex_unlock (GMutex *mutex)
154 {
155   g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
156 }
157
158 /* {{{1 GRecMutex */
159
160 static CRITICAL_SECTION *
161 g_rec_mutex_impl_new (void)
162 {
163   CRITICAL_SECTION *cs;
164
165   cs = g_slice_new (CRITICAL_SECTION);
166   InitializeCriticalSection (cs);
167
168   return cs;
169 }
170
171 static void
172 g_rec_mutex_impl_free (CRITICAL_SECTION *cs)
173 {
174   DeleteCriticalSection (cs);
175   g_slice_free (CRITICAL_SECTION, cs);
176 }
177
178 static CRITICAL_SECTION *
179 g_rec_mutex_get_impl (GRecMutex *mutex)
180 {
181   CRITICAL_SECTION *impl = mutex->impl;
182
183   if G_UNLIKELY (mutex->impl == NULL)
184     {
185       impl = g_rec_mutex_impl_new ();
186       if (InterlockedCompareExchangePointer (&mutex->impl, impl, NULL) != NULL)
187         g_rec_mutex_impl_free (impl);
188       impl = mutex->impl;
189     }
190
191   return impl;
192 }
193
194 void
195 g_rec_mutex_init (GRecMutex *mutex)
196 {
197   mutex->impl = g_rec_mutex_impl_new ();
198 }
199
200 void
201 g_rec_mutex_clear (GRecMutex *mutex)
202 {
203   if (mutex->impl)
204     g_rec_mutex_impl_free (mutex->impl);
205 }
206
207 void
208 g_rec_mutex_lock (GRecMutex *mutex)
209 {
210   EnterCriticalSection (g_rec_mutex_get_impl (mutex));
211 }
212
213 void
214 g_rec_mutex_unlock (GRecMutex *mutex)
215 {
216   LeaveCriticalSection (mutex->impl);
217 }
218
219 gboolean
220 g_rec_mutex_trylock (GRecMutex *mutex)
221 {
222   return TryEnterCriticalSection (g_rec_mutex_get_impl (mutex));
223 }
224
225 /* {{{1 GRWLock */
226
227 void
228 g_rw_lock_init (GRWLock *lock)
229 {
230   g_thread_impl_vtable.InitializeSRWLock (lock);
231 }
232
233 void
234 g_rw_lock_clear (GRWLock *lock)
235 {
236   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
237     g_thread_impl_vtable.DeleteSRWLock (lock);
238 }
239
240 void
241 g_rw_lock_writer_lock (GRWLock *lock)
242 {
243   g_thread_impl_vtable.AcquireSRWLockExclusive (lock);
244 }
245
246 gboolean
247 g_rw_lock_writer_trylock (GRWLock *lock)
248 {
249   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (lock);
250 }
251
252 void
253 g_rw_lock_writer_unlock (GRWLock *lock)
254 {
255   g_thread_impl_vtable.ReleaseSRWLockExclusive (lock);
256 }
257
258 void
259 g_rw_lock_reader_lock (GRWLock *lock)
260 {
261   g_thread_impl_vtable.AcquireSRWLockShared (lock);
262 }
263
264 gboolean
265 g_rw_lock_reader_trylock (GRWLock *lock)
266 {
267   return g_thread_impl_vtable.TryAcquireSRWLockShared (lock);
268 }
269
270 void
271 g_rw_lock_reader_unlock (GRWLock *lock)
272 {
273   g_thread_impl_vtable.ReleaseSRWLockShared (lock);
274 }
275
276 /* {{{1 GCond */
277 void
278 g_cond_init (GCond *cond)
279 {
280   g_thread_impl_vtable.InitializeConditionVariable (cond);
281 }
282
283 void
284 g_cond_clear (GCond *cond)
285 {
286   if (g_thread_impl_vtable.DeleteConditionVariable)
287     g_thread_impl_vtable.DeleteConditionVariable (cond);
288 }
289
290 void
291 g_cond_signal (GCond *cond)
292 {
293   g_thread_impl_vtable.WakeConditionVariable (cond);
294 }
295
296 void
297 g_cond_broadcast (GCond *cond)
298 {
299   g_thread_impl_vtable.WakeAllConditionVariable (cond);
300 }
301
302 void
303 g_cond_wait (GCond  *cond,
304              GMutex *entered_mutex)
305 {
306   g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
307 }
308
309 gboolean
310 g_cond_timedwait (GCond  *cond,
311                   GMutex *entered_mutex,
312                   gint64  abs_time)
313 {
314   gint64 span;
315   FILETIME ft;
316   gint64 now;
317
318   GetSystemTimeAsFileTime (&ft);
319   memmove (&now, &ft, sizeof (FILETIME));
320
321   now -= G_GINT64_CONSTANT (116444736000000000);
322   now /= 10;
323
324   span = abs_time - now;
325
326   if G_UNLIKELY (span < 0)
327     span = 0;
328
329   if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
330     span = INFINITE;
331
332   return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
333 }
334
335 gboolean
336 g_cond_timed_wait (GCond    *cond,
337                    GMutex   *entered_mutex,
338                    GTimeVal *abs_time)
339 {
340   if (abs_time)
341     {
342       gint64 micros;
343
344       micros = abs_time->tv_sec;
345       micros *= 1000000;
346       micros += abs_time->tv_usec;
347
348       return g_cond_timedwait (cond, entered_mutex, micros);
349     }
350   else
351     {
352       g_cond_wait (cond, entered_mutex);
353       return TRUE;
354     }
355 }
356
357 /* {{{1 GPrivate */
358
359 typedef struct _GPrivateDestructor GPrivateDestructor;
360
361 struct _GPrivateDestructor
362 {
363   DWORD               index;
364   GDestroyNotify      notify;
365   GPrivateDestructor *next;
366 };
367
368 static GPrivateDestructor * volatile g_private_destructors;
369
370 void
371 g_private_init (GPrivate       *key,
372                 GDestroyNotify  notify)
373 {
374   GPrivateDestructor *destructor;
375
376   key->index = TlsAlloc ();
377
378   destructor = malloc (sizeof (GPrivateDestructor));
379   if G_UNLIKELY (destructor == NULL)
380     g_thread_abort (errno, "malloc");
381   destructor->index = key->index;
382   destructor->notify = notify;
383
384   do
385     destructor->next = g_private_destructors;
386   while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
387
388   key->ready = TRUE;
389 }
390
391 gpointer
392 g_private_get (GPrivate *key)
393 {
394   if (!key->ready)
395     return key->single_value;
396
397   return TlsGetValue (key->index);
398 }
399
400 void
401 g_private_set (GPrivate *key,
402                gpointer  value)
403 {
404   if (!key->ready)
405     {
406       key->single_value = value;
407       return;
408     }
409
410   TlsSetValue (key->index, value);
411 }
412
413 /* {{{1 GThread */
414
415 #include "glib.h"
416 #include "gthreadprivate.h"
417
418 #define win32_check_for_error(what) G_STMT_START{                       \
419   if (!(what))                                                          \
420     g_error ("file %s: line %d (%s): error %s during %s",               \
421              __FILE__, __LINE__, G_STRFUNC,                             \
422              g_win32_error_message (GetLastError ()), #what);           \
423   }G_STMT_END
424
425 #define G_MUTEX_SIZE (sizeof (gpointer))
426
427 static DWORD g_thread_self_tls;
428 static DWORD g_private_tls;
429
430 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
431
432 typedef struct _GThreadData GThreadData;
433 struct _GThreadData
434 {
435   GThreadFunc func;
436   gpointer data;
437   HANDLE thread;
438   gboolean joinable;
439 };
440
441 void
442 g_system_thread_self (gpointer thread)
443 {
444   GThreadData *self = TlsGetValue (g_thread_self_tls);
445
446   if (!self)
447     {
448       /* This should only happen for the main thread! */
449       HANDLE handle = GetCurrentThread ();
450       HANDLE process = GetCurrentProcess ();
451       self = g_new (GThreadData, 1);
452       win32_check_for_error (DuplicateHandle (process, handle, process,
453                                               &self->thread, 0, FALSE,
454                                               DUPLICATE_SAME_ACCESS));
455       win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
456       self->func = NULL;
457       self->data = NULL;
458       self->joinable = FALSE;
459     }
460
461   *(GThreadData **)thread = self;
462 }
463
464 void
465 g_system_thread_exit (void)
466 {
467   GThreadData *self = TlsGetValue (g_thread_self_tls);
468   gboolean dtors_called;
469
470   do
471     {
472       GPrivateDestructor *dtor;
473
474       /* We go by the POSIX book on this one.
475        *
476        * If we call a destructor then there is a chance that some new
477        * TLS variables got set by code called in that destructor.
478        *
479        * Loop until nothing is left.
480        */
481       dtors_called = FALSE;
482
483       for (dtor = g_private_destructors; dtor; dtor = dtor->next)
484         {
485           gpointer value;
486
487           value = TlsGetValue (dtor->index);
488           if (value != NULL && dtor->notify != NULL)
489             {
490               /* POSIX says to clear this before the call */
491               TlsSetValue (dtor->index, NULL);
492               dtor->notify (value);
493               dtors_called = TRUE;
494             }
495         }
496     }
497   while (dtors_called);
498
499   if (self)
500     {
501       if (!self->joinable)
502         {
503           win32_check_for_error (CloseHandle (self->thread));
504           g_free (self);
505         }
506       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
507     }
508
509   if (g_thread_impl_vtable.CallThisOnThreadExit)
510     g_thread_impl_vtable.CallThisOnThreadExit ();
511
512   _endthreadex (0);
513 }
514
515 static guint __stdcall
516 g_thread_proxy (gpointer data)
517 {
518   GThreadData *self = (GThreadData*) data;
519
520   win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
521
522   self->func (self->data);
523
524   g_system_thread_exit ();
525
526   g_assert_not_reached ();
527
528   return 0;
529 }
530
531 void
532 g_system_thread_create (GThreadFunc       func,
533                         gpointer          data,
534                         gulong            stack_size,
535                         gboolean          joinable,
536                         gpointer          thread,
537                         GError          **error)
538 {
539   guint ignore;
540   GThreadData *retval;
541
542   g_return_if_fail (func);
543
544   retval = g_new(GThreadData, 1);
545   retval->func = func;
546   retval->data = data;
547
548   retval->joinable = joinable;
549
550   retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
551                                             retval, 0, &ignore);
552
553   if (retval->thread == NULL)
554     {
555       gchar *win_error = g_win32_error_message (GetLastError ());
556       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
557                    "Error creating thread: %s", win_error);
558       g_free (retval);
559       g_free (win_error);
560       return;
561     }
562
563   *(GThreadData **)thread = retval;
564 }
565
566 void
567 g_thread_yield (void)
568 {
569   Sleep(0);
570 }
571
572 void
573 g_system_thread_join (gpointer thread)
574 {
575   GThreadData *target = *(GThreadData **)thread;
576
577   g_return_if_fail (target->joinable);
578
579   win32_check_for_error (WAIT_FAILED !=
580                          WaitForSingleObject (target->thread, INFINITE));
581
582   win32_check_for_error (CloseHandle (target->thread));
583   g_free (target);
584 }
585
586 gboolean
587 g_system_thread_equal (gpointer thread1,
588                        gpointer thread2)
589 {
590    return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
591 }
592
593 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
594
595 static CRITICAL_SECTION g_thread_xp_lock;
596 static DWORD            g_thread_xp_waiter_tls;
597
598 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
599 typedef struct _GThreadXpWaiter GThreadXpWaiter;
600 struct _GThreadXpWaiter
601 {
602   HANDLE                    event;
603   volatile GThreadXpWaiter *next;
604 };
605
606 static GThreadXpWaiter *
607 g_thread_xp_waiter_get (void)
608 {
609   GThreadXpWaiter *waiter;
610
611   waiter = TlsGetValue (g_thread_xp_waiter_tls);
612
613   if G_UNLIKELY (waiter == NULL)
614     {
615       waiter = malloc (sizeof (GThreadXpWaiter));
616       if (waiter == NULL)
617         g_thread_abort (GetLastError (), "malloc");
618       waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
619       if (waiter->event == NULL)
620         g_thread_abort (GetLastError (), "CreateEvent");
621
622       TlsSetValue (g_thread_xp_waiter_tls, waiter);
623     }
624
625   return waiter;
626 }
627
628 static void __stdcall
629 g_thread_xp_CallThisOnThreadExit (void)
630 {
631   GThreadXpWaiter *waiter;
632
633   waiter = TlsGetValue (g_thread_xp_waiter_tls);
634
635   if (waiter != NULL)
636     {
637       TlsSetValue (g_thread_xp_waiter_tls, NULL);
638       CloseHandle (waiter->event);
639       free (waiter);
640     }
641 }
642
643 /* {{{2 SRWLock emulation */
644 typedef struct
645 {
646   CRITICAL_SECTION  writer_lock;
647   gboolean          ever_shared;    /* protected by writer_lock */
648   gboolean          writer_locked;  /* protected by writer_lock */
649
650   /* below is only ever touched if ever_shared becomes true */
651   CRITICAL_SECTION  atomicity;
652   GThreadXpWaiter  *queued_writer; /* protected by atomicity lock */
653   gint              num_readers;   /* protected by atomicity lock */
654 } GThreadSRWLock;
655
656 static void __stdcall
657 g_thread_xp_InitializeSRWLock (gpointer mutex)
658 {
659   *(GThreadSRWLock * volatile *) mutex = NULL;
660 }
661
662 static void __stdcall
663 g_thread_xp_DeleteSRWLock (gpointer mutex)
664 {
665   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
666
667   if (lock)
668     {
669       if (lock->ever_shared)
670         DeleteCriticalSection (&lock->atomicity);
671
672       DeleteCriticalSection (&lock->writer_lock);
673       free (lock);
674     }
675 }
676
677 static GThreadSRWLock * __stdcall
678 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
679 {
680   GThreadSRWLock *result;
681
682   /* It looks like we're missing some barriers here, but this code only
683    * ever runs on Windows XP, which in turn only ever runs on hardware
684    * with a relatively rigid memory model.  The 'volatile' will take
685    * care of the compiler.
686    */
687   result = *lock;
688
689   if G_UNLIKELY (result == NULL)
690     {
691       EnterCriticalSection (&g_thread_xp_lock);
692
693       result = malloc (sizeof (GThreadSRWLock));
694
695       if (result == NULL)
696         g_thread_abort (errno, "malloc");
697
698       InitializeCriticalSection (&result->writer_lock);
699       result->writer_locked = FALSE;
700       result->ever_shared = FALSE;
701       *lock = result;
702
703       LeaveCriticalSection (&g_thread_xp_lock);
704     }
705
706   return result;
707 }
708
709 static void __stdcall
710 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
711 {
712   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
713
714   EnterCriticalSection (&lock->writer_lock);
715
716   /* CRITICAL_SECTION is reentrant, but SRWLock is not.
717    * Detect the deadlock that would occur on later Windows version.
718    */
719   g_assert (!lock->writer_locked);
720   lock->writer_locked = TRUE;
721
722   if (lock->ever_shared)
723     {
724       GThreadXpWaiter *waiter = NULL;
725
726       EnterCriticalSection (&lock->atomicity);
727       if (lock->num_readers > 0)
728         lock->queued_writer = waiter = g_thread_xp_waiter_get ();
729       LeaveCriticalSection (&lock->atomicity);
730
731       if (waiter != NULL)
732         WaitForSingleObject (waiter->event, INFINITE);
733
734       lock->queued_writer = NULL;
735     }
736 }
737
738 static BOOLEAN __stdcall
739 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
740 {
741   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
742
743   if (!TryEnterCriticalSection (&lock->writer_lock))
744     return FALSE;
745
746   /* CRITICAL_SECTION is reentrant, but SRWLock is not.
747    * Ensure that this properly returns FALSE (as SRWLock would).
748    */
749   if G_UNLIKELY (lock->writer_locked)
750     {
751       LeaveCriticalSection (&lock->writer_lock);
752       return FALSE;
753     }
754
755   lock->writer_locked = TRUE;
756
757   if (lock->ever_shared)
758     {
759       gboolean available;
760
761       EnterCriticalSection (&lock->atomicity);
762       available = lock->num_readers == 0;
763       LeaveCriticalSection (&lock->atomicity);
764
765       if (!available)
766         {
767           LeaveCriticalSection (&lock->writer_lock);
768           return FALSE;
769         }
770     }
771
772   return TRUE;
773 }
774
775 static void __stdcall
776 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
777 {
778   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
779
780   lock->writer_locked = FALSE;
781
782   /* We need this until we fix some weird parts of GLib that try to
783    * unlock freshly-allocated mutexes.
784    */
785   if (lock != NULL)
786     LeaveCriticalSection (&lock->writer_lock);
787 }
788
789 static void
790 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
791 {
792   if G_UNLIKELY (!lock->ever_shared)
793     {
794       InitializeCriticalSection (&lock->atomicity);
795       lock->queued_writer = NULL;
796       lock->num_readers = 0;
797
798       lock->ever_shared = TRUE;
799     }
800
801   EnterCriticalSection (&lock->atomicity);
802   lock->num_readers++;
803   LeaveCriticalSection (&lock->atomicity);
804 }
805
806 static void __stdcall
807 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
808 {
809   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
810
811   EnterCriticalSection (&lock->writer_lock);
812
813   /* See g_thread_xp_AcquireSRWLockExclusive */
814   g_assert (!lock->writer_locked);
815
816   g_thread_xp_srwlock_become_reader (lock);
817
818   LeaveCriticalSection (&lock->writer_lock);
819 }
820
821 static BOOLEAN __stdcall
822 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
823 {
824   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
825
826   if (!TryEnterCriticalSection (&lock->writer_lock))
827     return FALSE;
828
829   /* See g_thread_xp_AcquireSRWLockExclusive */
830   if G_UNLIKELY (lock->writer_locked)
831     {
832       LeaveCriticalSection (&lock->writer_lock);
833       return FALSE;
834     }
835
836   g_thread_xp_srwlock_become_reader (lock);
837
838   LeaveCriticalSection (&lock->writer_lock);
839
840   return TRUE;
841 }
842
843 static void __stdcall
844 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
845 {
846   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
847
848   EnterCriticalSection (&lock->atomicity);
849
850   lock->num_readers--;
851
852   if (lock->num_readers == 0 && lock->queued_writer)
853     SetEvent (lock->queued_writer->event);
854
855   LeaveCriticalSection (&lock->atomicity);
856 }
857
858 /* {{{2 CONDITION_VARIABLE emulation */
859 typedef struct
860 {
861   volatile GThreadXpWaiter  *first;
862   volatile GThreadXpWaiter **last_ptr;
863 } GThreadXpCONDITION_VARIABLE;
864
865 static void __stdcall
866 g_thread_xp_InitializeConditionVariable (gpointer cond)
867 {
868   *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
869 }
870
871 static void __stdcall
872 g_thread_xp_DeleteConditionVariable (gpointer cond)
873 {
874   GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
875
876   if (cv)
877     free (cv);
878 }
879
880 static GThreadXpCONDITION_VARIABLE * __stdcall
881 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
882 {
883   GThreadXpCONDITION_VARIABLE *result;
884
885   /* It looks like we're missing some barriers here, but this code only
886    * ever runs on Windows XP, which in turn only ever runs on hardware
887    * with a relatively rigid memory model.  The 'volatile' will take
888    * care of the compiler.
889    */
890   result = *cond;
891
892   if G_UNLIKELY (result == NULL)
893     {
894       result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
895
896       if (result == NULL)
897         g_thread_abort (errno, "malloc");
898
899       result->first = NULL;
900       result->last_ptr = &result->first;
901
902       if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
903         {
904           free (result);
905           result = *cond;
906         }
907     }
908
909   return result;
910 }
911
912 static BOOL __stdcall
913 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
914                                        gpointer mutex,
915                                        DWORD    timeout,
916                                        ULONG    flags)
917 {
918   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
919   GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
920   DWORD status;
921
922   waiter->next = NULL;
923
924   EnterCriticalSection (&g_thread_xp_lock);
925   *cv->last_ptr = waiter;
926   cv->last_ptr = &waiter->next;
927   LeaveCriticalSection (&g_thread_xp_lock);
928
929   g_mutex_unlock (mutex);
930   status = WaitForSingleObject (waiter->event, timeout);
931
932   if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
933     g_thread_abort (GetLastError (), "WaitForSingleObject");
934
935   g_mutex_lock (mutex);
936
937   return status == WAIT_OBJECT_0;
938 }
939
940 static void __stdcall
941 g_thread_xp_WakeConditionVariable (gpointer cond)
942 {
943   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
944   volatile GThreadXpWaiter *waiter;
945
946   EnterCriticalSection (&g_thread_xp_lock);
947   waiter = cv->first;
948   if (waiter != NULL)
949     {
950       cv->first = waiter->next;
951       if (cv->first == NULL)
952         cv->last_ptr = &cv->first;
953     }
954   LeaveCriticalSection (&g_thread_xp_lock);
955
956   if (waiter != NULL)
957     SetEvent (waiter->event);
958 }
959
960 static void __stdcall
961 g_thread_xp_WakeAllConditionVariable (gpointer cond)
962 {
963   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
964   volatile GThreadXpWaiter *waiter;
965
966   EnterCriticalSection (&g_thread_xp_lock);
967   waiter = cv->first;
968   cv->first = NULL;
969   cv->last_ptr = &cv->first;
970   LeaveCriticalSection (&g_thread_xp_lock);
971
972   while (waiter != NULL)
973     {
974       volatile GThreadXpWaiter *next;
975
976       next = waiter->next;
977       SetEvent (waiter->event);
978       waiter = next;
979     }
980 }
981
982 /* {{{2 XP Setup */
983 static void
984 g_thread_xp_init (void)
985 {
986   static const GThreadImplVtable g_thread_xp_impl_vtable = {
987     g_thread_xp_CallThisOnThreadExit,
988     g_thread_xp_InitializeSRWLock,
989     g_thread_xp_DeleteSRWLock,
990     g_thread_xp_AcquireSRWLockExclusive,
991     g_thread_xp_TryAcquireSRWLockExclusive,
992     g_thread_xp_ReleaseSRWLockExclusive,
993     g_thread_xp_AcquireSRWLockShared,
994     g_thread_xp_TryAcquireSRWLockShared,
995     g_thread_xp_ReleaseSRWLockShared,
996     g_thread_xp_InitializeConditionVariable,
997     g_thread_xp_DeleteConditionVariable,
998     g_thread_xp_SleepConditionVariableSRW,
999     g_thread_xp_WakeAllConditionVariable,
1000     g_thread_xp_WakeConditionVariable
1001   };
1002
1003   InitializeCriticalSection (&g_thread_xp_lock);
1004   g_thread_xp_waiter_tls = TlsAlloc ();
1005
1006   g_thread_impl_vtable = g_thread_xp_impl_vtable;
1007 }
1008
1009 /* {{{1 Epilogue */
1010
1011 static gboolean
1012 g_thread_lookup_native_funcs (void)
1013 {
1014   GThreadImplVtable native_vtable = { 0, };
1015   HMODULE kernel32;
1016
1017   kernel32 = GetModuleHandle ("KERNEL32.DLL");
1018
1019   if (kernel32 == NULL)
1020     return FALSE;
1021
1022 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
1023   GET_FUNC(InitializeSRWLock);
1024   GET_FUNC(AcquireSRWLockExclusive);
1025   GET_FUNC(TryAcquireSRWLockExclusive);
1026   GET_FUNC(ReleaseSRWLockExclusive);
1027   GET_FUNC(AcquireSRWLockShared);
1028   GET_FUNC(TryAcquireSRWLockShared);
1029   GET_FUNC(ReleaseSRWLockShared);
1030
1031   GET_FUNC(InitializeConditionVariable);
1032   GET_FUNC(SleepConditionVariableSRW);
1033   GET_FUNC(WakeAllConditionVariable);
1034   GET_FUNC(WakeConditionVariable);
1035 #undef GET_FUNC
1036
1037   g_thread_impl_vtable = native_vtable;
1038
1039   return TRUE;
1040 }
1041
1042 G_GNUC_INTERNAL void
1043 g_thread_DllMain (void)
1044 {
1045   if (g_thread_lookup_native_funcs ())
1046     fprintf (stderr, "(debug) GThread using native mode\n");
1047   else
1048     {
1049       fprintf (stderr, "(debug) GThread using Windows XP mode\n");
1050       g_thread_xp_init ();
1051     }
1052
1053   win32_check_for_error (TLS_OUT_OF_INDEXES != (g_thread_self_tls = TlsAlloc ()));
1054   win32_check_for_error (TLS_OUT_OF_INDEXES != (g_private_tls = TlsAlloc ()));
1055 }
1056
1057 /* vim:set foldmethod=marker: */
1058