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-compiler.h>
18 #include <mono/utils/mono-semaphore.h>
19 #include <mono/utils/mono-threads.h>
20 #include <mono/utils/mono-tls.h>
21 #include <mono/utils/mono-mmap.h>
22 #include <mono/metadata/threads-types.h>
27 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
28 #define USE_TKILL_ON_ANDROID 1
31 #ifdef USE_TKILL_ON_ANDROID
32 extern int tkill (pid_t tid, int signal);
35 #if defined(_POSIX_VERSION) || defined(__native_client__)
36 #include <sys/resource.h>
39 #if defined(__native_client__)
40 void nacl_shutdown_gc_thread(void);
44 void *(*start_routine)(void*);
47 MonoSemType registered;
52 inner_start_thread (void *arg)
54 StartInfo *start_info = arg;
55 void *t_arg = start_info->arg;
57 void *(*start_func)(void*) = start_info->start_routine;
58 guint32 flags = start_info->flags;
63 /* Register the thread with the io-layer */
64 handle = wapi_create_thread_handle ();
66 res = MONO_SEM_POST (&(start_info->registered));
70 start_info->handle = handle;
72 info = mono_thread_info_attach (&result);
73 info->runtime_thread = TRUE;
74 info->handle = handle;
76 if (flags & CREATE_SUSPENDED) {
77 info->create_suspended = TRUE;
78 MONO_SEM_INIT (&info->create_suspended_sem, 0);
81 /* start_info is not valid after this */
82 res = MONO_SEM_POST (&(start_info->registered));
86 if (flags & CREATE_SUSPENDED) {
87 while (MONO_SEM_WAIT (&info->create_suspended_sem) != 0 &&
89 MONO_SEM_DESTROY (&info->create_suspended_sem);
92 /* Run the actual main function of the thread */
93 result = start_func (t_arg);
96 mono_thread_info_detach ();
99 #if defined(__native_client__)
100 nacl_shutdown_gc_thread();
103 wapi_thread_handle_set_exited (handle, GPOINTER_TO_UINT (result));
104 /* This is needed by mono_threads_core_unregister () which is called later */
107 g_assert (mono_threads_get_callbacks ()->thread_exit);
108 mono_threads_get_callbacks ()->thread_exit (NULL);
109 g_assert_not_reached ();
114 mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
119 StartInfo start_info;
121 res = pthread_attr_init (&attr);
124 if (stack_size == 0) {
125 #if HAVE_VALGRIND_MEMCHECK_H
126 if (RUNNING_ON_VALGRIND)
127 stack_size = 1 << 20;
129 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
131 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
135 #ifdef PTHREAD_STACK_MIN
136 if (stack_size < PTHREAD_STACK_MIN)
137 stack_size = PTHREAD_STACK_MIN;
140 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
141 res = pthread_attr_setstacksize (&attr, stack_size);
145 memset (&start_info, 0, sizeof (StartInfo));
146 start_info.start_routine = (gpointer)start_routine;
147 start_info.arg = arg;
148 start_info.flags = creation_flags;
149 MONO_SEM_INIT (&(start_info.registered), 0);
151 /* Actually start the thread */
152 res = mono_threads_get_callbacks ()->mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
154 MONO_SEM_DESTROY (&(start_info.registered));
158 /* Wait until the thread register itself in various places */
159 while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
160 /*if (EINTR != errno) ABORT("sem_wait failed"); */
162 MONO_SEM_DESTROY (&(start_info.registered));
167 return start_info.handle;
171 * mono_threads_core_resume_created:
173 * Resume a newly created thread created using CREATE_SUSPENDED.
176 mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
178 MONO_SEM_POST (&info->create_suspended_sem);
182 mono_threads_core_yield (void)
184 return sched_yield () == 0;
188 mono_threads_core_exit (int exit_code)
190 MonoThreadInfo *current = mono_thread_info_current ();
192 #if defined(__native_client__)
193 nacl_shutdown_gc_thread();
196 wapi_thread_handle_set_exited (current->handle, exit_code);
198 g_assert (mono_threads_get_callbacks ()->thread_exit);
199 mono_threads_get_callbacks ()->thread_exit (NULL);
203 mono_threads_core_unregister (MonoThreadInfo *info)
206 wapi_thread_handle_set_exited (info->handle, 0);
212 mono_threads_core_open_handle (void)
214 MonoThreadInfo *info;
216 info = mono_thread_info_current ();
220 info->handle = wapi_create_thread_handle ();
222 wapi_ref_thread_handle (info->handle);
227 mono_threads_get_max_stack_size (void)
231 /* If getrlimit fails, we don't enforce any limits. */
232 if (getrlimit (RLIMIT_STACK, &lim))
234 /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
235 if (lim.rlim_max > (rlim_t)INT_MAX)
237 return (int)lim.rlim_max;
241 mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
243 wapi_ref_thread_handle (handle);
249 mono_threads_core_prepare_interrupt (HANDLE thread_handle)
251 return wapi_prepare_interrupt_thread (thread_handle);
255 mono_threads_core_finish_interrupt (gpointer wait_handle)
257 wapi_finish_interrupt_thread (wait_handle);
261 mono_threads_core_self_interrupt (void)
263 wapi_self_interrupt ();
267 mono_threads_core_clear_interruption (void)
269 wapi_clear_interruption ();
273 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
275 THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
276 #ifdef USE_TKILL_ON_ANDROID
277 int result, old_errno = errno;
278 result = tkill (info->native_handle, signum);
284 #elif defined(__native_client__)
285 /* Workaround pthread_kill abort() in NaCl glibc. */
288 return pthread_kill (mono_thread_info_get_tid (info), signum);
293 #if defined (USE_POSIX_BACKEND)
295 static int suspend_signal_num;
296 static int restart_signal_num;
297 static int abort_signal_num;
298 static sigset_t suspend_signal_mask;
299 static sigset_t suspend_ack_signal_mask;
302 #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
303 #define DEFAULT_SUSPEND_SIGNAL SIGXFSZ
305 #define DEFAULT_SUSPEND_SIGNAL SIGPWR
307 #define DEFAULT_RESTART_SIGNAL SIGXCPU
310 mono_thread_search_alt_signal (int min_signal)
312 #if !defined (SIGRTMIN)
313 g_error ("signal search only works with RTMIN");
316 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
317 for (i = MAX (min_signal, SIGRTMIN) + 1; i < SIGRTMAX; ++i) {
318 struct sigaction sinfo;
319 sigaction (i, NULL, &sinfo);
320 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
324 g_error ("Could not find an available signal");
329 mono_thread_get_alt_suspend_signal (void)
331 #if defined(PLATFORM_ANDROID)
333 #elif !defined (SIGRTMIN)
340 static int suspend_signum = -1;
341 if (suspend_signum == -1)
342 suspend_signum = mono_thread_search_alt_signal (-1);
343 return suspend_signum;
344 #endif /* SIGRTMIN */
348 mono_thread_get_alt_resume_signal (void)
350 #if defined(PLATFORM_ANDROID)
352 #elif !defined (SIGRTMIN)
359 static int resume_signum = -1;
360 if (resume_signum == -1)
361 resume_signum = mono_thread_search_alt_signal (mono_thread_get_alt_suspend_signal () + 1);
362 return resume_signum;
363 #endif /* SIGRTMIN */
368 mono_threads_get_abort_signal (void)
370 #if defined(PLATFORM_ANDROID)
372 #elif !defined (SIGRTMIN)
377 #endif /* SIGRTMIN */
379 static int abort_signum = -1;
380 if (abort_signum == -1)
381 abort_signum = mono_thread_search_alt_signal (mono_thread_get_alt_resume_signal () + 1);
383 #endif /* SIGRTMIN */
387 #if !defined(__native_client__)
389 restart_signal_handler (int _dummy, siginfo_t *_info, void *context)
391 MonoThreadInfo *info;
392 int old_errno = errno;
394 info = mono_thread_info_current ();
395 info->signal = restart_signal_num;
400 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
402 int old_errno = errno;
403 int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
406 MonoThreadInfo *current = mono_thread_info_current ();
409 THREADS_SUSPEND_DEBUG ("SIGNAL HANDLER FOR %p [%p]\n", current, (void*)current->native_handle);
410 if (current->syscall_break_signal) {
411 current->syscall_break_signal = FALSE;
412 THREADS_SUSPEND_DEBUG ("\tsyscall break for %p\n", current);
416 /* Have we raced with self suspend? */
417 if (!mono_threads_transition_finish_async_suspend (current)) {
418 current->suspend_can_continue = TRUE;
419 THREADS_SUSPEND_DEBUG ("\tlost race with self suspend %p\n", current);
423 ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (¤t->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX], context);
425 /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
426 current->suspend_can_continue = ret;
430 Block the restart signal.
431 We need to block the restart signal while posting to the suspend_ack semaphore or we race to sigsuspend,
432 which might miss the signal and get stuck.
434 pthread_sigmask (SIG_BLOCK, &suspend_ack_signal_mask, NULL);
436 /* We're done suspending */
437 mono_threads_notify_initiator_of_suspend (current);
439 /* This thread is doomed, all we can do is give up and let the suspender recover. */
441 THREADS_SUSPEND_DEBUG ("\tThread is dying, failed to capture state %p\n", current);
442 mono_threads_transition_async_suspend_compensation (current);
443 /* Unblock the restart signal. */
444 pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
451 sigsuspend (&suspend_signal_mask);
452 } while (current->signal != restart_signal_num);
454 /* Unblock the restart signal. */
455 pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
457 if (current->async_target) {
458 #if MONO_ARCH_HAS_MONO_CONTEXT
459 MonoContext tmp = current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
460 mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
461 current->async_target = current->user_data = NULL;
462 mono_monoctx_to_sigctx (&tmp, context);
464 g_error ("The new interruption machinery requires a working mono-context");
468 /* We're done resuming */
469 mono_threads_notify_initiator_of_resume (current);
472 mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
477 abort_signal_handler (int _dummy, siginfo_t *info, void *context)
479 suspend_signal_handler (_dummy, info, context);
485 mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
487 #if !defined(__native_client__)
488 /*FIXME, move the code from mini to utils and do the right thing!*/
490 struct sigaction previous_sa;
493 sa.sa_sigaction = handler;
494 sigfillset (&sa.sa_mask);
496 sa.sa_flags = SA_SIGINFO | flags;
497 ret = sigaction (signo, &sa, &previous_sa);
499 g_assert (ret != -1);
504 mono_threads_init_platform (void)
508 abort_signal_num = mono_threads_get_abort_signal ();
509 if (mono_thread_info_unified_management_enabled ()) {
510 suspend_signal_num = DEFAULT_SUSPEND_SIGNAL;
511 restart_signal_num = DEFAULT_RESTART_SIGNAL;
513 suspend_signal_num = mono_thread_get_alt_suspend_signal ();
514 restart_signal_num = mono_thread_get_alt_resume_signal ();
517 sigfillset (&suspend_signal_mask);
518 sigdelset (&suspend_signal_mask, restart_signal_num);
520 sigemptyset (&suspend_ack_signal_mask);
521 sigaddset (&suspend_ack_signal_mask, restart_signal_num);
523 mono_posix_add_signal_handler (suspend_signal_num, suspend_signal_handler, SA_RESTART);
524 mono_posix_add_signal_handler (restart_signal_num, restart_signal_handler, SA_RESTART);
525 mono_posix_add_signal_handler (abort_signal_num, abort_signal_handler, 0);
527 /* ensure all the new signals are unblocked */
528 sigemptyset (&signal_set);
529 sigaddset (&signal_set, suspend_signal_num);
530 sigaddset (&signal_set, restart_signal_num);
531 sigaddset (&signal_set, abort_signal_num);
532 sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
536 mono_threads_core_abort_syscall (MonoThreadInfo *info)
539 We signal a thread to break it from the urrent syscall.
540 This signal should not be interpreted as a suspend request.
542 info->syscall_break_signal = TRUE;
543 mono_threads_pthread_kill (info, abort_signal_num);
547 mono_threads_core_needs_abort_syscall (void)
553 mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
555 int sig = interrupt_kernel ? abort_signal_num : suspend_signal_num;
557 if (!mono_threads_pthread_kill (info, sig)) {
558 mono_threads_add_to_pending_operation_set (info);
565 mono_threads_core_check_suspend_result (MonoThreadInfo *info)
567 return info->suspend_can_continue;
571 This begins async resume. This function must do the following:
573 - Install an async target if one was requested.
574 - Notify the target to resume.
577 mono_threads_core_begin_async_resume (MonoThreadInfo *info)
579 mono_threads_add_to_pending_operation_set (info);
580 return mono_threads_pthread_kill (info, restart_signal_num) == 0;
584 mono_threads_platform_register (MonoThreadInfo *info)
586 #if defined (PLATFORM_ANDROID)
587 info->native_handle = gettid ();
592 mono_threads_platform_free (MonoThreadInfo *info)
597 mono_native_thread_id_get (void)
599 return pthread_self ();
603 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
605 return pthread_equal (id1, id2);
609 * mono_native_thread_create:
611 * Low level thread creation function without any GC wrappers.
614 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
616 return pthread_create (tid, NULL, func, arg) == 0;
620 mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
622 #if defined (HAVE_PTHREAD_SETNAME_NP) && !defined (__MACH__)
624 pthread_setname_np (tid, "");
628 strncpy (n, name, 16);
630 pthread_setname_np (tid, n);
635 #endif /*defined (USE_POSIX_BACKEND)*/