[threads] Fix crash on unknown policy (#4264)
[mono.git] / mono / metadata / threads.c
index 51d7ccac064356305041fc2d2e62afb63ccedff6..b5ffc0202314853e9c36d478c6eab0df86575253 100644 (file)
@@ -140,12 +140,12 @@ static StaticDataInfo context_static_info;
 /* The hash of existing threads (key is thread ID, value is
  * MonoInternalThread*) that need joining before exit
  */
-static MonoGHashTable *threads;
+static MonoGHashTable *threads=NULL;
 
 /* List of app context GC handles.
  * Added to from ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext ().
  */
-static GHashTable *contexts;
+static GHashTable *contexts = NULL;
 
 /* Cleanup queue for contexts. */
 static MonoReferenceQueue *context_queue;
@@ -155,39 +155,15 @@ static MonoReferenceQueue *context_queue;
  * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
  * Protected by mono_threads_lock ().
  */
-static MonoGHashTable *threads_starting_up;
-
-/* The TLS key that holds the MonoObject assigned to each thread */
-static MonoNativeTlsKey current_object_key;
+static MonoGHashTable *threads_starting_up = NULL;
 
 /* Contains tids */
 /* Protected by the threads lock */
 static GHashTable *joinable_threads;
 static int joinable_thread_count;
 
-#define thread_wait_lock() mono_os_mutex_lock (&thread_wait_mutex)
-#define thread_wait_unlock() mono_os_mutex_unlock (&thread_wait_mutex)
-static mono_mutex_t thread_wait_mutex;
-/* Used to wait for a thread to be joined or to change state */
-/* Used to wait for njoined_threads to increase or for background_change to become true */
-static mono_cond_t thread_wait_cond;
-static int njoined_threads;
-static gboolean background_changed;
-
-#ifdef MONO_HAVE_FAST_TLS
-/* we need to use both the Tls* functions and __thread because
- * the gc needs to see all the threads 
- */
-MONO_FAST_TLS_DECLARE(tls_current_object);
-#define SET_CURRENT_OBJECT(x) do { \
-       MONO_FAST_TLS_SET (tls_current_object, 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) mono_native_tls_set_value (current_object_key, x)
-#define GET_CURRENT_OBJECT() (MonoInternalThread*) mono_native_tls_get_value (current_object_key)
-#endif
+#define SET_CURRENT_OBJECT(x) mono_tls_set_thread (x)
+#define GET_CURRENT_OBJECT() (MonoInternalThread*) mono_tls_get_thread ()
 
 /* function called at thread start */
 static MonoThreadStartCB mono_thread_start_cb = NULL;
@@ -223,10 +199,8 @@ static mono_mutex_t interlocked_mutex;
 /* global count of thread interruptions requested */
 static gint32 thread_interruption_requested = 0;
 
-#ifdef HOST_WIN32
 /* Event signaled when a thread changes its background mode */
 static MonoOSEvent background_change_event;
-#endif
 
 static gboolean shutting_down = FALSE;
 
@@ -254,26 +228,6 @@ get_next_managed_thread_id (void)
        return InterlockedIncrement (&managed_thread_id_counter);
 }
 
-MonoNativeTlsKey
-mono_thread_get_tls_key (void)
-{
-       return current_object_key;
-}
-
-gint32
-mono_thread_get_tls_offset (void)
-{
-       int offset = -1;
-
-#ifdef HOST_WIN32
-       if (current_object_key)
-               offset = current_object_key;
-#else
-       MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
-#endif
-       return offset;
-}
-
 static inline MonoNativeThreadId
 thread_get_tid (MonoInternalThread *thread)
 {
@@ -329,147 +283,6 @@ is_threadabort_exception (MonoClass *klass)
        return klass == mono_defaults.threadabortexception_class;
 }
 
