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