summaryrefslogtreecommitdiffstats
path: root/dbus/dbus-threads.c
blob: 98f087304a4f88caf14e7efa3c36f06301a5198f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dbus-threads.h  D-Bus threads handling
 *
 * Copyright (C) 2002, 2003 Red Hat Inc.
 *
 * Licensed under the Academic Free License version 2.1
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "dbus-threads.h"
#include "dbus-internals.h"
#include "dbus-threads-internal.h"
#include "dbus-list.h"

#if defined(__WIN32) || defined(__CYGWIN__)
#define USE_WIN32_THREADS
#endif

#ifdef USE_WIN32_THREADS
#include <windows.h>
#else
#include <sys/time.h>
#include <pthread.h>
#endif

static DBusThreadFunctions thread_functions =
{
  0,
  NULL, NULL, NULL, NULL, NULL,
  NULL, NULL, NULL, NULL, NULL,
  NULL, NULL, NULL, NULL,
  
  NULL, NULL, NULL, NULL
};

#ifdef USE_WIN32_THREADS
struct DBusCondVar {
  DBusList *list;
  CRITICAL_SECTION lock;
};

static DWORD dbus_cond_event_tls = TLS_OUT_OF_INDEXES;
#endif

static int thread_init_generation = 0;
 
static DBusList *uninitialized_mutex_list = NULL;
static DBusList *uninitialized_condvar_list = NULL;

/** This is used for the no-op default mutex pointer, just to be distinct from #NULL */
#define _DBUS_DUMMY_MUTEX ((DBusMutex*)0xABCDEF)

/** This is used for the no-op default mutex pointer, just to be distinct from #NULL */
#define _DBUS_DUMMY_CONDVAR ((DBusCondVar*)0xABCDEF2)

/**
 * @defgroup DBusThreadsInternals Thread functions
 * @ingroup  DBusInternals
 * @brief _dbus_mutex_lock(), etc.
 *
 * Functions and macros related to threads and thread locks.
 *
 * @{
 */

/**
 * Creates a new mutex using the function supplied to dbus_threads_init(),
 * or creates a no-op mutex if threads are not initialized.
 * May return #NULL even if threads are initialized, indicating
 * out-of-memory.
 *
 * @returns new mutex or #NULL
 */
DBusMutex*
_dbus_mutex_new (void)
{
  if (thread_functions.recursive_mutex_new)
    return (* thread_functions.recursive_mutex_new) ();
  else if (thread_functions.mutex_new)
    return (* thread_functions.mutex_new) ();
  else
    return _DBUS_DUMMY_MUTEX;
}

/**
 * This does the same thing as _dbus_mutex_new.  It however
 * gives another level of indirection by allocating a pointer
 * to point to the mutex location.  This allows the threading
 * module to swap out dummy mutexes for real a real mutex so libraries
 * can initialize threads even after the D-Bus API has been used.
 *
 * @param location_p the location of the new mutex, can return #NULL on OOM
 */
void
_dbus_mutex_new_at_location (DBusMutex **location_p)
{
  _dbus_assert (location_p != NULL);

  *location_p = _dbus_mutex_new();

  if (thread_init_generation != _dbus_current_generation && *location_p)
    {
      if (!_dbus_list_append (&uninitialized_mutex_list, location_p))
        {
	  _dbus_mutex_free (*location_p);
	  *location_p = NULL;
	}
    }
}

/**
 * Frees a mutex created with dbus_mutex_new(); does
 * nothing if passed a #NULL pointer.
 */
void
_dbus_mutex_free (DBusMutex *mutex)
{
  if (mutex)
    {
      if (mutex && thread_functions.recursive_mutex_free)
        (* thread_functions.recursive_mutex_free) (mutex);
      else if (mutex && thread_functions.mutex_free)
        (* thread_functions.mutex_free) (mutex);
    }
}

/**
 * Frees a mutex and removes it from the 
 * uninitialized_mutex_list;
 * does nothing if passed a #NULL pointer.
 */
void
_dbus_mutex_free_at_location (DBusMutex **location_p)
{
  if (location_p)
    {
      if (thread_init_generation != _dbus_current_generation)
        _dbus_list_remove (&uninitialized_mutex_list, location_p);

      _dbus_mutex_free (*location_p);
    }
}

/**
 * Locks a mutex. Does nothing if passed a #NULL pointer.
 * Locks may be recursive if threading implementation initialized
 * recursive locks.
 */
