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 MONO_GC_REGISTER_ROOT (threads);
126 threads=mono_g_hash_table_new(NULL, NULL);
129 /* We don't need to duplicate thread->handle, because it is
130 * only closed when the thread object is finalized by the GC.
132 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
133 LeaveCriticalSection(&threads_mutex);
136 static void handle_remove(guint32 tid)
139 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
142 EnterCriticalSection(&threads_mutex);
145 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
147 LeaveCriticalSection(&threads_mutex);
149 /* Don't close the handle here, wait for the object finalizer
150 * to do it. Otherwise, the following race condition applies:
152 * 1) Thread exits (and handle_remove() closes the handle)
154 * 2) Some other handle is reassigned the same slot
156 * 3) Another thread tries to join the first thread, and
157 * blocks waiting for the reassigned handle to be signalled
158 * (which might never happen). This is possible, because the
159 * thread calling Join() still has a reference to the first
164 static void thread_cleanup (MonoThread *thread)
166 if (!mono_monitor_enter (thread->synch_lock))
169 thread->state |= ThreadState_Stopped;
170 mono_monitor_exit (thread->synch_lock);
172 mono_profiler_thread_end (thread->tid);
173 handle_remove (thread->tid);
175 mono_thread_pop_appdomain_ref ();
177 if (mono_thread_cleanup)
178 mono_thread_cleanup (thread);
181 static guint32 start_wrapper(void *data)
183 struct StartInfo *start_info=(struct StartInfo *)data;
184 guint32 (*start_func)(void *);
187 MonoThread *thread=start_info->obj;
190 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
191 GetCurrentThreadId ());
194 /* We can be sure start_info->obj->tid and
195 * start_info->obj->handle have been set, because the thread
196 * was created suspended, and these values were set before the
202 TlsSetValue (current_object_key, thread);
204 if (!mono_domain_set (start_info->domain, FALSE)) {
205 /* No point in raising an appdomain_unloaded exception here */
206 /* FIXME: Cleanup here */
210 start_func = start_info->func;
211 this = start_info->this;
213 /* This MUST be called before any managed code can be
214 * executed, as it calls the callback function that (for the
215 * jit) sets the lmf marker.
217 mono_thread_new_init (tid, &tid, start_func);
218 thread->stack_ptr = &tid;
221 g_message (G_GNUC_PRETTY_FUNCTION
222 ": (%d,%d) Setting thread stack to %p",
223 GetCurrentThreadId (), getpid (), thread->stack_ptr);
227 g_message (G_GNUC_PRETTY_FUNCTION
228 ": (%d) Setting current_object_key to %p",
229 GetCurrentThreadId (), thread);
232 mono_profiler_thread_start (tid);
234 if(thread->start_notify!=NULL) {
235 /* Let the thread that called Start() know we're
238 ReleaseSemaphore (thread->start_notify, 1, NULL);
243 /* Every thread references the appdomain which created it */
244 mono_thread_push_appdomain_ref (mono_domain_get ());
246 thread_adjust_static_data (thread);
247 #ifndef PLATFORM_WIN32
249 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
251 pthread_cleanup_push ((void (*) (void *)) mono_thread_detach, thread);
255 #ifdef PLATFORM_WIN32
256 /* If the thread calls ExitThread at all, this remaining code
257 * will not be executed, but the main thread will eventually
258 * call thread_cleanup() on this thread's behalf.
262 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
263 GetCurrentThreadId ());
266 /* Remove the reference to the thread object in the TLS data,
267 * so the thread object can be finalized. This won't be
268 * reached if the thread threw an uncaught exception, so those
269 * thread handles will stay referenced :-( (This is due to
270 * missing support for scanning thread-specific data in the
271 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
274 TlsSetValue (current_object_key, NULL);
276 thread_cleanup (thread);
278 pthread_cleanup_pop (1);
284 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
286 if (mono_thread_start_cb) {
287 mono_thread_start_cb (tid, stack_start, func);
290 if (mono_thread_callbacks)
291 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
294 void mono_threads_set_default_stacksize (guint32 stacksize)
296 default_stacksize = stacksize;
299 guint32 mono_threads_get_default_stacksize (void)
301 return default_stacksize;
304 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
307 HANDLE thread_handle;
308 struct StartInfo *start_info;
311 thread=(MonoThread *)mono_object_new (domain,
312 mono_defaults.thread_class);
314 start_info=g_new0 (struct StartInfo, 1);
315 start_info->func = func;
316 start_info->obj = thread;
317 start_info->domain = domain;
318 start_info->this = arg;
320 /* Create suspended, so we can do some housekeeping before the thread
323 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
324 CREATE_SUSPENDED, &tid);
326 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
329 g_assert (thread_handle);
331 thread->handle=thread_handle;
334 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
336 handle_store(thread);
338 ResumeThread (thread_handle);
342 mono_thread_attach (MonoDomain *domain)
345 HANDLE thread_handle;
348 if ((thread = mono_thread_current ())) {
349 /* Already attached */
353 thread = (MonoThread *)mono_object_new (domain,
354 mono_defaults.thread_class);
356 thread_handle = GetCurrentThread ();
357 g_assert (thread_handle);
359 tid=GetCurrentThreadId ();
361 thread->handle=thread_handle;
365 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
369 handle_store(thread);
372 g_message (G_GNUC_PRETTY_FUNCTION
373 ": (%d) Setting current_object_key to %p",
374 GetCurrentThreadId (), thread);
377 TlsSetValue (current_object_key, thread);
378 mono_domain_set (domain, TRUE);
380 thread_adjust_static_data (thread);
382 if (mono_thread_attach_cb) {
383 mono_thread_attach_cb (tid, &tid);
390 mono_thread_detach (MonoThread *thread)
392 g_return_if_fail (thread != NULL);
395 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
397 TlsSetValue (current_object_key, NULL);
399 thread_cleanup (thread);
402 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
405 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
406 guint32 (*start_func)(void *);
407 struct StartInfo *start_info;
415 g_message(G_GNUC_PRETTY_FUNCTION
416 ": Trying to start a new thread: this (%p) start (%p)",
420 im = mono_get_delegate_invoke (start->vtable->klass);
421 im = mono_marshal_get_delegate_invoke (im);
422 if (mono_thread_callbacks)
423 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
425 start_func = mono_compile_method (im);
427 if(start_func==NULL) {
428 g_warning(G_GNUC_PRETTY_FUNCTION
429 ": Can't locate start method!");
432 /* This is freed in start_wrapper */
433 start_info = g_new0 (struct StartInfo, 1);
434 start_info->func = start_func;
435 start_info->this = delegate;
436 start_info->obj = this;
437 start_info->domain = mono_domain_get ();
439 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
440 if(this->start_notify==NULL) {
441 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
445 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
446 CREATE_SUSPENDED, &tid);
448 g_warning(G_GNUC_PRETTY_FUNCTION
449 ": CreateThread error 0x%x", GetLastError());
456 /* Don't call handle_store() here, delay it to Start.
457 * We can't join a thread (trying to will just block
458 * forever) until it actually starts running, so don't
459 * store the handle till then.
463 g_message(G_GNUC_PRETTY_FUNCTION
464 ": Started thread ID %d (handle %p)", tid, thread);
471 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
477 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
481 CloseHandle (thread);
484 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
490 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
491 GetCurrentThreadId (), this, this->tid);
494 /* Only store the handle when the thread is about to be
495 * launched, to avoid the main thread deadlocking while trying
496 * to clean up a thread that will never be signalled.
500 if (mono_thread_callbacks)
501 (* mono_thread_callbacks->start_resume) (this->tid);
503 ResumeThread(thread);
505 if (mono_thread_callbacks)
506 (* mono_thread_callbacks->end_resume) (this->tid);
508 if(this->start_notify!=NULL) {
509 /* Wait for the thread to set up its TLS data etc, so
510 * theres no potential race condition if someone tries
511 * to look up the data believing the thread has
516 g_message(G_GNUC_PRETTY_FUNCTION
517 ": (%d) waiting for thread %p (%d) to start",
518 GetCurrentThreadId (), this, this->tid);
521 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
522 CloseHandle (this->start_notify);
523 this->start_notify=NULL;
527 g_message(G_GNUC_PRETTY_FUNCTION
528 ": (%d) Done launching thread %p (%d)",
529 GetCurrentThreadId (), this, this->tid);
533 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
535 MonoThread *thread = mono_thread_current ();
540 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
543 mono_monitor_enter (thread->synch_lock);
544 thread->state |= ThreadState_WaitSleepJoin;
545 mono_monitor_exit (thread->synch_lock);
549 mono_monitor_enter (thread->synch_lock);
550 thread->state &= ~ThreadState_WaitSleepJoin;
551 mono_monitor_exit (thread->synch_lock);
555 ves_icall_System_Threading_Thread_GetDomainID (void)
559 return mono_domain_get()->domain_id;
563 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
568 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
572 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
575 g_free (this_obj->name);
577 this_obj->name = g_new (gunichar2, mono_string_length (name));
578 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
579 this_obj->name_len = mono_string_length (name);
582 this_obj->name = NULL;
586 mono_thread_current (void)
592 /* Find the current thread object */
593 thread=TlsGetValue (current_object_key);
596 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
602 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
603 int ms, HANDLE thread)
609 mono_monitor_enter (this->synch_lock);
610 this->state |= ThreadState_WaitSleepJoin;
611 mono_monitor_exit (this->synch_lock);
617 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
621 ret=WaitForSingleObjectEx (thread, ms, TRUE);
623 mono_monitor_enter (this->synch_lock);
624 this->state &= ~ThreadState_WaitSleepJoin;
625 mono_monitor_exit (this->synch_lock);
627 if(ret==WAIT_OBJECT_0) {
629 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
636 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
642 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
647 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
650 /* Object location stored here */
651 TlsSetValue(slothash_key, data);
654 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
660 data=TlsGetValue(slothash_key);
663 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
669 /* FIXME: exitContext isnt documented */
670 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
676 MonoObject *waitHandle;
681 numhandles = mono_array_length(mono_handles);
682 handles = g_new0(HANDLE, numhandles);
684 if (wait_handle_os_handle_field == 0) {
685 /* Get the field os_handle which will contain the actual handle */
686 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
687 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
690 for(i = 0; i < numhandles; i++) {
691 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
692 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
699 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
703 if(ret==WAIT_FAILED) {
704 #ifdef THREAD_WAIT_DEBUG
705 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
706 GetCurrentThreadId ());
709 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
710 /* Do we want to try again if we get
711 * WAIT_IO_COMPLETION? The documentation for
712 * WaitHandle doesn't give any clues. (We'd have to
713 * fiddle with the timeout if we retry.)
715 #ifdef THREAD_WAIT_DEBUG
716 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
717 GetCurrentThreadId ());
725 /* FIXME: exitContext isnt documented */
726 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
732 MonoObject *waitHandle;
737 numhandles = mono_array_length(mono_handles);
738 handles = g_new0(HANDLE, numhandles);
740 if (wait_handle_os_handle_field == 0) {
741 /* Get the field os_handle which will contain the actual handle */
742 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
743 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
746 for(i = 0; i < numhandles; i++) {
747 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
748 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
755 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
759 #ifdef THREAD_WAIT_DEBUG
760 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
761 GetCurrentThreadId (), ret);
765 * These need to be here. See MSDN dos on WaitForMultipleObjects.
767 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
768 return ret - WAIT_OBJECT_0;
770 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
771 return ret - WAIT_ABANDONED_0;
778 /* FIXME: exitContext isnt documented */
779 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
785 #ifdef THREAD_WAIT_DEBUG
786 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
787 GetCurrentThreadId (), handle, ms);
794 ret=WaitForSingleObjectEx (handle, ms, TRUE);
796 if(ret==WAIT_FAILED) {
797 #ifdef THREAD_WAIT_DEBUG
798 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
799 GetCurrentThreadId ());
802 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
803 /* Do we want to try again if we get
804 * WAIT_IO_COMPLETION? The documentation for
805 * WaitHandle doesn't give any clues. (We'd have to
806 * fiddle with the timeout if we retry.)
808 #ifdef THREAD_WAIT_DEBUG
809 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
810 GetCurrentThreadId ());
818 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
827 mutex = CreateMutex (NULL, owned, NULL);
829 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
831 if (GetLastError () == ERROR_ALREADY_EXISTS) {
839 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
842 ReleaseMutex(handle);
845 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
848 return(CreateEvent (NULL, manual, initial,
849 name==NULL?NULL:mono_string_chars (name)));
852 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
855 return (SetEvent(handle));
858 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
861 return (ResetEvent(handle));
865 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
868 CloseHandle (handle);
871 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
875 return InterlockedIncrement (location);
878 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
885 EnterCriticalSection(&interlocked_mutex);
887 lowret = InterlockedIncrement((gint32 *) location);
889 highret = InterlockedIncrement((gint32 *) location + 1);
891 highret = *((gint32 *) location + 1);
893 LeaveCriticalSection(&interlocked_mutex);
895 return (gint64) highret << 32 | (gint64) lowret;
898 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
902 return InterlockedDecrement(location);
905 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
912 EnterCriticalSection(&interlocked_mutex);
914 lowret = InterlockedDecrement((gint32 *) location);
916 highret = InterlockedDecrement((gint32 *) location + 1);
918 highret = *((gint32 *) location + 1);
920 LeaveCriticalSection(&interlocked_mutex);
922 return (gint64) highret << 32 | (gint64) lowret;
925 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
929 return InterlockedExchange(location1, value);
932 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
936 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
939 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
941 IntFloatUnion val, ret;
946 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
951 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
955 return InterlockedCompareExchange(location1, value, comparand);
958 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
962 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
965 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
967 IntFloatUnion val, ret, cmp;
972 cmp.fval = comparand;
973 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
979 mono_thread_get_abort_signal (void)
989 #endif /* __MINGW32__ */
993 static guint32 interruption_request_apc (gpointer param)
995 MonoException* exc = mono_thread_request_interruption (FALSE);
996 if (exc) mono_raise_exception (exc);
999 #endif /* __MINGW32__ */
1002 * signal_thread_state_change
1004 * Tells the thread that his state has changed and it has to enter the new
1005 * state as soon as possible.
1007 static void signal_thread_state_change (MonoThread *thread)
1010 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1012 /* fixme: store the state somewhere */
1013 #ifdef PTHREAD_POINTER_ID
1014 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1016 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1018 #endif /* __MINGW32__ */
1022 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1024 MONO_ARCH_SAVE_REGS;
1026 mono_monitor_enter (thread->synch_lock);
1028 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1029 (thread->state & ThreadState_StopRequested) != 0)
1031 mono_monitor_exit (thread->synch_lock);
1035 thread->state |= ThreadState_AbortRequested;
1036 thread->abort_state = state;
1037 thread->abort_exc = NULL;
1039 mono_monitor_exit (thread->synch_lock);
1042 g_message (G_GNUC_PRETTY_FUNCTION
1043 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1044 thread, thread->tid);
1047 /* Make sure the thread is awake */
1048 ves_icall_System_Threading_Thread_Resume (thread);
1050 signal_thread_state_change (thread);
1054 ves_icall_System_Threading_Thread_ResetAbort (void)
1056 MonoThread *thread = mono_thread_current ();
1058 MONO_ARCH_SAVE_REGS;
1060 mono_monitor_enter (thread->synch_lock);
1062 thread->state &= ~ThreadState_AbortRequested;
1064 if (!thread->abort_exc) {
1065 const char *msg = "Unable to reset abort because no abort was requested";
1066 mono_monitor_exit (thread->synch_lock);
1067 mono_raise_exception (mono_get_exception_thread_state (msg));
1069 thread->abort_exc = NULL;
1070 thread->abort_state = NULL;
1073 mono_monitor_exit (thread->synch_lock);
1077 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1079 MONO_ARCH_SAVE_REGS;
1081 mono_monitor_enter (thread->synch_lock);
1083 if ((thread->state & ThreadState_Suspended) != 0 ||
1084 (thread->state & ThreadState_SuspendRequested) != 0 ||
1085 (thread->state & ThreadState_StopRequested) != 0)
1087 mono_monitor_exit (thread->synch_lock);
1091 thread->state |= ThreadState_SuspendRequested;
1092 mono_monitor_exit (thread->synch_lock);
1094 signal_thread_state_change (thread);
1098 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1100 MONO_ARCH_SAVE_REGS;
1102 mono_monitor_enter (thread->synch_lock);
1104 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1105 thread->state &= ~ThreadState_SuspendRequested;
1106 mono_monitor_exit (thread->synch_lock);
1110 if ((thread->state & ThreadState_Suspended) == 0)
1112 mono_monitor_exit (thread->synch_lock);
1116 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1118 /* Awake the thread */
1119 SetEvent (thread->suspend_event);
1121 mono_monitor_exit (thread->synch_lock);
1123 /* Wait for the thread to awake */
1124 WaitForSingleObject (thread->resume_event, INFINITE);
1125 CloseHandle (thread->resume_event);
1126 thread->resume_event = NULL;
1129 void mono_thread_stop (MonoThread *thread)
1131 mono_monitor_enter (thread->synch_lock);
1133 if ((thread->state & ThreadState_StopRequested) != 0 ||
1134 (thread->state & ThreadState_Stopped) != 0)
1136 mono_monitor_exit (thread->synch_lock);
1140 /* Make sure the thread is awake */
1141 ves_icall_System_Threading_Thread_Resume (thread);
1143 thread->state |= ThreadState_StopRequested;
1144 thread->state &= ~ThreadState_AbortRequested;
1146 mono_monitor_exit (thread->synch_lock);
1148 signal_thread_state_change (thread);
1152 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1154 return *((volatile gint8 *) (ptr));
1158 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1160 return *((volatile gint16 *) (ptr));
1164 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1166 return *((volatile gint32 *) (ptr));
1170 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1172 return *((volatile gint64 *) (ptr));
1176 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1178 return (void *) *((volatile void **) ptr);
1182 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1184 *((volatile gint8 *) ptr) = value;
1188 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1190 *((volatile gint16 *) ptr) = value;
1194 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1196 *((volatile gint32 *) ptr) = value;
1200 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1202 *((volatile gint64 *) ptr) = value;
1206 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1208 *((volatile void **) ptr) = value;
1211 void mono_thread_init (MonoThreadStartCB start_cb,
1212 MonoThreadAttachCB attach_cb)
1214 InitializeCriticalSection(&threads_mutex);
1215 InitializeCriticalSection(&interlocked_mutex);
1216 InitializeCriticalSection(&contexts_mutex);
1217 InitializeCriticalSection(&interruption_mutex);
1219 mono_init_static_data_info (&thread_static_info);
1220 mono_init_static_data_info (&context_static_info);
1222 current_object_key=TlsAlloc();
1224 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1225 current_object_key);
1228 mono_thread_start_cb = start_cb;
1229 mono_thread_attach_cb = attach_cb;
1231 slothash_key=TlsAlloc();
1233 /* Get a pseudo handle to the current process. This is just a
1234 * kludge so that wapi can build a process handle if needed.
1235 * As a pseudo handle is returned, we don't need to clean
1238 GetCurrentProcess ();
1242 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1244 mono_thread_cleanup = func;
1247 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1249 mono_thread_callbacks = callbacks;
1253 static void print_tids (gpointer key, gpointer value, gpointer user)
1255 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1261 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1262 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1266 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1271 g_message(G_GNUC_PRETTY_FUNCTION
1272 ": %d threads to wait for in this batch", wait->num);
1275 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1277 if(ret==WAIT_FAILED) {
1278 /* See the comment in build_wait_tids() */
1280 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1286 for(i=0; i<wait->num; i++) {
1287 guint32 tid=wait->threads[i]->tid;
1288 CloseHandle (wait->handles[i]);
1290 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1291 /* This thread must have been killed, because
1292 * it hasn't cleaned itself up. (It's just
1293 * possible that the thread exited before the
1294 * parent thread had a chance to store the
1295 * handle, and now there is another pointer to
1296 * the already-exited thread stored. In this
1297 * case, we'll just get two
1298 * mono_profiler_thread_end() calls for the
1303 g_message (G_GNUC_PRETTY_FUNCTION
1304 ": cleaning up after thread %d", tid);
1306 thread_cleanup (wait->threads[i]);
1311 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1313 struct wait_data *wait=(struct wait_data *)user;
1315 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1317 MonoThread *thread=(MonoThread *)value;
1319 /* Ignore background threads, we abort them later */
1320 if (thread->state & ThreadState_Background)
1321 return; /* just leave, ignore */
1323 if (mono_gc_is_finalizer_thread (thread))
1326 if (thread == mono_thread_current ())
1329 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1333 wait->handles[wait->num]=handle;
1334 wait->threads[wait->num]=thread;
1337 /* Just ignore the rest, we can't do anything with
1344 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1346 struct wait_data *wait=(struct wait_data *)user;
1347 guint32 self = GetCurrentThreadId ();
1348 MonoThread *thread = (MonoThread *) value;
1351 /* The finalizer thread is not a background thread */
1352 if (thread->tid != self && thread->state & ThreadState_Background) {
1354 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1358 wait->handles[wait->num]=thread->handle;
1359 wait->threads[wait->num]=thread;
1362 if(thread->state & ThreadState_AbortRequested ||
1363 thread->state & ThreadState_Aborted) {
1365 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1371 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1373 mono_thread_stop (thread);
1377 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1380 void mono_thread_manage (void)
1382 struct wait_data *wait=g_new0 (struct wait_data, 1);
1384 /* join each thread that's still running */
1386 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1389 EnterCriticalSection (&threads_mutex);
1392 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1394 LeaveCriticalSection (&threads_mutex);
1397 LeaveCriticalSection (&threads_mutex);
1400 EnterCriticalSection (&threads_mutex);
1402 g_message(G_GNUC_PRETTY_FUNCTION
1403 ":There are %d threads to join",
1404 mono_g_hash_table_size (threads));
1405 mono_g_hash_table_foreach (threads, print_tids, NULL);
1409 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1410 LeaveCriticalSection (&threads_mutex);
1412 /* Something to wait for */
1413 wait_for_tids (wait, INFINITE);
1415 } while(wait->num>0);
1417 mono_thread_pool_cleanup ();
1419 EnterCriticalSection(&threads_mutex);
1422 * Remove everything but the finalizer thread and self.
1423 * Also abort all the background threads
1426 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1428 LeaveCriticalSection(&threads_mutex);
1431 /* Something to wait for */
1432 wait_for_tids (wait, INFINITE);
1438 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1440 MonoThread *thread=(MonoThread *)value;
1441 guint32 self=GPOINTER_TO_UINT (user);
1443 if(thread->tid!=self) {
1444 /*TerminateThread (thread->handle, -1);*/
1448 void mono_thread_abort_all_other_threads (void)
1450 guint32 self=GetCurrentThreadId ();
1452 EnterCriticalSection (&threads_mutex);
1454 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1455 mono_g_hash_table_size (threads));
1456 mono_g_hash_table_foreach (threads, print_tids, NULL);
1459 mono_g_hash_table_foreach (threads, terminate_thread,
1460 GUINT_TO_POINTER (self));
1462 LeaveCriticalSection (&threads_mutex);
1466 * mono_thread_push_appdomain_ref:
1468 * Register that the current thread may have references to objects in domain
1469 * @domain on its stack. Each call to this function should be paired with a
1470 * call to pop_appdomain_ref.
1473 mono_thread_push_appdomain_ref (MonoDomain *domain)
1475 MonoThread *thread = mono_thread_current ();
1478 /* printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name); */
1479 EnterCriticalSection (&threads_mutex);
1480 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1481 LeaveCriticalSection (&threads_mutex);
1486 mono_thread_pop_appdomain_ref (void)
1488 MonoThread *thread = mono_thread_current ();
1491 /* printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1492 EnterCriticalSection (&threads_mutex);
1493 /* FIXME: How can the list be empty ? */
1494 if (thread->appdomain_refs)
1495 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1496 LeaveCriticalSection (&threads_mutex);
1501 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1504 EnterCriticalSection (&threads_mutex);
1505 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1506 LeaveCriticalSection (&threads_mutex);
1510 typedef struct abort_appdomain_data {
1511 struct wait_data wait;
1513 } abort_appdomain_data;
1516 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1518 MonoThread *thread = (MonoThread*)value;
1519 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1520 MonoDomain *domain = data->domain;
1522 if (mono_thread_has_appdomain_ref (thread, domain)) {
1523 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1524 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1526 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1527 data->wait.handles [data->wait.num] = thread->handle;
1528 data->wait.threads [data->wait.num] = thread;
1531 /* Just ignore the rest, we can't do anything with
1539 * mono_threads_abort_appdomain_threads:
1541 * Abort threads which has references to the given appdomain.
1544 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1546 abort_appdomain_data user_data;
1549 /* printf ("ABORT BEGIN.\n"); */
1551 start_time = GetTickCount ();
1553 EnterCriticalSection (&threads_mutex);
1555 user_data.domain = domain;
1556 user_data.wait.num = 0;
1557 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1558 LeaveCriticalSection (&threads_mutex);
1560 if (user_data.wait.num > 0)
1561 wait_for_tids (&user_data.wait, timeout);
1563 /* Update remaining time */
1564 timeout -= GetTickCount () - start_time;
1565 start_time = GetTickCount ();
1570 while (user_data.wait.num > 0);
1572 /* printf ("ABORT DONE.\n"); */
1578 * mono_thread_get_pending_exception:
1580 * Return an exception which needs to be raised when leaving a catch clause.
1581 * This is used for undeniable exception propagation.
1584 mono_thread_get_pending_exception (void)
1586 MonoThread *thread = mono_thread_current ();
1588 MONO_ARCH_SAVE_REGS;
1590 if (thread && thread->abort_exc) {
1592 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1593 * exception if the thread no longer references a dying appdomain.
1595 thread->abort_exc->trace_ips = NULL;
1596 thread->abort_exc->stack_trace = NULL;
1597 return thread->abort_exc;
1603 #define NUM_STATIC_DATA_IDX 8
1604 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1605 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1610 * mono_alloc_static_data
1612 * Allocate memory blocks for storing threads or context static data
1615 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1617 guint idx = (offset >> 24) - 1;
1620 gpointer* static_data = *static_data_ptr;
1623 static_data = GC_MALLOC (static_data_size [0]);
1625 static_data = g_malloc0 (static_data_size [0]);
1627 *static_data_ptr = static_data;
1628 static_data [0] = static_data;
1631 for (i = 1; i < idx; ++i) {
1632 if (static_data [i])
1635 static_data [i] = GC_MALLOC (static_data_size [i]);
1637 static_data [i] = g_malloc0 (static_data_size [i]);
1643 * mono_init_static_data_info
1645 * Initializes static data counters
1647 static void mono_init_static_data_info (StaticDataInfo *static_data)
1649 static_data->idx = 0;
1650 static_data->offset = 0;
1654 * mono_alloc_static_data_slot
1656 * Generates an offset for static data. static_data contains the counters
1657 * used to generate it.
1660 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1664 if (!static_data->idx && !static_data->offset) {
1666 * we use the first chunk of the first allocation also as
1667 * an array for the rest of the data
1669 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1671 static_data->offset += align - 1;
1672 static_data->offset &= ~(align - 1);
1673 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1674 static_data->idx ++;
1675 g_assert (size <= static_data_size [static_data->idx]);
1677 * massive unloading and reloading of domains with thread-static
1678 * data may eventually exceed the allocated storage...
1679 * Need to check what the MS runtime does in that case.
1680 * Note that for each appdomain, we need to allocate a separate
1681 * thread data slot for security reasons. We could keep track
1682 * of the slots per-domain and when the domain is unloaded
1683 * out the slots on a sort of free list.
1685 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1686 static_data->offset = 0;
1688 offset = static_data->offset | ((static_data->idx + 1) << 24);
1689 static_data->offset += size;
1694 * ensure thread static fields already allocated are valid for thread
1695 * This function is called when a thread is created or on thread attach.
1698 thread_adjust_static_data (MonoThread *thread)
1702 EnterCriticalSection (&threads_mutex);
1703 if (thread_static_info.offset || thread_static_info.idx > 0) {
1704 /* get the current allocated size */
1705 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1706 mono_alloc_static_data (&(thread->static_data), offset);
1708 LeaveCriticalSection (&threads_mutex);
1712 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1714 MonoThread *thread = value;
1715 guint32 offset = GPOINTER_TO_UINT (user);
1717 mono_alloc_static_data (&(thread->static_data), offset);
1721 * The offset for a special static variable is composed of three parts:
1722 * a bit that indicates the type of static data (0:thread, 1:context),
1723 * an index in the array of chunks of memory for the thread (thread->static_data)
1724 * and an offset in that chunk of mem. This allows allocating less memory in the
1729 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1732 if (static_type == SPECIAL_STATIC_THREAD)
1734 EnterCriticalSection (&threads_mutex);
1735 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1736 /* This can be called during startup */
1737 if (threads != NULL)
1738 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1739 LeaveCriticalSection (&threads_mutex);
1743 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1744 EnterCriticalSection (&contexts_mutex);
1745 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1746 LeaveCriticalSection (&contexts_mutex);
1747 offset |= 0x80000000; /* Set the high bit to indicate context static data */
1753 mono_get_special_static_data (guint32 offset)
1755 /* The high bit means either thread (0) or static (1) data. */
1757 guint32 static_type = (offset & 0x80000000);
1760 offset &= 0x7fffffff;
1761 idx = (offset >> 24) - 1;
1763 if (static_type == 0)
1765 MonoThread *thread = mono_thread_current ();
1766 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1770 /* Allocate static data block under demand, since we don't have a list
1773 MonoAppContext *context = mono_context_get ();
1774 if (!context->static_data || !context->static_data [idx]) {
1775 EnterCriticalSection (&contexts_mutex);
1776 mono_alloc_static_data (&(context->static_data), offset);
1777 LeaveCriticalSection (&contexts_mutex);
1779 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
1783 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1785 MonoThread *thread=(MonoThread *)value;
1786 guint32 self=GPOINTER_TO_UINT (user);
1789 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1792 if(thread->tid==self)
1795 SuspendThread (thread->handle);
1798 void mono_gc_stop_world (void)
1800 guint32 self=GetCurrentThreadId ();
1803 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1806 EnterCriticalSection (&threads_mutex);
1808 if (threads != NULL)
1809 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1811 LeaveCriticalSection (&threads_mutex);
1814 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1816 MonoThread *thread=(MonoThread *)value;
1817 guint32 self=GPOINTER_TO_UINT (user);
1820 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1823 if(thread->tid==self)
1826 ResumeThread (thread->handle);
1829 void mono_gc_start_world (void)
1831 guint32 self=GetCurrentThreadId ();
1834 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1837 EnterCriticalSection (&threads_mutex);
1839 if (threads != NULL)
1840 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1842 LeaveCriticalSection (&threads_mutex);
1846 static guint32 dummy_apc (gpointer param)
1852 * mono_thread_execute_interruption
1854 * Performs the operation that the requested thread state requires (abort,
1857 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1859 mono_monitor_enter (thread->synch_lock);
1861 if (thread->interruption_requested) {
1862 /* this will consume pending APC calls */
1863 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1864 EnterCriticalSection (&interruption_mutex);
1865 thread_interruption_requested--;
1866 LeaveCriticalSection (&interruption_mutex);
1867 thread->interruption_requested = FALSE;
1870 if ((thread->state & ThreadState_AbortRequested) != 0) {
1871 thread->abort_exc = mono_get_exception_thread_abort ();
1872 mono_monitor_exit (thread->synch_lock);
1873 return thread->abort_exc;
1875 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1876 thread->state &= ~ThreadState_SuspendRequested;
1877 thread->state |= ThreadState_Suspended;
1878 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1879 mono_monitor_exit (thread->synch_lock);
1881 WaitForSingleObject (thread->suspend_event, INFINITE);
1883 mono_monitor_enter (thread->synch_lock);
1884 CloseHandle (thread->suspend_event);
1885 thread->suspend_event = NULL;
1886 thread->state &= ~ThreadState_Suspended;
1888 /* The thread that requested the resume will have replaced this event
1889 * and will be waiting for it
1891 SetEvent (thread->resume_event);
1892 mono_monitor_exit (thread->synch_lock);
1895 else if ((thread->state & ThreadState_StopRequested) != 0) {
1896 /* FIXME: do this through the JIT? */
1897 mono_monitor_exit (thread->synch_lock);
1902 mono_monitor_exit (thread->synch_lock);
1907 * mono_thread_request_interruption
1909 * A signal handler can call this method to request the interruption of a
1910 * thread. The result of the interruption will depend on the current state of
1911 * the thread. If the result is an exception that needs to be throw, it is
1912 * provided as return value.
1914 MonoException* mono_thread_request_interruption (gboolean running_managed)
1916 MonoThread *thread = mono_thread_current ();
1918 /* The thread may already be stopping */
1922 mono_monitor_enter (thread->synch_lock);
1924 if (thread->interruption_requested) {
1925 mono_monitor_exit (thread->synch_lock);
1929 if (!running_managed) {
1930 /* Can't stop while in unmanaged code. Increase the global interruption
1931 request count. When exiting the unmanaged method the count will be
1932 checked and the thread will be interrupted. */
1934 EnterCriticalSection (&interruption_mutex);
1935 thread_interruption_requested++;
1936 LeaveCriticalSection (&interruption_mutex);
1938 thread->interruption_requested = TRUE;
1939 mono_monitor_exit (thread->synch_lock);
1941 /* this will awake the thread if it is in WaitForSingleObject
1943 QueueUserAPC (dummy_apc, thread->handle, NULL);
1948 mono_monitor_exit (thread->synch_lock);
1949 return mono_thread_execute_interruption (thread);
1953 gboolean mono_thread_interruption_requested ()
1955 if (thread_interruption_requested) {
1956 MonoThread *thread = mono_thread_current ();
1957 /* The thread may already be stopping */
1959 return (thread->interruption_requested);
1965 * Performs the interruption of the current thread, if one has been requested.
1967 void mono_thread_interruption_checkpoint ()
1969 MonoThread *thread = mono_thread_current ();
1971 /* The thread may already be stopping */
1975 if (thread->interruption_requested) {
1976 MonoException* exc = mono_thread_execute_interruption (thread);
1977 if (exc) mono_raise_exception (exc);
1982 * Returns the address of a flag that will be non-zero if an interruption has
1983 * been requested for a thread. The thread to interrupt may not be the current
1984 * thread, so an additional call to mono_thread_interruption_requested() or
1985 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
1988 gint32* mono_thread_interruption_request_flag ()
1990 return &thread_interruption_requested;
1993 #ifdef WITH_INCLUDED_LIBGC
1995 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
1997 MonoThread *thread=(MonoThread *)value;
1998 guint32 *selfp=(guint32 *)user, self = *selfp;
2001 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2004 if(thread->tid==self) {
2006 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2008 GC_push_all_stack (selfp, thread->stack_ptr);
2012 #ifdef PLATFORM_WIN32
2013 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2015 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2019 void mono_gc_push_all_stacks (void)
2021 guint32 self=GetCurrentThreadId ();
2024 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2027 EnterCriticalSection (&threads_mutex);
2029 if (threads != NULL)
2030 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2032 LeaveCriticalSection (&threads_mutex);
2035 #endif /* WITH_INCLUDED_LIBGC */