win32: fix GPrivate fallout
[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 static CRITICAL_SECTION g_private_lock;
370
371 static DWORD
372 g_private_get_impl (GPrivate *key)
373 {
374   DWORD impl = (DWORD) key->p;
375
376   if G_UNLIKELY (impl == 0)
377     {
378       EnterCriticalSection (&g_private_lock);
379       impl = (DWORD) key->p;
380       if (impl == 0)
381         {
382           GPrivateDestructor *destructor;
383
384           impl = TlsAlloc ();
385
386           if (impl == TLS_OUT_OF_INDEXES)
387             g_thread_abort (0, "TlsAlloc");
388
389           if (key->notify != NULL)
390             {
391               destructor = malloc (sizeof (GPrivateDestructor));
392               if G_UNLIKELY (destructor == NULL)
393                 g_thread_abort (errno, "malloc");
394               destructor->index = impl;
395               destructor->notify = key->notify;
396               destructor->next = g_private_destructors;
397
398               /* We need to do an atomic store due to the unlocked
399                * access to the destructor list from the thread exit
400                * function.
401                *
402                * It can double as a sanity check...
403                */
404               if (InterlockedCompareExchangePointer (&g_private_destructors, destructor,
405                                                      destructor->next) != destructor->next)
406                 g_thread_abort (0, "g_private_get_impl(1)");
407             }
408
409           /* Ditto, due to the unlocked access on the fast path */
410           if (InterlockedCompareExchangePointer (&key->p, impl, NULL) != NULL)
411             g_thread_abort (0, "g_private_get_impl(2)");
412         }
413       LeaveCriticalSection (&g_private_lock);
414     }
415
416   return impl;
417 }
418
419 gpointer
420 g_private_get (GPrivate *key)
421 {
422   return TlsGetValue (g_private_get_impl (key));
423 }
424
425 void
426 g_private_set (GPrivate *key,
427                gpointer  value)
428 {
429   TlsSetValue (g_private_get_impl (key), value);
430 }
431
432 void
433 g_private_replace (GPrivate *key,
434                    gpointer  value)
435 {
436   DWORD impl = g_private_get_impl (key);
437   gpointer old;
438
439   old = TlsGetValue (impl);
440   if (old && key->notify)
441     key->notify (old);
442   TlsSetValue (impl, value);
443 }
444
445 /* {{{1 GThread */
446
447 #include "glib.h"
448 #include "gthreadprivate.h"
449
450 #define win32_check_for_error(what) G_STMT_START{                       \
451   if (!(what))                                                          \
452     g_error ("file %s: line %d (%s): error %s during %s",               \
453              __FILE__, __LINE__, G_STRFUNC,                             \
454              g_win32_error_message (GetLastError ()), #what);           \
455   }G_STMT_END
456
457 #define G_MUTEX_SIZE (sizeof (gpointer))
458
459 static DWORD g_thread_self_tls;
460
461 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
462
463 typedef struct _GThreadData GThreadData;
464 struct _GThreadData
465 {
466   GThreadFunc func;
467   gpointer data;
468   HANDLE thread;
469   gboolean joinable;
470 };
471
472 void
473 g_system_thread_self (gpointer thread)
474 {
475   GThreadData *self = TlsGetValue (g_thread_self_tls);
476
477   if (!self)
478     {
479       /* This should only happen for the main thread! */
480       HANDLE handle = GetCurrentThread ();
481       HANDLE process = GetCurrentProcess ();
482       self = g_new (GThreadData, 1);
483       win32_check_for_error (DuplicateHandle (process, handle, process,
484                                               &self->thread, 0, FALSE,
485                                               DUPLICATE_SAME_ACCESS));
486       win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
487       self->func = NULL;
488       self->data = NULL;
489       self->joinable = FALSE;
490     }
491
492   *(GThreadData **)thread = self;
493 }
494
495 void
496 g_system_thread_exit (void)
497 {
498   GThreadData *self = TlsGetValue (g_thread_self_tls);
499   gboolean dtors_called;
500
501   do
502     {
503       GPrivateDestructor *dtor;
504
505       /* We go by the POSIX book on this one.
506        *
507        * If we call a destructor then there is a chance that some new
508        * TLS variables got set by code called in that destructor.
509        *
510        * Loop until nothing is left.
511        */
512       dtors_called = FALSE;
513
514       for (dtor = g_private_destructors; dtor; dtor = dtor->next)
515         {
516           gpointer value;
517
518           value = TlsGetValue (dtor->index);
519           if (value != NULL && dtor->notify != NULL)
520             {
521               /* POSIX says to clear this before the call */
522               TlsSetValue (dtor->index, NULL);
523               dtor->notify (value);
524               dtors_called = TRUE;
525             }
526         }
527     }
528   while (dtors_called);
529
530   if (self)
531     {
532       if (!self->joinable)
533         {
534           win32_check_for_error (CloseHandle (self->thread));
535           g_free (self);
536         }
537       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
538     }
539
540   if (g_thread_impl_vtable.CallThisOnThreadExit)
541     g_thread_impl_vtable.CallThisOnThreadExit ();
542
543   _endthreadex (0);
544 }
545
546 static guint __stdcall
547 g_thread_proxy (gpointer data)
548 {
549   GThreadData *self = (GThreadData*) data;
550
551   win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
552
553   self->func (self->data);
554
555   g_system_thread_exit ();
556
557   g_assert_not_reached ();
558
559   return 0;
560 }
561
562 void
563 g_system_thread_create (GThreadFunc       func,
564                         gpointer          data,
565                         gulong            stack_size,
566                         gboolean          joinable,
567                         gpointer          thread,
568                         GError          **error)
569 {
570   guint ignore;
571   GThreadData *retval;
572
573   g_return_if_fail (func);
574
575   retval = g_new(GThreadData, 1);
576   retval->func = func;
577   retval->data = data;
578
579   retval->joinable = joinable;
580
581   retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
582                                             retval, 0, &ignore);
583
584   if (retval->thread == NULL)
585     {
586       gchar *win_error = g_win32_error_message (GetLastError ());
587       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
588                    "Error creating thread: %s", win_error);
589       g_free (retval);
590       g_free (win_error);
591       return;
592     }
593
594   *(GThreadData **)thread = retval;
595 }
596
597 void
598 g_thread_yield (void)
599 {
600   Sleep(0);
601 }
602
603 void
604 g_system_thread_join (gpointer thread)
605 {
606   GThreadData *target = *(GThreadData **)thread;
607
608   g_return_if_fail (target->joinable);
609
610   win32_check_for_error (WAIT_FAILED !=
611                          WaitForSingleObject (target->thread, INFINITE));
612
613   win32_check_for_error (CloseHandle (target->thread));
614   g_free (target);
615 }
616
617 gboolean
618 g_system_thread_equal (gpointer thread1,
619                        gpointer thread2)
620 {
621    return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
622 }
623
624 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
625
626 static CRITICAL_SECTION g_thread_xp_lock;
627 static DWORD            g_thread_xp_waiter_tls;
628
629 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
630 typedef struct _GThreadXpWaiter GThreadXpWaiter;
631 struct _GThreadXpWaiter
632 {
633   HANDLE                    event;
634   volatile GThreadXpWaiter *next;
635 };
636
637 static GThreadXpWaiter *
638 g_thread_xp_waiter_get (void)
639 {
640   GThreadXpWaiter *waiter;
641
642   waiter = TlsGetValue (g_thread_xp_waiter_tls);
643
644   if G_UNLIKELY (waiter == NULL)
645     {
646       waiter = malloc (sizeof (GThreadXpWaiter));
647       if (waiter == NULL)
648         g_thread_abort (GetLastError (), "malloc");
649       waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
650       if (waiter->event == NULL)
651         g_thread_abort (GetLastError (), "CreateEvent");
652
653       TlsSetValue (g_thread_xp_waiter_tls, waiter);
654     }
655
656   return waiter;
657 }
658
659 static void __stdcall
660 g_thread_xp_CallThisOnThreadExit (void)
661 {
662   GThreadXpWaiter *waiter;
663
664   waiter = TlsGetValue (g_thread_xp_waiter_tls);
665
666   if (waiter != NULL)
667     {
668       TlsSetValue (g_thread_xp_waiter_tls, NULL);
669       CloseHandle (waiter->event);
670       free (waiter);
671     }
672 }
673
674 /* {{{2 SRWLock emulation */
675 typedef struct
676 {
677   CRITICAL_SECTION  writer_lock;
678   gboolean          ever_shared;    /* protected by writer_lock */
679   gboolean          writer_locked;  /* protected by writer_lock */
680
681   /* below is only ever touched if ever_shared becomes true */
682   CRITICAL_SECTION  atomicity;
683   GThreadXpWaiter  *queued_writer; /* protected by atomicity lock */
684   gint              num_readers;   /* protected by atomicity lock */
685 } GThreadSRWLock;
686
687 static void __stdcall
688 g_thread_xp_InitializeSRWLock (gpointer mutex)
689 {
690   *(GThreadSRWLock * volatile *) mutex = NULL;
691 }
692
693 static void __stdcall
694 g_thread_xp_DeleteSRWLock (gpointer mutex)
695 {
696   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
697
698   if (lock)
699     {
700       if (lock->ever_shared)
701         DeleteCriticalSection (&lock->atomicity);
702
703       DeleteCriticalSection (&lock->writer_lock);
704       free (lock);
705     }
706 }
707
708 static GThreadSRWLock * __stdcall
709 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
710 {
711   GThreadSRWLock *result;
712
713   /* It looks like we're missing some barriers here, but this code only
714    * ever runs on Windows XP, which in turn only ever runs on hardware
715    * with a relatively rigid memory model.  The 'volatile' will take
716    * care of the compiler.
717    */
718   result = *lock;
719
720   if G_UNLIKELY (result == NULL)
721     {
722       EnterCriticalSection (&g_thread_xp_lock);
723
724       result = malloc (sizeof (GThreadSRWLock));
725
726       if (result == NULL)
727         g_thread_abort (errno, "malloc");
728
729       InitializeCriticalSection (&result->writer_lock);
730       result->writer_locked = FALSE;
731       result->ever_shared = FALSE;
732       *lock = result;
733
734       LeaveCriticalSection (&g_thread_xp_lock);
735     }
736
737   return result;
738 }
739
740 static void __stdcall
741 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
742 {
743   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
744
745   EnterCriticalSection (&lock->writer_lock);
746
747   /* CRITICAL_SECTION is reentrant, but SRWLock is not.
748    * Detect the deadlock that would occur on later Windows version.
749    */
750   g_assert (!lock->writer_locked);
751   lock->writer_locked = TRUE;
752
753   if (lock->ever_shared)
754     {
755       GThreadXpWaiter *waiter = NULL;
756
757       EnterCriticalSection (&lock->atomicity);
758       if (lock->num_readers > 0)
759         lock->queued_writer = waiter = g_thread_xp_waiter_get ();
760       LeaveCriticalSection (&lock->atomicity);
761
762       if (waiter != NULL)
763         WaitForSingleObject (waiter->event, INFINITE);
764
765       lock->queued_writer = NULL;
766     }
767 }
768
769 static BOOLEAN __stdcall
770 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
771 {
772   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
773
774   if (!TryEnterCriticalSection (&lock->writer_lock))
775     return FALSE;
776
777   /* CRITICAL_SECTION is reentrant, but SRWLock is not.
778    * Ensure that this properly returns FALSE (as SRWLock would).
779    */
780   if G_UNLIKELY (lock->writer_locked)
781     {
782       LeaveCriticalSection (&lock->writer_lock);
783       return FALSE;
784     }
785
786   lock->writer_locked = TRUE;
787
788   if (lock->ever_shared)
789     {
790       gboolean available;
791
792       EnterCriticalSection (&lock->atomicity);
793       available = lock->num_readers == 0;
794       LeaveCriticalSection (&lock->atomicity);
795
796       if (!available)
797         {
798           LeaveCriticalSection (&lock->writer_lock);
799           return FALSE;
800         }
801     }
802
803   return TRUE;
804 }
805
806 static void __stdcall
807 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
808 {
809   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
810
811   lock->writer_locked = FALSE;
812
813   /* We need this until we fix some weird parts of GLib that try to
814    * unlock freshly-allocated mutexes.
815    */
816   if (lock != NULL)
817     LeaveCriticalSection (&lock->writer_lock);
818 }
819
820 static void
821 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
822 {
823   if G_UNLIKELY (!lock->ever_shared)
824     {
825       InitializeCriticalSection (&lock->atomicity);
826       lock->queued_writer = NULL;
827       lock->num_readers = 0;
828
829       lock->ever_shared = TRUE;
830     }
831
832   EnterCriticalSection (&lock->atomicity);
833   lock->num_readers++;
834   LeaveCriticalSection (&lock->atomicity);
835 }
836
837 static void __stdcall
838 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
839 {
840   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
841
842   EnterCriticalSection (&lock->writer_lock);
843
844   /* See g_thread_xp_AcquireSRWLockExclusive */
845   g_assert (!lock->writer_locked);
846
847   g_thread_xp_srwlock_become_reader (lock);
848
849   LeaveCriticalSection (&lock->writer_lock);
850 }
851
852 static BOOLEAN __stdcall
853 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
854 {
855   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
856
857   if (!TryEnterCriticalSection (&lock->writer_lock))
858     return FALSE;
859
860   /* See g_thread_xp_AcquireSRWLockExclusive */
861   if G_UNLIKELY (lock->writer_locked)
862     {
863       LeaveCriticalSection (&lock->writer_lock);
864       return FALSE;
865     }
866
867   g_thread_xp_srwlock_become_reader (lock);
868
869   LeaveCriticalSection (&lock->writer_lock);
870
871   return TRUE;
872 }
873
874 static void __stdcall
875 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
876 {
877   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
878
879   EnterCriticalSection (&lock->atomicity);
880
881   lock->num_readers--;
882
883   if (lock->num_readers == 0 && lock->queued_writer)
884     SetEvent (lock->queued_writer->event);
885
886   LeaveCriticalSection (&lock->atomicity);
887 }
888
889 /* {{{2 CONDITION_VARIABLE emulation */
890 typedef struct
891 {
892   volatile GThreadXpWaiter  *first;
893   volatile GThreadXpWaiter **last_ptr;
894 } GThreadXpCONDITION_VARIABLE;
895
896 static void __stdcall
897 g_thread_xp_InitializeConditionVariable (gpointer cond)
898 {
899   *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
900 }
901
902 static void __stdcall
903 g_thread_xp_DeleteConditionVariable (gpointer cond)
904 {
905   GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
906
907   if (cv)
908     free (cv);
909 }
910
911 static GThreadXpCONDITION_VARIABLE * __stdcall
912 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
913 {
914   GThreadXpCONDITION_VARIABLE *result;
915
916   /* It looks like we're missing some barriers here, but this code only
917    * ever runs on Windows XP, which in turn only ever runs on hardware
918    * with a relatively rigid memory model.  The 'volatile' will take
919    * care of the compiler.
920    */
921   result = *cond;
922
923   if G_UNLIKELY (result == NULL)
924     {
925       result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
926
927       if (result == NULL)
928         g_thread_abort (errno, "malloc");
929
930       result->first = NULL;
931       result->last_ptr = &result->first;
932
933       if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
934         {
935           free (result);
936           result = *cond;
937         }
938     }
939
940   return result;
941 }
942
943 static BOOL __stdcall
944 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
945                                        gpointer mutex,
946                                        DWORD    timeout,
947                                        ULONG    flags)
948 {
949   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
950   GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
951   DWORD status;
952
953   waiter->next = NULL;
954
955   EnterCriticalSection (&g_thread_xp_lock);
956   *cv->last_ptr = waiter;
957   cv->last_ptr = &waiter->next;
958   LeaveCriticalSection (&g_thread_xp_lock);
959
960   g_mutex_unlock (mutex);
961   status = WaitForSingleObject (waiter->event, timeout);
962
963   if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
964     g_thread_abort (GetLastError (), "WaitForSingleObject");
965
966   g_mutex_lock (mutex);
967
968   return status == WAIT_OBJECT_0;
969 }
970
971 static void __stdcall
972 g_thread_xp_WakeConditionVariable (gpointer cond)
973 {
974   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
975   volatile GThreadXpWaiter *waiter;
976
977   EnterCriticalSection (&g_thread_xp_lock);
978   waiter = cv->first;
979   if (waiter != NULL)
980     {
981       cv->first = waiter->next;
982       if (cv->first == NULL)
983         cv->last_ptr = &cv->first;
984     }
985   LeaveCriticalSection (&g_thread_xp_lock);
986
987   if (waiter != NULL)
988     SetEvent (waiter->event);
989 }
990
991 static void __stdcall
992 g_thread_xp_WakeAllConditionVariable (gpointer cond)
993 {
994   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
995   volatile GThreadXpWaiter *waiter;
996
997   EnterCriticalSection (&g_thread_xp_lock);
998   waiter = cv->first;
999   cv->first = NULL;
1000   cv->last_ptr = &cv->first;
1001   LeaveCriticalSection (&g_thread_xp_lock);
1002
1003   while (waiter != NULL)
1004     {
1005       volatile GThreadXpWaiter *next;
1006
1007       next = waiter->next;
1008       SetEvent (waiter->event);
1009       waiter = next;
1010     }
1011 }
1012
1013 /* {{{2 XP Setup */
1014 static void
1015 g_thread_xp_init (void)
1016 {
1017   static const GThreadImplVtable g_thread_xp_impl_vtable = {
1018     g_thread_xp_CallThisOnThreadExit,
1019     g_thread_xp_InitializeSRWLock,
1020     g_thread_xp_DeleteSRWLock,
1021     g_thread_xp_AcquireSRWLockExclusive,
1022     g_thread_xp_TryAcquireSRWLockExclusive,
1023     g_thread_xp_ReleaseSRWLockExclusive,
1024     g_thread_xp_AcquireSRWLockShared,
1025     g_thread_xp_TryAcquireSRWLockShared,
1026     g_thread_xp_ReleaseSRWLockShared,
1027     g_thread_xp_InitializeConditionVariable,
1028     g_thread_xp_DeleteConditionVariable,
1029     g_thread_xp_SleepConditionVariableSRW,
1030     g_thread_xp_WakeAllConditionVariable,
1031     g_thread_xp_WakeConditionVariable
1032   };
1033
1034   InitializeCriticalSection (&g_thread_xp_lock);
1035   g_thread_xp_waiter_tls = TlsAlloc ();
1036
1037   g_thread_impl_vtable = g_thread_xp_impl_vtable;
1038 }
1039
1040 /* {{{1 Epilogue */
1041
1042 static gboolean
1043 g_thread_lookup_native_funcs (void)
1044 {
1045   GThreadImplVtable native_vtable = { 0, };
1046   HMODULE kernel32;
1047
1048   kernel32 = GetModuleHandle ("KERNEL32.DLL");
1049
1050   if (kernel32 == NULL)
1051     return FALSE;
1052
1053 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
1054   GET_FUNC(InitializeSRWLock);
1055   GET_FUNC(AcquireSRWLockExclusive);
1056   GET_FUNC(TryAcquireSRWLockExclusive);
1057   GET_FUNC(ReleaseSRWLockExclusive);
1058   GET_FUNC(AcquireSRWLockShared);
1059   GET_FUNC(TryAcquireSRWLockShared);
1060   GET_FUNC(ReleaseSRWLockShared);
1061
1062   GET_FUNC(InitializeConditionVariable);
1063   GET_FUNC(SleepConditionVariableSRW);
1064   GET_FUNC(WakeAllConditionVariable);
1065   GET_FUNC(WakeConditionVariable);
1066 #undef GET_FUNC
1067
1068   g_thread_impl_vtable = native_vtable;
1069
1070   return TRUE;
1071 }
1072
1073 G_GNUC_INTERNAL void
1074 g_thread_DllMain (void)
1075 {
1076   if (g_thread_lookup_native_funcs ())
1077     fprintf (stderr, "(debug) GThread using native mode\n");
1078   else
1079     {
1080       fprintf (stderr, "(debug) GThread using Windows XP mode\n");
1081       g_thread_xp_init ();
1082     }
1083
1084   win32_check_for_error (TLS_OUT_OF_INDEXES != (g_thread_self_tls = TlsAlloc ()));
1085   InitializeCriticalSection (&g_private_lock);
1086 }
1087
1088 /* vim:set foldmethod=marker: */
1089