[io-layer] Extract error (#4279)
[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/metadata/profiler.h"
43 #include <mono/metadata/profiler-private.h>
44 #include <mono/metadata/mono-config.h>
45 #include <mono/metadata/environment.h>
46 #include <mono/metadata/mono-debug.h>
47 #include <mono/metadata/gc-internals.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/metadata/verify.h>
50 #include <mono/metadata/verify-internals.h>
51 #include <mono/metadata/mempool-internals.h>
52 #include <mono/metadata/attach.h>
53 #include <mono/utils/mono-math.h>
54 #include <mono/utils/mono-compiler.h>
55 #include <mono/utils/mono-counters.h>
56 #include <mono/utils/mono-logger-internals.h>
57 #include <mono/utils/mono-mmap.h>
58 #include <mono/utils/dtrace.h>
59 #include <mono/utils/mono-signal-handler.h>
60 #include <mono/utils/mono-threads.h>
61
62 #include "mini.h"
63 #include <string.h>
64 #include <ctype.h>
65 #include "trace.h"
66 #include "version.h"
67 #include "debugger-agent.h"
68
69 #include "jit-icalls.h"
70
71 #ifdef PLATFORM_MACOSX
72 #include <mach/mach.h>
73 #include <mach/mach_time.h>
74 #include <mach/clock.h>
75 #endif
76
77 #if defined(__native_client__) || defined(HOST_WATCHOS)
78
79 void
80 mono_runtime_setup_stat_profiler (void)
81 {
82         printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
83 }
84
85
86 void
87 mono_runtime_shutdown_stat_profiler (void)
88 {
89 }
90
91
92 gboolean
93 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
94 {
95         return FALSE;
96 }
97
98 #ifndef PLATFORM_MACOSX
99 void
100 mono_runtime_install_handlers (void)
101 {
102 }
103 #endif
104
105 void
106 mono_runtime_posix_install_handlers(void)
107 {
108         /* we still need to ignore SIGPIPE */
109         signal (SIGPIPE, SIG_IGN);
110 }
111
112 void
113 mono_runtime_shutdown_handlers (void)
114 {
115 }
116
117 void
118 mono_runtime_cleanup_handlers (void)
119 {
120 }
121
122 #else
123
124 static GHashTable *mono_saved_signal_handlers = NULL;
125
126 static struct sigaction *
127 get_saved_signal_handler (int signo, gboolean remove)
128 {
129         if (mono_saved_signal_handlers) {
130                 /* The hash is only modified during startup, so no need for locking */
131                 struct sigaction *handler = g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
132                 if (remove && handler)
133                         g_hash_table_remove (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
134                 return handler;
135         }
136         return NULL;
137 }
138
139 static void
140 save_old_signal_handler (int signo, struct sigaction *old_action)
141 {
142         struct sigaction *handler_to_save = (struct sigaction *)g_malloc (sizeof (struct sigaction));
143
144         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
145                                 "Saving old signal handler for signal %d.", signo);
146
147         if (! (old_action->sa_flags & SA_SIGINFO)) {
148                 handler_to_save->sa_handler = old_action->sa_handler;
149         } else {
150 #ifdef MONO_ARCH_USE_SIGACTION
151                 handler_to_save->sa_sigaction = old_action->sa_sigaction;
152 #endif /* MONO_ARCH_USE_SIGACTION */
153         }
154         handler_to_save->sa_mask = old_action->sa_mask;
155         handler_to_save->sa_flags = old_action->sa_flags;
156         
157         if (!mono_saved_signal_handlers)
158                 mono_saved_signal_handlers = g_hash_table_new_full (NULL, NULL, NULL, g_free);
159         g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
160 }
161
162 static void
163 free_saved_signal_handlers (void)
164 {
165         if (mono_saved_signal_handlers) {
166                 g_hash_table_destroy (mono_saved_signal_handlers);
167                 mono_saved_signal_handlers = NULL;
168         }
169 }
170
171 /*
172  * mono_chain_signal:
173  *
174  *   Call the original signal handler for the signal given by the arguments, which
175  * should be the same as for a signal handler. Returns TRUE if the original handler
176  * was called, false otherwise.
177  */
178 gboolean
179 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
180 {
181         int signal = MONO_SIG_HANDLER_GET_SIGNO ();
182         struct sigaction *saved_handler = (struct sigaction *)get_saved_signal_handler (signal, FALSE);
183
184         if (saved_handler && saved_handler->sa_handler) {
185                 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
186                         saved_handler->sa_handler (signal);
187                 } else {
188 #ifdef MONO_ARCH_USE_SIGACTION
189                         saved_handler->sa_sigaction (MONO_SIG_HANDLER_PARAMS);
190 #endif /* MONO_ARCH_USE_SIGACTION */
191                 }
192                 return TRUE;
193         }
194         return FALSE;
195 }
196
197 MONO_SIG_HANDLER_FUNC (static, sigabrt_signal_handler)
198 {
199         MonoJitInfo *ji = NULL;
200         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
201         MONO_SIG_HANDLER_GET_CONTEXT;
202
203         if (mono_thread_internal_current ())
204                 ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
205         if (!ji) {
206         if (mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
207                         return;
208                 mono_handle_native_crash ("SIGABRT", ctx, info);
209         }
210 }
211
212 #if defined(__i386__) || defined(__x86_64__)
213 #define FULL_STAT_PROFILER_BACKTRACE 1
214 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
215 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
216 #if MONO_ARCH_STACK_GROWS_UP
217 #define IS_BEFORE_ON_STACK <
218 #define IS_AFTER_ON_STACK >
219 #else
220 #define IS_BEFORE_ON_STACK >
221 #define IS_AFTER_ON_STACK <
222 #endif
223 #else
224 #define FULL_STAT_PROFILER_BACKTRACE 0
225 #endif
226
227 #if (defined (USE_POSIX_BACKEND) && defined (SIGRTMIN)) || defined (SIGPROF)
228 #define HAVE_PROFILER_SIGNAL
229 #endif
230
231 #ifdef HAVE_PROFILER_SIGNAL
232
233 static void
234 per_thread_profiler_hit (void *ctx)
235 {
236         int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
237         MonoProfilerCallChainStrategy call_chain_strategy = mono_profiler_stat_get_call_chain_strategy ();
238
239         if (call_chain_depth == 0) {
240                 mono_profiler_stat_hit ((guchar *)mono_arch_ip_from_context (ctx), ctx);
241         } else {
242                 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
243                 int current_frame_index = 1;
244                 MonoContext mono_context;
245                 guchar *ips [call_chain_depth + 1];
246
247                 mono_sigctx_to_monoctx (ctx, &mono_context);
248                 ips [0] = (guchar *)MONO_CONTEXT_GET_IP (&mono_context);
249                 
250                 if (jit_tls != NULL) {
251                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_NATIVE) {
252 #if FULL_STAT_PROFILER_BACKTRACE
253                         guchar *current_frame;
254                         guchar *stack_bottom;
255                         guchar *stack_top;
256                         
257                         stack_bottom = (guchar *)jit_tls->end_of_stack;
258                         stack_top = (guchar *)MONO_CONTEXT_GET_SP (&mono_context);
259                         current_frame = (guchar *)MONO_CONTEXT_GET_BP (&mono_context);
260                         
261                         while ((current_frame_index <= call_chain_depth) &&
262                                         (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
263                                         ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
264                                 ips [current_frame_index] = (guchar *)CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
265                                 current_frame_index ++;
266                                 stack_top = current_frame;
267                                 current_frame = (guchar *)CURRENT_FRAME_GET_BASE_POINTER (current_frame);
268                         }
269 #else
270                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_GLIBC;
271 #endif
272                         }
273                         
274                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_GLIBC) {
275 #if GLIBC_PROFILER_BACKTRACE
276                                 current_frame_index = backtrace ((void**) & ips [1], call_chain_depth);
277 #else
278                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_MANAGED;
279 #endif
280                         }
281
282                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_MANAGED) {
283                                 MonoDomain *domain = mono_domain_get ();
284                                 if (domain != NULL) {
285                                         MonoLMF *lmf = NULL;
286                                         MonoJitInfo *ji;
287                                         MonoJitInfo res;
288                                         MonoContext new_mono_context;
289                                         int native_offset;
290                                         ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
291                                                         &new_mono_context, NULL, &lmf, &native_offset, NULL);
292                                         while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
293                                                 ips [current_frame_index] = (guchar *)MONO_CONTEXT_GET_IP (&new_mono_context);
294                                                 current_frame_index ++;
295                                                 mono_context = new_mono_context;
296                                                 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
297                                                                 &new_mono_context, NULL, &lmf, &native_offset, NULL);
298                                         }
299                                 }
300                         }
301                 }
302                 
303                 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
304         }
305 }
306
307 static MonoNativeThreadId sampling_thread;
308
309 static gint32 profiler_signals_sent;
310 static gint32 profiler_signals_received;
311 static gint32 profiler_signals_accepted;
312 static gint32 profiler_interrupt_signals_received;
313
314 MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler)
315 {
316         int old_errno = errno;
317         int hp_save_index;
318         MONO_SIG_HANDLER_GET_CONTEXT;
319
320         /* See the comment in mono_runtime_shutdown_stat_profiler (). */
321         if (mono_native_thread_id_get () == sampling_thread) {
322                 InterlockedIncrement (&profiler_interrupt_signals_received);
323                 return;
324         }
325
326         InterlockedIncrement (&profiler_signals_received);
327
328         if (mono_thread_info_get_small_id () == -1)
329                 return; //an non-attached thread got the signal
330
331         if (!mono_domain_get () || !mono_tls_get_jit_tls ())
332                 return; //thread in the process of dettaching
333
334         InterlockedIncrement (&profiler_signals_accepted);
335
336         hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
337
338         mono_thread_info_set_is_async_context (TRUE);
339         per_thread_profiler_hit (ctx);
340         mono_thread_info_set_is_async_context (FALSE);
341
342         mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
343         errno = old_errno;
344
345         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
346 }
347
348 #endif
349
350 MONO_SIG_HANDLER_FUNC (static, sigquit_signal_handler)
351 {
352         gboolean res;
353
354         /* We use this signal to start the attach agent too */
355         res = mono_attach_start ();
356         if (res)
357                 return;
358
359         mono_threads_request_thread_dump ();
360
361         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
362 }
363
364 MONO_SIG_HANDLER_FUNC (static, sigusr2_signal_handler)
365 {
366         gboolean enabled = mono_trace_is_enabled ();
367
368         mono_trace_enable (!enabled);
369
370         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
371 }
372
373 static void
374 add_signal_handler (int signo, gpointer handler, int flags)
375 {
376         struct sigaction sa;
377         struct sigaction previous_sa;
378
379 #ifdef MONO_ARCH_USE_SIGACTION
380         sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
381         sigemptyset (&sa.sa_mask);
382         sa.sa_flags = SA_SIGINFO | flags;
383 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
384
385 /*Apple likes to deliver SIGBUS for *0 */
386 #ifdef PLATFORM_MACOSX
387         if (signo == SIGSEGV || signo == SIGBUS) {
388 #else
389         if (signo == SIGSEGV) {
390 #endif
391                 sa.sa_flags |= SA_ONSTACK;
392
393                 /* 
394                  * libgc will crash when trying to do stack marking for threads which are on
395                  * an altstack, so delay the suspend signal after the signal handler has
396                  * executed.
397                  */
398                 if (mono_gc_get_suspend_signal () != -1)
399                         sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
400         }
401 #endif
402         if (signo == SIGSEGV) {
403                 /* 
404                  * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
405                  */
406                 sigset_t block_mask;
407      
408                 sigemptyset (&block_mask);
409         }
410 #else
411         sa.sa_handler = handler;
412         sigemptyset (&sa.sa_mask);
413         sa.sa_flags = flags;
414 #endif
415         g_assert (sigaction (signo, &sa, &previous_sa) != -1);
416
417         /* if there was already a handler in place for this signal, store it */
418         if (! (previous_sa.sa_flags & SA_SIGINFO) &&
419                         (SIG_DFL == previous_sa.sa_handler)) { 
420                 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
421         } else {
422                 if (mono_do_signal_chaining)
423                         save_old_signal_handler (signo, &previous_sa);
424         }
425 }
426
427 static void
428 remove_signal_handler (int signo)
429 {
430         struct sigaction sa;
431         struct sigaction *saved_action = get_saved_signal_handler (signo, TRUE);
432
433         if (!saved_action) {
434                 sa.sa_handler = SIG_DFL;
435                 sigemptyset (&sa.sa_mask);
436                 sa.sa_flags = 0;
437
438                 sigaction (signo, &sa, NULL);
439         } else {
440                 g_assert (sigaction (signo, saved_action, NULL) != -1);
441         }
442 }
443
444 void
445 mono_runtime_posix_install_handlers (void)
446 {
447
448         sigset_t signal_set;
449
450         if (mini_get_debug_options ()->handle_sigint)
451                 add_signal_handler (SIGINT, mono_sigint_signal_handler, SA_RESTART);
452
453         add_signal_handler (SIGFPE, mono_sigfpe_signal_handler, 0);
454         add_signal_handler (SIGQUIT, sigquit_signal_handler, SA_RESTART);
455         add_signal_handler (SIGILL, mono_sigill_signal_handler, 0);
456         add_signal_handler (SIGBUS, mono_sigsegv_signal_handler, 0);
457         if (mono_jit_trace_calls != NULL)
458                 add_signal_handler (SIGUSR2, sigusr2_signal_handler, SA_RESTART);
459
460         /* it seems to have become a common bug for some programs that run as parents
461          * of many processes to block signal delivery for real time signals.
462          * We try to detect and work around their breakage here.
463          */
464         sigemptyset (&signal_set);
465         if (mono_gc_get_suspend_signal () != -1)
466                 sigaddset (&signal_set, mono_gc_get_suspend_signal ());
467         if (mono_gc_get_restart_signal () != -1)
468                 sigaddset (&signal_set, mono_gc_get_restart_signal ());
469         sigaddset (&signal_set, SIGCHLD);
470         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
471
472         signal (SIGPIPE, SIG_IGN);
473
474         add_signal_handler (SIGABRT, sigabrt_signal_handler, 0);
475
476         /* catch SIGSEGV */
477         add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler, 0);
478 }
479
480 #ifndef PLATFORM_MACOSX
481 void
482 mono_runtime_install_handlers (void)
483 {
484         mono_runtime_posix_install_handlers ();
485 }
486 #endif
487
488 void
489 mono_runtime_cleanup_handlers (void)
490 {
491         if (mini_get_debug_options ()->handle_sigint)
492                 remove_signal_handler (SIGINT);
493
494         remove_signal_handler (SIGFPE);
495         remove_signal_handler (SIGQUIT);
496         remove_signal_handler (SIGILL);
497         remove_signal_handler (SIGBUS);
498         if (mono_jit_trace_calls != NULL)
499                 remove_signal_handler (SIGUSR2);
500
501         remove_signal_handler (SIGABRT);
502
503         remove_signal_handler (SIGSEGV);
504
505         free_saved_signal_handlers ();
506 }
507
508 #ifdef HAVE_PROFILER_SIGNAL
509
510 static volatile gint32 sampling_thread_running;
511
512 #ifdef PLATFORM_MACOSX
513
514 static clock_serv_t sampling_clock_service;
515
516 static void
517 clock_init (void)
518 {
519         kern_return_t ret;
520
521         do {
522                 ret = host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &sampling_clock_service);
523         } while (ret == KERN_ABORTED);
524
525         if (ret != KERN_SUCCESS)
526                 g_error ("%s: host_get_clock_service () returned %d", __func__, ret);
527 }
528
529 static void
530 clock_cleanup (void)
531 {
532         kern_return_t ret;
533
534         do {
535                 ret = mach_port_deallocate (mach_task_self (), sampling_clock_service);
536         } while (ret == KERN_ABORTED);
537
538         if (ret != KERN_SUCCESS)
539                 g_error ("%s: mach_port_deallocate () returned %d", __func__, ret);
540 }
541
542 static guint64
543 clock_get_time_ns (void)
544 {
545         kern_return_t ret;
546         mach_timespec_t mach_ts;
547
548         do {
549                 ret = clock_get_time (sampling_clock_service, &mach_ts);
550         } while (ret == KERN_ABORTED);
551
552         if (ret != KERN_SUCCESS)
553                 g_error ("%s: clock_get_time () returned %d", __func__, ret);
554
555         return ((guint64) mach_ts.tv_sec * 1000000000) + (guint64) mach_ts.tv_nsec;
556 }
557
558 static void
559 clock_sleep_ns_abs (guint64 ns_abs)
560 {
561         kern_return_t ret;
562         mach_timespec_t then, remain_unused;
563
564         then.tv_sec = ns_abs / 1000000000;
565         then.tv_nsec = ns_abs % 1000000000;
566
567         do {
568                 ret = clock_sleep (sampling_clock_service, TIME_ABSOLUTE, then, &remain_unused);
569
570                 if (ret != KERN_SUCCESS && ret != KERN_ABORTED)
571                         g_error ("%s: clock_sleep () returned %d", __func__, ret);
572         } while (ret == KERN_ABORTED && InterlockedRead (&sampling_thread_running));
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 && InterlockedRead (&sampling_thread_running));
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 && InterlockedRead (&sampling_thread_running));
671 #endif
672 }
673
674 #endif
675
676 static int profiler_signal;
677 static volatile gint32 sampling_thread_exiting;
678
679 static mono_native_thread_return_t
680 sampling_thread_func (void *data)
681 {
682         mono_threads_attach_tools_thread ();
683         mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler sampler");
684
685         gint64 rate = 1000000000 / mono_profiler_get_sampling_rate ();
686
687         int old_policy;
688         struct sched_param old_sched;
689         pthread_getschedparam (pthread_self (), &old_policy, &old_sched);
690
691         /*
692          * Attempt to switch the thread to real time scheduling. This will not
693          * necessarily work on all OSs; for example, most Linux systems will give
694          * us EPERM here unless configured to allow this.
695          *
696          * TODO: This does not work on Mac (and maybe some other OSs). On Mac, we
697          * have to use the Mach thread policy routines to switch to real-time
698          * scheduling. This is quite tricky as we need to specify how often we'll
699          * be doing work (easy), the normal processing time needed (also easy),
700          * and the maximum amount of processing time needed (hard). This is
701          * further complicated by the fact that if we misbehave and take too long
702          * to do our work, the kernel may knock us back down to the normal thread
703          * scheduling policy without telling us.
704          */
705         struct sched_param sched = { .sched_priority = sched_get_priority_max (SCHED_FIFO) };
706         pthread_setschedparam (pthread_self (), SCHED_FIFO, &sched);
707
708         clock_init ();
709
710         guint64 sleep = clock_get_time_ns ();
711
712         while (InterlockedRead (&sampling_thread_running)) {
713                 sleep += rate;
714
715                 FOREACH_THREAD_SAFE (info) {
716                         /* info should never be this thread as we're a tools thread. */
717                         g_assert (mono_thread_info_get_tid (info) != mono_native_thread_id_get ());
718
719                         mono_threads_pthread_kill (info, profiler_signal);
720                         InterlockedIncrement (&profiler_signals_sent);
721                 } FOREACH_THREAD_SAFE_END
722
723                 clock_sleep_ns_abs (sleep);
724         }
725
726         InterlockedWrite (&sampling_thread_exiting, 1);
727
728         clock_cleanup ();
729
730         pthread_setschedparam (pthread_self (), old_policy, &old_sched);
731
732         mono_thread_info_detach ();
733
734         return NULL;
735 }
736
737 void
738 mono_runtime_shutdown_stat_profiler (void)
739 {
740         InterlockedWrite (&sampling_thread_running, 0);
741
742 #ifndef PLATFORM_MACOSX
743         /*
744          * There is a slight problem when we're using CLOCK_PROCESS_CPUTIME_ID: If
745          * we're shutting down and there's largely no activity in the process other
746          * than waiting for the sampler thread to shut down, it can take upwards of
747          * 20 seconds (depending on a lot of factors) for us to shut down because
748          * the sleep progresses very slowly as a result of the low CPU activity.
749          *
750          * We fix this by repeatedly sending the profiler signal to the sampler
751          * thread in order to interrupt the sleep. clock_sleep_ns_abs () will check
752          * sampling_thread_running upon an interrupt and return immediately if it's
753          * zero. profiler_signal_handler () has a special case to ignore the signal
754          * for the sampler thread.
755          */
756         MonoThreadInfo *info;
757
758         // Did it shut down already?
759         if ((info = mono_thread_info_lookup (sampling_thread))) {
760                 while (!InterlockedRead (&sampling_thread_exiting)) {
761                         mono_threads_pthread_kill (info, profiler_signal);
762                         mono_thread_info_usleep (10 * 1000 /* 10ms */);
763                 }
764
765                 // Make sure info can be freed.
766                 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
767         }
768 #endif
769
770         mono_native_thread_join (sampling_thread);
771
772         /*
773          * We can't safely remove the signal handler because we have no guarantee
774          * that all pending signals have been delivered at this point. This should
775          * not really be a problem anyway.
776          */
777         //remove_signal_handler (profiler_signal);
778 }
779
780 void
781 mono_runtime_setup_stat_profiler (void)
782 {
783         /*
784          * Use a real-time signal when possible. This gives us roughly a 99% signal
785          * delivery rate in all cases. On the other hand, using a regular signal
786          * tends to result in awful delivery rates when the application is heavily
787          * loaded.
788          *
789          * We avoid real-time signals on Android as they're super broken in certain
790          * API levels (too small sigset_t, nonsensical SIGRTMIN/SIGRTMAX values,
791          * etc).
792          *
793          * TODO: On Mac, we should explore using the Mach thread suspend/resume
794          * functions and doing the stack walk from the sampling thread. This would
795          * get us a 100% sampling rate. However, this may interfere with the GC's
796          * STW logic. Could perhaps be solved by taking the suspend lock.
797          */
798 #if defined (USE_POSIX_BACKEND) && defined (SIGRTMIN) && !defined (PLATFORM_ANDROID)
799         /* Just take the first real-time signal we can get. */
800         profiler_signal = mono_threads_suspend_search_alternative_signal ();
801 #else
802         profiler_signal = SIGPROF;
803 #endif
804
805         add_signal_handler (profiler_signal, profiler_signal_handler, SA_RESTART);
806
807         mono_counters_register ("Sampling signals sent", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_sent);
808         mono_counters_register ("Sampling signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_received);
809         mono_counters_register ("Sampling signals accepted", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_accepted);
810         mono_counters_register ("Shutdown signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_interrupt_signals_received);
811
812         InterlockedWrite (&sampling_thread_running, 1);
813         mono_native_thread_create (&sampling_thread, sampling_thread_func, NULL);
814 }
815
816 #else
817
818 void
819 mono_runtime_shutdown_stat_profiler (void)
820 {
821 }
822
823 void
824 mono_runtime_setup_stat_profiler (void)
825 {
826 }
827
828 #endif
829
830 #endif /* defined(__native_client__) || defined(HOST_WATCHOS) */
831
832 #if defined(__native_client__)
833
834 void
835 mono_gdb_render_native_backtraces (pid_t crashed_pid)
836 {
837 }
838
839 #else
840
841 static gboolean
842 native_stack_with_gdb (pid_t crashed_pid, const char **argv, FILE *commands, char* commands_filename)
843 {
844         gchar *gdb;
845
846         gdb = g_find_program_in_path ("gdb");
847         if (!gdb)
848                 return FALSE;
849
850         argv [0] = gdb;
851         argv [1] = "-batch";
852         argv [2] = "-x";
853         argv [3] = commands_filename;
854         argv [4] = "-nx";
855
856         fprintf (commands, "attach %ld\n", (long) crashed_pid);
857         fprintf (commands, "info threads\n");
858         fprintf (commands, "thread apply all bt\n");
859
860         return TRUE;
861 }
862
863
864 static gboolean
865 native_stack_with_lldb (pid_t crashed_pid, const char **argv, FILE *commands, char* commands_filename)
866 {
867         gchar *lldb;
868
869         lldb = g_find_program_in_path ("lldb");
870         if (!lldb)
871                 return FALSE;
872
873         argv [0] = lldb;
874         argv [1] = "--batch";
875         argv [2] = "--source";
876         argv [3] = commands_filename;
877         argv [4] = "--no-lldbinit";
878
879         fprintf (commands, "process attach --pid %ld\n", (long) crashed_pid);
880         fprintf (commands, "thread list\n");
881         fprintf (commands, "thread backtrace all\n");
882         fprintf (commands, "detach\n");
883         fprintf (commands, "quit\n");
884
885         return TRUE;
886 }
887
888 void
889 mono_gdb_render_native_backtraces (pid_t crashed_pid)
890 {
891 #ifdef HAVE_EXECV
892         const char *argv [10];
893         FILE *commands;
894         char commands_filename [] = "/tmp/mono-gdb-commands.XXXXXX";
895
896         if (mkstemp (commands_filename) == -1)
897                 return;
898
899         commands = fopen (commands_filename, "w");
900         if (!commands) {
901                 unlink (commands_filename);
902                 return;
903         }
904
905         memset (argv, 0, sizeof (char*) * 10);
906
907 #if defined(PLATFORM_MACOSX)
908         if (native_stack_with_lldb (crashed_pid, argv, commands, commands_filename))
909                 goto exec;
910 #endif
911
912         if (native_stack_with_gdb (crashed_pid, argv, commands, commands_filename))
913                 goto exec;
914
915 #if !defined(PLATFORM_MACOSX)
916         if (native_stack_with_lldb (crashed_pid, argv, commands, commands_filename))
917                 goto exec;
918 #endif
919
920         fprintf (stderr, "mono_gdb_render_native_backtraces not supported on this platform, unable to find gdb or lldb\n");
921
922         fclose (commands);
923         unlink (commands_filename);
924         return;
925
926 exec:
927         fclose (commands);
928         execv (argv [0], (char**)argv);
929
930         _exit (-1);
931 #else
932         fprintf (stderr, "mono_gdb_render_native_backtraces not supported on this platform\n");
933 #endif // HAVE_EXECV
934 }
935
936 #endif /* defined(__native_client__) */
937
938 #if !defined (__MACH__)
939
940 gboolean
941 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
942 {
943         g_error ("Posix systems don't support mono_thread_state_init_from_handle");
944         return FALSE;
945 }
946
947 #endif