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>
37 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
38 #define THREAD_DEBUG(a)
39 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
40 #define THREAD_WAIT_DEBUG(a)
41 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
42 #define LIBGC_DEBUG(a)
46 guint32 (*func)(void *);
68 /* Number of cached culture objects in the MonoThread->culture_info array */
69 #define NUM_CACHED_CULTURES 4
72 * The "os_handle" field of the WaitHandle class.
74 static MonoClassField *wait_handle_os_handle_field = NULL;
76 /* Controls access to the 'threads' hash table */
77 static CRITICAL_SECTION threads_mutex;
79 /* Controls access to context static data */
80 static CRITICAL_SECTION contexts_mutex;
82 /* Holds current status of static data heap */
83 static StaticDataInfo thread_static_info;
84 static StaticDataInfo context_static_info;
86 /* The hash of existing threads (key is thread ID) that need joining
89 static MonoGHashTable *threads=NULL;
91 /* The TLS key that holds the MonoObject assigned to each thread */
92 static guint32 current_object_key = -1;
95 /* we need to use both the Tls* functions and __thread because
96 * the gc needs to see all the threads
98 static __thread MonoThread * tls_current_object;
99 #define SET_CURRENT_OBJECT(x) do { \
100 tls_current_object = x; \
101 TlsSetValue (current_object_key, x); \
103 #define GET_CURRENT_OBJECT() tls_current_object
105 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
106 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
109 /* function called at thread start */
110 static MonoThreadStartCB mono_thread_start_cb = NULL;
112 /* function called at thread attach */
113 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
115 /* function called at thread cleanup */
116 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
118 /* function called when a new thread has been created */
119 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
121 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
122 static guint32 slothash_key = -1;
124 /* The default stack size for each thread */
125 static guint32 default_stacksize = 0;
126 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
128 static void thread_adjust_static_data (MonoThread *thread);
129 static void mono_init_static_data_info (StaticDataInfo *static_data);
130 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
132 /* Spin lock for InterlockedXXX 64 bit functions */
133 static CRITICAL_SECTION interlocked_mutex;
135 /* Controls access to interruption flag */
136 static CRITICAL_SECTION interruption_mutex;
138 /* global count of thread interruptions requested */
139 static gint32 thread_interruption_requested = 0;
142 mono_thread_get_tls_key (void)
144 return current_object_key;
147 /* handle_store() and handle_remove() manage the array of threads that
148 * still need to be waited for when the main thread exits.
150 static void handle_store(MonoThread *thread)
152 EnterCriticalSection(&threads_mutex);
154 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread, thread->tid));
157 MONO_GC_REGISTER_ROOT (threads);
158 threads=mono_g_hash_table_new(NULL, NULL);
161 /* We don't need to duplicate thread->handle, because it is
162 * only closed when the thread object is finalized by the GC.
164 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
165 LeaveCriticalSection(&threads_mutex);
168 static void handle_remove(guint32 tid)
170 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid));
172 EnterCriticalSection(&threads_mutex);
175 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
177 LeaveCriticalSection(&threads_mutex);
179 /* Don't close the handle here, wait for the object finalizer
180 * to do it. Otherwise, the following race condition applies:
182 * 1) Thread exits (and handle_remove() closes the handle)
184 * 2) Some other handle is reassigned the same slot
186 * 3) Another thread tries to join the first thread, and
187 * blocks waiting for the reassigned handle to be signalled
188 * (which might never happen). This is possible, because the
189 * thread calling Join() still has a reference to the first
194 static void thread_cleanup (MonoThread *thread)
196 mono_release_type_locks (thread);
198 if (!mono_monitor_enter (thread->synch_lock))
201 thread->state |= ThreadState_Stopped;
202 mono_monitor_exit (thread->synch_lock);
204 mono_profiler_thread_end (thread->tid);
205 handle_remove (thread->tid);
207 mono_thread_pop_appdomain_ref ();
209 if (thread->serialized_culture_info)
210 g_free (thread->serialized_culture_info);
212 mono_gc_free_fixed (thread->culture_info);
213 mono_gc_free_fixed (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;
228 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper", GetCurrentThreadId ()));
230 /* We can be sure start_info->obj->tid and
231 * start_info->obj->handle have been set, because the thread
232 * was created suspended, and these values were set before the
238 SET_CURRENT_OBJECT (thread);
240 if (!mono_domain_set (start_info->domain, FALSE)) {
241 /* No point in raising an appdomain_unloaded exception here */
242 /* FIXME: Cleanup here */
246 start_func = start_info->func;
247 start_arg = start_info->start_arg;
249 /* This MUST be called before any managed code can be
250 * executed, as it calls the callback function that (for the
251 * jit) sets the lmf marker.
253 mono_thread_new_init (tid, &tid, start_func);
254 thread->stack_ptr = &tid;
256 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
257 ": (%d,%d) Setting thread stack to %p",
258 GetCurrentThreadId (), getpid (), thread->stack_ptr));
260 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
261 ": (%d) Setting current_object_key to %p",
262 GetCurrentThreadId (), thread));
264 mono_profiler_thread_start (tid);
266 if(thread->start_notify!=NULL) {
267 /* Let the thread that called Start() know we're
270 ReleaseSemaphore (thread->start_notify, 1, NULL);
275 /* Every thread references the appdomain which created it */
276 mono_thread_push_appdomain_ref (mono_domain_get ());
278 thread_adjust_static_data (thread);
280 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
283 /* start_func is set only for unamanged start functions */
285 start_func (start_arg);
288 g_assert (start_delegate != NULL);
289 args [0] = start_arg;
290 /* we may want to handle the exception here. See comment below on unhandled exceptions */
291 mono_runtime_delegate_invoke (start_delegate, args, NULL);
294 /* If the thread calls ExitThread at all, this remaining code
295 * will not be executed, but the main thread will eventually
296 * call thread_cleanup() on this thread's behalf.
299 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
300 GetCurrentThreadId ()));
302 /* Remove the reference to the thread object in the TLS data,
303 * so the thread object can be finalized. This won't be
304 * reached if the thread threw an uncaught exception, so those
305 * thread handles will stay referenced :-( (This is due to
306 * missing support for scanning thread-specific data in the
307 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
310 SET_CURRENT_OBJECT (NULL);
312 thread_cleanup (thread);
317 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
319 if (mono_thread_start_cb) {
320 mono_thread_start_cb (tid, stack_start, func);
323 if (mono_thread_callbacks)
324 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
327 void mono_threads_set_default_stacksize (guint32 stacksize)
329 default_stacksize = stacksize;
332 guint32 mono_threads_get_default_stacksize (void)
334 return default_stacksize;
337 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
340 HANDLE thread_handle;
341 struct StartInfo *start_info;
344 thread=(MonoThread *)mono_object_new (domain,
345 mono_defaults.thread_class);
347 start_info=g_new0 (struct StartInfo, 1);
348 start_info->func = func;
349 start_info->obj = thread;
350 start_info->domain = domain;
351 start_info->start_arg = arg;
353 /* Create suspended, so we can do some housekeeping before the thread
356 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
357 CREATE_SUSPENDED, &tid);
358 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
359 tid, thread_handle));
360 g_assert (thread_handle);
362 thread->handle=thread_handle;
365 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
367 handle_store(thread);
369 ResumeThread (thread_handle);
373 mono_thread_attach (MonoDomain *domain)
376 HANDLE thread_handle;
379 if ((thread = mono_thread_current ())) {
380 /* Already attached */
384 thread = (MonoThread *)mono_object_new (domain,
385 mono_defaults.thread_class);
387 thread_handle = GetCurrentThread ();
388 g_assert (thread_handle);
390 tid=GetCurrentThreadId ();
392 #ifdef PLATFORM_WIN32
394 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
395 * refer to the thread from other threads for things like aborting.
397 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
398 THREAD_ALL_ACCESS, TRUE, 0);
401 thread->handle=thread_handle;
403 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
405 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
406 tid, thread_handle));
408 handle_store(thread);
410 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Setting current_object_key to %p",
411 GetCurrentThreadId (), thread));
413 SET_CURRENT_OBJECT (thread);
414 mono_domain_set (domain, TRUE);
416 thread_adjust_static_data (thread);
418 if (mono_thread_attach_cb) {
419 mono_thread_attach_cb (tid, &tid);
426 mono_thread_detach (MonoThread *thread)
428 g_return_if_fail (thread != NULL);
430 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid));
431 SET_CURRENT_OBJECT (NULL);
433 thread_cleanup (thread);
439 MonoThread *thread = mono_thread_current ();
441 SET_CURRENT_OBJECT (NULL);
442 thread_cleanup (thread);
444 /* we could add a callback here for embedders to use. */
445 if (thread == mono_thread_get_main ())
446 exit (mono_environment_exitcode_get ());
450 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
453 guint32 (*start_func)(void *);
454 struct StartInfo *start_info;
461 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
462 ": Trying to start a new thread: this (%p) start (%p)", this, start));
464 /* FIXME: remove the code inside BROKEN_THREAD_START once martin gets rid of the
465 * thread_start_compile_func stuff.
467 #define BROKEN_THREAD_START
468 #ifdef BROKEN_THREAD_START
469 im = mono_get_delegate_invoke (start->vtable->klass);
470 im = mono_marshal_get_delegate_invoke (im);
471 if (mono_thread_callbacks)
472 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
474 start_func = mono_compile_method (im);
476 if(start_func==NULL) {
477 g_warning(G_GNUC_PRETTY_FUNCTION
478 ": Can't locate start method!");
485 /* This is freed in start_wrapper */
486 start_info = g_new0 (struct StartInfo, 1);
487 start_info->func = start_func;
488 #ifdef BROKEN_THREAD_START
489 start_info->start_arg = start;
491 start_info->start_arg = this->start_obj;
493 start_info->delegate = start;
494 start_info->obj = this;
495 start_info->domain = mono_domain_get ();
497 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
498 if(this->start_notify==NULL) {
499 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
503 thread=CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
504 CREATE_SUSPENDED, &tid);
506 g_warning(G_GNUC_PRETTY_FUNCTION
507 ": CreateThread error 0x%x", GetLastError());
514 /* Don't call handle_store() here, delay it to Start.
515 * We can't join a thread (trying to will just block
516 * forever) until it actually starts running, so don't
517 * store the handle till then.
520 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
521 ": Started thread ID %d (handle %p)", tid, thread));
527 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
532 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
535 CloseHandle (thread);
538 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
543 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
544 GetCurrentThreadId (), this, this->tid));
546 /* Only store the handle when the thread is about to be
547 * launched, to avoid the main thread deadlocking while trying
548 * to clean up a thread that will never be signalled.
552 if (mono_thread_callbacks)
553 (* mono_thread_callbacks->start_resume) (this->tid);
555 ResumeThread(thread);
557 if (mono_thread_callbacks)
558 (* mono_thread_callbacks->end_resume) (this->tid);
560 if(this->start_notify!=NULL) {
561 /* Wait for the thread to set up its TLS data etc, so
562 * theres no potential race condition if someone tries
563 * to look up the data believing the thread has
567 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
568 ": (%d) waiting for thread %p (%d) to start",
569 GetCurrentThreadId (), this, this->tid));
571 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
572 CloseHandle (this->start_notify);
573 this->start_notify=NULL;
576 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
577 ": (%d) Done launching thread %p (%d)",
578 GetCurrentThreadId (), this, this->tid));
581 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
583 MonoThread *thread = mono_thread_current ();
587 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms));
589 mono_monitor_enter (thread->synch_lock);
590 thread->state |= ThreadState_WaitSleepJoin;
591 mono_monitor_exit (thread->synch_lock);
595 mono_monitor_enter (thread->synch_lock);
596 thread->state &= ~ThreadState_WaitSleepJoin;
597 mono_monitor_exit (thread->synch_lock);
601 ves_icall_System_Threading_Thread_GetDomainID (void)
605 return mono_domain_get()->domain_id;
609 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
614 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
618 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
621 g_free (this_obj->name);
623 this_obj->name = g_new (gunichar2, mono_string_length (name));
624 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
625 this_obj->name_len = mono_string_length (name);
628 this_obj->name = NULL;
632 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
638 /* No need to lock here */
639 if (this->culture_info) {
640 domain = mono_domain_get ();
641 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
642 res = this->culture_info [i];
643 if (res && res->vtable->domain == domain)
652 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
656 mono_monitor_enter (this->synch_lock);
657 if (this->serialized_culture_info) {
658 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
659 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
663 mono_monitor_exit (this->synch_lock);
669 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
672 MonoDomain *domain = mono_domain_get ();
674 mono_monitor_enter (this->synch_lock);
675 if (!this->culture_info) {
676 this->culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
679 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
680 if (this->culture_info [i]) {
681 if (this->culture_info [i]->vtable->domain == domain)
689 if (i < NUM_CACHED_CULTURES)
690 this->culture_info [i] = culture;
691 mono_monitor_exit (this->synch_lock);
695 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
697 mono_monitor_enter (this->synch_lock);
698 if (this->serialized_culture_info)
699 g_free (this->serialized_culture_info);
700 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
701 this->serialized_culture_info_len = mono_array_length (arr);
702 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
703 mono_monitor_exit (this->synch_lock);
708 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
714 /* No need to lock here */
715 if (this->ui_culture_info) {
716 domain = mono_domain_get ();
717 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
718 res = this->ui_culture_info [i];
719 if (res && res->vtable->domain == domain)
728 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
732 mono_monitor_enter (this->synch_lock);
733 if (this->serialized_ui_culture_info) {
734 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
735 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
739 mono_monitor_exit (this->synch_lock);
745 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
748 MonoDomain *domain = mono_domain_get ();
750 mono_monitor_enter (this->synch_lock);
751 if (!this->ui_culture_info) {
752 this->ui_culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
755 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
756 if (this->ui_culture_info [i]) {
757 if (this->ui_culture_info [i]->vtable->domain == domain)
765 if (i < NUM_CACHED_CULTURES)
766 this->ui_culture_info [i] = culture;
767 mono_monitor_exit (this->synch_lock);
771 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
773 mono_monitor_enter (this->synch_lock);
774 if (this->serialized_ui_culture_info)
775 g_free (this->serialized_ui_culture_info);
776 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
777 this->serialized_ui_culture_info_len = mono_array_length (arr);
778 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
779 mono_monitor_exit (this->synch_lock);
782 /* the jit may read the compiled code of this function */
784 mono_thread_current (void)
786 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", GET_CURRENT_OBJECT ()));
787 return GET_CURRENT_OBJECT ();
790 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
791 int ms, HANDLE thread)
797 mono_monitor_enter (this->synch_lock);
798 this->state |= ThreadState_WaitSleepJoin;
799 mono_monitor_exit (this->synch_lock);
804 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
807 ret=WaitForSingleObjectEx (thread, ms, TRUE);
809 mono_monitor_enter (this->synch_lock);
810 this->state &= ~ThreadState_WaitSleepJoin;
811 mono_monitor_exit (this->synch_lock);
813 if(ret==WAIT_OBJECT_0) {
814 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join successful"));
819 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join failed"));
824 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
828 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Storing key %p", data));
830 /* Object location stored here */
831 TlsSetValue(slothash_key, data);
834 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
840 data=TlsGetValue(slothash_key);
842 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data));
847 /* FIXME: exitContext isnt documented */
848 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
854 MonoObject *waitHandle;
856 MonoThread *thread = mono_thread_current ();
860 numhandles = mono_array_length(mono_handles);
861 handles = g_new0(HANDLE, numhandles);
863 if (wait_handle_os_handle_field == 0) {
864 /* Get the field os_handle which will contain the actual handle */
865 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
866 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
869 for(i = 0; i < numhandles; i++) {
870 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
871 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
878 mono_monitor_enter (thread->synch_lock);
879 thread->state |= ThreadState_WaitSleepJoin;
880 mono_monitor_exit (thread->synch_lock);
882 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
884 mono_monitor_enter (thread->synch_lock);
885 thread->state &= ~ThreadState_WaitSleepJoin;
886 mono_monitor_exit (thread->synch_lock);
890 if(ret==WAIT_FAILED) {
891 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
892 GetCurrentThreadId ()));
894 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
895 /* Do we want to try again if we get
896 * WAIT_IO_COMPLETION? The documentation for
897 * WaitHandle doesn't give any clues. (We'd have to
898 * fiddle with the timeout if we retry.)
900 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
901 GetCurrentThreadId ()));
908 /* FIXME: exitContext isnt documented */
909 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
915 MonoObject *waitHandle;
917 MonoThread *thread = mono_thread_current ();
921 numhandles = mono_array_length(mono_handles);
922 handles = g_new0(HANDLE, numhandles);
924 if (wait_handle_os_handle_field == 0) {
925 /* Get the field os_handle which will contain the actual handle */
926 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
927 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
930 for(i = 0; i < numhandles; i++) {
931 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
932 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
939 mono_monitor_enter (thread->synch_lock);
940 thread->state |= ThreadState_WaitSleepJoin;
941 mono_monitor_exit (thread->synch_lock);
943 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
945 mono_monitor_enter (thread->synch_lock);
946 thread->state &= ~ThreadState_WaitSleepJoin;
947 mono_monitor_exit (thread->synch_lock);
951 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
952 GetCurrentThreadId (), ret));
955 * These need to be here. See MSDN dos on WaitForMultipleObjects.
957 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
958 return ret - WAIT_OBJECT_0;
960 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
961 return ret - WAIT_ABANDONED_0;
968 /* FIXME: exitContext isnt documented */
969 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
972 MonoThread *thread = mono_thread_current ();
976 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
977 GetCurrentThreadId (), handle, ms));
983 mono_monitor_enter (thread->synch_lock);
984 thread->state |= ThreadState_WaitSleepJoin;
985 mono_monitor_exit (thread->synch_lock);
987 ret=WaitForSingleObjectEx (handle, ms, TRUE);
989 mono_monitor_enter (thread->synch_lock);
990 thread->state &= ~ThreadState_WaitSleepJoin;
991 mono_monitor_exit (thread->synch_lock);
993 if(ret==WAIT_FAILED) {
994 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
995 GetCurrentThreadId ()));
997 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
998 /* Do we want to try again if we get
999 * WAIT_IO_COMPLETION? The documentation for
1000 * WaitHandle doesn't give any clues. (We'd have to
1001 * fiddle with the timeout if we retry.)
1003 THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1004 GetCurrentThreadId ()));
1011 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1015 MONO_ARCH_SAVE_REGS;
1020 mutex = CreateMutex (NULL, owned, NULL);
1022 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1024 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1032 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1033 MONO_ARCH_SAVE_REGS;
1035 ReleaseMutex(handle);
1038 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1039 MONO_ARCH_SAVE_REGS;
1041 return(CreateEvent (NULL, manual, initial,
1042 name==NULL?NULL:mono_string_chars (name)));
1045 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1046 MONO_ARCH_SAVE_REGS;
1048 return (SetEvent(handle));
1051 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1052 MONO_ARCH_SAVE_REGS;
1054 return (ResetEvent(handle));
1058 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1059 MONO_ARCH_SAVE_REGS;
1061 CloseHandle (handle);
1064 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1066 MONO_ARCH_SAVE_REGS;
1068 return InterlockedIncrement (location);
1071 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1075 MONO_ARCH_SAVE_REGS;
1077 EnterCriticalSection(&interlocked_mutex);
1081 LeaveCriticalSection(&interlocked_mutex);
1087 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1089 MONO_ARCH_SAVE_REGS;
1091 return InterlockedDecrement(location);
1094 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1098 MONO_ARCH_SAVE_REGS;
1100 EnterCriticalSection(&interlocked_mutex);
1104 LeaveCriticalSection(&interlocked_mutex);
1109 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1111 MONO_ARCH_SAVE_REGS;
1113 return InterlockedExchange(location1, value);
1116 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1118 MONO_ARCH_SAVE_REGS;
1120 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1123 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1125 IntFloatUnion val, ret;
1127 MONO_ARCH_SAVE_REGS;
1130 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1136 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location1, gint64 value)
1138 #if SIZEOF_VOID_P == 8
1139 return (gint64) InterlockedExchangePointer((gpointer *) location1, (gpointer)value);
1144 * According to MSDN, this function is only atomic with regards to the
1145 * other Interlocked functions on 32 bit platforms.
1147 EnterCriticalSection(&interlocked_mutex);
1150 LeaveCriticalSection(&interlocked_mutex);
1157 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location1, gdouble value)
1159 #if SIZEOF_VOID_P == 8
1160 LongDoubleUnion val, ret;
1163 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location1, (gpointer)val.ival);
1170 * According to MSDN, this function is only atomic with regards to the
1171 * other Interlocked functions on 32 bit platforms.
1173 EnterCriticalSection(&interlocked_mutex);
1176 LeaveCriticalSection(&interlocked_mutex);
1182 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1184 MONO_ARCH_SAVE_REGS;
1186 return InterlockedCompareExchange(location1, value, comparand);
1189 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1191 MONO_ARCH_SAVE_REGS;
1193 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1196 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1198 IntFloatUnion val, ret, cmp;
1200 MONO_ARCH_SAVE_REGS;
1203 cmp.fval = comparand;
1204 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1210 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location1, gdouble value, gdouble comparand)
1212 #if SIZEOF_VOID_P == 8
1213 LongDoubleUnion val, comp, ret;
1216 comp.fval = comparand;
1217 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location1, (gpointer)val.ival, (gpointer)comp.ival);
1223 EnterCriticalSection(&interlocked_mutex);
1225 if (old == comparand)
1227 LeaveCriticalSection(&interlocked_mutex);
1234 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location1, gint64 value, gint64 comparand)
1236 #if SIZEOF_VOID_P == 8
1237 return (gint64)InterlockedCompareExchangePointer((gpointer *) location1, (gpointer)value, (gpointer)comparand);
1241 EnterCriticalSection(&interlocked_mutex);
1243 if (old == comparand)
1245 LeaveCriticalSection(&interlocked_mutex);
1252 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location1, gint32 value)
1254 #if SIZEOF_VOID_P == 8
1255 /* Should be implemented as a JIT intrinsic */
1256 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1261 EnterCriticalSection(&interlocked_mutex);
1263 *location = orig + value;
1264 LeaveCriticalSection(&interlocked_mutex);
1271 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location1, gint64 value)
1273 #if SIZEOF_VOID_P == 8
1274 /* Should be implemented as a JIT intrinsic */
1275 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1280 EnterCriticalSection(&interlocked_mutex);
1282 *location = orig + value;
1283 LeaveCriticalSection(&interlocked_mutex);
1290 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location1)
1292 #if SIZEOF_VOID_P == 8
1293 /* 64 bit reads are already atomic */
1298 EnterCriticalSection(&interlocked_mutex);
1300 LeaveCriticalSection(&interlocked_mutex);
1307 mono_thread_get_abort_signal (void)
1317 #endif /* __MINGW32__ */
1321 static CALLBACK void interruption_request_apc (ULONG_PTR param)
1323 MonoException* exc = mono_thread_request_interruption (FALSE);
1324 if (exc) mono_raise_exception (exc);
1327 #endif /* __MINGW32__ */
1330 * signal_thread_state_change
1332 * Tells the thread that his state has changed and it has to enter the new
1333 * state as soon as possible.
1335 static void signal_thread_state_change (MonoThread *thread)
1337 if (thread == mono_thread_current ()) {
1338 /* Do it synchronously */
1339 MonoException *exc = mono_thread_request_interruption (FALSE);
1341 mono_raise_exception (exc);
1345 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1347 /* fixme: store the state somewhere */
1348 #ifdef PTHREAD_POINTER_ID
1349 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1351 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1353 #endif /* __MINGW32__ */
1357 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1359 MONO_ARCH_SAVE_REGS;
1361 mono_monitor_enter (thread->synch_lock);
1363 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1364 (thread->state & ThreadState_StopRequested) != 0)
1366 mono_monitor_exit (thread->synch_lock);
1370 thread->state |= ThreadState_AbortRequested;
1371 thread->abort_state = state;
1372 thread->abort_exc = NULL;
1374 mono_monitor_exit (thread->synch_lock);
1376 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1377 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1378 thread, thread->tid));
1380 /* Make sure the thread is awake */
1381 ves_icall_System_Threading_Thread_Resume (thread);
1383 signal_thread_state_change (thread);
1387 ves_icall_System_Threading_Thread_ResetAbort (void)
1389 MonoThread *thread = mono_thread_current ();
1391 MONO_ARCH_SAVE_REGS;
1393 mono_monitor_enter (thread->synch_lock);
1395 thread->state &= ~ThreadState_AbortRequested;
1397 if (!thread->abort_exc) {
1398 const char *msg = "Unable to reset abort because no abort was requested";
1399 mono_monitor_exit (thread->synch_lock);
1400 mono_raise_exception (mono_get_exception_thread_state (msg));
1402 thread->abort_exc = NULL;
1403 thread->abort_state = NULL;
1406 mono_monitor_exit (thread->synch_lock);
1410 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1412 MONO_ARCH_SAVE_REGS;
1414 mono_monitor_enter (thread->synch_lock);
1416 if ((thread->state & ThreadState_Suspended) != 0 ||
1417 (thread->state & ThreadState_SuspendRequested) != 0 ||
1418 (thread->state & ThreadState_StopRequested) != 0)
1420 mono_monitor_exit (thread->synch_lock);
1424 thread->state |= ThreadState_SuspendRequested;
1425 mono_monitor_exit (thread->synch_lock);
1427 signal_thread_state_change (thread);
1431 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1433 MONO_ARCH_SAVE_REGS;
1435 mono_monitor_enter (thread->synch_lock);
1437 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1438 thread->state &= ~ThreadState_SuspendRequested;
1439 mono_monitor_exit (thread->synch_lock);
1443 if ((thread->state & ThreadState_Suspended) == 0)
1445 mono_monitor_exit (thread->synch_lock);
1449 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1451 /* Awake the thread */
1452 SetEvent (thread->suspend_event);
1454 mono_monitor_exit (thread->synch_lock);
1456 /* Wait for the thread to awake */
1457 WaitForSingleObject (thread->resume_event, INFINITE);
1458 CloseHandle (thread->resume_event);
1459 thread->resume_event = NULL;
1463 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1468 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1469 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1470 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1472 *((gboolean*)data) = TRUE;
1479 is_running_protected_wrapper (void)
1481 gboolean found = FALSE;
1482 mono_stack_walk (find_wrapper, &found);
1486 void mono_thread_stop (MonoThread *thread)
1488 mono_monitor_enter (thread->synch_lock);
1490 if ((thread->state & ThreadState_StopRequested) != 0 ||
1491 (thread->state & ThreadState_Stopped) != 0)
1493 mono_monitor_exit (thread->synch_lock);
1497 /* Make sure the thread is awake */
1498 ves_icall_System_Threading_Thread_Resume (thread);
1500 thread->state |= ThreadState_StopRequested;
1501 thread->state &= ~ThreadState_AbortRequested;
1503 mono_monitor_exit (thread->synch_lock);
1505 signal_thread_state_change (thread);
1509 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1511 return *((volatile gint8 *) (ptr));
1515 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1517 return *((volatile gint16 *) (ptr));
1521 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1523 return *((volatile gint32 *) (ptr));
1527 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1529 return *((volatile gint64 *) (ptr));
1533 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1535 return (void *) *((volatile void **) ptr);
1539 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1541 *((volatile gint8 *) ptr) = value;
1545 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1547 *((volatile gint16 *) ptr) = value;
1551 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1553 *((volatile gint32 *) ptr) = value;
1557 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1559 *((volatile gint64 *) ptr) = value;
1563 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1565 *((volatile void **) ptr) = value;
1568 void mono_thread_init (MonoThreadStartCB start_cb,
1569 MonoThreadAttachCB attach_cb)
1571 InitializeCriticalSection(&threads_mutex);
1572 InitializeCriticalSection(&interlocked_mutex);
1573 InitializeCriticalSection(&contexts_mutex);
1574 InitializeCriticalSection(&interruption_mutex);
1576 mono_init_static_data_info (&thread_static_info);
1577 mono_init_static_data_info (&context_static_info);
1579 current_object_key=TlsAlloc();
1580 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1581 current_object_key));
1583 mono_thread_start_cb = start_cb;
1584 mono_thread_attach_cb = attach_cb;
1586 slothash_key=TlsAlloc();
1588 /* Get a pseudo handle to the current process. This is just a
1589 * kludge so that wapi can build a process handle if needed.
1590 * As a pseudo handle is returned, we don't need to clean
1593 GetCurrentProcess ();
1597 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1599 mono_thread_cleanup = func;
1602 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1604 mono_thread_callbacks = callbacks;
1608 static void print_tids (gpointer key, gpointer value, gpointer user)
1610 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1616 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1617 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1621 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1625 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1626 ": %d threads to wait for in this batch", wait->num));
1628 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1630 if(ret==WAIT_FAILED) {
1631 /* See the comment in build_wait_tids() */
1632 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
1636 for(i=0; i<wait->num; i++)
1637 CloseHandle (wait->handles[i]);
1639 if (ret == WAIT_TIMEOUT)
1642 for(i=0; i<wait->num; i++) {
1643 guint32 tid=wait->threads[i]->tid;
1645 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1646 /* This thread must have been killed, because
1647 * it hasn't cleaned itself up. (It's just
1648 * possible that the thread exited before the
1649 * parent thread had a chance to store the
1650 * handle, and now there is another pointer to
1651 * the already-exited thread stored. In this
1652 * case, we'll just get two
1653 * mono_profiler_thread_end() calls for the
1657 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1658 ": cleaning up after thread %d", tid));
1659 thread_cleanup (wait->threads[i]);
1664 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1666 struct wait_data *wait=(struct wait_data *)user;
1668 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1670 MonoThread *thread=(MonoThread *)value;
1672 /* Ignore background threads, we abort them later */
1673 if (thread->state & ThreadState_Background)
1674 return; /* just leave, ignore */
1676 if (mono_gc_is_finalizer_thread (thread))
1679 if (thread == mono_thread_current ())
1682 if (thread == mono_thread_get_main ())
1685 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1689 wait->handles[wait->num]=handle;
1690 wait->threads[wait->num]=thread;
1693 /* Just ignore the rest, we can't do anything with
1700 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1702 struct wait_data *wait=(struct wait_data *)user;
1703 guint32 self = GetCurrentThreadId ();
1704 MonoThread *thread = (MonoThread *) value;
1707 /* The finalizer thread is not a background thread */
1708 if (thread->tid != self && thread->state & ThreadState_Background) {
1710 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1714 wait->handles[wait->num]=thread->handle;
1715 wait->threads[wait->num]=thread;
1718 if(thread->state & ThreadState_AbortRequested ||
1719 thread->state & ThreadState_Aborted) {
1720 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid));
1724 THREAD_DEBUG (g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid));
1725 mono_thread_stop (thread);
1729 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1732 void mono_thread_manage (void)
1734 struct wait_data *wait=g_new0 (struct wait_data, 1);
1736 /* join each thread that's still running */
1737 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Joining each running thread..."));
1739 EnterCriticalSection (&threads_mutex);
1741 THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": No threads"));
1742 LeaveCriticalSection (&threads_mutex);
1745 LeaveCriticalSection (&threads_mutex);
1748 EnterCriticalSection (&threads_mutex);
1749 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1750 ":There are %d threads to join", mono_g_hash_table_size (threads));
1751 mono_g_hash_table_foreach (threads, print_tids, NULL));
1754 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1755 LeaveCriticalSection (&threads_mutex);
1757 /* Something to wait for */
1758 wait_for_tids (wait, INFINITE);
1760 } while(wait->num>0);
1762 mono_thread_pool_cleanup ();
1764 EnterCriticalSection(&threads_mutex);
1767 * Remove everything but the finalizer thread and self.
1768 * Also abort all the background threads
1771 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1773 LeaveCriticalSection(&threads_mutex);
1776 /* Something to wait for */
1777 wait_for_tids (wait, INFINITE);
1780 * give the subthreads a chance to really quit (this is mainly needed
1781 * to get correct user and system times from getrusage/wait/time(1)).
1782 * This could be removed if we avoid pthread_detach() and use pthread_join().
1784 #ifndef PLATFORM_WIN32
1791 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1793 MonoThread *thread=(MonoThread *)value;
1794 guint32 self=GPOINTER_TO_UINT (user);
1796 if(thread->tid!=self) {
1797 /*TerminateThread (thread->handle, -1);*/
1801 void mono_thread_abort_all_other_threads (void)
1803 guint32 self=GetCurrentThreadId ();
1805 EnterCriticalSection (&threads_mutex);
1806 THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1807 mono_g_hash_table_size (threads));
1808 mono_g_hash_table_foreach (threads, print_tids, NULL));
1810 mono_g_hash_table_foreach (threads, terminate_thread,
1811 GUINT_TO_POINTER (self));
1813 LeaveCriticalSection (&threads_mutex);
1816 static void suspend_thread (gpointer key, gpointer value, gpointer user)
1818 MonoThread *thread=(MonoThread *)value;
1819 guint32 self=GPOINTER_TO_UINT (user);
1821 if ((thread->tid!=self) && !mono_gc_is_finalizer_thread (thread))
1822 SuspendThread (thread->handle);
1826 * mono_thread_suspend_all_other_threads:
1828 * Suspend all managed threads except the finalizer thread and this thread.
1830 void mono_thread_suspend_all_other_threads (void)
1832 guint32 self=GetCurrentThreadId ();
1834 EnterCriticalSection (&threads_mutex);
1835 mono_g_hash_table_foreach (threads, suspend_thread,
1836 GUINT_TO_POINTER (self));
1837 LeaveCriticalSection (&threads_mutex);
1841 * mono_thread_push_appdomain_ref:
1843 * Register that the current thread may have references to objects in domain
1844 * @domain on its stack. Each call to this function should be paired with a
1845 * call to pop_appdomain_ref.
1848 mono_thread_push_appdomain_ref (MonoDomain *domain)
1850 MonoThread *thread = mono_thread_current ();
1853 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1854 EnterCriticalSection (&threads_mutex);
1855 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1856 LeaveCriticalSection (&threads_mutex);
1861 mono_thread_pop_appdomain_ref (void)
1863 MonoThread *thread = mono_thread_current ();
1866 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1867 EnterCriticalSection (&threads_mutex);
1868 /* FIXME: How can the list be empty ? */
1869 if (thread->appdomain_refs)
1870 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1871 LeaveCriticalSection (&threads_mutex);
1876 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1879 EnterCriticalSection (&threads_mutex);
1880 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1881 LeaveCriticalSection (&threads_mutex);
1885 typedef struct abort_appdomain_data {
1886 struct wait_data wait;
1888 } abort_appdomain_data;
1891 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1893 MonoThread *thread = (MonoThread*)value;
1894 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1895 MonoDomain *domain = data->domain;
1897 if (mono_thread_has_appdomain_ref (thread, domain)) {
1898 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1899 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1903 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1905 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1906 data->wait.handles [data->wait.num] = handle;
1907 data->wait.threads [data->wait.num] = thread;
1910 /* Just ignore the rest, we can't do anything with
1918 * mono_threads_abort_appdomain_threads:
1920 * Abort threads which has references to the given appdomain.
1923 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1925 abort_appdomain_data user_data;
1928 /* printf ("ABORT BEGIN.\n"); */
1930 start_time = GetTickCount ();
1932 EnterCriticalSection (&threads_mutex);
1934 user_data.domain = domain;
1935 user_data.wait.num = 0;
1936 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1937 LeaveCriticalSection (&threads_mutex);
1939 if (user_data.wait.num > 0)
1940 wait_for_tids (&user_data.wait, timeout);
1942 /* Update remaining time */
1943 timeout -= GetTickCount () - start_time;
1944 start_time = GetTickCount ();
1949 while (user_data.wait.num > 0);
1951 /* printf ("ABORT DONE.\n"); */
1957 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1959 MonoThread *thread = (MonoThread*)value;
1960 MonoDomain *domain = (MonoDomain*)user_data;
1963 /* No locking needed here */
1965 if (thread->culture_info) {
1966 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1967 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1968 thread->culture_info [i] = NULL;
1971 if (thread->ui_culture_info) {
1972 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1973 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1974 thread->ui_culture_info [i] = NULL;
1980 * mono_threads_clear_cached_culture:
1982 * Clear the cached_current_culture from all threads if it is in the
1986 mono_threads_clear_cached_culture (MonoDomain *domain)
1988 EnterCriticalSection (&threads_mutex);
1989 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1990 LeaveCriticalSection (&threads_mutex);
1994 * mono_thread_get_pending_exception:
1996 * Return an exception which needs to be raised when leaving a catch clause.
1997 * This is used for undeniable exception propagation.
2000 mono_thread_get_pending_exception (void)
2002 MonoThread *thread = mono_thread_current ();
2004 MONO_ARCH_SAVE_REGS;
2006 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2008 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2009 * exception if the thread no longer references a dying appdomain.
2011 thread->abort_exc->trace_ips = NULL;
2012 thread->abort_exc->stack_trace = NULL;
2013 return thread->abort_exc;
2019 #define NUM_STATIC_DATA_IDX 8
2020 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2021 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2026 * mono_alloc_static_data
2028 * Allocate memory blocks for storing threads or context static data
2031 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2033 guint idx = (offset >> 24) - 1;
2036 gpointer* static_data = *static_data_ptr;
2038 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2039 *static_data_ptr = static_data;
2040 static_data [0] = static_data;
2043 for (i = 1; i <= idx; ++i) {
2044 if (static_data [i])
2046 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2051 * mono_init_static_data_info
2053 * Initializes static data counters
2055 static void mono_init_static_data_info (StaticDataInfo *static_data)
2057 static_data->idx = 0;
2058 static_data->offset = 0;
2062 * mono_alloc_static_data_slot
2064 * Generates an offset for static data. static_data contains the counters
2065 * used to generate it.
2068 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2072 if (!static_data->idx && !static_data->offset) {
2074 * we use the first chunk of the first allocation also as
2075 * an array for the rest of the data
2077 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2079 static_data->offset += align - 1;
2080 static_data->offset &= ~(align - 1);
2081 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2082 static_data->idx ++;
2083 g_assert (size <= static_data_size [static_data->idx]);
2085 * massive unloading and reloading of domains with thread-static
2086 * data may eventually exceed the allocated storage...
2087 * Need to check what the MS runtime does in that case.
2088 * Note that for each appdomain, we need to allocate a separate
2089 * thread data slot for security reasons. We could keep track
2090 * of the slots per-domain and when the domain is unloaded
2091 * out the slots on a sort of free list.
2093 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2094 static_data->offset = 0;
2096 offset = static_data->offset | ((static_data->idx + 1) << 24);
2097 static_data->offset += size;
2102 * ensure thread static fields already allocated are valid for thread
2103 * This function is called when a thread is created or on thread attach.
2106 thread_adjust_static_data (MonoThread *thread)
2110 EnterCriticalSection (&threads_mutex);
2111 if (thread_static_info.offset || thread_static_info.idx > 0) {
2112 /* get the current allocated size */
2113 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2114 mono_alloc_static_data (&(thread->static_data), offset);
2116 LeaveCriticalSection (&threads_mutex);
2120 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2122 MonoThread *thread = value;
2123 guint32 offset = GPOINTER_TO_UINT (user);
2125 mono_alloc_static_data (&(thread->static_data), offset);
2129 * The offset for a special static variable is composed of three parts:
2130 * a bit that indicates the type of static data (0:thread, 1:context),
2131 * an index in the array of chunks of memory for the thread (thread->static_data)
2132 * and an offset in that chunk of mem. This allows allocating less memory in the
2137 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2140 if (static_type == SPECIAL_STATIC_THREAD)
2142 EnterCriticalSection (&threads_mutex);
2143 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2144 /* This can be called during startup */
2145 if (threads != NULL)
2146 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2147 LeaveCriticalSection (&threads_mutex);
2151 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2152 EnterCriticalSection (&contexts_mutex);
2153 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2154 LeaveCriticalSection (&contexts_mutex);
2155 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2161 mono_get_special_static_data (guint32 offset)
2163 /* The high bit means either thread (0) or static (1) data. */
2165 guint32 static_type = (offset & 0x80000000);
2168 offset &= 0x7fffffff;
2169 idx = (offset >> 24) - 1;
2171 if (static_type == 0)
2173 MonoThread *thread = mono_thread_current ();
2174 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2178 /* Allocate static data block under demand, since we don't have a list
2181 MonoAppContext *context = mono_context_get ();
2182 if (!context->static_data || !context->static_data [idx]) {
2183 EnterCriticalSection (&contexts_mutex);
2184 mono_alloc_static_data (&(context->static_data), offset);
2185 LeaveCriticalSection (&contexts_mutex);
2187 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2191 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2193 MonoThread *thread=(MonoThread *)value;
2194 guint32 self=GPOINTER_TO_UINT (user);
2196 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid));
2198 if(thread->tid==self)
2201 SuspendThread (thread->handle);
2204 void mono_gc_stop_world (void)
2206 guint32 self=GetCurrentThreadId ();
2208 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads));
2210 EnterCriticalSection (&threads_mutex);
2212 if (threads != NULL)
2213 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2215 LeaveCriticalSection (&threads_mutex);
2218 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2220 MonoThread *thread=(MonoThread *)value;
2221 guint32 self=GPOINTER_TO_UINT (user);
2223 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid));
2225 if(thread->tid==self)
2228 ResumeThread (thread->handle);
2231 void mono_gc_start_world (void)
2233 guint32 self=GetCurrentThreadId ();
2235 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads));
2237 EnterCriticalSection (&threads_mutex);
2239 if (threads != NULL)
2240 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2242 LeaveCriticalSection (&threads_mutex);
2246 static CALLBACK void dummy_apc (ULONG_PTR param)
2250 static guint32 dummy_apc (gpointer param)
2257 * mono_thread_execute_interruption
2259 * Performs the operation that the requested thread state requires (abort,
2262 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2264 mono_monitor_enter (thread->synch_lock);
2266 if (thread->interruption_requested) {
2267 /* this will consume pending APC calls */
2268 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2269 EnterCriticalSection (&interruption_mutex);
2270 thread_interruption_requested--;
2271 LeaveCriticalSection (&interruption_mutex);
2272 thread->interruption_requested = FALSE;
2275 if ((thread->state & ThreadState_AbortRequested) != 0) {
2276 if (thread->abort_exc == NULL)
2277 thread->abort_exc = mono_get_exception_thread_abort ();
2278 mono_monitor_exit (thread->synch_lock);
2279 return thread->abort_exc;
2281 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2282 thread->state &= ~ThreadState_SuspendRequested;
2283 thread->state |= ThreadState_Suspended;
2284 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2285 mono_monitor_exit (thread->synch_lock);
2287 WaitForSingleObject (thread->suspend_event, INFINITE);
2289 mono_monitor_enter (thread->synch_lock);
2290 CloseHandle (thread->suspend_event);
2291 thread->suspend_event = NULL;
2292 thread->state &= ~ThreadState_Suspended;
2294 /* The thread that requested the resume will have replaced this event
2295 * and will be waiting for it
2297 SetEvent (thread->resume_event);
2298 mono_monitor_exit (thread->synch_lock);
2301 else if ((thread->state & ThreadState_StopRequested) != 0) {
2302 /* FIXME: do this through the JIT? */
2303 mono_monitor_exit (thread->synch_lock);
2304 mono_thread_exit ();
2308 mono_monitor_exit (thread->synch_lock);
2313 * mono_thread_request_interruption
2315 * A signal handler can call this method to request the interruption of a
2316 * thread. The result of the interruption will depend on the current state of
2317 * the thread. If the result is an exception that needs to be throw, it is
2318 * provided as return value.
2320 MonoException* mono_thread_request_interruption (gboolean running_managed)
2322 MonoThread *thread = mono_thread_current ();
2324 /* The thread may already be stopping */
2328 mono_monitor_enter (thread->synch_lock);
2330 if (thread->interruption_requested) {
2331 mono_monitor_exit (thread->synch_lock);
2335 if (!running_managed || is_running_protected_wrapper ()) {
2336 /* Can't stop while in unmanaged code. Increase the global interruption
2337 request count. When exiting the unmanaged method the count will be
2338 checked and the thread will be interrupted. */
2340 EnterCriticalSection (&interruption_mutex);
2341 thread_interruption_requested++;
2342 LeaveCriticalSection (&interruption_mutex);
2344 thread->interruption_requested = TRUE;
2345 mono_monitor_exit (thread->synch_lock);
2347 /* this will awake the thread if it is in WaitForSingleObject
2349 QueueUserAPC (dummy_apc, thread->handle, NULL);
2354 mono_monitor_exit (thread->synch_lock);
2355 return mono_thread_execute_interruption (thread);
2359 gboolean mono_thread_interruption_requested ()
2361 if (thread_interruption_requested) {
2362 MonoThread *thread = mono_thread_current ();
2363 /* The thread may already be stopping */
2365 return (thread->interruption_requested);
2370 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2372 MonoThread *thread = mono_thread_current ();
2374 /* The thread may already be stopping */
2378 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2379 MonoException* exc = mono_thread_execute_interruption (thread);
2380 if (exc) mono_raise_exception (exc);
2385 * Performs the interruption of the current thread, if one has been requested,
2386 * and the thread is not running a protected wrapper.
2388 void mono_thread_interruption_checkpoint ()
2390 mono_thread_interruption_checkpoint_request (FALSE);
2394 * Performs the interruption of the current thread, if one has been requested.
2396 void mono_thread_force_interruption_checkpoint ()
2398 mono_thread_interruption_checkpoint_request (TRUE);
2402 * mono_thread_interruption_request_flag:
2404 * Returns the address of a flag that will be non-zero if an interruption has
2405 * been requested for a thread. The thread to interrupt may not be the current
2406 * thread, so an additional call to mono_thread_interruption_requested() or
2407 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2410 gint32* mono_thread_interruption_request_flag ()
2412 return &thread_interruption_requested;
2415 #ifdef WITH_INCLUDED_LIBGC
2417 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2419 MonoThread *thread=(MonoThread *)value;
2420 guint32 *selfp=(guint32 *)user, self = *selfp;
2422 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr));
2424 if(thread->tid==self) {
2425 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr));
2426 GC_push_all_stack (selfp, thread->stack_ptr);
2430 #ifdef PLATFORM_WIN32
2431 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2433 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2437 void mono_gc_push_all_stacks (void)
2439 guint32 self=GetCurrentThreadId ();
2441 LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads));
2443 EnterCriticalSection (&threads_mutex);
2445 if (threads != NULL)
2446 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2448 LeaveCriticalSection (&threads_mutex);
2451 #endif /* WITH_INCLUDED_LIBGC */