Merge pull request #1840 from ludovic-henry/iolayer-thread-interrupt
[mono.git] / mono / utils / mono-threads-posix.c
index 05cf12c91d8c16d6537c13163c1a7c276d335584..b2e4bd37bcc93a8ec42eb3e9a6f844ecf36e353e 100644 (file)
@@ -9,17 +9,23 @@
 
 #include <config.h>
 
+/* For pthread_main_np, pthread_get_stackaddr_np and pthread_get_stacksize_np */
+#if defined (__MACH__)
+#define _DARWIN_C_SOURCE 1
+#endif
+
 #include <mono/utils/mono-compiler.h>
 #include <mono/utils/mono-semaphore.h>
 #include <mono/utils/mono-threads.h>
 #include <mono/utils/mono-tls.h>
 #include <mono/utils/mono-mmap.h>
 #include <mono/metadata/threads-types.h>
+#include <mono/metadata/gc-internal.h>
 #include <limits.h>
 
 #include <errno.h>
 
-#if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64)
+#if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
 #define USE_TKILL_ON_ANDROID 1
 #endif
 
@@ -43,14 +49,10 @@ typedef struct {
        HANDLE handle;
 } StartInfo;
 
-#ifdef PLATFORM_ANDROID
-static int no_interrupt_signo;
-#endif
-
 static void*
 inner_start_thread (void *arg)
 {
-       StartInfo *start_info = arg;
+       StartInfo *start_info = (StartInfo *) arg;
        void *t_arg = start_info->arg;
        int res;
        void *(*start_func)(void*) = start_info->start_routine;
@@ -69,6 +71,8 @@ inner_start_thread (void *arg)
        start_info->handle = handle;
 
        info = mono_thread_info_attach (&result);
+       MONO_PREPARE_BLOCKING
+
        info->runtime_thread = TRUE;
        info->handle = handle;
 
@@ -88,25 +92,12 @@ inner_start_thread (void *arg)
                MONO_SEM_DESTROY (&info->create_suspended_sem);
        }
 
+       MONO_FINISH_BLOCKING
        /* Run the actual main function of the thread */
        result = start_func (t_arg);
 
-       /*
-       mono_thread_info_detach ();
-       */
-
-#if defined(__native_client__)
-       nacl_shutdown_gc_thread();
-#endif
-
-       wapi_thread_handle_set_exited (handle, GPOINTER_TO_UINT (result));
-       /* This is needed by mono_threads_core_unregister () which is called later */
-       info->handle = NULL;
-
-       g_assert (mono_threads_get_callbacks ()->thread_exit);
-       mono_threads_get_callbacks ()->thread_exit (NULL);
+       mono_threads_core_exit (GPOINTER_TO_UINT (result));
        g_assert_not_reached ();
-       return result;
 }
 
 HANDLE
@@ -142,13 +133,13 @@ mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer
 #endif
 
        memset (&start_info, 0, sizeof (StartInfo));
-       start_info.start_routine = (gpointer)start_routine;
+       start_info.start_routine = (void *(*)(void *)) start_routine;
        start_info.arg = arg;
        start_info.flags = creation_flags;
        MONO_SEM_INIT (&(start_info.registered), 0);
 
        /* Actually start the thread */
-       res = mono_threads_get_callbacks ()->mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
+       res = mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
        if (res) {
                MONO_SEM_DESTROY (&(start_info.registered));
                return NULL;
@@ -194,8 +185,9 @@ mono_threads_core_exit (int exit_code)
 
        wapi_thread_handle_set_exited (current->handle, exit_code);
 
-       g_assert (mono_threads_get_callbacks ()->thread_exit);
-       mono_threads_get_callbacks ()->thread_exit (NULL);
+       mono_thread_info_detach ();
+
+       pthread_exit (NULL);
 }
 
 void
@@ -244,33 +236,10 @@ mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
        return handle;
 }
 
-gpointer
-mono_threads_core_prepare_interrupt (HANDLE thread_handle)
-{
-       return wapi_prepare_interrupt_thread (thread_handle);
-}
-
-void
-mono_threads_core_finish_interrupt (gpointer wait_handle)
-{
-       wapi_finish_interrupt_thread (wait_handle);
-}
-
-void
-mono_threads_core_self_interrupt (void)
-{
-       wapi_self_interrupt ();
-}
-
-void
-mono_threads_core_clear_interruption (void)
-{
-       wapi_clear_interruption ();
-}
-
 int
 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
 {
+       THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
 #ifdef USE_TKILL_ON_ANDROID
        int result, old_errno = errno;
        result = tkill (info->native_handle, signum);
@@ -282,44 +251,221 @@ mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
 #elif defined(__native_client__)
        /* Workaround pthread_kill abort() in NaCl glibc. */
        return 0;
+#elif !defined(HAVE_PTHREAD_KILL)
+       g_error ("pthread_kill() is not supported by this platform");
 #else
        return pthread_kill (mono_thread_info_get_tid (info), signum);
 #endif
+}
 
