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