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