d03e1147d4fbe22ac33732640d42cca4637fc6cb
[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  */
13 #include <config.h>
14 #include <signal.h>
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #include <math.h>
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25 #ifdef HAVE_SYS_SYSCALL_H
26 #include <sys/syscall.h>
27 #endif
28
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/loader.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/class.h>
33 #include <mono/metadata/object.h>
34 #include <mono/metadata/tokentype.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/threads.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/io-layer/io-layer.h>
40 #include "mono/metadata/profiler.h"
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/gc-internal.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/verify.h>
48 #include <mono/metadata/verify-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/attach.h>
51 #include <mono/utils/mono-math.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-counters.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/dtrace.h>
57
58 #include "mini.h"
59 #include <string.h>
60 #include <ctype.h>
61 #include "trace.h"
62 #include "version.h"
63 #include "debugger-agent.h"
64
65 #include "jit-icalls.h"
66
67 #if defined(__native_client__)
68
69 void
70 mono_runtime_setup_stat_profiler (void)
71 {
72         printf("WARNING: mono_runtime_setup_stat_profiler() called!\n");
73 }
74
75
76 void
77 mono_runtime_shutdown_stat_profiler (void)
78 {
79 }
80
81
82 gboolean
83 SIG_HANDLER_SIGNATURE (mono_chain_signal)
84 {
85         return FALSE;
86 }
87
88 void
89 mono_runtime_install_handlers (void)
90 {
91 }
92
93 void
94 mono_runtime_shutdown_handlers (void)
95 {
96 }
97
98 void
99 mono_runtime_cleanup_handlers (void)
100 {
101 }
102
103
104
105 #else
106
107 static GHashTable *mono_saved_signal_handlers = NULL;
108
109 static gpointer
110 get_saved_signal_handler (int signo)
111 {
112         if (mono_saved_signal_handlers)
113                 /* The hash is only modified during startup, so no need for locking */
114                 return g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
115         return NULL;
116 }
117
118 static void
119 save_old_signal_handler (int signo, struct sigaction *old_action)
120 {
121         struct sigaction *handler_to_save = g_malloc (sizeof (struct sigaction));
122
123         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG,
124                                 "Saving old signal handler for signal %d.", signo);
125
126         if (! (old_action->sa_flags & SA_SIGINFO)) {
127                 handler_to_save->sa_handler = old_action->sa_handler;
128         } else {
129 #ifdef MONO_ARCH_USE_SIGACTION
130                 handler_to_save->sa_sigaction = old_action->sa_sigaction;
131 #endif /* MONO_ARCH_USE_SIGACTION */
132         }
133         handler_to_save->sa_mask = old_action->sa_mask;
134         handler_to_save->sa_flags = old_action->sa_flags;
135         
136         if (!mono_saved_signal_handlers)
137                 mono_saved_signal_handlers = g_hash_table_new (NULL, NULL);
138         g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
139 }
140
141 static void
142 free_saved_sig_handler_func (gpointer key, gpointer value, gpointer user_data)
143 {
144         g_free (value);
145 }
146
147 static void
148 free_saved_signal_handlers (void)
149 {
150         if (mono_saved_signal_handlers) {
151                 g_hash_table_foreach (mono_saved_signal_handlers, free_saved_sig_handler_func, NULL);
152                 g_hash_table_destroy (mono_saved_signal_handlers);
153                 mono_saved_signal_handlers = NULL;
154         }
155 }
156
157 /*
158  * mono_chain_signal:
159  *
160  *   Call the original signal handler for the signal given by the arguments, which
161  * should be the same as for a signal handler. Returns TRUE if the original handler
162  * was called, false otherwise.
163  */
164 gboolean
165 SIG_HANDLER_SIGNATURE (mono_chain_signal)
166 {
167         int signal = _dummy;
168         struct sigaction *saved_handler = get_saved_signal_handler (signal);
169
170         GET_CONTEXT;
171
172         if (saved_handler && saved_handler->sa_handler) {
173                 if (!(saved_handler->sa_flags & SA_SIGINFO)) {
174                         saved_handler->sa_handler (signal);
175                 } else {
176 #ifdef MONO_ARCH_USE_SIGACTION
177                         saved_handler->sa_sigaction (signal, info, ctx);
178 #endif /* MONO_ARCH_USE_SIGACTION */
179                 }
180                 return TRUE;
181         }
182         return FALSE;
183 }
184
185 static void
186 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
187 {
188         MonoJitInfo *ji = NULL;
189         GET_CONTEXT;
190
191         if (mono_thread_internal_current ())
192                 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
193         if (!ji) {
194         if (mono_chain_signal (SIG_HANDLER_PARAMS))
195                         return;
196                 mono_handle_native_sigsegv (SIGABRT, ctx);
197         }
198 }
199
200 static void
201 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
202 {
203         gboolean running_managed;
204         MonoException *exc;
205         MonoInternalThread *thread = mono_thread_internal_current ();
206         MonoDomain *domain = mono_domain_get ();
207         void *ji;
208         
209         GET_CONTEXT;
210
211         if (!thread || !domain) {
212                 /* The thread might not have started up yet */
213                 /* FIXME: Specify the synchronization with start_wrapper () in threads.c */
214                 mono_debugger_agent_thread_interrupt (ctx, NULL);
215                 return;
216         }
217
218         if (thread->ignore_next_signal) {
219                 thread->ignore_next_signal = FALSE;
220                 return;
221         }
222
223         if (thread->thread_dump_requested) {
224                 thread->thread_dump_requested = FALSE;
225
226                 mono_print_thread_dump (ctx);
227         }
228
229         /*
230          * This is an async signal, so the code below must not call anything which
231          * is not async safe. That includes the pthread locking functions. If we
232          * know that we interrupted managed code, then locking is safe.
233          */
234         /*
235          * On OpenBSD, ctx can be NULL if we are interrupting poll ().
236          */
237         if (ctx) {
238                 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
239                 running_managed = ji != NULL;
240
241                 if (mono_debugger_agent_thread_interrupt (ctx, ji))
242                         return;
243         } else {
244                 running_managed = FALSE;
245         }
246
247         /* We can't do handler block checking from metadata since it requires doing
248          * a stack walk with context.
249          *
250          * FIXME add full-aot support.
251          */
252 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
253         if (!mono_aot_only && ctx) {
254                 MonoThreadUnwindState unwind_state;
255                 if (mono_thread_state_init_from_sigctx (&unwind_state, ctx)) {
256                         if (mono_install_handler_block_guard (&unwind_state)) {
257 #ifndef HOST_WIN32
258                                 /*Clear current thread from been wapi interrupted otherwise things can go south*/
259                                 wapi_clear_interruption ();
260 #endif
261                                 return;
262                         }
263                 }
264         }
265 #endif
266
267         exc = mono_thread_request_interruption (running_managed); 
268         if (!exc)
269                 return;
270
271         mono_arch_handle_exception (ctx, exc);
272 }
273
274 #if defined(__i386__) || defined(__x86_64__)
275 #define FULL_STAT_PROFILER_BACKTRACE 1
276 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
277 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
278 #if MONO_ARCH_STACK_GROWS_UP
279 #define IS_BEFORE_ON_STACK <
280 #define IS_AFTER_ON_STACK >
281 #else
282 #define IS_BEFORE_ON_STACK >
283 #define IS_AFTER_ON_STACK <
284 #endif
285 #else
286 #define FULL_STAT_PROFILER_BACKTRACE 0
287 #endif
288
289 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
290
291 static void
292 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
293 {
294         if (mono_chain_signal (SIG_HANDLER_PARAMS))
295                 return;
296
297         NOT_IMPLEMENTED;
298 }
299
300 #else
301
302 static void
303 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
304 {
305         int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
306         MonoProfilerCallChainStrategy call_chain_strategy = mono_profiler_stat_get_call_chain_strategy ();
307         GET_CONTEXT;
308         
309         if (call_chain_depth == 0) {
310                 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
311         } else {
312                 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
313                 int current_frame_index = 1;
314                 MonoContext mono_context;
315                 guchar *ips [call_chain_depth + 1];
316
317                 mono_arch_sigctx_to_monoctx (ctx, &mono_context);
318                 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
319                 
320                 if (jit_tls != NULL) {
321                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_NATIVE) {
322 #if FULL_STAT_PROFILER_BACKTRACE
323                         guchar *current_frame;
324                         guchar *stack_bottom;
325                         guchar *stack_top;
326                         
327                         stack_bottom = jit_tls->end_of_stack;
328                         stack_top = MONO_CONTEXT_GET_SP (&mono_context);
329                         current_frame = MONO_CONTEXT_GET_BP (&mono_context);
330                         
331                         while ((current_frame_index <= call_chain_depth) &&
332                                         (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
333                                         ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
334                                 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
335                                 current_frame_index ++;
336                                 stack_top = current_frame;
337                                 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
338                         }
339 #else
340                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_GLIBC;
341 #endif
342                         }
343                         
344                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_GLIBC) {
345 #if GLIBC_PROFILER_BACKTRACE
346                                 current_frame_index = backtrace ((void**) & ips [1], call_chain_depth);
347 #else
348                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_MANAGED;
349 #endif
350                         }
351
352                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_MANAGED) {
353                                 MonoDomain *domain = mono_domain_get ();
354                                 if (domain != NULL) {
355                                         MonoLMF *lmf = NULL;
356                                         MonoJitInfo *ji;
357                                         MonoJitInfo res;
358                                         MonoContext new_mono_context;
359                                         int native_offset;
360                                         ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
361                                                         &new_mono_context, NULL, &lmf, &native_offset, NULL);
362                                         while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
363                                                 ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
364                                                 current_frame_index ++;
365                                                 mono_context = new_mono_context;
366                                                 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
367                                                                 &new_mono_context, NULL, &lmf, &native_offset, NULL);
368                                         }
369                                 }
370                         }
371                 }
372                 
373                 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
374         }
375
376         mono_chain_signal (SIG_HANDLER_PARAMS);
377 }
378
379 #endif
380
381 static void
382 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
383 {
384         gboolean res;
385
386         GET_CONTEXT;
387
388         /* We use this signal to start the attach agent too */
389         res = mono_attach_start ();
390         if (res)
391                 return;
392
393         if (mono_thread_info_new_interrupt_enabled ()) {
394                 mono_threads_request_thread_dump ();
395         } else {
396                 printf ("Full thread dump:\n");
397
398                 mono_threads_request_thread_dump ();
399
400                 /*
401                  * print_thread_dump () skips the current thread, since sending a signal
402                  * to it would invoke the signal handler below the sigquit signal handler,
403                  * and signal handlers don't create an lmf, so the stack walk could not
404                  * be performed.
405                  */
406                 mono_print_thread_dump (ctx);
407         }
408
409         mono_chain_signal (SIG_HANDLER_PARAMS);
410 }
411
412 static void
413 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
414 {
415         gboolean enabled = mono_trace_is_enabled ();
416
417         mono_trace_enable (!enabled);
418
419         mono_chain_signal (SIG_HANDLER_PARAMS);
420 }
421
422 static void
423 add_signal_handler (int signo, gpointer handler)
424 {
425         struct sigaction sa;
426         struct sigaction previous_sa;
427
428 #ifdef MONO_ARCH_USE_SIGACTION
429         sa.sa_sigaction = handler;
430         sigemptyset (&sa.sa_mask);
431         sa.sa_flags = SA_SIGINFO;
432 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
433
434 /*Apple likes to deliver SIGBUS for *0 */
435 #ifdef __APPLE__
436         if (signo == SIGSEGV || signo == SIGBUS) {
437 #else
438         if (signo == SIGSEGV) {
439 #endif
440                 sa.sa_flags |= SA_ONSTACK;
441
442                 /* 
443                  * libgc will crash when trying to do stack marking for threads which are on
444                  * an altstack, so delay the suspend signal after the signal handler has
445                  * executed.
446                  */
447                 if (mono_gc_get_suspend_signal () != -1)
448                         sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
449         }
450 #endif
451         if (signo == SIGSEGV) {
452                 /* 
453                  * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
454                  */
455                 sigset_t block_mask;
456      
457                 sigemptyset (&block_mask);
458                 sigaddset (&sa.sa_mask, mono_thread_get_abort_signal ());
459         }
460 #else
461         sa.sa_handler = handler;
462         sigemptyset (&sa.sa_mask);
463         sa.sa_flags = 0;
464 #endif
465         g_assert (sigaction (signo, &sa, &previous_sa) != -1);
466
467         /* if there was already a handler in place for this signal, store it */
468         if (! (previous_sa.sa_flags & SA_SIGINFO) &&
469                         (SIG_DFL == previous_sa.sa_handler)) { 
470                 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
471         } else {
472                 if (mono_do_signal_chaining)
473                         save_old_signal_handler (signo, &previous_sa);
474         }
475 }
476
477 static void
478 remove_signal_handler (int signo)
479 {
480         struct sigaction sa;
481         struct sigaction *saved_action = get_saved_signal_handler (signo);
482
483         if (!saved_action) {
484                 sa.sa_handler = SIG_DFL;
485                 sigemptyset (&sa.sa_mask);
486                 sa.sa_flags = 0;
487
488                 sigaction (signo, &sa, NULL);
489         } else {
490                 g_assert (sigaction (signo, saved_action, NULL) != -1);
491         }
492 }
493
494 void
495 mono_runtime_posix_install_handlers (void)
496 {
497
498         sigset_t signal_set;
499
500         if (mini_get_debug_options ()->handle_sigint)
501                 add_signal_handler (SIGINT, mono_sigint_signal_handler);
502
503         add_signal_handler (SIGFPE, mono_sigfpe_signal_handler);
504         add_signal_handler (SIGQUIT, sigquit_signal_handler);
505         add_signal_handler (SIGILL, mono_sigill_signal_handler);
506         add_signal_handler (SIGBUS, mono_sigsegv_signal_handler);
507         if (mono_jit_trace_calls != NULL)
508                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
509
510         if (!mono_thread_info_new_interrupt_enabled ())
511                 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
512         /* it seems to have become a common bug for some programs that run as parents
513          * of many processes to block signal delivery for real time signals.
514          * We try to detect and work around their breakage here.
515          */
516         sigemptyset (&signal_set);
517         sigaddset (&signal_set, mono_thread_get_abort_signal ());
518         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
519
520         signal (SIGPIPE, SIG_IGN);
521
522         add_signal_handler (SIGABRT, sigabrt_signal_handler);
523
524         /* catch SIGSEGV */
525         add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler);
526 }
527
528 #ifndef PLATFORM_MACOSX
529 void
530 mono_runtime_install_handlers (void)
531 {
532         mono_runtime_posix_install_handlers ();
533 }
534 #endif
535
536 void
537 mono_runtime_cleanup_handlers (void)
538 {
539         if (mini_get_debug_options ()->handle_sigint)
540                 remove_signal_handler (SIGINT);
541
542         remove_signal_handler (SIGFPE);
543         remove_signal_handler (SIGQUIT);
544         remove_signal_handler (SIGILL);
545         remove_signal_handler (SIGBUS);
546         if (mono_jit_trace_calls != NULL)
547                 remove_signal_handler (SIGUSR2);
548
549         remove_signal_handler (mono_thread_get_abort_signal ());
550
551         remove_signal_handler (SIGABRT);
552
553         remove_signal_handler (SIGSEGV);
554
555         free_saved_signal_handlers ();
556 }
557
558 #ifdef HAVE_LINUX_RTC_H
559 #include <linux/rtc.h>
560 #include <sys/ioctl.h>
561 #include <fcntl.h>
562 static int rtc_fd = -1;
563
564 static int
565 enable_rtc_timer (gboolean enable)
566 {
567         int flags;
568         flags = fcntl (rtc_fd, F_GETFL);
569         if (flags < 0) {
570                 perror ("getflags");
571                 return 0;
572         }
573         if (enable)
574                 flags |= FASYNC;
575         else
576                 flags &= ~FASYNC;
577         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
578                 perror ("setflags");
579                 return 0;
580         }
581         return 1;
582 }
583 #endif
584
585 void
586 mono_runtime_shutdown_stat_profiler (void)
587 {
588 #ifdef HAVE_LINUX_RTC_H
589         if (rtc_fd >= 0)
590                 enable_rtc_timer (FALSE);
591 #endif
592 }
593
594 void
595 mono_runtime_setup_stat_profiler (void)
596 {
597 #ifdef ITIMER_PROF
598         struct itimerval itval;
599         static int inited = 0;
600 #ifdef HAVE_LINUX_RTC_H
601         const char *rtc_freq;
602         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
603                 int freq = 0;
604                 inited = 1;
605                 if (*rtc_freq)
606                         freq = atoi (rtc_freq);
607                 if (!freq)
608                         freq = 1024;
609                 rtc_fd = open ("/dev/rtc", O_RDONLY);
610                 if (rtc_fd == -1) {
611                         perror ("open /dev/rtc");
612                         return;
613                 }
614                 add_signal_handler (SIGPROF, sigprof_signal_handler);
615                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
616                         perror ("set rtc freq");
617                         return;
618                 }
619                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
620                         perror ("start rtc");
621                         return;
622                 }
623                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
624                         perror ("setsig");
625                         return;
626                 }
627                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
628                         perror ("setown");
629                         return;
630                 }
631                 enable_rtc_timer (TRUE);
632                 return;
633         }
634         if (rtc_fd >= 0)
635                 return;
636 #endif
637
638         itval.it_interval.tv_usec = 999;
639         itval.it_interval.tv_sec = 0;
640         itval.it_value = itval.it_interval;
641         setitimer (ITIMER_PROF, &itval, NULL);
642         if (inited)
643                 return;
644         inited = 1;
645         add_signal_handler (SIGPROF, sigprof_signal_handler);
646 #endif
647 }
648
649 #if !defined(__APPLE__)
650 pid_t
651 mono_runtime_syscall_fork ()
652 {
653 #if defined(SYS_fork)
654         return (pid_t) syscall (SYS_fork);
655 #else
656         g_assert_not_reached ();
657         return 0;
658 #endif
659 }
660
661 void
662 mono_gdb_render_native_backtraces (pid_t crashed_pid)
663 {
664         const char *argv [9];
665         char buf1 [128];
666
667         argv [0] = g_find_program_in_path ("gdb");
668         if (argv [0] == NULL) {
669                 return;
670         }
671
672         argv [1] = "-ex";
673         sprintf (buf1, "attach %ld", (long) crashed_pid);
674         argv [2] = buf1;
675         argv [3] = "--ex";
676         argv [4] = "info threads";
677         argv [5] = "--ex";
678         argv [6] = "thread apply all bt";
679         argv [7] = "--batch";
680         argv [8] = 0;
681
682         execv (argv [0], (char**)argv);
683 }
684 #endif
685 #endif /* __native_client__ */
686
687 #if !defined (__MACH__)
688
689 gboolean
690 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoNativeThreadId thread_id, MonoNativeThreadHandle thread_handle)
691 {
692         g_error ("Posix systems don't support mono_thread_state_init_from_handle");
693         return FALSE;
694 }
695
696 #endif