download threads.c
Language: C
Copyright: (C) 2002-2006 Ximian, Inc.
LOC: 745
Project Info
Mono
Server: Mono
Type: svn
...\m\mono\mono\mono\io‑layer\
   access.h
   atomic.c
   atomic.h
   collection.c
   collection.h
   context.c
   context.h
   critical-sections.c
   critical-sections.h
   daemon-messages.c
   daemon-messages.h
   daemon-private.h
   daemon.c
   error.c
   error.h
   event-private.h
   events.c
   events.h
   handles-private.h
   handles.c
   handles.h
   hppa_atomic.s
   io-layer-dummy.c
   io-layer.h
   io-portability.c
   io-portability.h
   io-private.h
   io.c
   io.h
   macros.h
   Makefile.am
   misc-private.h
   misc.c
   mono-mutex.c
   mono-mutex.h
   mono-spinlock.h
   mutex-private.h
   mutexes.c
   mutexes.h
   process-private.h
   processes.c
   processes.h
   security.c
   security.h
   semaphore-private.h
   semaphores.c
   semaphores.h
   shared.c
   shared.h
   socket-private.h
   socket-wrappers.h
   sockets.c
   sockets.h
   status.h
   system.c
   system.h
   thread-private.h
   threads.c
   threads.h
   timefuncs-private.h
   timefuncs.c
   timefuncs.h
   types.h
   uglify.h
   versioninfo.h
   wait.c
   wait.h
   wapi-private.h
   wapi.h

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
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
/*
 * threads.c:  Thread handles
 *
 * Author:
 *	Dick Porter (dick@ximian.com)
 *
 * (C) 2002-2006 Ximian, Inc.
 */

#include <config.h>
#include <stdio.h>
#include <glib.h>
#include <string.h>
#include <mono/os/gc_wrapper.h>
#include <pthread.h>
#include <signal.h>
#include <sched.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

#include <mono/io-layer/wapi.h>
#include <mono/io-layer/wapi-private.h>
#include <mono/io-layer/handles-private.h>
#include <mono/io-layer/misc-private.h>
#include <mono/io-layer/mono-mutex.h>
#include <mono/io-layer/thread-private.h>
#include <mono/io-layer/mono-spinlock.h>
#include <mono/io-layer/mutex-private.h>

#if HAVE_VALGRIND_MEMCHECK_H
#include <valgrind/memcheck.h>
#endif

#undef DEBUG
#undef TLS_DEBUG

/* Hash threads with tids. I thought of using TLS for this, but that
 * would have to set the data in the new thread, which is more hassle
 */
static mono_once_t thread_hash_once = MONO_ONCE_INIT;
static pthread_key_t thread_hash_key;

/* This key is used with attached threads and a destructor to signal
 * when attached threads exit, as they don't have the thread_exit()
 * infrastructure
 */
static pthread_key_t thread_attached_key;

struct _WapiHandleOps _wapi_thread_ops = {
	NULL,				/* close */
	NULL,				/* signal */
	NULL,				/* own */
	NULL,				/* is_owned */
	NULL,				/* special_wait */
	NULL				/* prewait */
};

static mono_once_t thread_ops_once=MONO_ONCE_INIT;

static void thread_ops_init (void)
{
	_wapi_handle_register_capabilities (WAPI_HANDLE_THREAD,
					    WAPI_HANDLE_CAP_WAIT);
}

/* Called by thread_exit(), but maybe indirectly by
 * mono_thread_manage() via mono_thread_signal_self() too
 */
static void _wapi_thread_abandon_mutexes (gpointer handle)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	int i;
	pid_t pid = _wapi_getpid ();
	pthread_t tid = pthread_self ();
	
#ifdef DEBUG
	g_message ("%s: Thread %p abandoning held mutexes", __func__, handle);
#endif

	if (handle == NULL) {
		handle = _wapi_thread_handle_from_id (pthread_self ());
		if (handle == NULL) {
			/* Something gone badly wrong... */
			return;
		}
	}
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		return;
	}
	
	if (thread_handle->owner_pid != pid ||
	    !pthread_equal (thread_handle->id, tid)) {
		return;
	}
	
	for (i = 0; i < thread_handle->owned_mutexes->len; i++) {
		gpointer mutex = g_ptr_array_index (thread_handle->owned_mutexes, i);
		
		_wapi_mutex_abandon (mutex, pid, tid);
		_wapi_thread_disown_mutex (mutex);
	}
}

