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>
34 #include <mono/os/gc_wrapper.h>
37 #undef THREAD_WAIT_DEBUG
41 guint32 (*func)(void *);
58 * The "os_handle" field of the WaitHandle class.
60 static MonoClassField *wait_handle_os_handle_field = NULL;
62 /* Controls access to the 'threads' hash table */
63 static CRITICAL_SECTION threads_mutex;
65 /* Controls access to context static data */
66 static CRITICAL_SECTION contexts_mutex;
68 /* Holds current status of static data heap */
69 static StaticDataInfo thread_static_info;
70 static StaticDataInfo context_static_info;
72 /* The hash of existing threads (key is thread ID) that need joining
75 static MonoGHashTable *threads=NULL;
77 /* The TLS key that holds the MonoObject assigned to each thread */
78 static guint32 current_object_key = -1;
80 /* function called at thread start */
81 static MonoThreadStartCB mono_thread_start_cb = NULL;
83 /* function called at thread attach */
84 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
86 /* function called at thread cleanup */
87 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
89 /* function called when a new thread has been created */
90 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
92 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
93 static guint32 slothash_key = -1;
95 /* The default stack size for each thread */
96 static guint32 default_stacksize = 0;
98 static void thread_adjust_static_data (MonoThread *thread);
99 static void mono_init_static_data_info (StaticDataInfo *static_data);
100 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
102 /* Spin lock for InterlockedXXX 64 bit functions */
103 static CRITICAL_SECTION interlocked_mutex;
105 /* Controls access to interruption flag */
106 static CRITICAL_SECTION interruption_mutex;
108 /* global count of thread interruptions requested */
109 static gint32 thread_interruption_requested = 0;
112 /* handle_store() and handle_remove() manage the array of threads that
113 * still need to be waited for when the main thread exits.
115 static void handle_store(MonoThread *thread)
117 EnterCriticalSection(&threads_mutex);
120 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
125 threads=mono_g_hash_table_new(NULL, NULL);
128 /* We don't need to duplicate thread->handle, because it is
129 * only closed when the thread object is finalized by the GC.
131 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
132 LeaveCriticalSection(&threads_mutex);
135 static void handle_remove(guint32 tid)
138 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
141 EnterCriticalSection(&threads_mutex);
144 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
146 LeaveCriticalSection(&threads_mutex);
148 /* Don't close the handle here, wait for the object finalizer
149 * to do it. Otherwise, the following race condition applies:
151 * 1) Thread exits (and handle_remove() closes the handle)
153 * 2) Some other handle is reassigned the same slot
155 * 3) Another thread tries to join the first thread, and
156 * blocks waiting for the reassigned handle to be signalled
157 * (which might never happen). This is possible, because the
158 * thread calling Join() still has a reference to the first
163 static void thread_cleanup (MonoThread *thread)
165 if (!mono_monitor_enter (thread->synch_lock))
168 thread->state |= ThreadState_Stopped;
169 mono_monitor_exit (thread->synch_lock);
171 mono_profiler_thread_end (thread->tid);
172 handle_remove (thread->tid);
174 mono_thread_pop_appdomain_ref ();
176 if (mono_thread_cleanup)
177 mono_thread_cleanup (thread);
180 static guint32 start_wrapper(void *data)
182 struct StartInfo *start_info=(struct StartInfo *)data;
183 guint32 (*start_func)(void *);
186 MonoThread *thread=start_info->obj;
189 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
190 GetCurrentThreadId ());
193 /* We can be sure start_info->obj->tid and
194 * start_info->obj->handle have been set, because the thread
195 * was created suspended, and these values were set before the
201 TlsSetValue (current_object_key, thread);
203 if (!mono_domain_set (start_info->domain, FALSE)) {
204 /* No point in raising an appdomain_unloaded exception here */
205 /* FIXME: Cleanup here */
209 start_func = start_info->func;
210 this = start_info->this;
212 /* This MUST be called before any managed code can be
213 * executed, as it calls the callback function that (for the
214 * jit) sets the lmf marker.
216 mono_thread_new_init (tid, &tid, start_func);
217 thread->stack_ptr = &tid;
220 g_message (G_GNUC_PRETTY_FUNCTION
221 ": (%d,%d) Setting thread stack to %p",
222 GetCurrentThreadId (), getpid (), thread->stack_ptr);
226 g_message (G_GNUC_PRETTY_FUNCTION
227 ": (%d) Setting current_object_key to %p",
228 GetCurrentThreadId (), thread);
231 mono_profiler_thread_start (tid);
233 if(thread->start_notify!=NULL) {
234 /* Let the thread that called Start() know we're
237 ReleaseSemaphore (thread->start_notify, 1, NULL);
242 /* Every thread references the appdomain which created it */
243 mono_thread_push_appdomain_ref (mono_domain_get ());
245 thread_adjust_static_data (thread);
246 #ifndef PLATFORM_WIN32
248 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
250 pthread_cleanup_push ((void (*) (void *)) mono_thread_detach, thread);
254 #ifdef PLATFORM_WIN32
255 /* If the thread calls ExitThread at all, this remaining code
256 * will not be executed, but the main thread will eventually
257 * call thread_cleanup() on this thread's behalf.
261 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
262 GetCurrentThreadId ());
265 /* Remove the reference to the thread object in the TLS data,
266 * so the thread object can be finalized. This won't be
267 * reached if the thread threw an uncaught exception, so those
268 * thread handles will stay referenced :-( (This is due to
269 * missing support for scanning thread-specific data in the
270 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
273 TlsSetValue (current_object_key, NULL);
275 thread_cleanup (thread);
277 pthread_cleanup_pop (1);
283 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
285 if (mono_thread_start_cb) {
286 mono_thread_start_cb (tid, stack_start, func);
289 if (mono_thread_callbacks)
290 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
293 void mono_threads_set_default_stacksize (guint32 stacksize)
295 default_stacksize = stacksize;
298 guint32 mono_threads_get_default_stacksize (void)
300 return default_stacksize;
303 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
306 HANDLE thread_handle;
307 struct StartInfo *start_info;
310 thread=(MonoThread *)mono_object_new (domain,
311 mono_defaults.thread_class);
313 start_info=g_new0 (struct StartInfo, 1);
314 start_info->func = func;
315 start_info->obj = thread;
316 start_info->domain = domain;
317 start_info->this = arg;
319 /* Create suspended, so we can do some housekeeping before the thread
322 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
323 CREATE_SUSPENDED, &tid);
325 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
328 g_assert (thread_handle);
330 thread->handle=thread_handle;
333 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
335 handle_store(thread);
337 ResumeThread (thread_handle);
341 mono_thread_attach (MonoDomain *domain)
344 HANDLE thread_handle;
347 if ((thread = mono_thread_current ())) {
348 /* Already attached */
352 thread = (MonoThread *)mono_object_new (domain,
353 mono_defaults.thread_class);
355 thread_handle = GetCurrentThread ();
356 g_assert (thread_handle);
358 tid=GetCurrentThreadId ();
360 thread->handle=thread_handle;
364 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
368 handle_store(thread);
371 g_message (G_GNUC_PRETTY_FUNCTION
372 ": (%d) Setting current_object_key to %p",
373 GetCurrentThreadId (), thread);
376 TlsSetValue (current_object_key, thread);
377 mono_domain_set (domain, TRUE);
379 thread_adjust_static_data (thread);
381 if (mono_thread_attach_cb) {
382 mono_thread_attach_cb (tid, &tid);
389 mono_thread_detach (MonoThread *thread)
391 g_return_if_fail (thread != NULL);
394 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
396 TlsSetValue (current_object_key, NULL);
398 thread_cleanup (thread);
401 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
404 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
405 guint32 (*start_func)(void *);
406 struct StartInfo *start_info;
414 g_message(G_GNUC_PRETTY_FUNCTION
415 ": Trying to start a new thread: this (%p) start (%p)",
419 im = mono_get_delegate_invoke (start->vtable->klass);
420 im = mono_marshal_get_delegate_invoke (im);
421 if (mono_thread_callbacks)
422 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
424 start_func = mono_compile_method (im);
426 if(start_func==NULL) {
427 g_warning(G_GNUC_PRETTY_FUNCTION
428 ": Can't locate start method!");
431 /* This is freed in start_wrapper */
432 start_info = g_new0 (struct StartInfo, 1);
433 start_info->func = start_func;
434 start_info->this = delegate;
435 start_info->obj = this;
436 start_info->domain = mono_domain_get ();
438 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
439 if(this->start_notify==NULL) {
440 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
444 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
445 CREATE_SUSPENDED, &tid);
447 g_warning(G_GNUC_PRETTY_FUNCTION
448 ": CreateThread error 0x%x", GetLastError());
455 /* Don't call handle_store() here, delay it to Start.
456 * We can't join a thread (trying to will just block
457 * forever) until it actually starts running, so don't
458 * store the handle till then.
462 g_message(G_GNUC_PRETTY_FUNCTION
463 ": Started thread ID %d (handle %p)", tid, thread);
470 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
476 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
480 CloseHandle (thread);
483 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
489 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
490 GetCurrentThreadId (), this, this->tid);
493 /* Only store the handle when the thread is about to be
494 * launched, to avoid the main thread deadlocking while trying
495 * to clean up a thread that will never be signalled.
499 if (mono_thread_callbacks)
500 (* mono_thread_callbacks->start_resume) (this->tid);
502 ResumeThread(thread);
504 if (mono_thread_callbacks)
505 (* mono_thread_callbacks->end_resume) (this->tid);
507 if(this->start_notify!=NULL) {
508 /* Wait for the thread to set up its TLS data etc, so
509 * theres no potential race condition if someone tries
510 * to look up the data believing the thread has
515 g_message(G_GNUC_PRETTY_FUNCTION
516 ": (%d) waiting for thread %p (%d) to start",
517 GetCurrentThreadId (), this, this->tid);
520 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
521 CloseHandle (this->start_notify);
522 this->start_notify=NULL;
526 g_message(G_GNUC_PRETTY_FUNCTION
527 ": (%d) Done launching thread %p (%d)",
528 GetCurrentThreadId (), this, this->tid);
532 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
534 MonoThread *thread = mono_thread_current ();
539 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
542 mono_monitor_enter (thread->synch_lock);
543 thread->state |= ThreadState_WaitSleepJoin;
544 mono_monitor_exit (thread->synch_lock);
548 mono_monitor_enter (thread->synch_lock);
549 thread->state &= ~ThreadState_WaitSleepJoin;
550 mono_monitor_exit (thread->synch_lock);
554 ves_icall_System_Threading_Thread_GetDomainID (void)
558 return mono_domain_get()->domain_id;
562 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
567 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
571 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
574 g_free (this_obj->name);
576 this_obj->name = g_new (gunichar2, mono_string_length (name));
577 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
578 this_obj->name_len = mono_string_length (name);
581 this_obj->name = NULL;
585 mono_thread_current (void)
591 /* Find the current thread object */
592 thread=TlsGetValue (current_object_key);
595 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
601 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
602 int ms, HANDLE thread)
608 mono_monitor_enter (this->synch_lock);
609 this->state |= ThreadState_WaitSleepJoin;
610 mono_monitor_exit (this->synch_lock);
616 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
620 ret=WaitForSingleObjectEx (thread, ms, TRUE);
622 mono_monitor_enter (this->synch_lock);
623 this->state &= ~ThreadState_WaitSleepJoin;
624 mono_monitor_exit (this->synch_lock);
626 if(ret==WAIT_OBJECT_0) {
628 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
635 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
641 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
646 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
649 /* Object location stored here */
650 TlsSetValue(slothash_key, data);
653 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
659 data=TlsGetValue(slothash_key);
662 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
668 /* FIXME: exitContext isnt documented */
669 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
675 MonoObject *waitHandle;
680 numhandles = mono_array_length(mono_handles);
681 handles = g_new0(HANDLE, numhandles);
683 if (wait_handle_os_handle_field == 0) {
684 /* Get the field os_handle which will contain the actual handle */
685 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
686 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
689 for(i = 0; i < numhandles; i++) {
690 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
691 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
698 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
702 if(ret==WAIT_FAILED) {
703 #ifdef THREAD_WAIT_DEBUG
704 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
705 GetCurrentThreadId ());
708 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
709 /* Do we want to try again if we get
710 * WAIT_IO_COMPLETION? The documentation for
711 * WaitHandle doesn't give any clues. (We'd have to
712 * fiddle with the timeout if we retry.)
714 #ifdef THREAD_WAIT_DEBUG
715 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
716 GetCurrentThreadId ());
724 /* FIXME: exitContext isnt documented */
725 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
731 MonoObject *waitHandle;
736 numhandles = mono_array_length(mono_handles);
737 handles = g_new0(HANDLE, numhandles);
739 if (wait_handle_os_handle_field == 0) {
740 /* Get the field os_handle which will contain the actual handle */
741 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
742 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
745 for(i = 0; i < numhandles; i++) {
746 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
747 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
754 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
758 #ifdef THREAD_WAIT_DEBUG
759 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
760 GetCurrentThreadId (), ret);
764 * These need to be here. See MSDN dos on WaitForMultipleObjects.
766 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
767 return ret - WAIT_OBJECT_0;
769 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
770 return ret - WAIT_ABANDONED_0;
777 /* FIXME: exitContext isnt documented */
778 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
784 #ifdef THREAD_WAIT_DEBUG
785 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
786 GetCurrentThreadId (), handle, ms);
793 ret=WaitForSingleObjectEx (handle, ms, TRUE);
795 if(ret==WAIT_FAILED) {
796 #ifdef THREAD_WAIT_DEBUG
797 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
798 GetCurrentThreadId ());
801 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
802 /* Do we want to try again if we get
803 * WAIT_IO_COMPLETION? The documentation for
804 * WaitHandle doesn't give any clues. (We'd have to
805 * fiddle with the timeout if we retry.)
807 #ifdef THREAD_WAIT_DEBUG
808 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
809 GetCurrentThreadId ());
817 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name)
821 return(CreateMutex (NULL, owned,
822 name==NULL?NULL:mono_string_chars (name)));
825 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
828 ReleaseMutex(handle);
831 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
834 return(CreateEvent (NULL, manual, initial,
835 name==NULL?NULL:mono_string_chars (name)));
838 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
841 return (SetEvent(handle));
844 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
847 return (ResetEvent(handle));
851 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
854 CloseHandle (handle);
857 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
861 return InterlockedIncrement (location);
864 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
871 EnterCriticalSection(&interlocked_mutex);
873 lowret = InterlockedIncrement((gint32 *) location);
875 highret = InterlockedIncrement((gint32 *) location + 1);
877 highret = *((gint32 *) location + 1);
879 LeaveCriticalSection(&interlocked_mutex);
881 return (gint64) highret << 32 | (gint64) lowret;
884 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
888 return InterlockedDecrement(location);
891 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
898 EnterCriticalSection(&interlocked_mutex);
900 lowret = InterlockedDecrement((gint32 *) location);
902 highret = InterlockedDecrement((gint32 *) location + 1);
904 highret = *((gint32 *) location + 1);
906 LeaveCriticalSection(&interlocked_mutex);
908 return (gint64) highret << 32 | (gint64) lowret;
911 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
915 return InterlockedExchange(location1, value);
918 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
922 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
925 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
927 IntFloatUnion val, ret;
932 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
937 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
941 return InterlockedCompareExchange(location1, value, comparand);
944 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
948 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
951 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
953 IntFloatUnion val, ret, cmp;
958 cmp.fval = comparand;
959 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
965 mono_thread_get_abort_signal (void)
975 #endif /* __MINGW32__ */
979 static guint32 interruption_request_apc (gpointer param)
981 MonoException* exc = mono_thread_request_interruption (FALSE);
982 if (exc) mono_raise_exception (exc);
985 #endif /* __MINGW32__ */
988 * signal_thread_state_change
990 * Tells the thread that his state has changed and it has to enter the new
991 * state as soon as possible.
993 static void signal_thread_state_change (MonoThread *thread)
996 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
998 /* fixme: store the state somewhere */
999 #ifdef PTHREAD_POINTER_ID
1000 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1002 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1004 #endif /* __MINGW32__ */
1008 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1010 MONO_ARCH_SAVE_REGS;
1012 mono_monitor_enter (thread->synch_lock);
1014 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1015 (thread->state & ThreadState_StopRequested) != 0)
1017 mono_monitor_exit (thread->synch_lock);
1021 thread->state |= ThreadState_AbortRequested;
1022 thread->abort_state = state;
1023 thread->abort_exc = NULL;
1025 mono_monitor_exit (thread->synch_lock);
1028 g_message (G_GNUC_PRETTY_FUNCTION
1029 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1030 thread, thread->tid);
1033 /* Make sure the thread is awake */
1034 ves_icall_System_Threading_Thread_Resume (thread);
1036 signal_thread_state_change (thread);
1040 ves_icall_System_Threading_Thread_ResetAbort (void)
1042 MonoThread *thread = mono_thread_current ();
1044 MONO_ARCH_SAVE_REGS;
1046 mono_monitor_enter (thread->synch_lock);
1048 thread->state &= ~ThreadState_AbortRequested;
1050 if (!thread->abort_exc) {
1051 const char *msg = "Unable to reset abort because no abort was requested";
1052 mono_monitor_exit (thread->synch_lock);
1053 mono_raise_exception (mono_get_exception_thread_state (msg));
1055 thread->abort_exc = NULL;
1056 thread->abort_state = NULL;
1059 mono_monitor_exit (thread->synch_lock);
1063 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1065 MONO_ARCH_SAVE_REGS;
1067 mono_monitor_enter (thread->synch_lock);
1069 if ((thread->state & ThreadState_Suspended) != 0 ||
1070 (thread->state & ThreadState_SuspendRequested) != 0 ||
1071 (thread->state & ThreadState_StopRequested) != 0)
1073 mono_monitor_exit (thread->synch_lock);
1077 thread->state |= ThreadState_SuspendRequested;
1078 mono_monitor_exit (thread->synch_lock);
1080 signal_thread_state_change (thread);
1084 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1086 MONO_ARCH_SAVE_REGS;
1088 mono_monitor_enter (thread->synch_lock);
1090 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1091 thread->state &= ~ThreadState_SuspendRequested;
1092 mono_monitor_exit (thread->synch_lock);
1096 if ((thread->state & ThreadState_Suspended) == 0)
1098 mono_monitor_exit (thread->synch_lock);
1102 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1104 /* Awake the thread */
1105 SetEvent (thread->suspend_event);
1107 mono_monitor_exit (thread->synch_lock);
1109 /* Wait for the thread to awake */
1110 WaitForSingleObject (thread->resume_event, INFINITE);
1111 CloseHandle (thread->resume_event);
1112 thread->resume_event = NULL;
1115 void mono_thread_stop (MonoThread *thread)
1117 mono_monitor_enter (thread->synch_lock);
1119 if ((thread->state & ThreadState_StopRequested) != 0 ||
1120 (thread->state & ThreadState_Stopped) != 0)
1122 mono_monitor_exit (thread->synch_lock);
1126 /* Make sure the thread is awake */
1127 ves_icall_System_Threading_Thread_Resume (thread);
1129 thread->state |= ThreadState_StopRequested;
1130 thread->state &= ~ThreadState_AbortRequested;
1132 mono_monitor_exit (thread->synch_lock);
1134 signal_thread_state_change (thread);
1138 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1140 return *((volatile gint8 *) (ptr));
1144 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1146 return *((volatile gint16 *) (ptr));
1150 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1152 return *((volatile gint32 *) (ptr));
1156 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1158 return *((volatile gint64 *) (ptr));
1162 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1164 return (void *) *((volatile void **) ptr);
1168 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1170 *((volatile gint8 *) ptr) = value;
1174 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1176 *((volatile gint16 *) ptr) = value;
1180 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1182 *((volatile gint32 *) ptr) = value;
1186 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1188 *((volatile gint64 *) ptr) = value;
1192 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1194 *((volatile void **) ptr) = value;
1197 void mono_thread_init (MonoThreadStartCB start_cb,
1198 MonoThreadAttachCB attach_cb)
1200 InitializeCriticalSection(&threads_mutex);
1201 InitializeCriticalSection(&interlocked_mutex);
1202 InitializeCriticalSection(&contexts_mutex);
1203 InitializeCriticalSection(&interruption_mutex);
1205 mono_init_static_data_info (&thread_static_info);
1206 mono_init_static_data_info (&context_static_info);
1208 current_object_key=TlsAlloc();
1210 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1211 current_object_key);
1214 mono_thread_start_cb = start_cb;
1215 mono_thread_attach_cb = attach_cb;
1217 slothash_key=TlsAlloc();
1219 /* Get a pseudo handle to the current process. This is just a
1220 * kludge so that wapi can build a process handle if needed.
1221 * As a pseudo handle is returned, we don't need to clean
1224 GetCurrentProcess ();
1228 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1230 mono_thread_cleanup = func;
1233 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1235 mono_thread_callbacks = callbacks;
1239 static void print_tids (gpointer key, gpointer value, gpointer user)
1241 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1247 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1248 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1252 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1257 g_message(G_GNUC_PRETTY_FUNCTION
1258 ": %d threads to wait for in this batch", wait->num);
1261 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1263 if(ret==WAIT_FAILED) {
1264 /* See the comment in build_wait_tids() */
1266 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1272 for(i=0; i<wait->num; i++) {
1273 guint32 tid=wait->threads[i]->tid;
1274 CloseHandle (wait->handles[i]);
1276 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1277 /* This thread must have been killed, because
1278 * it hasn't cleaned itself up. (It's just
1279 * possible that the thread exited before the
1280 * parent thread had a chance to store the
1281 * handle, and now there is another pointer to
1282 * the already-exited thread stored. In this
1283 * case, we'll just get two
1284 * mono_profiler_thread_end() calls for the
1289 g_message (G_GNUC_PRETTY_FUNCTION
1290 ": cleaning up after thread %d", tid);
1292 thread_cleanup (wait->threads[i]);
1297 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1299 struct wait_data *wait=(struct wait_data *)user;
1301 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1303 MonoThread *thread=(MonoThread *)value;
1305 /* Ignore background threads, we abort them later */
1306 if (thread->state & ThreadState_Background)
1307 return; /* just leave, ignore */
1309 if (mono_gc_is_finalizer_thread (thread))
1312 if (thread == mono_thread_current ())
1315 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1319 wait->handles[wait->num]=handle;
1320 wait->threads[wait->num]=thread;
1323 /* Just ignore the rest, we can't do anything with
1330 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1332 struct wait_data *wait=(struct wait_data *)user;
1333 guint32 self = GetCurrentThreadId ();
1334 MonoThread *thread = (MonoThread *) value;
1337 /* The finalizer thread is not a background thread */
1338 if (thread->tid != self && thread->state & ThreadState_Background) {
1340 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1344 wait->handles[wait->num]=thread->handle;
1345 wait->threads[wait->num]=thread;
1348 if(thread->state & ThreadState_AbortRequested ||
1349 thread->state & ThreadState_Aborted) {
1351 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1357 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1359 mono_thread_stop (thread);
1363 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1366 void mono_thread_manage (void)
1368 struct wait_data *wait=g_new0 (struct wait_data, 1);
1370 /* join each thread that's still running */
1372 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1375 EnterCriticalSection (&threads_mutex);
1378 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1380 LeaveCriticalSection (&threads_mutex);
1383 LeaveCriticalSection (&threads_mutex);
1386 EnterCriticalSection (&threads_mutex);
1388 g_message(G_GNUC_PRETTY_FUNCTION
1389 ":There are %d threads to join",
1390 mono_g_hash_table_size (threads));
1391 mono_g_hash_table_foreach (threads, print_tids, NULL);
1395 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1396 LeaveCriticalSection (&threads_mutex);
1398 /* Something to wait for */
1399 wait_for_tids (wait, INFINITE);
1401 } while(wait->num>0);
1403 mono_thread_pool_cleanup ();
1405 EnterCriticalSection(&threads_mutex);
1408 * Remove everything but the finalizer thread and self.
1409 * Also abort all the background threads
1412 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1414 LeaveCriticalSection(&threads_mutex);
1417 /* Something to wait for */
1418 wait_for_tids (wait, INFINITE);
1424 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1426 MonoThread *thread=(MonoThread *)value;
1427 guint32 self=GPOINTER_TO_UINT (user);
1429 if(thread->tid!=self) {
1430 /*TerminateThread (thread->handle, -1);*/
1434 void mono_thread_abort_all_other_threads (void)
1436 guint32 self=GetCurrentThreadId ();
1438 EnterCriticalSection (&threads_mutex);
1440 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1441 mono_g_hash_table_size (threads));
1442 mono_g_hash_table_foreach (threads, print_tids, NULL);
1445 mono_g_hash_table_foreach (threads, terminate_thread,
1446 GUINT_TO_POINTER (self));
1448 LeaveCriticalSection (&threads_mutex);
1452 * mono_thread_push_appdomain_ref:
1454 * Register that the current thread may have references to objects in domain
1455 * @domain on its stack. Each call to this function should be paired with a
1456 * call to pop_appdomain_ref.
1459 mono_thread_push_appdomain_ref (MonoDomain *domain)
1461 MonoThread *thread = mono_thread_current ();
1464 //printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name);
1465 EnterCriticalSection (&threads_mutex);
1466 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1467 LeaveCriticalSection (&threads_mutex);
1472 mono_thread_pop_appdomain_ref (void)
1474 MonoThread *thread = mono_thread_current ();
1477 //printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name);
1478 EnterCriticalSection (&threads_mutex);
1479 // FIXME: How can the list be empty ?
1480 if (thread->appdomain_refs)
1481 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1482 LeaveCriticalSection (&threads_mutex);
1487 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1490 EnterCriticalSection (&threads_mutex);
1491 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1492 LeaveCriticalSection (&threads_mutex);
1496 typedef struct abort_appdomain_data {
1497 struct wait_data wait;
1499 } abort_appdomain_data;
1502 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1504 MonoThread *thread = (MonoThread*)value;
1505 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1506 MonoDomain *domain = data->domain;
1508 if (mono_thread_has_appdomain_ref (thread, domain)) {
1509 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1510 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1512 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1513 data->wait.handles [data->wait.num] = thread->handle;
1514 data->wait.threads [data->wait.num] = thread;
1517 /* Just ignore the rest, we can't do anything with
1525 * mono_threads_abort_appdomain_threads:
1527 * Abort threads which has references to the given appdomain.
1530 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1532 abort_appdomain_data user_data;
1535 /* printf ("ABORT BEGIN.\n"); */
1537 start_time = GetTickCount ();
1539 EnterCriticalSection (&threads_mutex);
1541 user_data.domain = domain;
1542 user_data.wait.num = 0;
1543 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1544 LeaveCriticalSection (&threads_mutex);
1546 if (user_data.wait.num > 0)
1547 wait_for_tids (&user_data.wait, timeout);
1549 /* Update remaining time */
1550 timeout -= GetTickCount () - start_time;
1551 start_time = GetTickCount ();
1556 while (user_data.wait.num > 0);
1558 /* printf ("ABORT DONE.\n"); */
1564 * mono_thread_get_pending_exception:
1566 * Return an exception which needs to be raised when leaving a catch clause.
1567 * This is used for undeniable exception propagation.
1570 mono_thread_get_pending_exception (void)
1572 MonoThread *thread = mono_thread_current ();
1574 MONO_ARCH_SAVE_REGS;
1576 if (thread && thread->abort_exc) {
1578 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1579 * exception if the thread no longer references a dying appdomain.
1581 thread->abort_exc->trace_ips = NULL;
1582 thread->abort_exc->stack_trace = NULL;
1583 return thread->abort_exc;
1589 #define NUM_STATIC_DATA_IDX 8
1590 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1591 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1596 * mono_alloc_static_data
1598 * Allocate memory blocks for storing threads or context static data
1601 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1603 guint idx = (offset >> 24) - 1;
1606 gpointer* static_data = *static_data_ptr;
1609 static_data = GC_MALLOC (static_data_size [0]);
1611 static_data = g_malloc0 (static_data_size [0]);
1613 *static_data_ptr = static_data;
1614 static_data [0] = static_data;
1617 for (i = 1; i < idx; ++i) {
1618 if (static_data [i])
1621 static_data [i] = GC_MALLOC (static_data_size [i]);
1623 static_data [i] = g_malloc0 (static_data_size [i]);
1629 * mono_init_static_data_info
1631 * Initializes static data counters
1633 static void mono_init_static_data_info (StaticDataInfo *static_data)
1635 static_data->idx = 0;
1636 static_data->offset = 0;
1640 * mono_alloc_static_data_slot
1642 * Generates an offset for static data. static_data contains the counters
1643 * used to generate it.
1646 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1650 if (!static_data->idx && !static_data->offset) {
1652 * we use the first chunk of the first allocation also as
1653 * an array for the rest of the data
1655 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1657 static_data->offset += align - 1;
1658 static_data->offset &= ~(align - 1);
1659 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1660 static_data->idx ++;
1661 g_assert (size <= static_data_size [static_data->idx]);
1663 * massive unloading and reloading of domains with thread-static
1664 * data may eventually exceed the allocated storage...
1665 * Need to check what the MS runtime does in that case.
1666 * Note that for each appdomain, we need to allocate a separate
1667 * thread data slot for security reasons. We could keep track
1668 * of the slots per-domain and when the domain is unloaded
1669 * out the slots on a sort of free list.
1671 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1672 static_data->offset = 0;
1674 offset = static_data->offset | ((static_data->idx + 1) << 24);
1675 static_data->offset += size;
1680 * ensure thread static fields already allocated are valid for thread
1681 * This function is called when a thread is created or on thread attach.
1684 thread_adjust_static_data (MonoThread *thread)
1688 EnterCriticalSection (&threads_mutex);
1689 if (thread_static_info.offset || thread_static_info.idx > 0) {
1690 /* get the current allocated size */
1691 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1692 mono_alloc_static_data (&(thread->static_data), offset);
1694 LeaveCriticalSection (&threads_mutex);
1698 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1700 MonoThread *thread = value;
1701 guint32 offset = GPOINTER_TO_UINT (user);
1703 mono_alloc_static_data (&(thread->static_data), offset);
1707 * The offset for a special static variable is composed of three parts:
1708 * a bit that indicates the type of static data (0:thread, 1:context),
1709 * an index in the array of chunks of memory for the thread (thread->static_data)
1710 * and an offset in that chunk of mem. This allows allocating less memory in the
1715 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1718 if (static_type == SPECIAL_STATIC_THREAD)
1720 EnterCriticalSection (&threads_mutex);
1721 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1722 /* This can be called during startup */
1723 if (threads != NULL)
1724 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1725 LeaveCriticalSection (&threads_mutex);
1729 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1730 EnterCriticalSection (&contexts_mutex);
1731 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1732 LeaveCriticalSection (&contexts_mutex);
1733 offset |= 0x80000000; // Set the high bit to indicate context static data
1739 mono_get_special_static_data (guint32 offset)
1741 // The high bit means either thread (0) or static (1) data.
1743 guint32 static_type = (offset & 0x80000000);
1746 offset &= 0x7fffffff;
1747 idx = (offset >> 24) - 1;
1749 if (static_type == 0)
1751 MonoThread *thread = mono_thread_current ();
1752 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1756 // Allocate static data block under demand, since we don't have a list
1758 MonoAppContext *context = mono_context_get ();
1759 if (!context->static_data || !context->static_data [idx]) {
1760 EnterCriticalSection (&contexts_mutex);
1761 mono_alloc_static_data (&(context->static_data), offset);
1762 LeaveCriticalSection (&contexts_mutex);
1764 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
1768 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1770 MonoThread *thread=(MonoThread *)value;
1771 guint32 self=GPOINTER_TO_UINT (user);
1774 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1777 if(thread->tid==self)
1780 SuspendThread (thread->handle);
1783 void mono_gc_stop_world (void)
1785 guint32 self=GetCurrentThreadId ();
1788 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1791 EnterCriticalSection (&threads_mutex);
1793 if (threads != NULL)
1794 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1796 LeaveCriticalSection (&threads_mutex);
1799 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1801 MonoThread *thread=(MonoThread *)value;
1802 guint32 self=GPOINTER_TO_UINT (user);
1805 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1808 if(thread->tid==self)
1811 ResumeThread (thread->handle);
1814 void mono_gc_start_world (void)
1816 guint32 self=GetCurrentThreadId ();
1819 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1822 EnterCriticalSection (&threads_mutex);
1824 if (threads != NULL)
1825 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1827 LeaveCriticalSection (&threads_mutex);
1831 static guint32 dummy_apc (gpointer param)
1837 * mono_thread_execute_interruption
1839 * Performs the operation that the requested thread state requires (abort,
1842 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1844 mono_monitor_enter (thread->synch_lock);
1846 if (thread->interruption_requested) {
1847 /* this will consume pending APC calls */
1848 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1849 EnterCriticalSection (&interruption_mutex);
1850 thread_interruption_requested--;
1851 LeaveCriticalSection (&interruption_mutex);
1852 thread->interruption_requested = FALSE;
1855 if ((thread->state & ThreadState_AbortRequested) != 0) {
1856 thread->abort_exc = mono_get_exception_thread_abort ();
1857 mono_monitor_exit (thread->synch_lock);
1858 return thread->abort_exc;
1860 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1861 thread->state &= ~ThreadState_SuspendRequested;
1862 thread->state |= ThreadState_Suspended;
1863 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1864 mono_monitor_exit (thread->synch_lock);
1866 WaitForSingleObject (thread->suspend_event, INFINITE);
1868 mono_monitor_enter (thread->synch_lock);
1869 CloseHandle (thread->suspend_event);
1870 thread->suspend_event = NULL;
1871 thread->state &= ~ThreadState_Suspended;
1873 /* The thread that requested the resume will have replaced this event
1874 * and will be waiting for it
1876 SetEvent (thread->resume_event);
1877 mono_monitor_exit (thread->synch_lock);
1880 else if ((thread->state & ThreadState_StopRequested) != 0) {
1881 /* FIXME: do this through the JIT? */
1882 mono_monitor_exit (thread->synch_lock);
1887 mono_monitor_exit (thread->synch_lock);
1892 * mono_thread_request_interruption
1894 * A signal handler can call this method to request the interruption of a
1895 * thread. The result of the interruption will depend on the current state of
1896 * the thread. If the result is an exception that needs to be throw, it is
1897 * provided as return value.
1899 MonoException* mono_thread_request_interruption (gboolean running_managed)
1901 MonoThread *thread = mono_thread_current ();
1903 /* The thread may already be stopping */
1907 mono_monitor_enter (thread->synch_lock);
1909 if (thread->interruption_requested) {
1910 mono_monitor_exit (thread->synch_lock);
1914 if (!running_managed) {
1915 /* Can't stop while in unmanaged code. Increase the global interruption
1916 request count. When exiting the unmanaged method the count will be
1917 checked and the thread will be interrupted. */
1919 EnterCriticalSection (&interruption_mutex);
1920 thread_interruption_requested++;
1921 LeaveCriticalSection (&interruption_mutex);
1923 thread->interruption_requested = TRUE;
1924 mono_monitor_exit (thread->synch_lock);
1926 /* this will awake the thread if it is in WaitForSingleObject
1928 QueueUserAPC (dummy_apc, thread->handle, NULL);
1933 mono_monitor_exit (thread->synch_lock);
1934 return mono_thread_execute_interruption (thread);
1938 gboolean mono_thread_interruption_requested ()
1940 if (thread_interruption_requested) {
1941 MonoThread *thread = mono_thread_current ();
1942 /* The thread may already be stopping */
1944 return (thread->interruption_requested);
1950 * Performs the interruption of the current thread, if one has been requested.
1952 void mono_thread_interruption_checkpoint ()
1954 MonoThread *thread = mono_thread_current ();
1956 /* The thread may already be stopping */
1960 if (thread->interruption_requested) {
1961 MonoException* exc = mono_thread_execute_interruption (thread);
1962 if (exc) mono_raise_exception (exc);
1967 * Returns the address of a flag that will be non-zero if an interruption has
1968 * been requested for a thread. The thread to interrupt may not be the current
1969 * thread, so an additional call to mono_thread_interruption_requested() or
1970 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
1973 gint32* mono_thread_interruption_request_flag ()
1975 return &thread_interruption_requested;
1978 #ifdef WITH_INCLUDED_LIBGC
1980 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
1982 MonoThread *thread=(MonoThread *)value;
1983 guint32 *selfp=(guint32 *)user, self = *selfp;
1986 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
1989 if(thread->tid==self) {
1991 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
1993 GC_push_all_stack (selfp, thread->stack_ptr);
1997 #ifdef PLATFORM_WIN32
1998 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2000 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2004 void mono_gc_push_all_stacks (void)
2006 guint32 self=GetCurrentThreadId ();
2009 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2012 EnterCriticalSection (&threads_mutex);
2014 if (threads != NULL)
2015 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2017 LeaveCriticalSection (&threads_mutex);
2020 #endif /* WITH_INCLUDED_LIBGC */