Merge pull request #3769 from evincarofautumn/fix-verify-before-allocs
[mono.git] / mono / utils / mono-threads-posix.c
index 8c1c9430ff6dc9c2d42a756f2dac9f014e5f6641..be440711fb3bfcbdf3be365bd25876045dfe8bf5 100644 (file)
 #endif
 
 #include <mono/utils/mono-threads.h>
-#include <mono/utils/mono-threads-posix-signals.h>
 #include <mono/utils/mono-coop-semaphore.h>
 #include <mono/metadata/gc-internals.h>
 #include <mono/utils/w32handle.h>
+#include <mono/utils/mono-threads-debug.h>
 
 #include <errno.h>
 
@@ -40,199 +40,115 @@ extern int tkill (pid_t tid, int signal);
 void nacl_shutdown_gc_thread(void);
 #endif
 
-static gpointer
-thread_handle_create (void)
+void
+mono_threads_platform_register (MonoThreadInfo *info)
 {
-       MonoW32HandleThread thread_data;
        gpointer thread_handle;
 
-       thread_data.id = pthread_self ();
-       thread_data.owned_mutexes = g_ptr_array_new ();
-       thread_data.priority = MONO_THREAD_PRIORITY_NORMAL;
-
-       thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, (gpointer) &thread_data);
+       thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, NULL);
        if (thread_handle == INVALID_HANDLE_VALUE)
-               return NULL;
-
-       /* We need to keep the handle alive, as long as the corresponding managed
-        * thread object is alive. The handle is going to be unref when calling
-        * the finalizer on the MonoThreadInternal object */
-       mono_w32handle_ref (thread_handle);
+               g_error ("%s: failed to create handle", __func__);
 
-       return thread_handle;
-}
-
-static int
-win32_priority_to_posix_priority (MonoThreadPriority priority, int policy)
-{
-       g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
-       g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
-
-/* Necessary to get valid priority range */
-#ifdef _POSIX_PRIORITY_SCHEDULING
-       int max, min;
-
-       min = sched_get_priority_min (policy);
-       max = sched_get_priority_max (policy);
-
-       /* Partition priority range linearly (cross-multiply) */
-       if (max > 0 && min >= 0 && max > min)
-               return (int)((double) priority * (max - min) / (MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST));
-#endif
-
-       switch (policy) {
-       case SCHED_FIFO:
-       case SCHED_RR:
-               return 50;
-#ifdef SCHED_BATCH
-       case SCHED_BATCH:
-#endif
-       case SCHED_OTHER:
-               return 0;
-       default:
-               return -1;
-       }
-}
-
-typedef struct {
-       void *(*start_routine)(void*);
-       void *arg;
-       int flags;
-       gint32 priority;
-       MonoCoopSem registered;
-       HANDLE handle;
-} StartInfo;
-
-static void*
-inner_start_thread (void *arg)
-{
-       StartInfo *start_info = (StartInfo *) arg;
-       void *t_arg = start_info->arg;
-       int res;
-       void *(*start_func)(void*) = start_info->start_routine;
-       guint32 flags = start_info->flags;
-       void *result;
-       HANDLE handle;
-       MonoThreadInfo *info;
-
-       /* Register the thread with the io-layer */
-       handle = thread_handle_create ();
-       if (!handle) {
-               mono_coop_sem_post (&(start_info->registered));
-               return NULL;
-       }
-       start_info->handle = handle;
-
-       info = mono_thread_info_attach (&result);
-
-       info->runtime_thread = TRUE;
-       info->handle = handle;
-
-       mono_threads_platform_set_priority (info, start_info->priority);
-
-       if (flags & CREATE_SUSPENDED) {
-               info->create_suspended = TRUE;
-               mono_coop_sem_init (&info->create_suspended_sem, 0);
-       }
-
-       /* start_info is not valid after this */
-       mono_coop_sem_post (&(start_info->registered));
-       start_info = NULL;
-
-       if (flags & CREATE_SUSPENDED) {
-               res = mono_coop_sem_wait (&info->create_suspended_sem, MONO_SEM_FLAGS_NONE);
-               g_assert (res != -1);
-
-               mono_coop_sem_destroy (&info->create_suspended_sem);
-       }
-
-       /* Run the actual main function of the thread */
-       result = start_func (t_arg);
-
-       mono_threads_platform_exit (GPOINTER_TO_UINT (result));
-       g_assert_not_reached ();
+       g_assert (!info->handle);
+       info->handle = thread_handle;
 }
 
