Merge pull request #505 from roji/shutdown_flow
[mono.git] / mono / metadata / threads.c
index 660eabaf632d7c7fb9847dd59973f34cd6919f8d..56a1ea2646be71194ebe78c192d034ce8c60dd2f 100644 (file)
@@ -17,7 +17,7 @@
 #include <signal.h>
 #include <string.h>
 
-#if defined(__OpenBSD__)
+#if defined(__OpenBSD__) || defined(__FreeBSD__)
 #include <pthread.h>
 #include <pthread_np.h>
 #endif
@@ -33,6 +33,7 @@
 #include <mono/metadata/monitor.h>
 #include <mono/metadata/gc-internal.h>
 #include <mono/metadata/marshal.h>
+#include <mono/metadata/runtime.h>
 #include <mono/io-layer/io-layer.h>
 #ifndef HOST_WIN32
 #include <mono/io-layer/threads.h>
 extern int tkill (pid_t tid, int signal);
 #endif
 
+#if defined(PLATFORM_MACOSX) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
+void *pthread_get_stackaddr_np(pthread_t);
+size_t pthread_get_stacksize_np(pthread_t);
+#endif
+
 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
 #define THREAD_DEBUG(a)
 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
@@ -359,15 +365,6 @@ static void thread_cleanup (MonoInternalThread *thread)
                        mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
        }
 
-       /* if the thread is not in the hash it has been removed already */
-       if (!handle_remove (thread)) {
-               /* This needs to be called even if handle_remove () fails */
-               if (mono_thread_cleanup_fn)
-                       mono_thread_cleanup_fn (thread);
-               return;
-       }
-       mono_release_type_locks (thread);
-
        ensure_synch_cs_set (thread);
 
        EnterCriticalSection (thread->synch_cs);
@@ -376,7 +373,29 @@ static void thread_cleanup (MonoInternalThread *thread)
        thread->state &= ~ThreadState_Background;
 
        LeaveCriticalSection (thread->synch_cs);
+
+       /*
+       An interruption request has leaked to cleanup. Adjust the global counter.
+
+       This can happen is the abort source thread finds the abortee (this) thread
+       in unmanaged code. If this thread never trips back to managed code or check
+       the local flag it will be left set and positively unbalance the global counter.
        
+       Leaving the counter unbalanced will cause a performance degradation since all threads
+       will now keep checking their local flags all the time.
+       */
+       if (InterlockedExchange (&thread->interruption_requested, 0))
+               InterlockedDecrement (&thread_interruption_requested);
+
+       /* if the thread is not in the hash it has been removed already */
+       if (!handle_remove (thread)) {
+               /* This needs to be called even if handle_remove () fails */
+               if (mono_thread_cleanup_fn)
+                       mono_thread_cleanup_fn (thread);
+               return;
+       }
+       mono_release_type_locks (thread);
+
        mono_profiler_thread_end (thread->tid);
 
        if (thread == mono_thread_internal_current ())
@@ -392,7 +411,11 @@ static void thread_cleanup (MonoInternalThread *thread)
        if (mono_thread_cleanup_fn)
                mono_thread_cleanup_fn (thread);
 
-       MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
+       if (mono_gc_is_moving ()) {
+               MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
+               thread->thread_pinning_ref = NULL;
+       }
+               
 }
 
 static gpointer
@@ -609,12 +632,10 @@ static guint32 WINAPI start_wrapper_internal(void *data)
 
 static guint32 WINAPI start_wrapper(void *data)
 {
-#ifdef HAVE_SGEN_GC
        volatile int dummy;
 
        /* Avoid scanning the frames above this frame during a GC */
        mono_gc_set_stack_end ((void*)&dummy);
-#endif
 
        return start_wrapper_internal (data);
 }
@@ -679,13 +700,22 @@ register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info
        mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
 }
 
-MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size)
+/*
+ * mono_thread_create_internal:
+ * 
+ * If NO_DETACH is TRUE, then the thread is not detached using pthread_detach (). This is needed to fix the race condition where waiting for a thred to exit only waits for its exit event to be
+ * signalled, which can cause shutdown crashes if the thread shutdown code accesses data already freed by the runtime shutdown.
+ * Currently, this is only used for the finalizer thread.
+ */
+MonoInternalThread*
+mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, gboolean no_detach, guint32 stack_size)
 {
        MonoThread *thread;
        MonoInternalThread *internal;
        HANDLE thread_handle;
        struct StartInfo *start_info;
        gsize tid;
+       guint32 create_flags;
 
        thread = create_thread_object (domain);
        internal = create_internal_thread_object ();
@@ -717,8 +747,13 @@ MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer fu
        /* Create suspended, so we can do some housekeeping before the thread
         * starts
         */
+       create_flags = CREATE_SUSPENDED;
+#ifndef HOST_WIN32
+       if (no_detach)
+               create_flags |= CREATE_NO_DETACH;
+#endif
        thread_handle = mono_create_thread (NULL, stack_size, (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
-                                    CREATE_SUSPENDED, &tid);
+                                    create_flags, &tid);
        THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
        if (thread_handle == NULL) {
                /* The thread couldn't be created, so throw an exception */
@@ -733,9 +768,11 @@ MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer fu
        internal->handle=thread_handle;
        internal->tid=tid;
        internal->apartment_state=ThreadApartmentState_Unknown;
-       internal->thread_pinning_ref = internal;
        internal->managed_id = get_next_managed_thread_id ();
-       MONO_GC_REGISTER_ROOT (internal->thread_pinning_ref);
+       if (mono_gc_is_moving ()) {
+               internal->thread_pinning_ref = internal;
+               MONO_GC_REGISTER_ROOT_PINNING (internal->thread_pinning_ref);
+       }
 
        internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
        InitializeCriticalSection (internal->synch_cs);
@@ -747,13 +784,17 @@ MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer fu
        if (handle_store (thread))
                ResumeThread (thread_handle);
 
+       /* Check that the managed and unmanaged layout of MonoInternalThread matches */
+       if (mono_check_corlib_version () == NULL)
+               g_assert (((char*)&internal->unused2 - (char*)internal) == mono_defaults.internal_thread_class->fields [mono_defaults.internal_thread_class->field.count - 1].offset);
+
        return internal;
 }
 
 void
 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
 {
-       mono_thread_create_internal (domain, func, arg, FALSE, 0);
+       mono_thread_create_internal (domain, func, arg, FALSE, FALSE, 0);
 }
 
 /*
@@ -860,9 +901,11 @@ mono_thread_attach (MonoDomain *domain)
        thread->android_tid = (gpointer) gettid ();
 #endif
        thread->apartment_state=ThreadApartmentState_Unknown;
-       thread->thread_pinning_ref = thread;
        thread->managed_id = get_next_managed_thread_id ();
-       MONO_GC_REGISTER_ROOT (thread->thread_pinning_ref);
+       if (mono_gc_is_moving ()) {
+               thread->thread_pinning_ref = thread;
+               MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref);
+       }
 
        thread->stack_ptr = &tid;
 
@@ -918,6 +961,8 @@ mono_thread_detach (MonoThread *thread)
 
        THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->internal_thread->tid));
        
+       mono_profiler_thread_end (thread->internal_thread->tid);
+
        thread_cleanup (thread->internal_thread);
 
        SET_CURRENT_OBJECT (NULL);
@@ -1027,8 +1072,10 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                
                internal->handle=thread;
                internal->tid=tid;
-               internal->thread_pinning_ref = internal;
-               MONO_GC_REGISTER_ROOT (internal->thread_pinning_ref);
+               if (mono_gc_is_moving ()) {
+                       internal->thread_pinning_ref = internal;
+                       MONO_GC_REGISTER_ROOT_PINNING (internal->thread_pinning_ref);
+               }
                
 
                /* Don't call handle_store() here, delay it to Start.
@@ -1206,13 +1253,13 @@ ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj
 }
 
 void 
-ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
+mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean managed)
 {
        ensure_synch_cs_set (this_obj);
        
        EnterCriticalSection (this_obj->synch_cs);
-       
-       if (this_obj->name) {
+
+       if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
                LeaveCriticalSection (this_obj->synch_cs);
                
                mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
@@ -1225,6 +1272,9 @@ ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj
        }
        else
                this_obj->name = NULL;
+
+       if (managed)
+               this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
        
        LeaveCriticalSection (this_obj->synch_cs);
        if (this_obj->name) {
@@ -1234,6 +1284,12 @@ ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj
        }
 }
 
+void 
+ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
+{
+       mono_thread_set_name_internal (this_obj, name, TRUE);
+}
+
 /* If the array is already in the requested domain, we just return it,
    otherwise we return a copy in that domain. */
 static MonoArray*
@@ -1332,6 +1388,44 @@ gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *thi
        return(FALSE);
 }
 
