[runtime] Write unmanaged exception dumper
[mono-project.git] / mono / mini / mini-posix.c
blob693cae121c46e764dcba4cc59c70ab6f28b38f11
1 /**
2 * \file
3 * POSIX signal handling support for Mono.
5 * Authors:
6 * Mono Team (mono-list@lists.ximian.com)
8 * Copyright 2001-2003 Ximian, Inc.
9 * Copyright 2003-2008 Ximian, Inc.
10 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12 * See LICENSE for licensing information.
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include <config.h>
16 #include <signal.h>
17 #ifdef HAVE_ALLOCA_H
18 #include <alloca.h>
19 #endif
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 #include <math.h>
24 #ifdef HAVE_SYS_TIME_H
25 #include <sys/time.h>
26 #endif
27 #ifdef HAVE_SYS_SYSCALL_H
28 #include <sys/syscall.h>
29 #endif
30 #include <errno.h>
31 #include <sched.h>
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/tabledefs.h>
40 #include <mono/metadata/threads.h>
41 #include <mono/metadata/appdomain.h>
42 #include <mono/metadata/debug-helpers.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-internals.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-internals.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>
61 #include <mono/utils/os-event.h>
63 #include "mini.h"
64 #include <string.h>
65 #include <ctype.h>
66 #include "trace.h"
67 #include "version.h"
68 #include "debugger-agent.h"
69 #include "mini-runtime.h"
70 #include "jit-icalls.h"
72 #ifdef HOST_DARWIN
73 #include <mach/mach.h>
74 #include <mach/mach_time.h>
75 #include <mach/clock.h>
76 #include <mono/utils/mono-merp.h>
77 #endif
79 #if defined(HOST_WATCHOS)
81 void
82 mono_runtime_setup_stat_profiler (void)
84 printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
88 void
89 mono_runtime_shutdown_stat_profiler (void)
94 gboolean
95 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
97 return FALSE;
100 #ifndef HOST_DARWIN
101 void
102 mono_runtime_install_handlers (void)
105 #endif
107 void
108 mono_runtime_posix_install_handlers(void)
110 /* we still need to ignore SIGPIPE */
111 signal (SIGPIPE, SIG_IGN);
114 void
115 mono_runtime_shutdown_handlers (void)
119 void
120 mono_runtime_cleanup_handlers (void)
124 #else
126 static GHashTable *mono_saved_signal_handlers = NULL;
128 static struct sigaction *
129 get_saved_signal_handler (int signo, gboolean remove)
131 if (mono_saved_signal_handlers) {
132 /* The hash is only modified during startup, so no need for locking */
133 struct sigaction *handler = g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
134 if (remove && handler)
135 g_hash_table_remove (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
136 return handler;
138 return NULL;
141 static void
142 save_old_signal_handler (int signo, struct sigaction *old_action)
144 struct sigaction *handler_to_save = (struct sigaction *)g_malloc (sizeof (struct sigaction));
146 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
147 "Saving old signal handler for signal %d.", signo);
149 if (! (old_action->sa_flags & SA_SIGINFO)) {
150 handler_to_save->sa_handler = old_action->sa_handler;
151 } else {
152 #ifdef MONO_ARCH_USE_SIGACTION
153 handler_to_save->sa_sigaction = old_action->sa_sigaction;
154 #endif /* MONO_ARCH_USE_SIGACTION */
156 handler_to_save->sa_mask = old_action->sa_mask;
157 handler_to_save->sa_flags = old_action->sa_flags;
159 if (!mono_saved_signal_handlers)
160 mono_saved_signal_handlers = g_hash_table_new_full (NULL, NULL, NULL, g_free);
161 g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
164 static void
165 free_saved_signal_handlers (void)
167 g_hash_table_destroy (mono_saved_signal_handlers);
168 mono_saved_signal_handlers = NULL;
172 * mono_chain_signal:
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.
178 gboolean
179 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
181 int signal = MONO_SIG_HANDLER_GET_SIGNO ();
182 struct sigaction *saved_handler = (struct sigaction *)get_saved_signal_handler (signal, FALSE);
184 if (saved_handler && saved_handler->sa_handler) {
185 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
186 saved_handler->sa_handler (signal);
187 } else {
188 #ifdef MONO_ARCH_USE_SIGACTION
189 saved_handler->sa_sigaction (MONO_SIG_HANDLER_PARAMS);
190 #endif /* MONO_ARCH_USE_SIGACTION */
192 return TRUE;
194 return FALSE;
197 MONO_SIG_HANDLER_FUNC (static, sigabrt_signal_handler)
199 MonoJitInfo *ji = NULL;
200 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
201 MONO_SIG_HANDLER_GET_CONTEXT;
203 if (mono_thread_internal_current ())
204 ji = mono_jit_info_table_find_internal (mono_domain_get (), mono_arch_ip_from_context (ctx), TRUE, TRUE);
205 if (!ji) {
206 if (mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
207 return;
208 mono_handle_native_crash ("SIGABRT", ctx, info);
212 #ifdef TARGET_OSX
213 MONO_SIG_HANDLER_FUNC (static, sigterm_signal_handler)
215 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
216 MONO_SIG_HANDLER_GET_CONTEXT;
218 // Note: this function only returns for a single thread
219 // When it's invoked on other threads once the dump begins,
220 // those threads perform their dumps and then sleep until we
221 // die. The dump ends with the exit(1) below
222 MonoContext mctx;
223 gchar *output = NULL;
224 mono_sigctx_to_monoctx (ctx, &mctx);
225 if (!mono_threads_summarize (&mctx, &output))
226 g_assert_not_reached ();
228 // Only the dumping-supervisor thread exits mono_thread_summarize
229 fprintf (stderr, "Unhandled exception dump: \n######\n%s\n######\n", output);
231 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
232 exit (1);
234 #endif
236 #if (defined (USE_POSIX_BACKEND) && defined (SIGRTMIN)) || defined (SIGPROF)
237 #define HAVE_PROFILER_SIGNAL
238 #endif
240 #ifdef HAVE_PROFILER_SIGNAL
242 static MonoNativeThreadId sampling_thread;
244 static gint32 profiler_signals_sent;
245 static gint32 profiler_signals_received;
246 static gint32 profiler_signals_accepted;
247 static gint32 profiler_interrupt_signals_received;
249 MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler)
251 int old_errno = errno;
253 MONO_SIG_HANDLER_GET_CONTEXT;
255 /* See the comment in mono_runtime_shutdown_stat_profiler (). */
256 if (mono_native_thread_id_get () == sampling_thread) {
257 mono_atomic_inc_i32 (&profiler_interrupt_signals_received);
258 return;
261 mono_atomic_inc_i32 (&profiler_signals_received);
263 // Did a non-attached or detaching thread get the signal?
264 if (mono_thread_info_get_small_id () == -1 ||
265 !mono_domain_get () ||
266 !mono_tls_get_jit_tls ()) {
267 errno = old_errno;
268 return;
271 // See the comment in sampling_thread_func ().
272 mono_atomic_store_i32 (&mono_thread_info_current ()->profiler_signal_ack, 1);
274 mono_atomic_inc_i32 (&profiler_signals_accepted);
276 int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
278 mono_thread_info_set_is_async_context (TRUE);
280 MONO_PROFILER_RAISE (sample_hit, (mono_arch_ip_from_context (ctx), ctx));
282 mono_thread_info_set_is_async_context (FALSE);
284 mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
286 errno = old_errno;
288 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
291 #endif
293 MONO_SIG_HANDLER_FUNC (static, sigquit_signal_handler)
295 gboolean res;
297 /* We use this signal to start the attach agent too */
298 res = mono_attach_start ();
299 if (res)
300 return;
302 mono_threads_request_thread_dump ();
304 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
307 MONO_SIG_HANDLER_FUNC (static, sigusr2_signal_handler)
309 gboolean enabled = mono_trace_is_enabled ();
311 mono_trace_enable (!enabled);
313 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
316 static void
317 add_signal_handler (int signo, gpointer handler, int flags)
319 struct sigaction sa;
320 struct sigaction previous_sa;
322 #ifdef MONO_ARCH_USE_SIGACTION
323 sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
324 sigemptyset (&sa.sa_mask);
325 sa.sa_flags = SA_SIGINFO | flags;
326 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
328 /*Apple likes to deliver SIGBUS for *0 */
329 #ifdef HOST_DARWIN
330 if (signo == SIGSEGV || signo == SIGBUS) {
331 #else
332 if (signo == SIGSEGV) {
333 #endif
334 sa.sa_flags |= SA_ONSTACK;
337 * libgc will crash when trying to do stack marking for threads which are on
338 * an altstack, so delay the suspend signal after the signal handler has
339 * executed.
341 if (mono_gc_get_suspend_signal () != -1)
342 sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
344 #endif
345 if (signo == SIGSEGV) {
347 * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
349 sigset_t block_mask;
351 sigemptyset (&block_mask);
353 #else
354 sa.sa_handler = handler;
355 sigemptyset (&sa.sa_mask);
356 sa.sa_flags = flags;
357 #endif
358 g_assert (sigaction (signo, &sa, &previous_sa) != -1);
360 /* if there was already a handler in place for this signal, store it */
361 if (! (previous_sa.sa_flags & SA_SIGINFO) &&
362 (SIG_DFL == previous_sa.sa_handler)) {
363 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
364 } else {
365 if (mono_do_signal_chaining)
366 save_old_signal_handler (signo, &previous_sa);
370 static void
371 remove_signal_handler (int signo)
373 struct sigaction sa;
374 struct sigaction *saved_action = get_saved_signal_handler (signo, TRUE);
376 if (!saved_action) {
377 sa.sa_handler = SIG_DFL;
378 sigemptyset (&sa.sa_mask);
379 sa.sa_flags = 0;
381 sigaction (signo, &sa, NULL);
382 } else {
383 g_assert (sigaction (signo, saved_action, NULL) != -1);
387 #ifdef TARGET_OSX
388 void
389 mini_register_sigterm_handler (void)
391 /* always catch SIGTERM, conditionals inside of handler */
392 add_signal_handler (SIGTERM, sigterm_signal_handler, 0);
394 #endif
396 void
397 mono_runtime_posix_install_handlers (void)
400 sigset_t signal_set;
402 if (mini_get_debug_options ()->handle_sigint)
403 add_signal_handler (SIGINT, mono_sigint_signal_handler, SA_RESTART);
405 add_signal_handler (SIGFPE, mono_sigfpe_signal_handler, 0);
406 add_signal_handler (SIGQUIT, sigquit_signal_handler, SA_RESTART);
407 add_signal_handler (SIGILL, mono_sigill_signal_handler, 0);
408 add_signal_handler (SIGBUS, mono_sigsegv_signal_handler, 0);
409 if (mono_jit_trace_calls != NULL)
410 add_signal_handler (SIGUSR2, sigusr2_signal_handler, SA_RESTART);
412 /* it seems to have become a common bug for some programs that run as parents
413 * of many processes to block signal delivery for real time signals.
414 * We try to detect and work around their breakage here.
416 sigemptyset (&signal_set);
417 if (mono_gc_get_suspend_signal () != -1)
418 sigaddset (&signal_set, mono_gc_get_suspend_signal ());
419 if (mono_gc_get_restart_signal () != -1)
420 sigaddset (&signal_set, mono_gc_get_restart_signal ());
421 sigaddset (&signal_set, SIGCHLD);
422 sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
424 signal (SIGPIPE, SIG_IGN);
426 add_signal_handler (SIGABRT, sigabrt_signal_handler, 0);
428 /* catch SIGSEGV */
429 add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler, 0);
432 #ifndef HOST_DARWIN
433 void
434 mono_runtime_install_handlers (void)
436 mono_runtime_posix_install_handlers ();
438 #endif
440 void
441 mono_runtime_cleanup_handlers (void)
443 if (mini_get_debug_options ()->handle_sigint)
444 remove_signal_handler (SIGINT);
446 remove_signal_handler (SIGFPE);
447 remove_signal_handler (SIGQUIT);
448 remove_signal_handler (SIGILL);
449 remove_signal_handler (SIGBUS);
450 if (mono_jit_trace_calls != NULL)
451 remove_signal_handler (SIGUSR2);
453 remove_signal_handler (SIGABRT);
455 remove_signal_handler (SIGSEGV);
457 free_saved_signal_handlers ();
460 #ifdef HAVE_PROFILER_SIGNAL
462 static volatile gint32 sampling_thread_running;
464 #ifdef HOST_DARWIN
466 static clock_serv_t sampling_clock_service;
468 static void
469 clock_init (MonoProfilerSampleMode mode)
471 kern_return_t ret;
473 do {
474 ret = host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &sampling_clock_service);
475 } while (ret == KERN_ABORTED);
477 if (ret != KERN_SUCCESS)
478 g_error ("%s: host_get_clock_service () returned %d", __func__, ret);
481 static void
482 clock_cleanup (void)
484 kern_return_t ret;
486 do {
487 ret = mach_port_deallocate (mach_task_self (), sampling_clock_service);
488 } while (ret == KERN_ABORTED);
490 if (ret != KERN_SUCCESS)
491 g_error ("%s: mach_port_deallocate () returned %d", __func__, ret);
494 static guint64
495 clock_get_time_ns (void)
497 kern_return_t ret;
498 mach_timespec_t mach_ts;
500 do {
501 ret = clock_get_time (sampling_clock_service, &mach_ts);
502 } while (ret == KERN_ABORTED);
504 if (ret != KERN_SUCCESS)
505 g_error ("%s: clock_get_time () returned %d", __func__, ret);
507 return ((guint64) mach_ts.tv_sec * 1000000000) + (guint64) mach_ts.tv_nsec;
510 static void
511 clock_sleep_ns_abs (guint64 ns_abs)
513 kern_return_t ret;
514 mach_timespec_t then, remain_unused;
516 then.tv_sec = ns_abs / 1000000000;
517 then.tv_nsec = ns_abs % 1000000000;
519 do {
520 ret = clock_sleep (sampling_clock_service, TIME_ABSOLUTE, then, &remain_unused);
522 if (ret != KERN_SUCCESS && ret != KERN_ABORTED)
523 g_error ("%s: clock_sleep () returned %d", __func__, ret);
524 } while (ret == KERN_ABORTED && mono_atomic_load_i32 (&sampling_thread_running));
527 #else
529 static clockid_t sampling_posix_clock;
531 static void
532 clock_init (MonoProfilerSampleMode mode)
534 switch (mode) {
535 case MONO_PROFILER_SAMPLE_MODE_PROCESS: {
537 * If we don't have clock_nanosleep (), measuring the process time
538 * makes very little sense as we can only use nanosleep () to sleep on
539 * real time.
541 #ifdef HAVE_CLOCK_NANOSLEEP
542 struct timespec ts = { 0 };
545 * Some systems (e.g. Windows Subsystem for Linux) declare the
546 * CLOCK_PROCESS_CPUTIME_ID clock but don't actually support it. For
547 * those systems, we fall back to CLOCK_MONOTONIC if we get EINVAL.
549 if (clock_nanosleep (CLOCK_PROCESS_CPUTIME_ID, TIMER_ABSTIME, &ts, NULL) != EINVAL) {
550 sampling_posix_clock = CLOCK_PROCESS_CPUTIME_ID;
551 break;
553 #endif
555 // fallthrough
557 case MONO_PROFILER_SAMPLE_MODE_REAL: sampling_posix_clock = CLOCK_MONOTONIC; break;
558 default: g_assert_not_reached (); break;
562 static void
563 clock_cleanup (void)
567 static guint64
568 clock_get_time_ns (void)
570 struct timespec ts;
572 if (clock_gettime (sampling_posix_clock, &ts) == -1)
573 g_error ("%s: clock_gettime () returned -1, errno = %d", __func__, errno);
575 return ((guint64) ts.tv_sec * 1000000000) + (guint64) ts.tv_nsec;
578 static void
579 clock_sleep_ns_abs (guint64 ns_abs)
581 #ifdef HAVE_CLOCK_NANOSLEEP
582 int ret;
583 struct timespec then;
585 then.tv_sec = ns_abs / 1000000000;
586 then.tv_nsec = ns_abs % 1000000000;
588 do {
589 ret = clock_nanosleep (sampling_posix_clock, TIMER_ABSTIME, &then, NULL);
591 if (ret != 0 && ret != EINTR)
592 g_error ("%s: clock_nanosleep () returned %d", __func__, ret);
593 } while (ret == EINTR && mono_atomic_load_i32 (&sampling_thread_running));
594 #else
595 int ret;
596 gint64 diff;
597 struct timespec req;
600 * What follows is a crude attempt at emulating clock_nanosleep () on OSs
601 * which don't provide it (e.g. FreeBSD).
603 * The problem with nanosleep () is that if it is interrupted by a signal,
604 * time will drift as a result of having to restart the call after the
605 * signal handler has finished. For this reason, we avoid using the rem
606 * argument of nanosleep (). Instead, before every nanosleep () call, we
607 * check if enough time has passed to satisfy the sleep request. If yes, we
608 * simply return. If not, we calculate the difference and do another sleep.
610 * This should reduce the amount of drift that happens because we account
611 * for the time spent executing the signal handler, which nanosleep () is
612 * not guaranteed to do for the rem argument.
614 * The downside to this approach is that it is slightly expensive: We have
615 * to make an extra system call to retrieve the current time whenever we're
616 * going to restart a nanosleep () call. This is unlikely to be a problem
617 * in practice since the sampling thread won't be receiving many signals in
618 * the first place (it's a tools thread, so no STW), and because typical
619 * sleep periods for the thread are many orders of magnitude bigger than
620 * the time it takes to actually perform that system call (just a few
621 * nanoseconds).
623 do {
624 diff = (gint64) ns_abs - (gint64) clock_get_time_ns ();
626 if (diff <= 0)
627 break;
629 req.tv_sec = diff / 1000000000;
630 req.tv_nsec = diff % 1000000000;
632 if ((ret = nanosleep (&req, NULL)) == -1 && errno != EINTR)
633 g_error ("%s: nanosleep () returned -1, errno = %d", __func__, errno);
634 } while (ret == -1 && mono_atomic_load_i32 (&sampling_thread_running));
635 #endif
638 #endif
640 static int profiler_signal;
641 static volatile gint32 sampling_thread_exiting;
642 static MonoOSEvent sampling_thread_exited;
644 static gsize
645 sampling_thread_func (gpointer unused)
647 MonoInternalThread *thread = mono_thread_internal_current ();
649 thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
651 ERROR_DECL (error);
653 MonoString *name = mono_string_new_checked (mono_get_root_domain (), "Profiler Sampler", error);
654 mono_error_assert_ok (error);
655 mono_thread_set_name_internal (thread, name, FALSE, FALSE, error);
656 mono_error_assert_ok (error);
658 mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NO_GC | MONO_THREAD_INFO_FLAGS_NO_SAMPLE);
660 int old_policy;
661 struct sched_param old_sched;
662 pthread_getschedparam (pthread_self (), &old_policy, &old_sched);
665 * Attempt to switch the thread to real time scheduling. This will not
666 * necessarily work on all OSs; for example, most Linux systems will give
667 * us EPERM here unless configured to allow this.
669 * TODO: This does not work on Mac (and maybe some other OSs). On Mac, we
670 * have to use the Mach thread policy routines to switch to real-time
671 * scheduling. This is quite tricky as we need to specify how often we'll
672 * be doing work (easy), the normal processing time needed (also easy),
673 * and the maximum amount of processing time needed (hard). This is
674 * further complicated by the fact that if we misbehave and take too long
675 * to do our work, the kernel may knock us back down to the normal thread
676 * scheduling policy without telling us.
678 struct sched_param sched = { .sched_priority = sched_get_priority_max (SCHED_FIFO) };
679 pthread_setschedparam (pthread_self (), SCHED_FIFO, &sched);
681 MonoProfilerSampleMode mode;
683 init:
684 mono_profiler_get_sample_mode (NULL, &mode, NULL);
686 if (mode == MONO_PROFILER_SAMPLE_MODE_NONE) {
687 mono_profiler_sampling_thread_wait ();
689 if (!mono_atomic_load_i32 (&sampling_thread_running))
690 goto done;
692 goto init;
695 clock_init (mode);
697 for (guint64 sleep = clock_get_time_ns (); mono_atomic_load_i32 (&sampling_thread_running); clock_sleep_ns_abs (sleep)) {
698 uint32_t freq;
699 MonoProfilerSampleMode new_mode;
701 mono_profiler_get_sample_mode (NULL, &new_mode, &freq);
703 if (new_mode != mode) {
704 clock_cleanup ();
705 goto init;
708 sleep += 1000000000 / freq;
710 FOREACH_THREAD_SAFE_EXCLUDE (info, MONO_THREAD_INFO_FLAGS_NO_SAMPLE) {
711 g_assert (mono_thread_info_get_tid (info) != sampling_thread);
714 * Require an ack for the last sampling signal sent to the thread
715 * so that we don't overflow the signal queue, leading to all sorts
716 * of problems (e.g. GC STW failing).
718 if (profiler_signal != SIGPROF && !mono_atomic_cas_i32 (&info->profiler_signal_ack, 0, 1))
719 continue;
721 mono_threads_pthread_kill (info, profiler_signal);
722 mono_atomic_inc_i32 (&profiler_signals_sent);
723 } FOREACH_THREAD_SAFE_END
726 clock_cleanup ();
728 done:
729 mono_atomic_store_i32 (&sampling_thread_exiting, 1);
731 pthread_setschedparam (pthread_self (), old_policy, &old_sched);
733 mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NONE);
735 mono_os_event_set (&sampling_thread_exited);
737 return 0;
740 void
741 mono_runtime_shutdown_stat_profiler (void)
743 mono_atomic_store_i32 (&sampling_thread_running, 0);
745 mono_profiler_sampling_thread_post ();
747 #ifndef HOST_DARWIN
749 * There is a slight problem when we're using CLOCK_PROCESS_CPUTIME_ID: If
750 * we're shutting down and there's largely no activity in the process other
751 * than waiting for the sampler thread to shut down, it can take upwards of
752 * 20 seconds (depending on a lot of factors) for us to shut down because
753 * the sleep progresses very slowly as a result of the low CPU activity.
755 * We fix this by repeatedly sending the profiler signal to the sampler
756 * thread in order to interrupt the sleep. clock_sleep_ns_abs () will check
757 * sampling_thread_running upon an interrupt and return immediately if it's
758 * zero. profiler_signal_handler () has a special case to ignore the signal
759 * for the sampler thread.
761 MonoThreadInfo *info;
763 // Did it shut down already?
764 if ((info = mono_thread_info_lookup (sampling_thread))) {
765 while (!mono_atomic_load_i32 (&sampling_thread_exiting)) {
766 mono_threads_pthread_kill (info, profiler_signal);
767 mono_thread_info_usleep (10 * 1000 /* 10ms */);
770 // Make sure info can be freed.
771 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
773 #endif
775 mono_os_event_wait_one (&sampling_thread_exited, MONO_INFINITE_WAIT, FALSE);
776 mono_os_event_destroy (&sampling_thread_exited);
779 * We can't safely remove the signal handler because we have no guarantee
780 * that all pending signals have been delivered at this point. This should
781 * not really be a problem anyway.
783 //remove_signal_handler (profiler_signal);
786 void
787 mono_runtime_setup_stat_profiler (void)
790 * Use a real-time signal when possible. This gives us roughly a 99% signal
791 * delivery rate in all cases. On the other hand, using a regular signal
792 * tends to result in awful delivery rates when the application is heavily
793 * loaded.
795 * We avoid real-time signals on Android as they're super broken in certain
796 * API levels (too small sigset_t, nonsensical SIGRTMIN/SIGRTMAX values,
797 * etc).
799 * TODO: On Mac, we should explore using the Mach thread suspend/resume
800 * functions and doing the stack walk from the sampling thread. This would
801 * get us a 100% sampling rate. However, this may interfere with the GC's
802 * STW logic. Could perhaps be solved by taking the suspend lock.
804 #if defined (USE_POSIX_BACKEND) && defined (SIGRTMIN) && !defined (HOST_ANDROID)
805 /* Just take the first real-time signal we can get. */
806 profiler_signal = mono_threads_suspend_search_alternative_signal ();
807 #else
808 profiler_signal = SIGPROF;
809 #endif
811 add_signal_handler (profiler_signal, profiler_signal_handler, SA_RESTART);
813 mono_counters_register ("Sampling signals sent", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_sent);
814 mono_counters_register ("Sampling signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_received);
815 mono_counters_register ("Sampling signals accepted", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_accepted);
816 mono_counters_register ("Shutdown signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_interrupt_signals_received);
818 mono_os_event_init (&sampling_thread_exited, FALSE);
820 mono_atomic_store_i32 (&sampling_thread_running, 1);
822 MonoError error;
823 MonoInternalThread *thread = mono_thread_create_internal (mono_get_root_domain (), sampling_thread_func, NULL, MONO_THREAD_CREATE_FLAGS_NONE, &error);
824 mono_error_assert_ok (&error);
826 sampling_thread = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
829 #else
831 void
832 mono_runtime_shutdown_stat_profiler (void)
836 void
837 mono_runtime_setup_stat_profiler (void)
841 #endif
843 #endif /* defined(HOST_WATCHOS) */
845 static gboolean
846 native_stack_with_gdb (pid_t crashed_pid, const char **argv, FILE *commands, char* commands_filename)
848 gchar *gdb;
850 gdb = g_find_program_in_path ("gdb");
851 if (!gdb)
852 return FALSE;
854 argv [0] = gdb;
855 argv [1] = "-batch";
856 argv [2] = "-x";
857 argv [3] = commands_filename;
858 argv [4] = "-nx";
860 fprintf (commands, "attach %ld\n", (long) crashed_pid);
861 fprintf (commands, "info threads\n");
862 fprintf (commands, "thread apply all bt\n");
863 for (int i = 0; i < 32; ++i) {
864 fprintf (commands, "info registers\n");
865 fprintf (commands, "info frame\n");
866 fprintf (commands, "info locals\n");
867 fprintf (commands, "up\n");
870 return TRUE;
874 static gboolean
875 native_stack_with_lldb (pid_t crashed_pid, const char **argv, FILE *commands, char* commands_filename)
877 gchar *lldb;
879 lldb = g_find_program_in_path ("lldb");
880 if (!lldb)
881 return FALSE;
883 argv [0] = lldb;
884 argv [1] = "--batch";
885 argv [2] = "--source";
886 argv [3] = commands_filename;
887 argv [4] = "--no-lldbinit";
889 fprintf (commands, "process attach --pid %ld\n", (long) crashed_pid);
890 fprintf (commands, "thread list\n");
891 fprintf (commands, "thread backtrace all\n");
892 for (int i = 0; i < 32; ++i) {
893 fprintf (commands, "reg read\n");
894 fprintf (commands, "frame info\n");
895 fprintf (commands, "frame variable\n");
896 fprintf (commands, "up\n");
898 fprintf (commands, "detach\n");
899 fprintf (commands, "quit\n");
901 return TRUE;
904 void
905 mono_gdb_render_native_backtraces (pid_t crashed_pid)
907 #ifdef HAVE_EXECV
908 const char *argv [10];
909 FILE *commands;
910 char commands_filename [] = "/tmp/mono-gdb-commands.XXXXXX";
912 if (mkstemp (commands_filename) == -1)
913 return;
915 commands = fopen (commands_filename, "w");
916 if (!commands) {
917 unlink (commands_filename);
918 return;
921 memset (argv, 0, sizeof (char*) * 10);
923 #if defined(HOST_DARWIN)
924 if (native_stack_with_lldb (crashed_pid, argv, commands, commands_filename))
925 goto exec;
926 #endif
928 if (native_stack_with_gdb (crashed_pid, argv, commands, commands_filename))
929 goto exec;
931 #if !defined(HOST_DARWIN)
932 if (native_stack_with_lldb (crashed_pid, argv, commands, commands_filename))
933 goto exec;
934 #endif
936 fprintf (stderr, "mono_gdb_render_native_backtraces not supported on this platform, unable to find gdb or lldb\n");
938 fclose (commands);
939 unlink (commands_filename);
940 return;
942 exec:
943 fclose (commands);
944 execv (argv [0], (char**)argv);
946 _exit (-1);
947 #else
948 fprintf (stderr, "mono_gdb_render_native_backtraces not supported on this platform\n");
949 #endif // HAVE_EXECV
952 #if !defined (__MACH__)
954 gboolean
955 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info, void *sigctx)
957 g_error ("Posix systems don't support mono_thread_state_init_from_handle");
958 return FALSE;
961 #endif