Merge pull request #505 from roji/shutdown_flow
[mono.git] / mono / metadata / threads.c
index b1376cd2de9493482688980d39de3f7dca1d4590..56a1ea2646be71194ebe78c192d034ce8c60dd2f 100644 (file)
@@ -411,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
@@ -696,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 ();
@@ -734,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 */
@@ -750,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_PINNING (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);
@@ -765,7 +785,8 @@ MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer fu
                ResumeThread (thread_handle);
 
        /* Check that the managed and unmanaged layout of MonoInternalThread matches */
-       g_assert (((char*)&internal->unused2 - (char*)internal) == mono_defaults.internal_thread_class->fields [mono_defaults.internal_thread_class->field.count - 1].offset);
+       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;
 }
@@ -773,7 +794,7 @@ MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer fu
 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);
 }
 
 /*
@@ -880,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_PINNING (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;
 
@@ -1049,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_PINNING (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.
@@ -1363,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)
 {
@@ -1390,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);
 
@@ -1399,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);
        }
@@ -1421,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 ();
@@ -1441,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);
 
@@ -1490,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);
        }
@@ -2058,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;
@@ -2081,7 +2121,6 @@ mono_thread_get_abort_signal (void)
        }
        /* fallback to the old way */
        return SIGRTMIN;
-#endif
 #endif /* HOST_WIN32 */
 }
 
@@ -2428,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)
 {
@@ -2476,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)
 {
@@ -4455,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;
 }
@@ -4561,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);