void _wapi_thread_set_termination_details (gpointer handle,
					   guint32 exitstatus)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	int thr_ret;
	
	if (_wapi_handle_issignalled (handle) ||
	    _wapi_handle_type (handle) == WAPI_HANDLE_UNUSED) {
		/* We must have already deliberately finished with
		 * this thread, so don't do any more now
		 */
		return;
	}

#ifdef DEBUG
	g_message ("%s: Thread %p terminating", __func__, handle);
#endif
	
	thr_ret = _wapi_handle_lock_shared_handles ();
	g_assert (thr_ret == 0);
	
	_wapi_thread_abandon_mutexes (handle);
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);

		_wapi_handle_unlock_shared_handles ();
		return;
	}
	
	thread_handle->exitstatus = exitstatus;
	thread_handle->state = THREAD_STATE_EXITED;
	MONO_SEM_DESTROY (&thread_handle->suspend_sem);
	g_ptr_array_free (thread_handle->owned_mutexes, TRUE);

	_wapi_shared_handle_set_signal_state (handle, TRUE);

	_wapi_handle_unlock_shared_handles ();
	
#ifdef DEBUG
	g_message("%s: Recording thread handle %p id %ld status as %d",
		  __func__, handle, thread_handle->id, exitstatus);
#endif
	
	/* The thread is no longer active, so unref it */
	_wapi_handle_unref (handle);
}

void _wapi_thread_signal_self (guint32 exitstatus)
{
	gpointer handle;
	
	handle = _wapi_thread_handle_from_id (pthread_self ());
	if (handle == NULL) {
		/* Something gone badly wrong... */
		return;
	}
	
	_wapi_thread_set_termination_details (handle, exitstatus);
}

/* Called by the thread creation code as a thread is finishing up, and
 * by ExitThread()
*/
static void thread_exit (guint32 exitstatus, gpointer handle) G_GNUC_NORETURN;
static void thread_exit (guint32 exitstatus, gpointer handle)
{
	_wapi_thread_set_termination_details (handle, exitstatus);
	
	/* Call pthread_exit() to call destructors and really exit the
	 * thread
	 */
	pthread_exit (NULL);
}

static void thread_attached_exit (gpointer handle)
{
	/* Drop the extra reference we take in thread_attach, now this
	 * thread is dead
	 */
	
	_wapi_thread_set_termination_details (handle, 0);
}

static void thread_hash_init(void)
{
	int thr_ret;
	
	thr_ret = pthread_key_create (&thread_hash_key, NULL);
	g_assert (thr_ret == 0);

	thr_ret = pthread_key_create (&thread_attached_key,
				      thread_attached_exit);
	g_assert (thr_ret == 0);
}

static void _wapi_thread_suspend (struct _WapiHandle_thread *thread)
{
	g_assert (thread->owner_pid == _wapi_getpid ());
	g_assert (pthread_equal (thread->id, pthread_self ()));
	
	while (MONO_SEM_WAIT (&thread->suspend_sem) != 0 &&
	       errno == EINTR);
}

static void _wapi_thread_resume (struct _WapiHandle_thread *thread)
{
	if (thread->owner_pid != _wapi_getpid ()) {
		return;
	}
	
	MONO_SEM_POST (&thread->suspend_sem);
}

static void *thread_start_routine (gpointer args) G_GNUC_NORETURN;
static void *thread_start_routine (gpointer args)
{
	struct _WapiHandle_thread *thread = (struct _WapiHandle_thread *)args;
	int thr_ret;
	
	thr_ret = pthread_detach (pthread_self ());
	g_assert (thr_ret == 0);

	thr_ret = pthread_setspecific (thread_hash_key,
				       (void *)thread->handle);
	g_assert (thr_ret == 0);

	thread->id = pthread_self();

#ifdef DEBUG
	g_message ("%s: started thread id %ld", __func__, thread->id);
#endif

	if (thread->create_flags & CREATE_SUSPENDED) {
		_wapi_thread_suspend (thread);
	}
	
	thread_exit (thread->start_routine (thread->start_arg),
		     thread->handle);

#ifndef __GNUC__
	/* Even though we tell gcc that this function doesn't return,
	 * other compilers won't see that.
	 */
	return(NULL);
#endif
}

