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>
23 #include <mono/metadata/gc-internal.h>
28 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
29 #define USE_TKILL_ON_ANDROID 1
32 #ifdef USE_TKILL_ON_ANDROID
33 extern int tkill (pid_t tid, int signal);
36 #if defined(_POSIX_VERSION) || defined(__native_client__)
37 #include <sys/resource.h>
40 #if defined(__native_client__)
41 void nacl_shutdown_gc_thread(void);
45 void *(*start_routine)(void*);
48 MonoSemType registered;
53 inner_start_thread (void *arg)
55 StartInfo *start_info = (StartInfo *) arg;
56 void *t_arg = start_info->arg;
58 void *(*start_func)(void*) = start_info->start_routine;
59 guint32 flags = start_info->flags;
64 /* Register the thread with the io-layer */
65 handle = wapi_create_thread_handle ();
67 res = MONO_SEM_POST (&(start_info->registered));
71 start_info->handle = handle;
73 info = mono_thread_info_attach (&result);
76 info->runtime_thread = TRUE;
77 info->handle = handle;
79 if (flags & CREATE_SUSPENDED) {
80 info->create_suspended = TRUE;
81 MONO_SEM_INIT (&info->create_suspended_sem, 0);
84 /* start_info is not valid after this */
85 res = MONO_SEM_POST (&(start_info->registered));
89 if (flags & CREATE_SUSPENDED) {
90 while (MONO_SEM_WAIT (&info->create_suspended_sem) != 0 &&
92 MONO_SEM_DESTROY (&info->create_suspended_sem);
96 /* Run the actual main function of the thread */
97 result = start_func (t_arg);
99 mono_threads_core_exit (GPOINTER_TO_UINT (result));
100 g_assert_not_reached ();
104 mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
109 StartInfo start_info;
111 res = pthread_attr_init (&attr);
114 if (stack_size == 0) {
115 #if HAVE_VALGRIND_MEMCHECK_H
116 if (RUNNING_ON_VALGRIND)
117 stack_size = 1 << 20;
119 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
121 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
125 #ifdef PTHREAD_STACK_MIN
126 if (stack_size < PTHREAD_STACK_MIN)
127 stack_size = PTHREAD_STACK_MIN;
130 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
131 res = pthread_attr_setstacksize (&attr, stack_size);
135 memset (&start_info, 0, sizeof (StartInfo));
136 start_info.start_routine = (void *(*)(void *)) start_routine;
137 start_info.arg = arg;
138 start_info.flags = creation_flags;
139 MONO_SEM_INIT (&(start_info.registered), 0);
141 /* Actually start the thread */
142 res = mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
144 MONO_SEM_DESTROY (&(start_info.registered));
148 /* Wait until the thread register itself in various places */
149 while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
150 /*if (EINTR != errno) ABORT("sem_wait failed"); */
152 MONO_SEM_DESTROY (&(start_info.registered));
157 return start_info.handle;
161 * mono_threads_core_resume_created:
163 * Resume a newly created thread created using CREATE_SUSPENDED.
166 mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
168 MONO_SEM_POST (&info->create_suspended_sem);
172 mono_threads_core_yield (void)
174 return sched_yield () == 0;
178 mono_threads_core_exit (int exit_code)
180 MonoThreadInfo *current = mono_thread_info_current ();
182 #if defined(__native_client__)
183 nacl_shutdown_gc_thread();
186 wapi_thread_handle_set_exited (current->handle, exit_code);
188 mono_thread_info_detach ();
194 mono_threads_core_unregister (MonoThreadInfo *info)
197 wapi_thread_handle_set_exited (info->handle, 0);
203 mono_threads_core_open_handle (void)
205 MonoThreadInfo *info;
207 info = mono_thread_info_current ();
211 info->handle = wapi_create_thread_handle ();
213 wapi_ref_thread_handle (info->handle);
218 mono_threads_get_max_stack_size (void)
222 /* If getrlimit fails, we don't enforce any limits. */
223 if (getrlimit (RLIMIT_STACK, &lim))
225 /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
226 if (lim.rlim_max > (rlim_t)INT_MAX)
228 return (int)lim.rlim_max;
232 mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
234 wapi_ref_thread_handle (handle);
240 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
242 THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
243 #ifdef USE_TKILL_ON_ANDROID
244 int result, old_errno = errno;
245 result = tkill (info->native_handle, signum);
251 #elif defined(__native_client__)
252 /* Workaround pthread_kill abort() in NaCl glibc. */
254 #elif !defined(HAVE_PTHREAD_KILL)
255 g_error ("pthread_kill() is not supported by this platform");
257 return pthread_kill (mono_thread_info_get_tid (info), signum);
262 mono_native_thread_id_get (void)
264 return pthread_self ();
268 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
270 return pthread_equal (id1, id2);
274 * mono_native_thread_create:
276 * Low level thread creation function without any GC wrappers.
279 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
281 return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
285 mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
287 #if defined (HAVE_PTHREAD_SETNAME_NP) && !defined (__MACH__)
289 pthread_setname_np (tid, "");
293 strncpy (n, name, 16);
295 pthread_setname_np (tid, n);
301 #if defined (USE_POSIX_BACKEND) && !defined (USE_COOP_GC)
303 static int suspend_signal_num;
304 static int restart_signal_num;
305 static int abort_signal_num;
306 static sigset_t suspend_signal_mask;
307 static sigset_t suspend_ack_signal_mask;
310 #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
311 #define DEFAULT_SUSPEND_SIGNAL SIGXFSZ
313 #define DEFAULT_SUSPEND_SIGNAL SIGPWR
315 #define DEFAULT_RESTART_SIGNAL SIGXCPU
318 mono_thread_search_alt_signal (int min_signal)
320 #if !defined (SIGRTMIN)
321 g_error ("signal search only works with RTMIN");
324 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
325 for (i = MAX (min_signal, SIGRTMIN) + 1; i < SIGRTMAX; ++i) {
326 struct sigaction sinfo;
327 sigaction (i, NULL, &sinfo);
328 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
332 g_error ("Could not find an available signal");
337 mono_thread_get_alt_suspend_signal (void)
339 #if defined(PLATFORM_ANDROID)
341 #elif !defined (SIGRTMIN)
348 static int suspend_signum = -1;
349 if (suspend_signum == -1)
350 suspend_signum = mono_thread_search_alt_signal (-1);
351 return suspend_signum;
352 #endif /* SIGRTMIN */
356 mono_thread_get_alt_resume_signal (void)
358 #if defined(PLATFORM_ANDROID)
360 #elif !defined (SIGRTMIN)
367 static int resume_signum = -1;
368 if (resume_signum == -1)
369 resume_signum = mono_thread_search_alt_signal (mono_thread_get_alt_suspend_signal () + 1);
370 return resume_signum;
371 #endif /* SIGRTMIN */
376 mono_threads_get_abort_signal (void)
378 #if defined(PLATFORM_ANDROID)
380 #elif !defined (SIGRTMIN)
385 #endif /* SIGRTMIN */
387 static int abort_signum = -1;
388 if (abort_signum == -1)
389 abort_signum = mono_thread_search_alt_signal (mono_thread_get_alt_resume_signal () + 1);
391 #endif /* SIGRTMIN */
395 #if !defined(__native_client__)
397 restart_signal_handler (int _dummy, siginfo_t *_info, void *context)
399 MonoThreadInfo *info;
400 int old_errno = errno;
402 info = mono_thread_info_current ();
403 info->signal = restart_signal_num;
408 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
410 int old_errno = errno;
411 int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
414 MonoThreadInfo *current = mono_thread_info_current ();
417 THREADS_SUSPEND_DEBUG ("SIGNAL HANDLER FOR %p [%p]\n", current, (void*)current->native_handle);
418 if (current->syscall_break_signal) {
419 current->syscall_break_signal = FALSE;
420 THREADS_SUSPEND_DEBUG ("\tsyscall break for %p\n", current);
421 mono_threads_notify_initiator_of_abort (current);
425 /* Have we raced with self suspend? */
426 if (!mono_threads_transition_finish_async_suspend (current)) {
427 current->suspend_can_continue = TRUE;
428 THREADS_SUSPEND_DEBUG ("\tlost race with self suspend %p\n", current);
432 ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (¤t->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX], context);
434 /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
435 current->suspend_can_continue = ret;
439 Block the restart signal.
440 We need to block the restart signal while posting to the suspend_ack semaphore or we race to sigsuspend,
441 which might miss the signal and get stuck.
443 pthread_sigmask (SIG_BLOCK, &suspend_ack_signal_mask, NULL);
445 /* We're done suspending */
446 mono_threads_notify_initiator_of_suspend (current);
448 /* This thread is doomed, all we can do is give up and let the suspender recover. */
450 THREADS_SUSPEND_DEBUG ("\tThread is dying, failed to capture state %p\n", current);
451 mono_threads_transition_async_suspend_compensation (current);
452 /* Unblock the restart signal. */
453 pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
460 sigsuspend (&suspend_signal_mask);
461 } while (current->signal != restart_signal_num);
463 /* Unblock the restart signal. */
464 pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);
466 if (current->async_target) {
467 #if MONO_ARCH_HAS_MONO_CONTEXT
468 MonoContext tmp = current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
469 mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
470 current->async_target = current->user_data = NULL;
471 mono_monoctx_to_sigctx (&tmp, context);
473 g_error ("The new interruption machinery requires a working mono-context");
477 /* We're done resuming */
478 mono_threads_notify_initiator_of_resume (current);
481 mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
486 abort_signal_handler (int _dummy, siginfo_t *info, void *context)
488 suspend_signal_handler (_dummy, info, context);
494 mono_posix_add_signal_handler (int signo, gpointer handler, int flags)
496 #if !defined(__native_client__)
497 /*FIXME, move the code from mini to utils and do the right thing!*/
499 struct sigaction previous_sa;
502 sa.sa_sigaction = handler;
503 sigfillset (&sa.sa_mask);
505 sa.sa_flags = SA_SIGINFO | flags;
506 ret = sigaction (signo, &sa, &previous_sa);
508 g_assert (ret != -1);
513 mono_threads_init_platform (void)
517 abort_signal_num = mono_threads_get_abort_signal ();
518 if (mono_thread_info_unified_management_enabled ()) {
519 suspend_signal_num = DEFAULT_SUSPEND_SIGNAL;
520 restart_signal_num = DEFAULT_RESTART_SIGNAL;
522 suspend_signal_num = mono_thread_get_alt_suspend_signal ();
523 restart_signal_num = mono_thread_get_alt_resume_signal ();
526 sigfillset (&suspend_signal_mask);
527 sigdelset (&suspend_signal_mask, restart_signal_num);
529 sigemptyset (&suspend_ack_signal_mask);
530 sigaddset (&suspend_ack_signal_mask, restart_signal_num);
532 mono_posix_add_signal_handler (suspend_signal_num, suspend_signal_handler, SA_RESTART);
533 mono_posix_add_signal_handler (restart_signal_num, restart_signal_handler, SA_RESTART);
534 mono_posix_add_signal_handler (abort_signal_num, abort_signal_handler, 0);
536 /* ensure all the new signals are unblocked */
537 sigemptyset (&signal_set);
538 sigaddset (&signal_set, suspend_signal_num);
539 sigaddset (&signal_set, restart_signal_num);
540 sigaddset (&signal_set, abort_signal_num);
541 sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
545 mono_threads_core_abort_syscall (MonoThreadInfo *info)
548 We signal a thread to break it from the urrent syscall.
549 This signal should not be interpreted as a suspend request.
551 info->syscall_break_signal = TRUE;
552 if (!mono_threads_pthread_kill (info, abort_signal_num))
553 mono_threads_add_to_pending_operation_set (info);
557 mono_threads_core_needs_abort_syscall (void)
563 mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
565 int sig = interrupt_kernel ? abort_signal_num : suspend_signal_num;
567 if (!mono_threads_pthread_kill (info, sig)) {
568 mono_threads_add_to_pending_operation_set (info);
575 mono_threads_core_check_suspend_result (MonoThreadInfo *info)
577 return info->suspend_can_continue;
581 This begins async resume. This function must do the following:
583 - Install an async target if one was requested.
584 - Notify the target to resume.
587 mono_threads_core_begin_async_resume (MonoThreadInfo *info)
589 mono_threads_add_to_pending_operation_set (info);
590 return mono_threads_pthread_kill (info, restart_signal_num) == 0;
594 mono_threads_platform_register (MonoThreadInfo *info)
596 #if defined (PLATFORM_ANDROID)
597 info->native_handle = gettid ();
602 mono_threads_platform_free (MonoThreadInfo *info)
607 mono_threads_core_begin_global_suspend (void)
612 mono_threads_core_end_global_suspend (void)
616 #endif /*defined (USE_POSIX_BACKEND)*/