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