Fix warnings.
[mono.git] / mono / metadata / threads.c
index 7b4db2c695053f96ac5ab71cd04e00a0d0df2b72..660eabaf632d7c7fb9847dd59973f34cd6919f8d 100644 (file)
@@ -8,6 +8,7 @@
  *
  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
+ * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
  */
 
 #include <config.h>
@@ -44,6 +45,7 @@
 #include <mono/utils/mono-time.h>
 #include <mono/utils/mono-threads.h>
 #include <mono/utils/hazard-pointer.h>
+#include <mono/utils/mono-tls.h>
 
 #include <mono/metadata/gc-internal.h>
 
@@ -147,7 +149,7 @@ static MonoGHashTable *threads_starting_up = NULL;
 static MonoGHashTable *thread_start_args = NULL;
 
 /* The TLS key that holds the MonoObject assigned to each thread */
-static guint32 current_object_key = -1;
+static MonoNativeTlsKey current_object_key;
 
 #ifdef MONO_HAVE_FAST_TLS
 /* we need to use both the Tls* functions and __thread because
@@ -156,12 +158,12 @@ static guint32 current_object_key = -1;
 MONO_FAST_TLS_DECLARE(tls_current_object);
 #define SET_CURRENT_OBJECT(x) do { \
        MONO_FAST_TLS_SET (tls_current_object, x); \
-       TlsSetValue (current_object_key, x); \
+       mono_native_tls_set_value (current_object_key, x); \
 } while (FALSE)
 #define GET_CURRENT_OBJECT() ((MonoInternalThread*) MONO_FAST_TLS_GET (tls_current_object))
 #else
-#define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
-#define GET_CURRENT_OBJECT() (MonoInternalThread*) TlsGetValue (current_object_key)
+#define SET_CURRENT_OBJECT(x) mono_native_tls_set_value (current_object_key, x)
+#define GET_CURRENT_OBJECT() (MonoInternalThread*) mono_native_tls_get_value (current_object_key)
 #endif
 
 /* function called at thread start */
@@ -187,6 +189,10 @@ static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32
 static gboolean mono_thread_resume (MonoInternalThread* thread);
 static void mono_thread_start (MonoThread *thread);
 static void signal_thread_state_change (MonoInternalThread *thread);
+static void abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception, gboolean install_async_abort);
+static void suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt);
+static void self_suspend_internal (MonoInternalThread *thread);
+static gboolean resume_thread_internal (MonoInternalThread *thread);
 
 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
 static void ref_stack_destroy (gpointer rs);
@@ -212,7 +218,7 @@ get_next_managed_thread_id (void)
        return InterlockedIncrement (&managed_thread_id_counter);
 }
 
-guint32
+MonoNativeTlsKey
 mono_thread_get_tls_key (void)
 {
        return current_object_key;
@@ -362,6 +368,8 @@ static void thread_cleanup (MonoInternalThread *thread)
        }
        mono_release_type_locks (thread);
 
+       ensure_synch_cs_set (thread);
+
        EnterCriticalSection (thread->synch_cs);
 
        thread->state |= ThreadState_Stopped;