/**
 * CreateThread:
 * @security: Ignored for now.
 * @stacksize: the size in bytes of the new thread's stack. Use 0 to
 * default to the normal stack size. (Ignored for now).
 * @start: The function that the new thread should start with
 * @param: The parameter to give to @start.
 * @create: If 0, the new thread is ready to run immediately.  If
 * %CREATE_SUSPENDED, the new thread will be in the suspended state,
 * requiring a ResumeThread() call to continue running.
 * @tid: If non-NULL, the ID of the new thread is stored here.  NB
 * this is defined as a DWORD (ie 32bit) in the MS API, but we need to
 * cope with 64 bit IDs for s390x and amd64.
 *
 * Creates a new threading handle.
 *
 * Return value: a new handle, or NULL
 */
gpointer CreateThread(WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 stacksize,
		      WapiThreadStart start, gpointer param, guint32 create,
		      gsize *tid) 
{
	struct _WapiHandle_thread thread_handle = {0}, *thread_handle_p;
	pthread_attr_t attr;
	gpointer handle;
	gboolean ok;
	int ret;
	int thr_ret;
	int i, unrefs = 0;
	gpointer ct_ret = NULL;
	
	mono_once (&thread_hash_once, thread_hash_init);
	mono_once (&thread_ops_once, thread_ops_init);
	
	if (start == NULL) {
		return(NULL);
	}

	thread_handle.state = THREAD_STATE_START;
	thread_handle.owner_pid = _wapi_getpid ();
	thread_handle.owned_mutexes = g_ptr_array_new ();
	thread_handle.create_flags = create;
	thread_handle.start_routine = start;
	thread_handle.start_arg = param;
	
	handle = _wapi_handle_new (WAPI_HANDLE_THREAD, &thread_handle);
	if (handle == _WAPI_HANDLE_INVALID) {
		g_warning ("%s: error creating thread handle", __func__);
		SetLastError (ERROR_GEN_FAILURE);
		
		return (NULL);
	}

	thr_ret = _wapi_handle_lock_shared_handles ();
	g_assert (thr_ret == 0);
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle_p);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		SetLastError (ERROR_GEN_FAILURE);
		
		goto cleanup;
	}

	/* Hold a reference while the thread is active, because we use
	 * the handle to store thread exit information
	 */
	_wapi_handle_ref (handle);
	
	/* Set a 2M stack size.  This is the default on Linux, but BSD
	 * needs it.  (The original bug report from Martin Dvorak <md@9ll.cz>
	 * set the size to 2M-4k.  I don't know why it's short by 4k, so
	 * I'm leaving it as 2M until I'm told differently.)
	 */
	thr_ret = pthread_attr_init(&attr);
	g_assert (thr_ret == 0);
	
	/* defaults of 2Mb for 32bits and 4Mb for 64bits */
	/* temporarily changed to use 1 MB: this allows more threads
	 * to be used, as well as using less virtual memory and so
	 * more is available for the GC heap.
	 */
	if (stacksize == 0){
#if HAVE_VALGRIND_MEMCHECK_H
		if (RUNNING_ON_VALGRIND) {
			stacksize = 1 << 20;
		} else {
			stacksize = (SIZEOF_VOID_P / 4) * 1024 * 1024;
		}
#else
		stacksize = (SIZEOF_VOID_P / 4) * 1024 * 1024;
#endif
	}

#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
	thr_ret = pthread_attr_setstacksize(&attr, stacksize);
	g_assert (thr_ret == 0);
#endif

	MONO_SEM_INIT (&thread_handle_p->suspend_sem, 0);
	thread_handle_p->handle = handle;
	
	ret = pthread_create (&thread_handle_p->id, &attr,
			      thread_start_routine, (void *)thread_handle_p);
	if (ret != 0) {
#ifdef DEBUG
		g_message ("%s: Thread create error: %s", __func__,
			   strerror(ret));
#endif

		/* Two, because of the reference we took above */
		unrefs = 2;
		
		goto cleanup;
	}
	ct_ret = handle;
	
#ifdef DEBUG
	g_message("%s: Started thread handle %p ID %ld", __func__, handle,
		  thread_handle_p->id);
#endif
	
	if (tid != NULL) {
#ifdef PTHREAD_POINTER_ID
		/* Don't use GPOINTER_TO_UINT here, it can't cope with
		 * sizeof(void *) > sizeof(uint) when a cast to uint
		 * would overflow
		 */
		*tid = (gsize)(thread_handle_p->id);
#else
		*tid = thread_handle_p->id;
#endif
	}

