[runtime] New profiler API.
[mono.git] / mono / mini / mini-posix.c
1 /**
2  * \file
3  * POSIX signal handling support for Mono.
4  *
5  * Authors:
6  *   Mono Team (mono-list@lists.ximian.com)
7  *
8  * Copyright 2001-2003 Ximian, Inc.
9  * Copyright 2003-2008 Ximian, Inc.
10  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11  *
12  * See LICENSE for licensing information.
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
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>
32
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.h"
44 #include <mono/metadata/profiler-private.h>
45 #include <mono/metadata/mono-config.h>
46 #include <mono/metadata/environment.h>
47 #include <mono/metadata/mono-debug.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/threads-types.h>
50 #include <mono/metadata/verify.h>
51 #include <mono/metadata/verify-internals.h>
52 #include <mono/metadata/mempool-internals.h>
53 #include <mono/metadata/attach.h>
54 #include <mono/utils/mono-math.h>
55 #include <mono/utils/mono-compiler.h>
56 #include <mono/utils/mono-counters.h>
57 #include <mono/utils/mono-logger-internals.h>
58 #include <mono/utils/mono-mmap.h>
59 #include <mono/utils/dtrace.h>
60 #include <mono/utils/mono-signal-handler.h>
61 #include <mono/utils/mono-threads.h>
62
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
70 #include "jit-icalls.h"
71
72 #ifdef PLATFORM_MACOSX
73 #include <mach/mach.h>
74 #include <mach/mach_time.h>
75 #include <mach/clock.h>
76 #endif
77
78 #if defined(HOST_WATCHOS)
79
80 void
81 mono_runtime_setup_stat_profiler (void)
82 {
83         printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
84 }
85
86
87 void
88 mono_runtime_shutdown_stat_profiler (void)
89 {
90 }
91
92
93 gboolean
94 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
95 {
96         return FALSE;
97 }
98
99 #ifndef PLATFORM_MACOSX
100 void
101 mono_runtime_install_handlers (void)
102 {
103 }
104 #endif
105
106 void
107 mono_runtime_posix_install_handlers(void)
108 {
109         /* we still need to ignore SIGPIPE */
110         signal (SIGPIPE, SIG_IGN);
111 }
112
113 void
114 mono_runtime_shutdown_handlers (void)
115 {
116 }
117
118 void
119 mono_runtime_cleanup_handlers (void)
120 {
121 }
122
123 #else
124
125 static GHashTable *mono_saved_signal_handlers = NULL;
126
127 static struct sigaction *
128 get_saved_signal_handler (int signo, gboolean remove)
129 {
130         if (mono_saved_signal_handlers) {
131                 /* The hash is only modified during startup, so no need for locking */
132                 struct sigaction *handler = g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
133                 if (remove && handler)
134                         g_hash_table_remove (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
135                 return handler;
136         }
137         return NULL;
138 }
139
140 static void
141 save_old_signal_handler (int signo, struct sigaction *old_action)
142 {
143         struct sigaction *handler_to_save = (struct sigaction *)g_malloc (sizeof (struct sigaction));
144
145         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
146                                 "Saving old signal handler for signal %d.", signo);
147
148         if (! (old_action->sa_flags & SA_SIGINFO)) {
149                 handler_to_save->sa_handler = old_action->sa_handler;
150         } else {
151 #ifdef MONO_ARCH_USE_SIGACTION
152                 handler_to_save->sa_sigaction = old_action->sa_sigaction;
153 #endif /* MONO_ARCH_USE_SIGACTION */
154         }
155         handler_to_save->sa_mask = old_action->sa_mask;
156         handler_to_save->sa_flags = old_action->sa_flags;
157         
158         if (!mono_saved_signal_handlers)
159                 mono_saved_signal_handlers = g_hash_table_new_full (NULL, NULL, NULL, g_free);
160         g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
161 }
162
163 static void
164 free_saved_signal_handlers (void)
165 {
166         if (mono_saved_signal_handlers) {
167                 g_hash_table_destroy (mono_saved_signal_handlers);
168                 mono_saved_signal_handlers = NULL;
169         }
170 }
171
172 /*
173  * mono_chain_signal:
174  *
175  *   Call the original signal handler for the signal given by the arguments, which
176  * should be the same as for a signal handler. Returns TRUE if the original handler
177  * was called, false otherwise.
178  */
179 gboolean
180 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
181 {
182         int signal = MONO_SIG_HANDLER_GET_SIGNO ();
183         struct sigaction *saved_handler = (struct sigaction *)get_saved_signal_handler (signal, FALSE);
184
185         if (saved_handler && saved_handler->sa_handler) {
186                 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
187                         saved_handler->sa_handler (signal);
188                 } else {
189 #ifdef MONO_ARCH_USE_SIGACTION
190                         saved_handler->sa_sigaction (MONO_SIG_HANDLER_PARAMS);
191 #endif /* MONO_ARCH_USE_SIGACTION */
192                 }
193                 return TRUE;
194         }
195         return FALSE;
196 }
197
198 MONO_SIG_HANDLER_FUNC (static, sigabrt_signal_handler)
199 {
200         MonoJitInfo *ji = NULL;
201         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
202         MONO_SIG_HANDLER_GET_CONTEXT;
203
204         if (mono_thread_internal_current ())
205                 ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
206         if (!ji) {
207         if (mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
208                         return;
209                 mono_handle_native_crash ("SIGABRT", ctx, info);
210         }
211 }
212
213 #if (defined (USE_POSIX_BACKEND) && defined (SIGRTMIN)) || defined (SIGPROF)
214 #define HAVE_PROFILER_SIGNAL
215 #endif
216
217 #ifdef HAVE_PROFILER_SIGNAL
218
219 static MonoNativeThreadId sampling_thread;
220
221 static gint32 profiler_signals_sent;
222 static gint32 profiler_signals_received;
223 static gint32 profiler_signals_accepted;
224 static gint32 profiler_interrupt_signals_received;
225
226 MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler)
227 {
228         int old_errno = errno;
229
230         MONO_SIG_HANDLER_GET_CONTEXT;
231
232         /* See the comment in mono_runtime_shutdown_stat_profiler (). */
233         if (mono_native_thread_id_get () == sampling_thread) {
234                 InterlockedIncrement (&profiler_interrupt_signals_received);
235                 return;
236         }
237
238         InterlockedIncrement (&profiler_signals_received);
239
240         // Did a non-attached or detaching thread get the signal?
241         if (mono_thread_info_get_small_id () == -1 ||
242             !mono_domain_get () ||
243             !mono_tls_get_jit_tls ()) {
244                 errno = old_errno;
245                 return;
246         }
247
248         // See the comment in sampling_thread_func ().
249         InterlockedWrite (&mono_thread_info_current ()->profiler_signal_ack, 1);
250
251         InterlockedIncrement (&profiler_signals_accepted);
252
253         int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
254
255         mono_thread_info_set_is_async_context (TRUE);
256
257         MONO_PROFILER_RAISE (sample_hit, (mono_arch_ip_from_context (ctx), ctx));
258
259         mono_thread_info_set_is_async_context (FALSE);
260
261         mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
262
263         errno = old_errno;
264
265         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
266 }
267
268 #endif
269
270 MONO_SIG_HANDLER_FUNC (static, sigquit_signal_handler)
271 {
272         gboolean res;
273
274         /* We use this signal to start the attach agent too */
275         res = mono_attach_start ();
276         if (res)
277                 return;
278
279         mono_threads_request_thread_dump ();
280
281         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
282 }
283
284 MONO_SIG_HANDLER_FUNC (static, sigusr2_signal_handler)
285 {
286         gboolean enabled = mono_trace_is_enabled ();
287
288         mono_trace_enable (!enabled);
289
290         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
291 }
292
293 static void
294 add_signal_handler (int signo, gpointer handler, int flags)
295 {
296         struct sigaction sa;
297         struct sigaction previous_sa;
298
299 #ifdef MONO_ARCH_USE_SIGACTION
300         sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
301         sigemptyset (&sa.sa_mask);
302         sa.sa_flags = SA_SIGINFO | flags;
303 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
304
305 /*Apple likes to deliver SIGBUS for *0 */
306 #ifdef PLATFORM_MACOSX
307         if (signo == SIGSEGV || signo == SIGBUS) {
308 #else
309         if (signo == SIGSEGV) {
310 #endif
311                 sa.sa_flags |= SA_ONSTACK;
312
313                 /* 
314                  * libgc will crash when trying to do stack marking for threads which are on
315                  * an altstack, so delay the suspend signal after the signal handler has
316                  * executed.
317                  */
318                 if (mono_gc_get_suspend_signal () != -1)
319                         sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
320         }
321 #endif
322         if (signo == SIGSEGV) {
323                 /* 
324                  * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
325                  */
326                 sigset_t block_mask;
327      
328                 sigemptyset (&block_mask);
329         }
330 #else
331         sa.sa_handler = handler;
332         sigemptyset (&sa.sa_mask);
333         sa.sa_flags = flags;
334 #endif
335         g_assert (sigaction (signo, &sa, &previous_sa) != -1);
336
337         /* if there was already a handler in place for this signal, store it */
338         if (! (previous_sa.sa_flags & SA_SIGINFO) &&
339                         (SIG_DFL == previous_sa.sa_handler)) { 
340                 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
341         } else {
342                 if (mono_do_signal_chaining)
343                         save_old_signal_handler (signo, &previous_sa);
344         }
345 }
346
347 static void
348 remove_signal_handler (int signo)
349 {
350         struct sigaction sa;
351         struct sigaction *saved_action = get_saved_signal_handler (signo, TRUE);
352
353         if (!saved_action) {
354                 sa.sa_handler = SIG_DFL;
355                 sigemptyset (&sa.sa_mask);
356                 sa.sa_flags = 0;
357
358                 sigaction (signo, &sa, NULL);
359         } else {
360                 g_assert (sigaction (signo, saved_action, NULL) != -1);
361         }
362 }
363
364 void
365 mono_runtime_posix_install_handlers (void)
366 {
367
368         sigset_t signal_set;
369
370         if (mini_get_debug_options ()->handle_sigint)
371                 add_signal_handler (SIGINT, mono_sigint_signal_handler, SA_RESTART);
372
373         add_signal_handler (SIGFPE, mono_sigfpe_signal_handler, 0);
374         add_signal_handler (SIGQUIT, sigquit_signal_handler, SA_RESTART);
375         add_signal_handler (SIGILL, mono_sigill_signal_handler, 0);
376         add_signal_handler (SIGBUS, mono_sigsegv_signal_handler, 0);
377         if (mono_jit_trace_calls != NULL)
378                 add_signal_handler (SIGUSR2, sigusr2_signal_handler, SA_RESTART);
379
380         /* it seems to have become a common bug for some programs that run as parents
381          * of many processes to block signal delivery for real time signals.
382          * We try to detect and work around their breakage here.
383          */
384         sigemptyset (&signal_set);
385         if (mono_gc_get_suspend_signal () != -1)
386                 sigaddset (&signal_set, mono_gc_get_suspend_signal ());
387         if (mono_gc_get_restart_signal () != -1)
388                 sigaddset (&signal_set, mono_gc_get_restart_signal ());
389         sigaddset (&signal_set, SIGCHLD);
390         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
391
392         signal (SIGPIPE, SIG_IGN);
393
394         add_signal_handler (SIGABRT, sigabrt_signal_handler, 0);
395
396         /* catch SIGSEGV */
397         add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler, 0);
398 }
399
400 #ifndef PLATFORM_MACOSX
401 void
402 mono_runtime_install_handlers (void)
403 {
404         mono_runtime_posix_install_handlers ();
405 }
406 #endif
407
408 void
409 mono_runtime_cleanup_handlers (void)
410 {
411         if (mini_get_debug_options ()->handle_sigint)
412                 remove_signal_handler (SIGINT);
413
414         remove_signal_handler (SIGFPE);
415         remove_signal_handler (SIGQUIT);
416         remove_signal_handler (SIGILL);
417         remove_signal_handler (SIGBUS);
418         if (mono_jit_trace_calls != NULL)
419                 remove_signal_handler (SIGUSR2);
420
421         remove_signal_handler (SIGABRT);
422
423         remove_signal_handler (SIGSEGV);
424
425         free_saved_signal_handlers ();
426 }
427
428 #ifdef HAVE_PROFILER_SIGNAL
429
430 static volatile gint32 sampling_thread_running;
431
432 #ifdef PLATFORM_MACOSX
433
434 static clock_serv_t sampling_clock_service;
435
436 static void
437 clock_init (MonoProfilerSampleMode mode)
438 {
439         kern_return_t ret;
440
441         do {
442                 ret = host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &sampling_clock_service);
443         } while (ret == KERN_ABORTED);
444
445         if (ret != KERN_SUCCESS)
446                 g_error ("%s: host_get_clock_service () returned %d", __func__, ret);
447 }
448
449 static void
450 clock_cleanup (void)
451 {
452         kern_return_t ret;
453
454         do {
455                 ret = mach_port_deallocate (mach_task_self (), sampling_clock_service);
456         } while (ret == KERN_ABORTED);
457
458         if (ret != KERN_SUCCESS)
459                 g_error ("%s: mach_port_deallocate () returned %d", __func__, ret);
460 }
461
462 static guint64
463 clock_get_time_ns (void)
464 {
465         kern_return_t ret;
466         mach_timespec_t mach_ts;
467
468         do {
469                 ret = clock_get_time (sampling_clock_service, &mach_ts);
470         } while (ret == KERN_ABORTED);
471
472         if (ret != KERN_SUCCESS)
473                 g_error ("%s: clock_get_time () returned %d", __func__, ret);
474
475         return ((guint64) mach_ts.tv_sec * 1000000000) + (guint64) mach_ts.tv_nsec;
476 }
477
478 static void
479 clock_sleep_ns_abs (guint64 ns_abs)
480 {
481         kern_return_t ret;
482         mach_timespec_t then, remain_unused;
483
484         then.tv_sec = ns_abs / 1000000000;
485         then.tv_nsec = ns_abs % 1000000000;
486
487         do {
488                 ret = clock_sleep (sampling_clock_service, TIME_ABSOLUTE, then, &remain_unused);
489
490                 if (ret != KERN_SUCCESS && ret != KERN_ABORTED)
491                         g_error ("%s: clock_sleep () returned %d", __func__, ret);
492         } while (ret == KERN_ABORTED && InterlockedRead (&sampling_thread_running));
493 }
494
495 #else
496
497 clockid_t sampling_posix_clock;
498
499 static void
500 clock_init (MonoProfilerSampleMode mode)
501 {
502         switch (mode) {
503         case MONO_PROFILER_SAMPLE_MODE_PROCESS: {
504         /*
505          * If we don't have clock_nanosleep (), measuring the process time
506          * makes very little sense as we can only use nanosleep () to sleep on
507          * real time.
508          */
509 #ifdef HAVE_CLOCK_NANOSLEEP
510                 struct timespec ts = { 0 };
511
512                 /*
513                  * Some systems (e.g. Windows Subsystem for Linux) declare the
514                  * CLOCK_PROCESS_CPUTIME_ID clock but don't actually support it. For
515                  * those systems, we fall back to CLOCK_MONOTONIC if we get EINVAL.
516                  */
517                 if (clock_nanosleep (CLOCK_PROCESS_CPUTIME_ID, TIMER_ABSTIME, &ts, NULL) != EINVAL) {
518                         sampling_posix_clock = CLOCK_PROCESS_CPUTIME_ID;
519                         break;
520                 }
521 #endif
522
523                 // fallthrough
524         }
525         case MONO_PROFILER_SAMPLE_MODE_REAL: sampling_posix_clock = CLOCK_MONOTONIC; break;
526         default: g_assert_not_reached (); break;
527         }
528 }
529
530 static void
531 clock_cleanup (void)
532 {
533 }
534
535 static guint64
536 clock_get_time_ns (void)
537 {
538         struct timespec ts;
539
540         if (clock_gettime (sampling_posix_clock, &ts) == -1)
541                 g_error ("%s: clock_gettime () returned -1, errno = %d", __func__, errno);
542
543         return ((guint64) ts.tv_sec * 1000000000) + (guint64) ts.tv_nsec;
544 }
545
546 static void
547 clock_sleep_ns_abs (guint64 ns_abs)
548 {
549 #ifdef HAVE_CLOCK_NANOSLEEP
550         int ret;
551         struct timespec then;
552
553         then.tv_sec = ns_abs / 1000000000;
554         then.tv_nsec = ns_abs % 1000000000;
555
556         do {
557                 ret = clock_nanosleep (sampling_posix_clock, TIMER_ABSTIME, &then, NULL);
558
559                 if (ret != 0 && ret != EINTR)
560                         g_error ("%s: clock_nanosleep () returned %d", __func__, ret);
561         } while (ret == EINTR && InterlockedRead (&sampling_thread_running));
562 #else
563         int ret;
564         gint64 diff;
565         struct timespec req;
566
567         /*
568          * What follows is a crude attempt at emulating clock_nanosleep () on OSs
569          * which don't provide it (e.g. FreeBSD).
570          *
571          * The problem with nanosleep () is that if it is interrupted by a signal,
572          * time will drift as a result of having to restart the call after the
573          * signal handler has finished. For this reason, we avoid using the rem
574          * argument of nanosleep (). Instead, before every nanosleep () call, we
575          * check if enough time has passed to satisfy the sleep request. If yes, we
576          * simply return. If not, we calculate the difference and do another sleep.
577          *
578          * This should reduce the amount of drift that happens because we account
579          * for the time spent executing the signal handler, which nanosleep () is
580          * not guaranteed to do for the rem argument.
581          *
582          * The downside to this approach is that it is slightly expensive: We have
583          * to make an extra system call to retrieve the current time whenever we're
584          * going to restart a nanosleep () call. This is unlikely to be a problem
585          * in practice since the sampling thread won't be receiving many signals in
586          * the first place (it's a tools thread, so no STW), and because typical
587          * sleep periods for the thread are many orders of magnitude bigger than
588          * the time it takes to actually perform that system call (just a few
589          * nanoseconds).
590          */
591         do {
592                 diff = (gint64) ns_abs - (gint64) clock_get_time_ns ();
593
594                 if (diff <= 0)
595                         break;
596
597                 req.tv_sec = diff / 1000000000;
598                 req.tv_nsec = diff % 1000000000;
599
600                 if ((ret = nanosleep (&req, NULL)) == -1 && errno != EINTR)
601                         g_error ("%s: nanosleep () returned -1, errno = %d", __func__, errno);
602         } while (ret == -1 && InterlockedRead (&sampling_thread_running));
603 #endif
604 }
605
606 #endif
607
608 static int profiler_signal;
609 static volatile gint32 sampling_thread_exiting;
610
611 static mono_native_thread_return_t
612 sampling_thread_func (void *data)
613 {
614         mono_threads_attach_tools_thread ();
615         mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler sampler");
616
617         int old_policy;
618         struct sched_param old_sched;
619         pthread_getschedparam (pthread_self (), &old_policy, &old_sched);
620
621         /*
622          * Attempt to switch the thread to real time scheduling. This will not
623          * necessarily work on all OSs; for example, most Linux systems will give
624          * us EPERM here unless configured to allow this.
625          *
626          * TODO: This does not work on Mac (and maybe some other OSs). On Mac, we
627          * have to use the Mach thread policy routines to switch to real-time
628          * scheduling. This is quite tricky as we need to specify how often we'll
629          * be doing work (easy), the normal processing time needed (also easy),
630          * and the maximum amount of processing time needed (hard). This is
631          * further complicated by the fact that if we misbehave and take too long
632          * to do our work, the kernel may knock us back down to the normal thread
633          * scheduling policy without telling us.
634          */
635         struct sched_param sched = { .sched_priority = sched_get_priority_max (SCHED_FIFO) };
636         pthread_setschedparam (pthread_self (), SCHED_FIFO, &sched);
637
638         MonoProfilerSampleMode mode;
639
640 init:
641         mono_profiler_get_sample_mode (NULL, &mode, NULL);
642
643         if (mode == MONO_PROFILER_SAMPLE_MODE_NONE) {
644                 mono_profiler_sampling_thread_sleep ();
645                 goto init;
646         }
647
648         clock_init (mode);
649
650         for (guint64 sleep = clock_get_time_ns (); InterlockedRead (&sampling_thread_running); clock_sleep_ns_abs (sleep)) {
651                 uint64_t freq;
652                 MonoProfilerSampleMode new_mode;
653
654                 mono_profiler_get_sample_mode (NULL, &new_mode, &freq);
655
656                 if (new_mode != mode) {
657                         clock_cleanup ();
658                         goto init;
659                 }
660
661                 sleep += 1000000000 / freq;
662
663                 FOREACH_THREAD_SAFE (info) {
664                         /* info should never be this thread as we're a tools thread. */
665                         g_assert (mono_thread_info_get_tid (info) != mono_native_thread_id_get ());
666
667                         /*
668                          * Require an ack for the last sampling signal sent to the thread
669                          * so that we don't overflow the signal queue, leading to all sorts
670                          * of problems (e.g. GC STW failing).
671                          */
672                         if (profiler_signal != SIGPROF && !InterlockedCompareExchange (&info->profiler_signal_ack, 0, 1))
673                                 continue;
674
675                         mono_threads_pthread_kill (info, profiler_signal);
676                         InterlockedIncrement (&profiler_signals_sent);
677                 } FOREACH_THREAD_SAFE_END
678         }
679
680         InterlockedWrite (&sampling_thread_exiting, 1);
681
682         clock_cleanup ();
683
684         pthread_setschedparam (pthread_self (), old_policy, &old_sched);
685
686         mono_thread_info_detach ();
687
688         return NULL;
689 }
690
691 void
692 mono_runtime_shutdown_stat_profiler (void)
693 {
694         InterlockedWrite (&sampling_thread_running, 0);
695
696 #ifndef PLATFORM_MACOSX
697         /*
698          * There is a slight problem when we're using CLOCK_PROCESS_CPUTIME_ID: If
699          * we're shutting down and there's largely no activity in the process other
700          * than waiting for the sampler thread to shut down, it can take upwards of
701          * 20 seconds (depending on a lot of factors) for us to shut down because
702          * the sleep progresses very slowly as a result of the low CPU activity.
703          *
704          * We fix this by repeatedly sending the profiler signal to the sampler
705          * thread in order to interrupt the sleep. clock_sleep_ns_abs () will check
706          * sampling_thread_running upon an interrupt and return immediately if it's
707          * zero. profiler_signal_handler () has a special case to ignore the signal
708          * for the sampler thread.
709          */
710         MonoThreadInfo *info;
711
712         // Did it shut down already?
713         if ((info = mono_thread_info_lookup (sampling_thread))) {
714                 while (!InterlockedRead (&sampling_thread_exiting)) {
715                         mono_threads_pthread_kill (info, profiler_signal);
716                         mono_thread_info_usleep (10 * 1000 /* 10ms */);
717                 }
718
719                 // Make sure info can be freed.
720                 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
721         }
722 #endif
723
724         mono_native_thread_join (sampling_thread);
725
726         /*
727          * We can't safely remove the signal handler because we have no guarantee
728          * that all pending signals have been delivered at this point. This should
729          * not really be a problem anyway.
730          */
731         //remove_signal_handler (profiler_signal);
732 }
733
734 void
735 mono_runtime_setup_stat_profiler (void)
736 {
737         /*
738          * Use a real-time signal when possible. This gives us roughly a 99% signal
739          * delivery rate in all cases. On the other hand, using a regular signal
740          * tends to result in awful delivery rates when the application is heavily
741          * loaded.
742          *
743          * We avoid real-time signals on Android as they're super broken in certain
744          * API levels (too small sigset_t, nonsensical SIGRTMIN/SIGRTMAX values,
745          * etc).
746          *
747          * TODO: On Mac, we should explore using the Mach thread suspend/resume
748          * functions and doing the stack walk from the sampling thread. This would
749          * get us a 100% sampling rate. However, this may interfere with the GC's
750          * STW logic. Could perhaps be solved by taking the suspend lock.
751          */
752 #if defined (USE_POSIX_BACKEND) && defined (SIGRTMIN) && !defined (PLATFORM_ANDROID)
753         /* Just take the first real-time signal we can get. */
754         profiler_signal = mono_threads_suspend_search_alternative_signal ();
755 #else
756         profiler_signal = SIGPROF;
757 #endif
758
759         add_signal_handler (profiler_signal, profiler_signal_handler, SA_RESTART);
760
761         mono_counters_register ("Sampling signals sent", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_sent);
762         mono_counters_register ("Sampling signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_received);
763         mono_counters_register ("Sampling signals accepted", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_accepted);
764         mono_counters_register ("Shutdown signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_interrupt_signals_received);
765
766         InterlockedWrite (&sampling_thread_running, 1);
767         mono_native_thread_create (&sampling_thread, sampling_thread_func, NULL);
768 }
769
770 #else
771
772 void
773 mono_runtime_shutdown_stat_profiler (void)
774 {
775 }
776
777 void
778 mono_runtime_setup_stat_profiler (void)
779 {
780 }
781
782 #endif
783
784 #endif /* defined(HOST_WATCHOS) */
785
786 static gboolean
787 native_stack_with_gdb (pid_t crashed_pid, const char **argv, FILE *commands, char* commands_filename)
788 {
789         gchar *gdb;
790
791         gdb = g_find_program_in_path ("gdb");
792         if (!gdb)
793                 return FALSE;
794
795         argv [0] = gdb;
796         argv [1] = "-batch";
797         argv [2] = "-x";
798         argv [3] = commands_filename;
799         argv [4] = "-nx";
800
801         fprintf (commands, "attach %ld\n", (long) crashed_pid);
802         fprintf (commands, "info threads\n");
803         fprintf (commands, "thread apply all bt\n");
804
805         return TRUE;
806 }
807
808
809 static gboolean
810 native_stack_with_lldb (pid_t crashed_pid, const char **argv, FILE *commands, char* commands_filename)
811 {
812         gchar *lldb;
813
814         lldb = g_find_program_in_path ("lldb");
815         if (!lldb)
816                 return FALSE;
817
818         argv [0] = lldb;
819         argv [1] = "--batch";
820         argv [2] = "--source";
821         argv [3] = commands_filename;
822         argv [4] = "--no-lldbinit";
823
824         fprintf (commands, "process attach --pid %ld\n", (long) crashed_pid);
825         fprintf (commands, "thread list\n");
826         fprintf (commands, "thread backtrace all\n");
827         fprintf (commands, "detach\n");
828         fprintf (commands, "quit\n");
829
830         return TRUE;
831 }
832
833 void
834 mono_gdb_render_native_backtraces (pid_t crashed_pid)
835 {
836 #ifdef HAVE_EXECV
837         const char *argv [10];
838         FILE *commands;
839         char commands_filename [] = "/tmp/mono-gdb-commands.XXXXXX";
840
841         if (mkstemp (commands_filename) == -1)
842                 return;
843
844         commands = fopen (commands_filename, "w");
845         if (!commands) {
846                 unlink (commands_filename);
847                 return;
848         }
849
850         memset (argv, 0, sizeof (char*) * 10);
851
852 #if defined(PLATFORM_MACOSX)
853         if (native_stack_with_lldb (crashed_pid, argv, commands, commands_filename))
854                 goto exec;
855 #endif
856
857         if (native_stack_with_gdb (crashed_pid, argv, commands, commands_filename))
858                 goto exec;
859
860 #if !defined(PLATFORM_MACOSX)
861         if (native_stack_with_lldb (crashed_pid, argv, commands, commands_filename))
862                 goto exec;
863 #endif
864
865         fprintf (stderr, "mono_gdb_render_native_backtraces not supported on this platform, unable to find gdb or lldb\n");
866
867         fclose (commands);
868         unlink (commands_filename);
869         return;
870
871 exec:
872         fclose (commands);
873         execv (argv [0], (char**)argv);
874
875         _exit (-1);
876 #else
877         fprintf (stderr, "mono_gdb_render_native_backtraces not supported on this platform\n");
878 #endif // HAVE_EXECV
879 }
880
881 #if !defined (__MACH__)
882
883 gboolean
884 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
885 {
886         g_error ("Posix systems don't support mono_thread_state_init_from_handle");
887         return FALSE;
888 }
889
890 #endif