void
_dbus_mutex_lock (DBusMutex *mutex)
{
  if (mutex) 
    {
      if (thread_functions.recursive_mutex_lock)
        (* thread_functions.recursive_mutex_lock) (mutex);
      else if (thread_functions.mutex_lock)
        (* thread_functions.mutex_lock) (mutex);
    }
}

/**
 * Unlocks a mutex. Does nothing if passed a #NULL pointer.
 *
 * @returns #TRUE on success
 */
void
_dbus_mutex_unlock (DBusMutex *mutex)
{
  if (mutex)
    {
      if (thread_functions.recursive_mutex_unlock)
        (* thread_functions.recursive_mutex_unlock) (mutex);
      else if (thread_functions.mutex_unlock)
        (* thread_functions.mutex_unlock) (mutex);
    }
}

/**
 * Creates a new condition variable using the function supplied
 * to dbus_threads_init(), or creates a no-op condition variable
 * if threads are not initialized. May return #NULL even if
 * threads are initialized, indicating out-of-memory.
 *
 * @returns new mutex or #NULL
 */
DBusCondVar *
_dbus_condvar_new (void)
{
  if (thread_functions.condvar_new)
    return (* thread_functions.condvar_new) ();
  else
    return _DBUS_DUMMY_CONDVAR;
}


/**
 * This does the same thing as _dbus_condvar_new.  It however
 * gives another level of indirection by allocating a pointer
 * to point to the condvar location.  This allows the threading
 * module to swap out dummy condvars for real a real condvar so libraries
 * can initialize threads even after the D-Bus API has been used.
 *
 * @returns the location of a new condvar or #NULL on OOM
 */

void 
_dbus_condvar_new_at_location (DBusCondVar **location_p)
{
  *location_p = _dbus_condvar_new();

  if (thread_init_generation != _dbus_current_generation && *location_p)
    {
      if (!_dbus_list_append (&uninitialized_condvar_list, location_p))
        {
          _dbus_condvar_free (*location_p);
          *location_p = NULL;
        }
    }
}


/**
 * Frees a conditional variable created with dbus_condvar_new(); does
 * nothing if passed a #NULL pointer.
 */
void
_dbus_condvar_free (DBusCondVar *cond)
{
  if (cond && thread_functions.condvar_free)
    (* thread_functions.condvar_free) (cond);
}

/**
 * Frees a conditional variable and removes it from the 
 * uninitialized_condvar_list; 
 * does nothing if passed a #NULL pointer.
 */
void
_dbus_condvar_free_at_location (DBusCondVar **location_p)
{
  if (location_p)
    {
      if (thread_init_generation != _dbus_current_generation)
        _dbus_list_remove (&uninitialized_condvar_list, location_p);

      _dbus_condvar_free (*location_p);
    }
}

/**
 * Atomically unlocks the mutex and waits for the conditions
 * variable to be signalled. Locks the mutex again before
 * returning.
 * Does nothing if passed a #NULL pointer.
 */
void
_dbus_condvar_wait (DBusCondVar *cond,
                    DBusMutex   *mutex)
{
  if (cond && mutex && thread_functions.condvar_wait)
    (* thread_functions.condvar_wait) (cond, mutex);
}

/**
 * Atomically unlocks the mutex and waits for the conditions
 * variable to be signalled, or for a timeout. Locks the
 * mutex again before returning.
 * Does nothing if passed a #NULL pointer.
 *
 * @param cond the condition variable
 * @param mutex the mutex
 * @param timeout_milliseconds the maximum time to wait
 * @returns TRUE if the condition was reached, or FALSE if the
 * timeout was reached.
 */
dbus_bool_t
_dbus_condvar_wait_timeout (DBusCondVar               *cond,
                            DBusMutex                 *mutex,
                            int                        timeout_milliseconds)
{
  if (cond && mutex && thread_functions.condvar_wait)
    return (* thread_functions.condvar_wait_timeout) (cond, mutex, timeout_milliseconds);
  else
    return TRUE;
}

/**
 * If there are threads waiting on the condition variable, wake
 * up exactly one. 
 * Does nothing if passed a #NULL pointer.
 */
void
_dbus_condvar_wake_one (DBusCondVar *cond)
{
  if (cond && thread_functions.condvar_wake_one)
    (* thread_functions.condvar_wake_one) (cond);
}