@@ -643,7 +651,7 @@ gpointer mono_create_thread (WapiSecurityAttributes *security,
 #ifdef HOST_WIN32
        DWORD real_tid;
 
-       res = CreateThread (security, stacksize, start, param, create, &real_tid);
+       res = mono_threads_CreateThread (security, stacksize, start, param, create, &real_tid);
        if (tid)
                *tid = real_tid;
 #else
@@ -760,6 +768,9 @@ mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
        *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
        *stsize = pthread_get_stacksize_np (pthread_self ());
+
+       /* staddr points to the start of the stack, not the end */
+       *staddr -= *stsize;
        *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
        return;
        /* FIXME: simplify the mess below */
@@ -1237,7 +1248,7 @@ byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
                return arr;
 
        copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
-       memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
+       mono_gc_memmove (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
        return copy;
 }
 
@@ -1969,25 +1980,22 @@ ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
 
 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
 {
-       gboolean throw = FALSE;
-       
+       MonoInternalThread *current;
+       gboolean throw;
+
        ensure_synch_cs_set (this);
 
-       if (this == mono_thread_internal_current ())
-               return;
-       
-       EnterCriticalSection (this->synch_cs);
-       
-       this->thread_interrupt_requested = TRUE;
-       
-       if (this->state & ThreadState_WaitSleepJoin) {
-               throw = TRUE;
-       }
-       
+       current = mono_thread_internal_current ();
+
+       EnterCriticalSection (this->synch_cs);  
+
+       this->thread_interrupt_requested = TRUE;        
+       throw = current != this && (this->state & ThreadState_WaitSleepJoin);   
+
        LeaveCriticalSection (this->synch_cs);
        
        if (throw) {
-               signal_thread_state_change (this);
+               abort_thread_internal (this, TRUE, FALSE);
        }
 }
 
@@ -2135,7 +2143,7 @@ ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject
                /* Make sure the thread is awake */
                mono_thread_resume (thread);
        
-       signal_thread_state_change (thread);
+       abort_thread_internal (thread, TRUE, TRUE);
 }
 
 void
@@ -2242,7 +2250,7 @@ mono_thread_suspend (MonoInternalThread *thread)
 
        LeaveCriticalSection (thread->synch_cs);
 
-       signal_thread_state_change (thread);
+       suspend_thread_internal (thread, FALSE);
        return TRUE;
 }
 
@@ -2274,24 +2282,8 @@ mono_thread_resume (MonoInternalThread *thread)
                LeaveCriticalSection (thread->synch_cs);
                return FALSE;
        }
-       
-       thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
-       if (thread->resume_event == NULL) {
-               LeaveCriticalSection (thread->synch_cs);
-               return(FALSE);
-       }
-       
-       /* Awake the thread */
-       SetEvent (thread->suspend_event);
-
-       LeaveCriticalSection (thread->synch_cs);
-
-       /* Wait for the thread to awake */
-       WaitForSingleObject (thread->resume_event, INFINITE);
-       CloseHandle (thread->resume_event);
-       thread->resume_event = NULL;
 
-       return TRUE;
+       return resume_thread_internal (thread);
 }
 
 void
@@ -2355,7 +2347,7 @@ void mono_thread_internal_stop (MonoInternalThread *thread)
        
        LeaveCriticalSection (thread->synch_cs);
        
-       signal_thread_state_change (thread);
+       abort_thread_internal (thread, TRUE, TRUE);
 }
 
 void mono_thread_stop (MonoThread *thread)
@@ -2393,6 +2385,18 @@ ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
        return (void *)  *((volatile void **) ptr);
 }
 
+double
+ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
+{
+       return *((volatile double *) (ptr));
+}
+
+float
+ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
+{
+       return *((volatile float *) (ptr));
+}
+
 void
 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
 {
@@ -2429,11 +2433,21 @@ ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
        mono_gc_wbarrier_generic_store (ptr, value);
 }
 
+void
+ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
+{
+       *((volatile double *) ptr) = value;
+}
+
+void
+ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
+{
+       *((volatile float *) ptr) = value;
+}
+
 void mono_thread_init (MonoThreadStartCB start_cb,
                       MonoThreadAttachCB attach_cb)
 {
-       mono_thread_smr_init ();
-
        InitializeCriticalSection(&threads_mutex);
        InitializeCriticalSection(&interlocked_mutex);
        InitializeCriticalSection(&contexts_mutex);
@@ -2445,7 +2459,7 @@ void mono_thread_init (MonoThreadStartCB start_cb,
        mono_init_static_data_info (&context_static_info);
 
        MONO_FAST_TLS_INIT (tls_current_object);
-       current_object_key=TlsAlloc();
+       mono_native_tls_alloc (&current_object_key, NULL);
        THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
 
        mono_thread_start_cb = start_cb;
@@ -2488,7 +2502,7 @@ void mono_thread_cleanup (void)
        CloseHandle (background_change_event);
 #endif
 
-       TlsFree (current_object_key);
+       mono_native_tls_free (current_object_key);
 }
 
 void
@@ -2998,11 +3012,14 @@ void mono_thread_suspend_all_other_threads (void)
                        LeaveCriticalSection (thread->synch_cs);
 
                        /* Signal the thread to suspend */
-                       if (signal_suspend)
+                       if (mono_thread_info_new_interrupt_enabled ())
+                               suspend_thread_internal (thread, TRUE);
+                       else if (signal_suspend)
                                signal_thread_state_change (thread);
                }
 
