2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * (C) 2001 Ximian, Inc.
14 #define _WIN32_WINNT 0x0500
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/environment.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/io-layer/io-layer.h>
33 #include <mono/metadata/object-internals.h>
35 #include <mono/os/gc_wrapper.h>
38 #undef THREAD_WAIT_DEBUG
42 guint32 (*func)(void *);
59 /* Number of cached culture objects in the MonoThread->culture_info array */
60 #define NUM_CACHED_CULTURES 4
63 * The "os_handle" field of the WaitHandle class.
65 static MonoClassField *wait_handle_os_handle_field = NULL;
67 /* Controls access to the 'threads' hash table */
68 static CRITICAL_SECTION threads_mutex;
70 /* Controls access to context static data */
71 static CRITICAL_SECTION contexts_mutex;
73 /* Holds current status of static data heap */
74 static StaticDataInfo thread_static_info;
75 static StaticDataInfo context_static_info;
77 /* The hash of existing threads (key is thread ID) that need joining
80 static MonoGHashTable *threads=NULL;
82 /* The TLS key that holds the MonoObject assigned to each thread */
83 static guint32 current_object_key = -1;
86 /* we need to use both the Tls* functions and __thread because
87 * the gc needs to see all the threads
89 static __thread MonoThread * tls_current_object;
90 #define SET_CURRENT_OBJECT(x) do { \
91 tls_current_object = x; \
92 TlsSetValue (current_object_key, x); \
94 #define GET_CURRENT_OBJECT() tls_current_object
96 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
97 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
100 /* function called at thread start */
101 static MonoThreadStartCB mono_thread_start_cb = NULL;
103 /* function called at thread attach */
104 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
106 /* function called at thread cleanup */
107 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
109 /* function called when a new thread has been created */
110 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
112 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
113 static guint32 slothash_key = -1;
115 /* The default stack size for each thread */
116 static guint32 default_stacksize = 0;
117 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
119 static void thread_adjust_static_data (MonoThread *thread);
120 static void mono_init_static_data_info (StaticDataInfo *static_data);
121 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
123 /* Spin lock for InterlockedXXX 64 bit functions */
124 static CRITICAL_SECTION interlocked_mutex;
126 /* Controls access to interruption flag */
127 static CRITICAL_SECTION interruption_mutex;
129 /* global count of thread interruptions requested */
130 static gint32 thread_interruption_requested = 0;
133 mono_thread_get_tls_key (void)
135 return current_object_key;
138 /* handle_store() and handle_remove() manage the array of threads that
139 * still need to be waited for when the main thread exits.
141 static void handle_store(MonoThread *thread)
143 EnterCriticalSection(&threads_mutex);
146 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
151 MONO_GC_REGISTER_ROOT (threads);
152 threads=mono_g_hash_table_new(NULL, NULL);
155 /* We don't need to duplicate thread->handle, because it is
156 * only closed when the thread object is finalized by the GC.
158 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
159 LeaveCriticalSection(&threads_mutex);
162 static void handle_remove(guint32 tid)
165 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
168 EnterCriticalSection(&threads_mutex);
171 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
173 LeaveCriticalSection(&threads_mutex);
175 /* Don't close the handle here, wait for the object finalizer
176 * to do it. Otherwise, the following race condition applies:
178 * 1) Thread exits (and handle_remove() closes the handle)
180 * 2) Some other handle is reassigned the same slot
182 * 3) Another thread tries to join the first thread, and
183 * blocks waiting for the reassigned handle to be signalled
184 * (which might never happen). This is possible, because the
185 * thread calling Join() still has a reference to the first
190 static void thread_cleanup (MonoThread *thread)
192 mono_release_type_locks (thread);
194 if (!mono_monitor_enter (thread->synch_lock))
197 thread->state |= ThreadState_Stopped;
198 mono_monitor_exit (thread->synch_lock);
200 mono_profiler_thread_end (thread->tid);
201 handle_remove (thread->tid);
203 mono_thread_pop_appdomain_ref ();
205 if (thread->serialized_culture_info)
206 g_free (thread->serialized_culture_info);
208 mono_gc_free_fixed (thread->culture_info);
209 mono_gc_free_fixed (thread->ui_culture_info);
211 if (mono_thread_cleanup)
212 mono_thread_cleanup (thread);
215 static guint32 start_wrapper(void *data)
217 struct StartInfo *start_info=(struct StartInfo *)data;
218 guint32 (*start_func)(void *);
221 MonoThread *thread=start_info->obj;
222 MonoObject *start_delegate = start_info->delegate;
225 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
226 GetCurrentThreadId ());
229 /* We can be sure start_info->obj->tid and
230 * start_info->obj->handle have been set, because the thread
231 * was created suspended, and these values were set before the
237 SET_CURRENT_OBJECT (thread);
239 if (!mono_domain_set (start_info->domain, FALSE)) {
240 /* No point in raising an appdomain_unloaded exception here */
241 /* FIXME: Cleanup here */
245 start_func = start_info->func;
246 start_arg = start_info->start_arg;
248 /* This MUST be called before any managed code can be
249 * executed, as it calls the callback function that (for the
250 * jit) sets the lmf marker.
252 mono_thread_new_init (tid, &tid, start_func);
253 thread->stack_ptr = &tid;
256 g_message (G_GNUC_PRETTY_FUNCTION
257 ": (%d,%d) Setting thread stack to %p",
258 GetCurrentThreadId (), getpid (), thread->stack_ptr);
262 g_message (G_GNUC_PRETTY_FUNCTION
263 ": (%d) Setting current_object_key to %p",
264 GetCurrentThreadId (), thread);
267 mono_profiler_thread_start (tid);
269 if(thread->start_notify!=NULL) {
270 /* Let the thread that called Start() know we're
273 ReleaseSemaphore (thread->start_notify, 1, NULL);
278 /* Every thread references the appdomain which created it */
279 mono_thread_push_appdomain_ref (mono_domain_get ());
281 thread_adjust_static_data (thread);
283 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
286 /* start_func is set only for unamanged start functions */
288 start_func (start_arg);
291 g_assert (start_delegate != NULL);
292 args [0] = start_arg;
293 /* we may want to handle the exception here. See comment below on unhandled exceptions */
294 mono_runtime_delegate_invoke (start_delegate, args, NULL);
296 #ifdef PLATFORM_WIN32
297 /* If the thread calls ExitThread at all, this remaining code
298 * will not be executed, but the main thread will eventually
299 * call thread_cleanup() on this thread's behalf.
303 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
304 GetCurrentThreadId ());
307 /* Remove the reference to the thread object in the TLS data,
308 * so the thread object can be finalized. This won't be
309 * reached if the thread threw an uncaught exception, so those
310 * thread handles will stay referenced :-( (This is due to
311 * missing support for scanning thread-specific data in the
312 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
315 SET_CURRENT_OBJECT (NULL);
318 thread_cleanup (thread);
323 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
325 if (mono_thread_start_cb) {
326 mono_thread_start_cb (tid, stack_start, func);
329 if (mono_thread_callbacks)
330 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
333 void mono_threads_set_default_stacksize (guint32 stacksize)
335 default_stacksize = stacksize;
338 guint32 mono_threads_get_default_stacksize (void)
340 return default_stacksize;
343 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
346 HANDLE thread_handle;
347 struct StartInfo *start_info;
350 thread=(MonoThread *)mono_object_new (domain,
351 mono_defaults.thread_class);
353 start_info=g_new0 (struct StartInfo, 1);
354 start_info->func = func;
355 start_info->obj = thread;
356 start_info->domain = domain;
357 start_info->start_arg = arg;
359 /* Create suspended, so we can do some housekeeping before the thread
362 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
363 thread_handle = GC_CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
364 CREATE_SUSPENDED, &tid);
366 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
367 CREATE_SUSPENDED, &tid);
370 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
373 g_assert (thread_handle);
375 thread->handle=thread_handle;
378 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
380 handle_store(thread);
382 ResumeThread (thread_handle);
386 mono_thread_attach (MonoDomain *domain)
389 HANDLE thread_handle;
392 if ((thread = mono_thread_current ())) {
393 /* Already attached */
397 thread = (MonoThread *)mono_object_new (domain,
398 mono_defaults.thread_class);
400 thread_handle = GetCurrentThread ();
401 g_assert (thread_handle);
403 tid=GetCurrentThreadId ();
405 #ifdef PLATFORM_WIN32
407 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
408 * refer to the thread from other threads for things like aborting.
410 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
411 THREAD_ALL_ACCESS, TRUE, 0);
414 thread->handle=thread_handle;
416 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
419 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
423 handle_store(thread);
426 g_message (G_GNUC_PRETTY_FUNCTION
427 ": (%d) Setting current_object_key to %p",
428 GetCurrentThreadId (), thread);
431 SET_CURRENT_OBJECT (thread);
432 mono_domain_set (domain, TRUE);
434 thread_adjust_static_data (thread);
436 if (mono_thread_attach_cb) {
437 mono_thread_attach_cb (tid, &tid);
444 mono_thread_detach (MonoThread *thread)
446 g_return_if_fail (thread != NULL);
449 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
451 SET_CURRENT_OBJECT (NULL);
453 thread_cleanup (thread);
459 MonoThread *thread = mono_thread_current ();
461 SET_CURRENT_OBJECT (NULL);
462 thread_cleanup (thread);
464 /* we could add a callback here for embedders to use. */
465 if (thread == mono_thread_get_main ())
466 exit (mono_environment_exitcode_get ());
470 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
473 guint32 (*start_func)(void *);
474 struct StartInfo *start_info;
482 g_message(G_GNUC_PRETTY_FUNCTION
483 ": Trying to start a new thread: this (%p) start (%p)",
487 /* FIXME: remove the code inside BROKEN_THREAD_START once martin gets rid of the
488 * thread_start_compile_func stuff.
490 #define BROKEN_THREAD_START
491 #ifdef BROKEN_THREAD_START
492 im = mono_get_delegate_invoke (start->vtable->klass);
493 im = mono_marshal_get_delegate_invoke (im);
494 if (mono_thread_callbacks)
495 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
497 start_func = mono_compile_method (im);
499 if(start_func==NULL) {
500 g_warning(G_GNUC_PRETTY_FUNCTION
501 ": Can't locate start method!");
508 /* This is freed in start_wrapper */
509 start_info = g_new0 (struct StartInfo, 1);
510 start_info->func = start_func;
511 #ifdef BROKEN_THREAD_START
512 start_info->start_arg = start;
514 start_info->start_arg = this->start_obj;
516 start_info->delegate = start;
517 start_info->obj = this;
518 start_info->domain = mono_domain_get ();
520 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
521 if(this->start_notify==NULL) {
522 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
526 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
527 thread=GC_CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
528 CREATE_SUSPENDED, &tid);
530 thread=CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
531 CREATE_SUSPENDED, &tid);
534 g_warning(G_GNUC_PRETTY_FUNCTION
535 ": CreateThread error 0x%x", GetLastError());
542 /* Don't call handle_store() here, delay it to Start.
543 * We can't join a thread (trying to will just block
544 * forever) until it actually starts running, so don't
545 * store the handle till then.
549 g_message(G_GNUC_PRETTY_FUNCTION
550 ": Started thread ID %d (handle %p)", tid, thread);
557 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
563 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
567 CloseHandle (thread);
570 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
576 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
577 GetCurrentThreadId (), this, this->tid);
580 /* Only store the handle when the thread is about to be
581 * launched, to avoid the main thread deadlocking while trying
582 * to clean up a thread that will never be signalled.
586 if (mono_thread_callbacks)
587 (* mono_thread_callbacks->start_resume) (this->tid);
589 ResumeThread(thread);
591 if (mono_thread_callbacks)
592 (* mono_thread_callbacks->end_resume) (this->tid);
594 if(this->start_notify!=NULL) {
595 /* Wait for the thread to set up its TLS data etc, so
596 * theres no potential race condition if someone tries
597 * to look up the data believing the thread has
602 g_message(G_GNUC_PRETTY_FUNCTION
603 ": (%d) waiting for thread %p (%d) to start",
604 GetCurrentThreadId (), this, this->tid);
607 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
608 CloseHandle (this->start_notify);
609 this->start_notify=NULL;
613 g_message(G_GNUC_PRETTY_FUNCTION
614 ": (%d) Done launching thread %p (%d)",
615 GetCurrentThreadId (), this, this->tid);
619 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
621 MonoThread *thread = mono_thread_current ();
626 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
629 mono_monitor_enter (thread->synch_lock);
630 thread->state |= ThreadState_WaitSleepJoin;
631 mono_monitor_exit (thread->synch_lock);
635 mono_monitor_enter (thread->synch_lock);
636 thread->state &= ~ThreadState_WaitSleepJoin;
637 mono_monitor_exit (thread->synch_lock);
641 ves_icall_System_Threading_Thread_GetDomainID (void)
645 return mono_domain_get()->domain_id;
649 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
654 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
658 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
661 g_free (this_obj->name);
663 this_obj->name = g_new (gunichar2, mono_string_length (name));
664 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
665 this_obj->name_len = mono_string_length (name);
668 this_obj->name = NULL;
672 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
678 /* No need to lock here */
679 if (this->culture_info) {
680 domain = mono_domain_get ();
681 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
682 res = this->culture_info [i];
683 if (res && res->vtable->domain == domain)
692 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
696 mono_monitor_enter (this->synch_lock);
697 if (this->serialized_culture_info) {
698 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
699 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
703 mono_monitor_exit (this->synch_lock);
709 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
712 MonoDomain *domain = mono_domain_get ();
714 mono_monitor_enter (this->synch_lock);
715 if (!this->culture_info) {
716 this->culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
719 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
720 if (this->culture_info [i]) {
721 if (this->culture_info [i]->vtable->domain == domain)
729 if (i < NUM_CACHED_CULTURES)
730 this->culture_info [i] = culture;
731 mono_monitor_exit (this->synch_lock);
735 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
737 mono_monitor_enter (this->synch_lock);
738 if (this->serialized_culture_info)
739 g_free (this->serialized_culture_info);
740 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
741 this->serialized_culture_info_len = mono_array_length (arr);
742 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
743 mono_monitor_exit (this->synch_lock);
748 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
754 /* No need to lock here */
755 if (this->ui_culture_info) {
756 domain = mono_domain_get ();
757 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
758 res = this->ui_culture_info [i];
759 if (res && res->vtable->domain == domain)
768 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
772 mono_monitor_enter (this->synch_lock);
773 if (this->serialized_ui_culture_info) {
774 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
775 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
779 mono_monitor_exit (this->synch_lock);
785 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
788 MonoDomain *domain = mono_domain_get ();
790 mono_monitor_enter (this->synch_lock);
791 if (!this->ui_culture_info) {
792 this->ui_culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
795 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
796 if (this->ui_culture_info [i]) {
797 if (this->ui_culture_info [i]->vtable->domain == domain)
805 if (i < NUM_CACHED_CULTURES)
806 this->ui_culture_info [i] = culture;
807 mono_monitor_exit (this->synch_lock);
811 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
813 mono_monitor_enter (this->synch_lock);
814 if (this->serialized_ui_culture_info)
815 g_free (this->serialized_ui_culture_info);
816 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
817 this->serialized_ui_culture_info_len = mono_array_length (arr);
818 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
819 mono_monitor_exit (this->synch_lock);
822 /* the jit may read the compiled code of this function */
824 mono_thread_current (void)
829 thread = GET_CURRENT_OBJECT ();
830 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
834 return GET_CURRENT_OBJECT ();
838 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
839 int ms, HANDLE thread)
845 mono_monitor_enter (this->synch_lock);
846 this->state |= ThreadState_WaitSleepJoin;
847 mono_monitor_exit (this->synch_lock);
853 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
857 ret=WaitForSingleObjectEx (thread, ms, TRUE);
859 mono_monitor_enter (this->synch_lock);
860 this->state &= ~ThreadState_WaitSleepJoin;
861 mono_monitor_exit (this->synch_lock);
863 if(ret==WAIT_OBJECT_0) {
865 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
872 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
878 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
883 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
886 /* Object location stored here */
887 TlsSetValue(slothash_key, data);
890 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
896 data=TlsGetValue(slothash_key);
899 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
905 /* FIXME: exitContext isnt documented */
906 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
912 MonoObject *waitHandle;
914 MonoThread *thread = mono_thread_current ();
918 numhandles = mono_array_length(mono_handles);
919 handles = g_new0(HANDLE, numhandles);
921 if (wait_handle_os_handle_field == 0) {
922 /* Get the field os_handle which will contain the actual handle */
923 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
924 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
927 for(i = 0; i < numhandles; i++) {
928 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
929 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
936 mono_monitor_enter (thread->synch_lock);
937 thread->state |= ThreadState_WaitSleepJoin;
938 mono_monitor_exit (thread->synch_lock);
940 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
942 mono_monitor_enter (thread->synch_lock);
943 thread->state &= ~ThreadState_WaitSleepJoin;
944 mono_monitor_exit (thread->synch_lock);
948 if(ret==WAIT_FAILED) {
949 #ifdef THREAD_WAIT_DEBUG
950 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
951 GetCurrentThreadId ());
954 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
955 /* Do we want to try again if we get
956 * WAIT_IO_COMPLETION? The documentation for
957 * WaitHandle doesn't give any clues. (We'd have to
958 * fiddle with the timeout if we retry.)
960 #ifdef THREAD_WAIT_DEBUG
961 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
962 GetCurrentThreadId ());
970 /* FIXME: exitContext isnt documented */
971 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
977 MonoObject *waitHandle;
979 MonoThread *thread = mono_thread_current ();
983 numhandles = mono_array_length(mono_handles);
984 handles = g_new0(HANDLE, numhandles);
986 if (wait_handle_os_handle_field == 0) {
987 /* Get the field os_handle which will contain the actual handle */
988 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
989 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
992 for(i = 0; i < numhandles; i++) {
993 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
994 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
1001 mono_monitor_enter (thread->synch_lock);
1002 thread->state |= ThreadState_WaitSleepJoin;
1003 mono_monitor_exit (thread->synch_lock);
1005 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1007 mono_monitor_enter (thread->synch_lock);
1008 thread->state &= ~ThreadState_WaitSleepJoin;
1009 mono_monitor_exit (thread->synch_lock);
1013 #ifdef THREAD_WAIT_DEBUG
1014 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
1015 GetCurrentThreadId (), ret);
1019 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1021 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1022 return ret - WAIT_OBJECT_0;
1024 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1025 return ret - WAIT_ABANDONED_0;
1032 /* FIXME: exitContext isnt documented */
1033 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1036 MonoThread *thread = mono_thread_current ();
1038 MONO_ARCH_SAVE_REGS;
1040 #ifdef THREAD_WAIT_DEBUG
1041 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
1042 GetCurrentThreadId (), handle, ms);
1049 mono_monitor_enter (thread->synch_lock);
1050 thread->state |= ThreadState_WaitSleepJoin;
1051 mono_monitor_exit (thread->synch_lock);
1053 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1055 mono_monitor_enter (thread->synch_lock);
1056 thread->state &= ~ThreadState_WaitSleepJoin;
1057 mono_monitor_exit (thread->synch_lock);
1059 if(ret==WAIT_FAILED) {
1060 #ifdef THREAD_WAIT_DEBUG
1061 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1062 GetCurrentThreadId ());
1065 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1066 /* Do we want to try again if we get
1067 * WAIT_IO_COMPLETION? The documentation for
1068 * WaitHandle doesn't give any clues. (We'd have to
1069 * fiddle with the timeout if we retry.)
1071 #ifdef THREAD_WAIT_DEBUG
1072 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1073 GetCurrentThreadId ());
1081 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1085 MONO_ARCH_SAVE_REGS;
1090 mutex = CreateMutex (NULL, owned, NULL);
1092 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1094 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1102 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1103 MONO_ARCH_SAVE_REGS;
1105 ReleaseMutex(handle);
1108 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1109 MONO_ARCH_SAVE_REGS;
1111 return(CreateEvent (NULL, manual, initial,
1112 name==NULL?NULL:mono_string_chars (name)));
1115 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1116 MONO_ARCH_SAVE_REGS;
1118 return (SetEvent(handle));
1121 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1122 MONO_ARCH_SAVE_REGS;
1124 return (ResetEvent(handle));
1128 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1129 MONO_ARCH_SAVE_REGS;
1131 CloseHandle (handle);
1134 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1136 MONO_ARCH_SAVE_REGS;
1138 return InterlockedIncrement (location);
1141 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1145 MONO_ARCH_SAVE_REGS;
1147 EnterCriticalSection(&interlocked_mutex);
1151 LeaveCriticalSection(&interlocked_mutex);
1157 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1159 MONO_ARCH_SAVE_REGS;
1161 return InterlockedDecrement(location);
1164 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1168 MONO_ARCH_SAVE_REGS;
1170 EnterCriticalSection(&interlocked_mutex);
1174 LeaveCriticalSection(&interlocked_mutex);
1179 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1181 MONO_ARCH_SAVE_REGS;
1183 return InterlockedExchange(location1, value);
1186 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1188 MONO_ARCH_SAVE_REGS;
1190 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1193 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1195 IntFloatUnion val, ret;
1197 MONO_ARCH_SAVE_REGS;
1200 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1205 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1207 MONO_ARCH_SAVE_REGS;
1209 return InterlockedCompareExchange(location1, value, comparand);
1212 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1214 MONO_ARCH_SAVE_REGS;
1216 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1219 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1221 IntFloatUnion val, ret, cmp;
1223 MONO_ARCH_SAVE_REGS;
1226 cmp.fval = comparand;
1227 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1233 mono_thread_get_abort_signal (void)
1243 #endif /* __MINGW32__ */
1247 static CALLBACK void interruption_request_apc (ULONG_PTR param)
1249 MonoException* exc = mono_thread_request_interruption (FALSE);
1250 if (exc) mono_raise_exception (exc);
1253 #endif /* __MINGW32__ */
1256 * signal_thread_state_change
1258 * Tells the thread that his state has changed and it has to enter the new
1259 * state as soon as possible.
1261 static void signal_thread_state_change (MonoThread *thread)
1263 if (thread == mono_thread_current ()) {
1264 /* Do it synchronously */
1265 MonoException *exc = mono_thread_request_interruption (FALSE);
1267 mono_raise_exception (exc);
1271 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1273 /* fixme: store the state somewhere */
1274 #ifdef PTHREAD_POINTER_ID
1275 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1277 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1279 #endif /* __MINGW32__ */
1283 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1285 MONO_ARCH_SAVE_REGS;
1287 mono_monitor_enter (thread->synch_lock);
1289 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1290 (thread->state & ThreadState_StopRequested) != 0)
1292 mono_monitor_exit (thread->synch_lock);
1296 thread->state |= ThreadState_AbortRequested;
1297 thread->abort_state = state;
1298 thread->abort_exc = NULL;
1300 mono_monitor_exit (thread->synch_lock);
1303 g_message (G_GNUC_PRETTY_FUNCTION
1304 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1305 thread, thread->tid);
1308 /* Make sure the thread is awake */
1309 ves_icall_System_Threading_Thread_Resume (thread);
1311 signal_thread_state_change (thread);
1315 ves_icall_System_Threading_Thread_ResetAbort (void)
1317 MonoThread *thread = mono_thread_current ();
1319 MONO_ARCH_SAVE_REGS;
1321 mono_monitor_enter (thread->synch_lock);
1323 thread->state &= ~ThreadState_AbortRequested;
1325 if (!thread->abort_exc) {
1326 const char *msg = "Unable to reset abort because no abort was requested";
1327 mono_monitor_exit (thread->synch_lock);
1328 mono_raise_exception (mono_get_exception_thread_state (msg));
1330 thread->abort_exc = NULL;
1331 thread->abort_state = NULL;
1334 mono_monitor_exit (thread->synch_lock);
1338 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1340 MONO_ARCH_SAVE_REGS;
1342 mono_monitor_enter (thread->synch_lock);
1344 if ((thread->state & ThreadState_Suspended) != 0 ||
1345 (thread->state & ThreadState_SuspendRequested) != 0 ||
1346 (thread->state & ThreadState_StopRequested) != 0)
1348 mono_monitor_exit (thread->synch_lock);
1352 thread->state |= ThreadState_SuspendRequested;
1353 mono_monitor_exit (thread->synch_lock);
1355 signal_thread_state_change (thread);
1359 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1361 MONO_ARCH_SAVE_REGS;
1363 mono_monitor_enter (thread->synch_lock);
1365 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1366 thread->state &= ~ThreadState_SuspendRequested;
1367 mono_monitor_exit (thread->synch_lock);
1371 if ((thread->state & ThreadState_Suspended) == 0)
1373 mono_monitor_exit (thread->synch_lock);
1377 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1379 /* Awake the thread */
1380 SetEvent (thread->suspend_event);
1382 mono_monitor_exit (thread->synch_lock);
1384 /* Wait for the thread to awake */
1385 WaitForSingleObject (thread->resume_event, INFINITE);
1386 CloseHandle (thread->resume_event);
1387 thread->resume_event = NULL;
1391 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1396 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1397 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1398 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1400 *((gboolean*)data) = TRUE;
1407 is_running_protected_wrapper (void)
1409 gboolean found = FALSE;
1410 mono_stack_walk (find_wrapper, &found);
1414 void mono_thread_stop (MonoThread *thread)
1416 mono_monitor_enter (thread->synch_lock);
1418 if ((thread->state & ThreadState_StopRequested) != 0 ||
1419 (thread->state & ThreadState_Stopped) != 0)
1421 mono_monitor_exit (thread->synch_lock);
1425 /* Make sure the thread is awake */
1426 ves_icall_System_Threading_Thread_Resume (thread);
1428 thread->state |= ThreadState_StopRequested;
1429 thread->state &= ~ThreadState_AbortRequested;
1431 mono_monitor_exit (thread->synch_lock);
1433 signal_thread_state_change (thread);
1437 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1439 return *((volatile gint8 *) (ptr));
1443 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1445 return *((volatile gint16 *) (ptr));
1449 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1451 return *((volatile gint32 *) (ptr));
1455 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1457 return *((volatile gint64 *) (ptr));
1461 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1463 return (void *) *((volatile void **) ptr);
1467 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1469 *((volatile gint8 *) ptr) = value;
1473 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1475 *((volatile gint16 *) ptr) = value;
1479 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1481 *((volatile gint32 *) ptr) = value;
1485 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1487 *((volatile gint64 *) ptr) = value;
1491 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1493 *((volatile void **) ptr) = value;
1496 void mono_thread_init (MonoThreadStartCB start_cb,
1497 MonoThreadAttachCB attach_cb)
1499 InitializeCriticalSection(&threads_mutex);
1500 InitializeCriticalSection(&interlocked_mutex);
1501 InitializeCriticalSection(&contexts_mutex);
1502 InitializeCriticalSection(&interruption_mutex);
1504 mono_init_static_data_info (&thread_static_info);
1505 mono_init_static_data_info (&context_static_info);
1507 current_object_key=TlsAlloc();
1509 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1510 current_object_key);
1513 mono_thread_start_cb = start_cb;
1514 mono_thread_attach_cb = attach_cb;
1516 slothash_key=TlsAlloc();
1518 /* Get a pseudo handle to the current process. This is just a
1519 * kludge so that wapi can build a process handle if needed.
1520 * As a pseudo handle is returned, we don't need to clean
1523 GetCurrentProcess ();
1527 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1529 mono_thread_cleanup = func;
1532 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1534 mono_thread_callbacks = callbacks;
1538 static void print_tids (gpointer key, gpointer value, gpointer user)
1540 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1546 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1547 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1551 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1556 g_message(G_GNUC_PRETTY_FUNCTION
1557 ": %d threads to wait for in this batch", wait->num);
1560 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1562 if(ret==WAIT_FAILED) {
1563 /* See the comment in build_wait_tids() */
1565 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1570 for(i=0; i<wait->num; i++)
1571 CloseHandle (wait->handles[i]);
1573 if (ret == WAIT_TIMEOUT)
1576 for(i=0; i<wait->num; i++) {
1577 guint32 tid=wait->threads[i]->tid;
1579 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1580 /* This thread must have been killed, because
1581 * it hasn't cleaned itself up. (It's just
1582 * possible that the thread exited before the
1583 * parent thread had a chance to store the
1584 * handle, and now there is another pointer to
1585 * the already-exited thread stored. In this
1586 * case, we'll just get two
1587 * mono_profiler_thread_end() calls for the
1592 g_message (G_GNUC_PRETTY_FUNCTION
1593 ": cleaning up after thread %d", tid);
1595 thread_cleanup (wait->threads[i]);
1600 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1602 struct wait_data *wait=(struct wait_data *)user;
1604 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1606 MonoThread *thread=(MonoThread *)value;
1608 /* Ignore background threads, we abort them later */
1609 if (thread->state & ThreadState_Background)
1610 return; /* just leave, ignore */
1612 if (mono_gc_is_finalizer_thread (thread))
1615 if (thread == mono_thread_current ())
1618 if (thread == mono_thread_get_main ())
1621 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1625 wait->handles[wait->num]=handle;
1626 wait->threads[wait->num]=thread;
1629 /* Just ignore the rest, we can't do anything with
1636 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1638 struct wait_data *wait=(struct wait_data *)user;
1639 guint32 self = GetCurrentThreadId ();
1640 MonoThread *thread = (MonoThread *) value;
1643 /* The finalizer thread is not a background thread */
1644 if (thread->tid != self && thread->state & ThreadState_Background) {
1646 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1650 wait->handles[wait->num]=thread->handle;
1651 wait->threads[wait->num]=thread;
1654 if(thread->state & ThreadState_AbortRequested ||
1655 thread->state & ThreadState_Aborted) {
1657 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1663 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1665 mono_thread_stop (thread);
1669 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1672 void mono_thread_manage (void)
1674 struct wait_data *wait=g_new0 (struct wait_data, 1);
1676 /* join each thread that's still running */
1678 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1681 EnterCriticalSection (&threads_mutex);
1684 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1686 LeaveCriticalSection (&threads_mutex);
1689 LeaveCriticalSection (&threads_mutex);
1692 EnterCriticalSection (&threads_mutex);
1694 g_message(G_GNUC_PRETTY_FUNCTION
1695 ":There are %d threads to join",
1696 mono_g_hash_table_size (threads));
1697 mono_g_hash_table_foreach (threads, print_tids, NULL);
1701 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1702 LeaveCriticalSection (&threads_mutex);
1704 /* Something to wait for */
1705 wait_for_tids (wait, INFINITE);
1707 } while(wait->num>0);
1709 mono_thread_pool_cleanup ();
1711 EnterCriticalSection(&threads_mutex);
1714 * Remove everything but the finalizer thread and self.
1715 * Also abort all the background threads
1718 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1720 LeaveCriticalSection(&threads_mutex);
1723 /* Something to wait for */
1724 wait_for_tids (wait, INFINITE);
1727 * give the subthreads a chance to really quit (this is mainly needed
1728 * to get correct user and system times from getrusage/wait/time(1)).
1729 * This could be removed if we avoid pthread_detach() and use pthread_join().
1731 #ifndef PLATFORM_WIN32
1738 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1740 MonoThread *thread=(MonoThread *)value;
1741 guint32 self=GPOINTER_TO_UINT (user);
1743 if(thread->tid!=self) {
1744 /*TerminateThread (thread->handle, -1);*/
1748 void mono_thread_abort_all_other_threads (void)
1750 guint32 self=GetCurrentThreadId ();
1752 EnterCriticalSection (&threads_mutex);
1754 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1755 mono_g_hash_table_size (threads));
1756 mono_g_hash_table_foreach (threads, print_tids, NULL);
1759 mono_g_hash_table_foreach (threads, terminate_thread,
1760 GUINT_TO_POINTER (self));
1762 LeaveCriticalSection (&threads_mutex);
1765 static void suspend_thread (gpointer key, gpointer value, gpointer user)
1767 MonoThread *thread=(MonoThread *)value;
1768 guint32 self=GPOINTER_TO_UINT (user);
1770 if ((thread->tid!=self) && !mono_gc_is_finalizer_thread (thread))
1771 SuspendThread (thread->handle);
1775 * mono_thread_suspend_all_other_threads:
1777 * Suspend all managed threads except the finalizer thread and this thread.
1779 void mono_thread_suspend_all_other_threads (void)
1781 guint32 self=GetCurrentThreadId ();
1783 EnterCriticalSection (&threads_mutex);
1784 mono_g_hash_table_foreach (threads, suspend_thread,
1785 GUINT_TO_POINTER (self));
1786 LeaveCriticalSection (&threads_mutex);
1790 * mono_thread_push_appdomain_ref:
1792 * Register that the current thread may have references to objects in domain
1793 * @domain on its stack. Each call to this function should be paired with a
1794 * call to pop_appdomain_ref.
1797 mono_thread_push_appdomain_ref (MonoDomain *domain)
1799 MonoThread *thread = mono_thread_current ();
1802 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1803 EnterCriticalSection (&threads_mutex);
1804 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1805 LeaveCriticalSection (&threads_mutex);
1810 mono_thread_pop_appdomain_ref (void)
1812 MonoThread *thread = mono_thread_current ();
1815 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1816 EnterCriticalSection (&threads_mutex);
1817 /* FIXME: How can the list be empty ? */
1818 if (thread->appdomain_refs)
1819 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1820 LeaveCriticalSection (&threads_mutex);
1825 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1828 EnterCriticalSection (&threads_mutex);
1829 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1830 LeaveCriticalSection (&threads_mutex);
1834 typedef struct abort_appdomain_data {
1835 struct wait_data wait;
1837 } abort_appdomain_data;
1840 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1842 MonoThread *thread = (MonoThread*)value;
1843 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1844 MonoDomain *domain = data->domain;
1846 if (mono_thread_has_appdomain_ref (thread, domain)) {
1847 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1848 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1852 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1854 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1855 data->wait.handles [data->wait.num] = handle;
1856 data->wait.threads [data->wait.num] = thread;
1859 /* Just ignore the rest, we can't do anything with
1867 * mono_threads_abort_appdomain_threads:
1869 * Abort threads which has references to the given appdomain.
1872 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1874 abort_appdomain_data user_data;
1877 /* printf ("ABORT BEGIN.\n"); */
1879 start_time = GetTickCount ();
1881 EnterCriticalSection (&threads_mutex);
1883 user_data.domain = domain;
1884 user_data.wait.num = 0;
1885 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1886 LeaveCriticalSection (&threads_mutex);
1888 if (user_data.wait.num > 0)
1889 wait_for_tids (&user_data.wait, timeout);
1891 /* Update remaining time */
1892 timeout -= GetTickCount () - start_time;
1893 start_time = GetTickCount ();
1898 while (user_data.wait.num > 0);
1900 /* printf ("ABORT DONE.\n"); */
1906 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1908 MonoThread *thread = (MonoThread*)value;
1909 MonoDomain *domain = (MonoDomain*)user_data;
1912 /* No locking needed here */
1914 if (thread->culture_info) {
1915 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1916 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1917 thread->culture_info [i] = NULL;
1920 if (thread->ui_culture_info) {
1921 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1922 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1923 thread->ui_culture_info [i] = NULL;
1929 * mono_threads_clear_cached_culture:
1931 * Clear the cached_current_culture from all threads if it is in the
1935 mono_threads_clear_cached_culture (MonoDomain *domain)
1937 EnterCriticalSection (&threads_mutex);
1938 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1939 LeaveCriticalSection (&threads_mutex);
1943 * mono_thread_get_pending_exception:
1945 * Return an exception which needs to be raised when leaving a catch clause.
1946 * This is used for undeniable exception propagation.
1949 mono_thread_get_pending_exception (void)
1951 MonoThread *thread = mono_thread_current ();
1953 MONO_ARCH_SAVE_REGS;
1955 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1957 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1958 * exception if the thread no longer references a dying appdomain.
1960 thread->abort_exc->trace_ips = NULL;
1961 thread->abort_exc->stack_trace = NULL;
1962 return thread->abort_exc;
1968 #define NUM_STATIC_DATA_IDX 8
1969 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1970 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1975 * mono_alloc_static_data
1977 * Allocate memory blocks for storing threads or context static data
1980 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1982 guint idx = (offset >> 24) - 1;
1985 gpointer* static_data = *static_data_ptr;
1987 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
1988 *static_data_ptr = static_data;
1989 static_data [0] = static_data;
1992 for (i = 1; i <= idx; ++i) {
1993 if (static_data [i])
1995 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2000 * mono_init_static_data_info
2002 * Initializes static data counters
2004 static void mono_init_static_data_info (StaticDataInfo *static_data)
2006 static_data->idx = 0;
2007 static_data->offset = 0;
2011 * mono_alloc_static_data_slot
2013 * Generates an offset for static data. static_data contains the counters
2014 * used to generate it.
2017 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2021 if (!static_data->idx && !static_data->offset) {
2023 * we use the first chunk of the first allocation also as
2024 * an array for the rest of the data
2026 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2028 static_data->offset += align - 1;
2029 static_data->offset &= ~(align - 1);
2030 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2031 static_data->idx ++;
2032 g_assert (size <= static_data_size [static_data->idx]);
2034 * massive unloading and reloading of domains with thread-static
2035 * data may eventually exceed the allocated storage...
2036 * Need to check what the MS runtime does in that case.
2037 * Note that for each appdomain, we need to allocate a separate
2038 * thread data slot for security reasons. We could keep track
2039 * of the slots per-domain and when the domain is unloaded
2040 * out the slots on a sort of free list.
2042 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2043 static_data->offset = 0;
2045 offset = static_data->offset | ((static_data->idx + 1) << 24);
2046 static_data->offset += size;
2051 * ensure thread static fields already allocated are valid for thread
2052 * This function is called when a thread is created or on thread attach.
2055 thread_adjust_static_data (MonoThread *thread)
2059 EnterCriticalSection (&threads_mutex);
2060 if (thread_static_info.offset || thread_static_info.idx > 0) {
2061 /* get the current allocated size */
2062 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2063 mono_alloc_static_data (&(thread->static_data), offset);
2065 LeaveCriticalSection (&threads_mutex);
2069 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2071 MonoThread *thread = value;
2072 guint32 offset = GPOINTER_TO_UINT (user);
2074 mono_alloc_static_data (&(thread->static_data), offset);
2078 * The offset for a special static variable is composed of three parts:
2079 * a bit that indicates the type of static data (0:thread, 1:context),
2080 * an index in the array of chunks of memory for the thread (thread->static_data)
2081 * and an offset in that chunk of mem. This allows allocating less memory in the
2086 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2089 if (static_type == SPECIAL_STATIC_THREAD)
2091 EnterCriticalSection (&threads_mutex);
2092 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2093 /* This can be called during startup */
2094 if (threads != NULL)
2095 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2096 LeaveCriticalSection (&threads_mutex);
2100 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2101 EnterCriticalSection (&contexts_mutex);
2102 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2103 LeaveCriticalSection (&contexts_mutex);
2104 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2110 mono_get_special_static_data (guint32 offset)
2112 /* The high bit means either thread (0) or static (1) data. */
2114 guint32 static_type = (offset & 0x80000000);
2117 offset &= 0x7fffffff;
2118 idx = (offset >> 24) - 1;
2120 if (static_type == 0)
2122 MonoThread *thread = mono_thread_current ();
2123 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2127 /* Allocate static data block under demand, since we don't have a list
2130 MonoAppContext *context = mono_context_get ();
2131 if (!context->static_data || !context->static_data [idx]) {
2132 EnterCriticalSection (&contexts_mutex);
2133 mono_alloc_static_data (&(context->static_data), offset);
2134 LeaveCriticalSection (&contexts_mutex);
2136 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2140 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2142 MonoThread *thread=(MonoThread *)value;
2143 guint32 self=GPOINTER_TO_UINT (user);
2146 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2149 if(thread->tid==self)
2152 SuspendThread (thread->handle);
2155 void mono_gc_stop_world (void)
2157 guint32 self=GetCurrentThreadId ();
2160 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2163 EnterCriticalSection (&threads_mutex);
2165 if (threads != NULL)
2166 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2168 LeaveCriticalSection (&threads_mutex);
2171 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2173 MonoThread *thread=(MonoThread *)value;
2174 guint32 self=GPOINTER_TO_UINT (user);
2177 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2180 if(thread->tid==self)
2183 ResumeThread (thread->handle);
2186 void mono_gc_start_world (void)
2188 guint32 self=GetCurrentThreadId ();
2191 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2194 EnterCriticalSection (&threads_mutex);
2196 if (threads != NULL)
2197 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2199 LeaveCriticalSection (&threads_mutex);
2203 static CALLBACK void dummy_apc (ULONG_PTR param)
2207 static guint32 dummy_apc (gpointer param)
2214 * mono_thread_execute_interruption
2216 * Performs the operation that the requested thread state requires (abort,
2219 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2221 mono_monitor_enter (thread->synch_lock);
2223 if (thread->interruption_requested) {
2224 /* this will consume pending APC calls */
2225 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2226 EnterCriticalSection (&interruption_mutex);
2227 thread_interruption_requested--;
2228 LeaveCriticalSection (&interruption_mutex);
2229 thread->interruption_requested = FALSE;
2232 if ((thread->state & ThreadState_AbortRequested) != 0) {
2233 if (thread->abort_exc == NULL)
2234 thread->abort_exc = mono_get_exception_thread_abort ();
2235 mono_monitor_exit (thread->synch_lock);
2236 return thread->abort_exc;
2238 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2239 thread->state &= ~ThreadState_SuspendRequested;
2240 thread->state |= ThreadState_Suspended;
2241 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2242 mono_monitor_exit (thread->synch_lock);
2244 WaitForSingleObject (thread->suspend_event, INFINITE);
2246 mono_monitor_enter (thread->synch_lock);
2247 CloseHandle (thread->suspend_event);
2248 thread->suspend_event = NULL;
2249 thread->state &= ~ThreadState_Suspended;
2251 /* The thread that requested the resume will have replaced this event
2252 * and will be waiting for it
2254 SetEvent (thread->resume_event);
2255 mono_monitor_exit (thread->synch_lock);
2258 else if ((thread->state & ThreadState_StopRequested) != 0) {
2259 /* FIXME: do this through the JIT? */
2260 mono_monitor_exit (thread->synch_lock);
2261 mono_thread_exit ();
2265 mono_monitor_exit (thread->synch_lock);
2270 * mono_thread_request_interruption
2272 * A signal handler can call this method to request the interruption of a
2273 * thread. The result of the interruption will depend on the current state of
2274 * the thread. If the result is an exception that needs to be throw, it is
2275 * provided as return value.
2277 MonoException* mono_thread_request_interruption (gboolean running_managed)
2279 MonoThread *thread = mono_thread_current ();
2281 /* The thread may already be stopping */
2285 mono_monitor_enter (thread->synch_lock);
2287 if (thread->interruption_requested) {
2288 mono_monitor_exit (thread->synch_lock);
2292 if (!running_managed || is_running_protected_wrapper ()) {
2293 /* Can't stop while in unmanaged code. Increase the global interruption
2294 request count. When exiting the unmanaged method the count will be
2295 checked and the thread will be interrupted. */
2297 EnterCriticalSection (&interruption_mutex);
2298 thread_interruption_requested++;
2299 LeaveCriticalSection (&interruption_mutex);
2301 thread->interruption_requested = TRUE;
2302 mono_monitor_exit (thread->synch_lock);
2304 /* this will awake the thread if it is in WaitForSingleObject
2306 QueueUserAPC (dummy_apc, thread->handle, NULL);
2311 mono_monitor_exit (thread->synch_lock);
2312 return mono_thread_execute_interruption (thread);
2316 gboolean mono_thread_interruption_requested ()
2318 if (thread_interruption_requested) {
2319 MonoThread *thread = mono_thread_current ();
2320 /* The thread may already be stopping */
2322 return (thread->interruption_requested);
2327 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2329 MonoThread *thread = mono_thread_current ();
2331 /* The thread may already be stopping */
2335 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2336 MonoException* exc = mono_thread_execute_interruption (thread);
2337 if (exc) mono_raise_exception (exc);
2342 * Performs the interruption of the current thread, if one has been requested,
2343 * and the thread is not running a protected wrapper.
2345 void mono_thread_interruption_checkpoint ()
2347 mono_thread_interruption_checkpoint_request (FALSE);
2351 * Performs the interruption of the current thread, if one has been requested.
2353 void mono_thread_force_interruption_checkpoint ()
2355 mono_thread_interruption_checkpoint_request (TRUE);
2359 * mono_thread_interruption_request_flag:
2361 * Returns the address of a flag that will be non-zero if an interruption has
2362 * been requested for a thread. The thread to interrupt may not be the current
2363 * thread, so an additional call to mono_thread_interruption_requested() or
2364 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2367 gint32* mono_thread_interruption_request_flag ()
2369 return &thread_interruption_requested;
2372 #ifdef WITH_INCLUDED_LIBGC
2374 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2376 MonoThread *thread=(MonoThread *)value;
2377 guint32 *selfp=(guint32 *)user, self = *selfp;
2380 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2383 if(thread->tid==self) {
2385 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2387 GC_push_all_stack (selfp, thread->stack_ptr);
2391 #ifdef PLATFORM_WIN32
2392 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2394 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2398 void mono_gc_push_all_stacks (void)
2400 guint32 self=GetCurrentThreadId ();
2403 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2406 EnterCriticalSection (&threads_mutex);
2408 if (threads != NULL)
2409 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2411 LeaveCriticalSection (&threads_mutex);
2414 #endif /* WITH_INCLUDED_LIBGC */