/**
 * If there are threads waiting on the condition variable, wake
 * up all of them. 
 * Does nothing if passed a #NULL pointer.
 */
void
_dbus_condvar_wake_all (DBusCondVar *cond)
{
  if (cond && thread_functions.condvar_wake_all)
    (* thread_functions.condvar_wake_all) (cond);
}

static void
shutdown_global_locks (void *data)
{
  DBusMutex ***locks = data;
  int i;

  i = 0;
  while (i < _DBUS_N_GLOBAL_LOCKS)
    {
      _dbus_mutex_free (*(locks[i]));
      *(locks[i]) = NULL;
      ++i;
    }
  
  dbus_free (locks);
}

static void
shutdown_uninitialized_locks (void *data)
{
  _dbus_list_clear (&uninitialized_mutex_list);
  _dbus_list_clear (&uninitialized_condvar_list);
}

static dbus_bool_t
init_uninitialized_locks (void)
{
  DBusList *link;

  _dbus_assert (thread_init_generation != _dbus_current_generation);

  link = uninitialized_mutex_list;
  while (link != NULL)
    {
      DBusMutex **mp;

      mp = (DBusMutex **)link->data;
      _dbus_assert (*mp == _DBUS_DUMMY_MUTEX);

      *mp = _dbus_mutex_new ();
      if (*mp == NULL)
        goto fail_mutex;

      link = _dbus_list_get_next_link (&uninitialized_mutex_list, link);
    }

  link = uninitialized_condvar_list;
  while (link != NULL)
    {
      DBusCondVar **cp;

      cp = (DBusCondVar **)link->data;
      _dbus_assert (*cp == _DBUS_DUMMY_CONDVAR);

      *cp = _dbus_condvar_new ();
      if (*cp == NULL)
        goto fail_condvar;

      link = _dbus_list_get_next_link (&uninitialized_condvar_list, link);
    }

  _dbus_list_clear (&uninitialized_mutex_list);
  _dbus_list_clear (&uninitialized_condvar_list);

  if (!_dbus_register_shutdown_func (shutdown_uninitialized_locks,
                                     NULL))
    goto fail_condvar;

  return TRUE;

 fail_condvar:
  link = uninitialized_condvar_list;
  while (link != NULL)
    {
      DBusCondVar **cp;

      cp = (DBusCondVar **)link->data;

      if (*cp != _DBUS_DUMMY_CONDVAR)
        _dbus_condvar_free (*cp);
      else
        break;

      *cp = _DBUS_DUMMY_CONDVAR;

      link = _dbus_list_get_next_link (&uninitialized_condvar_list, link);
    }

 fail_mutex:
  link = uninitialized_mutex_list;
  while (link != NULL)
    {
      DBusMutex **mp;

      mp = (DBusMutex **)link->data;

      if (*mp != _DBUS_DUMMY_MUTEX)
        _dbus_mutex_free (*mp);
      else
        break;

      *mp = _DBUS_DUMMY_MUTEX;

      link = _dbus_list_get_next_link (&uninitialized_mutex_list, link);
    }

  return FALSE;
}

static dbus_bool_t
init_locks (void)
{
  int i;
  DBusMutex ***dynamic_global_locks;
  
  DBusMutex **global_locks[] = {
#define LOCK_ADDR(name) (& _dbus_lock_##name)
    LOCK_ADDR (win_fds),
    LOCK_ADDR (sid_atom_cache),
    LOCK_ADDR (list),
    LOCK_ADDR (connection_slots),
    LOCK_ADDR (pending_call_slots),
    LOCK_ADDR (server_slots),
    LOCK_ADDR (message_slots),
    LOCK_ADDR (atomic),
    LOCK_ADDR (bus),
    LOCK_ADDR (shutdown_funcs),
    LOCK_ADDR (system_users),
    LOCK_ADDR (message_cache),
    LOCK_ADDR (shared_connections),
    LOCK_ADDR (machine_uuid)
#undef LOCK_ADDR
  };

  _dbus_assert (_DBUS_N_ELEMENTS (global_locks) ==
                _DBUS_N_GLOBAL_LOCKS);

  i = 0;
  
  dynamic_global_locks = dbus_new (DBusMutex**, _DBUS_N_GLOBAL_LOCKS);
  if (dynamic_global_locks == NULL)
    goto failed;
  
  while (i < _DBUS_N_ELEMENTS (global_locks))
    {
      *global_locks[i] = _dbus_mutex_new ();
      
      if (*global_locks[i] == NULL)
        goto failed;

      dynamic_global_locks[i] = global_locks[i];

      ++i;
    }
  
  if (!_dbus_register_shutdown_func (shutdown_global_locks,
                                     dynamic_global_locks))
    goto failed;

  if (!init_uninitialized_locks ())
    goto failed;
  
  return TRUE;

 failed:
  dbus_free (dynamic_global_locks);
                                     
  for (i = i - 1; i >= 0; i--)
    {
      _dbus_mutex_free (*global_locks[i]);
      *global_locks[i] = NULL;
    }
  return FALSE;
}