+static gint32
+mono_wait_uninterrupted (MonoInternalThread *thread, gboolean multiple, guint32 numhandles, gpointer *handles, gboolean waitall, gint32 ms, gboolean alertable)
+{
+       MonoException *exc;
+       guint32 ret;
+       gint64 start;
+       gint32 diff_ms;
+       gint32 wait = ms;
+
+       start = (ms == -1) ? 0 : mono_100ns_ticks ();
+       do {
+               if (multiple)
+                       ret = WaitForMultipleObjectsEx (numhandles, handles, waitall, wait, alertable);
+               else
+                       ret = WaitForSingleObjectEx (handles [0], ms, alertable);
+
+               if (ret != WAIT_IO_COMPLETION)
+                       break;
+
+               exc = mono_thread_execute_interruption (thread);
+               if (exc)
+                       mono_raise_exception (exc);
+
+               if (ms == -1)
+                       continue;
+
+               /* Re-calculate ms according to the time passed */
+               diff_ms = (mono_100ns_ticks () - start) / 10000;
+               if (diff_ms >= ms) {
+                       ret = WAIT_TIMEOUT;
+                       break;
+               }
+               wait = ms - diff_ms;
+       } while (TRUE);
+       
+       return ret;
+}
+
 /* FIXME: exitContext isnt documented */
 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
 {
@@ -1359,7 +1453,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
        
-       ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
+       ret = mono_wait_uninterrupted (thread, TRUE, numhandles, handles, TRUE, ms, TRUE);
 
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
 
@@ -1368,12 +1462,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_
        if(ret==WAIT_FAILED) {
                THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
                return(FALSE);
-       } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
-               /* Do we want to try again if we get
-                * WAIT_IO_COMPLETION? The documentation for
-                * WaitHandle doesn't give any clues.  (We'd have to
-                * fiddle with the timeout if we retry.)
-                */
+       } else if(ret==WAIT_TIMEOUT) {
                THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
                return(FALSE);
        }
@@ -1390,7 +1479,6 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
        guint32 i;
        MonoObject *waitHandle;
        MonoInternalThread *thread = mono_thread_internal_current ();
-       guint32 start;
 
        /* Do this WaitSleepJoin check before creating objects */
        mono_thread_current_check_pending_interrupt ();
@@ -1410,20 +1498,7 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
 
-       start = (ms == -1) ? 0 : mono_msec_ticks ();
-       do {
-               ret = WaitForMultipleObjectsEx (numhandles, handles, FALSE, ms, TRUE);
-               if (ret != WAIT_IO_COMPLETION)
-                       break;
-               if (ms != -1) {
-                       guint32 diff;
-
-                       diff = mono_msec_ticks () - start;
-                       ms -= diff;
-                       if (ms <= 0)
-                               break;
-               }
-       } while (ms == -1 || ms > 0);
+       ret = mono_wait_uninterrupted (thread, TRUE, numhandles, handles, FALSE, ms, TRUE);
 
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
 
@@ -1459,19 +1534,14 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
        
-       ret=WaitForSingleObjectEx (handle, ms, TRUE);
+       ret = mono_wait_uninterrupted (thread, FALSE, 1, &handle, FALSE, ms, TRUE);
        
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
        
        if(ret==WAIT_FAILED) {
                THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
                return(FALSE);
-       } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
-               /* Do we want to try again if we get
-                * WAIT_IO_COMPLETION? The documentation for
-                * WaitHandle doesn't give any clues.  (We'd have to
-                * fiddle with the timeout if we retry.)
-                */
+       } else if(ret==WAIT_TIMEOUT) {
                THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
                return(FALSE);
        }
@@ -2027,13 +2097,14 @@ mono_thread_get_abort_signal (void)
 {
 #ifdef HOST_WIN32
        return -1;
-#else
-#ifndef        SIGRTMIN
+#elif defined(PLATFORM_ANDROID)
+       return SIGUNUSED;
+#elif !defined (SIGRTMIN)
 #ifdef SIGUSR1
        return SIGUSR1;
 #else
        return -1;
-#endif
+#endif /* SIGUSR1 */
 #else
        static int abort_signum = -1;
        int i;
@@ -2050,7 +2121,6 @@ mono_thread_get_abort_signal (void)
        }
        /* fallback to the old way */
        return SIGRTMIN;