-/*
- * NOTE: this function can be called also for threads different from the current one:
- * make sure no code called from it will ever assume it is run on the thread that is
- * getting cleaned up.
- */
-static void thread_cleanup (MonoInternalThread *thread)
-{
-       gboolean ret;
-
-       g_assert (thread != NULL);
-
-       if (thread->abort_state_handle) {
-               mono_gchandle_free (thread->abort_state_handle);
-               thread->abort_state_handle = 0;
-       }
-       thread->abort_exc = NULL;
-       thread->current_appcontext = NULL;
-
-       /*
-        * This is necessary because otherwise we might have
-        * cross-domain references which will not get cleaned up when
-        * the target domain is unloaded.
-        */
-       if (thread->cached_culture_info) {
-               int i;
-               for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
-                       mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
-       }
-
-       /*
-        * thread->synch_cs can be NULL if this was called after
-        * ves_icall_System_Threading_InternalThread_Thread_free_internal.
-        * This can happen only during shutdown.
-        * The shutting_down flag is not always set, so we can't assert on it.
-        */
-       if (thread->synch_cs)
-               LOCK_THREAD (thread);
-
-       thread->state |= ThreadState_Stopped;
-       thread->state &= ~ThreadState_Background;
-
-       if (thread->synch_cs)
-               UNLOCK_THREAD (thread);
-
-       /*
-       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);
-
-       mono_threads_lock ();
-
-       if (!threads) {
-               ret = FALSE;
-       } else if (mono_g_hash_table_lookup (threads, (gpointer)thread->tid) != thread) {
-               /* We have to check whether the thread object for the
-                * tid is still the same in the table because the
-                * thread might have been destroyed and the tid reused
-                * in the meantime, in which case the tid would be in
-                * the table, but with another thread object.
-                */
-               ret = FALSE;
-       } else {
-               mono_g_hash_table_remove (threads, (gpointer)thread->tid);
-               ret = TRUE;
-       }
-
-       mono_threads_unlock ();
-
-       /* Don't close the handle here, wait for the object finalizer
-        * to do it. Otherwise, the following race condition applies:
-        *
-        * 1) Thread exits (and thread_cleanup() closes the handle)
-        *
-        * 2) Some other handle is reassigned the same slot
-        *
-        * 3) Another thread tries to join the first thread, and
-        * blocks waiting for the reassigned handle to be signalled
-        * (which might never happen).  This is possible, because the
-        * thread calling Join() still has a reference to the first
-        * thread's object.
-        */
-
-       /* if the thread is not in the hash it has been removed already */
-       if (!ret) {
-               if (thread == mono_thread_internal_current ()) {
-                       mono_domain_unset ();
-                       mono_memory_barrier ();
-               }
-               if (mono_thread_cleanup_fn)
-                       mono_thread_cleanup_fn (thread_get_tid (thread));
-               return;
-       }
-       mono_release_type_locks (thread);
-
-       /* Can happen when we attach the profiler helper thread in order to heapshot. */
-       if (!mono_thread_info_lookup (MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid))->tools_thread)
-               mono_profiler_thread_end (thread->tid);
-
-       mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
-
-       if (thread == mono_thread_internal_current ()) {
-               /*
-                * This will signal async signal handlers that the thread has exited.
-                * The profiler callback needs this to be set, so it cannot be done earlier.
-                */
-               mono_domain_unset ();
-               mono_memory_barrier ();
-       }
-
-       if (thread == mono_thread_internal_current ())
-               mono_thread_pop_appdomain_ref ();
-
-       thread->cached_culture_info = NULL;
-
-       mono_free_static_data (thread->static_data);
-       thread->static_data = NULL;
-       ref_stack_destroy (thread->appdomain_refs);
-       thread->appdomain_refs = NULL;
-
-       if (mono_thread_cleanup_fn)
-               mono_thread_cleanup_fn (thread_get_tid (thread));
-
-       if (mono_gc_is_moving ()) {
-               MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
-               thread->thread_pinning_ref = NULL;
-       }
-
-       g_assert (thread->suspended);
-       mono_os_event_destroy (thread->suspended);
-       g_free (thread->suspended);
-       thread->suspended = NULL;
-}
-
 /*
  * A special static data offset (guint32) consists of 3 parts:
  *
@@ -663,7 +476,8 @@ mono_thread_internal_set_priority (MonoInternalThread *internal, MonoThreadPrior
                        param.sched_priority = 0;
                        break;
                default:
-                       g_error ("%s: unknown policy %d", __func__, policy);
+                       g_warning ("%s: unknown policy %d", __func__, policy);
+                       return;
                }
        }
 
@@ -887,14 +701,15 @@ static guint32 WINAPI start_wrapper_internal(StartInfo *start_info, gsize *stack
 
        /* If the thread calls ExitThread at all, this remaining code
         * will not be executed, but the main thread will eventually
-        * call thread_cleanup() on this thread's behalf.
+        * call mono_thread_detach_internal() on this thread's behalf.
         */
 
        THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
 
        /* Do any cleanup needed for apartment state. This
-        * cannot be done in thread_cleanup since thread_cleanup could be 
-        * called for a thread other than the current thread.
+        * cannot be done in mono_thread_detach_internal since
+        * mono_thread_detach_internal could be  called for a
+        * thread other than the current thread.
         * mono_thread_cleanup_apartment_state cleans up apartment
         * for the current thead */
        mono_thread_cleanup_apartment_state ();