+MonoNativeThreadId
+mono_native_thread_id_get (void)
+{
+       return pthread_self ();
+}
+
+gboolean
+mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
+{
+       return pthread_equal (id1, id2);
+}
+
+/*
+ * mono_native_thread_create:
+ *
+ *   Low level thread creation function without any GC wrappers.
+ */
+gboolean
+mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
+{
+       return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
+}
+
+void
+mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
+{
+#if defined (HAVE_PTHREAD_SETNAME_NP) && !defined (__MACH__)
+       if (!name) {
+               pthread_setname_np (tid, "");
+       } else {
+               char n [16];
+
+               strncpy (n, name, 16);
+               n [15] = '\0';
+               pthread_setname_np (tid, n);
+       }
+#endif
+}
+
+
+#if defined (USE_POSIX_BACKEND) && !defined (USE_COOP_GC)
+
+static int suspend_signal_num;
+static int restart_signal_num;
+static int abort_signal_num;
+static sigset_t suspend_signal_mask;
+static sigset_t suspend_ack_signal_mask;
+
+
+#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
+#define DEFAULT_SUSPEND_SIGNAL SIGXFSZ
+#else
+#define DEFAULT_SUSPEND_SIGNAL SIGPWR
+#endif
+#define DEFAULT_RESTART_SIGNAL SIGXCPU
+
+static int
+mono_thread_search_alt_signal (int min_signal)
+{
+#if !defined (SIGRTMIN)
+       g_error ("signal search only works with RTMIN");
+#else
+       int i;
+       /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
+       for (i = MAX (min_signal, SIGRTMIN) + 1; i < SIGRTMAX; ++i) {
+               struct sigaction sinfo;
+               sigaction (i, NULL, &sinfo);
+               if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
+                       return i;
+               }
+       }
+       g_error ("Could not find an available signal");
+#endif
+}
+
+static int
+mono_thread_get_alt_suspend_signal (void)
+{
+#if defined(PLATFORM_ANDROID)
+       return SIGUNUSED;
+#elif !defined (SIGRTMIN)
+#ifdef SIGUSR1
+       return SIGUSR1;
+#else
+       return -1;
+#endif /* SIGUSR1 */
+#else
+       static int suspend_signum = -1;
+       if (suspend_signum == -1)
+               suspend_signum = mono_thread_search_alt_signal (-1);
+       return suspend_signum;
+#endif /* SIGRTMIN */
+}
+
+static int
+mono_thread_get_alt_resume_signal (void)
+{
+#if defined(PLATFORM_ANDROID)
+       return SIGTTOU;
+#elif !defined (SIGRTMIN)
+#ifdef SIGUSR2
+       return SIGUSR2;
+#else
+       return -1;
+#endif /* SIGUSR1 */
+#else
+       static int resume_signum = -1;
+       if (resume_signum == -1)
+               resume_signum = mono_thread_search_alt_signal (mono_thread_get_alt_suspend_signal () + 1);
+       return resume_signum;
+#endif /* SIGRTMIN */
+}
+
+
+static int
+mono_threads_get_abort_signal (void)
+{
+#if defined(PLATFORM_ANDROID)
+       return SIGTTIN;
+#elif !defined (SIGRTMIN)
+#ifdef SIGTTIN
+       return SIGTTIN;
+#else
+       return -1;
+#endif /* SIGRTMIN */
+#else
+       static int abort_signum = -1;
+       if (abort_signum == -1)
+               abort_signum = mono_thread_search_alt_signal (mono_thread_get_alt_resume_signal () + 1);
+       return abort_signum;
+#endif /* SIGRTMIN */
 }
 
-#if !defined (__MACH__)
 
 #if !defined(__native_client__)
