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