/
threads.c
4311 lines (3513 loc) · 115 KB
/
threads.c
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
/*
* threads.c: Thread support internal calls
*
* Author:
* Dick Porter (dick@ximian.com)
* Paolo Molaro (lupus@ximian.com)
* Patrik Torstensson (patrik.torstensson@labs2.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*/
#include <config.h>
#include <glib.h>
#include <signal.h>
#include <string.h>
#if defined(__OpenBSD__)
#include <pthread.h>
#include <pthread_np.h>
#endif
#include <mono/metadata/object.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/threadpool.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/monitor.h>
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/marshal.h>
#include <mono/io-layer/io-layer.h>
#ifndef HOST_WIN32
#include <mono/io-layer/threads.h>
#endif
#include <mono/metadata/object-internals.h>
#include <mono/metadata/mono-debug-debugger.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-membar.h>
#include <mono/utils/mono-time.h>
#include <mono/metadata/gc-internal.h>
/*#define THREAD_DEBUG(a) do { a; } while (0)*/
#define THREAD_DEBUG(a)
/*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
#define THREAD_WAIT_DEBUG(a)
/*#define LIBGC_DEBUG(a) do { a; } while (0)*/
#define LIBGC_DEBUG(a)
#define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
#define SPIN_LOCK(i) do { \
if (SPIN_TRYLOCK (i)) \
break; \
} while (1)
#define SPIN_UNLOCK(i) i = 0
/* Provide this for systems with glib < 2.6 */
#ifndef G_GSIZE_FORMAT
# if GLIB_SIZEOF_LONG == 8
# define G_GSIZE_FORMAT "lu"
# else
# define G_GSIZE_FORMAT "u"
# endif
#endif
struct StartInfo
{
guint32 (*func)(void *);
MonoThread *obj;
MonoObject *delegate;
void *start_arg;
};
typedef union {
gint32 ival;
gfloat fval;
} IntFloatUnion;
typedef union {
gint64 ival;
gdouble fval;
} LongDoubleUnion;
typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
struct _MonoThreadDomainTls {
MonoThreadDomainTls *next;
guint32 offset;
guint32 size;
};
typedef struct {
int idx;
int offset;
MonoThreadDomainTls *freelist;
} StaticDataInfo;
typedef struct {
gpointer p;
MonoHazardousFreeFunc free_func;
} DelayedFreeItem;
/* Number of cached culture objects in the MonoThread->cached_culture_info array
* (per-type): we use the first NUM entries for CultureInfo and the last for
* UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
*/
#define NUM_CACHED_CULTURES 4
#define CULTURES_START_IDX 0
#define UICULTURES_START_IDX NUM_CACHED_CULTURES
/* Controls access to the 'threads' hash table */
#define mono_threads_lock() EnterCriticalSection (&threads_mutex)
#define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
static CRITICAL_SECTION threads_mutex;
/* Controls access to context static data */
#define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
#define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
static CRITICAL_SECTION contexts_mutex;
/* Holds current status of static data heap */
static StaticDataInfo thread_static_info;
static StaticDataInfo context_static_info;
/* The hash of existing threads (key is thread ID, value is
* MonoInternalThread*) that need joining before exit
*/
static MonoGHashTable *threads=NULL;
/*
* Threads which are starting up and they are not in the 'threads' hash yet.
* When handle_store is called for a thread, it will be removed from this hash table.
* Protected by mono_threads_lock ().
*/
static MonoGHashTable *threads_starting_up = NULL;
/* Maps a MonoThread to its start argument */
/* Protected by mono_threads_lock () */
static MonoGHashTable *thread_start_args = NULL;
/* The TLS key that holds the MonoObject assigned to each thread */
static guint32 current_object_key = -1;
#ifdef HAVE_KW_THREAD
/* we need to use both the Tls* functions and __thread because
* the gc needs to see all the threads
*/
static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
#define SET_CURRENT_OBJECT(x) do { \
tls_current_object = x; \
TlsSetValue (current_object_key, x); \
} while (FALSE)
#define GET_CURRENT_OBJECT() tls_current_object
#else
#define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
#define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
#endif
/* function called at thread start */
static MonoThreadStartCB mono_thread_start_cb = NULL;
/* function called at thread attach */
static MonoThreadAttachCB mono_thread_attach_cb = NULL;
/* function called at thread cleanup */
static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
/* function called to notify the runtime about a pending exception on the current thread */
static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
/* The default stack size for each thread */
static guint32 default_stacksize = 0;
#define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
static void thread_adjust_static_data (MonoInternalThread *thread);
static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
static void mono_init_static_data_info (StaticDataInfo *static_data);
static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
static gboolean mono_thread_resume (MonoInternalThread* thread);
static void mono_thread_start (MonoThread *thread);
static void signal_thread_state_change (MonoInternalThread *thread);
static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
/* Spin lock for InterlockedXXX 64 bit functions */
#define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
#define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
static CRITICAL_SECTION interlocked_mutex;
/* global count of thread interruptions requested */
static gint32 thread_interruption_requested = 0;
/* Event signaled when a thread changes its background mode */
static HANDLE background_change_event;
/* The table for small ID assignment */
static CRITICAL_SECTION small_id_mutex;
static int small_id_table_size = 0;
static int small_id_next = 0;
static int highest_small_id = -1;
static MonoInternalThread **small_id_table = NULL;
/* The hazard table */
#if MONO_SMALL_CONFIG
#define HAZARD_TABLE_MAX_SIZE 256
#else
#define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
#endif
static volatile int hazard_table_size = 0;
static MonoThreadHazardPointers * volatile hazard_table = NULL;
/* The table where we keep pointers to blocks to be freed but that
have to wait because they're guarded by a hazard pointer. */
static CRITICAL_SECTION delayed_free_table_mutex;
static GArray *delayed_free_table = NULL;
static gboolean shutting_down = FALSE;
guint32
mono_thread_get_tls_key (void)
{
return current_object_key;
}
gint32
mono_thread_get_tls_offset (void)
{
int offset;
MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
return offset;
}
/* handle_store() and handle_remove() manage the array of threads that
* still need to be waited for when the main thread exits.
*
* If handle_store() returns FALSE the thread must not be started
* because Mono is shutting down.
*/
static gboolean handle_store(MonoThread *thread)
{
mono_threads_lock ();
THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
if (threads_starting_up)
mono_g_hash_table_remove (threads_starting_up, thread);
if (shutting_down) {
mono_threads_unlock ();
return FALSE;
}
if(threads==NULL) {
MONO_GC_REGISTER_ROOT (threads);
threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
}
/* We don't need to duplicate thread->handle, because it is
* only closed when the thread object is finalized by the GC.
*/
g_assert (thread->internal_thread);
mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
thread->internal_thread);
mono_threads_unlock ();
return TRUE;
}
static gboolean handle_remove(MonoInternalThread *thread)
{
gboolean ret;
gsize tid = thread->tid;
THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
mono_threads_lock ();
if (threads) {
/* We have to check whether the thread object for the
* tid is still the same in the table because the
* thread might have been destroyed and the tid reused
* in the meantime, in which case the tid would be in
* the table, but with another thread object.
*/
if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
mono_g_hash_table_remove (threads, (gpointer)tid);
ret = TRUE;
} else {
ret = FALSE;
}
}
else
ret = FALSE;
mono_threads_unlock ();
/* Don't close the handle here, wait for the object finalizer
* to do it. Otherwise, the following race condition applies:
*
* 1) Thread exits (and handle_remove() closes the handle)
*
* 2) Some other handle is reassigned the same slot
*
* 3) Another thread tries to join the first thread, and
* blocks waiting for the reassigned handle to be signalled
* (which might never happen). This is possible, because the
* thread calling Join() still has a reference to the first
* thread's object.
*/
return ret;
}
/*
* Allocate a small thread id.
*
* FIXME: The biggest part of this function is very similar to
* domain_id_alloc() in domain.c and should be merged.
*/
static int
small_id_alloc (MonoInternalThread *thread)
{
int id = -1, i;
EnterCriticalSection (&small_id_mutex);
if (!small_id_table) {
small_id_table_size = 2;
small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
}
for (i = small_id_next; i < small_id_table_size; ++i) {
if (!small_id_table [i]) {
id = i;
break;
}
}
if (id == -1) {
for (i = 0; i < small_id_next; ++i) {
if (!small_id_table [i]) {
id = i;
break;
}
}
}
if (id == -1) {
MonoInternalThread **new_table;
int new_size = small_id_table_size * 2;
if (new_size >= (1 << 16))
g_assert_not_reached ();
id = small_id_table_size;
new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
mono_gc_free_fixed (small_id_table);
small_id_table = new_table;
small_id_table_size = new_size;
}
thread->small_id = id;
g_assert (small_id_table [id] == NULL);
small_id_table [id] = thread;
small_id_next++;
if (small_id_next > small_id_table_size)
small_id_next = 0;
g_assert (id < HAZARD_TABLE_MAX_SIZE);
if (id >= hazard_table_size) {
#if MONO_SMALL_CONFIG
hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
hazard_table_size = HAZARD_TABLE_MAX_SIZE;
#else
gpointer page_addr;
int pagesize = mono_pagesize ();
int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
if (hazard_table == NULL) {
hazard_table = mono_valloc (NULL,
sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
MONO_MMAP_NONE);
}
g_assert (hazard_table != NULL);
page_addr = (guint8*)hazard_table + num_pages * pagesize;
mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
++num_pages;
hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
#endif
g_assert (id < hazard_table_size);
hazard_table [id].hazard_pointers [0] = NULL;
hazard_table [id].hazard_pointers [1] = NULL;
}
if (id > highest_small_id) {
highest_small_id = id;
mono_memory_write_barrier ();
}
LeaveCriticalSection (&small_id_mutex);
return id;
}
static void
small_id_free (int id)
{
g_assert (id >= 0 && id < small_id_table_size);
g_assert (small_id_table [id] != NULL);
small_id_table [id] = NULL;
}
static gboolean
is_pointer_hazardous (gpointer p)
{
int i;
int highest = highest_small_id;
g_assert (highest < hazard_table_size);
for (i = 0; i <= highest; ++i) {
if (hazard_table [i].hazard_pointers [0] == p
|| hazard_table [i].hazard_pointers [1] == p)
return TRUE;
}
return FALSE;
}
MonoThreadHazardPointers*
mono_hazard_pointer_get (void)
{
MonoInternalThread *current_thread = mono_thread_internal_current ();
if (!(current_thread && current_thread->small_id >= 0)) {
static MonoThreadHazardPointers emerg_hazard_table;
g_warning ("Thread %p may have been prematurely finalized", current_thread);
return &emerg_hazard_table;
}
return &hazard_table [current_thread->small_id];
}
static void
try_free_delayed_free_item (int index)
{
if (delayed_free_table->len > index) {
DelayedFreeItem item = { NULL, NULL };
EnterCriticalSection (&delayed_free_table_mutex);
/* We have to check the length again because another
thread might have freed an item before we acquired
the lock. */
if (delayed_free_table->len > index) {
item = g_array_index (delayed_free_table, DelayedFreeItem, index);
if (!is_pointer_hazardous (item.p))
g_array_remove_index_fast (delayed_free_table, index);
else
item.p = NULL;
}
LeaveCriticalSection (&delayed_free_table_mutex);
if (item.p != NULL)
item.free_func (item.p);
}
}
void
mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
{
int i;
/* First try to free a few entries in the delayed free
table. */
for (i = 2; i >= 0; --i)
try_free_delayed_free_item (i);
/* Now see if the pointer we're freeing is hazardous. If it
isn't, free it. Otherwise put it in the delay list. */
if (is_pointer_hazardous (p)) {
DelayedFreeItem item = { p, free_func };
++mono_stats.hazardous_pointer_count;
EnterCriticalSection (&delayed_free_table_mutex);
g_array_append_val (delayed_free_table, item);
LeaveCriticalSection (&delayed_free_table_mutex);
} else
free_func (p);
}
void
mono_thread_hazardous_try_free_all (void)
{
int len;
int i;
if (!delayed_free_table)
return;
len = delayed_free_table->len;
for (i = len - 1; i >= 0; --i)
try_free_delayed_free_item (i);
}
static void ensure_synch_cs_set (MonoInternalThread *thread)
{
CRITICAL_SECTION *synch_cs;
if (thread->synch_cs != NULL) {
return;
}
synch_cs = g_new0 (CRITICAL_SECTION, 1);
InitializeCriticalSection (synch_cs);
if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
synch_cs, NULL) != NULL) {
/* Another thread must have installed this CS */
DeleteCriticalSection (synch_cs);
g_free (synch_cs);
}
}
/*
* NOTE: this function can be called also for threads different from the current one:
* make sure no code called from it will ever assume it is run on the thread that is
* getting cleaned up.
*/
static void thread_cleanup (MonoInternalThread *thread)
{
g_assert (thread != NULL);
if (thread->abort_state_handle) {
mono_gchandle_free (thread->abort_state_handle);
thread->abort_state_handle = 0;
}
thread->abort_exc = NULL;
thread->current_appcontext = NULL;
/*
* This is necessary because otherwise we might have
* cross-domain references which will not get cleaned up when
* the target domain is unloaded.
*/
if (thread->cached_culture_info) {
int i;
for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
}
/* if the thread is not in the hash it has been removed already */
if (!handle_remove (thread))
return;
mono_release_type_locks (thread);
EnterCriticalSection (thread->synch_cs);
thread->state |= ThreadState_Stopped;
thread->state &= ~ThreadState_Background;
LeaveCriticalSection (thread->synch_cs);
mono_profiler_thread_end (thread->tid);
if (thread == mono_thread_internal_current ())
mono_thread_pop_appdomain_ref ();
thread->cached_culture_info = NULL;
mono_free_static_data (thread->static_data, TRUE);
thread->static_data = NULL;
/*
* FIXME: The check for shutting_down here is a kludge and
* should be removed. The reason we need it here is because
* mono_thread_manage() does not wait for finalizer threads,
* so we might still be at this point in a finalizer thread
* after the main thread has cleared the root domain, so
* thread could have been zeroed out.
*/
if (mono_thread_cleanup_fn && !shutting_down)
mono_thread_cleanup_fn (thread->root_domain_thread);
small_id_free (thread->small_id);
thread->small_id = -2;
}
static gpointer
get_thread_static_data (MonoInternalThread *thread, guint32 offset)
{
int idx;
g_assert ((offset & 0x80000000) == 0);
offset &= 0x7fffffff;
idx = (offset >> 24) - 1;
return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
}
static MonoThread**
get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
{
static MonoClassField *current_thread_field = NULL;
guint32 offset;
if (!current_thread_field) {
current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
g_assert (current_thread_field);
}
mono_class_vtable (domain, mono_defaults.thread_class);
mono_domain_lock (domain);
offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
mono_domain_unlock (domain);
g_assert (offset);
return get_thread_static_data (thread, offset);
}
static void
set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
{
MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
g_assert (current->obj.vtable->domain == domain);
g_assert (!*current_thread_ptr);
*current_thread_ptr = current;
}
static MonoThread*
new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
{
MonoThread *thread = (MonoThread*) mono_object_new (domain, mono_defaults.thread_class);
MONO_OBJECT_SETREF (thread, internal_thread, internal);
return thread;
}
static void
init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
{
MonoDomain *domain = mono_get_root_domain ();
if (!candidate || candidate->obj.vtable->domain != domain)
candidate = new_thread_with_internal (domain, thread);
set_current_thread_for_domain (domain, thread, candidate);
g_assert (!thread->root_domain_thread);
MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
}
static guint32 WINAPI start_wrapper(void *data)
{
struct StartInfo *start_info=(struct StartInfo *)data;
guint32 (*start_func)(void *);
void *start_arg;
gsize tid;
MonoThread *thread=start_info->obj;
MonoInternalThread *internal = thread->internal_thread;
MonoObject *start_delegate = start_info->delegate;
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
/* We can be sure start_info->obj->tid and
* start_info->obj->handle have been set, because the thread
* was created suspended, and these values were set before the
* thread resumed
*/
tid=internal->tid;
SET_CURRENT_OBJECT (internal);
mono_monitor_init_tls ();
/* Every thread references the appdomain which created it */
mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
/* No point in raising an appdomain_unloaded exception here */
/* FIXME: Cleanup here */
mono_thread_pop_appdomain_ref ();
return 0;
}
start_func = start_info->func;
start_arg = start_info->start_arg;
/* We have to do this here because mono_thread_new_init()
requires that root_domain_thread is set up. */
thread_adjust_static_data (internal);
init_root_domain_thread (internal, thread);
/* This MUST be called before any managed code can be
* executed, as it calls the callback function that (for the
* jit) sets the lmf marker.
*/
mono_thread_new_init (tid, &tid, start_func);
internal->stack_ptr = &tid;
LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
/* On 2.0 profile (and higher), set explicitly since state might have been
Unknown */
if (internal->apartment_state == ThreadApartmentState_Unknown)
internal->apartment_state = ThreadApartmentState_MTA;
mono_thread_init_apartment_state ();
if(internal->start_notify!=NULL) {
/* Let the thread that called Start() know we're
* ready
*/
ReleaseSemaphore (internal->start_notify, 1, NULL);
}
mono_threads_lock ();
mono_g_hash_table_remove (thread_start_args, thread);
mono_threads_unlock ();
g_free (start_info);
#ifdef DEBUG
g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
thread->tid);
#endif
mono_thread_set_execution_context (thread->ec_to_set);
thread->ec_to_set = NULL;
/*
* Call this after calling start_notify, since the profiler callback might want
* to lock the thread, and the lock is held by thread_start () which waits for
* start_notify.
*/
mono_profiler_thread_start (tid);
/* start_func is set only for unmanaged start functions */
if (start_func) {
start_func (start_arg);
} else {
void *args [1];
g_assert (start_delegate != NULL);
args [0] = start_arg;
/* we may want to handle the exception here. See comment below on unhandled exceptions */
mono_runtime_delegate_invoke (start_delegate, args, NULL);
}
/* If the thread calls ExitThread at all, this remaining code
* will not be executed, but the main thread will eventually
* call thread_cleanup() on this thread's behalf.
*/
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
thread_cleanup (internal);
/* Do any cleanup needed for apartment state. This
* cannot be done in thread_cleanup since thread_cleanup could be
* called for a thread other than the current thread.
* mono_thread_cleanup_apartment_state cleans up apartment
* for the current thead */
mono_thread_cleanup_apartment_state ();
/* Remove the reference to the thread object in the TLS data,
* so the thread object can be finalized. This won't be
* reached if the thread threw an uncaught exception, so those
* thread handles will stay referenced :-( (This is due to
* missing support for scanning thread-specific data in the
* Boehm GC - the io-layer keeps a GC-visible hash of pointers
* to TLS data.)
*/
SET_CURRENT_OBJECT (NULL);
mono_domain_unset ();
return(0);
}
void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
{
if (mono_thread_start_cb) {
mono_thread_start_cb (tid, stack_start, func);
}
}
void mono_threads_set_default_stacksize (guint32 stacksize)
{
default_stacksize = stacksize;
}
guint32 mono_threads_get_default_stacksize (void)
{
return default_stacksize;
}
/*
* mono_create_thread:
*
* This is a wrapper around CreateThread which handles differences in the type of
* the the 'tid' argument.
*/
gpointer mono_create_thread (WapiSecurityAttributes *security,
guint32 stacksize, WapiThreadStart start,
gpointer param, guint32 create, gsize *tid)
{
gpointer res;
#ifdef HOST_WIN32
DWORD real_tid;
res = CreateThread (security, stacksize, start, param, create, &real_tid);
if (tid)
*tid = real_tid;
#else
res = CreateThread (security, stacksize, start, param, create, tid);
#endif
return res;
}
/*
* The thread start argument may be an object reference, and there is
* no ref to keep it alive when the new thread is started but not yet
* registered with the collector. So we store it in a GC tracked hash
* table.
*
* LOCKING: Assumes the threads lock is held.
*/
static void
register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
{
if (thread_start_args == NULL) {
MONO_GC_REGISTER_ROOT (thread_start_args);
thread_start_args = mono_g_hash_table_new (NULL, NULL);
}
mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
}
MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
{
MonoThread *thread;
MonoInternalThread *internal;
HANDLE thread_handle;
struct StartInfo *start_info;
gsize tid;
thread=(MonoThread *)mono_object_new (domain,
mono_defaults.thread_class);
internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
mono_defaults.internal_thread_class);
MONO_OBJECT_SETREF (thread, internal_thread, internal);
start_info=g_new0 (struct StartInfo, 1);
start_info->func = func;
start_info->obj = thread;
start_info->start_arg = arg;
mono_threads_lock ();
if (shutting_down) {
mono_threads_unlock ();
g_free (start_info);
return NULL;
}
if (threads_starting_up == NULL) {
MONO_GC_REGISTER_ROOT (threads_starting_up);
threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
}
register_thread_start_argument (thread, start_info);
mono_g_hash_table_insert (threads_starting_up, thread, thread);
mono_threads_unlock ();
/* Create suspended, so we can do some housekeeping before the thread
* starts
*/
thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
CREATE_SUSPENDED, &tid);
THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
if (thread_handle == NULL) {
/* The thread couldn't be created, so throw an exception */
mono_threads_lock ();
mono_g_hash_table_remove (threads_starting_up, thread);
mono_threads_unlock ();
g_free (start_info);
mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
return NULL;
}
internal->handle=thread_handle;
internal->tid=tid;
internal->apartment_state=ThreadApartmentState_Unknown;
small_id_alloc (internal);
internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
InitializeCriticalSection (internal->synch_cs);
internal->threadpool_thread = threadpool_thread;
if (threadpool_thread)
mono_thread_set_state (internal, ThreadState_Background);
if (handle_store (thread))
ResumeThread (thread_handle);
return internal;
}
void
mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
{
mono_thread_create_internal (domain, func, arg, FALSE);
}
/*
* mono_thread_get_stack_bounds:
*
* Return the address and size of the current threads stack. Return NULL as the
* stack address if the stack address cannot be determined.
*/
void
mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
{
#if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
*staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
*stsize = pthread_get_stacksize_np (pthread_self ());
*staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
return;
/* FIXME: simplify the mess below */
#elif !defined(HOST_WIN32)
pthread_attr_t attr;
guint8 *current = (guint8*)&attr;
pthread_attr_init (&attr);
# ifdef HAVE_PTHREAD_GETATTR_NP
pthread_getattr_np (pthread_self(), &attr);
# else
# ifdef HAVE_PTHREAD_ATTR_GET_NP
pthread_attr_get_np (pthread_self(), &attr);
# elif defined(sun)
*staddr = NULL;
pthread_attr_getstacksize (&attr, &stsize);
# elif defined(__OpenBSD__)
stack_t ss;
int rslt;
rslt = pthread_stackseg_np(pthread_self(), &ss);
g_assert (rslt == 0);
*staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
*stsize = ss.ss_size;
# else
*staddr = NULL;
*stsize = 0;
return;
# endif
# endif
# if !defined(sun)
# if !defined(__OpenBSD__)
pthread_attr_getstack (&attr, (void**)staddr, stsize);
# endif
if (*staddr)
g_assert ((current > *staddr) && (current < *staddr + *stsize));
# endif
pthread_attr_destroy (&attr);
#endif
/* When running under emacs, sometimes staddr is not aligned to a page size */
*staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
}
MonoThread *
mono_thread_attach (MonoDomain *domain)
{
MonoInternalThread *thread;
MonoThread *current_thread;
HANDLE thread_handle;
gsize tid;
if ((thread = mono_thread_internal_current ())) {
if (domain != mono_domain_get ())
mono_domain_set (domain, TRUE);
/* Already attached */
return mono_thread_current ();
}
if (!mono_gc_register_thread (&domain)) {
g_error ("Thread %"G_GSIZE_FORMAT" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
}
thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
thread_handle = GetCurrentThread ();