-               if (eventidx > 0) {
+               /*Only wait on the suspend event if we are using the old path */
+               if (eventidx > 0 && !mono_thread_info_new_interrupt_enabled ()) {
                        WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
                        for (i = 0; i < wait->num; ++i) {
                                MonoInternalThread *thread = wait->threads [i];
@@ -3019,7 +3036,9 @@ void mono_thread_suspend_all_other_threads (void)
                                }
                                LeaveCriticalSection (thread->synch_cs);
                        }
-               } else {
+               }
+               
+               if (eventidx <= 0) {
                        /* 
                         * If there are threads which are starting up, we wait until they
                         * are suspended when they try to register in the threads hash.
@@ -3061,6 +3080,109 @@ collect_threads (gpointer key, gpointer value, gpointer user_data)
        }
 }
 
+static gboolean thread_dump_requested;
+
+static G_GNUC_UNUSED gboolean
+print_stack_frame_to_string (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
+{
+       GString *p = (GString*)data;
+       MonoMethod *method = NULL;
+       if (frame->ji)
+               method = frame->ji->method;
+
+       if (method) {
+               gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
+               g_string_append_printf (p, "  %s\n", location);
+               g_free (location);
+       } else
+               g_string_append_printf (p, "  at <unknown> <0x%05x>\n", frame->native_offset);
+
+       return FALSE;
+}
+
+static void
+print_thread_dump (MonoInternalThread *thread, MonoThreadInfo *info)
+{
+       GString* text = g_string_new (0);
+       char *name;
+       GError *error = NULL;
+
+       if (thread->name) {
+               name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
+               g_assert (!error);
+               g_string_append_printf (text, "\n\"%s\"", name);
+               g_free (name);
+       }
+       else if (thread->threadpool_thread)
+               g_string_append (text, "\n\"<threadpool thread>\"");
+       else
+               g_string_append (text, "\n\"<unnamed thread>\"");
+
+#if 0
+/* This no longer works with remote unwinding */
+#ifndef HOST_WIN32
+       wapi_desc = wapi_current_thread_desc ();
+       g_string_append_printf (text, " tid=0x%p this=0x%p %s\n", (gpointer)(gsize)thread->tid, thread,  wapi_desc);
+       free (wapi_desc);
+#endif
+#endif
+
+       mono_get_eh_callbacks ()->mono_walk_stack_with_state (print_stack_frame_to_string, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, text);
+       mono_thread_info_resume (mono_thread_info_get_tid (info));
+
+       fprintf (stdout, "%s", text->str);
+
+#if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
+       OutputDebugStringA(text->str);
+#endif
+
+       g_string_free (text, TRUE);
+       fflush (stdout);
+}
+
+static void
+dump_thread (gpointer key, gpointer value, gpointer user)
+{
+       MonoInternalThread *thread = (MonoInternalThread *)value;
+       MonoThreadInfo *info;
+
+       if (thread == mono_thread_internal_current ())
+               return;
+
+       /*
+       FIXME This still can hang if we stop a thread during malloc.
+       FIXME This can hang if we suspend on a critical method and the GC kicks in. A fix might be to have function
+       that takes a callback and runs it with the target suspended.
+       We probably should loop a bit around trying to get it to either managed code
+       or WSJ state.
+       */
+       info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
+
+       if (!info)
+               return;
+
+       print_thread_dump (thread, info);
+}
+
+void
+mono_threads_perform_thread_dump (void)
+{
+       if (!thread_dump_requested)
+               return;
+
+       printf ("Full thread dump:\n");
+
+       /* 
+        * Make a copy of the hashtable since we can't do anything with
+        * threads while threads_mutex is held.
+        */
+       mono_threads_lock ();
+       mono_g_hash_table_foreach (threads, dump_thread, NULL);
+       mono_threads_unlock ();
+
+       thread_dump_requested = FALSE;
+}
+
 /**
  * mono_threads_request_thread_dump:
  *
@@ -3073,6 +3195,14 @@ mono_threads_request_thread_dump (void)
        struct wait_data *wait = &wait_data;
        int i;
 
+       /*The new thread dump code runs out of the finalizer thread. */
+       if (mono_thread_info_new_interrupt_enabled ()) {
+               thread_dump_requested = TRUE;
+               mono_gc_finalize_notify ();
+               return;
+       }
+
+
        memset (wait, 0, sizeof (struct wait_data));
 
        /* 
@@ -3659,7 +3789,7 @@ free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
        if (!thread->static_data || !thread->static_data [idx])
                return;
        ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
-       memset (ptr, 0, data->size);
+       mono_gc_bzero (ptr, data->size);
 }
 
 static void
@@ -3898,39 +4028,7 @@ static MonoException* mono_thread_execute_interruption (MonoInternalThread *thre
                return thread->abort_exc;
        }
        else if ((thread->state & ThreadState_SuspendRequested) != 0) {
-               thread->state &= ~ThreadState_SuspendRequested;
-               thread->state |= ThreadState_Suspended;
-               thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
-               if (thread->suspend_event == NULL) {
-                       LeaveCriticalSection (thread->synch_cs);
-                       return(NULL);
-               }
-               if (thread->suspended_event)
-                       SetEvent (thread->suspended_event);
-
-               LeaveCriticalSection (thread->synch_cs);
-
-               if (shutting_down) {
-                       /* After we left the lock, the runtime might shut down so everything becomes invalid */
-                       for (;;)
-                               Sleep (1000);
-               }
-               
-               WaitForSingleObject (thread->suspend_event, INFINITE);
-               
-               EnterCriticalSection (thread->synch_cs);
-
-               CloseHandle (thread->suspend_event);
-               thread->suspend_event = NULL;
-               thread->state &= ~ThreadState_Suspended;
-       
-               /* The thread that requested the resume will have replaced this event
-                * and will be waiting for it
-                */
-               SetEvent (thread->resume_event);
-
-               LeaveCriticalSection (thread->synch_cs);
-               
+               self_suspend_internal (thread);         
                return NULL;
        }
        else if ((thread->state & ThreadState_StopRequested) != 0) {
@@ -4219,26 +4317,27 @@ mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
        return ret;
 }
 