-HANDLE
-mono_threads_platform_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, MonoThreadParm *tp, MonoNativeThreadId *out_tid)
+int
+mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid)
 {
        pthread_attr_t attr;
-       int res;
        pthread_t thread;
-       StartInfo start_info;
-       guint32 stack_size;
        int policy;
-       struct sched_param sp;
+       struct sched_param param;
+       gint res;
+       gsize set_stack_size;
+       size_t min_size;
 
        res = pthread_attr_init (&attr);
        g_assert (!res);
 
-       if (tp->stack_size == 0) {
+       if (stack_size)
+               set_stack_size = *stack_size;
+       else
+               set_stack_size = 0;
+
+#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
+       if (set_stack_size == 0) {
 #if HAVE_VALGRIND_MEMCHECK_H
                if (RUNNING_ON_VALGRIND)
-                       stack_size = 1 << 20;
+                       set_stack_size = 1 << 20;
                else
-                       stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+                       set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
 #else
-               stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+               set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
 #endif
-       } else
-               stack_size = tp->stack_size;
+       }
 
 #ifdef PTHREAD_STACK_MIN
-       if (stack_size < PTHREAD_STACK_MIN)
-               stack_size = PTHREAD_STACK_MIN;
+       if (set_stack_size < PTHREAD_STACK_MIN)
+               set_stack_size = PTHREAD_STACK_MIN;
 #endif
 
-#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
-       res = pthread_attr_setstacksize (&attr, stack_size);
+       res = pthread_attr_setstacksize (&attr, set_stack_size);
        g_assert (!res);
-#endif
+#endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
 
-       /*
-        * For policies that respect priorities set the prirority for the new thread
-        */ 
-       pthread_getschedparam(pthread_self(), &policy, &sp);
-       if ((policy == SCHED_FIFO) || (policy == SCHED_RR)) {
-               sp.sched_priority = win32_priority_to_posix_priority (tp->priority, policy);
-               res = pthread_attr_setschedparam (&attr, &sp);
-       }
+       memset (&param, 0, sizeof (param));
 
-       memset (&start_info, 0, sizeof (StartInfo));
-       start_info.start_routine = (void *(*)(void *)) start_routine;
-       start_info.arg = arg;
-       start_info.flags = tp->creation_flags;
-       start_info.priority = tp->priority;
-       mono_coop_sem_init (&(start_info.registered), 0);
+       res = pthread_attr_getschedpolicy (&attr, &policy);
+       if (res != 0)
+               g_error ("%s: pthread_attr_getschedpolicy failed, error: \"%s\" (%d)", g_strerror (res), res);
 
-       /* Actually start the thread */
-       res = mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
-       if (res) {
-               mono_coop_sem_destroy (&(start_info.registered));
-               return NULL;
+#ifdef _POSIX_PRIORITY_SCHEDULING
+       int max, min;
+
+       /* Necessary to get valid priority range */
+
+       min = sched_get_priority_min (policy);
+       max = sched_get_priority_max (policy);
+
+       if (max > 0 && min >= 0 && max > min)
+               param.sched_priority = (max - min) / 2 + min;
+       else
+#endif
+       {
+               switch (policy) {
+               case SCHED_FIFO:
+               case SCHED_RR:
+                       param.sched_priority = 50;
+                       break;
+#ifdef SCHED_BATCH
+               case SCHED_BATCH:
+#endif
+               case SCHED_OTHER:
+                       param.sched_priority = 0;
+                       break;
+               default:
+                       g_error ("%s: unknown policy %d", __func__, policy);
+               }
        }
 
-       /* Wait until the thread register itself in various places */
-       res = mono_coop_sem_wait (&start_info.registered, MONO_SEM_FLAGS_NONE);
-       g_assert (res != -1);
+       res = pthread_attr_setschedparam (&attr, &param);
+       if (res != 0)
+               g_error ("%s: pthread_attr_setschedparam failed, error: \"%s\" (%d)", g_strerror (res), res);
+
+       if (stack_size) {
+               res = pthread_attr_getstacksize (&attr, &min_size);
+               if (res != 0)
+                       g_error ("%s: pthread_attr_getstacksize failed, error: \"%s\" (%d)", g_strerror (res), res);
+               else
+                       *stack_size = min_size;
+       }
 
-       mono_coop_sem_destroy (&(start_info.registered));
+       /* Actually start the thread */
+       res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
+       if (res)
+               return -1;
 
        if (out_tid)
                *out_tid = thread;
 
-       return start_info.handle;
-}
-
-/*
- * mono_threads_platform_resume_created:
- *
- *   Resume a newly created thread created using CREATE_SUSPENDED.
- */
-void
-mono_threads_platform_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
-{
-       mono_coop_sem_post (&info->create_suspended_sem);
+       return 0;
 }
 
 gboolean
@@ -244,14 +160,10 @@ mono_threads_platform_yield (void)
 void
 mono_threads_platform_exit (int exit_code)
 {
-       MonoThreadInfo *current = mono_thread_info_current ();
-
 #if defined(__native_client__)
        nacl_shutdown_gc_thread();
 #endif
 
-       mono_threads_platform_set_exited (current);
-
        mono_thread_info_detach ();
 
        pthread_exit (NULL);
@@ -260,25 +172,11 @@ mono_threads_platform_exit (int exit_code)
 void
 mono_threads_platform_unregister (MonoThreadInfo *info)
 {
-       if (info->handle) {
-               mono_threads_platform_set_exited (info);
-               info->handle = NULL;
-       }
-}
-
-HANDLE
-mono_threads_platform_open_handle (void)
-{
-       MonoThreadInfo *info;
-
-       info = mono_thread_info_current ();
-       g_assert (info);
+       g_assert (info->handle);
 
-       if (!info->handle)
-               info->handle = thread_handle_create ();
-       else
-               mono_w32handle_ref (info->handle);
-       return info->handle;
+       /* The thread is no longer active, so unref it */
+       mono_w32handle_unref (info->handle);
+       info->handle = NULL;
 }
 
 int
@@ -295,6 +193,14 @@ mono_threads_get_max_stack_size (void)
        return (int)lim.rlim_max;
 }
 
+gpointer
+mono_threads_platform_duplicate_handle (MonoThreadInfo *info)
+{
+       g_assert (info->handle);
+       mono_w32handle_ref (info->handle);
+       return info->handle;
+}
+
 HANDLE
 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
 {
@@ -303,6 +209,12 @@ mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
        return handle;
 }
 
+void
+mono_threads_platform_close_thread_handle (HANDLE handle)
+{
+       mono_w32handle_unref (handle);
+}
+
 int
 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
 {
@@ -391,159 +303,62 @@ mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
 #endif
 }
 
-void
-mono_threads_platform_set_exited (MonoThreadInfo *info)
+gboolean
+mono_native_thread_join (MonoNativeThreadId tid)
 {
-       MonoW32HandleThread *thread_data;
-       gpointer mutex_handle;
-       int i, thr_ret;
-       pid_t pid;
-       pthread_t tid;
-
-       if (!info->handle || mono_w32handle_issignalled (info->handle) || mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED) {
-               /* We must have already deliberately finished
-                * with this thread, so don't do any more now */
-               return;
-       }
-
-       if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
-               g_error ("unknown thread handle %p", info->handle);
+       void *res;
 
-       pid = wapi_getpid ();
-       tid = pthread_self ();
-
-       for (i = 0; i < thread_data->owned_mutexes->len; i++) {
-               mutex_handle = g_ptr_array_index (thread_data->owned_mutexes, i);
-               wapi_mutex_abandon (mutex_handle, pid, tid);
-               mono_thread_info_disown_mutex (info, mutex_handle);
-       }
-
-       g_ptr_array_free (thread_data->owned_mutexes, TRUE);
-
-       thr_ret = mono_w32handle_lock_handle (info->handle);
-       g_assert (thr_ret == 0);
-
-       mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
-
-       thr_ret = mono_w32handle_unlock_handle (info->handle);
-       g_assert (thr_ret == 0);
-
-       /* The thread is no longer active, so unref it */
-       mono_w32handle_unref (info->handle);
-
-       info->handle = NULL;
+       return !pthread_join (tid, &res);
 }
 
 void
-mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
+mono_threads_platform_set_exited (gpointer handle)
 {
-       MonoW32HandleThread *thread_data;
-       int i;
-
-       g_assert (info->handle);
+       int thr_ret;
 
-       if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
-               g_error ("unknown thread handle %p", info->handle);
+       g_assert (handle);
+       if (mono_w32handle_issignalled (handle))
+               g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, handle, mono_native_thread_id_get ());
+       if (mono_w32handle_get_type (handle) == MONO_W32HANDLE_UNUSED)
+               g_error ("%s: handle %p thread %p has already exited, it's handle type is 'unused'", __func__, handle, mono_native_thread_id_get ());
 
-       g_string_append_printf (text, "thread handle %p state : ", info->handle);
+       thr_ret = mono_w32handle_lock_handle (handle);
+       g_assert (thr_ret == 0);
 
-       mono_thread_info_describe_interrupt_token (info, text);
+       mono_w32handle_set_signal_state (handle, TRUE, TRUE);
 
-       g_string_append_printf (text, ", owns (");
-       for (i = 0; i < thread_data->owned_mutexes->len; i++)
-               g_string_append_printf (text, i > 0 ? ", %p" : "%p", g_ptr_array_index (thread_data->owned_mutexes, i));
-       g_string_append_printf (text, ")");
+       thr_ret = mono_w32handle_unlock_handle (handle);
+       g_assert (thr_ret == 0);
 }
 