+static void
+restart_signal_handler (int _dummy, siginfo_t *_info, void *context)
+{
+       MonoThreadInfo *info;
+       int old_errno = errno;
+
+       info = mono_thread_info_current ();
+       info->signal = restart_signal_num;
+       errno = old_errno;
+}
+
 static void
 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
 {
+       int old_errno = errno;
+       int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
+
+
        MonoThreadInfo *current = mono_thread_info_current ();
        gboolean ret;
-       
+
+       THREADS_SUSPEND_DEBUG ("SIGNAL HANDLER FOR %p [%p]\n", current, (void*)current->native_handle);
        if (current->syscall_break_signal) {
                current->syscall_break_signal = FALSE;
-               return;
+               THREADS_SUSPEND_DEBUG ("\tsyscall break for %p\n", current);
+               mono_threads_notify_initiator_of_abort (current);
+               goto done;
+       }
+
+       /* Have we raced with self suspend? */
+       if (!mono_threads_transition_finish_async_suspend (current)) {
+               current->suspend_can_continue = TRUE;
+               THREADS_SUSPEND_DEBUG ("\tlost race with self suspend %p\n", current);
+               goto done;
        }
 
-       ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->suspend_state, context);
+       ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX], context);
 
        /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
        current->suspend_can_continue = ret;
 
-       MONO_SEM_POST (&current->begin_suspend_semaphore);
+
+       /*
+       Block the restart signal.
+       We need to block the restart signal while posting to the suspend_ack semaphore or we race to sigsuspend,
+       which might miss the signal and get stuck.
+       */
+       pthread_sigmask (SIG_BLOCK, &suspend_ack_signal_mask, NULL);
+
+       /* We're done suspending */
+       mono_threads_notify_initiator_of_suspend (current);
 
        /* This thread is doomed, all we can do is give up and let the suspender recover. */
-       if (!ret)
-               return;
+       if (!ret) {
+               THREADS_SUSPEND_DEBUG ("\tThread is dying, failed to capture state %p\n", current);
+               mono_threads_transition_async_suspend_compensation (current);
+               /* Unblock the restart signal. */
+               pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
 
-       while (MONO_SEM_WAIT (&current->resume_semaphore) != 0) {
-               /*if (EINTR != errno) ABORT("sem_wait failed"); */
+               goto done;
        }
 
+       do {
+               current->signal = 0;
+               sigsuspend (&suspend_signal_mask);
+       } while (current->signal != restart_signal_num);
+
+       /* Unblock the restart signal. */
+       pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
+
        if (current->async_target) {
 #if MONO_ARCH_HAS_MONO_CONTEXT
-               MonoContext tmp = current->suspend_state.ctx;
+               MonoContext tmp = current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
                mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
                current->async_target = current->user_data = NULL;
                mono_monoctx_to_sigctx (&tmp, context);
@@ -328,8 +474,20 @@ suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
 #endif
        }
 
-       MONO_SEM_POST (&current->finish_resume_semaphore);
+       /* We're done resuming */
+       mono_threads_notify_initiator_of_resume (current);
+
+done:
+       mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
+       errno = old_errno;
 }
+
+static void
+abort_signal_handler (int _dummy, siginfo_t *info, void *context)
+{
+       suspend_signal_handler (_dummy, info, context);
+}
+
 #endif
 
 static void
@@ -342,7 +500,8 @@ mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
        int ret;
 
        sa.sa_sigaction = handler;
-       sigemptyset (&sa.sa_mask);
+       sigfillset (&sa.sa_mask);
+
        sa.sa_flags = SA_SIGINFO | flags;
        ret = sigaction (signo, &sa, &previous_sa);
 
@@ -353,37 +512,33 @@ mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
 void
 mono_threads_init_platform (void)
 {
-#if !defined(__native_client__)
-       int abort_signo;
+       sigset_t signal_set;
 
-       /*
-       FIXME we should use all macros from mini to make this more portable
-       FIXME it would be very sweet if sgen could end up using this too.
-       */
-       if (!mono_thread_info_new_interrupt_enabled ())
-               return;
-       abort_signo = mono_thread_get_abort_signal ();
-       mono_posix_add_signal_handler (abort_signo, suspend_signal_handler, 0);
+       abort_signal_num = mono_threads_get_abort_signal ();
+       if (mono_thread_info_unified_management_enabled ()) {
+               suspend_signal_num = DEFAULT_SUSPEND_SIGNAL;
+               restart_signal_num = DEFAULT_RESTART_SIGNAL;
+       } else {
+               suspend_signal_num = mono_thread_get_alt_suspend_signal ();
+               restart_signal_num = mono_thread_get_alt_resume_signal ();
+       }
 
-#ifdef PLATFORM_ANDROID
-       /*
-        * Lots of android native code can't handle the EINTR caused by
-        * the normal abort signal, so use a different signal for the
-        * no interruption case, which is used by sdb.
-        * FIXME: Use this on all platforms.
-        * SIGUSR1 is used by dalvik/art.
-        */
-       no_interrupt_signo = SIGUSR2;
-       g_assert (abort_signo != no_interrupt_signo);
-       mono_posix_add_signal_handler (no_interrupt_signo, suspend_signal_handler, SA_RESTART);
-#endif
-#endif
-}
+       sigfillset (&suspend_signal_mask);
+       sigdelset (&suspend_signal_mask, restart_signal_num);
 
