Merge pull request #1659 from alexanderkyte/stringbuilder-referencesource
[mono.git] / mono / utils / mono-threads-posix.c
index 37bc7580da51fd08cc59b13c61fba969a73b1fdc..303f2529aeeed6dbda934b097c17647261792444 100644 (file)
@@ -9,9 +9,9 @@
 
 #include <config.h>
 
-#if defined(__OpenBSD__) || defined(__FreeBSD__)
-#include <pthread.h>
-#include <pthread_np.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 <errno.h>
 
-#if defined(PLATFORM_ANDROID)
-extern int tkill (pid_t tid, int signal);
+#if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
+#define USE_TKILL_ON_ANDROID 1
 #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);
+#ifdef USE_TKILL_ON_ANDROID
+extern int tkill (pid_t tid, int signal);
 #endif
 
 #if defined(_POSIX_VERSION) || defined(__native_client__)
@@ -179,114 +178,6 @@ mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
        MONO_SEM_POST (&info->create_suspended_sem);
 }
 
-void
-mono_threads_core_get_stack_bounds (guint8 **staddr, size_t *stsize)
-{
-#if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
-       /* Mac OS X */
-       *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self());
-       *stsize = pthread_get_stacksize_np (pthread_self());
-
-
-#ifdef TARGET_OSX
-       /*
-        * Mavericks reports stack sizes as 512kb:
-        * http://permalink.gmane.org/gmane.comp.java.openjdk.hotspot.devel/11590
-        * https://bugs.openjdk.java.net/browse/JDK-8020753
-        */
-       if (*stsize == 512 * 1024)
-               *stsize = 2048 * mono_pagesize ();
-#endif
-
-       /* staddr points to the start of the stack, not the end */
-       *staddr -= *stsize;
-
-       /* When running under emacs, sometimes staddr is not aligned to a page size */
-       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize() - 1));
-       return;
-
-#elif (defined(HAVE_PTHREAD_GETATTR_NP) || defined(HAVE_PTHREAD_ATTR_GET_NP)) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
-       /* Linux, BSD */
-
-       pthread_attr_t attr;
-       guint8 *current = (guint8*)&attr;
-
-       *staddr = NULL;
-       *stsize = (size_t)-1;
-
-       pthread_attr_init (&attr);
-
-#if     defined(HAVE_PTHREAD_GETATTR_NP)
-       /* Linux */
-       pthread_getattr_np (pthread_self(), &attr);
-
-#elif   defined(HAVE_PTHREAD_ATTR_GET_NP)
-       /* BSD */
-       pthread_attr_get_np (pthread_self(), &attr);
-
-#else
-#error         Cannot determine which API is needed to retrieve pthread attributes.
-#endif
-
-       pthread_attr_getstack (&attr, (void**)staddr, stsize);
-       pthread_attr_destroy (&attr);
-
-       if (*staddr)
-               g_assert ((current > *staddr) && (current < *staddr + *stsize));
-
-       /* When running under emacs, sometimes staddr is not aligned to a page size */
-       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
-       return;
-
-#elif defined(__OpenBSD__)
-       /* OpenBSD */
-       /* TODO :   Determine if this code is actually still needed. It may already be covered by the case above. */
-
-       pthread_attr_t attr;
-       guint8 *current = (guint8*)&attr;
-
-       *staddr = NULL;
-       *stsize = (size_t)-1;
-
-       pthread_attr_init (&attr);
-
-       stack_t ss;
-       int rslt;
-
-       rslt = pthread_stackseg_np(pthread_self(), &ss);
-       g_assert (rslt == 0);
-
-       *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
-       *stsize = ss.ss_size;
-
-       pthread_attr_destroy (&attr);
-
-       if (*staddr)
-               g_assert ((current > *staddr) && (current < *staddr + *stsize));
-
-       /* When running under emacs, sometimes staddr is not aligned to a page size */
-       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
-       return;
-
-#elif defined(sun) || defined(__native_client__)
-       /* Solaris/Illumos, NaCl */
-       pthread_attr_t attr;
-       pthread_attr_init (&attr);
-       pthread_attr_getstacksize (&attr, &stsize);
-       pthread_attr_destroy (&attr);
-       *staddr = NULL;
-       return;
-
-#else
-       /* FIXME:   It'd be better to use the 'error' preprocessor macro here so we know
-                   at compile-time if the target platform isn't supported. */
-#warning "Unable to determine how to retrieve a thread's stack-bounds for this platform in 'mono_thread_get_stack_bounds()'."
-       *staddr = NULL;
-       *stsize = 0;
-       return;
-#endif
-}
-
 gboolean
 mono_threads_core_yield (void)
 {
@@ -354,38 +245,257 @@ mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
        return handle;
 }
 
-#if !defined (__MACH__)
+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);
+       if (result < 0) {
+               result = errno;
+               errno = old_errno;
+       }
+       return result;
+#elif defined(__native_client__)
+       /* Workaround pthread_kill abort() in NaCl glibc. */
+       return 0;
+#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, 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(__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);
+               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);
@@ -394,12 +504,24 @@ 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
-mono_posix_add_signal_handler (int signo, gpointer handler)
+mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
 {
 #if !defined(__native_client__)
        /*FIXME, move the code from mini to utils and do the right thing!*/
@@ -408,8 +530,9 @@ mono_posix_add_signal_handler (int signo, gpointer handler)
        int ret;
 
        sa.sa_sigaction = handler;
-       sigemptyset (&sa.sa_mask);
-       sa.sa_flags = SA_SIGINFO;
+       sigfillset (&sa.sa_mask);
+
+       sa.sa_flags = SA_SIGINFO | flags;
        ret = sigaction (signo, &sa, &previous_sa);
 
        g_assert (ret != -1);
@@ -419,40 +542,33 @@ mono_posix_add_signal_handler (int signo, gpointer handler)
 void
 mono_threads_init_platform (void)
 {
-#if !defined(__native_client__)
-       /*
-       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 ())
-               mono_posix_add_signal_handler (mono_thread_get_abort_signal (), suspend_signal_handler);
-#endif
-}
-
-/*nothing to be done here since suspend always abort syscalls due using signals*/
-void
-mono_threads_core_interrupt (MonoThreadInfo *info)
-{
-}
+       sigset_t signal_set;
 
-int
-mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
-{
-#if defined (PLATFORM_ANDROID)
-       int result, old_errno = errno;
-       result = tkill (info->native_handle, signum);
-       if (result < 0) {
-               result = errno;
-               errno = old_errno;
+       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 ();
        }
-       return result;
-#elif defined(__native_client__)
-       /* Workaround pthread_kill abort() in NaCl glibc. */
-       return 0;
-#else
-       return pthread_kill (mono_thread_info_get_tid (info), signum);
-#endif
 
+       sigfillset (&suspend_signal_mask);
+       sigdelset (&suspend_signal_mask, restart_signal_num);
+
+       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
@@ -463,7 +579,7 @@ 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 ());
+       mono_threads_pthread_kill (info, abort_signal_num);
 }
 
 gboolean
@@ -473,82 +589,49 @@ mono_threads_core_needs_abort_syscall (void)
 }
 
 gboolean
-mono_threads_core_suspend (MonoThreadInfo *info)
+mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
 {
-       /*FIXME, check return value*/
-       mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
-       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 = (gpointer) gettid ();
+       info->native_handle = gettid ();
 #endif
 }
 
 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)
-{
-       return pthread_create (tid, NULL, func, arg) == 0;
-}
-
-void
-mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
-{
-#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