/** @} */ /* end of internals */

/**
 * @defgroup DBusThreads Thread functions
 * @ingroup  DBus
 * @brief dbus_threads_init() and dbus_threads_init_default()
 *
 * Functions and macros related to threads and thread locks.
 *
 * If threads are initialized, the D-Bus library has locks on all
 * global data structures.  In addition, each #DBusConnection has a
 * lock, so only one thread at a time can touch the connection.  (See
 * @ref DBusConnection for more on connection locking.)
 *
 * Most other objects, however, do not have locks - they can only be
 * used from a single thread at a time, unless you lock them yourself.
 * For example, a #DBusMessage can't be modified from two threads
 * at once.
 * 
 * @{
 */

/**
 * 
 * Initializes threads. If this function is not called, the D-Bus
 * library will not lock any data structures.  If it is called, D-Bus
 * will do locking, at some cost in efficiency. Note that this
 * function must be called BEFORE the second thread is started.
 *
 * Almost always, you should use dbus_threads_init_default() instead.
 * The raw dbus_threads_init() is only useful if you require a
 * particular thread implementation for some reason.
 *
 * A possible reason to use dbus_threads_init() rather than
 * dbus_threads_init_default() is to insert debugging checks or print
 * statements.
 *
 * dbus_threads_init() may be called more than once.  The first one
 * wins and subsequent calls are ignored. (Unless you use
 * dbus_shutdown() to reset libdbus, which will let you re-init
 * threads.)
 *
 * Either recursive or nonrecursive mutex functions must be specified,
 * but not both. New code should provide only the recursive functions
 * - specifying the nonrecursive ones is deprecated.
 *
 * Because this function effectively sets global state, all code
 * running in a given application must agree on the thread
 * implementation. Most code won't care which thread implementation is
 * used, so there's no problem. However, usually libraries should not
 * call dbus_threads_init() or dbus_threads_init_default(), instead
 * leaving this policy choice to applications.
 *
 * The exception is for application frameworks (GLib, Qt, etc.)  and
 * D-Bus bindings based on application frameworks. These frameworks
 * define a cross-platform thread abstraction and can assume
 * applications using the framework are OK with using that thread
 * abstraction.
 *
 * However, even these app frameworks may find it easier to simply call
 * dbus_threads_init_default(), and there's no reason they shouldn't.
 * 
 * @param functions functions for using threads
 * @returns #TRUE on success, #FALSE if no memory
 */
