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