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 #ifndef HAVE_BOEHM_GC
209 if (thread->culture_info)
210 g_free (thread->culture_info);
211 if (thread->ui_culture_info)
212 g_free (thread->ui_culture_info);
215 if (mono_thread_cleanup)
216 mono_thread_cleanup (thread);
219 static guint32 start_wrapper(void *data)
221 struct StartInfo *start_info=(struct StartInfo *)data;
222 guint32 (*start_func)(void *);
225 MonoThread *thread=start_info->obj;
226 MonoObject *start_delegate = start_info->delegate;
229 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
230 GetCurrentThreadId ());
233 /* We can be sure start_info->obj->tid and
234 * start_info->obj->handle have been set, because the thread
235 * was created suspended, and these values were set before the
241 SET_CURRENT_OBJECT (thread);
243 if (!mono_domain_set (start_info->domain, FALSE)) {
244 /* No point in raising an appdomain_unloaded exception here */
245 /* FIXME: Cleanup here */
249 start_func = start_info->func;
250 start_arg = start_info->start_arg;
252 /* This MUST be called before any managed code can be
253 * executed, as it calls the callback function that (for the
254 * jit) sets the lmf marker.
256 mono_thread_new_init (tid, &tid, start_func);
257 thread->stack_ptr = &tid;
260 g_message (G_GNUC_PRETTY_FUNCTION
261 ": (%d,%d) Setting thread stack to %p",
262 GetCurrentThreadId (), getpid (), thread->stack_ptr);
266 g_message (G_GNUC_PRETTY_FUNCTION
267 ": (%d) Setting current_object_key to %p",
268 GetCurrentThreadId (), thread);
271 mono_profiler_thread_start (tid);
273 if(thread->start_notify!=NULL) {
274 /* Let the thread that called Start() know we're
277 ReleaseSemaphore (thread->start_notify, 1, NULL);
282 /* Every thread references the appdomain which created it */
283 mono_thread_push_appdomain_ref (mono_domain_get ());
285 thread_adjust_static_data (thread);
287 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
290 /* start_func is set only for unamanged start functions */
292 start_func (start_arg);
295 g_assert (start_delegate != NULL);
296 args [0] = start_arg;
297 /* we may want to handle the exception here. See comment below on unhandled exceptions */
298 mono_runtime_delegate_invoke (start_delegate, args, NULL);
300 #ifdef PLATFORM_WIN32
301 /* If the thread calls ExitThread at all, this remaining code
302 * will not be executed, but the main thread will eventually
303 * call thread_cleanup() on this thread's behalf.
307 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
308 GetCurrentThreadId ());
311 /* Remove the reference to the thread object in the TLS data,
312 * so the thread object can be finalized. This won't be
313 * reached if the thread threw an uncaught exception, so those
314 * thread handles will stay referenced :-( (This is due to
315 * missing support for scanning thread-specific data in the
316 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
319 SET_CURRENT_OBJECT (NULL);
322 thread_cleanup (thread);
327 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
329 if (mono_thread_start_cb) {
330 mono_thread_start_cb (tid, stack_start, func);
333 if (mono_thread_callbacks)
334 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
337 void mono_threads_set_default_stacksize (guint32 stacksize)
339 default_stacksize = stacksize;
342 guint32 mono_threads_get_default_stacksize (void)
344 return default_stacksize;
347 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
350 HANDLE thread_handle;
351 struct StartInfo *start_info;
354 thread=(MonoThread *)mono_object_new (domain,
355 mono_defaults.thread_class);
357 start_info=g_new0 (struct StartInfo, 1);
358 start_info->func = func;
359 start_info->obj = thread;
360 start_info->domain = domain;
361 start_info->start_arg = arg;
363 /* Create suspended, so we can do some housekeeping before the thread
366 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
367 thread_handle = GC_CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
368 CREATE_SUSPENDED, &tid);
370 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
371 CREATE_SUSPENDED, &tid);
374 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
377 g_assert (thread_handle);
379 thread->handle=thread_handle;
382 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
384 handle_store(thread);
386 ResumeThread (thread_handle);
390 mono_thread_attach (MonoDomain *domain)
393 HANDLE thread_handle;
396 if ((thread = mono_thread_current ())) {
397 /* Already attached */
401 thread = (MonoThread *)mono_object_new (domain,
402 mono_defaults.thread_class);
404 thread_handle = GetCurrentThread ();
405 g_assert (thread_handle);
407 tid=GetCurrentThreadId ();
409 #ifdef PLATFORM_WIN32
411 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
412 * refer to the thread from other threads for things like aborting.
414 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
415 THREAD_ALL_ACCESS, TRUE, 0);
418 thread->handle=thread_handle;
420 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
423 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
427 handle_store(thread);
430 g_message (G_GNUC_PRETTY_FUNCTION
431 ": (%d) Setting current_object_key to %p",
432 GetCurrentThreadId (), thread);
435 SET_CURRENT_OBJECT (thread);
436 mono_domain_set (domain, TRUE);
438 thread_adjust_static_data (thread);
440 if (mono_thread_attach_cb) {
441 mono_thread_attach_cb (tid, &tid);
448 mono_thread_detach (MonoThread *thread)
450 g_return_if_fail (thread != NULL);
453 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
455 SET_CURRENT_OBJECT (NULL);
457 thread_cleanup (thread);
463 MonoThread *thread = mono_thread_current ();
465 SET_CURRENT_OBJECT (NULL);
466 thread_cleanup (thread);
468 /* we could add a callback here for embedders to use. */
469 if (thread == mono_thread_get_main ())
470 exit (mono_environment_exitcode_get ());
474 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
477 guint32 (*start_func)(void *);
478 struct StartInfo *start_info;
486 g_message(G_GNUC_PRETTY_FUNCTION
487 ": Trying to start a new thread: this (%p) start (%p)",
491 /* FIXME: remove the code inside BROKEN_THREAD_START once martin gets rid of the
492 * thread_start_compile_func stuff.
494 #define BROKEN_THREAD_START
495 #ifdef BROKEN_THREAD_START
496 im = mono_get_delegate_invoke (start->vtable->klass);
497 im = mono_marshal_get_delegate_invoke (im);
498 if (mono_thread_callbacks)
499 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
501 start_func = mono_compile_method (im);
503 if(start_func==NULL) {
504 g_warning(G_GNUC_PRETTY_FUNCTION
505 ": Can't locate start method!");
512 /* This is freed in start_wrapper */
513 start_info = g_new0 (struct StartInfo, 1);
514 start_info->func = start_func;
515 #ifdef BROKEN_THREAD_START
516 start_info->start_arg = start;
518 start_info->start_arg = this->start_obj;
520 start_info->delegate = start;
521 start_info->obj = this;
522 start_info->domain = mono_domain_get ();
524 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
525 if(this->start_notify==NULL) {
526 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
530 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
531 thread=GC_CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
532 CREATE_SUSPENDED, &tid);
534 thread=CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
535 CREATE_SUSPENDED, &tid);
538 g_warning(G_GNUC_PRETTY_FUNCTION
539 ": CreateThread error 0x%x", GetLastError());
546 /* Don't call handle_store() here, delay it to Start.
547 * We can't join a thread (trying to will just block
548 * forever) until it actually starts running, so don't
549 * store the handle till then.
553 g_message(G_GNUC_PRETTY_FUNCTION
554 ": Started thread ID %d (handle %p)", tid, thread);
561 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
567 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
571 CloseHandle (thread);
574 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
580 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
581 GetCurrentThreadId (), this, this->tid);
584 /* Only store the handle when the thread is about to be
585 * launched, to avoid the main thread deadlocking while trying
586 * to clean up a thread that will never be signalled.
590 if (mono_thread_callbacks)
591 (* mono_thread_callbacks->start_resume) (this->tid);
593 ResumeThread(thread);
595 if (mono_thread_callbacks)
596 (* mono_thread_callbacks->end_resume) (this->tid);
598 if(this->start_notify!=NULL) {
599 /* Wait for the thread to set up its TLS data etc, so
600 * theres no potential race condition if someone tries
601 * to look up the data believing the thread has
606 g_message(G_GNUC_PRETTY_FUNCTION
607 ": (%d) waiting for thread %p (%d) to start",
608 GetCurrentThreadId (), this, this->tid);
611 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
612 CloseHandle (this->start_notify);
613 this->start_notify=NULL;
617 g_message(G_GNUC_PRETTY_FUNCTION
618 ": (%d) Done launching thread %p (%d)",
619 GetCurrentThreadId (), this, this->tid);
623 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
625 MonoThread *thread = mono_thread_current ();
630 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
633 mono_monitor_enter (thread->synch_lock);
634 thread->state |= ThreadState_WaitSleepJoin;
635 mono_monitor_exit (thread->synch_lock);
639 mono_monitor_enter (thread->synch_lock);
640 thread->state &= ~ThreadState_WaitSleepJoin;
641 mono_monitor_exit (thread->synch_lock);
645 ves_icall_System_Threading_Thread_GetDomainID (void)
649 return mono_domain_get()->domain_id;
653 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
658 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
662 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
665 g_free (this_obj->name);
667 this_obj->name = g_new (gunichar2, mono_string_length (name));
668 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
669 this_obj->name_len = mono_string_length (name);
672 this_obj->name = NULL;
676 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
682 /* No need to lock here */
683 if (this->culture_info) {
684 domain = mono_domain_get ();
685 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
686 res = this->culture_info [i];
687 if (res && res->vtable->domain == domain)
696 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
700 mono_monitor_enter (this->synch_lock);
701 if (this->serialized_culture_info) {
702 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
703 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
707 mono_monitor_exit (this->synch_lock);
713 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
716 MonoDomain *domain = mono_domain_get ();
718 mono_monitor_enter (this->synch_lock);
719 if (!this->culture_info) {
721 this->culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
723 this->culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
727 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
728 if (this->culture_info [i]) {
729 if (this->culture_info [i]->vtable->domain == domain)
737 if (i < NUM_CACHED_CULTURES)
738 this->culture_info [i] = culture;
739 mono_monitor_exit (this->synch_lock);
743 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
745 mono_monitor_enter (this->synch_lock);
746 if (this->serialized_culture_info)
747 g_free (this->serialized_culture_info);
748 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
749 this->serialized_culture_info_len = mono_array_length (arr);
750 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
751 mono_monitor_exit (this->synch_lock);
756 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
762 /* No need to lock here */
763 if (this->ui_culture_info) {
764 domain = mono_domain_get ();
765 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
766 res = this->ui_culture_info [i];
767 if (res && res->vtable->domain == domain)
776 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
780 mono_monitor_enter (this->synch_lock);
781 if (this->serialized_ui_culture_info) {
782 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
783 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
787 mono_monitor_exit (this->synch_lock);
793 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
796 MonoDomain *domain = mono_domain_get ();
798 mono_monitor_enter (this->synch_lock);
799 if (!this->ui_culture_info) {
801 this->ui_culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
803 this->ui_culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
807 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
808 if (this->ui_culture_info [i]) {
809 if (this->ui_culture_info [i]->vtable->domain == domain)
817 if (i < NUM_CACHED_CULTURES)
818 this->ui_culture_info [i] = culture;
819 mono_monitor_exit (this->synch_lock);
823 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
825 mono_monitor_enter (this->synch_lock);
826 if (this->serialized_ui_culture_info)
827 g_free (this->serialized_ui_culture_info);
828 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
829 this->serialized_ui_culture_info_len = mono_array_length (arr);
830 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
831 mono_monitor_exit (this->synch_lock);
834 /* the jit may read the compiled code of this function */
836 mono_thread_current (void)
841 thread = GET_CURRENT_OBJECT ();
842 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
846 return GET_CURRENT_OBJECT ();
850 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
851 int ms, HANDLE thread)
857 mono_monitor_enter (this->synch_lock);
858 this->state |= ThreadState_WaitSleepJoin;
859 mono_monitor_exit (this->synch_lock);
865 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
869 ret=WaitForSingleObjectEx (thread, ms, TRUE);
871 mono_monitor_enter (this->synch_lock);
872 this->state &= ~ThreadState_WaitSleepJoin;
873 mono_monitor_exit (this->synch_lock);
875 if(ret==WAIT_OBJECT_0) {
877 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
884 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
890 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
895 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
898 /* Object location stored here */
899 TlsSetValue(slothash_key, data);
902 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
908 data=TlsGetValue(slothash_key);
911 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
917 /* FIXME: exitContext isnt documented */
918 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
924 MonoObject *waitHandle;
926 MonoThread *thread = mono_thread_current ();
930 numhandles = mono_array_length(mono_handles);
931 handles = g_new0(HANDLE, numhandles);
933 if (wait_handle_os_handle_field == 0) {
934 /* Get the field os_handle which will contain the actual handle */
935 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
936 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
939 for(i = 0; i < numhandles; i++) {
940 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
941 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
948 mono_monitor_enter (thread->synch_lock);
949 thread->state |= ThreadState_WaitSleepJoin;
950 mono_monitor_exit (thread->synch_lock);
952 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
954 mono_monitor_enter (thread->synch_lock);
955 thread->state &= ~ThreadState_WaitSleepJoin;
956 mono_monitor_exit (thread->synch_lock);
960 if(ret==WAIT_FAILED) {
961 #ifdef THREAD_WAIT_DEBUG
962 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
963 GetCurrentThreadId ());
966 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
967 /* Do we want to try again if we get
968 * WAIT_IO_COMPLETION? The documentation for
969 * WaitHandle doesn't give any clues. (We'd have to
970 * fiddle with the timeout if we retry.)
972 #ifdef THREAD_WAIT_DEBUG
973 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
974 GetCurrentThreadId ());
982 /* FIXME: exitContext isnt documented */
983 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
989 MonoObject *waitHandle;
991 MonoThread *thread = mono_thread_current ();
995 numhandles = mono_array_length(mono_handles);
996 handles = g_new0(HANDLE, numhandles);
998 if (wait_handle_os_handle_field == 0) {
999 /* Get the field os_handle which will contain the actual handle */
1000 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
1001 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
1004 for(i = 0; i < numhandles; i++) {
1005 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1006 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
1013 mono_monitor_enter (thread->synch_lock);
1014 thread->state |= ThreadState_WaitSleepJoin;
1015 mono_monitor_exit (thread->synch_lock);
1017 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1019 mono_monitor_enter (thread->synch_lock);
1020 thread->state &= ~ThreadState_WaitSleepJoin;
1021 mono_monitor_exit (thread->synch_lock);
1025 #ifdef THREAD_WAIT_DEBUG
1026 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
1027 GetCurrentThreadId (), ret);
1031 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1033 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1034 return ret - WAIT_OBJECT_0;
1036 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1037 return ret - WAIT_ABANDONED_0;
1044 /* FIXME: exitContext isnt documented */
1045 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1048 MonoThread *thread = mono_thread_current ();
1050 MONO_ARCH_SAVE_REGS;
1052 #ifdef THREAD_WAIT_DEBUG
1053 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
1054 GetCurrentThreadId (), handle, ms);
1061 mono_monitor_enter (thread->synch_lock);
1062 thread->state |= ThreadState_WaitSleepJoin;
1063 mono_monitor_exit (thread->synch_lock);
1065 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1067 mono_monitor_enter (thread->synch_lock);
1068 thread->state &= ~ThreadState_WaitSleepJoin;
1069 mono_monitor_exit (thread->synch_lock);
1071 if(ret==WAIT_FAILED) {
1072 #ifdef THREAD_WAIT_DEBUG
1073 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1074 GetCurrentThreadId ());
1077 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1078 /* Do we want to try again if we get
1079 * WAIT_IO_COMPLETION? The documentation for
1080 * WaitHandle doesn't give any clues. (We'd have to
1081 * fiddle with the timeout if we retry.)
1083 #ifdef THREAD_WAIT_DEBUG
1084 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1085 GetCurrentThreadId ());
1093 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1097 MONO_ARCH_SAVE_REGS;
1102 mutex = CreateMutex (NULL, owned, NULL);
1104 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1106 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1114 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1115 MONO_ARCH_SAVE_REGS;
1117 ReleaseMutex(handle);
1120 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1121 MONO_ARCH_SAVE_REGS;
1123 return(CreateEvent (NULL, manual, initial,
1124 name==NULL?NULL:mono_string_chars (name)));
1127 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1128 MONO_ARCH_SAVE_REGS;
1130 return (SetEvent(handle));
1133 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1134 MONO_ARCH_SAVE_REGS;
1136 return (ResetEvent(handle));
1140 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1141 MONO_ARCH_SAVE_REGS;
1143 CloseHandle (handle);
1146 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1148 MONO_ARCH_SAVE_REGS;
1150 return InterlockedIncrement (location);
1153 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1157 MONO_ARCH_SAVE_REGS;
1159 EnterCriticalSection(&interlocked_mutex);
1163 LeaveCriticalSection(&interlocked_mutex);
1169 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1171 MONO_ARCH_SAVE_REGS;
1173 return InterlockedDecrement(location);
1176 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1180 MONO_ARCH_SAVE_REGS;
1182 EnterCriticalSection(&interlocked_mutex);
1186 LeaveCriticalSection(&interlocked_mutex);
1191 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1193 MONO_ARCH_SAVE_REGS;
1195 return InterlockedExchange(location1, value);
1198 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1200 MONO_ARCH_SAVE_REGS;
1202 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1205 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1207 IntFloatUnion val, ret;
1209 MONO_ARCH_SAVE_REGS;
1212 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1217 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1219 MONO_ARCH_SAVE_REGS;
1221 return InterlockedCompareExchange(location1, value, comparand);
1224 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1226 MONO_ARCH_SAVE_REGS;
1228 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1231 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1233 IntFloatUnion val, ret, cmp;
1235 MONO_ARCH_SAVE_REGS;
1238 cmp.fval = comparand;
1239 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1245 mono_thread_get_abort_signal (void)
1255 #endif /* __MINGW32__ */
1259 static CALLBACK void interruption_request_apc (ULONG_PTR param)
1261 MonoException* exc = mono_thread_request_interruption (FALSE);
1262 if (exc) mono_raise_exception (exc);
1265 #endif /* __MINGW32__ */
1268 * signal_thread_state_change
1270 * Tells the thread that his state has changed and it has to enter the new
1271 * state as soon as possible.
1273 static void signal_thread_state_change (MonoThread *thread)
1275 if (thread == mono_thread_current ()) {
1276 /* Do it synchronously */
1277 MonoException *exc = mono_thread_request_interruption (FALSE);
1279 mono_raise_exception (exc);
1283 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1285 /* fixme: store the state somewhere */
1286 #ifdef PTHREAD_POINTER_ID
1287 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1289 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1291 #endif /* __MINGW32__ */
1295 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1297 MONO_ARCH_SAVE_REGS;
1299 mono_monitor_enter (thread->synch_lock);
1301 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1302 (thread->state & ThreadState_StopRequested) != 0)
1304 mono_monitor_exit (thread->synch_lock);
1308 thread->state |= ThreadState_AbortRequested;
1309 thread->abort_state = state;
1310 thread->abort_exc = NULL;
1312 mono_monitor_exit (thread->synch_lock);
1315 g_message (G_GNUC_PRETTY_FUNCTION
1316 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1317 thread, thread->tid);
1320 /* Make sure the thread is awake */
1321 ves_icall_System_Threading_Thread_Resume (thread);
1323 signal_thread_state_change (thread);
1327 ves_icall_System_Threading_Thread_ResetAbort (void)
1329 MonoThread *thread = mono_thread_current ();
1331 MONO_ARCH_SAVE_REGS;
1333 mono_monitor_enter (thread->synch_lock);
1335 thread->state &= ~ThreadState_AbortRequested;
1337 if (!thread->abort_exc) {
1338 const char *msg = "Unable to reset abort because no abort was requested";
1339 mono_monitor_exit (thread->synch_lock);
1340 mono_raise_exception (mono_get_exception_thread_state (msg));
1342 thread->abort_exc = NULL;
1343 thread->abort_state = NULL;
1346 mono_monitor_exit (thread->synch_lock);
1350 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1352 MONO_ARCH_SAVE_REGS;
1354 mono_monitor_enter (thread->synch_lock);
1356 if ((thread->state & ThreadState_Suspended) != 0 ||
1357 (thread->state & ThreadState_SuspendRequested) != 0 ||
1358 (thread->state & ThreadState_StopRequested) != 0)
1360 mono_monitor_exit (thread->synch_lock);
1364 thread->state |= ThreadState_SuspendRequested;
1365 mono_monitor_exit (thread->synch_lock);
1367 signal_thread_state_change (thread);
1371 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1373 MONO_ARCH_SAVE_REGS;
1375 mono_monitor_enter (thread->synch_lock);
1377 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1378 thread->state &= ~ThreadState_SuspendRequested;
1379 mono_monitor_exit (thread->synch_lock);
1383 if ((thread->state & ThreadState_Suspended) == 0)
1385 mono_monitor_exit (thread->synch_lock);
1389 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1391 /* Awake the thread */
1392 SetEvent (thread->suspend_event);
1394 mono_monitor_exit (thread->synch_lock);
1396 /* Wait for the thread to awake */
1397 WaitForSingleObject (thread->resume_event, INFINITE);
1398 CloseHandle (thread->resume_event);
1399 thread->resume_event = NULL;
1403 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1408 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1409 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1410 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1412 *((gboolean*)data) = TRUE;
1419 is_running_protected_wrapper (void)
1421 gboolean found = FALSE;
1422 mono_stack_walk (find_wrapper, &found);
1426 void mono_thread_stop (MonoThread *thread)
1428 mono_monitor_enter (thread->synch_lock);
1430 if ((thread->state & ThreadState_StopRequested) != 0 ||
1431 (thread->state & ThreadState_Stopped) != 0)
1433 mono_monitor_exit (thread->synch_lock);
1437 /* Make sure the thread is awake */
1438 ves_icall_System_Threading_Thread_Resume (thread);
1440 thread->state |= ThreadState_StopRequested;
1441 thread->state &= ~ThreadState_AbortRequested;
1443 mono_monitor_exit (thread->synch_lock);
1445 signal_thread_state_change (thread);
1449 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1451 return *((volatile gint8 *) (ptr));
1455 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1457 return *((volatile gint16 *) (ptr));
1461 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1463 return *((volatile gint32 *) (ptr));
1467 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1469 return *((volatile gint64 *) (ptr));
1473 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1475 return (void *) *((volatile void **) ptr);
1479 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1481 *((volatile gint8 *) ptr) = value;
1485 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1487 *((volatile gint16 *) ptr) = value;
1491 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1493 *((volatile gint32 *) ptr) = value;
1497 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1499 *((volatile gint64 *) ptr) = value;
1503 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1505 *((volatile void **) ptr) = value;
1508 void mono_thread_init (MonoThreadStartCB start_cb,
1509 MonoThreadAttachCB attach_cb)
1511 InitializeCriticalSection(&threads_mutex);
1512 InitializeCriticalSection(&interlocked_mutex);
1513 InitializeCriticalSection(&contexts_mutex);
1514 InitializeCriticalSection(&interruption_mutex);
1516 mono_init_static_data_info (&thread_static_info);
1517 mono_init_static_data_info (&context_static_info);
1519 current_object_key=TlsAlloc();
1521 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1522 current_object_key);
1525 mono_thread_start_cb = start_cb;
1526 mono_thread_attach_cb = attach_cb;
1528 slothash_key=TlsAlloc();
1530 /* Get a pseudo handle to the current process. This is just a
1531 * kludge so that wapi can build a process handle if needed.
1532 * As a pseudo handle is returned, we don't need to clean
1535 GetCurrentProcess ();
1539 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1541 mono_thread_cleanup = func;
1544 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1546 mono_thread_callbacks = callbacks;
1550 static void print_tids (gpointer key, gpointer value, gpointer user)
1552 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1558 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1559 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1563 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1568 g_message(G_GNUC_PRETTY_FUNCTION
1569 ": %d threads to wait for in this batch", wait->num);
1572 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1574 if(ret==WAIT_FAILED) {
1575 /* See the comment in build_wait_tids() */
1577 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1582 for(i=0; i<wait->num; i++)
1583 CloseHandle (wait->handles[i]);
1585 if (ret == WAIT_TIMEOUT)
1588 for(i=0; i<wait->num; i++) {
1589 guint32 tid=wait->threads[i]->tid;
1591 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1592 /* This thread must have been killed, because
1593 * it hasn't cleaned itself up. (It's just
1594 * possible that the thread exited before the
1595 * parent thread had a chance to store the
1596 * handle, and now there is another pointer to
1597 * the already-exited thread stored. In this
1598 * case, we'll just get two
1599 * mono_profiler_thread_end() calls for the
1604 g_message (G_GNUC_PRETTY_FUNCTION
1605 ": cleaning up after thread %d", tid);
1607 thread_cleanup (wait->threads[i]);
1612 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1614 struct wait_data *wait=(struct wait_data *)user;
1616 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1618 MonoThread *thread=(MonoThread *)value;
1620 /* Ignore background threads, we abort them later */
1621 if (thread->state & ThreadState_Background)
1622 return; /* just leave, ignore */
1624 if (mono_gc_is_finalizer_thread (thread))
1627 if (thread == mono_thread_current ())
1630 if (thread == mono_thread_get_main ())
1633 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1637 wait->handles[wait->num]=handle;
1638 wait->threads[wait->num]=thread;
1641 /* Just ignore the rest, we can't do anything with
1648 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1650 struct wait_data *wait=(struct wait_data *)user;
1651 guint32 self = GetCurrentThreadId ();
1652 MonoThread *thread = (MonoThread *) value;
1655 /* The finalizer thread is not a background thread */
1656 if (thread->tid != self && thread->state & ThreadState_Background) {
1658 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1662 wait->handles[wait->num]=thread->handle;
1663 wait->threads[wait->num]=thread;
1666 if(thread->state & ThreadState_AbortRequested ||
1667 thread->state & ThreadState_Aborted) {
1669 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1675 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1677 mono_thread_stop (thread);
1681 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1684 void mono_thread_manage (void)
1686 struct wait_data *wait=g_new0 (struct wait_data, 1);
1688 /* join each thread that's still running */
1690 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1693 EnterCriticalSection (&threads_mutex);
1696 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1698 LeaveCriticalSection (&threads_mutex);
1701 LeaveCriticalSection (&threads_mutex);
1704 EnterCriticalSection (&threads_mutex);
1706 g_message(G_GNUC_PRETTY_FUNCTION
1707 ":There are %d threads to join",
1708 mono_g_hash_table_size (threads));
1709 mono_g_hash_table_foreach (threads, print_tids, NULL);
1713 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1714 LeaveCriticalSection (&threads_mutex);
1716 /* Something to wait for */
1717 wait_for_tids (wait, INFINITE);
1719 } while(wait->num>0);
1721 mono_thread_pool_cleanup ();
1723 EnterCriticalSection(&threads_mutex);
1726 * Remove everything but the finalizer thread and self.
1727 * Also abort all the background threads
1730 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1732 LeaveCriticalSection(&threads_mutex);
1735 /* Something to wait for */
1736 wait_for_tids (wait, INFINITE);
1739 * give the subthreads a chance to really quit (this is mainly needed
1740 * to get correct user and system times from getrusage/wait/time(1)).
1741 * This could be removed if we avoid pthread_detach() and use pthread_join().
1743 #ifndef PLATFORM_WIN32
1750 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1752 MonoThread *thread=(MonoThread *)value;
1753 guint32 self=GPOINTER_TO_UINT (user);
1755 if(thread->tid!=self) {
1756 /*TerminateThread (thread->handle, -1);*/
1760 void mono_thread_abort_all_other_threads (void)
1762 guint32 self=GetCurrentThreadId ();
1764 EnterCriticalSection (&threads_mutex);
1766 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1767 mono_g_hash_table_size (threads));
1768 mono_g_hash_table_foreach (threads, print_tids, NULL);
1771 mono_g_hash_table_foreach (threads, terminate_thread,
1772 GUINT_TO_POINTER (self));
1774 LeaveCriticalSection (&threads_mutex);
1777 static void suspend_thread (gpointer key, gpointer value, gpointer user)
1779 MonoThread *thread=(MonoThread *)value;
1780 guint32 self=GPOINTER_TO_UINT (user);
1782 if ((thread->tid!=self) && !mono_gc_is_finalizer_thread (thread))
1783 SuspendThread (thread->handle);
1787 * mono_thread_suspend_all_other_threads:
1789 * Suspend all managed threads except the finalizer thread and this thread.
1791 void mono_thread_suspend_all_other_threads (void)
1793 guint32 self=GetCurrentThreadId ();
1795 EnterCriticalSection (&threads_mutex);
1796 mono_g_hash_table_foreach (threads, suspend_thread,
1797 GUINT_TO_POINTER (self));
1798 LeaveCriticalSection (&threads_mutex);
1802 * mono_thread_push_appdomain_ref:
1804 * Register that the current thread may have references to objects in domain
1805 * @domain on its stack. Each call to this function should be paired with a
1806 * call to pop_appdomain_ref.
1809 mono_thread_push_appdomain_ref (MonoDomain *domain)
1811 MonoThread *thread = mono_thread_current ();
1814 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1815 EnterCriticalSection (&threads_mutex);
1816 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1817 LeaveCriticalSection (&threads_mutex);
1822 mono_thread_pop_appdomain_ref (void)
1824 MonoThread *thread = mono_thread_current ();
1827 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1828 EnterCriticalSection (&threads_mutex);
1829 /* FIXME: How can the list be empty ? */
1830 if (thread->appdomain_refs)
1831 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1832 LeaveCriticalSection (&threads_mutex);
1837 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1840 EnterCriticalSection (&threads_mutex);
1841 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1842 LeaveCriticalSection (&threads_mutex);
1846 typedef struct abort_appdomain_data {
1847 struct wait_data wait;
1849 } abort_appdomain_data;
1852 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1854 MonoThread *thread = (MonoThread*)value;
1855 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1856 MonoDomain *domain = data->domain;
1858 if (mono_thread_has_appdomain_ref (thread, domain)) {
1859 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1860 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1864 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1866 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1867 data->wait.handles [data->wait.num] = handle;
1868 data->wait.threads [data->wait.num] = thread;
1871 /* Just ignore the rest, we can't do anything with
1879 * mono_threads_abort_appdomain_threads:
1881 * Abort threads which has references to the given appdomain.
1884 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1886 abort_appdomain_data user_data;
1889 /* printf ("ABORT BEGIN.\n"); */
1891 start_time = GetTickCount ();
1893 EnterCriticalSection (&threads_mutex);
1895 user_data.domain = domain;
1896 user_data.wait.num = 0;
1897 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1898 LeaveCriticalSection (&threads_mutex);
1900 if (user_data.wait.num > 0)
1901 wait_for_tids (&user_data.wait, timeout);
1903 /* Update remaining time */
1904 timeout -= GetTickCount () - start_time;
1905 start_time = GetTickCount ();
1910 while (user_data.wait.num > 0);
1912 /* printf ("ABORT DONE.\n"); */
1918 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1920 MonoThread *thread = (MonoThread*)value;
1921 MonoDomain *domain = (MonoDomain*)user_data;
1924 /* No locking needed here */
1926 if (thread->culture_info) {
1927 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1928 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1929 thread->culture_info [i] = NULL;
1932 if (thread->ui_culture_info) {
1933 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1934 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1935 thread->ui_culture_info [i] = NULL;
1941 * mono_threads_clear_cached_culture:
1943 * Clear the cached_current_culture from all threads if it is in the
1947 mono_threads_clear_cached_culture (MonoDomain *domain)
1949 EnterCriticalSection (&threads_mutex);
1950 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1951 LeaveCriticalSection (&threads_mutex);
1955 * mono_thread_get_pending_exception:
1957 * Return an exception which needs to be raised when leaving a catch clause.
1958 * This is used for undeniable exception propagation.
1961 mono_thread_get_pending_exception (void)
1963 MonoThread *thread = mono_thread_current ();
1965 MONO_ARCH_SAVE_REGS;
1967 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1969 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1970 * exception if the thread no longer references a dying appdomain.
1972 thread->abort_exc->trace_ips = NULL;
1973 thread->abort_exc->stack_trace = NULL;
1974 return thread->abort_exc;
1980 #define NUM_STATIC_DATA_IDX 8
1981 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1982 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1987 * mono_alloc_static_data
1989 * Allocate memory blocks for storing threads or context static data
1992 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1994 guint idx = (offset >> 24) - 1;
1997 gpointer* static_data = *static_data_ptr;
2000 static_data = GC_MALLOC (static_data_size [0]);
2002 static_data = g_malloc0 (static_data_size [0]);
2004 *static_data_ptr = static_data;
2005 static_data [0] = static_data;
2008 for (i = 1; i <= idx; ++i) {
2009 if (static_data [i])
2012 static_data [i] = GC_MALLOC (static_data_size [i]);
2014 static_data [i] = g_malloc0 (static_data_size [i]);
2020 * mono_init_static_data_info
2022 * Initializes static data counters
2024 static void mono_init_static_data_info (StaticDataInfo *static_data)
2026 static_data->idx = 0;
2027 static_data->offset = 0;
2031 * mono_alloc_static_data_slot
2033 * Generates an offset for static data. static_data contains the counters
2034 * used to generate it.
2037 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2041 if (!static_data->idx && !static_data->offset) {
2043 * we use the first chunk of the first allocation also as
2044 * an array for the rest of the data
2046 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2048 static_data->offset += align - 1;
2049 static_data->offset &= ~(align - 1);
2050 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2051 static_data->idx ++;
2052 g_assert (size <= static_data_size [static_data->idx]);
2054 * massive unloading and reloading of domains with thread-static
2055 * data may eventually exceed the allocated storage...
2056 * Need to check what the MS runtime does in that case.
2057 * Note that for each appdomain, we need to allocate a separate
2058 * thread data slot for security reasons. We could keep track
2059 * of the slots per-domain and when the domain is unloaded
2060 * out the slots on a sort of free list.
2062 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2063 static_data->offset = 0;
2065 offset = static_data->offset | ((static_data->idx + 1) << 24);
2066 static_data->offset += size;
2071 * ensure thread static fields already allocated are valid for thread
2072 * This function is called when a thread is created or on thread attach.
2075 thread_adjust_static_data (MonoThread *thread)
2079 EnterCriticalSection (&threads_mutex);
2080 if (thread_static_info.offset || thread_static_info.idx > 0) {
2081 /* get the current allocated size */
2082 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2083 mono_alloc_static_data (&(thread->static_data), offset);
2085 LeaveCriticalSection (&threads_mutex);
2089 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2091 MonoThread *thread = value;
2092 guint32 offset = GPOINTER_TO_UINT (user);
2094 mono_alloc_static_data (&(thread->static_data), offset);
2098 * The offset for a special static variable is composed of three parts:
2099 * a bit that indicates the type of static data (0:thread, 1:context),
2100 * an index in the array of chunks of memory for the thread (thread->static_data)
2101 * and an offset in that chunk of mem. This allows allocating less memory in the
2106 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2109 if (static_type == SPECIAL_STATIC_THREAD)
2111 EnterCriticalSection (&threads_mutex);
2112 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2113 /* This can be called during startup */
2114 if (threads != NULL)
2115 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2116 LeaveCriticalSection (&threads_mutex);
2120 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2121 EnterCriticalSection (&contexts_mutex);
2122 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2123 LeaveCriticalSection (&contexts_mutex);
2124 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2130 mono_get_special_static_data (guint32 offset)
2132 /* The high bit means either thread (0) or static (1) data. */
2134 guint32 static_type = (offset & 0x80000000);
2137 offset &= 0x7fffffff;
2138 idx = (offset >> 24) - 1;
2140 if (static_type == 0)
2142 MonoThread *thread = mono_thread_current ();
2143 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2147 /* Allocate static data block under demand, since we don't have a list
2150 MonoAppContext *context = mono_context_get ();
2151 if (!context->static_data || !context->static_data [idx]) {
2152 EnterCriticalSection (&contexts_mutex);
2153 mono_alloc_static_data (&(context->static_data), offset);
2154 LeaveCriticalSection (&contexts_mutex);
2156 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2160 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2162 MonoThread *thread=(MonoThread *)value;
2163 guint32 self=GPOINTER_TO_UINT (user);
2166 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2169 if(thread->tid==self)
2172 SuspendThread (thread->handle);
2175 void mono_gc_stop_world (void)
2177 guint32 self=GetCurrentThreadId ();
2180 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2183 EnterCriticalSection (&threads_mutex);
2185 if (threads != NULL)
2186 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2188 LeaveCriticalSection (&threads_mutex);
2191 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2193 MonoThread *thread=(MonoThread *)value;
2194 guint32 self=GPOINTER_TO_UINT (user);
2197 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2200 if(thread->tid==self)
2203 ResumeThread (thread->handle);
2206 void mono_gc_start_world (void)
2208 guint32 self=GetCurrentThreadId ();
2211 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2214 EnterCriticalSection (&threads_mutex);
2216 if (threads != NULL)
2217 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2219 LeaveCriticalSection (&threads_mutex);
2223 static CALLBACK void dummy_apc (ULONG_PTR param)
2227 static guint32 dummy_apc (gpointer param)
2234 * mono_thread_execute_interruption
2236 * Performs the operation that the requested thread state requires (abort,
2239 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2241 mono_monitor_enter (thread->synch_lock);
2243 if (thread->interruption_requested) {
2244 /* this will consume pending APC calls */
2245 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2246 EnterCriticalSection (&interruption_mutex);
2247 thread_interruption_requested--;
2248 LeaveCriticalSection (&interruption_mutex);
2249 thread->interruption_requested = FALSE;
2252 if ((thread->state & ThreadState_AbortRequested) != 0) {
2253 if (thread->abort_exc == NULL)
2254 thread->abort_exc = mono_get_exception_thread_abort ();
2255 mono_monitor_exit (thread->synch_lock);
2256 return thread->abort_exc;
2258 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2259 thread->state &= ~ThreadState_SuspendRequested;
2260 thread->state |= ThreadState_Suspended;
2261 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2262 mono_monitor_exit (thread->synch_lock);
2264 WaitForSingleObject (thread->suspend_event, INFINITE);
2266 mono_monitor_enter (thread->synch_lock);
2267 CloseHandle (thread->suspend_event);
2268 thread->suspend_event = NULL;
2269 thread->state &= ~ThreadState_Suspended;
2271 /* The thread that requested the resume will have replaced this event
2272 * and will be waiting for it
2274 SetEvent (thread->resume_event);
2275 mono_monitor_exit (thread->synch_lock);
2278 else if ((thread->state & ThreadState_StopRequested) != 0) {
2279 /* FIXME: do this through the JIT? */
2280 mono_monitor_exit (thread->synch_lock);
2281 mono_thread_exit ();
2285 mono_monitor_exit (thread->synch_lock);
2290 * mono_thread_request_interruption
2292 * A signal handler can call this method to request the interruption of a
2293 * thread. The result of the interruption will depend on the current state of
2294 * the thread. If the result is an exception that needs to be throw, it is
2295 * provided as return value.
2297 MonoException* mono_thread_request_interruption (gboolean running_managed)
2299 MonoThread *thread = mono_thread_current ();
2301 /* The thread may already be stopping */
2305 mono_monitor_enter (thread->synch_lock);
2307 if (thread->interruption_requested) {
2308 mono_monitor_exit (thread->synch_lock);
2312 if (!running_managed || is_running_protected_wrapper ()) {
2313 /* Can't stop while in unmanaged code. Increase the global interruption
2314 request count. When exiting the unmanaged method the count will be
2315 checked and the thread will be interrupted. */
2317 EnterCriticalSection (&interruption_mutex);
2318 thread_interruption_requested++;
2319 LeaveCriticalSection (&interruption_mutex);
2321 thread->interruption_requested = TRUE;
2322 mono_monitor_exit (thread->synch_lock);
2324 /* this will awake the thread if it is in WaitForSingleObject
2326 QueueUserAPC (dummy_apc, thread->handle, NULL);
2331 mono_monitor_exit (thread->synch_lock);
2332 return mono_thread_execute_interruption (thread);
2336 gboolean mono_thread_interruption_requested ()
2338 if (thread_interruption_requested) {
2339 MonoThread *thread = mono_thread_current ();
2340 /* The thread may already be stopping */
2342 return (thread->interruption_requested);
2347 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2349 MonoThread *thread = mono_thread_current ();
2351 /* The thread may already be stopping */
2355 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2356 MonoException* exc = mono_thread_execute_interruption (thread);
2357 if (exc) mono_raise_exception (exc);
2362 * Performs the interruption of the current thread, if one has been requested,
2363 * and the thread is not running a protected wrapper.
2365 void mono_thread_interruption_checkpoint ()
2367 mono_thread_interruption_checkpoint_request (FALSE);
2371 * Performs the interruption of the current thread, if one has been requested.
2373 void mono_thread_force_interruption_checkpoint ()
2375 mono_thread_interruption_checkpoint_request (TRUE);
2379 * mono_thread_interruption_request_flag:
2381 * Returns the address of a flag that will be non-zero if an interruption has
2382 * been requested for a thread. The thread to interrupt may not be the current
2383 * thread, so an additional call to mono_thread_interruption_requested() or
2384 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2387 gint32* mono_thread_interruption_request_flag ()
2389 return &thread_interruption_requested;
2392 #ifdef WITH_INCLUDED_LIBGC
2394 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2396 MonoThread *thread=(MonoThread *)value;
2397 guint32 *selfp=(guint32 *)user, self = *selfp;
2400 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2403 if(thread->tid==self) {
2405 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2407 GC_push_all_stack (selfp, thread->stack_ptr);
2411 #ifdef PLATFORM_WIN32
2412 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2414 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2418 void mono_gc_push_all_stacks (void)
2420 guint32 self=GetCurrentThreadId ();
2423 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2426 EnterCriticalSection (&threads_mutex);
2428 if (threads != NULL)
2429 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2431 LeaveCriticalSection (&threads_mutex);
2434 #endif /* WITH_INCLUDED_LIBGC */