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 * The "os_handle" field of the WaitHandle class.
61 static MonoClassField *wait_handle_os_handle_field = NULL;
63 /* Controls access to the 'threads' hash table */
64 static CRITICAL_SECTION threads_mutex;
66 /* Controls access to context static data */
67 static CRITICAL_SECTION contexts_mutex;
69 /* Holds current status of static data heap */
70 static StaticDataInfo thread_static_info;
71 static StaticDataInfo context_static_info;
73 /* The hash of existing threads (key is thread ID) that need joining
76 static MonoGHashTable *threads=NULL;
78 /* The TLS key that holds the MonoObject assigned to each thread */
79 static guint32 current_object_key = -1;
82 /* we need to use both the Tls* functions and __thread because
83 * the gc needs to see all the threads
85 static __thread MonoThread * tls_current_object;
86 #define SET_CURRENT_OBJECT(x) do { \
87 tls_current_object = x; \
88 TlsSetValue (current_object_key, x); \
90 #define GET_CURRENT_OBJECT() tls_current_object
92 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
93 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
96 /* function called at thread start */
97 static MonoThreadStartCB mono_thread_start_cb = NULL;
99 /* function called at thread attach */
100 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
102 /* function called at thread cleanup */
103 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
105 /* function called when a new thread has been created */
106 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
108 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
109 static guint32 slothash_key = -1;
111 /* The default stack size for each thread */
112 static guint32 default_stacksize = 0;
114 static void thread_adjust_static_data (MonoThread *thread);
115 static void mono_init_static_data_info (StaticDataInfo *static_data);
116 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
118 /* Spin lock for InterlockedXXX 64 bit functions */
119 static CRITICAL_SECTION interlocked_mutex;
121 /* Controls access to interruption flag */
122 static CRITICAL_SECTION interruption_mutex;
124 /* global count of thread interruptions requested */
125 static gint32 thread_interruption_requested = 0;
128 /* handle_store() and handle_remove() manage the array of threads that
129 * still need to be waited for when the main thread exits.
131 static void handle_store(MonoThread *thread)
133 EnterCriticalSection(&threads_mutex);
136 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
141 MONO_GC_REGISTER_ROOT (threads);
142 threads=mono_g_hash_table_new(NULL, NULL);
145 /* We don't need to duplicate thread->handle, because it is
146 * only closed when the thread object is finalized by the GC.
148 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
149 LeaveCriticalSection(&threads_mutex);
152 static void handle_remove(guint32 tid)
155 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
158 EnterCriticalSection(&threads_mutex);
161 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
163 LeaveCriticalSection(&threads_mutex);
165 /* Don't close the handle here, wait for the object finalizer
166 * to do it. Otherwise, the following race condition applies:
168 * 1) Thread exits (and handle_remove() closes the handle)
170 * 2) Some other handle is reassigned the same slot
172 * 3) Another thread tries to join the first thread, and
173 * blocks waiting for the reassigned handle to be signalled
174 * (which might never happen). This is possible, because the
175 * thread calling Join() still has a reference to the first
180 static void thread_cleanup (MonoThread *thread)
182 mono_release_type_locks (thread);
184 if (!mono_monitor_enter (thread->synch_lock))
187 thread->state |= ThreadState_Stopped;
188 mono_monitor_exit (thread->synch_lock);
190 mono_profiler_thread_end (thread->tid);
191 handle_remove (thread->tid);
193 mono_thread_pop_appdomain_ref ();
195 if (mono_thread_cleanup)
196 mono_thread_cleanup (thread);
199 static guint32 start_wrapper(void *data)
201 struct StartInfo *start_info=(struct StartInfo *)data;
202 guint32 (*start_func)(void *);
205 MonoThread *thread=start_info->obj;
208 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
209 GetCurrentThreadId ());
212 /* We can be sure start_info->obj->tid and
213 * start_info->obj->handle have been set, because the thread
214 * was created suspended, and these values were set before the
220 SET_CURRENT_OBJECT (thread);
222 if (!mono_domain_set (start_info->domain, FALSE)) {
223 /* No point in raising an appdomain_unloaded exception here */
224 /* FIXME: Cleanup here */
228 start_func = start_info->func;
229 this = start_info->this;
231 /* This MUST be called before any managed code can be
232 * executed, as it calls the callback function that (for the
233 * jit) sets the lmf marker.
235 mono_thread_new_init (tid, &tid, start_func);
236 thread->stack_ptr = &tid;
239 g_message (G_GNUC_PRETTY_FUNCTION
240 ": (%d,%d) Setting thread stack to %p",
241 GetCurrentThreadId (), getpid (), thread->stack_ptr);
245 g_message (G_GNUC_PRETTY_FUNCTION
246 ": (%d) Setting current_object_key to %p",
247 GetCurrentThreadId (), thread);
250 mono_profiler_thread_start (tid);
252 if(thread->start_notify!=NULL) {
253 /* Let the thread that called Start() know we're
256 ReleaseSemaphore (thread->start_notify, 1, NULL);
261 /* Every thread references the appdomain which created it */
262 mono_thread_push_appdomain_ref (mono_domain_get ());
264 thread_adjust_static_data (thread);
266 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
270 #ifdef PLATFORM_WIN32
271 /* If the thread calls ExitThread at all, this remaining code
272 * will not be executed, but the main thread will eventually
273 * call thread_cleanup() on this thread's behalf.
277 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
278 GetCurrentThreadId ());
281 /* Remove the reference to the thread object in the TLS data,
282 * so the thread object can be finalized. This won't be
283 * reached if the thread threw an uncaught exception, so those
284 * thread handles will stay referenced :-( (This is due to
285 * missing support for scanning thread-specific data in the
286 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
289 SET_CURRENT_OBJECT (NULL);
292 thread_cleanup (thread);
297 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
299 if (mono_thread_start_cb) {
300 mono_thread_start_cb (tid, stack_start, func);
303 if (mono_thread_callbacks)
304 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
307 void mono_threads_set_default_stacksize (guint32 stacksize)
309 default_stacksize = stacksize;
312 guint32 mono_threads_get_default_stacksize (void)
314 return default_stacksize;
317 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
320 HANDLE thread_handle;
321 struct StartInfo *start_info;
324 thread=(MonoThread *)mono_object_new (domain,
325 mono_defaults.thread_class);
327 start_info=g_new0 (struct StartInfo, 1);
328 start_info->func = func;
329 start_info->obj = thread;
330 start_info->domain = domain;
331 start_info->this = arg;
333 /* Create suspended, so we can do some housekeeping before the thread
336 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
337 thread_handle = GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
338 CREATE_SUSPENDED, &tid);
340 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
341 CREATE_SUSPENDED, &tid);
344 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
347 g_assert (thread_handle);
349 thread->handle=thread_handle;
352 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
354 handle_store(thread);
356 ResumeThread (thread_handle);
360 mono_thread_attach (MonoDomain *domain)
363 HANDLE thread_handle;
366 if ((thread = mono_thread_current ())) {
367 /* Already attached */
371 thread = (MonoThread *)mono_object_new (domain,
372 mono_defaults.thread_class);
374 thread_handle = GetCurrentThread ();
375 g_assert (thread_handle);
377 tid=GetCurrentThreadId ();
379 thread->handle=thread_handle;
381 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
384 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
388 handle_store(thread);
391 g_message (G_GNUC_PRETTY_FUNCTION
392 ": (%d) Setting current_object_key to %p",
393 GetCurrentThreadId (), thread);
396 SET_CURRENT_OBJECT (thread);
397 mono_domain_set (domain, TRUE);
399 thread_adjust_static_data (thread);
401 if (mono_thread_attach_cb) {
402 mono_thread_attach_cb (tid, &tid);
409 mono_thread_detach (MonoThread *thread)
411 g_return_if_fail (thread != NULL);
414 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
416 SET_CURRENT_OBJECT (NULL);
418 thread_cleanup (thread);
424 MonoThread *thread = mono_thread_current ();
426 SET_CURRENT_OBJECT (NULL);
427 thread_cleanup (thread);
432 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
435 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
436 guint32 (*start_func)(void *);
437 struct StartInfo *start_info;
445 g_message(G_GNUC_PRETTY_FUNCTION
446 ": Trying to start a new thread: this (%p) start (%p)",
450 im = mono_get_delegate_invoke (start->vtable->klass);
451 im = mono_marshal_get_delegate_invoke (im);
452 if (mono_thread_callbacks)
453 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
455 start_func = mono_compile_method (im);
457 if(start_func==NULL) {
458 g_warning(G_GNUC_PRETTY_FUNCTION
459 ": Can't locate start method!");
462 /* This is freed in start_wrapper */
463 start_info = g_new0 (struct StartInfo, 1);
464 start_info->func = start_func;
465 start_info->this = delegate;
466 start_info->obj = this;
467 start_info->domain = mono_domain_get ();
469 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
470 if(this->start_notify==NULL) {
471 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
475 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
476 thread=GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
477 CREATE_SUSPENDED, &tid);
479 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
480 CREATE_SUSPENDED, &tid);
483 g_warning(G_GNUC_PRETTY_FUNCTION
484 ": CreateThread error 0x%x", GetLastError());
491 /* Don't call handle_store() here, delay it to Start.
492 * We can't join a thread (trying to will just block
493 * forever) until it actually starts running, so don't
494 * store the handle till then.
498 g_message(G_GNUC_PRETTY_FUNCTION
499 ": Started thread ID %d (handle %p)", tid, thread);
506 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
512 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
516 CloseHandle (thread);
519 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
525 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
526 GetCurrentThreadId (), this, this->tid);
529 /* Only store the handle when the thread is about to be
530 * launched, to avoid the main thread deadlocking while trying
531 * to clean up a thread that will never be signalled.
535 if (mono_thread_callbacks)
536 (* mono_thread_callbacks->start_resume) (this->tid);
538 ResumeThread(thread);
540 if (mono_thread_callbacks)
541 (* mono_thread_callbacks->end_resume) (this->tid);
543 if(this->start_notify!=NULL) {
544 /* Wait for the thread to set up its TLS data etc, so
545 * theres no potential race condition if someone tries
546 * to look up the data believing the thread has
551 g_message(G_GNUC_PRETTY_FUNCTION
552 ": (%d) waiting for thread %p (%d) to start",
553 GetCurrentThreadId (), this, this->tid);
556 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
557 CloseHandle (this->start_notify);
558 this->start_notify=NULL;
562 g_message(G_GNUC_PRETTY_FUNCTION
563 ": (%d) Done launching thread %p (%d)",
564 GetCurrentThreadId (), this, this->tid);
568 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
570 MonoThread *thread = mono_thread_current ();
575 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
578 mono_monitor_enter (thread->synch_lock);
579 thread->state |= ThreadState_WaitSleepJoin;
580 mono_monitor_exit (thread->synch_lock);
584 mono_monitor_enter (thread->synch_lock);
585 thread->state &= ~ThreadState_WaitSleepJoin;
586 mono_monitor_exit (thread->synch_lock);
590 ves_icall_System_Threading_Thread_GetDomainID (void)
594 return mono_domain_get()->domain_id;
598 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
603 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
607 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
610 g_free (this_obj->name);
612 this_obj->name = g_new (gunichar2, mono_string_length (name));
613 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
614 this_obj->name_len = mono_string_length (name);
617 this_obj->name = NULL;
620 /* the jit may read the compiled code of this function */
622 mono_thread_current (void)
627 thread = GET_CURRENT_OBJECT ();
628 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
632 return GET_CURRENT_OBJECT ();
636 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
637 int ms, HANDLE thread)
643 mono_monitor_enter (this->synch_lock);
644 this->state |= ThreadState_WaitSleepJoin;
645 mono_monitor_exit (this->synch_lock);
651 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
655 ret=WaitForSingleObjectEx (thread, ms, TRUE);
657 mono_monitor_enter (this->synch_lock);
658 this->state &= ~ThreadState_WaitSleepJoin;
659 mono_monitor_exit (this->synch_lock);
661 if(ret==WAIT_OBJECT_0) {
663 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
670 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
676 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
681 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
684 /* Object location stored here */
685 TlsSetValue(slothash_key, data);
688 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
694 data=TlsGetValue(slothash_key);
697 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
703 /* FIXME: exitContext isnt documented */
704 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
710 MonoObject *waitHandle;
715 numhandles = mono_array_length(mono_handles);
716 handles = g_new0(HANDLE, numhandles);
718 if (wait_handle_os_handle_field == 0) {
719 /* Get the field os_handle which will contain the actual handle */
720 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
721 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
724 for(i = 0; i < numhandles; i++) {
725 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
726 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
733 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
737 if(ret==WAIT_FAILED) {
738 #ifdef THREAD_WAIT_DEBUG
739 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
740 GetCurrentThreadId ());
743 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
744 /* Do we want to try again if we get
745 * WAIT_IO_COMPLETION? The documentation for
746 * WaitHandle doesn't give any clues. (We'd have to
747 * fiddle with the timeout if we retry.)
749 #ifdef THREAD_WAIT_DEBUG
750 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
751 GetCurrentThreadId ());
759 /* FIXME: exitContext isnt documented */
760 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
766 MonoObject *waitHandle;
771 numhandles = mono_array_length(mono_handles);
772 handles = g_new0(HANDLE, numhandles);
774 if (wait_handle_os_handle_field == 0) {
775 /* Get the field os_handle which will contain the actual handle */
776 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
777 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
780 for(i = 0; i < numhandles; i++) {
781 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
782 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
789 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
793 #ifdef THREAD_WAIT_DEBUG
794 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
795 GetCurrentThreadId (), ret);
799 * These need to be here. See MSDN dos on WaitForMultipleObjects.
801 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
802 return ret - WAIT_OBJECT_0;
804 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
805 return ret - WAIT_ABANDONED_0;
812 /* FIXME: exitContext isnt documented */
813 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
819 #ifdef THREAD_WAIT_DEBUG
820 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
821 GetCurrentThreadId (), handle, ms);
828 ret=WaitForSingleObjectEx (handle, ms, TRUE);
830 if(ret==WAIT_FAILED) {
831 #ifdef THREAD_WAIT_DEBUG
832 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
833 GetCurrentThreadId ());
836 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
837 /* Do we want to try again if we get
838 * WAIT_IO_COMPLETION? The documentation for
839 * WaitHandle doesn't give any clues. (We'd have to
840 * fiddle with the timeout if we retry.)
842 #ifdef THREAD_WAIT_DEBUG
843 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
844 GetCurrentThreadId ());
852 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
861 mutex = CreateMutex (NULL, owned, NULL);
863 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
865 if (GetLastError () == ERROR_ALREADY_EXISTS) {
873 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
876 ReleaseMutex(handle);
879 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
882 return(CreateEvent (NULL, manual, initial,
883 name==NULL?NULL:mono_string_chars (name)));
886 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
889 return (SetEvent(handle));
892 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
895 return (ResetEvent(handle));
899 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
902 CloseHandle (handle);
905 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
909 return InterlockedIncrement (location);
912 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
919 EnterCriticalSection(&interlocked_mutex);
921 lowret = InterlockedIncrement((gint32 *) location);
923 highret = InterlockedIncrement((gint32 *) location + 1);
925 highret = *((gint32 *) location + 1);
927 LeaveCriticalSection(&interlocked_mutex);
929 return (gint64) highret << 32 | (gint64) lowret;
932 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
936 return InterlockedDecrement(location);
939 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
946 EnterCriticalSection(&interlocked_mutex);
948 lowret = InterlockedDecrement((gint32 *) location);
950 highret = InterlockedDecrement((gint32 *) location + 1);
952 highret = *((gint32 *) location + 1);
954 LeaveCriticalSection(&interlocked_mutex);
956 return (gint64) highret << 32 | (gint64) lowret;
959 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
963 return InterlockedExchange(location1, value);
966 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
970 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
973 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
975 IntFloatUnion val, ret;
980 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
985 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
989 return InterlockedCompareExchange(location1, value, comparand);
992 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
996 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
999 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1001 IntFloatUnion val, ret, cmp;
1003 MONO_ARCH_SAVE_REGS;
1006 cmp.fval = comparand;
1007 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1013 mono_thread_get_abort_signal (void)
1023 #endif /* __MINGW32__ */
1027 static guint32 interruption_request_apc (gpointer param)
1029 MonoException* exc = mono_thread_request_interruption (FALSE);
1030 if (exc) mono_raise_exception (exc);
1033 #endif /* __MINGW32__ */
1036 * signal_thread_state_change
1038 * Tells the thread that his state has changed and it has to enter the new
1039 * state as soon as possible.
1041 static void signal_thread_state_change (MonoThread *thread)
1044 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1046 /* fixme: store the state somewhere */
1047 #ifdef PTHREAD_POINTER_ID
1048 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1050 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1052 #endif /* __MINGW32__ */
1056 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1058 MONO_ARCH_SAVE_REGS;
1060 mono_monitor_enter (thread->synch_lock);
1062 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1063 (thread->state & ThreadState_StopRequested) != 0)
1065 mono_monitor_exit (thread->synch_lock);
1069 thread->state |= ThreadState_AbortRequested;
1070 thread->abort_state = state;
1071 thread->abort_exc = NULL;
1073 mono_monitor_exit (thread->synch_lock);
1076 g_message (G_GNUC_PRETTY_FUNCTION
1077 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1078 thread, thread->tid);
1081 /* Make sure the thread is awake */
1082 ves_icall_System_Threading_Thread_Resume (thread);
1084 signal_thread_state_change (thread);
1088 ves_icall_System_Threading_Thread_ResetAbort (void)
1090 MonoThread *thread = mono_thread_current ();
1092 MONO_ARCH_SAVE_REGS;
1094 mono_monitor_enter (thread->synch_lock);
1096 thread->state &= ~ThreadState_AbortRequested;
1098 if (!thread->abort_exc) {
1099 const char *msg = "Unable to reset abort because no abort was requested";
1100 mono_monitor_exit (thread->synch_lock);
1101 mono_raise_exception (mono_get_exception_thread_state (msg));
1103 thread->abort_exc = NULL;
1104 thread->abort_state = NULL;
1107 mono_monitor_exit (thread->synch_lock);
1111 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1113 MONO_ARCH_SAVE_REGS;
1115 mono_monitor_enter (thread->synch_lock);
1117 if ((thread->state & ThreadState_Suspended) != 0 ||
1118 (thread->state & ThreadState_SuspendRequested) != 0 ||
1119 (thread->state & ThreadState_StopRequested) != 0)
1121 mono_monitor_exit (thread->synch_lock);
1125 thread->state |= ThreadState_SuspendRequested;
1126 mono_monitor_exit (thread->synch_lock);
1128 signal_thread_state_change (thread);
1132 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1134 MONO_ARCH_SAVE_REGS;
1136 mono_monitor_enter (thread->synch_lock);
1138 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1139 thread->state &= ~ThreadState_SuspendRequested;
1140 mono_monitor_exit (thread->synch_lock);
1144 if ((thread->state & ThreadState_Suspended) == 0)
1146 mono_monitor_exit (thread->synch_lock);
1150 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1152 /* Awake the thread */
1153 SetEvent (thread->suspend_event);
1155 mono_monitor_exit (thread->synch_lock);
1157 /* Wait for the thread to awake */
1158 WaitForSingleObject (thread->resume_event, INFINITE);
1159 CloseHandle (thread->resume_event);
1160 thread->resume_event = NULL;
1164 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1169 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1170 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1171 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1173 *((gboolean*)data) = TRUE;
1180 is_running_protected_wrapper (void)
1182 gboolean found = FALSE;
1183 mono_stack_walk (find_wrapper, &found);
1187 void mono_thread_stop (MonoThread *thread)
1189 mono_monitor_enter (thread->synch_lock);
1191 if ((thread->state & ThreadState_StopRequested) != 0 ||
1192 (thread->state & ThreadState_Stopped) != 0)
1194 mono_monitor_exit (thread->synch_lock);
1198 /* Make sure the thread is awake */
1199 ves_icall_System_Threading_Thread_Resume (thread);
1201 thread->state |= ThreadState_StopRequested;
1202 thread->state &= ~ThreadState_AbortRequested;
1204 mono_monitor_exit (thread->synch_lock);
1206 signal_thread_state_change (thread);
1210 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1212 return *((volatile gint8 *) (ptr));
1216 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1218 return *((volatile gint16 *) (ptr));
1222 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1224 return *((volatile gint32 *) (ptr));
1228 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1230 return *((volatile gint64 *) (ptr));
1234 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1236 return (void *) *((volatile void **) ptr);
1240 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1242 *((volatile gint8 *) ptr) = value;
1246 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1248 *((volatile gint16 *) ptr) = value;
1252 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1254 *((volatile gint32 *) ptr) = value;
1258 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1260 *((volatile gint64 *) ptr) = value;
1264 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1266 *((volatile void **) ptr) = value;
1269 void mono_thread_init (MonoThreadStartCB start_cb,
1270 MonoThreadAttachCB attach_cb)
1272 InitializeCriticalSection(&threads_mutex);
1273 InitializeCriticalSection(&interlocked_mutex);
1274 InitializeCriticalSection(&contexts_mutex);
1275 InitializeCriticalSection(&interruption_mutex);
1277 mono_init_static_data_info (&thread_static_info);
1278 mono_init_static_data_info (&context_static_info);
1280 current_object_key=TlsAlloc();
1282 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1283 current_object_key);
1286 mono_thread_start_cb = start_cb;
1287 mono_thread_attach_cb = attach_cb;
1289 slothash_key=TlsAlloc();
1291 /* Get a pseudo handle to the current process. This is just a
1292 * kludge so that wapi can build a process handle if needed.
1293 * As a pseudo handle is returned, we don't need to clean
1296 GetCurrentProcess ();
1300 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1302 mono_thread_cleanup = func;
1305 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1307 mono_thread_callbacks = callbacks;
1311 static void print_tids (gpointer key, gpointer value, gpointer user)
1313 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1319 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1320 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1324 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1329 g_message(G_GNUC_PRETTY_FUNCTION
1330 ": %d threads to wait for in this batch", wait->num);
1333 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1335 if(ret==WAIT_FAILED) {
1336 /* See the comment in build_wait_tids() */
1338 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1344 for(i=0; i<wait->num; i++) {
1345 guint32 tid=wait->threads[i]->tid;
1346 CloseHandle (wait->handles[i]);
1348 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1349 /* This thread must have been killed, because
1350 * it hasn't cleaned itself up. (It's just
1351 * possible that the thread exited before the
1352 * parent thread had a chance to store the
1353 * handle, and now there is another pointer to
1354 * the already-exited thread stored. In this
1355 * case, we'll just get two
1356 * mono_profiler_thread_end() calls for the
1361 g_message (G_GNUC_PRETTY_FUNCTION
1362 ": cleaning up after thread %d", tid);
1364 thread_cleanup (wait->threads[i]);
1369 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1371 struct wait_data *wait=(struct wait_data *)user;
1373 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1375 MonoThread *thread=(MonoThread *)value;
1377 /* Ignore background threads, we abort them later */
1378 if (thread->state & ThreadState_Background)
1379 return; /* just leave, ignore */
1381 if (mono_gc_is_finalizer_thread (thread))
1384 if (thread == mono_thread_current ())
1387 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1391 wait->handles[wait->num]=handle;
1392 wait->threads[wait->num]=thread;
1395 /* Just ignore the rest, we can't do anything with
1402 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1404 struct wait_data *wait=(struct wait_data *)user;
1405 guint32 self = GetCurrentThreadId ();
1406 MonoThread *thread = (MonoThread *) value;
1409 /* The finalizer thread is not a background thread */
1410 if (thread->tid != self && thread->state & ThreadState_Background) {
1412 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1416 wait->handles[wait->num]=thread->handle;
1417 wait->threads[wait->num]=thread;
1420 if(thread->state & ThreadState_AbortRequested ||
1421 thread->state & ThreadState_Aborted) {
1423 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1429 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1431 mono_thread_stop (thread);
1435 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1438 void mono_thread_manage (void)
1440 struct wait_data *wait=g_new0 (struct wait_data, 1);
1442 /* join each thread that's still running */
1444 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1447 EnterCriticalSection (&threads_mutex);
1450 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1452 LeaveCriticalSection (&threads_mutex);
1455 LeaveCriticalSection (&threads_mutex);
1458 EnterCriticalSection (&threads_mutex);
1460 g_message(G_GNUC_PRETTY_FUNCTION
1461 ":There are %d threads to join",
1462 mono_g_hash_table_size (threads));
1463 mono_g_hash_table_foreach (threads, print_tids, NULL);
1467 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1468 LeaveCriticalSection (&threads_mutex);
1470 /* Something to wait for */
1471 wait_for_tids (wait, INFINITE);
1473 } while(wait->num>0);
1475 mono_thread_pool_cleanup ();
1477 EnterCriticalSection(&threads_mutex);
1480 * Remove everything but the finalizer thread and self.
1481 * Also abort all the background threads
1484 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1486 LeaveCriticalSection(&threads_mutex);
1489 /* Something to wait for */
1490 wait_for_tids (wait, INFINITE);
1493 * give the subthreads a chance to really quit (this is mainly needed
1494 * to get correct user and system times from getrusage/wait/time(1)).
1495 * This could be removed if we avoid pthread_detach() and use pthread_join().
1497 #ifndef PLATFORM_WIN32
1504 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1506 MonoThread *thread=(MonoThread *)value;
1507 guint32 self=GPOINTER_TO_UINT (user);
1509 if(thread->tid!=self) {
1510 /*TerminateThread (thread->handle, -1);*/
1514 void mono_thread_abort_all_other_threads (void)
1516 guint32 self=GetCurrentThreadId ();
1518 EnterCriticalSection (&threads_mutex);
1520 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1521 mono_g_hash_table_size (threads));
1522 mono_g_hash_table_foreach (threads, print_tids, NULL);
1525 mono_g_hash_table_foreach (threads, terminate_thread,
1526 GUINT_TO_POINTER (self));
1528 LeaveCriticalSection (&threads_mutex);
1532 * mono_thread_push_appdomain_ref:
1534 * Register that the current thread may have references to objects in domain
1535 * @domain on its stack. Each call to this function should be paired with a
1536 * call to pop_appdomain_ref.
1539 mono_thread_push_appdomain_ref (MonoDomain *domain)
1541 MonoThread *thread = mono_thread_current ();
1544 /* printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name); */
1545 EnterCriticalSection (&threads_mutex);
1546 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1547 LeaveCriticalSection (&threads_mutex);
1552 mono_thread_pop_appdomain_ref (void)
1554 MonoThread *thread = mono_thread_current ();
1557 /* printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1558 EnterCriticalSection (&threads_mutex);
1559 /* FIXME: How can the list be empty ? */
1560 if (thread->appdomain_refs)
1561 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1562 LeaveCriticalSection (&threads_mutex);
1567 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1570 EnterCriticalSection (&threads_mutex);
1571 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1572 LeaveCriticalSection (&threads_mutex);
1576 typedef struct abort_appdomain_data {
1577 struct wait_data wait;
1579 } abort_appdomain_data;
1582 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1584 MonoThread *thread = (MonoThread*)value;
1585 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1586 MonoDomain *domain = data->domain;
1588 if (mono_thread_has_appdomain_ref (thread, domain)) {
1589 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1590 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1594 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1596 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1597 data->wait.handles [data->wait.num] = handle;
1598 data->wait.threads [data->wait.num] = thread;
1601 /* Just ignore the rest, we can't do anything with
1609 * mono_threads_abort_appdomain_threads:
1611 * Abort threads which has references to the given appdomain.
1614 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1616 abort_appdomain_data user_data;
1619 /* printf ("ABORT BEGIN.\n"); */
1621 start_time = GetTickCount ();
1623 EnterCriticalSection (&threads_mutex);
1625 user_data.domain = domain;
1626 user_data.wait.num = 0;
1627 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1628 LeaveCriticalSection (&threads_mutex);
1630 if (user_data.wait.num > 0)
1631 wait_for_tids (&user_data.wait, timeout);
1633 /* Update remaining time */
1634 timeout -= GetTickCount () - start_time;
1635 start_time = GetTickCount ();
1640 while (user_data.wait.num > 0);
1642 /* printf ("ABORT DONE.\n"); */
1648 * mono_thread_get_pending_exception:
1650 * Return an exception which needs to be raised when leaving a catch clause.
1651 * This is used for undeniable exception propagation.
1654 mono_thread_get_pending_exception (void)
1656 MonoThread *thread = mono_thread_current ();
1658 MONO_ARCH_SAVE_REGS;
1660 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1662 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1663 * exception if the thread no longer references a dying appdomain.
1665 thread->abort_exc->trace_ips = NULL;
1666 thread->abort_exc->stack_trace = NULL;
1667 return thread->abort_exc;
1673 #define NUM_STATIC_DATA_IDX 8
1674 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1675 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1680 * mono_alloc_static_data
1682 * Allocate memory blocks for storing threads or context static data
1685 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1687 guint idx = (offset >> 24) - 1;
1690 gpointer* static_data = *static_data_ptr;
1693 static_data = GC_MALLOC (static_data_size [0]);
1695 static_data = g_malloc0 (static_data_size [0]);
1697 *static_data_ptr = static_data;
1698 static_data [0] = static_data;
1701 for (i = 1; i < idx; ++i) {
1702 if (static_data [i])
1705 static_data [i] = GC_MALLOC (static_data_size [i]);
1707 static_data [i] = g_malloc0 (static_data_size [i]);
1713 * mono_init_static_data_info
1715 * Initializes static data counters
1717 static void mono_init_static_data_info (StaticDataInfo *static_data)
1719 static_data->idx = 0;
1720 static_data->offset = 0;
1724 * mono_alloc_static_data_slot
1726 * Generates an offset for static data. static_data contains the counters
1727 * used to generate it.
1730 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1734 if (!static_data->idx && !static_data->offset) {
1736 * we use the first chunk of the first allocation also as
1737 * an array for the rest of the data
1739 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1741 static_data->offset += align - 1;
1742 static_data->offset &= ~(align - 1);
1743 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1744 static_data->idx ++;
1745 g_assert (size <= static_data_size [static_data->idx]);
1747 * massive unloading and reloading of domains with thread-static
1748 * data may eventually exceed the allocated storage...
1749 * Need to check what the MS runtime does in that case.
1750 * Note that for each appdomain, we need to allocate a separate
1751 * thread data slot for security reasons. We could keep track
1752 * of the slots per-domain and when the domain is unloaded
1753 * out the slots on a sort of free list.
1755 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1756 static_data->offset = 0;
1758 offset = static_data->offset | ((static_data->idx + 1) << 24);
1759 static_data->offset += size;
1764 * ensure thread static fields already allocated are valid for thread
1765 * This function is called when a thread is created or on thread attach.
1768 thread_adjust_static_data (MonoThread *thread)
1772 EnterCriticalSection (&threads_mutex);
1773 if (thread_static_info.offset || thread_static_info.idx > 0) {
1774 /* get the current allocated size */
1775 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1776 mono_alloc_static_data (&(thread->static_data), offset);
1778 LeaveCriticalSection (&threads_mutex);
1782 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1784 MonoThread *thread = value;
1785 guint32 offset = GPOINTER_TO_UINT (user);
1787 mono_alloc_static_data (&(thread->static_data), offset);
1791 * The offset for a special static variable is composed of three parts:
1792 * a bit that indicates the type of static data (0:thread, 1:context),
1793 * an index in the array of chunks of memory for the thread (thread->static_data)
1794 * and an offset in that chunk of mem. This allows allocating less memory in the
1799 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1802 if (static_type == SPECIAL_STATIC_THREAD)
1804 EnterCriticalSection (&threads_mutex);
1805 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1806 /* This can be called during startup */
1807 if (threads != NULL)
1808 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1809 LeaveCriticalSection (&threads_mutex);
1813 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1814 EnterCriticalSection (&contexts_mutex);
1815 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1816 LeaveCriticalSection (&contexts_mutex);
1817 offset |= 0x80000000; /* Set the high bit to indicate context static data */
1823 mono_get_special_static_data (guint32 offset)
1825 /* The high bit means either thread (0) or static (1) data. */
1827 guint32 static_type = (offset & 0x80000000);
1830 offset &= 0x7fffffff;
1831 idx = (offset >> 24) - 1;
1833 if (static_type == 0)
1835 MonoThread *thread = mono_thread_current ();
1836 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1840 /* Allocate static data block under demand, since we don't have a list
1843 MonoAppContext *context = mono_context_get ();
1844 if (!context->static_data || !context->static_data [idx]) {
1845 EnterCriticalSection (&contexts_mutex);
1846 mono_alloc_static_data (&(context->static_data), offset);
1847 LeaveCriticalSection (&contexts_mutex);
1849 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
1853 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1855 MonoThread *thread=(MonoThread *)value;
1856 guint32 self=GPOINTER_TO_UINT (user);
1859 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1862 if(thread->tid==self)
1865 SuspendThread (thread->handle);
1868 void mono_gc_stop_world (void)
1870 guint32 self=GetCurrentThreadId ();
1873 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1876 EnterCriticalSection (&threads_mutex);
1878 if (threads != NULL)
1879 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1881 LeaveCriticalSection (&threads_mutex);
1884 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1886 MonoThread *thread=(MonoThread *)value;
1887 guint32 self=GPOINTER_TO_UINT (user);
1890 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1893 if(thread->tid==self)
1896 ResumeThread (thread->handle);
1899 void mono_gc_start_world (void)
1901 guint32 self=GetCurrentThreadId ();
1904 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1907 EnterCriticalSection (&threads_mutex);
1909 if (threads != NULL)
1910 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1912 LeaveCriticalSection (&threads_mutex);
1916 static guint32 dummy_apc (gpointer param)
1922 * mono_thread_execute_interruption
1924 * Performs the operation that the requested thread state requires (abort,
1927 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1929 mono_monitor_enter (thread->synch_lock);
1931 if (thread->interruption_requested) {
1932 /* this will consume pending APC calls */
1933 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1934 EnterCriticalSection (&interruption_mutex);
1935 thread_interruption_requested--;
1936 LeaveCriticalSection (&interruption_mutex);
1937 thread->interruption_requested = FALSE;
1940 if ((thread->state & ThreadState_AbortRequested) != 0) {
1941 if (thread->abort_exc == NULL)
1942 thread->abort_exc = mono_get_exception_thread_abort ();
1943 mono_monitor_exit (thread->synch_lock);
1944 return thread->abort_exc;
1946 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1947 thread->state &= ~ThreadState_SuspendRequested;
1948 thread->state |= ThreadState_Suspended;
1949 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1950 mono_monitor_exit (thread->synch_lock);
1952 WaitForSingleObject (thread->suspend_event, INFINITE);
1954 mono_monitor_enter (thread->synch_lock);
1955 CloseHandle (thread->suspend_event);
1956 thread->suspend_event = NULL;
1957 thread->state &= ~ThreadState_Suspended;
1959 /* The thread that requested the resume will have replaced this event
1960 * and will be waiting for it
1962 SetEvent (thread->resume_event);
1963 mono_monitor_exit (thread->synch_lock);
1966 else if ((thread->state & ThreadState_StopRequested) != 0) {
1967 /* FIXME: do this through the JIT? */
1968 mono_monitor_exit (thread->synch_lock);
1969 mono_thread_exit ();
1973 mono_monitor_exit (thread->synch_lock);
1978 * mono_thread_request_interruption
1980 * A signal handler can call this method to request the interruption of a
1981 * thread. The result of the interruption will depend on the current state of
1982 * the thread. If the result is an exception that needs to be throw, it is
1983 * provided as return value.
1985 MonoException* mono_thread_request_interruption (gboolean running_managed)
1987 MonoThread *thread = mono_thread_current ();
1989 /* The thread may already be stopping */
1993 mono_monitor_enter (thread->synch_lock);
1995 if (thread->interruption_requested) {
1996 mono_monitor_exit (thread->synch_lock);
2000 if (!running_managed || is_running_protected_wrapper ()) {
2001 /* Can't stop while in unmanaged code. Increase the global interruption
2002 request count. When exiting the unmanaged method the count will be
2003 checked and the thread will be interrupted. */
2005 EnterCriticalSection (&interruption_mutex);
2006 thread_interruption_requested++;
2007 LeaveCriticalSection (&interruption_mutex);
2009 thread->interruption_requested = TRUE;
2010 mono_monitor_exit (thread->synch_lock);
2012 /* this will awake the thread if it is in WaitForSingleObject
2014 QueueUserAPC (dummy_apc, thread->handle, NULL);
2019 mono_monitor_exit (thread->synch_lock);
2020 return mono_thread_execute_interruption (thread);
2024 gboolean mono_thread_interruption_requested ()
2026 if (thread_interruption_requested) {
2027 MonoThread *thread = mono_thread_current ();
2028 /* The thread may already be stopping */
2030 return (thread->interruption_requested);
2035 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2037 MonoThread *thread = mono_thread_current ();
2039 /* The thread may already be stopping */
2043 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2044 MonoException* exc = mono_thread_execute_interruption (thread);
2045 if (exc) mono_raise_exception (exc);
2050 * Performs the interruption of the current thread, if one has been requested,
2051 * and the thread is not running a protected wrapper.
2053 void mono_thread_interruption_checkpoint ()
2055 mono_thread_interruption_checkpoint_request (FALSE);
2059 * Performs the interruption of the current thread, if one has been requested.
2061 void mono_thread_force_interruption_checkpoint ()
2063 mono_thread_interruption_checkpoint_request (TRUE);
2067 * Returns the address of a flag that will be non-zero if an interruption has
2068 * been requested for a thread. The thread to interrupt may not be the current
2069 * thread, so an additional call to mono_thread_interruption_requested() or
2070 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2073 gint32* mono_thread_interruption_request_flag ()
2075 return &thread_interruption_requested;
2078 #ifdef WITH_INCLUDED_LIBGC
2080 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2082 MonoThread *thread=(MonoThread *)value;
2083 guint32 *selfp=(guint32 *)user, self = *selfp;
2086 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2089 if(thread->tid==self) {
2091 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2093 GC_push_all_stack (selfp, thread->stack_ptr);
2097 #ifdef PLATFORM_WIN32
2098 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2100 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2104 void mono_gc_push_all_stacks (void)
2106 guint32 self=GetCurrentThreadId ();
2109 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2112 EnterCriticalSection (&threads_mutex);
2114 if (threads != NULL)
2115 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2117 LeaveCriticalSection (&threads_mutex);
2120 #endif /* WITH_INCLUDED_LIBGC */