@@ -1138,7 +953,9 @@ mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
 void
 mono_thread_detach_internal (MonoInternalThread *thread)
 {
-       g_return_if_fail (thread != NULL);
+       gboolean removed;
+
+       g_assert (thread != NULL);
 
        THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
 
@@ -1146,8 +963,138 @@ mono_thread_detach_internal (MonoInternalThread *thread)
        mono_w32mutex_abandon ();
 #endif
 
-       thread_cleanup (thread);
+       if (thread->abort_state_handle) {
+               mono_gchandle_free (thread->abort_state_handle);
+               thread->abort_state_handle = 0;
+       }
+
+       thread->abort_exc = NULL;
+       thread->current_appcontext = NULL;
+
+       /*
+        * This is necessary because otherwise we might have
+        * cross-domain references which will not get cleaned up when
+        * the target domain is unloaded.
+        */
+       if (thread->cached_culture_info) {
+               int i;
+               for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
+                       mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
+       }
+
+       /*
+        * thread->synch_cs can be NULL if this was called after
+        * ves_icall_System_Threading_InternalThread_Thread_free_internal.
+        * This can happen only during shutdown.
+        * The shutting_down flag is not always set, so we can't assert on it.
+        */
+       if (thread->synch_cs)
+               LOCK_THREAD (thread);
+
+       thread->state |= ThreadState_Stopped;
+       thread->state &= ~ThreadState_Background;
+
+       if (thread->synch_cs)
+               UNLOCK_THREAD (thread);
+
+       /*
+       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) != 0)
+               InterlockedDecrement (&thread_interruption_requested);
+
+       mono_threads_lock ();
+
+       if (!threads) {
+               removed = FALSE;
+       } else if (mono_g_hash_table_lookup (threads, (gpointer)thread->tid) != thread) {
+               /* We have to check whether the thread object for the
+                * tid is still the same in the table because the
+                * thread might have been destroyed and the tid reused
+                * in the meantime, in which case the tid would be in
+                * the table, but with another thread object.
+                */
+               removed = FALSE;
+       } else {
+               mono_g_hash_table_remove (threads, (gpointer)thread->tid);
+               removed = TRUE;
+       }
+
+       mono_threads_unlock ();
+
+       /* Don't close the handle here, wait for the object finalizer
+        * to do it. Otherwise, the following race condition applies:
+        *
+        * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
+        *
+        * 2) Some other handle is reassigned the same slot
+        *
+        * 3) Another thread tries to join the first thread, and
+        * blocks waiting for the reassigned handle to be signalled
+        * (which might never happen).  This is possible, because the
+        * thread calling Join() still has a reference to the first
+        * thread's object.
+        */
+
+       /* if the thread is not in the hash it has been removed already */
+       if (!removed) {
+               mono_domain_unset ();
+               mono_memory_barrier ();
+
+               if (mono_thread_cleanup_fn)
+                       mono_thread_cleanup_fn (thread_get_tid (thread));
 
+               goto done;
+       }
+
+       mono_release_type_locks (thread);
+
+       /* Can happen when we attach the profiler helper thread in order to heapshot. */
+       if (!mono_thread_info_lookup (MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid))->tools_thread)
+               mono_profiler_thread_end (thread->tid);
+
+       mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
+
+       /*
+        * This will signal async signal handlers that the thread has exited.
+        * The profiler callback needs this to be set, so it cannot be done earlier.
+        */
+       mono_domain_unset ();
+       mono_memory_barrier ();
+
+       if (thread == mono_thread_internal_current ())
+               mono_thread_pop_appdomain_ref ();
+
+       thread->cached_culture_info = NULL;
+
+       mono_free_static_data (thread->static_data);
+       thread->static_data = NULL;
+       ref_stack_destroy (thread->appdomain_refs);
+       thread->appdomain_refs = NULL;
+
+       g_assert (thread->suspended);
+       mono_os_event_destroy (thread->suspended);
+       g_free (thread->suspended);
+       thread->suspended = NULL;
+
+       if (mono_thread_cleanup_fn)
+               mono_thread_cleanup_fn (thread_get_tid (thread));
+
+       mono_memory_barrier ();
+
+       if (mono_gc_is_moving ()) {
+               MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
+               thread->thread_pinning_ref = NULL;
+       }
+
+done:
        SET_CURRENT_OBJECT (NULL);
        mono_domain_unset ();
 
@@ -1227,6 +1174,12 @@ ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this_obj)
        InterlockedCompareExchangePointer ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
 }
 
+MonoThread *
+ves_icall_System_Threading_Thread_GetCurrentThread (void)
+{
+       return mono_thread_current ();
+}
+
 HANDLE
 ves_icall_System_Threading_Thread_Thread_internal (MonoThread *this_obj,
                                                                                                   MonoObject *start)
@@ -1278,9 +1231,10 @@ ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThre
        THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, this_obj->handle));
 
        /*
-        * Since threads keep a reference to their thread object while running, by the time this function is called,
-        * the thread has already exited/detached, i.e. thread_cleanup () has ran. The exception is during shutdown,
-        * when thread_cleanup () can be called after this.
+        * Since threads keep a reference to their thread object while running, by
+        * the time this function is called, the thread has already exited/detached,
+        * i.e. mono_thread_detach_internal () has ran. The exception is during
+        * shutdown, when mono_thread_detach_internal () can be called after this.
         */
        if (this_obj->handle) {
                mono_threads_close_thread_handle (this_obj->handle);
@@ -1330,8 +1284,8 @@ ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
                        if (exc) {
                                mono_raise_exception (exc);
                        } else {
-                               // FIXME: !INFINITE
-                               if (ms != INFINITE)
+                               // FIXME: !MONO_INFINITE_WAIT
+                               if (ms != MONO_INFINITE_WAIT)
                                        break;
                        }
                } else {
@@ -1620,6 +1574,47 @@ mono_thread_internal_current (void)
        return res;
 }
 