dbus_bool_t
dbus_threads_init (const DBusThreadFunctions *functions)
{
  dbus_bool_t mutex_set;
  dbus_bool_t recursive_mutex_set;

  _dbus_assert (functions != NULL);

  /* these base functions are required. Future additions to
   * DBusThreadFunctions may be optional.
   */
  _dbus_assert (functions->mask & DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK);
  _dbus_assert (functions->mask & DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK);
  _dbus_assert (functions->mask & DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK);
  _dbus_assert (functions->mask & DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK);
  _dbus_assert (functions->mask & DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK);
  _dbus_assert (functions->mask & DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK);
  _dbus_assert (functions->condvar_new != NULL);
  _dbus_assert (functions->condvar_free != NULL);
  _dbus_assert (functions->condvar_wait != NULL);
  _dbus_assert (functions->condvar_wait_timeout != NULL);
  _dbus_assert (functions->condvar_wake_one != NULL);
  _dbus_assert (functions->condvar_wake_all != NULL);

  /* Either the mutex function set or recursive mutex set needs 
   * to be available but not both
   */
  mutex_set = (functions->mask & DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK) &&  
              (functions->mask & DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK) && 
              (functions->mask & DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK) &&
              (functions->mask & DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK) &&
               functions->mutex_new &&
               functions->mutex_free &&
               functions->mutex_lock &&
               functions->mutex_unlock;

  recursive_mutex_set = 
              (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK) && 
              (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK) && 
              (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK) && 
              (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK) &&
                functions->recursive_mutex_new &&
                functions->recursive_mutex_free &&
                functions->recursive_mutex_lock &&
                functions->recursive_mutex_unlock;

  if (!(mutex_set || recursive_mutex_set))
    _dbus_assert_not_reached ("Either the nonrecusrive or recursive mutex " 
                              "functions sets should be passed into "
                              "dbus_threads_init. Neither sets were passed.");

  if (mutex_set && recursive_mutex_set)
    _dbus_assert_not_reached ("Either the nonrecusrive or recursive mutex " 
                              "functions sets should be passed into "
                              "dbus_threads_init. Both sets were passed. "
                              "You most likely just want to set the recursive "
                              "mutex functions to avoid deadlocks in D-Bus.");
                          
  /* Check that all bits in the mask actually are valid mask bits.
   * ensures people won't write code that breaks when we add
   * new bits.
   */
  _dbus_assert ((functions->mask & ~DBUS_THREAD_FUNCTIONS_ALL_MASK) == 0);

  if (thread_init_generation != _dbus_current_generation)
    thread_functions.mask = 0; /* allow re-init in new generation */
 
  /* Silently allow multiple init
   * First init wins and D-Bus will always use its threading system 
   */ 
  if (thread_functions.mask != 0)
    return TRUE;
  
  thread_functions.mutex_new = functions->mutex_new;
  thread_functions.mutex_free = functions->mutex_free;
  thread_functions.mutex_lock = functions->mutex_lock;
  thread_functions.mutex_unlock = functions->mutex_unlock;
  
  thread_functions.condvar_new = functions->condvar_new;
  thread_functions.condvar_free = functions->condvar_free;
  thread_functions.condvar_wait = functions->condvar_wait;
  thread_functions.condvar_wait_timeout = functions->condvar_wait_timeout;
  thread_functions.condvar_wake_one = functions->condvar_wake_one;
  thread_functions.condvar_wake_all = functions->condvar_wake_all;
 
  if (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK)
    thread_functions.recursive_mutex_new = functions->recursive_mutex_new;
  
  if (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK)
    thread_functions.recursive_mutex_free = functions->recursive_mutex_free;
  
  if (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK)
    thread_functions.recursive_mutex_lock = functions->recursive_mutex_lock;

  if (functions->mask & DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK)
    thread_functions.recursive_mutex_unlock = functions->recursive_mutex_unlock;

  thread_functions.mask = functions->mask;

  if (!init_locks ())
    return FALSE;

  thread_init_generation = _dbus_current_generation;
  
  return TRUE;
}



/* Default thread implemenation */

static DBusMutex*   _dbus_internal_mutex_new            (void);
static void         _dbus_internal_mutex_free           (DBusMutex   *mutex);
static dbus_bool_t  _dbus_internal_mutex_lock           (DBusMutex   *mutex);
static dbus_bool_t  _dbus_internal_mutex_unlock         (DBusMutex   *mutex);
static DBusCondVar *_dbus_internal_condvar_new          (void);
static void         _dbus_internal_condvar_free         (DBusCondVar *cond);
static void         _dbus_internal_condvar_wait         (DBusCondVar *cond,
							 DBusMutex   *mutex);
static dbus_bool_t  _dbus_internal_condvar_wait_timeout (DBusCondVar *cond,
							 DBusMutex   *mutex,
							 int          timeout_milliseconds);
static void         _dbus_internal_condvar_wake_one     (DBusCondVar *cond);
static void         _dbus_internal_condvar_wake_all     (DBusCondVar *cond);

#ifdef USE_WIN32_THREADS

BOOL WINAPI DllMain (HINSTANCE hinstDLL,
		     DWORD     fdwReason,
		     LPVOID    lpvReserved);