cleanup:
	_wapi_handle_unlock_shared_handles ();
	
	/* Must not call _wapi_handle_unref() with the shared handles
	 * already locked
	 */
	for (i = 0; i < unrefs; i++) {
		_wapi_handle_unref (handle);
	}
	
	return(ct_ret);
}

/* The only time this function is called when tid != pthread_self ()
 * is from OpenThread (), so we can fast-path most cases by just
 * looking up the handle in TLS.  OpenThread () must cope with a NULL
 * return and do a handle search in that case.
 */
gpointer _wapi_thread_handle_from_id (pthread_t tid)
{
	gpointer ret;

	if (pthread_equal (tid, pthread_self ()) &&
	    (ret = pthread_getspecific (thread_hash_key)) != NULL) {
		/* We know the handle */

#ifdef DEBUG
		g_message ("%s: Returning %p for self thread %ld from TLS",
			   __func__, ret, tid);
#endif
		
		return(ret);
	}
	
#ifdef DEBUG
	g_message ("%s: Returning NULL for unknown or non-self thread %ld",
		   __func__, tid);
#endif
		

	return(NULL);
}

static gboolean find_thread_by_id (gpointer handle, gpointer user_data)
{
	pthread_t tid = (pthread_t)user_data;
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	
	/* Ignore threads that have already exited (ie they are signalled) */
	if (_wapi_handle_issignalled (handle) == FALSE) {
		ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
					  (gpointer *)&thread_handle);
		if (ok == FALSE) {
			/* It's possible that the handle has vanished
			 * during the _wapi_search_handle before it
			 * gets here, so don't spam the console with
			 * warnings.
			 */
			return(FALSE);
		}
		
#ifdef DEBUG
		g_message ("%s: looking at thread %ld from process %d", __func__, thread_handle->id, thread_handle->owner_pid);
#endif

		if (thread_handle->owner_pid != _wapi_getpid ()) {
			/* Not sure if ms has this limitation with
			 * OpenThread(), but pthreads IDs are not
			 * unique across processes
			 */
#ifdef DEBUG
			g_message ("%s: not this process", __func__);
#endif
			return(FALSE);
		}
		
		if (pthread_equal (thread_handle->id, tid)) {
#ifdef DEBUG
			g_message ("%s: found the thread we are looking for",
				   __func__);
#endif
			return(TRUE);
		}
	}
	
#ifdef DEBUG
	g_message ("%s: not found %ld, returning FALSE", __func__, tid);
#endif
	
	return(FALSE);
}

/* NB tid is 32bit in MS API, but we need 64bit on amd64 and s390x
 * (and probably others)
 */
gpointer OpenThread (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, gsize tid)
{
	gpointer ret=NULL;
	
	mono_once (&thread_hash_once, thread_hash_init);
	mono_once (&thread_ops_once, thread_ops_init);
	
#ifdef DEBUG
	g_message ("%s: looking up thread %"G_GSIZE_FORMAT, __func__, tid);
#endif

	ret = _wapi_thread_handle_from_id ((pthread_t)tid);
	if (ret == NULL) {
		/* We need to search for this thread */
		ret = _wapi_search_handle (WAPI_HANDLE_THREAD, find_thread_by_id, (gpointer)tid, NULL, TRUE);	/* FIXME: have a proper look at this, me might not need to set search_shared = TRUE */
	} else {
		/* if _wapi_search_handle() returns a found handle, it
		 * refs it itself
		 */
		_wapi_handle_ref (ret);
	}
	
#ifdef DEBUG
	g_message ("%s: returning thread handle %p", __func__, ret);
#endif
	
	return(ret);
}

/**
 * ExitThread:
 * @exitcode: Sets the thread's exit code, which can be read from
 * another thread with GetExitCodeThread().
 *
 * Terminates the calling thread.  A thread can also exit by returning
 * from its start function. When the last thread in a process
 * terminates, the process itself terminates.
 */
void ExitThread(guint32 exitcode)
{
	gpointer thread = _wapi_thread_handle_from_id (pthread_self ());
	
	if (thread != NULL) {
		thread_exit(exitcode, thread);
	} else {
		/* Just blow this thread away */
		pthread_exit (NULL);
	}
}