+static MonoThreadInfoWaitRet
+mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
+{
+       MonoException *exc;
+       MonoThreadInfoWaitRet ret;
+       gint64 start;
+       gint32 diff_ms;
+       gint32 wait = ms;
+
+       mono_error_init (error);
+
+       start = (ms == -1) ? 0 : mono_msec_ticks ();
+       for (;;) {
+               MONO_ENTER_GC_SAFE;
+               ret = mono_thread_info_wait_one_handle (thread_to_join, ms, TRUE);
+               MONO_EXIT_GC_SAFE;
+
+               if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
+                       return ret;
+
+               exc = mono_thread_execute_interruption ();
+               if (exc) {
+                       mono_error_set_exception_instance (error, exc);
+                       return ret;
+               }
+
+               if (ms == -1)
+                       continue;
+
+               /* Re-calculate ms according to the time passed */
+               diff_ms = (gint32)(mono_msec_ticks () - start);
+               if (diff_ms >= ms) {
+                       ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
+                       return ret;
+               }
+               wait = ms - diff_ms;
+       }
+
+       return ret;
+}
+
 gboolean
 ves_icall_System_Threading_Thread_Join_internal(MonoThread *this_obj, int ms)
 {
@@ -1627,6 +1622,7 @@ ves_icall_System_Threading_Thread_Join_internal(MonoThread *this_obj, int ms)
        MonoThreadHandle *handle = thread->handle;
        MonoInternalThread *cur_thread = mono_thread_internal_current ();
        gboolean ret;
+       MonoError error;
 
        if (mono_thread_current_check_pending_interrupt ())
                return FALSE;
@@ -1643,18 +1639,18 @@ ves_icall_System_Threading_Thread_Join_internal(MonoThread *this_obj, int ms)
        UNLOCK_THREAD (thread);
 
        if(ms== -1) {
-               ms=INFINITE;
+               ms=MONO_INFINITE_WAIT;
        }
        THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
        
        mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
 
-       MONO_ENTER_GC_SAFE;
-       ret=mono_thread_info_wait_one_handle (handle, ms, TRUE);
-       MONO_EXIT_GC_SAFE;
+       ret=mono_join_uninterrupted (handle, ms, &error);
 
        mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
-       
+
+       mono_error_set_pending_exception (&error);
+
        if(ret==MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
                THREAD_DEBUG (g_message ("%s: join successful", __func__));
 
@@ -1669,17 +1665,29 @@ ves_icall_System_Threading_Thread_Join_internal(MonoThread *this_obj, int ms)
 #define MANAGED_WAIT_FAILED 0x7fffffff
 
 static gint32
-map_native_wait_result_to_managed (gint32 val)
-{
-       /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
-       return val == WAIT_FAILED ? MANAGED_WAIT_FAILED : val;
+map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
+{
+       if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
+               return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
+       } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
+               return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
+       } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
+               return WAIT_IO_COMPLETION;
+       } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
+               return WAIT_TIMEOUT;
+       } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
+               /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
+               return MANAGED_WAIT_FAILED;
+       } else {
+               g_error ("%s: unknown val value %d", __func__, val);
+       }
 }
 
-static gint32
+static MonoW32HandleWaitRet
 mono_wait_uninterrupted (MonoInternalThread *thread, guint32 numhandles, gpointer *handles, gboolean waitall, gint32 ms, MonoError *error)
 {
        MonoException *exc;
-       guint32 ret;
+       MonoW32HandleWaitRet ret;
        gint64 start;
        gint32 diff_ms;
        gint32 wait = ms;
@@ -1689,13 +1697,18 @@ mono_wait_uninterrupted (MonoInternalThread *thread, guint32 numhandles, gpointe
        start = (ms == -1) ? 0 : mono_100ns_ticks ();
        do {
                MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
                if (numhandles != 1)
-                       ret = WaitForMultipleObjectsEx (numhandles, handles, waitall, wait, TRUE);
+                       ret = mono_w32handle_convert_wait_ret (WaitForMultipleObjectsEx (numhandles, handles, waitall, wait, TRUE), numhandles);
                else
-                       ret = WaitForSingleObjectEx (handles [0], ms, TRUE);
+                       ret = mono_w32handle_convert_wait_ret (WaitForSingleObjectEx (handles [0], ms, TRUE), 1);
+#else
+               /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
+               ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, wait, TRUE);
+#endif /* HOST_WIN32 */
                MONO_EXIT_GC_SAFE;
 
-               if (ret != WAIT_IO_COMPLETION)
+               if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
                        break;
 
                exc = mono_thread_execute_interruption ();
@@ -1710,7 +1723,7 @@ mono_wait_uninterrupted (MonoInternalThread *thread, guint32 numhandles, gpointe
                /* Re-calculate ms according to the time passed */
                diff_ms = (gint32)((mono_100ns_ticks () - start) / 10000);
                if (diff_ms >= ms) {
-                       ret = WAIT_TIMEOUT;
+                       ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
                        break;
                }
                wait = ms - diff_ms;
@@ -1724,14 +1737,14 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_ha
        MonoError error;
        HANDLE *handles;
        guint32 numhandles;
-       guint32 ret;
+       MonoW32HandleWaitRet ret;
        guint32 i;
        MonoObject *waitHandle;
        MonoInternalThread *thread = mono_thread_internal_current ();
 
        /* Do this WaitSleepJoin check before creating objects */
        if (mono_thread_current_check_pending_interrupt ())
-               return map_native_wait_result_to_managed (WAIT_FAILED);
+               return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
 
        /* We fail in managed if the array has more than 64 elements */
        numhandles = (guint32)mono_array_length(mono_handles);
@@ -1743,7 +1756,7 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_ha
        }
        
        if(ms== -1) {
-               ms=INFINITE;
+               ms=MONO_INFINITE_WAIT;
        }
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
@@ -1756,8 +1769,7 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_ha
 
        mono_error_set_pending_exception (&error);
 
-       /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
-       return map_native_wait_result_to_managed (ret);
+       return map_native_wait_result_to_managed (ret, numhandles);
 }
 
 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms)
