2 * mini-posix.c: POSIX signal handling support for Mono.
5 * Mono Team (mono-list@lists.ximian.com)
7 * Copyright 2001-2003 Ximian, Inc.
8 * Copyright 2003-2008 Ximian, Inc.
9 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11 * See LICENSE for licensing information.
22 #ifdef HAVE_SYS_TIME_H
25 #ifdef HAVE_SYS_SYSCALL_H
26 #include <sys/syscall.h>
31 #include <mono/metadata/assembly.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/tabledefs.h>
34 #include <mono/metadata/class.h>
35 #include <mono/metadata/object.h>
36 #include <mono/metadata/tokentype.h>
37 #include <mono/metadata/tabledefs.h>
38 #include <mono/metadata/threads.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/io-layer/io-layer.h>
42 #include "mono/metadata/profiler.h"
43 #include <mono/metadata/profiler-private.h>
44 #include <mono/metadata/mono-config.h>
45 #include <mono/metadata/environment.h>
46 #include <mono/metadata/mono-debug.h>
47 #include <mono/metadata/gc-internal.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/metadata/verify.h>
50 #include <mono/metadata/verify-internals.h>
51 #include <mono/metadata/mempool-internals.h>
52 #include <mono/metadata/attach.h>
53 #include <mono/utils/mono-math.h>
54 #include <mono/utils/mono-compiler.h>
55 #include <mono/utils/mono-counters.h>
56 #include <mono/utils/mono-logger-internal.h>
57 #include <mono/utils/mono-mmap.h>
58 #include <mono/utils/dtrace.h>
59 #include <mono/utils/mono-signal-handler.h>
60 #include <mono/utils/mono-threads.h>
67 #include "debugger-agent.h"
69 #include "jit-icalls.h"
71 #if defined(__native_client__)
74 mono_runtime_setup_stat_profiler (void)
76 printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
81 mono_runtime_shutdown_stat_profiler (void)
87 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
93 mono_runtime_install_handlers (void)
98 mono_runtime_shutdown_handlers (void)
103 mono_runtime_cleanup_handlers (void)
108 mono_runtime_syscall_fork (void)
110 g_assert_not_reached();
115 mono_gdb_render_native_backtraces (pid_t crashed_pid)
121 static GHashTable *mono_saved_signal_handlers = NULL;
124 get_saved_signal_handler (int signo)
126 if (mono_saved_signal_handlers)
127 /* The hash is only modified during startup, so no need for locking */
128 return g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
133 save_old_signal_handler (int signo, struct sigaction *old_action)
135 struct sigaction *handler_to_save = g_malloc (sizeof (struct sigaction));
137 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
138 "Saving old signal handler for signal %d.", signo);
140 if (! (old_action->sa_flags & SA_SIGINFO)) {
141 handler_to_save->sa_handler = old_action->sa_handler;
143 #ifdef MONO_ARCH_USE_SIGACTION
144 handler_to_save->sa_sigaction = old_action->sa_sigaction;
145 #endif /* MONO_ARCH_USE_SIGACTION */
147 handler_to_save->sa_mask = old_action->sa_mask;
148 handler_to_save->sa_flags = old_action->sa_flags;
150 if (!mono_saved_signal_handlers)
151 mono_saved_signal_handlers = g_hash_table_new (NULL, NULL);
152 g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
156 free_saved_sig_handler_func (gpointer key, gpointer value, gpointer user_data)
162 free_saved_signal_handlers (void)
164 if (mono_saved_signal_handlers) {
165 g_hash_table_foreach (mono_saved_signal_handlers, free_saved_sig_handler_func, NULL);
166 g_hash_table_destroy (mono_saved_signal_handlers);
167 mono_saved_signal_handlers = NULL;
174 * Call the original signal handler for the signal given by the arguments, which
175 * should be the same as for a signal handler. Returns TRUE if the original handler
176 * was called, false otherwise.
179 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
181 int signal = MONO_SIG_HANDLER_GET_SIGNO ();
182 struct sigaction *saved_handler = get_saved_signal_handler (signal);
184 if (saved_handler && saved_handler->sa_handler) {
185 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
186 saved_handler->sa_handler (signal);
188 #ifdef MONO_ARCH_USE_SIGACTION
189 saved_handler->sa_sigaction (MONO_SIG_HANDLER_PARAMS);
190 #endif /* MONO_ARCH_USE_SIGACTION */
197 MONO_SIG_HANDLER_FUNC (static, sigabrt_signal_handler)
199 MonoJitInfo *ji = NULL;
200 MONO_SIG_HANDLER_GET_CONTEXT;
202 if (mono_thread_internal_current ())
203 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
205 if (mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
207 mono_handle_native_sigsegv (SIGABRT, ctx);
211 MONO_SIG_HANDLER_FUNC (static, sigusr1_signal_handler)
213 gboolean running_managed;
215 MonoInternalThread *thread = mono_thread_internal_current ();
216 MonoDomain *domain = mono_domain_get ();
218 MONO_SIG_HANDLER_GET_CONTEXT;
220 if (!thread || !domain) {
221 /* The thread might not have started up yet */
222 /* FIXME: Specify the synchronization with start_wrapper () in threads.c */
223 mono_debugger_agent_thread_interrupt (ctx, NULL);
227 if (thread->ignore_next_signal) {
228 thread->ignore_next_signal = FALSE;
232 if (thread->thread_dump_requested) {
233 thread->thread_dump_requested = FALSE;
235 mono_print_thread_dump (ctx);
239 * This is an async signal, so the code below must not call anything which
240 * is not async safe. That includes the pthread locking functions. If we
241 * know that we interrupted managed code, then locking is safe.
244 * On OpenBSD, ctx can be NULL if we are interrupting poll ().
247 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
248 running_managed = ji != NULL;
250 if (mono_debugger_agent_thread_interrupt (ctx, ji))
253 running_managed = FALSE;
256 /* We can't do handler block checking from metadata since it requires doing
257 * a stack walk with context.
259 * FIXME add full-aot support.
261 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
262 if (!mono_aot_only && ctx) {
263 MonoThreadUnwindState unwind_state;
264 if (mono_thread_state_init_from_sigctx (&unwind_state, ctx)) {
265 if (mono_install_handler_block_guard (&unwind_state)) {
267 /*Clear current thread from been wapi interrupted otherwise things can go south*/
268 wapi_clear_interruption ();
276 exc = mono_thread_request_interruption (running_managed);
280 mono_arch_handle_exception (ctx, exc);
284 #if defined(__i386__) || defined(__x86_64__)
285 #define FULL_STAT_PROFILER_BACKTRACE 1
286 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
287 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
288 #if MONO_ARCH_STACK_GROWS_UP
289 #define IS_BEFORE_ON_STACK <
290 #define IS_AFTER_ON_STACK >
292 #define IS_BEFORE_ON_STACK >
293 #define IS_AFTER_ON_STACK <
296 #define FULL_STAT_PROFILER_BACKTRACE 0
301 static int profiling_signal_in_use;
303 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
305 MONO_SIG_HANDLER_FUNC (static, sigprof_signal_handler)
307 if (mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
316 per_thread_profiler_hit (void *ctx)
318 int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
319 MonoProfilerCallChainStrategy call_chain_strategy = mono_profiler_stat_get_call_chain_strategy ();
321 if (call_chain_depth == 0) {
322 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
324 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
325 int current_frame_index = 1;
326 MonoContext mono_context;
327 guchar *ips [call_chain_depth + 1];
329 mono_sigctx_to_monoctx (ctx, &mono_context);
330 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
332 if (jit_tls != NULL) {
333 if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_NATIVE) {
334 #if FULL_STAT_PROFILER_BACKTRACE
335 guchar *current_frame;
336 guchar *stack_bottom;
339 stack_bottom = jit_tls->end_of_stack;
340 stack_top = MONO_CONTEXT_GET_SP (&mono_context);
341 current_frame = MONO_CONTEXT_GET_BP (&mono_context);
343 while ((current_frame_index <= call_chain_depth) &&
344 (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
345 ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
346 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
347 current_frame_index ++;
348 stack_top = current_frame;
349 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
352 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_GLIBC;
356 if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_GLIBC) {
357 #if GLIBC_PROFILER_BACKTRACE
358 current_frame_index = backtrace ((void**) & ips [1], call_chain_depth);
360 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_MANAGED;
364 if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_MANAGED) {
365 MonoDomain *domain = mono_domain_get ();
366 if (domain != NULL) {
370 MonoContext new_mono_context;
372 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
373 &new_mono_context, NULL, &lmf, &native_offset, NULL);
374 while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
375 ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
376 current_frame_index ++;
377 mono_context = new_mono_context;
378 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
379 &new_mono_context, NULL, &lmf, &native_offset, NULL);
385 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
389 MONO_SIG_HANDLER_FUNC (static, sigprof_signal_handler)
391 MonoThreadInfo *info;
392 int old_errno = errno;
394 MONO_SIG_HANDLER_GET_CONTEXT;
396 if (mono_thread_info_get_small_id () == -1)
397 return; //an non-attached thread got the signal
399 if (!mono_domain_get () || !mono_native_tls_get_value (mono_jit_tls_id))
400 return; //thread in the process of dettaching
402 hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
404 /* If we can't consume a profiling request it means we're the initiator. */
405 if (!(mono_threads_consume_async_jobs () & MONO_SERVICE_REQUEST_SAMPLE)) {
406 FOREACH_THREAD_SAFE (info) {
407 if (mono_thread_info_get_tid (info) == mono_native_thread_id_get ())
410 mono_threads_add_async_job (info, MONO_SERVICE_REQUEST_SAMPLE);
411 mono_threads_pthread_kill (info, profiling_signal_in_use);
412 } END_FOREACH_THREAD_SAFE;
415 mono_thread_info_set_is_async_context (TRUE);
416 per_thread_profiler_hit (ctx);
417 mono_thread_info_set_is_async_context (FALSE);
419 mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
422 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
428 MONO_SIG_HANDLER_FUNC (static, sigquit_signal_handler)
431 MONO_SIG_HANDLER_GET_CONTEXT;
433 /* We use this signal to start the attach agent too */
434 res = mono_attach_start ();
438 if (mono_thread_info_new_interrupt_enabled ()) {
439 mono_threads_request_thread_dump ();
441 printf ("Full thread dump:\n");
443 mono_threads_request_thread_dump ();
446 * print_thread_dump () skips the current thread, since sending a signal
447 * to it would invoke the signal handler below the sigquit signal handler,
448 * and signal handlers don't create an lmf, so the stack walk could not
451 mono_print_thread_dump (ctx);
454 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
457 MONO_SIG_HANDLER_FUNC (static, sigusr2_signal_handler)
459 gboolean enabled = mono_trace_is_enabled ();
461 mono_trace_enable (!enabled);
463 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
467 add_signal_handler (int signo, gpointer handler)
470 struct sigaction previous_sa;
472 #ifdef MONO_ARCH_USE_SIGACTION
473 sa.sa_sigaction = handler;
474 sigemptyset (&sa.sa_mask);
475 sa.sa_flags = SA_SIGINFO;
476 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
478 /*Apple likes to deliver SIGBUS for *0 */
480 if (signo == SIGSEGV || signo == SIGBUS) {
482 if (signo == SIGSEGV) {
484 sa.sa_flags |= SA_ONSTACK;
487 * libgc will crash when trying to do stack marking for threads which are on
488 * an altstack, so delay the suspend signal after the signal handler has
491 if (mono_gc_get_suspend_signal () != -1)
492 sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
495 if (signo == SIGSEGV) {
497 * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
501 sigemptyset (&block_mask);
502 sigaddset (&sa.sa_mask, mono_thread_get_abort_signal ());
505 sa.sa_handler = handler;
506 sigemptyset (&sa.sa_mask);
509 g_assert (sigaction (signo, &sa, &previous_sa) != -1);
511 /* if there was already a handler in place for this signal, store it */
512 if (! (previous_sa.sa_flags & SA_SIGINFO) &&
513 (SIG_DFL == previous_sa.sa_handler)) {
514 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
516 if (mono_do_signal_chaining)
517 save_old_signal_handler (signo, &previous_sa);
522 remove_signal_handler (int signo)
525 struct sigaction *saved_action = get_saved_signal_handler (signo);
528 sa.sa_handler = SIG_DFL;
529 sigemptyset (&sa.sa_mask);
532 sigaction (signo, &sa, NULL);
534 g_assert (sigaction (signo, saved_action, NULL) != -1);
539 mono_runtime_posix_install_handlers (void)
544 if (mini_get_debug_options ()->handle_sigint)
545 add_signal_handler (SIGINT, mono_sigint_signal_handler);
547 add_signal_handler (SIGFPE, mono_sigfpe_signal_handler);
548 add_signal_handler (SIGQUIT, sigquit_signal_handler);
549 add_signal_handler (SIGILL, mono_sigill_signal_handler);
550 add_signal_handler (SIGBUS, mono_sigsegv_signal_handler);
551 if (mono_jit_trace_calls != NULL)
552 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
554 if (!mono_thread_info_new_interrupt_enabled ())
555 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
556 /* it seems to have become a common bug for some programs that run as parents
557 * of many processes to block signal delivery for real time signals.
558 * We try to detect and work around their breakage here.
560 sigemptyset (&signal_set);
561 sigaddset (&signal_set, mono_thread_get_abort_signal ());
562 if (mono_gc_get_suspend_signal () != -1)
563 sigaddset (&signal_set, mono_gc_get_suspend_signal ());
564 if (mono_gc_get_restart_signal () != -1)
565 sigaddset (&signal_set, mono_gc_get_restart_signal ());
566 sigaddset (&signal_set, SIGCHLD);
567 sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
569 signal (SIGPIPE, SIG_IGN);
571 add_signal_handler (SIGABRT, sigabrt_signal_handler);
574 add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler);
577 #ifndef PLATFORM_MACOSX
579 mono_runtime_install_handlers (void)
581 mono_runtime_posix_install_handlers ();
586 mono_runtime_cleanup_handlers (void)
588 if (mini_get_debug_options ()->handle_sigint)
589 remove_signal_handler (SIGINT);
591 remove_signal_handler (SIGFPE);
592 remove_signal_handler (SIGQUIT);
593 remove_signal_handler (SIGILL);
594 remove_signal_handler (SIGBUS);
595 if (mono_jit_trace_calls != NULL)
596 remove_signal_handler (SIGUSR2);
598 remove_signal_handler (mono_thread_get_abort_signal ());
600 remove_signal_handler (SIGABRT);
602 remove_signal_handler (SIGSEGV);
604 free_saved_signal_handlers ();
607 #ifdef HAVE_LINUX_RTC_H
608 #include <linux/rtc.h>
609 #include <sys/ioctl.h>
611 static int rtc_fd = -1;
614 enable_rtc_timer (gboolean enable)
617 flags = fcntl (rtc_fd, F_GETFL);
626 if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
635 mono_runtime_shutdown_stat_profiler (void)
637 #ifdef HAVE_LINUX_RTC_H
639 enable_rtc_timer (FALSE);
645 get_itimer_mode (void)
647 switch (mono_profiler_get_sampling_mode ()) {
648 case MONO_PROFILER_STAT_MODE_PROCESS: return ITIMER_PROF;
649 case MONO_PROFILER_STAT_MODE_REAL: return ITIMER_REAL;
651 g_assert_not_reached ();
656 get_itimer_signal (void)
658 switch (mono_profiler_get_sampling_mode ()) {
659 case MONO_PROFILER_STAT_MODE_PROCESS: return SIGPROF;
660 case MONO_PROFILER_STAT_MODE_REAL: return SIGALRM;
662 g_assert_not_reached ();
668 mono_runtime_setup_stat_profiler (void)
671 struct itimerval itval;
672 static int inited = 0;
673 #ifdef HAVE_LINUX_RTC_H
674 const char *rtc_freq;
675 if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
679 freq = atoi (rtc_freq);
682 rtc_fd = open ("/dev/rtc", O_RDONLY);
684 perror ("open /dev/rtc");
687 profiling_signal_in_use = SIGPROF;
688 add_signal_handler (profiling_signal_in_use, sigprof_signal_handler);
689 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
690 perror ("set rtc freq");
693 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
694 perror ("start rtc");
697 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
701 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
705 enable_rtc_timer (TRUE);
712 itval.it_interval.tv_usec = (1000000 / mono_profiler_get_sampling_rate ()) - 1;
713 itval.it_interval.tv_sec = 0;
714 itval.it_value = itval.it_interval;
718 profiling_signal_in_use = get_itimer_signal ();
719 add_signal_handler (profiling_signal_in_use, sigprof_signal_handler);
720 setitimer (get_itimer_mode (), &itval, NULL);
724 #if !defined(__APPLE__)
726 mono_runtime_syscall_fork ()
728 #if defined(PLATFORM_ANDROID)
729 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
730 g_assert_not_reached ();
732 #elif defined(SYS_fork)
733 return (pid_t) syscall (SYS_fork);
735 g_assert_not_reached ();
741 mono_gdb_render_native_backtraces (pid_t crashed_pid)
743 const char *argv [9];
744 char template [] = "/tmp/mono-lldb-commands.XXXXXX";
747 gboolean using_lldb = FALSE;
749 argv [0] = g_find_program_in_path ("gdb");
750 if (argv [0] == NULL) {
751 argv [0] = g_find_program_in_path ("lldb");
755 if (argv [0] == NULL)
759 if (mkstemp (template) == -1)
762 commands = fopen (template, "w");
764 fprintf (commands, "process attach --pid %ld\n", (long) crashed_pid);
765 fprintf (commands, "thread list\n");
766 fprintf (commands, "thread backtrace all\n");
767 fprintf (commands, "detach\n");
768 fprintf (commands, "quit\n");
773 argv [1] = "--source";
778 sprintf (buf1, "attach %ld", (long) crashed_pid);
781 argv [4] = "info threads";
783 argv [6] = "thread apply all bt";
784 argv [7] = "--batch";
788 execv (argv [0], (char**)argv);
794 #endif /* __native_client__ */
796 #if !defined (__MACH__)
799 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
801 g_error ("Posix systems don't support mono_thread_state_init_from_handle");