/* We need this to free the TLS events on thread exit */
BOOL WINAPI
DllMain (HINSTANCE hinstDLL,
	 DWORD     fdwReason,
	 LPVOID    lpvReserved)
{
  HANDLE event;
  switch (fdwReason) 
    { 
    case DLL_THREAD_DETACH:
      if (dbus_cond_event_tls != TLS_OUT_OF_INDEXES)
	{
	  event = TlsGetValue(dbus_cond_event_tls);
	  CloseHandle (event);
	  TlsSetValue(dbus_cond_event_tls, NULL);
	}
      break;
    case DLL_PROCESS_DETACH: 
      if (dbus_cond_event_tls != TLS_OUT_OF_INDEXES)
	{
	  event = TlsGetValue(dbus_cond_event_tls);
	  CloseHandle (event);
	  TlsSetValue(dbus_cond_event_tls, NULL);

	  TlsFree(dbus_cond_event_tls); 
	}
      break;
    default: 
      break; 
    }
  return TRUE;
}

static DBusMutex*
_dbus_internal_mutex_new (void)
{
  HANDLE handle;
  handle = CreateMutex (NULL, FALSE, NULL);
  return (DBusMutex *) handle;
}

static void
_dbus_internal_mutex_free (DBusMutex *mutex)
{
  CloseHandle ((HANDLE *) mutex);
}

static dbus_bool_t
_dbus_internal_mutex_lock (DBusMutex *mutex)
{
  return WaitForSingleObject ((HANDLE *) mutex, INFINITE) != WAIT_FAILED;
}

static dbus_bool_t
_dbus_internal_mutex_unlock (DBusMutex *mutex)
{
  return ReleaseMutex ((HANDLE *) mutex) != 0;
}

static DBusCondVar *
_dbus_internal_condvar_new (void)
{
  DBusCondVar *cond;
    
  cond = dbus_new (DBusCondVar, 1);
  if (cond == NULL)
    return NULL;
  
  cond->list = NULL;
  
  InitializeCriticalSection (&cond->lock);
  return (DBusCondVar *) cond;
}

static void
_dbus_internal_condvar_free (DBusCondVar *cond)
{
  DeleteCriticalSection (&cond->lock);
  _dbus_list_clear (&cond->list);
  dbus_free (cond);
}

static dbus_bool_t
_dbus_condvar_wait_win32 (DBusCondVar *cond,
			  DBusMutex *mutex,
			  int milliseconds)
{
  DWORD retval;
  dbus_bool_t ret;
  HANDLE event = TlsGetValue (dbus_cond_event_tls);

  if (!event)
    {
      event = CreateEvent (0, FALSE, FALSE, NULL);
      if (event == 0)
	return FALSE;
      TlsSetValue (dbus_cond_event_tls, event);
    }

  EnterCriticalSection (&cond->lock);

  /* The event must not be signaled. Check this */
  _dbus_assert (WaitForSingleObject (event, 0) == WAIT_TIMEOUT);

  ret = _dbus_list_append (&cond->list, event);
  
  LeaveCriticalSection (&cond->lock);
  
  if (!ret)
    return FALSE; /* Prepend failed */

  _dbus_mutex_unlock (mutex);
  retval = WaitForSingleObject (event, milliseconds);
  _dbus_mutex_lock (mutex);
  
  if (retval == WAIT_TIMEOUT)
    {
      EnterCriticalSection (&cond->lock);
      _dbus_list_remove (&cond->list, event);

      /* In the meantime we could have been signaled, so we must again
       * wait for the signal, this time with no timeout, to reset
       * it. retval is set again to honour the late arrival of the
       * signal */
      retval = WaitForSingleObject (event, 0);

      LeaveCriticalSection (&cond->lock);
    }

#ifndef DBUS_DISABLE_ASSERT
  EnterCriticalSection (&cond->lock);

  /* Now event must not be inside the array, check this */
  _dbus_assert (_dbus_list_remove (cond->list, event) == FALSE);

  LeaveCriticalSection (&cond->lock);
#endif /* !G_DISABLE_ASSERT */

  return retval != WAIT_TIMEOUT;
}

static void
_dbus_internal_condvar_wait (DBusCondVar *cond,
                    DBusMutex   *mutex)
{
  _dbus_condvar_wait_win32 (cond, mutex, INFINITE);
}

static dbus_bool_t
_dbus_internal_condvar_wait_timeout (DBusCondVar               *cond,
				     DBusMutex                 *mutex,
				     int                        timeout_milliseconds)
{
  return _dbus_condvar_wait_win32 (cond, mutex, timeout_milliseconds);
}