@@ -1765,18 +1777,18 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
        MonoError error;
        HANDLE handles [MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
        uintptr_t numhandles;
-       guint32 ret;
+       MonoW32HandleWaitRet ret;
        guint32 i;
        MonoObject *waitHandle;
        MonoInternalThread *thread = mono_thread_internal_current ();
 
        /* Do this WaitSleepJoin check before creating objects */
        if (mono_thread_current_check_pending_interrupt ())
-               return map_native_wait_result_to_managed (WAIT_FAILED);
+               return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
 
        numhandles = mono_array_length(mono_handles);
        if (numhandles > MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
-               return map_native_wait_result_to_managed (WAIT_FAILED);
+               return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
 
        for(i = 0; i < numhandles; i++) {       
                waitHandle = mono_array_get(mono_handles, MonoObject*, i);
@@ -1784,7 +1796,7 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
        }
        
        if(ms== -1) {
-               ms=INFINITE;
+               ms=MONO_INFINITE_WAIT;
        }
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
@@ -1797,24 +1809,23 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
 
        mono_error_set_pending_exception (&error);
 
-       /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
-       return map_native_wait_result_to_managed (ret);
+       return map_native_wait_result_to_managed (ret, numhandles);
 }
 
 gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms)
 {
        MonoError error;
-       guint32 ret;
+       MonoW32HandleWaitRet ret;
        MonoInternalThread *thread = mono_thread_internal_current ();
 
        THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, mono_native_thread_id_get (), handle, ms));
        
        if(ms== -1) {
-               ms=INFINITE;
+               ms=MONO_INFINITE_WAIT;
        }
        
        if (mono_thread_current_check_pending_interrupt ())
-               return map_native_wait_result_to_managed (WAIT_FAILED);
+               return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
        
@@ -1823,30 +1834,34 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gin
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
 
        mono_error_set_pending_exception (&error);
-       return map_native_wait_result_to_managed (ret);
+       return map_native_wait_result_to_managed (ret, 1);
 }
 
 gint32
 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms)
 {
-       guint32 ret;
+       MonoW32HandleWaitRet ret;
        MonoInternalThread *thread = mono_thread_internal_current ();
 
        if (ms == -1)
-               ms = INFINITE;
+               ms = MONO_INFINITE_WAIT;
 
        if (mono_thread_current_check_pending_interrupt ())
-               return map_native_wait_result_to_managed (WAIT_FAILED);
+               return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
 
        mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
        
        MONO_ENTER_GC_SAFE;
-       ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
+#ifdef HOST_WIN32
+       ret = mono_w32handle_convert_wait_ret (SignalObjectAndWait (toSignal, toWait, ms, TRUE), 1);
+#else
+       ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
+#endif
        MONO_EXIT_GC_SAFE;
        
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
 
-       return map_native_wait_result_to_managed (ret);
+       return map_native_wait_result_to_managed (ret, 1);
 }
 
 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
@@ -2083,18 +2098,6 @@ ves_icall_System_Threading_Thread_MemoryBarrier (void)
        mono_memory_barrier ();
 }
 
-static void
-signal_background_change (void)
-{
-       thread_wait_lock ();
-       background_changed = TRUE;
-       mono_os_cond_signal (&thread_wait_cond);
-       thread_wait_unlock ();
-#ifdef HOST_WIN32
-       mono_os_event_set (&background_change_event);
-#endif
-}
-
 void
 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this_obj, guint32 state)
 {
@@ -2105,7 +2108,7 @@ ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this_obj, guint3
                 * be notified, since it has to rebuild the list of threads to
                 * wait for.
                 */
-               signal_background_change ();
+               mono_os_event_set (&background_change_event);
        }
 }
 
@@ -2119,7 +2122,7 @@ ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this_obj, guint3
                 * be notified, since it has to rebuild the list of threads to
                 * wait for.
                 */
-               signal_background_change ();
+               mono_os_event_set (&background_change_event);
        }
 }
 
@@ -2273,6 +2276,8 @@ ves_icall_System_Threading_Thread_ResetAbort (MonoThread *this_obj)
                mono_set_pending_exception (mono_get_exception_thread_state (msg));
                return;
        }