-#endif
 #endif /* HOST_WIN32 */
 }
 
@@ -2397,6 +2467,12 @@ ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
        return *((volatile float *) (ptr));
 }
 
+MonoObject*
+ves_icall_System_Threading_Volatile_Read_T (void *ptr)
+{
+       return (MonoObject*)*((volatile MonoObject**)ptr);
+}
+
 void
 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
 {
@@ -2445,6 +2521,13 @@ ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
        *((volatile float *) ptr) = value;
 }
 
+void
+ves_icall_System_Threading_Volatile_Write_T (void *ptr, MonoObject *value)
+{
+       *((volatile MonoObject **) ptr) = value;
+       mono_gc_wbarrier_generic_nostore (ptr);
+}
+
 void mono_thread_init (MonoThreadStartCB start_cb,
                       MonoThreadAttachCB attach_cb)
 {
@@ -2824,6 +2907,10 @@ void mono_thread_manage (void)
                THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
        } while(wait->num>0);
 
+#ifndef MONO_CROSS_COMPILE
+       mono_runtime_shutdown ();
+#endif
+
        mono_threads_set_shutting_down ();
 
        /* No new threads will be created after this point */
@@ -3500,7 +3587,6 @@ static const int static_data_size [NUM_STATIC_DATA_IDX] = {
 
 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
 
-#ifdef HAVE_SGEN_GC
 static void
 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
 {
@@ -3526,7 +3612,6 @@ mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
                }
        }
 }
-#endif
 
 /*
  *  mono_alloc_static_data
@@ -3542,10 +3627,8 @@ mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean thr
        gpointer* static_data = *static_data_ptr;
        if (!static_data) {
                static void* tls_desc = NULL;
-#ifdef HAVE_SGEN_GC
-               if (!tls_desc)
+               if (mono_gc_user_markers_supported () && !tls_desc)
                        tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
-#endif
                static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
                *static_data_ptr = static_data;
                static_data [0] = static_data;
@@ -3554,11 +3637,10 @@ mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean thr
        for (i = 1; i <= idx; ++i) {
                if (static_data [i])
                        continue;
-#ifdef HAVE_SGEN_GC
-               static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
-#else
-               static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
-#endif
+               if (mono_gc_user_markers_supported () && threadlocal)
+                       static_data [i] = g_malloc0 (static_data_size [i]);
+               else
+                       static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
        }
 }
 
@@ -3569,14 +3651,10 @@ mono_free_static_data (gpointer* static_data, gboolean threadlocal)
        for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
                if (!static_data [i])
                        continue;
-#ifdef HAVE_SGEN_GC
-               if (threadlocal)
+               if (mono_gc_user_markers_supported () && threadlocal)
                        g_free (static_data [i]);
                else
                        mono_gc_free_fixed (static_data [i]);
-#else
-               mono_gc_free_fixed (static_data [i]);
-#endif
        }
        mono_gc_free_fixed (static_data);
 }
@@ -3670,7 +3748,7 @@ search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32
 }
 
 static void
-update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
+update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int numbits)
 {
        int i;
        int idx = (offset >> 24) - 1;
@@ -3681,7 +3759,7 @@ update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
        offset &= 0xffffff;
        offset /= sizeof (gpointer);
        /* offset is now the bitmap offset */