static void
_dbus_internal_condvar_wake_one (DBusCondVar *cond)
{
  EnterCriticalSection (&cond->lock);
  
  if (cond->list != NULL)
    SetEvent (_dbus_list_pop_first (&cond->list));
    
  LeaveCriticalSection (&cond->lock);
}

static void
_dbus_internal_condvar_wake_all (DBusCondVar *cond)
{
  EnterCriticalSection (&cond->lock);

  while (cond->list != NULL)
    SetEvent (_dbus_list_pop_first (&cond->list));
  
  LeaveCriticalSection (&cond->lock);
}


#else /* Posix threads */

static DBusMutex*
_dbus_internal_mutex_new (void)
{
  pthread_mutex_t *retval;
  
  retval = dbus_new (pthread_mutex_t, 1);
  if (retval == NULL)
    return NULL;
  
  if (pthread_mutex_init (retval, NULL))
    {
      dbus_free (retval);
      return NULL;
    }
  return (DBusMutex *) retval;
}

static void
_dbus_internal_mutex_free (DBusMutex *mutex)
{
  pthread_mutex_destroy ((pthread_mutex_t *) mutex);
  dbus_free (mutex);
}

static dbus_bool_t
_dbus_internal_mutex_lock (DBusMutex *mutex)
{
  return pthread_mutex_lock ((pthread_mutex_t *) mutex) == 0;
}

static dbus_bool_t
_dbus_internal_mutex_unlock (DBusMutex *mutex)
{
  return pthread_mutex_unlock ((pthread_mutex_t *) mutex) == 0;
}

static DBusCondVar *
_dbus_internal_condvar_new (void)
{
  pthread_cond_t *retval;
  
  retval = dbus_new (pthread_cond_t, 1);
  if (retval == NULL)
    return NULL;
  
  if (pthread_cond_init (retval, NULL))
    {
      dbus_free (retval);
      return NULL;
    }
  return (DBusCondVar *) retval;
}

static void
_dbus_internal_condvar_free (DBusCondVar *cond)
{
  pthread_cond_destroy ((pthread_cond_t *) cond);
  dbus_free (cond);
}

static void
_dbus_internal_condvar_wait (DBusCondVar *cond,
                    DBusMutex   *mutex)
{
  pthread_cond_wait ((pthread_cond_t *)cond,
		     (pthread_mutex_t *) mutex);
}

static dbus_bool_t
_dbus_internal_condvar_wait_timeout (DBusCondVar               *cond,
				     DBusMutex                 *mutex,
				     int                        timeout_milliseconds)
{
  struct timeval time_now;
  struct timespec end_time;
  int result;
  
  gettimeofday (&time_now, NULL);
  
  end_time.tv_sec = time_now.tv_sec + timeout_milliseconds / 1000;
  end_time.tv_nsec = (time_now.tv_usec + (timeout_milliseconds % 1000) * 1000) * 1000;
  if (end_time.tv_nsec > 1000*1000*1000)
    {
      end_time.tv_sec += 1;
      end_time.tv_nsec -= 1000*1000*1000;
    }
  
  result = pthread_cond_timedwait ((pthread_cond_t *) cond,
				   (pthread_mutex_t *) mutex,
				   &end_time);
  return result == ETIMEDOUT;
}

static void
_dbus_internal_condvar_wake_one (DBusCondVar *cond)
{
  pthread_cond_signal ((pthread_cond_t *)cond);
}

static void
_dbus_internal_condvar_wake_all (DBusCondVar *cond)
{
  pthread_cond_broadcast ((pthread_cond_t *)cond);
}

#endif

static const DBusThreadFunctions internal_functions =
{
  DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK |
  DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK |
  DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK |
  DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
  _dbus_internal_mutex_new,
  _dbus_internal_mutex_free,
  _dbus_internal_mutex_lock,
  _dbus_internal_mutex_unlock,
  _dbus_internal_condvar_new,
  _dbus_internal_condvar_free,
  _dbus_internal_condvar_wait,
  _dbus_internal_condvar_wait_timeout,
  _dbus_internal_condvar_wake_one,
  _dbus_internal_condvar_wake_all
};

/**
 *
 * Calls dbus_threads_init() with a default set of
 * #DBusThreadFunctions appropriate for the platform.
 *
 * Most applications should use this rather than dbus_threads_init().
 *
 * It's safe to call dbus_threads_init_default() as many times as you
 * want, but only the first time will have an effect.
 *
 * dbus_shutdown() reverses the effects of this function when it
 * resets all global state in libdbus.
 * 
 * @returns #TRUE on success, #FALSE if not enough memory
 */