+
+       mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
        thread->abort_exc = NULL;
        if (thread->abort_state_handle) {
                mono_gchandle_free (thread->abort_state_handle);
@@ -2290,6 +2295,7 @@ mono_thread_internal_reset_abort (MonoInternalThread *thread)
        thread->state &= ~ThreadState_AbortRequested;
 
        if (thread->abort_exc) {
+               mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
                thread->abort_exc = NULL;
                if (thread->abort_state_handle) {
                        mono_gchandle_free (thread->abort_state_handle);
@@ -2865,13 +2871,6 @@ ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContex
        mono_profiler_context_unloaded (ctx);
 }
 
-void
-mono_thread_init_tls (void)
-{
-       MONO_FAST_TLS_INIT (tls_current_object);
-       mono_native_tls_alloc (&current_object_key, NULL);
-}
-
 void mono_thread_init (MonoThreadStartCB start_cb,
                       MonoThreadAttachCB attach_cb)
 {
@@ -2879,19 +2878,12 @@ void mono_thread_init (MonoThreadStartCB start_cb,
 
        mono_os_mutex_init_recursive(&interlocked_mutex);
        mono_os_mutex_init_recursive(&joinable_threads_mutex);
-
-       mono_os_mutex_init_recursive(&thread_wait_mutex);
-       mono_os_cond_init(&thread_wait_cond);
        
-#ifdef HOST_WIN32
        mono_os_event_init (&background_change_event, FALSE);
-#endif
        
        mono_init_static_data_info (&thread_static_info);
        mono_init_static_data_info (&context_static_info);
 
-       THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
-
        mono_thread_start_cb = start_cb;
        mono_thread_attach_cb = attach_cb;
 }
@@ -2917,12 +2909,8 @@ void mono_thread_cleanup (void)
        mono_os_mutex_destroy (&interlocked_mutex);
        mono_os_mutex_destroy (&delayed_free_table_mutex);
        mono_os_mutex_destroy (&small_id_mutex);
-#ifdef HOST_WIN32
        mono_os_event_destroy (&background_change_event);
 #endif
-#endif
-
-       mono_native_tls_free (current_object_key);
 }
 
 void
@@ -2949,56 +2937,19 @@ static void print_tids (gpointer key, gpointer value, gpointer user)
        g_message ("Waiting for: %p", key);
 }
 
-typedef struct {
-       int njoined;
+struct wait_data 
+{
        MonoThreadHandle *handles[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
        MonoInternalThread *threads[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
        guint32 num;
-} WaitData;
+};
 
-/*
- * wait_for_tids:
- *
- * Wait until either:
- * - wait->num threads are joined
- * - @check_state_change is TRUE and a thread changes background state
- * - timeout elapses
- */
 static void
-wait_for_tids (WaitData *wait, guint32 timeout, gboolean check_state_change)
+wait_for_tids (struct wait_data *wait, guint32 timeout, gboolean check_state_change)
 {
-#ifndef HOST_WIN32
-       /*
-        * Its is complicated to wait for a given set of threads, so we wait for a given
-        * number of threads instead, the caller needs to call us until the set of threads
-        * it is waiting for are terminated.
-        */
-       gboolean finished = FALSE;
-       gint64 start = mono_msec_ticks ();
-       while (!finished) {
-               thread_wait_lock ();
-               if (njoined_threads >= wait->njoined + wait->num || (check_state_change && background_changed)) {
-                       finished = TRUE;
-               } else {
-                       int res = mono_os_cond_timedwait (&thread_wait_cond, &thread_wait_mutex, timeout);
-                       if (res)
-                               finished = TRUE;
-                       if (timeout != INFINITE) {
-                               gint64 now = mono_msec_ticks ();
-                               if (now - start >= timeout) {
-                                       finished = TRUE;
-                               } else {
-                                       timeout -= now - start;
-                                       start = now;
-                               }
-                       }
-               }
-               thread_wait_unlock ();
-       }
-#else
        guint32 i;
        MonoThreadInfoWaitRet ret;
-
+       
        THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
 
        /* Add the thread state change event, so it wakes
@@ -3033,102 +2984,87 @@ wait_for_tids (WaitData *wait, guint32 timeout, gboolean check_state_change)
                        g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
                mono_threads_unlock ();
        }
-#endif
-}
-
-static void
-init_wait_data (WaitData *wait)
-{
-       /* This is used calculate the number of joined threads in wait_for_tids () */
-       thread_wait_lock ();
-       wait->njoined = njoined_threads;
-       thread_wait_unlock ();
-       wait->num = 0;
-       /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
-       memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
-}
-
-static void
-add_wait_thread (WaitData *wait, MonoInternalThread *thread)
-{
-#ifdef HOST_WIN32
-       /* These are not used by the wait_for_tids () code on unix */
-       wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
-#endif
-       wait->threads [wait->num] = thread;
-       wait->num++;
 }
 
-static void
-build_wait_tids (gpointer key, gpointer value, gpointer user)
+static void build_wait_tids (gpointer key, gpointer value, gpointer user)
 {
-       WaitData *wait = (WaitData *)user;
-       MonoInternalThread *thread = (MonoInternalThread *)value;
+       struct wait_data *wait=(struct wait_data *)user;
 
-       if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
-               /* Just ignore the rest, we can't do anything with
-                * them yet
-                */
-               return;
-       }
+       if(wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
+               MonoInternalThread *thread=(MonoInternalThread *)value;
 
-       /* Ignore background threads, we abort them later */
-       /* Do not lock here since it is not needed and the caller holds threads_lock */
-       if (thread->state & ThreadState_Background) {
-               THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
-               return; /* just leave, ignore */
-       }
+               /* Ignore background threads, we abort them later */
+               /* Do not lock here since it is not needed and the caller holds threads_lock */
+               if (thread->state & ThreadState_Background) {
+                       THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+                       return; /* just leave, ignore */
+               }
                
-       if (mono_gc_is_finalizer_internal_thread (thread)) {
-               THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
-               return;
-       }
+               if (mono_gc_is_finalizer_internal_thread (thread)) {
+                       THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+                       return;
+               }
 
-       if (thread == mono_thread_internal_current ()) {
-               THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
-               return;
-       }
+               if (thread == mono_thread_internal_current ()) {
+                       THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+                       return;
+               }
 
-       if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
-               THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
-               return;
-       }
+               if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
+                       THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+                       return;
+               }
 
-       if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
-               THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
-               return;
-       }
+               if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
+                       THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
+                       return;
+               }
 
