[mini] Provide a free function to the saved signal handler hash table.
[mono.git] / mono / mini / mini-posix.c
1 /*
2  * mini-posix.c: POSIX signal handling support for Mono.
3  *
4  * Authors:
5  *   Mono Team (mono-list@lists.ximian.com)
6  *
7  * Copyright 2001-2003 Ximian, Inc.
8  * Copyright 2003-2008 Ximian, Inc.
9  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
10  *
11  * See LICENSE for licensing information.
12  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13  */
14 #include <config.h>
15 #include <signal.h>
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
22 #include <math.h>
23 #ifdef HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 #endif
26 #ifdef HAVE_SYS_SYSCALL_H
27 #include <sys/syscall.h>
28 #endif
29 #include <errno.h>
30 #include <sched.h>
31
32 #include <mono/metadata/assembly.h>
33 #include <mono/metadata/loader.h>
34 #include <mono/metadata/tabledefs.h>
35 #include <mono/metadata/class.h>
36 #include <mono/metadata/object.h>
37 #include <mono/metadata/tokentype.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/threads.h>
40 #include <mono/metadata/appdomain.h>
41 #include <mono/metadata/debug-helpers.h>
42 #include <mono/io-layer/io-layer.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 #include <mono/utils/mono-threads-posix-signals.h>
63
64 #include "mini.h"
65 #include <string.h>
66 #include <ctype.h>
67 #include "trace.h"
68 #include "version.h"
69 #include "debugger-agent.h"
70
71 #include "jit-icalls.h"
72
73 #ifdef PLATFORM_MACOSX
74 #include <mach/mach.h>
75 #include <mach/mach_time.h>
76 #include <mach/clock.h>
77 #endif
78
79 #if defined(__native_client__) || defined(HOST_WATCHOS)
80
81 void
82 mono_runtime_setup_stat_profiler (void)
83 {
84         printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
85 }
86
87
88 void
89 mono_runtime_shutdown_stat_profiler (void)
90 {
91 }
92
93
94 gboolean
95 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
96 {
97         return FALSE;
98 }
99
100 #ifndef PLATFORM_MACOSX
101 void
102 mono_runtime_install_handlers (void)
103 {
104 }
105 #endif
106
107 void
108 mono_runtime_posix_install_handlers(void)
109 {
110         /* we still need to ignore SIGPIPE */
111         signal (SIGPIPE, SIG_IGN);
112 }
113
114 void
115 mono_runtime_shutdown_handlers (void)
116 {
117 }
118
119 void
120 mono_runtime_cleanup_handlers (void)
121 {
122 }
123
124 #if !defined(PLATFORM_MACOSX)
125 pid_t
126 mono_runtime_syscall_fork (void)
127 {
128         g_assert_not_reached();
129         return 0;
130 }
131
132 void
133 mono_gdb_render_native_backtraces (pid_t crashed_pid)
134 {
135 }
136 #endif
137
138 #else
139
140 static GHashTable *mono_saved_signal_handlers = NULL;
141
142 static struct sigaction *
143 get_saved_signal_handler (int signo)
144 {
145         if (mono_saved_signal_handlers)
146                 /* The hash is only modified during startup, so no need for locking */
147                 return (struct sigaction *)g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
148         return NULL;
149 }
150
151 static void
152 save_old_signal_handler (int signo, struct sigaction *old_action)
153 {
154         struct sigaction *handler_to_save = (struct sigaction *)g_malloc (sizeof (struct sigaction));
155
156         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
157                                 "Saving old signal handler for signal %d.", signo);
158
159         if (! (old_action->sa_flags & SA_SIGINFO)) {
160                 handler_to_save->sa_handler = old_action->sa_handler;
161         } else {
162 #ifdef MONO_ARCH_USE_SIGACTION
163                 handler_to_save->sa_sigaction = old_action->sa_sigaction;
164 #endif /* MONO_ARCH_USE_SIGACTION */
165         }
166         handler_to_save->sa_mask = old_action->sa_mask;
167         handler_to_save->sa_flags = old_action->sa_flags;
168         
169         if (!mono_saved_signal_handlers)
170                 mono_saved_signal_handlers = g_hash_table_new_full (NULL, NULL, NULL, g_free);
171         g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
172 }
173
174 static void
175 free_saved_signal_handlers (void)
176 {
177         if (mono_saved_signal_handlers) {
178                 g_hash_table_destroy (mono_saved_signal_handlers);
179                 mono_saved_signal_handlers = NULL;
180         }
181 }
182
183 /*
184  * mono_chain_signal:
185  *
186  *   Call the original signal handler for the signal given by the arguments, which
187  * should be the same as for a signal handler. Returns TRUE if the original handler
188  * was called, false otherwise.
189  */
190 gboolean
191 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
192 {
193         int signal = MONO_SIG_HANDLER_GET_SIGNO ();
194         struct sigaction *saved_handler = (struct sigaction *)get_saved_signal_handler (signal);
195
196         if (saved_handler && saved_handler->sa_handler) {
197                 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
198                         saved_handler->sa_handler (signal);
199                 } else {
200 #ifdef MONO_ARCH_USE_SIGACTION
201                         saved_handler->sa_sigaction (MONO_SIG_HANDLER_PARAMS);
202 #endif /* MONO_ARCH_USE_SIGACTION */
203                 }
204                 return TRUE;
205         }
206         return FALSE;
207 }
208
209 MONO_SIG_HANDLER_FUNC (static, sigabrt_signal_handler)
210 {
211         MonoJitInfo *ji = NULL;
212         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
213         MONO_SIG_HANDLER_GET_CONTEXT;
214
215         if (mono_thread_internal_current ())
216                 ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
217         if (!ji) {
218         if (mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
219                         return;
220                 mono_handle_native_sigsegv (SIGABRT, ctx, info);
221         }
222 }
223
224 #if defined(__i386__) || defined(__x86_64__)
225 #define FULL_STAT_PROFILER_BACKTRACE 1
226 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
227 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
228 #if MONO_ARCH_STACK_GROWS_UP
229 #define IS_BEFORE_ON_STACK <
230 #define IS_AFTER_ON_STACK >
231 #else
232 #define IS_BEFORE_ON_STACK >
233 #define IS_AFTER_ON_STACK <
234 #endif
235 #else
236 #define FULL_STAT_PROFILER_BACKTRACE 0
237 #endif
238
239 #if (defined (USE_POSIX_BACKEND) && defined (SIGRTMIN)) || defined (SIGPROF)
240 #define HAVE_PROFILER_SIGNAL
241 #endif
242
243 #ifdef HAVE_PROFILER_SIGNAL
244
245 static void
246 per_thread_profiler_hit (void *ctx)
247 {
248         int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
249         MonoProfilerCallChainStrategy call_chain_strategy = mono_profiler_stat_get_call_chain_strategy ();
250
251         if (call_chain_depth == 0) {
252                 mono_profiler_stat_hit ((guchar *)mono_arch_ip_from_context (ctx), ctx);
253         } else {
254                 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
255                 int current_frame_index = 1;
256                 MonoContext mono_context;
257                 guchar *ips [call_chain_depth + 1];
258
259                 mono_sigctx_to_monoctx (ctx, &mono_context);
260                 ips [0] = (guchar *)MONO_CONTEXT_GET_IP (&mono_context);
261                 
262                 if (jit_tls != NULL) {
263                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_NATIVE) {
264 #if FULL_STAT_PROFILER_BACKTRACE
265                         guchar *current_frame;
266                         guchar *stack_bottom;
267                         guchar *stack_top;
268                         
269                         stack_bottom = (guchar *)jit_tls->end_of_stack;
270                         stack_top = (guchar *)MONO_CONTEXT_GET_SP (&mono_context);
271                         current_frame = (guchar *)MONO_CONTEXT_GET_BP (&mono_context);
272                         
273                         while ((current_frame_index <= call_chain_depth) &&
274                                         (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
275                                         ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
276                                 ips [current_frame_index] = (guchar *)CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
277                                 current_frame_index ++;
278                                 stack_top = current_frame;
279                                 current_frame = (guchar *)CURRENT_FRAME_GET_BASE_POINTER (current_frame);
280                         }
281 #else
282                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_GLIBC;
283 #endif
284                         }
285                         
286                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_GLIBC) {
287 #if GLIBC_PROFILER_BACKTRACE
288                                 current_frame_index = backtrace ((void**) & ips [1], call_chain_depth);
289 #else
290                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_MANAGED;
291 #endif
292                         }
293
294                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_MANAGED) {
295                                 MonoDomain *domain = mono_domain_get ();
296                                 if (domain != NULL) {
297                                         MonoLMF *lmf = NULL;
298                                         MonoJitInfo *ji;
299                                         MonoJitInfo res;
300                                         MonoContext new_mono_context;
301                                         int native_offset;
302                                         ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
303                                                         &new_mono_context, NULL, &lmf, &native_offset, NULL);
304                                         while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
305                                                 ips [current_frame_index] = (guchar *)MONO_CONTEXT_GET_IP (&new_mono_context);
306                                                 current_frame_index ++;
307                                                 mono_context = new_mono_context;
308                                                 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
309                                                                 &new_mono_context, NULL, &lmf, &native_offset, NULL);
310                                         }
311                                 }
312                         }
313                 }
314                 
315                 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
316         }
317 }
318
319 static MonoNativeThreadId sampling_thread;
320
321 static gint32 profiler_signals_sent;
322 static gint32 profiler_signals_received;
323 static gint32 profiler_signals_accepted;
324 static gint32 profiler_interrupt_signals_received;
325
326 MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler)
327 {
328         int old_errno = errno;
329         int hp_save_index;
330         MONO_SIG_HANDLER_GET_CONTEXT;
331
332         /* See the comment in mono_runtime_shutdown_stat_profiler (). */
333         if (mono_native_thread_id_get () == sampling_thread) {
334 #ifdef HAVE_CLOCK_NANOSLEEP
335                 if (mono_profiler_get_sampling_mode () == MONO_PROFILER_STAT_MODE_PROCESS) {
336                         InterlockedIncrement (&profiler_interrupt_signals_received);
337                         return;
338                 }
339 #endif
340
341                 g_error ("%s: Unexpected profiler signal received by the sampler thread", __func__);
342         }
343
344         InterlockedIncrement (&profiler_signals_received);
345
346         if (mono_thread_info_get_small_id () == -1)
347                 return; //an non-attached thread got the signal
348
349         if (!mono_domain_get () || !mono_native_tls_get_value (mono_jit_tls_id))
350                 return; //thread in the process of dettaching
351
352         InterlockedIncrement (&profiler_signals_accepted);
353
354         hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
355
356         mono_thread_info_set_is_async_context (TRUE);
357         per_thread_profiler_hit (ctx);
358         mono_thread_info_set_is_async_context (FALSE);
359
360         mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
361         errno = old_errno;
362
363         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
364 }
365
366 #endif
367
368 MONO_SIG_HANDLER_FUNC (static, sigquit_signal_handler)
369 {
370         gboolean res;
371
372         /* We use this signal to start the attach agent too */
373         res = mono_attach_start ();
374         if (res)
375                 return;
376
377         mono_threads_request_thread_dump ();
378
379         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
380 }
381
382 MONO_SIG_HANDLER_FUNC (static, sigusr2_signal_handler)
383 {
384         gboolean enabled = mono_trace_is_enabled ();
385
386         mono_trace_enable (!enabled);
387
388         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
389 }
390
391 static void
392 add_signal_handler (int signo, gpointer handler, int flags)
393 {
394         struct sigaction sa;
395         struct sigaction previous_sa;
396
397 #ifdef MONO_ARCH_USE_SIGACTION
398         sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
399         sigemptyset (&sa.sa_mask);
400         sa.sa_flags = SA_SIGINFO | flags;
401 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
402
403 /*Apple likes to deliver SIGBUS for *0 */
404 #ifdef PLATFORM_MACOSX
405         if (signo == SIGSEGV || signo == SIGBUS) {
406 #else
407         if (signo == SIGSEGV) {
408 #endif
409                 sa.sa_flags |= SA_ONSTACK;
410
411                 /* 
412                  * libgc will crash when trying to do stack marking for threads which are on
413                  * an altstack, so delay the suspend signal after the signal handler has
414                  * executed.
415                  */
416                 if (mono_gc_get_suspend_signal () != -1)
417                         sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
418         }
419 #endif
420         if (signo == SIGSEGV) {
421                 /* 
422                  * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
423                  */
424                 sigset_t block_mask;
425      
426                 sigemptyset (&block_mask);
427         }
428 #else
429         sa.sa_handler = handler;
430         sigemptyset (&sa.sa_mask);
431         sa.sa_flags = flags;
432 #endif
433         g_assert (sigaction (signo, &sa, &previous_sa) != -1);
434
435         /* if there was already a handler in place for this signal, store it */
436         if (! (previous_sa.sa_flags & SA_SIGINFO) &&
437                         (SIG_DFL == previous_sa.sa_handler)) { 
438                 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
439         } else {
440                 if (mono_do_signal_chaining)
441                         save_old_signal_handler (signo, &previous_sa);
442         }
443 }
444
445 static void
446 remove_signal_handler (int signo)
447 {
448         struct sigaction sa;
449         struct sigaction *saved_action = get_saved_signal_handler (signo);
450
451         if (!saved_action) {
452                 sa.sa_handler = SIG_DFL;
453                 sigemptyset (&sa.sa_mask);
454                 sa.sa_flags = 0;
455
456                 sigaction (signo, &sa, NULL);
457         } else {
458                 g_assert (sigaction (signo, saved_action, NULL) != -1);
459         }
460 }
461
462 void
463 mono_runtime_posix_install_handlers (void)
464 {
465
466         sigset_t signal_set;
467
468         if (mini_get_debug_options ()->handle_sigint)
469                 add_signal_handler (SIGINT, mono_sigint_signal_handler, SA_RESTART);
470
471         add_signal_handler (SIGFPE, mono_sigfpe_signal_handler, 0);
472         add_signal_handler (SIGQUIT, sigquit_signal_handler, SA_RESTART);
473         add_signal_handler (SIGILL, mono_sigill_signal_handler, 0);
474         add_signal_handler (SIGBUS, mono_sigsegv_signal_handler, 0);
475         if (mono_jit_trace_calls != NULL)
476                 add_signal_handler (SIGUSR2, sigusr2_signal_handler, SA_RESTART);
477
478         /* it seems to have become a common bug for some programs that run as parents
479          * of many processes to block signal delivery for real time signals.
480          * We try to detect and work around their breakage here.
481          */
482         sigemptyset (&signal_set);
483         if (mono_gc_get_suspend_signal () != -1)
484                 sigaddset (&signal_set, mono_gc_get_suspend_signal ());
485         if (mono_gc_get_restart_signal () != -1)
486                 sigaddset (&signal_set, mono_gc_get_restart_signal ());
487         sigaddset (&signal_set, SIGCHLD);
488         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
489
490         signal (SIGPIPE, SIG_IGN);
491
492         add_signal_handler (SIGABRT, sigabrt_signal_handler, 0);
493
494         /* catch SIGSEGV */
495         add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler, 0);
496 }
497
498 #ifndef PLATFORM_MACOSX
499 void
500 mono_runtime_install_handlers (void)
501 {
502         mono_runtime_posix_install_handlers ();
503 }
504 #endif
505
506 void
507 mono_runtime_cleanup_handlers (void)
508 {
509         if (mini_get_debug_options ()->handle_sigint)
510                 remove_signal_handler (SIGINT);
511
512         remove_signal_handler (SIGFPE);
513         remove_signal_handler (SIGQUIT);
514         remove_signal_handler (SIGILL);
515         remove_signal_handler (SIGBUS);
516         if (mono_jit_trace_calls != NULL)
517                 remove_signal_handler (SIGUSR2);
518
519         remove_signal_handler (SIGABRT);
520
521         remove_signal_handler (SIGSEGV);
522
523         free_saved_signal_handlers ();
524 }
525
526 #ifdef HAVE_PROFILER_SIGNAL
527
528 static volatile gint32 sampling_thread_running;
529
530 #ifdef PLATFORM_MACOSX
531
532 static clock_serv_t sampling_clock_service;
533
534 static void
535 clock_init (void)
536 {
537         kern_return_t ret;
538
539         do {
540                 ret = host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &sampling_clock_service);
541         } while (ret == KERN_ABORTED);
542
543         if (ret != KERN_SUCCESS)
544                 g_error ("%s: host_get_clock_service () returned %d", __func__, ret);
545 }
546
547 static void
548 clock_cleanup (void)
549 {
550         kern_return_t ret;
551
552         do {
553                 ret = mach_port_deallocate (mach_task_self (), sampling_clock_service);
554         } while (ret == KERN_ABORTED);
555
556         if (ret != KERN_SUCCESS)
557                 g_error ("%s: mach_port_deallocate () returned %d", __func__, ret);
558 }
559
560 static guint64
561 clock_get_time_ns (void)
562 {
563         kern_return_t ret;
564         mach_timespec_t mach_ts;
565
566         do {
567                 ret = clock_get_time (sampling_clock_service, &mach_ts);
568         } while (ret == KERN_ABORTED);
569
570         if (ret != KERN_SUCCESS)
571                 g_error ("%s: clock_get_time () returned %d", __func__, ret);
572
573         return ((guint64) mach_ts.tv_sec * 1000000000) + (guint64) mach_ts.tv_nsec;
574 }
575
576 static void
577 clock_sleep_ns_abs (guint64 ns_abs)
578 {
579         kern_return_t ret;
580         mach_timespec_t then, remain_unused;
581
582         then.tv_sec = ns_abs / 1000000000;
583         then.tv_nsec = ns_abs % 1000000000;
584
585         do {
586                 ret = clock_sleep (sampling_clock_service, TIME_ABSOLUTE, then, &remain_unused);
587
588                 if (ret != KERN_SUCCESS && ret != KERN_ABORTED)
589                         g_error ("%s: clock_sleep () returned %d", __func__, ret);
590         } while (ret == KERN_ABORTED && InterlockedRead (&sampling_thread_running));
591 }
592
593 #else
594
595 clockid_t sampling_posix_clock;
596
597 static void
598 clock_init (void)
599 {
600         switch (mono_profiler_get_sampling_mode ()) {
601         case MONO_PROFILER_STAT_MODE_PROCESS:
602 #ifdef HAVE_CLOCK_NANOSLEEP
603                 /*
604                  * If we don't have clock_nanosleep (), measuring the process time
605                  * makes very little sense as we can only use nanosleep () to sleep on
606                  * real time.
607                  */
608                 sampling_posix_clock = CLOCK_PROCESS_CPUTIME_ID;
609                 break;
610 #endif
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                         mono_threads_pthread_kill (info, profiler_signal);
738                         InterlockedIncrement (&profiler_signals_sent);
739                 } FOREACH_THREAD_SAFE_END
740
741                 clock_sleep_ns_abs (sleep);
742         }
743
744         InterlockedWrite (&sampling_thread_exiting, 1);
745
746         clock_cleanup ();
747
748         pthread_setschedparam (pthread_self (), old_policy, &old_sched);
749
750         mono_thread_info_detach ();
751
752         return NULL;
753 }
754
755 void
756 mono_runtime_shutdown_stat_profiler (void)
757 {
758         InterlockedWrite (&sampling_thread_running, 0);
759
760 #ifdef HAVE_CLOCK_NANOSLEEP
761         /*
762          * There is a slight problem when we're using CLOCK_PROCESS_CPUTIME_ID: If
763          * we're shutting down and there's largely no activity in the process other
764          * than waiting for the sampler thread to shut down, it can take upwards of
765          * 20 seconds (depending on a lot of factors) for us to shut down because
766          * the sleep progresses very slowly as a result of the low CPU activity.
767          *
768          * We fix this by repeatedly sending the profiler signal to the sampler
769          * thread in order to interrupt the sleep. clock_sleep_ns_abs () will check
770          * sampling_thread_running upon an interrupt and return immediately if it's
771          * zero. profiler_signal_handler () has a special case to ignore the signal
772          * for the sampler thread.
773          *
774          * We do not need to do this on platforms where we use a regular sleep
775          * based on a monotonic clock. The sleep will return in a reasonable amount
776          * of time in those cases.
777          */
778         if (mono_profiler_get_sampling_mode () == MONO_PROFILER_STAT_MODE_PROCESS) {
779                 MonoThreadInfo *info;
780
781                 // Did it shut down already?
782                 if ((info = mono_thread_info_lookup (sampling_thread))) {
783                         while (!InterlockedRead (&sampling_thread_exiting)) {
784                                 mono_threads_pthread_kill (info, profiler_signal);
785                                 mono_thread_info_usleep (10 * 1000 /* 10ms */);
786                         }
787
788                         // Make sure info can be freed.
789                         mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
790                 }
791         }
792 #endif
793
794         pthread_join (sampling_thread, NULL);
795
796         /*
797          * We can't safely remove the signal handler because we have no guarantee
798          * that all pending signals have been delivered at this point. This should
799          * not really be a problem anyway.
800          */
801         //remove_signal_handler (profiler_signal);
802 }
803
804 void
805 mono_runtime_setup_stat_profiler (void)
806 {
807         /*
808          * Use a real-time signal when possible. This gives us roughly a 99% signal
809          * delivery rate in all cases. On the other hand, using a regular signal
810          * tends to result in awful delivery rates when the application is heavily
811          * loaded.
812          *
813          * We avoid real-time signals on Android as they're super broken in certain
814          * API levels (too small sigset_t, nonsensical SIGRTMIN/SIGRTMAX values,
815          * etc).
816          *
817          * TODO: On Mac, we should explore using the Mach thread suspend/resume
818          * functions and doing the stack walk from the sampling thread. This would
819          * get us a 100% sampling rate. However, this may interfere with the GC's
820          * STW logic. Could perhaps be solved by taking the suspend lock.
821          */
822 #if defined (USE_POSIX_BACKEND) && defined (SIGRTMIN) && !defined (PLATFORM_ANDROID)
823         /* Just take the first real-time signal we can get. */
824         profiler_signal = mono_threads_posix_signal_search_alternative (-1);
825 #else
826         profiler_signal = SIGPROF;
827 #endif
828
829         add_signal_handler (profiler_signal, profiler_signal_handler, SA_RESTART);
830
831         mono_counters_register ("Sampling signals sent", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_sent);
832         mono_counters_register ("Sampling signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_received);
833         mono_counters_register ("Sampling signals accepted", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_accepted);
834         mono_counters_register ("Shutdown signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_interrupt_signals_received);
835
836         InterlockedWrite (&sampling_thread_running, 1);
837         mono_native_thread_create (&sampling_thread, sampling_thread_func, NULL);
838 }
839
840 #else
841
842 void
843 mono_runtime_shutdown_stat_profiler (void)
844 {
845 }
846
847 void
848 mono_runtime_setup_stat_profiler (void)
849 {
850 }
851
852 #endif
853
854 #if !defined(PLATFORM_MACOSX)
855 pid_t
856 mono_runtime_syscall_fork ()
857 {
858 #if defined(PLATFORM_ANDROID)
859         /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
860         g_assert_not_reached ();
861         return 0;
862 #elif defined(SYS_fork)
863         return (pid_t) syscall (SYS_fork);
864 #else
865         g_assert_not_reached ();
866         return 0;
867 #endif
868 }
869
870 void
871 mono_gdb_render_native_backtraces (pid_t crashed_pid)
872 {
873         const char *argv [9];
874         char template_ [] = "/tmp/mono-lldb-commands.XXXXXX";
875         char buf1 [128];
876         FILE *commands;
877         gboolean using_lldb = FALSE;
878
879         argv [0] = g_find_program_in_path ("gdb");
880         if (argv [0] == NULL) {
881                 argv [0] = g_find_program_in_path ("lldb");
882                 using_lldb = TRUE;
883         }
884
885         if (argv [0] == NULL)
886                 return;
887
888         if (using_lldb) {
889                 if (mkstemp (template_) == -1)
890                         return;
891
892                 commands = fopen (template_, "w");
893
894                 fprintf (commands, "process attach --pid %ld\n", (long) crashed_pid);
895                 fprintf (commands, "thread list\n");
896                 fprintf (commands, "thread backtrace all\n");
897                 fprintf (commands, "detach\n");
898                 fprintf (commands, "quit\n");
899
900                 fflush (commands);
901                 fclose (commands);
902
903                 argv [1] = "--source";
904                 argv [2] = template_;
905                 argv [3] = 0;
906         } else {
907                 argv [1] = "-ex";
908                 sprintf (buf1, "attach %ld", (long) crashed_pid);
909                 argv [2] = buf1;
910                 argv [3] = "--ex";
911                 argv [4] = "info threads";
912                 argv [5] = "--ex";
913                 argv [6] = "thread apply all bt";
914                 argv [7] = "--batch";
915                 argv [8] = 0;
916         }
917
918         execv (argv [0], (char**)argv);
919
920         if (using_lldb)
921                 unlink (template_);
922 }
923 #endif
924 #endif /* __native_client__ */
925
926 #if !defined (__MACH__)
927
928 gboolean
929 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
930 {
931         g_error ("Posix systems don't support mono_thread_state_init_from_handle");
932         return FALSE;
933 }
934
935 #endif