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