Merge pull request #439 from mono-soc-2012/garyb/iconfix
[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                 return;
215
216         if (thread->ignore_next_signal) {
217                 thread->ignore_next_signal = FALSE;
218                 return;
219         }
220
221         if (thread->thread_dump_requested) {
222                 thread->thread_dump_requested = FALSE;
223
224                 mono_print_thread_dump (ctx);
225         }
226
227         /*
228          * This is an async signal, so the code below must not call anything which
229          * is not async safe. That includes the pthread locking functions. If we
230          * know that we interrupted managed code, then locking is safe.
231          */
232         /*
233          * On OpenBSD, ctx can be NULL if we are interrupting poll ().
234          */
235         if (ctx) {
236                 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
237                 running_managed = ji != NULL;
238
239                 if (mono_debugger_agent_thread_interrupt (ctx, ji))
240                         return;
241         } else {
242                 running_managed = FALSE;
243         }
244
245         /* We can't do handler block checking from metadata since it requires doing
246          * a stack walk with context.
247          *
248          * FIXME add full-aot support.
249          */
250 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
251         if (!mono_aot_only && ctx) {
252                 MonoThreadUnwindState unwind_state;
253                 if (mono_thread_state_init_from_sigctx (&unwind_state, ctx)) {
254                         if (mono_install_handler_block_guard (&unwind_state)) {
255 #ifndef HOST_WIN32
256                                 /*Clear current thread from been wapi interrupted otherwise things can go south*/
257                                 wapi_clear_interruption ();
258 #endif
259                                 return;
260                         }
261                 }
262         }
263 #endif
264
265         exc = mono_thread_request_interruption (running_managed); 
266         if (!exc)
267                 return;
268
269         mono_arch_handle_exception (ctx, exc);
270 }
271
272 #if defined(__i386__) || defined(__x86_64__)
273 #define FULL_STAT_PROFILER_BACKTRACE 1
274 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
275 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
276 #if MONO_ARCH_STACK_GROWS_UP
277 #define IS_BEFORE_ON_STACK <
278 #define IS_AFTER_ON_STACK >
279 #else
280 #define IS_BEFORE_ON_STACK >
281 #define IS_AFTER_ON_STACK <
282 #endif
283 #else
284 #define FULL_STAT_PROFILER_BACKTRACE 0
285 #endif
286
287 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
288
289 static void
290 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
291 {
292         if (mono_chain_signal (SIG_HANDLER_PARAMS))
293                 return;
294
295         NOT_IMPLEMENTED;
296 }
297
298 #else
299
300 static void
301 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
302 {
303         int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
304         MonoProfilerCallChainStrategy call_chain_strategy = mono_profiler_stat_get_call_chain_strategy ();
305         GET_CONTEXT;
306         
307         if (call_chain_depth == 0) {
308                 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
309         } else {
310                 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
311                 int current_frame_index = 1;
312                 MonoContext mono_context;
313                 guchar *ips [call_chain_depth + 1];
314
315                 mono_arch_sigctx_to_monoctx (ctx, &mono_context);
316                 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
317                 
318                 if (jit_tls != NULL) {
319                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_NATIVE) {
320 #if FULL_STAT_PROFILER_BACKTRACE
321                         guchar *current_frame;
322                         guchar *stack_bottom;
323                         guchar *stack_top;
324                         
325                         stack_bottom = jit_tls->end_of_stack;
326                         stack_top = MONO_CONTEXT_GET_SP (&mono_context);
327                         current_frame = MONO_CONTEXT_GET_BP (&mono_context);
328                         
329                         while ((current_frame_index <= call_chain_depth) &&
330                                         (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
331                                         ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
332                                 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
333                                 current_frame_index ++;
334                                 stack_top = current_frame;
335                                 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
336                         }
337 #else
338                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_GLIBC;
339 #endif
340                         }
341                         
342                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_GLIBC) {
343 #if GLIBC_PROFILER_BACKTRACE
344                                 current_frame_index = backtrace ((void**) & ips [1], call_chain_depth);
345 #else
346                                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_MANAGED;
347 #endif
348                         }
349
350                         if (call_chain_strategy == MONO_PROFILER_CALL_CHAIN_MANAGED) {
351                                 MonoDomain *domain = mono_domain_get ();
352                                 if (domain != NULL) {
353                                         MonoLMF *lmf = NULL;
354                                         MonoJitInfo *ji;
355                                         MonoJitInfo res;
356                                         MonoContext new_mono_context;
357                                         int native_offset;
358                                         ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
359                                                         &new_mono_context, NULL, &lmf, &native_offset, NULL);
360                                         while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
361                                                 ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
362                                                 current_frame_index ++;
363                                                 mono_context = new_mono_context;
364                                                 ji = mono_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
365                                                                 &new_mono_context, NULL, &lmf, &native_offset, NULL);
366                                         }
367                                 }
368                         }
369                 }
370                 
371                 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
372         }
373
374         mono_chain_signal (SIG_HANDLER_PARAMS);
375 }
376
377 #endif
378
379 static void
380 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
381 {
382         gboolean res;
383
384         GET_CONTEXT;
385
386         /* We use this signal to start the attach agent too */
387         res = mono_attach_start ();
388         if (res)
389                 return;
390
391         if (mono_thread_info_new_interrupt_enabled ()) {
392                 mono_threads_request_thread_dump ();
393         } else {
394                 printf ("Full thread dump:\n");
395
396                 mono_threads_request_thread_dump ();
397
398                 /*
399                  * print_thread_dump () skips the current thread, since sending a signal
400                  * to it would invoke the signal handler below the sigquit signal handler,
401                  * and signal handlers don't create an lmf, so the stack walk could not
402                  * be performed.
403                  */
404                 mono_print_thread_dump (ctx);
405         }
406
407         mono_chain_signal (SIG_HANDLER_PARAMS);
408 }
409
410 static void
411 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
412 {
413         gboolean enabled = mono_trace_is_enabled ();
414
415         mono_trace_enable (!enabled);
416
417         mono_chain_signal (SIG_HANDLER_PARAMS);
418 }
419
420 static void
421 add_signal_handler (int signo, gpointer handler)
422 {
423         struct sigaction sa;
424         struct sigaction previous_sa;
425
426 #ifdef MONO_ARCH_USE_SIGACTION
427         sa.sa_sigaction = handler;
428         sigemptyset (&sa.sa_mask);
429         sa.sa_flags = SA_SIGINFO;
430 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
431
432 /*Apple likes to deliver SIGBUS for *0 */
433 #ifdef __APPLE__
434         if (signo == SIGSEGV || signo == SIGBUS) {
435 #else
436         if (signo == SIGSEGV) {
437 #endif
438                 sa.sa_flags |= SA_ONSTACK;
439
440                 /* 
441                  * libgc will crash when trying to do stack marking for threads which are on
442                  * an altstack, so delay the suspend signal after the signal handler has
443                  * executed.
444                  */
445                 if (mono_gc_get_suspend_signal () != -1)
446                         sigaddset (&sa.sa_mask, mono_gc_get_suspend_signal ());
447         }
448 #endif
449         if (signo == SIGSEGV) {
450                 /* 
451                  * Delay abort signals while handling SIGSEGVs since they could go unnoticed.
452                  */
453                 sigset_t block_mask;
454      
455                 sigemptyset (&block_mask);
456                 sigaddset (&sa.sa_mask, mono_thread_get_abort_signal ());
457         }
458 #else
459         sa.sa_handler = handler;
460         sigemptyset (&sa.sa_mask);
461         sa.sa_flags = 0;
462 #endif
463         g_assert (sigaction (signo, &sa, &previous_sa) != -1);
464
465         /* if there was already a handler in place for this signal, store it */
466         if (! (previous_sa.sa_flags & SA_SIGINFO) &&
467                         (SIG_DFL == previous_sa.sa_handler)) { 
468                 /* it there is no sa_sigaction function and the sa_handler is default, we can safely ignore this */
469         } else {
470                 if (mono_do_signal_chaining)
471                         save_old_signal_handler (signo, &previous_sa);
472         }
473 }
474
475 static void
476 remove_signal_handler (int signo)
477 {
478         struct sigaction sa;
479         struct sigaction *saved_action = get_saved_signal_handler (signo);
480
481         if (!saved_action) {
482                 sa.sa_handler = SIG_DFL;
483                 sigemptyset (&sa.sa_mask);
484                 sa.sa_flags = 0;
485
486                 sigaction (signo, &sa, NULL);
487         } else {
488                 g_assert (sigaction (signo, saved_action, NULL) != -1);
489         }
490 }
491
492 void
493 mono_runtime_posix_install_handlers (void)
494 {
495
496         sigset_t signal_set;
497
498         if (mini_get_debug_options ()->handle_sigint)
499                 add_signal_handler (SIGINT, mono_sigint_signal_handler);
500
501         add_signal_handler (SIGFPE, mono_sigfpe_signal_handler);
502         add_signal_handler (SIGQUIT, sigquit_signal_handler);
503         add_signal_handler (SIGILL, mono_sigill_signal_handler);
504         add_signal_handler (SIGBUS, mono_sigsegv_signal_handler);
505         if (mono_jit_trace_calls != NULL)
506                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
507
508         if (!mono_thread_info_new_interrupt_enabled ())
509                 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
510         /* it seems to have become a common bug for some programs that run as parents
511          * of many processes to block signal delivery for real time signals.
512          * We try to detect and work around their breakage here.
513          */
514         sigemptyset (&signal_set);
515         sigaddset (&signal_set, mono_thread_get_abort_signal ());
516         sigprocmask (SIG_UNBLOCK, &signal_set, NULL);
517
518         signal (SIGPIPE, SIG_IGN);
519
520         add_signal_handler (SIGABRT, sigabrt_signal_handler);
521
522         /* catch SIGSEGV */
523         add_signal_handler (SIGSEGV, mono_sigsegv_signal_handler);
524 }
525
526 #ifndef PLATFORM_MACOSX
527 void
528 mono_runtime_install_handlers (void)
529 {
530         mono_runtime_posix_install_handlers ();
531 }
532 #endif
533
534 void
535 mono_runtime_cleanup_handlers (void)
536 {
537         if (mini_get_debug_options ()->handle_sigint)
538                 remove_signal_handler (SIGINT);
539
540         remove_signal_handler (SIGFPE);
541         remove_signal_handler (SIGQUIT);
542         remove_signal_handler (SIGILL);
543         remove_signal_handler (SIGBUS);
544         if (mono_jit_trace_calls != NULL)
545                 remove_signal_handler (SIGUSR2);
546
547         remove_signal_handler (mono_thread_get_abort_signal ());
548
549         remove_signal_handler (SIGABRT);
550
551         remove_signal_handler (SIGSEGV);
552
553         free_saved_signal_handlers ();
554 }
555
556 #ifdef HAVE_LINUX_RTC_H
557 #include <linux/rtc.h>
558 #include <sys/ioctl.h>
559 #include <fcntl.h>
560 static int rtc_fd = -1;
561
562 static int
563 enable_rtc_timer (gboolean enable)
564 {
565         int flags;
566         flags = fcntl (rtc_fd, F_GETFL);
567         if (flags < 0) {
568                 perror ("getflags");
569                 return 0;
570         }
571         if (enable)
572                 flags |= FASYNC;
573         else
574                 flags &= ~FASYNC;
575         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
576                 perror ("setflags");
577                 return 0;
578         }
579         return 1;
580 }
581 #endif
582
583 void
584 mono_runtime_shutdown_stat_profiler (void)
585 {
586 #ifdef HAVE_LINUX_RTC_H
587         if (rtc_fd >= 0)
588                 enable_rtc_timer (FALSE);
589 #endif
590 }
591
592 void
593 mono_runtime_setup_stat_profiler (void)
594 {
595 #ifdef ITIMER_PROF
596         struct itimerval itval;
597         static int inited = 0;
598 #ifdef HAVE_LINUX_RTC_H
599         const char *rtc_freq;
600         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
601                 int freq = 0;
602                 inited = 1;
603                 if (*rtc_freq)
604                         freq = atoi (rtc_freq);
605                 if (!freq)
606                         freq = 1024;
607                 rtc_fd = open ("/dev/rtc", O_RDONLY);
608                 if (rtc_fd == -1) {
609                         perror ("open /dev/rtc");
610                         return;
611                 }
612                 add_signal_handler (SIGPROF, sigprof_signal_handler);
613                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
614                         perror ("set rtc freq");
615                         return;
616                 }
617                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
618                         perror ("start rtc");
619                         return;
620                 }
621                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
622                         perror ("setsig");
623                         return;
624                 }
625                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
626                         perror ("setown");
627                         return;
628                 }
629                 enable_rtc_timer (TRUE);
630                 return;
631         }
632         if (rtc_fd >= 0)
633                 return;
634 #endif
635
636         itval.it_interval.tv_usec = 999;
637         itval.it_interval.tv_sec = 0;
638         itval.it_value = itval.it_interval;
639         setitimer (ITIMER_PROF, &itval, NULL);
640         if (inited)
641                 return;
642         inited = 1;
643         add_signal_handler (SIGPROF, sigprof_signal_handler);
644 #endif
645 }
646
647 #if !defined(__APPLE__)
648 pid_t
649 mono_runtime_syscall_fork ()
650 {
651 #if defined(SYS_fork)
652         return (pid_t) syscall (SYS_fork);
653 #else
654         g_assert_not_reached ();
655         return 0;
656 #endif
657 }
658
659 void
660 mono_gdb_render_native_backtraces (pid_t crashed_pid)
661 {
662         const char *argv [9];
663         char buf1 [128];
664
665         argv [0] = g_find_program_in_path ("gdb");
666         if (argv [0] == NULL) {
667                 return;
668         }
669
670         argv [1] = "-ex";
671         sprintf (buf1, "attach %ld", (long) crashed_pid);
672         argv [2] = buf1;
673         argv [3] = "--ex";
674         argv [4] = "info threads";
675         argv [5] = "--ex";
676         argv [6] = "thread apply all bt";
677         argv [7] = "--batch";
678         argv [8] = 0;
679
680         execv (argv [0], (char**)argv);
681 }
682 #endif
683 #endif /* __native_client__ */
684
685 #if !defined (__MACH__)
686
687 gboolean
688 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoNativeThreadId thread_id, MonoNativeThreadHandle thread_handle)
689 {
690         g_error ("Posix systems don't support mono_thread_state_init_from_handle");
691         return FALSE;
692 }
693
694 #endif