-       THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
-       if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
-               add_wait_thread (wait, thread);
+               THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
+               if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
+                       wait->handles[wait->num]=mono_threads_open_thread_handle (thread->handle);
+                       wait->threads[wait->num]=thread;
+                       wait->num++;
 
-               THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+                       THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+               } else {
+                       THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+               }
+               
+               
        } else {
-               THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
+               /* Just ignore the rest, we can't do anything with
+                * them yet
+                */
        }
 }
 
-static void
-collect_and_abort_threads (gpointer key, gpointer value, gpointer user)
+static gboolean
+remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
 {
-       WaitData *wait = (WaitData *)user;
+       struct wait_data *wait=(struct wait_data *)user;
        MonoNativeThreadId self = mono_native_thread_id_get ();
        MonoInternalThread *thread = (MonoInternalThread *)value;
 
        if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
-               return;
+               return FALSE;
 
        /* The finalizer thread is not a background thread */
        if (!mono_native_thread_id_equals (thread_get_tid (thread), self)
             && (thread->state & ThreadState_Background) != 0
-               && (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) == 0) {
-               add_wait_thread (wait, thread);
+            && (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) == 0
+       ) {
+               wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
+               wait->threads[wait->num] = thread;
+               wait->num++;
 
                THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
                mono_thread_internal_abort (thread);
-               return;
+               return TRUE;
        }
+
+       return !mono_native_thread_id_equals (thread_get_tid (thread), self)
+               && !mono_gc_is_finalizer_internal_thread (thread);
 }
 
 /** 
@@ -3174,19 +3110,18 @@ mono_threads_set_shutting_down (void)
                 * interrupt the main thread if it is waiting for all
                 * the other threads.
                 */
-               signal_background_change ();
+               mono_os_event_set (&background_change_event);
                
                mono_threads_unlock ();
        }
 }
 
-void
-mono_thread_manage (void)
+void mono_thread_manage (void)
 {
-       WaitData wait_data;
-       WaitData *wait = &wait_data;
+       struct wait_data wait_data;
+       struct wait_data *wait = &wait_data;
 
-       memset (wait, 0, sizeof (WaitData));
+       memset (wait, 0, sizeof (struct wait_data));
        /* join each thread that's still running */
        THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
        
@@ -3208,18 +3143,17 @@ mono_thread_manage (void)
                THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
                        mono_g_hash_table_foreach (threads, print_tids, NULL));
        
-#ifdef HOST_WIN32
                mono_os_event_reset (&background_change_event);
-#endif
-               background_changed = FALSE;
-               init_wait_data (wait);
+               wait->num=0;
+               /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
+               memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
                mono_g_hash_table_foreach (threads, build_wait_tids, wait);
                mono_threads_unlock ();
                if (wait->num > 0)
                        /* Something to wait for */
-                       wait_for_tids (wait, INFINITE, TRUE);
+                       wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
                THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