-static MonoClassField *execution_context_field;
+//static MonoClassField *execution_context_field;
 
 static MonoObject**
 get_execution_context_addr (void)
 {
        MonoDomain *domain = mono_domain_get ();
-       guint32 offset;
+       guint32 offset = domain->execution_context_field_offset;
 
-       if (!execution_context_field) {
-               execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
-                               "_ec");
-               g_assert (execution_context_field);
-       }
+       if (!offset) {
+               MonoClassField *field = mono_class_get_field_from_name (mono_defaults.thread_class, "_ec");
+               g_assert (field);
 
-       g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
+               g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
 
-       mono_domain_lock (domain);
-       offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
-       mono_domain_unlock (domain);
-       g_assert (offset);
+               mono_domain_lock (domain);
+               offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, field));
+               mono_domain_unlock (domain);
+               g_assert (offset);
+
+               domain->execution_context_field_offset = offset;
+       }
 
        return (MonoObject**) mono_get_special_static_data (offset);
 }
@@ -4300,3 +4399,242 @@ mono_thread_kill (MonoInternalThread *thread, int signal)
 #  endif
 #endif
 }
+
+static void
+self_interrupt_thread (void *_unused)
+{
+       MonoThreadInfo *info = mono_thread_info_current ();
+       MonoException *exc = mono_thread_execute_interruption (mono_thread_internal_current ()); 
+       if (exc) /*We must use _with_context since we didn't trampoline into the runtime*/
+               mono_raise_exception_with_context (exc, &info->suspend_state.ctx);
+       g_assert_not_reached (); /*this MUST not happen since we can't resume from an async call*/
+}
+
+static gboolean
+mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
+{
+       if (!ji)
+               return FALSE;
+       return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
+}
+
+static gboolean
+last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
+{
+       MonoJitInfo **dest = data;
+       *dest = frame->ji;
+       return TRUE;
+}
+
+static MonoJitInfo*
+mono_thread_info_get_last_managed (MonoThreadInfo *info)
+{
+       MonoJitInfo *ji = NULL;
+       mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &ji);
+       return ji;
+}
+
+static void
+abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception, gboolean install_async_abort)
+{
+       MonoJitInfo *ji;
+       MonoThreadInfo *info = NULL;
+       gboolean protected_wrapper;
+       gboolean running_managed;
+
+       if (!mono_thread_info_new_interrupt_enabled ()) {
+               signal_thread_state_change (thread);
+               return;
+       }
+
+       /*
+       FIXME this is insanely broken, it doesn't cause interruption to happen
+       synchronously since passing FALSE to mono_thread_request_interruption makes sure it returns NULL
+       */
+       if (thread == mono_thread_internal_current ()) {
+               /* Do it synchronously */
+               MonoException *exc = mono_thread_request_interruption (can_raise_exception); 
+               if (exc)
+                       mono_raise_exception (exc);
+#ifndef HOST_WIN32
+               wapi_interrupt_thread (thread->handle);
+#endif
+               return;
+       }
+
+       /*FIXME we need to check 2 conditions here, request to interrupt this thread or if the target died*/
+       if (!(info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gsize)thread->tid, TRUE))) {
+               return;
+       }
+
+       if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (&info->suspend_state)) {
+               mono_thread_info_resume (mono_thread_info_get_tid (info));
+               return;
+       }
+
+       /*someone is already interrupting it*/
+       if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1) {
+               mono_thread_info_resume (mono_thread_info_get_tid (info));
+               return;
+       }
+
+       ji = mono_thread_info_get_last_managed (info);
+       protected_wrapper = ji && mono_threads_is_critical_method (ji->method);
+       running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
+
+       if (!protected_wrapper && running_managed) {
+               /*We are in managed code*/
+               /*Set the thread to call */
+               if (install_async_abort)
+                       mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
+               mono_thread_info_resume (mono_thread_info_get_tid (info));
+       } else {
+               gpointer interrupt_handle;
+               /* 
+                * This will cause waits to be broken.
+                * It will also prevent the thread from entering a wait, so if the thread returns
+                * from the wait before it receives the abort signal, it will just spin in the wait
+                * functions in the io-layer until the signal handler calls QueueUserAPC which will
+                * make it return.
+                */
+               InterlockedIncrement (&thread_interruption_requested);
+#ifndef HOST_WIN32
+               interrupt_handle = wapi_prepare_interrupt_thread (thread->handle);
+#endif
+               mono_thread_info_resume (mono_thread_info_get_tid (info));
+#ifndef HOST_WIN32
+               wapi_finish_interrupt_thread (interrupt_handle);
+#endif
+       }
+       /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
+}
+
+static void
+transition_to_suspended (MonoInternalThread *thread)
+{
+       if ((thread->state & ThreadState_SuspendRequested) == 0) {
+               g_assert (0); /*FIXME we should not reach this */
+               /*Make sure we balance the suspend count.*/
+               mono_thread_info_resume ((MonoNativeThreadId)(gpointer)(gsize)thread->tid);
+       } else {
+               thread->state &= ~ThreadState_SuspendRequested;
+               thread->state |= ThreadState_Suspended;
+       }
+       LeaveCriticalSection (thread->synch_cs);
+}
+
+static void
+suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt)
+{
+       if (!mono_thread_info_new_interrupt_enabled ()) {
+               signal_thread_state_change (thread);
+               return;
+       }
+
+       EnterCriticalSection (thread->synch_cs);
+       if (thread == mono_thread_internal_current ()) {
+               transition_to_suspended (thread);
+               mono_thread_info_self_suspend ();
+       } else {
+               MonoThreadInfo *info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gsize)thread->tid, interrupt);
+               MonoJitInfo *ji = mono_thread_info_get_last_managed (info);
+               gboolean protected_wrapper = ji && mono_threads_is_critical_method (ji->method);
+               gboolean running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
+
+               if (running_managed && !protected_wrapper) {
+                       transition_to_suspended (thread);
+               } else {
+                       gpointer interrupt_handle;
+
+                       if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 0)
+                               InterlockedIncrement (&thread_interruption_requested);
+#ifndef HOST_WIN32
+                       if (interrupt)
+                               interrupt_handle = wapi_prepare_interrupt_thread (thread->handle);
+#endif
+                       mono_thread_info_resume (mono_thread_info_get_tid (info));
+#ifndef HOST_WIN32
+                       if (interrupt)
+                               wapi_finish_interrupt_thread (interrupt_handle);
+#endif
+                       LeaveCriticalSection (thread->synch_cs);
+               }
+       }
+}
+
+/*This is called with @thread synch_cs held and it must release it*/
+static void
+self_suspend_internal (MonoInternalThread *thread)
+{
+       if (!mono_thread_info_new_interrupt_enabled ()) {
+               thread->state &= ~ThreadState_SuspendRequested;
+               thread->state |= ThreadState_Suspended;
+               thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+               if (thread->suspend_event == NULL) {
+                       LeaveCriticalSection (thread->synch_cs);
+                       return;
+               }
+               if (thread->suspended_event)
+                       SetEvent (thread->suspended_event);
+
+               LeaveCriticalSection (thread->synch_cs);
+
+               if (shutting_down) {
+                       /* After we left the lock, the runtime might shut down so everything becomes invalid */
+                       for (;;)
+                               Sleep (1000);
+               }
+               
+               WaitForSingleObject (thread->suspend_event, INFINITE);
+               
+               EnterCriticalSection (thread->synch_cs);
+
+               CloseHandle (thread->suspend_event);
+               thread->suspend_event = NULL;
+               thread->state &= ~ThreadState_Suspended;
+       
+               /* The thread that requested the resume will have replaced this event
+                * and will be waiting for it
+                */
+               SetEvent (thread->resume_event);
+
+               LeaveCriticalSection (thread->synch_cs);
+               return;
+       }
+
+       transition_to_suspended (thread);
+       mono_thread_info_self_suspend ();
+}
+
+/*This is called with @thread synch_cs held and it must release it*/
+static gboolean
+resume_thread_internal (MonoInternalThread *thread)
+{
+       if (!mono_thread_info_new_interrupt_enabled ()) {
+               thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+               if (thread->resume_event == NULL) {
+                       LeaveCriticalSection (thread->synch_cs);
+                       return FALSE;
+               }
+
+               /* Awake the thread */
+               SetEvent (thread->suspend_event);
+
+               LeaveCriticalSection (thread->synch_cs);
+
+               /* Wait for the thread to awake */
+               WaitForSingleObject (thread->resume_event, INFINITE);
+               CloseHandle (thread->resume_event);
+               thread->resume_event = NULL;
+               return TRUE;
+       }
+
+       LeaveCriticalSection (thread->synch_cs);        
+       /* Awake the thread */
+       if (!mono_thread_info_resume ((MonoNativeThreadId)(gpointer)(gsize)thread->tid))
+               return FALSE;
+       EnterCriticalSection (thread->synch_cs);
+       thread->state &= ~ThreadState_Suspended;
+       LeaveCriticalSection (thread->synch_cs);
+       return TRUE;
+}