-void
-mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
+static const gchar* thread_typename (void)
 {
-       MonoW32HandleThread *thread_data;
-
-       g_assert (info->handle);
-
-       if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
-               g_error ("unknown thread handle %p", info->handle);
-
-       mono_w32handle_ref (mutex_handle);
-
-       g_ptr_array_add (thread_data->owned_mutexes, mutex_handle);
+       return "Thread";
 }
 
-void
-mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
+static gsize thread_typesize (void)
 {
-       MonoW32HandleThread *thread_data;
-
-       g_assert (info->handle);
-
-       if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
-               g_error ("unknown thread handle %p", info->handle);
-
-       mono_w32handle_unref (mutex_handle);
-
-       g_ptr_array_remove (thread_data->owned_mutexes, mutex_handle);
+       return 0;
 }
 
-MonoThreadPriority
-mono_threads_platform_get_priority (MonoThreadInfo *info)
-{
-       MonoW32HandleThread *thread_data;
-
-       g_assert (info->handle);
-
-       if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer *)&thread_data))
-               return MONO_THREAD_PRIORITY_NORMAL;
-
-       return thread_data->priority;
-}
+static MonoW32HandleOps thread_ops = {
+       NULL,                           /* close */
+       NULL,                           /* signal */
+       NULL,                           /* own */
+       NULL,                           /* is_owned */
+       NULL,                           /* special_wait */
+       NULL,                           /* prewait */
+       NULL,                           /* details */
+       thread_typename,        /* typename */
+       thread_typesize,        /* typesize */
+};
 
