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