2 * mono-threads-posix.c: Low-level threading, posix version
5 * Rodrigo Kumpera (kumpera@gmail.com)
12 /* For pthread_main_np, pthread_get_stackaddr_np and pthread_get_stacksize_np */
13 #if defined (__MACH__)
14 #define _DARWIN_C_SOURCE 1
17 #include <mono/utils/mono-threads.h>
18 #include <mono/utils/mono-threads-posix-signals.h>
19 #include <mono/utils/mono-coop-semaphore.h>
20 #include <mono/metadata/gc-internals.h>
21 #include <mono/utils/w32handle.h>
25 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
26 #define USE_TKILL_ON_ANDROID 1
29 #ifdef USE_TKILL_ON_ANDROID
30 extern int tkill (pid_t tid, int signal);
33 #if defined(_POSIX_VERSION) || defined(__native_client__)
37 #include <sys/resource.h>
39 #if defined(__native_client__)
40 void nacl_shutdown_gc_thread(void);
44 thread_handle_create (void)
46 MonoW32HandleThread thread_data;
47 gpointer thread_handle;
49 thread_data.id = pthread_self ();
50 thread_data.owned_mutexes = g_ptr_array_new ();
51 thread_data.priority = MONO_THREAD_PRIORITY_NORMAL;
53 thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, (gpointer) &thread_data);
54 if (thread_handle == INVALID_HANDLE_VALUE)
57 /* We need to keep the handle alive, as long as the corresponding managed
58 * thread object is alive. The handle is going to be unref when calling
59 * the finalizer on the MonoThreadInternal object */
60 mono_w32handle_ref (thread_handle);
66 win32_priority_to_posix_priority (MonoThreadPriority priority, int policy)
68 g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
69 g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
71 /* Necessary to get valid priority range */
72 #ifdef _POSIX_PRIORITY_SCHEDULING
75 min = sched_get_priority_min (policy);
76 max = sched_get_priority_max (policy);
78 /* Partition priority range linearly (cross-multiply) */
79 if (max > 0 && min >= 0 && max > min)
80 return (int)((double) priority * (max - min) / (MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST));
98 void *(*start_routine)(void*);
102 MonoCoopSem registered;
107 inner_start_thread (void *arg)
109 StartInfo *start_info = (StartInfo *) arg;
110 void *t_arg = start_info->arg;
112 void *(*start_func)(void*) = start_info->start_routine;
113 guint32 flags = start_info->flags;
116 MonoThreadInfo *info;
118 /* Register the thread with the io-layer */
119 handle = thread_handle_create ();
121 mono_coop_sem_post (&(start_info->registered));
124 start_info->handle = handle;
126 info = mono_thread_info_attach (&result);
128 info->runtime_thread = TRUE;
129 info->handle = handle;
131 mono_threads_platform_set_priority (info, start_info->priority);
133 if (flags & CREATE_SUSPENDED) {
134 info->create_suspended = TRUE;
135 mono_coop_sem_init (&info->create_suspended_sem, 0);
138 /* start_info is not valid after this */
139 mono_coop_sem_post (&(start_info->registered));
142 if (flags & CREATE_SUSPENDED) {
143 res = mono_coop_sem_wait (&info->create_suspended_sem, MONO_SEM_FLAGS_NONE);
144 g_assert (res != -1);
146 mono_coop_sem_destroy (&info->create_suspended_sem);
149 /* Run the actual main function of the thread */
150 result = start_func (t_arg);
152 mono_threads_platform_exit (GPOINTER_TO_UINT (result));
153 g_assert_not_reached ();
157 mono_threads_platform_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, MonoThreadParm *tp, MonoNativeThreadId *out_tid)
162 StartInfo start_info;
165 struct sched_param sp;
167 res = pthread_attr_init (&attr);
170 if (tp->stack_size == 0) {
171 #if HAVE_VALGRIND_MEMCHECK_H
172 if (RUNNING_ON_VALGRIND)
173 stack_size = 1 << 20;
175 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
177 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
180 stack_size = tp->stack_size;
182 #ifdef PTHREAD_STACK_MIN
183 if (stack_size < PTHREAD_STACK_MIN)
184 stack_size = PTHREAD_STACK_MIN;
187 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
188 res = pthread_attr_setstacksize (&attr, stack_size);
193 * For policies that respect priorities set the prirority for the new thread
195 pthread_getschedparam(pthread_self(), &policy, &sp);
196 if ((policy == SCHED_FIFO) || (policy == SCHED_RR)) {
197 sp.sched_priority = win32_priority_to_posix_priority (tp->priority, policy);
198 res = pthread_attr_setschedparam (&attr, &sp);
201 memset (&start_info, 0, sizeof (StartInfo));
202 start_info.start_routine = (void *(*)(void *)) start_routine;
203 start_info.arg = arg;
204 start_info.flags = tp->creation_flags;
205 start_info.priority = tp->priority;
206 mono_coop_sem_init (&(start_info.registered), 0);
208 /* Actually start the thread */
209 res = mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
211 mono_coop_sem_destroy (&(start_info.registered));
215 /* Wait until the thread register itself in various places */
216 res = mono_coop_sem_wait (&start_info.registered, MONO_SEM_FLAGS_NONE);
217 g_assert (res != -1);
219 mono_coop_sem_destroy (&(start_info.registered));
224 return start_info.handle;
228 * mono_threads_platform_resume_created:
230 * Resume a newly created thread created using CREATE_SUSPENDED.
233 mono_threads_platform_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
235 mono_coop_sem_post (&info->create_suspended_sem);
239 mono_threads_platform_yield (void)
241 return sched_yield () == 0;
245 mono_threads_platform_exit (int exit_code)
247 MonoThreadInfo *current = mono_thread_info_current ();
249 #if defined(__native_client__)
250 nacl_shutdown_gc_thread();
253 mono_threads_platform_set_exited (current);
255 mono_thread_info_detach ();
261 mono_threads_platform_unregister (MonoThreadInfo *info)
264 mono_threads_platform_set_exited (info);
270 mono_threads_platform_open_handle (void)
272 MonoThreadInfo *info;
274 info = mono_thread_info_current ();
278 info->handle = thread_handle_create ();
280 mono_w32handle_ref (info->handle);
285 mono_threads_get_max_stack_size (void)
289 /* If getrlimit fails, we don't enforce any limits. */
290 if (getrlimit (RLIMIT_STACK, &lim))
292 /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
293 if (lim.rlim_max > (rlim_t)INT_MAX)
295 return (int)lim.rlim_max;
299 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
301 mono_w32handle_ref (handle);
307 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
309 THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
310 #ifdef USE_TKILL_ON_ANDROID
311 int result, old_errno = errno;
312 result = tkill (info->native_handle, signum);
318 #elif defined(__native_client__)
319 /* Workaround pthread_kill abort() in NaCl glibc. */
321 #elif !defined(HAVE_PTHREAD_KILL)
322 g_error ("pthread_kill() is not supported by this platform");
324 return pthread_kill (mono_thread_info_get_tid (info), signum);
329 mono_native_thread_id_get (void)
331 return pthread_self ();
335 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
337 return pthread_equal (id1, id2);
341 * mono_native_thread_create:
343 * Low level thread creation function without any GC wrappers.
346 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
348 return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
352 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
356 * We can't set the thread name for other threads, but we can at least make
357 * it work for threads that try to change their own name.
359 if (tid != mono_native_thread_id_get ())
363 pthread_setname_np ("");
367 strncpy (n, name, 63);
369 pthread_setname_np (n);
371 #elif defined (__NetBSD__)
373 pthread_setname_np (tid, "%s", (void*)"");
375 char n [PTHREAD_MAX_NAMELEN_NP];
377 strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
378 n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
379 pthread_setname_np (tid, "%s", (void*)n);
381 #elif defined (HAVE_PTHREAD_SETNAME_NP)
383 pthread_setname_np (tid, "");
387 strncpy (n, name, 16);
389 pthread_setname_np (tid, n);
395 mono_threads_platform_set_exited (MonoThreadInfo *info)
397 MonoW32HandleThread *thread_data;
398 gpointer mutex_handle;
403 if (!info->handle || mono_w32handle_issignalled (info->handle) || mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED) {
404 /* We must have already deliberately finished
405 * with this thread, so don't do any more now */
409 if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
410 g_error ("unknown thread handle %p", info->handle);
412 pid = wapi_getpid ();
413 tid = pthread_self ();
415 for (i = 0; i < thread_data->owned_mutexes->len; i++) {
416 mutex_handle = g_ptr_array_index (thread_data->owned_mutexes, i);
417 wapi_mutex_abandon (mutex_handle, pid, tid);
418 mono_thread_info_disown_mutex (info, mutex_handle);
421 g_ptr_array_free (thread_data->owned_mutexes, TRUE);
423 thr_ret = mono_w32handle_lock_handle (info->handle);
424 g_assert (thr_ret == 0);
426 mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
428 thr_ret = mono_w32handle_unlock_handle (info->handle);
429 g_assert (thr_ret == 0);
431 /* The thread is no longer active, so unref it */
432 mono_w32handle_unref (info->handle);
438 mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
440 MonoW32HandleThread *thread_data;
443 g_assert (info->handle);
445 if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
446 g_error ("unknown thread handle %p", info->handle);
448 g_string_append_printf (text, "thread handle %p state : ", info->handle);
450 mono_thread_info_describe_interrupt_token (info, text);
452 g_string_append_printf (text, ", owns (");
453 for (i = 0; i < thread_data->owned_mutexes->len; i++)
454 g_string_append_printf (text, i > 0 ? ", %p" : "%p", g_ptr_array_index (thread_data->owned_mutexes, i));
455 g_string_append_printf (text, ")");
459 mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
461 MonoW32HandleThread *thread_data;
463 g_assert (info->handle);
465 if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
466 g_error ("unknown thread handle %p", info->handle);
468 mono_w32handle_ref (mutex_handle);
470 g_ptr_array_add (thread_data->owned_mutexes, mutex_handle);
474 mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
476 MonoW32HandleThread *thread_data;
478 g_assert (info->handle);
480 if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
481 g_error ("unknown thread handle %p", info->handle);
483 mono_w32handle_unref (mutex_handle);
485 g_ptr_array_remove (thread_data->owned_mutexes, mutex_handle);
489 mono_threads_platform_get_priority (MonoThreadInfo *info)
491 MonoW32HandleThread *thread_data;
493 g_assert (info->handle);
495 if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer *)&thread_data))
496 return MONO_THREAD_PRIORITY_NORMAL;
498 return thread_data->priority;
502 mono_threads_platform_set_priority (MonoThreadInfo *info, MonoThreadPriority priority)
504 MonoW32HandleThread *thread_data;
505 int policy, posix_priority;
506 struct sched_param param;
508 g_assert (info->handle);
510 if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
513 switch (pthread_getschedparam (thread_data->id, &policy, ¶m)) {
517 g_warning ("pthread_getschedparam: error looking up thread id %x", (gsize)thread_data->id);
523 posix_priority = win32_priority_to_posix_priority (priority, policy);
524 if (posix_priority < 0)
527 param.sched_priority = posix_priority;
528 switch (pthread_setschedparam (thread_data->id, policy, ¶m)) {
532 g_warning ("%s: pthread_setschedprio: error looking up thread id %x", __func__, (gsize)thread_data->id);
535 g_warning ("%s: priority %d not supported", __func__, priority);
538 g_warning ("%s: permission denied", __func__);
544 thread_data->priority = priority;
549 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
551 #if defined(USE_POSIX_BACKEND)
554 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
556 int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () : mono_threads_posix_get_suspend_signal ();
558 if (!mono_threads_pthread_kill (info, sig)) {
559 mono_threads_add_to_pending_operation_set (info);
566 mono_threads_suspend_check_suspend_result (MonoThreadInfo *info)
568 return info->suspend_can_continue;
572 This begins async resume. This function must do the following:
574 - Install an async target if one was requested.
575 - Notify the target to resume.
578 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
580 mono_threads_add_to_pending_operation_set (info);
581 return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
585 mono_threads_suspend_register (MonoThreadInfo *info)
587 #if defined (PLATFORM_ANDROID)
588 info->native_handle = gettid ();
591 g_assert (!info->handle);
592 info->handle = thread_handle_create ();
596 mono_threads_suspend_free (MonoThreadInfo *info)
601 mono_threads_suspend_init (void)
603 mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
606 #endif /* defined(USE_POSIX_BACKEND) */