-       } while (wait->num > 0);
+       } while(wait->num>0);
 
        /* Mono is shutting down, so just wait for the end */
        if (!mono_runtime_try_shutdown ()) {
@@ -3235,15 +3169,17 @@ mono_thread_manage (void)
        do {
                mono_threads_lock ();
 
-               init_wait_data (wait);
-               mono_g_hash_table_foreach (threads, collect_and_abort_threads, wait);
+               wait->num = 0;
+               /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
+               memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
+               mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
 
                mono_threads_unlock ();
 
                THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
                if (wait->num > 0) {
                        /* Something to wait for */
-                       wait_for_tids (wait, INFINITE, FALSE);
+                       wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
                }
        } while (wait->num > 0);
        
@@ -3259,7 +3195,7 @@ static void
 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
 {
        MonoInternalThread *thread = (MonoInternalThread*)value;
-       WaitData *wait = (WaitData*)user_data;
+       struct wait_data *wait = (struct wait_data*)user_data;
 
        /* 
         * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
@@ -3270,9 +3206,9 @@ collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
                (thread->state & ThreadState_Stopped) != 0)
                return;
 
-       if (wait->num < MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
-               wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
-               wait->threads[wait->num] = thread;
+       if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
+               wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
+               wait->threads [wait->num] = thread;
                wait->num++;
        }
 }
@@ -3283,17 +3219,16 @@ collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
  *  Suspend all managed threads except the finalizer thread and this thread. It is
  * not possible to resume them later.
  */
-void
-mono_thread_suspend_all_other_threads (void)
+void mono_thread_suspend_all_other_threads (void)
 {
-       WaitData wait_data;
-       WaitData *wait = &wait_data;
+       struct wait_data wait_data;
+       struct wait_data *wait = &wait_data;
        int i;
        MonoNativeThreadId self = mono_native_thread_id_get ();
        guint32 eventidx = 0;
        gboolean starting, finished;
 
-       memset (wait, 0, sizeof (WaitData));
+       memset (wait, 0, sizeof (struct wait_data));
        /*
         * The other threads could be in an arbitrary state at this point, i.e.
         * they could be starting up, shutting down etc. This means that there could be
@@ -3319,7 +3254,9 @@ mono_thread_suspend_all_other_threads (void)
                 * Make a copy of the hashtable since we can't do anything with
                 * threads while threads_mutex is held.
                 */
-               init_wait_data (wait);
+               wait->num = 0;
+               /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
+               memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
                mono_threads_lock ();
                mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
                mono_threads_unlock ();
@@ -3783,7 +3720,7 @@ mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
 }
 
 typedef struct abort_appdomain_data {
-       WaitData wait;
+       struct wait_data wait;
        MonoDomain *domain;
 } abort_appdomain_data;
 
@@ -3797,8 +3734,10 @@ collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
        if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
                /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
 
-               if (data->wait.num < MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
-                       add_wait_thread (&data->wait, thread);
+               if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
+                       data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
+                       data->wait.threads [data->wait.num] = thread;
+                       data->wait.num++;
                } else {
                        /* Just ignore the rest, we can't do anything with
                         * them yet
@@ -3831,7 +3770,7 @@ mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
                mono_threads_lock ();
 
                user_data.domain = domain;
-               init_wait_data (&user_data.wait);
+               user_data.wait.num = 0;
                /* This shouldn't take any locks */
                mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
                mono_threads_unlock ();
@@ -3906,17 +3845,22 @@ mono_thread_get_undeniable_exception (void)
 {
        MonoInternalThread *thread = mono_thread_internal_current ();
 
-       if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
-               /*
-                * FIXME: Clear the abort exception and return an AppDomainUnloaded 
-                * exception if the thread no longer references a dying appdomain.
-                */
-               thread->abort_exc->trace_ips = NULL;
-               thread->abort_exc->stack_trace = NULL;
-               return thread->abort_exc;
-       }
+       if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
+               return NULL;
 
-       return NULL;
+       // We don't want to have our exception effect calls made by
+       // the catching block
+
+       if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
+               return NULL;
+
+       /*
+        * FIXME: Clear the abort exception and return an AppDomainUnloaded 
+        * exception if the thread no longer references a dying appdomain.
+        */ 
+       thread->abort_exc->trace_ips = NULL;
+       thread->abort_exc->stack_trace = NULL;
+       return thread->abort_exc;
 }
 
 #if MONO_SMALL_CONFIG
@@ -4512,15 +4456,14 @@ mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
        MonoInternalThread *thread = mono_thread_internal_current ();
 
        /* The thread may already be stopping */
-       if (thread == NULL)
+       if (!thread)
+               return NULL;
+       if (!thread->interruption_requested)
+               return NULL;
+       if (!bypass_abort_protection && is_running_protected_wrapper ())
                return NULL;
 
-       if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
-               MonoException* exc = mono_thread_execute_interruption ();
-               if (exc)
-                       return exc;
-       }
-       return NULL;
+       return mono_thread_execute_interruption ();
 }
 
 /*
@@ -4665,20 +4608,6 @@ mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
        return ret;
 }
 
-static gboolean has_tls_get = FALSE;
-
-void
-mono_runtime_set_has_tls_get (gboolean val)
-{
-       has_tls_get = val;
-}
-
-gboolean
-mono_runtime_has_tls_get (void)
-{
-       return has_tls_get;
-}
-
 static void
 self_interrupt_thread (void *_unused)
 {
@@ -4998,10 +4927,6 @@ mono_threads_join_threads (void)
                                /* This shouldn't block */
                                mono_native_thread_join (thread);
                                MONO_EXIT_GC_SAFE;
-                               thread_wait_lock ();
-                               njoined_threads ++;
-                               mono_os_cond_signal (&thread_wait_cond);
-                               thread_wait_unlock ();
                        }
                } else {
                        break;