2006-01-03 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / mini-exceptions.c
index f18bb462182e51c03a45c683f05e291671350c43..b7fcf5208f746f7e87f9ce7946abcf2c1de0e2e6 100644 (file)
 #include <signal.h>
 #include <string.h>
 
+#ifdef HAVE_EXECINFO_H
+#include <execinfo.h>
+#endif
+
 #include <mono/metadata/appdomain.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/threads.h>
 
 #include "mini.h"
 
+#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
+#include <unistd.h>
+#include <sys/mman.h>
+#endif
+
 #define IS_ON_SIGALTSTACK(jit_tls) ((jit_tls) && ((guint8*)&(jit_tls) > (guint8*)(jit_tls)->signal_stack) && ((guint8*)&(jit_tls) < ((guint8*)(jit_tls)->signal_stack + (jit_tls)->signal_stack_size)))
 
 #ifndef MONO_ARCH_CONTEXT_DEF
@@ -540,14 +549,15 @@ ves_icall_System_Security_SecurityFrame_GetSecurityStack (gint32 skip)
 #ifndef CUSTOM_EXCEPTION_HANDLING
 
 /**
- * mono_handle_exception:
+ * mono_handle_exception_internal:
  * @ctx: saved processor state
  * @obj: the exception object
  * @test_only: only test if the exception is caught, but dont call handlers
- *
+ * @out_filter_idx: out parameter. if test_only is true, set to the index of 
+ * the first filter clause which caught the exception.
  */
-gboolean
-mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
+static gboolean
+mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only, gint32 *out_filter_idx)
 {
        MonoDomain *domain = mono_domain_get ();
        MonoJitInfo *ji, rji;
@@ -563,6 +573,7 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
        int frame_count = 0;
        gboolean gc_disabled = FALSE;
        gboolean has_dynamic_methods = FALSE;
+       gint32 filter_idx, first_filter_idx;
        
        /*
         * This function might execute on an alternate signal stack, and Boehm GC
@@ -620,7 +631,7 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
                MonoContext ctx_cp = *ctx;
                if (mono_jit_trace_calls != NULL)
                        g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
-               if (!mono_handle_exception (&ctx_cp, obj, original_ip, TRUE)) {
+               if (!mono_handle_exception_internal (&ctx_cp, obj, original_ip, TRUE, &first_filter_idx)) {
                        if (mono_break_on_exc)
                                G_BREAKPOINT ();
                        mono_unhandled_exception (obj);
@@ -640,6 +651,9 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
                }
        }
 
+       if (out_filter_idx)
+               *out_filter_idx = -1;
+       filter_idx = 0;
        initial_ctx = *ctx;
        memset (&rji, 0, sizeof (rji));
 
@@ -699,12 +713,24 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
                                                if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
                                                        /* store the exception object in cfg->excvar */
                                                        g_assert (ei->exvar_offset);
-                                                       *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = obj;
+                                                       *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = obj;
                                                }
 
                                                if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
                                                        // mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
-                                                       filtered = call_filter (ctx, ei->data.filter);
+                                                       if (test_only) {
+                                                               filtered = call_filter (ctx, ei->data.filter);
+                                                               if (filtered && out_filter_idx)
+                                                                       *out_filter_idx = filter_idx;
+                                                       }
+                                                       else {
+                                                               /* 
+                                                                * Filter clauses should only be run in the 
+                                                                * first pass of exception handling.
+                                                                */
+                                                               filtered = (filter_idx == first_filter_idx);
+                                                       }
+                                                       filter_idx ++;
                                                }
 
                                                if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
@@ -749,7 +775,7 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
 
                *ctx = new_ctx;
 
