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>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/loader.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/class.h>
33 #include <mono/metadata/object.h>
34 #include <mono/metadata/tokentype.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/threads.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/io-layer/io-layer.h>
40 #include "mono/metadata/profiler.h"
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/gc-internal.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/verify.h>
48 #include <mono/metadata/verify-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/attach.h>
51 #include <mono/utils/mono-math.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-counters.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/dtrace.h>
57 #include <mono/utils/mono-signal-handler.h>
64 #include "debugger-agent.h"
66 #include "jit-icalls.h"
68 #if defined(__native_client__)
71 mono_runtime_setup_stat_profiler (void)
73 printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
78 mono_runtime_shutdown_stat_profiler (void)
84 SIG_HANDLER_SIGNATURE (mono_chain_signal)
90 mono_runtime_install_handlers (void)
95 mono_runtime_shutdown_handlers (void)
100 mono_runtime_cleanup_handlers (void)
105 mono_runtime_syscall_fork (void)
107 g_assert_not_reached();
112 mono_gdb_render_native_backtraces (pid_t crashed_pid)
118 static GHashTable *mono_saved_signal_handlers = NULL;
121 get_saved_signal_handler (int signo)
123 if (mono_saved_signal_handlers)
124 /* The hash is only modified during startup, so no need for locking */
125 return g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
130 save_old_signal_handler (int signo, struct sigaction *old_action)
132 struct sigaction *handler_to_save = g_malloc (sizeof (struct sigaction));
134 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
135 "Saving old signal handler for signal %d.", signo);
137 if (! (old_action->sa_flags & SA_SIGINFO)) {
138 handler_to_save->sa_handler = old_action->sa_handler;
140 #ifdef MONO_ARCH_USE_SIGACTION
141 handler_to_save->sa_sigaction = old_action->sa_sigaction;
142 #endif /* MONO_ARCH_USE_SIGACTION */
144 handler_to_save->sa_mask = old_action->sa_mask;
145 handler_to_save->sa_flags = old_action->sa_flags;
147 if (!mono_saved_signal_handlers)
148 mono_saved_signal_handlers = g_hash_table_new (NULL, NULL);
149 g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
153 free_saved_sig_handler_func (gpointer key, gpointer value, gpointer user_data)
159 free_saved_signal_handlers (void)
161 if (mono_saved_signal_handlers) {
162 g_hash_table_foreach (mono_saved_signal_handlers, free_saved_sig_handler_func, NULL);
163 g_hash_table_destroy (mono_saved_signal_handlers);
164 mono_saved_signal_handlers = NULL;
171 * Call the original signal handler for the signal given by the arguments, which
172 * should be the same as for a signal handler. Returns TRUE if the original handler
173 * was called, false otherwise.
176 SIG_HANDLER_SIGNATURE (mono_chain_signal)
179 struct sigaction *saved_handler = get_saved_signal_handler (signal);
183 if (saved_handler && saved_handler->sa_handler) {
184 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
185 saved_handler->sa_handler (signal);
187 #ifdef MONO_ARCH_USE_SIGACTION
188 saved_handler->sa_sigaction (signal, info, ctx);
189 #endif /* MONO_ARCH_USE_SIGACTION */
196 SIG_HANDLER_FUNC (static, sigabrt_signal_handler)
198 MonoJitInfo *ji = NULL;
201 if (mono_thread_internal_current ())
202 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
204 if (mono_chain_signal (SIG_HANDLER_PARAMS))
206 mono_handle_native_sigsegv (SIGABRT, ctx);
210 SIG_HANDLER_FUNC (static, sigusr1_signal_handler)
212 gboolean running_managed;
214 MonoInternalThread *thread = mono_thread_internal_current ();
215 MonoDomain *domain = mono_domain_get ();
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
300 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
302 SIG_HANDLER_FUNC (static, sigprof_signal_handler)
304 if (mono_chain_signal (SIG_HANDLER_PARAMS))
312 SIG_HANDLER_FUNC (static, sigprof_signal_handler)
314 int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
315 MonoProfilerCallChainStrategy call_chain_strategy = mono_profiler_stat_get_call_chain_strategy ();
318 if (call_chain_depth == 0) {
319 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
321 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
322 int current_frame_index = 1;
323 MonoContext mono_context;
324 guchar *ips [call_chain_depth + 1];
326 mono_arch_sigctx_to_monoctx (ctx, &mono_context);
327 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
329 if (jit_tls != NULL) {
330 if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_NATIVE) {
331 #if FULL_STAT_PROFILER_BACKTRACE
332 guchar *current_frame;
333 guchar *stack_bottom;
336 stack_bottom = jit_tls->end_of_stack;
337 stack_top = MONO_CONTEXT_GET_SP (&mono_context);
338 current_frame = MONO_CONTEXT_GET_BP (&mono_context);
340 while ((current_frame_index <= call_chain_depth) &&
341 (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
342 ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
343 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
344 current_frame_index ++;
345 stack_top = current_frame;
346 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
349 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_GLIBC;
353 if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_GLIBC) {
354 #if GLIBC_PROFILER_BACKTRACE
355 current_frame_index = backtrace ((void**) & ips [1], call_chain_depth);
357 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_MANAGED;
361 if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_MANAGED) {
362 MonoDomain *domain = mono_domain_get ();
363 if (domain != NULL) {
367 MonoContext new_mono_context;
369 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
370 &new_mono_context, NULL, &lmf, &native_offset, NULL);
371 while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
372 ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
373 current_frame_index ++;
374 mono_context = new_mono_context;
375 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
376 &new_mono_context, NULL, &lmf, &native_offset, NULL);
382 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
385 mono_chain_signal (SIG_HANDLER_PARAMS);
391 SIG_HANDLER_FUNC (static, sigquit_signal_handler)
397 /* We use this signal to start the attach agent too */
398 res = mono_attach_start ();
402 if (mono_thread_info_new_interrupt_enabled ()) {
403 mono_threads_request_thread_dump ();
405 printf ("Full thread dump:\n");
407 mono_threads_request_thread_dump ();
410 * print_thread_dump () skips the current thread, since sending a signal
411 * to it would invoke the signal handler below the sigquit signal handler,
412 * and signal handlers don't create an lmf, so the stack walk could not
415 mono_print_thread_dump (ctx);
418 mono_chain_signal (SIG_HANDLER_PARAMS);
421 SIG_HANDLER_FUNC (static, sigusr2_signal_handler)
423 gboolean enabled = mono_trace_is_enabled ();
425 mono_trace_enable (!enabled);
427 mono_chain_signal (SIG_HANDLER_PARAMS);
431 add_signal_handler (int signo, gpointer handler)
434 struct sigaction previous_sa;
436 #ifdef MONO_ARCH_USE_SIGACTION
437 sa.sa_sigaction = handler;
438 sigemptyset (&sa.sa_mask);
439 sa.sa_flags = SA_SIGINFO;
440 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
442 /*Apple likes to deliver SIGBUS for *0 */
444 if (signo == SIGSEGV || signo == SIGBUS) {
446 if (signo == SIGSEGV) {
448 sa.sa_flags |= SA_ONSTACK;
451 * libgc will crash when trying to do stack marking for threads which are on
452 * an altstack, so delay the suspend signal after the signal handler has
455 if (mono_gc_get_suspend_signal () != -1)
456 sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
459 if (signo == SIGSEGV) {
461 * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
465 sigemptyset (&block_mask);
466 sigaddset (&sa.sa_mask, mono_thread_get_abort_signal ());
469 sa.sa_handler = handler;
470 sigemptyset (&sa.sa_mask);
473 g_assert (sigaction (signo, &sa, &previous_sa) != -1);
475 /* if there was already a handler in place for this signal, store it */
476 if (! (previous_sa.sa_flags & SA_SIGINFO) &&
477 (SIG_DFL == previous_sa.sa_handler)) {
478 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
480 if (mono_do_signal_chaining)
481 save_old_signal_handler (signo, &previous_sa);
486 remove_signal_handler (int signo)
489 struct sigaction *saved_action = get_saved_signal_handler (signo);
492 sa.sa_handler = SIG_DFL;
493 sigemptyset (&sa.sa_mask);
496 sigaction (signo, &sa, NULL);
498 g_assert (sigaction (signo, saved_action, NULL) != -1);
503 mono_runtime_posix_install_handlers (void)
508 if (mini_get_debug_options ()->handle_sigint)
509 add_signal_handler (SIGINT, mono_sigint_signal_handler);
511 add_signal_handler (SIGFPE, mono_sigfpe_signal_handler);
512 add_signal_handler (SIGQUIT, sigquit_signal_handler);
513 add_signal_handler (SIGILL, mono_sigill_signal_handler);
514 add_signal_handler (SIGBUS, mono_sigsegv_signal_handler);
515 if (mono_jit_trace_calls != NULL)
516 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
518 if (!mono_thread_info_new_interrupt_enabled ())
519 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
520 /* it seems to have become a common bug for some programs that run as parents
521 * of many processes to block signal delivery for real time signals.
522 * We try to detect and work around their breakage here.
524 sigemptyset (&signal_set);
525 sigaddset (&signal_set, mono_thread_get_abort_signal ());
526 if (mono_gc_get_suspend_signal () != -1)
527 sigaddset (&signal_set, mono_gc_get_suspend_signal ());
528 if (mono_gc_get_restart_signal () != -1)
529 sigaddset (&signal_set, mono_gc_get_restart_signal ());
530 sigaddset (&signal_set, SIGCHLD);
531 sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
533 signal (SIGPIPE, SIG_IGN);
535 add_signal_handler (SIGABRT, sigabrt_signal_handler);
538 add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler);
541 #ifndef PLATFORM_MACOSX
543 mono_runtime_install_handlers (void)
545 mono_runtime_posix_install_handlers ();
550 mono_runtime_cleanup_handlers (void)
552 if (mini_get_debug_options ()->handle_sigint)
553 remove_signal_handler (SIGINT);
555 remove_signal_handler (SIGFPE);
556 remove_signal_handler (SIGQUIT);
557 remove_signal_handler (SIGILL);
558 remove_signal_handler (SIGBUS);
559 if (mono_jit_trace_calls != NULL)
560 remove_signal_handler (SIGUSR2);
562 remove_signal_handler (mono_thread_get_abort_signal ());
564 remove_signal_handler (SIGABRT);
566 remove_signal_handler (SIGSEGV);
568 free_saved_signal_handlers ();
571 #ifdef HAVE_LINUX_RTC_H
572 #include <linux/rtc.h>
573 #include <sys/ioctl.h>
575 static int rtc_fd = -1;
578 enable_rtc_timer (gboolean enable)
581 flags = fcntl (rtc_fd, F_GETFL);
590 if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
599 mono_runtime_shutdown_stat_profiler (void)
601 #ifdef HAVE_LINUX_RTC_H
603 enable_rtc_timer (FALSE);
608 mono_runtime_setup_stat_profiler (void)
611 struct itimerval itval;
612 static int inited = 0;
613 #ifdef HAVE_LINUX_RTC_H
614 const char *rtc_freq;
615 if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
619 freq = atoi (rtc_freq);
622 rtc_fd = open ("/dev/rtc", O_RDONLY);
624 perror ("open /dev/rtc");
627 add_signal_handler (SIGPROF, sigprof_signal_handler);
628 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
629 perror ("set rtc freq");
632 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
633 perror ("start rtc");
636 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
640 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
644 enable_rtc_timer (TRUE);
651 itval.it_interval.tv_usec = 999;
652 itval.it_interval.tv_sec = 0;
653 itval.it_value = itval.it_interval;
654 setitimer (ITIMER_PROF, &itval, NULL);
658 add_signal_handler (SIGPROF, sigprof_signal_handler);
662 #if !defined(__APPLE__)
664 mono_runtime_syscall_fork ()
666 #if defined(SYS_fork)
667 return (pid_t) syscall (SYS_fork);
669 g_assert_not_reached ();
675 mono_gdb_render_native_backtraces (pid_t crashed_pid)
677 const char *argv [9];
678 char template [] = "/tmp/mono-lldb-commands.XXXXXX";
681 gboolean using_lldb = FALSE;
683 argv [0] = g_find_program_in_path ("gdb");
684 if (argv [0] == NULL) {
685 argv [0] = g_find_program_in_path ("lldb");
689 if (argv [0] == NULL)
693 if (mkstemp (template) == -1)
696 commands = fopen (template, "w");
698 fprintf (commands, "process attach --pid %ld\n", (long) crashed_pid);
699 fprintf (commands, "thread list\n");
700 fprintf (commands, "thread backtrace all\n");
701 fprintf (commands, "detach\n");
702 fprintf (commands, "quit\n");
707 argv [1] = "--source";
712 sprintf (buf1, "attach %ld", (long) crashed_pid);
715 argv [4] = "info threads";
717 argv [6] = "thread apply all bt";
718 argv [7] = "--batch";
722 execv (argv [0], (char**)argv);
728 #endif /* __native_client__ */
730 #if !defined (__MACH__)
733 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
735 g_error ("Posix systems don't support mono_thread_state_init_from_handle");