/
threads.c
4869 lines (4054 loc) · 129 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)
* Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
*/
#include <config.h>
#include <glib.h>
#include <signal.h>
#include <string.h>
#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/metadata/runtime.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/utils/mono-threads.h>
#include <mono/utils/hazard-pointer.h>
#include <mono/utils/mono-tls.h>
#include <mono/utils/atomic.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/metadata/gc-internal.h>
#ifdef PLATFORM_ANDROID
#include <errno.h>
extern int tkill (pid_t tid, int signal);
#endif
/*#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
#define LOCK_THREAD(thread) lock_thread((thread))
#define UNLOCK_THREAD(thread) unlock_thread((thread))
/* 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
typedef struct
{
guint32 (*func)(void *);
MonoThread *obj;
MonoObject *delegate;
void *start_arg;
} StartInfo;
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;
/* 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() mono_mutex_lock (&threads_mutex)
#define mono_threads_unlock() mono_mutex_unlock (&threads_mutex)
static mono_mutex_t threads_mutex;
/* Controls access to context static data */
#define mono_contexts_lock() mono_mutex_lock (&contexts_mutex)
#define mono_contexts_unlock() mono_mutex_unlock (&contexts_mutex)
static mono_mutex_t contexts_mutex;
/* Controls access to the 'joinable_threads' hash table */
#define joinable_threads_lock() mono_mutex_lock (&joinable_threads_mutex)
#define joinable_threads_unlock() mono_mutex_unlock (&joinable_threads_mutex)
static mono_mutex_t joinable_threads_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 MonoNativeTlsKey current_object_key;
/* Contains tids */
/* Protected by the threads lock */
static GHashTable *joinable_threads;
static int joinable_thread_count;
#ifdef MONO_HAVE_FAST_TLS
/* we need to use both the Tls* functions and __thread because
* the gc needs to see all the threads
*/
MONO_FAST_TLS_DECLARE(tls_current_object);
#define SET_CURRENT_OBJECT(x) do { \
MONO_FAST_TLS_SET (tls_current_object, x); \
mono_native_tls_set_value (current_object_key, x); \
} while (FALSE)
#define GET_CURRENT_OBJECT() ((MonoInternalThread*) MONO_FAST_TLS_GET (tls_current_object))
#else
#define SET_CURRENT_OBJECT(x) mono_native_tls_set_value (current_object_key, x)
#define GET_CURRENT_OBJECT() (MonoInternalThread*) mono_native_tls_get_value (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 signal_thread_state_change (MonoInternalThread *thread);
static void abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception, gboolean install_async_abort);
static void suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt);
static void self_suspend_internal (MonoInternalThread *thread);
static gboolean resume_thread_internal (MonoInternalThread *thread);
static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
static void ref_stack_destroy (gpointer rs);
/* Spin lock for InterlockedXXX 64 bit functions */
#define mono_interlocked_lock() mono_mutex_lock (&interlocked_mutex)
#define mono_interlocked_unlock() mono_mutex_unlock (&interlocked_mutex)
static mono_mutex_t 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;
static gboolean shutting_down = FALSE;
static gint32 managed_thread_id_counter = 0;
static guint32
get_next_managed_thread_id (void)
{
return InterlockedIncrement (&managed_thread_id_counter);
}
MonoNativeTlsKey
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;
}
static inline MonoNativeThreadId
thread_get_tid (MonoInternalThread *thread)
{
/* We store the tid as a guint64 to keep the object layout constant between platforms */
return MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
}
/* 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, gboolean force_attach)
{
mono_threads_lock ();
THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->internal_thread->tid));
if (threads_starting_up)
mono_g_hash_table_remove (threads_starting_up, thread);
if (shutting_down && !force_attach) {
mono_threads_unlock ();
return FALSE;
}
if(threads==NULL) {
MONO_GC_REGISTER_ROOT_FIXED (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;
}
static void ensure_synch_cs_set (MonoInternalThread *thread)
{
mono_mutex_t *synch_cs;
if (thread->synch_cs != NULL) {
return;
}
synch_cs = g_new0 (mono_mutex_t, 1);
mono_mutex_init_recursive (synch_cs);
if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
synch_cs, NULL) != NULL) {
/* Another thread must have installed this CS */
mono_mutex_destroy (synch_cs);
g_free (synch_cs);
}
}
static inline void
lock_thread (MonoInternalThread *thread)
{
if (!thread->synch_cs)
ensure_synch_cs_set (thread);
g_assert (thread->synch_cs);
mono_mutex_lock (thread->synch_cs);
}
static inline void
unlock_thread (MonoInternalThread *thread)
{
mono_mutex_unlock (thread->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);
}
/*
* thread->synch_cs can be NULL if this was called after
* ves_icall_System_Threading_InternalThread_Thread_free_internal.
* This can happen only during shutdown.
* The shutting_down flag is not always set, so we can't assert on it.
*/
if (thread->synch_cs)
LOCK_THREAD (thread);
thread->state |= ThreadState_Stopped;
thread->state &= ~ThreadState_Background;
if (thread->synch_cs)
UNLOCK_THREAD (thread);
/*
An interruption request has leaked to cleanup. Adjust the global counter.
This can happen is the abort source thread finds the abortee (this) thread
in unmanaged code. If this thread never trips back to managed code or check
the local flag it will be left set and positively unbalance the global counter.
Leaving the counter unbalanced will cause a performance degradation since all threads
will now keep checking their local flags all the time.
*/
if (InterlockedExchange (&thread->interruption_requested, 0))
InterlockedDecrement (&thread_interruption_requested);
/* if the thread is not in the hash it has been removed already */
if (!handle_remove (thread)) {
if (thread == mono_thread_internal_current ()) {
mono_domain_unset ();
mono_memory_barrier ();
}
/* This needs to be called even if handle_remove () fails */
if (mono_thread_cleanup_fn)
mono_thread_cleanup_fn (thread);
return;
}
mono_release_type_locks (thread);
mono_profiler_thread_end (thread->tid);
if (thread == mono_thread_internal_current ()) {
/*
* This will signal async signal handlers that the thread has exited.
* The profiler callback needs this to be set, so it cannot be done earlier.
*/
mono_domain_unset ();
mono_memory_barrier ();
}
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;
ref_stack_destroy (thread->appdomain_refs);
thread->appdomain_refs = NULL;
if (mono_thread_cleanup_fn)
mono_thread_cleanup_fn (thread);
if (mono_gc_is_moving ()) {
MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
thread->thread_pinning_ref = NULL;
}
}
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*
create_thread_object (MonoDomain *domain)
{
MonoVTable *vt = mono_class_vtable (domain, mono_defaults.thread_class);
return (MonoThread*)mono_gc_alloc_mature (vt);
}
static MonoThread*
new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
{
MonoThread *thread = create_thread_object (domain);
MONO_OBJECT_SETREF (thread, internal_thread, internal);
return thread;
}
static MonoInternalThread*
create_internal_thread (void)
{
MonoInternalThread *thread;
MonoVTable *vt;
vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
thread = (MonoInternalThread*)mono_gc_alloc_mature (vt);
thread->synch_cs = g_new0 (mono_mutex_t, 1);
mono_mutex_init_recursive (thread->synch_cs);
thread->apartment_state = ThreadApartmentState_Unknown;
thread->managed_id = get_next_managed_thread_id ();
if (mono_gc_is_moving ()) {
thread->thread_pinning_ref = thread;
MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref);
}
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_internal(void *data)
{
MonoThreadInfo *info;
StartInfo *start_info = (StartInfo *)data;
guint32 (*start_func)(void *);
void *start_arg;
gsize tid;
/*
* We don't create a local to hold start_info->obj, so hopefully it won't get pinned during a
* GC stack walk.
*/
MonoInternalThread *internal = start_info->obj->internal_thread;
MonoObject *start_delegate = start_info->delegate;
MonoDomain *domain = start_info->obj->obj.vtable->domain;
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
*/
info = mono_thread_info_current ();
g_assert (info);
internal->thread_info = info;
tid=internal->tid;
SET_CURRENT_OBJECT (internal);
mono_monitor_init_tls ();
/* Every thread references the appdomain which created it */
mono_thread_push_appdomain_ref (domain);
if (!mono_domain_set (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, start_info->obj);
/* 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 (), internal));
/* 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, start_info->obj);
mono_threads_unlock ();
mono_thread_set_execution_context (start_info->obj->ec_to_set);
start_info->obj->ec_to_set = NULL;
g_free (start_info);
THREAD_DEBUG (g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
internal->tid));
/*
* 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);
/* if the name was set before starting, we didn't invoke the profiler callback */
if (internal->name && (internal->flags & MONO_THREAD_FLAG_NAME_SET)) {
char *tname = g_utf16_to_utf8 (internal->name, -1, NULL, NULL, NULL);
mono_profiler_thread_name (internal->tid, tname);
g_free (tname);
}
/* 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 ()));
/* 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 ();
thread_cleanup (internal);
internal->tid = 0;
/* 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);
return(0);
}
static guint32 WINAPI start_wrapper(void *data)
{
volatile int dummy;
/* Avoid scanning the frames above this frame during a GC */
mono_gc_set_stack_end ((void*)&dummy);
return start_wrapper_internal (data);
}
/*
* create_thread:
*
* Common thread creation code.
* LOCKING: Acquires the threads lock.
*/
static gboolean
create_thread (MonoThread *thread, MonoInternalThread *internal, StartInfo *start_info, gboolean threadpool_thread, guint32 stack_size,
gboolean throw_on_failure)
{
HANDLE thread_handle;
MonoNativeThreadId tid;
guint32 create_flags;
/*
* Join joinable threads to prevent running out of threads since the finalizer
* thread might be blocked/backlogged.
*/
mono_threads_join_threads ();
mono_threads_lock ();
if (shutting_down) {
g_free (start_info);
mono_threads_unlock ();
return FALSE;
}
/*
* 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.
*/
if (thread_start_args == NULL) {
MONO_GC_REGISTER_ROOT_FIXED (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);
if (threads_starting_up == NULL) {
MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
}
mono_g_hash_table_insert (threads_starting_up, thread, thread);
mono_threads_unlock ();
internal->start_notify = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
if (!internal->start_notify) {
mono_threads_lock ();
mono_g_hash_table_remove (threads_starting_up, thread);
mono_threads_unlock ();
g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
g_free (start_info);
return FALSE;
}
if (stack_size == 0)
stack_size = default_stacksize_for_thread (internal);
/* Create suspended, so we can do some housekeeping before the thread
* starts
*/
create_flags = CREATE_SUSPENDED;
thread_handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)start_wrapper, start_info,
stack_size, create_flags, &tid);
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);
if (throw_on_failure)
mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
else
g_warning ("%s: CreateThread error 0x%x", __func__, GetLastError ());
return FALSE;
}
THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
internal->handle = thread_handle;
internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (tid);
internal->threadpool_thread = threadpool_thread;
if (threadpool_thread)
mono_thread_set_state (internal, ThreadState_Background);
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
/* Only store the handle when the thread is about to be
* launched, to avoid the main thread deadlocking while trying
* to clean up a thread that will never be signalled.
*/
if (!handle_store (thread, FALSE))
return FALSE;
mono_thread_info_resume (tid);
if (internal->start_notify) {
/*
* Wait for the thread to set up its TLS data etc, so
* theres no potential race condition if someone tries
* to look up the data believing the thread has
* started
*/
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
CloseHandle (internal->start_notify);
internal->start_notify = NULL;
}
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
return TRUE;
}
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_thread_create_internal:
*
*/
MonoInternalThread*
mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size)
{
MonoThread *thread;
MonoInternalThread *internal;
StartInfo *start_info;
gboolean res;
thread = create_thread_object (domain);
internal = create_internal_thread ();
MONO_OBJECT_SETREF (thread, internal_thread, internal);
start_info = g_new0 (StartInfo, 1);
start_info->func = func;
start_info->obj = thread;
start_info->start_arg = arg;
res = create_thread (thread, internal, start_info, threadpool_thread, stack_size, TRUE);
if (!res)
return NULL;
/* Check that the managed and unmanaged layout of MonoInternalThread matches */
if (mono_check_corlib_version () == NULL)
g_assert (((char*)&internal->unused2 - (char*)internal) == mono_defaults.internal_thread_class->fields [mono_defaults.internal_thread_class->field.count - 1].offset);
return internal;
}
void
mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
{
mono_thread_create_internal (domain, func, arg, FALSE, 0);
}
MonoThread *
mono_thread_attach (MonoDomain *domain)
{
return mono_thread_attach_full (domain, FALSE);
}
MonoThread *
mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
{
MonoThreadInfo *info;
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 = create_internal_thread ();
thread_handle = mono_thread_info_open_handle ();
g_assert (thread_handle);
tid=GetCurrentThreadId ();
thread->handle=thread_handle;
thread->tid=tid;
#ifdef PLATFORM_ANDROID
thread->android_tid = (gpointer) gettid ();
#endif
thread->stack_ptr = &tid;
THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
info = mono_thread_info_current ();
g_assert (info);
thread->thread_info = info;
current_thread = new_thread_with_internal (domain, thread);
if (!handle_store (current_thread, force_attach)) {
/* Mono is shutting down, so just wait for the end */
for (;;)
Sleep (10000);
}
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
SET_CURRENT_OBJECT (thread);
mono_domain_set (domain, TRUE);
mono_monitor_init_tls ();
thread_adjust_static_data (thread);
init_root_domain_thread (thread, current_thread);
if (domain != mono_get_root_domain ())
set_current_thread_for_domain (domain, thread, current_thread);
if (mono_thread_attach_cb) {
guint8 *staddr;
size_t stsize;
mono_thread_info_get_stack_bounds (&staddr, &stsize);
if (staddr == NULL)
mono_thread_attach_cb (tid, &tid);
else
mono_thread_attach_cb (tid, staddr + stsize);
}
// FIXME: Need a separate callback
mono_profiler_thread_start (tid);
return current_thread;
}
void
mono_thread_detach_internal (MonoInternalThread *thread)
{
g_return_if_fail (thread != NULL);
THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
thread_cleanup (thread);
SET_CURRENT_OBJECT (NULL);
mono_domain_unset ();
/* Don't need to CloseHandle this thread, even though we took a
* reference in mono_thread_attach (), because the GC will do it
* when the Thread object is finalised.
*/
}
void
mono_thread_detach (MonoThread *thread)
{
if (thread)
mono_thread_detach_internal (thread->internal_thread);
}
/*
* mono_thread_detach_if_exiting:
*
* Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
* This should be used at the end of embedding code which calls into managed code, and which
* can be called from pthread dtors, like dealloc: implementations in objective-c.
*/
void
mono_thread_detach_if_exiting (void)
{
if (mono_thread_info_is_exiting ()) {