-       for (i = 0; i < max_set; ++i) {
+       for (i = 0; i < numbits; ++i) {
                if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
                        rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
        }
@@ -3711,7 +3789,7 @@ clear_reference_bitmap (guint32 offset, guint32 size)
  */
 
 guint32
-mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
+mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
 {
        guint32 offset;
        if (static_type == SPECIAL_STATIC_THREAD) {
@@ -3725,7 +3803,7 @@ mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align
                } else {
                        offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
                }
-               update_tls_reference_bitmap (offset, bitmap, max_set);
+               update_tls_reference_bitmap (offset, bitmap, numbits);
                /* This can be called during startup */
                if (threads != NULL)
                        mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
@@ -3868,7 +3946,7 @@ mono_thread_alloc_tls (MonoReflectionType *type)
        /* TlsDatum is a struct, so we subtract the object header size offset */
        bitmap = mono_class_compute_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, - (int)(sizeof (MonoObject) / sizeof (gpointer)), &max_set, FALSE);
        size = mono_type_size (type->type, &align);
-       tls_offset = mono_alloc_special_static_data (SPECIAL_STATIC_THREAD, size, align, bitmap, max_set);
+       tls_offset = mono_alloc_special_static_data (SPECIAL_STATIC_THREAD, size, align, (uintptr_t*)bitmap, max_set + 1);
        if (bitmap != default_bitmap)
                g_free (bitmap);
        tlsrec = g_new0 (MonoTlsDataRecord, 1);
@@ -4038,6 +4116,14 @@ static MonoException* mono_thread_execute_interruption (MonoInternalThread *thre
                
                mono_thread_exit ();
                return NULL;
+       } else if (thread->pending_exception) {
+               MonoException *exc;
+
+               exc = thread->pending_exception;
+               thread->pending_exception = NULL;
+
+        LeaveCriticalSection (thread->synch_cs);
+        return exc;
        } else if (thread->thread_interrupt_requested) {
 
                thread->thread_interrupt_requested = FALSE;
@@ -4077,13 +4163,13 @@ mono_thread_request_interruption (gboolean running_managed)
        
        if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
                return NULL;
+       InterlockedIncrement (&thread_interruption_requested);
 
        if (!running_managed || is_running_protected_wrapper ()) {
                /* Can't stop while in unmanaged code. Increase the global interruption
                   request count. When exiting the unmanaged method the count will be
                   checked and the thread will be interrupted. */
                
-               InterlockedIncrement (&thread_interruption_requested);
 
                if (mono_thread_notify_pending_exc_fn && !running_managed)
                        /* The JIT will notify the thread about the interruption */
@@ -4207,12 +4293,8 @@ mono_thread_get_and_clear_pending_exception (void)
 /*
  * mono_set_pending_exception:
  *
- *   Set the pending exception of the current thread to EXC. On platforms which 
- * support it, the exception will be thrown when execution returns to managed code. 
- * On other platforms, this function is equivalent to mono_raise_exception (). 
- * Internal calls which report exceptions using this function instead of 
- * raise_exception () might be called by JITted code using a more efficient calling 
- * convention.
+ *   Set the pending exception of the current thread to EXC.
+ * The exception will be thrown when execution returns to managed code.
  */
 void
 mono_set_pending_exception (MonoException *exc)
@@ -4223,14 +4305,9 @@ mono_set_pending_exception (MonoException *exc)
        if (thread == NULL)
                return;
 
-       if (mono_thread_notify_pending_exc_fn) {
-               MONO_OBJECT_SETREF (thread, pending_exception, exc);
+       MONO_OBJECT_SETREF (thread, pending_exception, exc);
 
-               mono_thread_notify_pending_exc_fn ();
-       } else {
-               /* No way to notify the JIT about the exception, have to throw it now */
-               mono_raise_exception (exc);
-       }
+    mono_thread_request_interruption (FALSE);
 }
 
 /**
@@ -4430,6 +4507,8 @@ static MonoJitInfo*
 mono_thread_info_get_last_managed (MonoThreadInfo *info)
 {
        MonoJitInfo *ji = NULL;
+       if (!info)
+               return NULL;
        mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &ji);
        return ji;
 }
@@ -4477,6 +4556,7 @@ abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception,
                mono_thread_info_resume (mono_thread_info_get_tid (info));
                return;
        }
+       InterlockedIncrement (&thread_interruption_requested);
 
        ji = mono_thread_info_get_last_managed (info);
        protected_wrapper = ji && mono_threads_is_critical_method (ji->method);
@@ -4497,7 +4577,6 @@ abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception,
                 * 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
@@ -4536,10 +4615,20 @@ suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt)
                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));
+               MonoThreadInfo *info;
+               MonoJitInfo *ji;
+               gboolean protected_wrapper;
+               gboolean running_managed;
+
+               /*A null info usually means the thread is already dead. */
+               if (!(info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gsize)thread->tid, interrupt))) {
+                       LeaveCriticalSection (thread->synch_cs);
+                       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 (running_managed && !protected_wrapper) {
                        transition_to_suspended (thread);