/**
 * GetExitCodeThread:
 * @handle: The thread handle to query
 * @exitcode: The thread @handle exit code is stored here
 *
 * Finds the exit code of @handle, and stores it in @exitcode.  If the
 * thread @handle is still running, the value stored is %STILL_ACTIVE.
 *
 * Return value: %TRUE, or %FALSE on error.
 */
gboolean GetExitCodeThread(gpointer handle, guint32 *exitcode)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		return (FALSE);
	}
	
#ifdef DEBUG
	g_message ("%s: Finding exit status for thread handle %p id %ld",
		   __func__, handle, thread_handle->id);
#endif

	if (exitcode == NULL) {
#ifdef DEBUG
		g_message ("%s: Nowhere to store exit code", __func__);
#endif
		return(FALSE);
	}
	
	if (thread_handle->state != THREAD_STATE_EXITED) {
#ifdef DEBUG
		g_message ("%s: Thread still active (state %d, exited is %d)",
			   __func__, thread_handle->state,
			   THREAD_STATE_EXITED);
#endif
		*exitcode = STILL_ACTIVE;
		return(TRUE);
	}
	
	*exitcode = thread_handle->exitstatus;
	
	return(TRUE);
}

/**
 * GetCurrentThreadId:
 *
 * Looks up the thread ID of the current thread.  This ID can be
 * passed to OpenThread() to create a new handle on this thread.
 *
 * Return value: the thread ID.  NB this is defined as DWORD (ie 32
 * bit) in the MS API, but we need to cope with 64 bit IDs for s390x
 * and amd64.  This doesn't really break the API, it just embraces and
 * extends it on 64bit platforms :)
 */
gsize GetCurrentThreadId(void)
{
	pthread_t tid = pthread_self();
	
#ifdef PTHREAD_POINTER_ID
	/* Don't use GPOINTER_TO_UINT here, it can't cope with
	 * sizeof(void *) > sizeof(uint) when a cast to uint would
	 * overflow
	 */
	return((gsize)tid);
#else
	return(tid);
#endif
}

static gpointer thread_attach(gsize *tid)
{
	struct _WapiHandle_thread thread_handle = {0}, *thread_handle_p;
	gpointer handle;
	gboolean ok;
	int thr_ret;
	
	mono_once (&thread_hash_once, thread_hash_init);
	mono_once (&thread_ops_once, thread_ops_init);

	thread_handle.state = THREAD_STATE_START;
	thread_handle.owner_pid = _wapi_getpid ();
	thread_handle.owned_mutexes = g_ptr_array_new ();

	handle = _wapi_handle_new (WAPI_HANDLE_THREAD, &thread_handle);
	if (handle == _WAPI_HANDLE_INVALID) {
		g_warning ("%s: error creating thread handle", __func__);
		
		SetLastError (ERROR_GEN_FAILURE);
		return (NULL);
	}

	thr_ret = _wapi_handle_lock_shared_handles ();
	g_assert (thr_ret == 0);
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle_p);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		
		SetLastError (ERROR_GEN_FAILURE);
		goto cleanup;
	}

	/* Hold a reference while the thread is active, because we use
	 * the handle to store thread exit information
	 */
	_wapi_handle_ref (handle);

	/* suspend_sem is not used for attached threads, but
	 * thread_exit() might try to destroy it
	 */
	MONO_SEM_INIT (&thread_handle_p->suspend_sem, 0);
	thread_handle_p->handle = handle;
	thread_handle_p->id = pthread_self ();

	thr_ret = pthread_setspecific (thread_hash_key, (void *)handle);
	g_assert (thr_ret == 0);

	thr_ret = pthread_setspecific (thread_attached_key, (void *)handle);
	g_assert (thr_ret == 0);
	
#ifdef DEBUG
	g_message("%s: Attached thread handle %p ID %ld", __func__, handle,
		  thread_handle_p->id);
#endif

	if (tid != NULL) {
#ifdef PTHREAD_POINTER_ID
		/* Don't use GPOINTER_TO_UINT here, it can't cope with
		 * sizeof(void *) > sizeof(uint) when a cast to uint
		 * would overflow
		 */
		*tid = (gsize)(thread_handle_p->id);
#else
		*tid = thread_handle_p->id;
#endif
	}

cleanup:
	_wapi_handle_unlock_shared_handles ();
	
	return(handle);
}