-void
-mono_threads_core_interrupt (MonoThreadInfo *info)
-{
-       /* Handled in mono_threads_core_suspend () */
+       sigemptyset (&suspend_ack_signal_mask);
+       sigaddset (&suspend_ack_signal_mask, restart_signal_num);
+
+       mono_posix_add_signal_handler (suspend_signal_num, suspend_signal_handler, SA_RESTART);
+       mono_posix_add_signal_handler (restart_signal_num, restart_signal_handler, SA_RESTART);
+       mono_posix_add_signal_handler (abort_signal_num, abort_signal_handler, 0);
+
+       /* ensure all the new signals are unblocked */
+       sigemptyset (&signal_set);
+       sigaddset (&signal_set, suspend_signal_num);
+       sigaddset (&signal_set, restart_signal_num);
+       sigaddset (&signal_set, abort_signal_num);
+       sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
 }
 
 void
@@ -394,7 +549,8 @@ mono_threads_core_abort_syscall (MonoThreadInfo *info)
        This signal should not be interpreted as a suspend request.
        */
        info->syscall_break_signal = TRUE;
-       mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
+       if (!mono_threads_pthread_kill (info, abort_signal_num))
+               mono_threads_add_to_pending_operation_set (info);
 }
 
 gboolean
@@ -404,39 +560,39 @@ mono_threads_core_needs_abort_syscall (void)
 }
 
 gboolean
-mono_threads_core_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
+mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
 {
-       /*FIXME, check return value*/
-#ifdef PLATFORM_ANDROID
-       if (!interrupt_kernel)
-               mono_threads_pthread_kill (info, no_interrupt_signo);
-       else
-               mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
-#else
-               mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
-#endif
-       while (MONO_SEM_WAIT (&info->begin_suspend_semaphore) != 0) {
-               /* g_assert (errno == EINTR); */
+       int sig = interrupt_kernel ? abort_signal_num :  suspend_signal_num;
+
+       if (!mono_threads_pthread_kill (info, sig)) {
+               mono_threads_add_to_pending_operation_set (info);
+               return TRUE;
        }
-       return info->suspend_can_continue;
+       return FALSE;
 }
 
 gboolean
-mono_threads_core_resume (MonoThreadInfo *info)
+mono_threads_core_check_suspend_result (MonoThreadInfo *info)
 {
-       MONO_SEM_POST (&info->resume_semaphore);
-       while (MONO_SEM_WAIT (&info->finish_resume_semaphore) != 0) {
-               /* g_assert (errno == EINTR); */
-       }
+       return info->suspend_can_continue;
+}
 
-       return TRUE;
+/*
+This begins async resume. This function must do the following:
+
+- Install an async target if one was requested.
+- Notify the target to resume.
+*/
+gboolean
+mono_threads_core_begin_async_resume (MonoThreadInfo *info)
+{
+       mono_threads_add_to_pending_operation_set (info);
+       return mono_threads_pthread_kill (info, restart_signal_num) == 0;
 }
 
 void
 mono_threads_platform_register (MonoThreadInfo *info)
 {
-       MONO_SEM_INIT (&info->begin_suspend_semaphore, 0);
-
 #if defined (PLATFORM_ANDROID)
        info->native_handle = gettid ();
 #endif
@@ -445,48 +601,18 @@ mono_threads_platform_register (MonoThreadInfo *info)
 void
 mono_threads_platform_free (MonoThreadInfo *info)
 {
-       MONO_SEM_DESTROY (&info->begin_suspend_semaphore);
 }
 
-MonoNativeThreadId
-mono_native_thread_id_get (void)
-{
-       return pthread_self ();
-}
-
-gboolean
-mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
-{
-       return pthread_equal (id1, id2);
-}
-
-/*
- * mono_native_thread_create:
- *
- *   Low level thread creation function without any GC wrappers.
- */
-gboolean
-mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
+void
+mono_threads_core_begin_global_suspend (void)
 {
-       return pthread_create (tid, NULL, func, arg) == 0;
 }
 
 void
-mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
+mono_threads_core_end_global_suspend (void)
 {
-#ifdef HAVE_PTHREAD_SETNAME_NP
-       if (!name) {
-               pthread_setname_np (tid, "");
-       } else {
-               char n [16];
-
-               strncpy (n, name, 16);
-               n [15] = '\0';
-               pthread_setname_np (tid, n);
-       }
-#endif
 }
 
-#endif /*!defined (__MACH__)*/
+#endif /*defined (USE_POSIX_BACKEND)*/
 
 #endif