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