dbus_bool_t
dbus_threads_init_default (void)
{
#ifdef USE_WIN32_THREADS
  /* We reuse this over several generations, because we can't
   * free the events once they are in use
   */
  if (dbus_cond_event_tls == TLS_OUT_OF_INDEXES)
    {
      dbus_cond_event_tls = TlsAlloc ();
      if (dbus_cond_event_tls == TLS_OUT_OF_INDEXES)
	return FALSE;
    }
#endif
  
  return dbus_threads_init (&internal_functions);
}


/** @} */

#ifdef DBUS_BUILD_TESTS
/** Fake mutex used for debugging */
typedef struct DBusFakeMutex DBusFakeMutex;
/** Fake mutex used for debugging */
struct DBusFakeMutex
{
  dbus_bool_t locked; /**< Mutex is "locked" */
};	

static DBusMutex *  dbus_fake_mutex_new            (void);
static void         dbus_fake_mutex_free           (DBusMutex   *mutex);
static dbus_bool_t  dbus_fake_mutex_lock           (DBusMutex   *mutex);
static dbus_bool_t  dbus_fake_mutex_unlock         (DBusMutex   *mutex);
static DBusCondVar* dbus_fake_condvar_new          (void);
static void         dbus_fake_condvar_free         (DBusCondVar *cond);
static void         dbus_fake_condvar_wait         (DBusCondVar *cond,
                                                    DBusMutex   *mutex);
static dbus_bool_t  dbus_fake_condvar_wait_timeout (DBusCondVar *cond,
                                                    DBusMutex   *mutex,
                                                    int          timeout_msec);
static void         dbus_fake_condvar_wake_one     (DBusCondVar *cond);
static void         dbus_fake_condvar_wake_all     (DBusCondVar *cond);


static const DBusThreadFunctions fake_functions =
{
  DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK |
  DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK |
  DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK |
  DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
  DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
  dbus_fake_mutex_new,
  dbus_fake_mutex_free,
  dbus_fake_mutex_lock,
  dbus_fake_mutex_unlock,
  dbus_fake_condvar_new,
  dbus_fake_condvar_free,
  dbus_fake_condvar_wait,
  dbus_fake_condvar_wait_timeout,
  dbus_fake_condvar_wake_one,
  dbus_fake_condvar_wake_all
};

static DBusMutex *
dbus_fake_mutex_new (void)
{
  DBusFakeMutex *mutex;

  mutex = dbus_new0 (DBusFakeMutex, 1);

  return (DBusMutex *)mutex;
}

static void
dbus_fake_mutex_free (DBusMutex *mutex)
{
  DBusFakeMutex *fake = (DBusFakeMutex*) mutex;

  _dbus_assert (!fake->locked);
  
  dbus_free (fake);
}

static dbus_bool_t
dbus_fake_mutex_lock (DBusMutex *mutex)
{
  DBusFakeMutex *fake = (DBusFakeMutex*) mutex;

  _dbus_assert (!fake->locked);

  fake->locked = TRUE;
  
  return TRUE;
}

static dbus_bool_t
dbus_fake_mutex_unlock (DBusMutex *mutex)
{
  DBusFakeMutex *fake = (DBusFakeMutex*) mutex;

  _dbus_assert (fake->locked);

  fake->locked = FALSE;
  
  return TRUE;
}

static DBusCondVar*
dbus_fake_condvar_new (void)
{
  return (DBusCondVar*) _dbus_strdup ("FakeCondvar");
}

static void
dbus_fake_condvar_free (DBusCondVar *cond)
{
  dbus_free (cond);
}

static void
dbus_fake_condvar_wait (DBusCondVar *cond,
                        DBusMutex   *mutex)
{
  
}

static dbus_bool_t
dbus_fake_condvar_wait_timeout (DBusCondVar *cond,
                                DBusMutex   *mutex,
                                int         timeout_msec)
{
  return TRUE;
}

static void
dbus_fake_condvar_wake_one (DBusCondVar *cond)
{

}

static void
dbus_fake_condvar_wake_all (DBusCondVar *cond)
{

}

dbus_bool_t
_dbus_threads_init_debug (void)
{
  return dbus_threads_init (&fake_functions);
}

#endif /* DBUS_BUILD_TESTS */