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