gpointer _wapi_thread_duplicate ()
{
	gpointer ret = NULL;
	
	mono_once (&thread_hash_once, thread_hash_init);
	mono_once (&thread_ops_once, thread_ops_init);
	
	ret = _wapi_thread_handle_from_id (pthread_self ());
	if (!ret) {
		ret = thread_attach (NULL);
	} else {
		_wapi_handle_ref (ret);
	}
	
	return(ret);
}

/**
 * GetCurrentThread:
 *
 * Looks up the handle associated with the current thread.  Under
 * Windows this is a pseudohandle, and must be duplicated with
 * DuplicateHandle() for some operations.
 *
 * Return value: The current thread handle, or %NULL on failure.
 * (Unknown whether Windows has a possible failure here.  It may be
 * necessary to implement the pseudohandle-constant behaviour).
 */
gpointer GetCurrentThread(void)
{
	mono_once(&thread_hash_once, thread_hash_init);
	mono_once (&thread_ops_once, thread_ops_init);
	
	return(_WAPI_THREAD_CURRENT);
}

/**
 * ResumeThread:
 * @handle: the thread handle to resume
 *
 * Decrements the suspend count of thread @handle. A thread can only
 * run if its suspend count is zero.
 *
 * Return value: the previous suspend count, or 0xFFFFFFFF on error.
 */
guint32 ResumeThread(gpointer handle)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		
		return (0xFFFFFFFF);
	}

	/* This is still a kludge that only copes with starting a
	 * thread that was suspended on create, so don't bother with
	 * the suspend count crap yet
	 */
	_wapi_thread_resume (thread_handle);
	return(0xFFFFFFFF);
}

/**
 * SuspendThread:
 * @handle: the thread handle to suspend
 *
 * Increments the suspend count of thread @handle. A thread can only
 * run if its suspend count is zero.
 *
 * Return value: the previous suspend count, or 0xFFFFFFFF on error.
 */
guint32 SuspendThread(gpointer handle)
{
	return(0xFFFFFFFF);
}

/*
 * We assume here that TLS_MINIMUM_AVAILABLE is less than
 * PTHREAD_KEYS_MAX, allowing enough overhead for a few TLS keys for
 * library usage.
 *
 * Currently TLS_MINIMUM_AVAILABLE is 64 and _POSIX_THREAD_KEYS_MAX
 * (the minimum value for PTHREAD_KEYS_MAX) is 128, so we should be
 * fine.
 */

static pthread_key_t TLS_keys[TLS_MINIMUM_AVAILABLE];
static gboolean TLS_used[TLS_MINIMUM_AVAILABLE]={FALSE};
static guint32 TLS_spinlock=0;

guint32
mono_pthread_key_for_tls (guint32 idx)
{
	return (guint32)TLS_keys [idx];
}

/**
 * TlsAlloc:
 *
 * Allocates a Thread Local Storage (TLS) index.  Any thread in the
 * same process can use this index to store and retrieve values that
 * are local to that thread.
 *
 * Return value: The index value, or %TLS_OUT_OF_INDEXES if no index
 * is available.
 */
guint32 TlsAlloc(void)
{
	guint32 i;
	int thr_ret;
	
	MONO_SPIN_LOCK (TLS_spinlock);
	
	for(i=0; i<TLS_MINIMUM_AVAILABLE; i++) {
		if(TLS_used[i]==FALSE) {
			TLS_used[i]=TRUE;
			thr_ret = pthread_key_create(&TLS_keys[i], NULL);
			g_assert (thr_ret == 0);

			MONO_SPIN_UNLOCK (TLS_spinlock);
	
#ifdef TLS_DEBUG
			g_message ("%s: returning key %d", __func__, i);
#endif
			
			return(i);
		}
	}

	MONO_SPIN_UNLOCK (TLS_spinlock);
	
#ifdef TLS_DEBUG
	g_message ("%s: out of indices", __func__);
#endif
			
	
	return(TLS_OUT_OF_INDEXES);
}

#define MAKE_GC_ID(idx) (GUINT_TO_POINTER((idx)|(GetCurrentThreadId()<<8)))

/**
 * TlsFree:
 * @idx: The TLS index to free
 *
 * Releases a TLS index, making it available for reuse.  This call
 * will delete any TLS data stored under index @idx in all threads.
 *
 * Return value: %TRUE on success, %FALSE otherwise.
 */
