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