-gboolean
-mono_threads_platform_set_priority (MonoThreadInfo *info, MonoThreadPriority priority)
+void
+mono_threads_platform_init (void)
 {
-       MonoW32HandleThread *thread_data;
-       int policy, posix_priority;
-       struct sched_param param;
-
-       g_assert (info->handle);
-
-       if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
-               return FALSE;
-
-       switch (pthread_getschedparam (thread_data->id, &policy, &param)) {
-       case 0:
-               break;
-       case ESRCH:
-               g_warning ("pthread_getschedparam: error looking up thread id %x", (gsize)thread_data->id);
-               return FALSE;
-       default:
-               return FALSE;
-       }
-
-       posix_priority =  win32_priority_to_posix_priority (priority, policy);
-       if (posix_priority < 0)
-               return FALSE;
-
-       param.sched_priority = posix_priority;
-       switch (pthread_setschedparam (thread_data->id, policy, &param)) {
-       case 0:
-               break;
-       case ESRCH:
-               g_warning ("%s: pthread_setschedprio: error looking up thread id %x", __func__, (gsize)thread_data->id);
-               return FALSE;
-       case ENOTSUP:
-               g_warning ("%s: priority %d not supported", __func__, priority);
-               return FALSE;
-       case EPERM:
-               g_warning ("%s: permission denied", __func__);
-               return FALSE;
-       default:
-               return FALSE;
-       }
-
-       thread_data->priority = priority;
-       return TRUE;
+       mono_w32handle_register_ops (MONO_W32HANDLE_THREAD, &thread_ops);
 
+       mono_w32handle_register_capabilities (MONO_W32HANDLE_THREAD, MONO_W32HANDLE_CAP_WAIT);
 }
 
 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