gboolean TlsFree(guint32 idx)
{
	int thr_ret;
	
#ifdef TLS_DEBUG
	g_message ("%s: freeing key %d", __func__, idx);
#endif

	MONO_SPIN_LOCK (TLS_spinlock);
	
	if(TLS_used[idx]==FALSE) {
		MONO_SPIN_UNLOCK (TLS_spinlock);

		return(FALSE);
	}
	
	TLS_used[idx]=FALSE;
	thr_ret = pthread_key_delete(TLS_keys[idx]);
	g_assert (thr_ret == 0);
	
	MONO_SPIN_UNLOCK (TLS_spinlock);
	
	return(TRUE);
}

/**
 * TlsGetValue:
 * @idx: The TLS index to retrieve
 *
 * Retrieves the TLS data stored under index @idx.
 *
 * Return value: The value stored in the TLS index @idx in the current
 * thread, or %NULL on error.  As %NULL can be a valid return value,
 * in this case GetLastError() returns %ERROR_SUCCESS.
 */
gpointer TlsGetValue(guint32 idx)
{
	gpointer ret;
	
#ifdef TLS_DEBUG
	g_message ("%s: looking up key %d", __func__, idx);
#endif
	
	ret=pthread_getspecific(TLS_keys[idx]);

#ifdef TLS_DEBUG
	g_message ("%s: returning %p", __func__, ret);
#endif
	
	return(ret);
}

/**
 * TlsSetValue:
 * @idx: The TLS index to store
 * @value: The value to store under index @idx
 *
 * Stores @value at TLS index @idx.
 *
 * Return value: %TRUE on success, %FALSE otherwise.
 */
gboolean TlsSetValue(guint32 idx, gpointer value)
{
	int ret;

#ifdef TLS_DEBUG
	g_message ("%s: setting key %d to %p", __func__, idx, value);
#endif
	
	MONO_SPIN_LOCK (TLS_spinlock);
	
	if(TLS_used[idx]==FALSE) {
#ifdef TLS_DEBUG
		g_message ("%s: key %d unused", __func__, idx);
#endif

		MONO_SPIN_UNLOCK (TLS_spinlock);

		return(FALSE);
	}
	
	ret=pthread_setspecific(TLS_keys[idx], value);
	if(ret!=0) {
#ifdef TLS_DEBUG
		g_message ("%s: pthread_setspecific error: %s", __func__,
			   strerror (ret));
#endif

		MONO_SPIN_UNLOCK (TLS_spinlock);

		return(FALSE);
	}
	
	MONO_SPIN_UNLOCK (TLS_spinlock);
	
	return(TRUE);
}

/**
 * SleepEx:
 * @ms: The time in milliseconds to suspend for
 * @alertable: if TRUE, the wait can be interrupted by an APC call
 *
 * Suspends execution of the current thread for @ms milliseconds.  A
 * value of zero causes the thread to relinquish its time slice.  A
 * value of %INFINITE causes an infinite delay.
 */
guint32 SleepEx(guint32 ms, gboolean alertable)
{
	struct timespec req, rem;
	int ms_quot, ms_rem;
	int ret;
	gpointer current_thread = NULL;
	
#ifdef DEBUG
	g_message("%s: Sleeping for %d ms", __func__, ms);
#endif

	if (alertable) {
		current_thread = _wapi_thread_handle_from_id (pthread_self ());
		if (current_thread == NULL) {
			SetLastError (ERROR_INVALID_HANDLE);
			return(WAIT_FAILED);
		}
		
		if (_wapi_thread_apc_pending (current_thread)) {
			_wapi_thread_dispatch_apc_queue (current_thread);
			return WAIT_IO_COMPLETION;
		}
	}
	
	if(ms==0) {
		sched_yield();
		return 0;
	}
	
	/* FIXME: check for INFINITE and sleep forever */
	ms_quot = ms / 1000;
	ms_rem = ms % 1000;
	
	req.tv_sec=ms_quot;
	req.tv_nsec=ms_rem*1000000;
	
again:
	ret=nanosleep(&req, &rem);

	if (alertable && _wapi_thread_apc_pending (current_thread)) {
		_wapi_thread_dispatch_apc_queue (current_thread);
		return WAIT_IO_COMPLETION;
	}
	
	if(ret==-1) {
		/* Sleep interrupted with rem time remaining */
#ifdef DEBUG
		guint32 rems=rem.tv_sec*1000 + rem.tv_nsec/1000000;
		
		g_message("%s: Still got %d ms to go", __func__, rems);
#endif
		req=rem;
		goto again;
	}

	return 0;
}

