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