@@ -553,7 +368,7 @@ mono_threads_platform_set_priority (MonoThreadInfo *info, MonoThreadPriority pri
 gboolean
 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
 {
-       int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () :  mono_threads_posix_get_suspend_signal ();
+       int sig = interrupt_kernel ? mono_threads_suspend_get_abort_signal () :  mono_threads_suspend_get_suspend_signal ();
 
        if (!mono_threads_pthread_kill (info, sig)) {
                mono_threads_add_to_pending_operation_set (info);
@@ -578,7 +393,24 @@ gboolean
 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
 {
        mono_threads_add_to_pending_operation_set (info);
-       return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
+       return mono_threads_pthread_kill (info, mono_threads_suspend_get_restart_signal ()) == 0;
+}
+
+void
+mono_threads_suspend_abort_syscall (MonoThreadInfo *info)
+{
+       /* We signal a thread to break it from the current syscall.
+        * This signal should not be interpreted as a suspend request. */
+       info->syscall_break_signal = TRUE;
+       if (mono_threads_pthread_kill (info, mono_threads_suspend_get_abort_signal ()) == 0) {
+               mono_threads_add_to_pending_operation_set (info);
+       }
+}
+
+gboolean
+mono_threads_suspend_needs_abort_syscall (void)
+{
+       return TRUE;
 }
 
 void
@@ -587,9 +419,6 @@ mono_threads_suspend_register (MonoThreadInfo *info)
 #if defined (PLATFORM_ANDROID)
        info->native_handle = gettid ();
 #endif
-
-       g_assert (!info->handle);
-       info->handle = thread_handle_create ();
 }
 
 void
@@ -600,7 +429,6 @@ mono_threads_suspend_free (MonoThreadInfo *info)
 void
 mono_threads_suspend_init (void)
 {
-       mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
 }
 
 #endif /* defined(USE_POSIX_BACKEND) */