-               if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
+               if (ji == (gpointer)-1) {
                        if (gc_disabled)
                                mono_gc_enable ();
 
@@ -758,9 +784,11 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
 
                                if (IS_ON_SIGALTSTACK (jit_tls)) {
                                        /* Switch back to normal stack */
-                                       if (stack_overflow)
+                                       if (stack_overflow) {
                                                /* Free up some stack space */
                                                MONO_CONTEXT_SET_SP (&initial_ctx, (gssize)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
+                                               g_assert ((gssize)MONO_CONTEXT_GET_SP (&initial_ctx) < (gssize)jit_tls->end_of_stack);
+                                       }
                                        MONO_CONTEXT_SET_IP (&initial_ctx, (gssize)jit_tls->abort_func);
                                        restore_context (&initial_ctx);
                                }
@@ -783,5 +811,200 @@ mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gbo
 
        g_assert_not_reached ();
 }
-#endif /* CUSTOM_EXECPTION_HANDLING */
 
+/**
+ * mono_debugger_run_finally:
+ * @start_ctx: saved processor state
+ *
+ * This method is called by the Mono Debugger to call all `finally' clauses of the
+ * current stack frame.  It's used when the user issues a `return' command to make
+ * the current stack frame return.  After returning from this method, the debugger
+ * unwinds the stack one frame and gives control back to the user.
+ *
+ * NOTE: This method is only used when running inside the Mono Debugger.
+ */
+void
+mono_debugger_run_finally (MonoContext *start_ctx)
+{
+       static int (*call_filter) (MonoContext *, gpointer) = NULL;
+       MonoDomain *domain = mono_domain_get ();
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+       MonoLMF *lmf = jit_tls->lmf;
+       MonoContext ctx, new_ctx;
+       MonoJitInfo *ji, rji;
+       int i;
+
+       ctx = *start_ctx;
+
+       ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
+       if (!ji || ji == (gpointer)-1)
+               return;
+
+       if (!call_filter)
+               call_filter = mono_arch_get_call_filter ();
+
+       for (i = 0; i < ji->num_clauses; i++) {
+               MonoJitExceptionInfo *ei = &ji->clauses [i];
+
+               if ((ei->try_start <= MONO_CONTEXT_GET_IP (&ctx)) && 
+                   (MONO_CONTEXT_GET_IP (&ctx) < ei->try_end) &&
+                   (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
+                       call_filter (&ctx, ei->handler_start);
+               }
+       }
+}
+
+/**
+ * mono_handle_exception:
+ * @ctx: saved processor state
+ * @obj: the exception object
+ * @test_only: only test if the exception is caught, but dont call handlers
+ */
+gboolean
+mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
+{
+       return mono_handle_exception_internal (ctx, obj, original_ip, test_only, NULL);
+}
+
+#endif /* CUSTOM_EXCEPTION_HANDLING */
+
+#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
+
+void
+mono_setup_altstack (MonoJitTlsData *tls)
+{
+       pthread_t self = pthread_self();
+       pthread_attr_t attr;
+       size_t stsize = 0;
+       struct sigaltstack sa;
+       guint8 *staddr = NULL;
+       guint8 *current = (guint8*)&staddr;
+
+       if (mono_running_on_valgrind ())
+               return;
+
+       /* Determine stack boundaries */
+       pthread_attr_init( &attr );
+#ifdef HAVE_PTHREAD_GETATTR_NP
+       pthread_getattr_np( self, &attr );
+#else
+#ifdef HAVE_PTHREAD_ATTR_GET_NP
+       pthread_attr_get_np( self, &attr );
+#elif defined(sun)
+       pthread_attr_getstacksize( &attr, &stsize );
+#else
+#error "Not implemented"
+#endif
+#endif
+#ifndef sun
+       pthread_attr_getstack( &attr, (void**)&staddr, &stsize );
+#endif
+
+       g_assert (staddr);
+
+       g_assert ((current > staddr) && (current < staddr + stsize));
+
+       tls->end_of_stack = staddr + stsize;
+
+       /*
+        * threads created by nptl does not seem to have a guard page, and
+        * since the main thread is not created by us, we can't even set one.
+        * Increasing stsize fools the SIGSEGV signal handler into thinking this
+        * is a stack overflow exception.
+        */
+       tls->stack_size = stsize + getpagesize ();
+
+       /* Setup an alternate signal stack */
+       tls->signal_stack = mmap (0, MONO_ARCH_SIGNAL_STACK_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
+       tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
+
+       g_assert (tls->signal_stack);
+
+       sa.ss_sp = tls->signal_stack;
+       sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
+       sa.ss_flags = SS_ONSTACK;
+       sigaltstack (&sa, NULL);
+}
+
+void
+mono_free_altstack (MonoJitTlsData *tls)
+{
+       struct sigaltstack sa;
+       int err;
+
+       sa.ss_sp = tls->signal_stack;
+       sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
+       sa.ss_flags = SS_DISABLE;
+       err = sigaltstack  (&sa, NULL);
+       g_assert (err == 0);
+
+       if (tls->signal_stack)
+               munmap (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
+}
+
+#endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
+
+static gboolean
+print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
+{
+       if (method) {
+               if (il_offset != -1)
+                       fprintf (stderr, "in [0x%lx] %s\n", (long)il_offset, mono_method_full_name (method, TRUE));
+               else
+                       fprintf (stderr, "in <0x%lx> %s\n", (long)native_offset, mono_method_full_name (method, TRUE));
+       } else
+               fprintf (stderr, "in <%lx> <unknown>\n", (long)native_offset);
+
+       return FALSE;
+}
+
+/*
+ * mono_handle_native_sigsegv:
+ *
+ *   Handle a SIGSEGV received while in native code by printing diagnostic 
+ * information and aborting.
+ */
+void
+mono_handle_native_sigsegv (void *ctx)
+{
+       /*
+        * A SIGSEGV indicates something went very wrong so we can no longer depend
+        * on anything working. So try to print out lots of diagnostics, starting 
+        * with ones which have a greater change of working.
+        */
+       fprintf (stderr,
+                        "\n"
+                        "=================================================================\n"
+                        "Got a SIGSEGV while executing native code. This usually indicates\n"
+                        "a fatal error in the mono runtime or one of the native libraries \n"
+                        "used by your application.\n"
+                        "=================================================================\n"
+                        "\n");
+
+       fprintf (stderr, "Stacktrace:\n\n");
+
+       mono_jit_walk_stack (print_stack_frame, TRUE, NULL);
+
+       fflush (stderr);
+
+#ifdef HAVE_BACKTRACE_SYMBOLS
+ {
+       void *array [256];
+       char **names;
+       int i, size;
+
+       fprintf (stderr, "\nNative stacktrace:\n\n");
+
+       size = backtrace (array, 256);
+       names = backtrace_symbols (array, size);
+       for (i =0; i < size; ++i) {
+               fprintf (stderr, "\t%s\n", names [i]);
+       }
+       free (names);
+ }
+
+       fflush (stderr);
+#endif
+
+       abort ();
+}