void Sleep(guint32 ms)
{
	SleepEx(ms, FALSE);
}

static mono_mutex_t apc_mutex = MONO_MUTEX_INITIALIZER;

gboolean _wapi_thread_cur_apc_pending (void)
{
	gpointer thread = _wapi_thread_handle_from_id (pthread_self ());
	
	if (thread == NULL) {
		SetLastError (ERROR_INVALID_HANDLE);
		return(FALSE);
	}
	
	return(_wapi_thread_apc_pending (thread));
}

static void _wapi_thread_queue_apc (struct _WapiHandle_thread *thread,
				    guint32 (*apc_callback)(gpointer),
				    gpointer param)
{
	ApcInfo *apc;
	int thr_ret;
	
	if (thread->owner_pid != _wapi_getpid ()) {
		return;
	}

	apc = (ApcInfo *)g_new (ApcInfo, 1);
	apc->callback = apc_callback;
	apc->param = param;
	
	pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
			      (void *)&apc_mutex);
	thr_ret = mono_mutex_lock (&apc_mutex);
	g_assert (thr_ret == 0);
	
	thread->apc_queue = g_slist_append (thread->apc_queue, apc);
	
	thr_ret = mono_mutex_unlock (&apc_mutex);
	g_assert (thr_ret == 0);
	pthread_cleanup_pop (0);
}

gboolean _wapi_thread_apc_pending (gpointer handle)
{
	struct _WapiHandle_thread *thread;
	gboolean ok;
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread);
	if (ok == FALSE) {
#ifdef DEBUG
		/* This might happen at process shutdown, as all
		 * thread handles are forcibly closed.  If a thread
		 * still has an alertable wait the final
		 * _wapi_thread_apc_pending check will probably fail
		 * to find the handle
		 */
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
#endif
		return (FALSE);
	}
	
	if (thread->owner_pid != _wapi_getpid ()) {
		return(FALSE);
	}
	
	return(thread->apc_queue != NULL);
}

gboolean _wapi_thread_dispatch_apc_queue (gpointer handle)
{
	struct _WapiHandle_thread *thread;
	gboolean ok;
	ApcInfo *apc;
	GSList *list;
	int thr_ret;
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		return (FALSE);
	}
	
	if (thread->owner_pid != _wapi_getpid ()) {
		return(FALSE);
	}
	
	pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
			      (void *)&apc_mutex);
	thr_ret = mono_mutex_lock (&apc_mutex);
	g_assert (thr_ret == 0);
	
	list = thread->apc_queue;
	thread->apc_queue = NULL;
	
	thr_ret = mono_mutex_unlock (&apc_mutex);
	g_assert (thr_ret == 0);
	pthread_cleanup_pop (0);

	while (list != NULL) {
		apc = (ApcInfo *)list->data;
		apc->callback (apc->param);
		g_free (apc);
		list = g_slist_next (list);
	}
	g_slist_free (list);
	
	return(TRUE);
}

guint32 QueueUserAPC (WapiApcProc apc_callback, gpointer handle, 
		      gpointer param)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   handle);
		return (0);
	}
	
	_wapi_thread_queue_apc (thread_handle, apc_callback, param);
	return(1);
}

void _wapi_thread_own_mutex (gpointer mutex)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	gpointer thread;
	
	thread = _wapi_thread_handle_from_id (pthread_self ());
	if (thread == NULL) {
		g_warning ("%s: error looking up thread by ID", __func__);
		return;
	}

	ok = _wapi_lookup_handle (thread, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   thread);
		return;
	}

	_wapi_handle_ref (mutex);
	
	g_ptr_array_add (thread_handle->owned_mutexes, mutex);
}

void _wapi_thread_disown_mutex (gpointer mutex)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	gpointer thread;

	thread = _wapi_thread_handle_from_id (pthread_self ());
	if (thread == NULL) {
		g_warning ("%s: error looking up thread by ID", __func__);
		return;
	}

	ok = _wapi_lookup_handle (thread, WAPI_HANDLE_THREAD,
				  (gpointer *)&thread_handle);
	if (ok == FALSE) {
		g_warning ("%s: error looking up thread handle %p", __func__,
			   thread);
		return;
	}

	_wapi_handle_unref (mutex);
	
	g_ptr_array_remove (thread_handle->owned_mutexes, mutex);
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us