2008-10-24 Mark Probst <mark.probst@gmail.com>
[mono.git] / mono / mini / mini-exceptions.c
index 52cc9b053b15cd28f803a3b7a84e87f5c45fb8d3..9a430eed175897af2725b9b89b9d1f59a065e380 100644 (file)
 
 #ifndef PLATFORM_WIN32
 #include <sys/types.h>
+#include <sys/wait.h>
 #include <unistd.h>
 #endif
 
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef HAVE_SYS_SYSCALL_H
+#include <sys/syscall.h>
+#endif
+
 #include <mono/metadata/appdomain.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/threads.h>
+#include <mono/metadata/threads-types.h>
 #include <mono/metadata/debug-helpers.h>
 #include <mono/metadata/exception.h>
 #include <mono/metadata/gc-internal.h>
 #include <mono/metadata/mono-debug.h>
 #include <mono/metadata/profiler.h>
+#include <mono/utils/mono-mmap.h>
 
 #include "mini.h"
 #include "trace.h"
 
-#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
-#include <unistd.h>
-#include <sys/mman.h>
+#ifndef MONO_ARCH_CONTEXT_DEF
+#define MONO_ARCH_CONTEXT_DEF
 #endif
 
-/* FreeBSD and NetBSD need SA_STACK and MAP_ANON re-definitions */
-#      if defined(__FreeBSD__) || defined(__NetBSD__) 
-#              ifndef SA_STACK
-#                      define SA_STACK SA_ONSTACK
-#              endif
-#              ifndef MAP_ANONYMOUS
-#                      define MAP_ANONYMOUS MAP_ANON
-#              endif
-#      endif /* BSDs */
+static gpointer restore_context_func, call_filter_func;
+static gpointer throw_exception_func, rethrow_exception_func;
+static gpointer throw_exception_by_name_func, throw_corlib_exception_func;
 
-#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)))
+static gpointer try_more_restore_tramp = NULL;
+static gpointer restore_stack_protection_tramp = NULL;
 
-#ifndef MONO_ARCH_CONTEXT_DEF
-#define MONO_ARCH_CONTEXT_DEF
+static void try_more_restore (void);
+static void restore_stack_protection (void);
+
+void
+mono_exceptions_init (void)
+{
+#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
+       guint32 code_size;
+       MonoJumpInfo *ji;
+
+       if (mono_aot_only) {
+               restore_context_func = mono_aot_get_named_code ("restore_context");
+               call_filter_func = mono_aot_get_named_code ("call_filter");
+               throw_exception_func = mono_aot_get_named_code ("throw_exception");
+               rethrow_exception_func = mono_aot_get_named_code ("rethrow_exception");
+       } else {
+               restore_context_func = mono_arch_get_restore_context_full (&code_size, &ji, FALSE);
+               call_filter_func = mono_arch_get_call_filter_full (&code_size, &ji, FALSE);
+               throw_exception_func = mono_arch_get_throw_exception_full (&code_size, &ji, FALSE);
+               rethrow_exception_func = mono_arch_get_rethrow_exception_full (&code_size, &ji, FALSE);
+       }
+#else
+       restore_context_func = mono_arch_get_restore_context ();
+       call_filter_func = mono_arch_get_call_filter ();
+       throw_exception_func = mono_arch_get_throw_exception ();
+       rethrow_exception_func = mono_arch_get_rethrow_exception ();
+#endif
+#ifdef MONO_ARCH_HAVE_RESTORE_STACK_SUPPORT
+       try_more_restore_tramp = mono_create_specific_trampoline (try_more_restore, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
+       restore_stack_protection_tramp = mono_create_specific_trampoline (restore_stack_protection, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
+#endif
+}
+
+gpointer
+mono_get_throw_exception (void)
+{
+       g_assert (throw_exception_func);
+       return throw_exception_func;
+}
+
+gpointer
+mono_get_rethrow_exception (void)
+{
+       g_assert (rethrow_exception_func);
+       return rethrow_exception_func;
+}
+
+gpointer
+mono_get_call_filter (void)
+{
+       g_assert (call_filter_func);
+       return call_filter_func;
+}
+
+gpointer
+mono_get_restore_context (void)
+{
+       g_assert (restore_context_func);
+       return restore_context_func;
+}
+
+gpointer
+mono_get_throw_exception_by_name (void)
+{
+       gpointer code = NULL;
+#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
+       guint32 code_size;
+       MonoJumpInfo *ji;
 #endif
 
-#ifndef mono_find_jit_info
+       /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
+       if (throw_exception_by_name_func)
+               return throw_exception_by_name_func;
+
+#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
+       if (mono_aot_only)
+               code = mono_aot_get_named_code ("throw_exception_by_name");
+       else
+               code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, FALSE);
+#else
+               code = mono_arch_get_throw_exception_by_name ();
+#endif
+
+       mono_memory_barrier ();
+
+       throw_exception_by_name_func = code;
+
+       return throw_exception_by_name_func;
+}
+
+gpointer
+mono_get_throw_corlib_exception (void)
+{
+       gpointer code = NULL;
+#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
+       guint32 code_size;
+       MonoJumpInfo *ji;
+#endif
+
+       /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
+       if (throw_corlib_exception_func)
+               return throw_corlib_exception_func;
+
+#if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
+#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
+       if (mono_aot_only)
+               code = mono_aot_get_named_code ("throw_corlib_exception");
+       else
+               code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, FALSE);
+#else
+               code = mono_arch_get_throw_corlib_exception ();
+#endif
+#else
+       g_assert_not_reached ();
+#endif
+
+       mono_memory_barrier ();
+
+       throw_corlib_exception_func = code;
+
+       return throw_corlib_exception_func;
+}
 
 /* mono_find_jit_info:
  *
  * the @lmf if necessary. @native_offset return the IP offset from the 
  * start of the function or -1 if that info is not available.
  */
-static MonoJitInfo *
+MonoJitInfo *
 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx, 
                    MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
                    gboolean *managed)
@@ -83,7 +205,7 @@ mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *re
        if (managed)
                *managed = FALSE;
 
-       ji = mono_arch_find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, NULL, lmf, NULL, &managed2);
+       ji = mono_arch_find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, lmf, &managed2);
 
        if (ji == (gpointer)-1)
                return ji;
@@ -124,8 +246,6 @@ mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *re
        return ji;
 }
 
-#endif /* mono_find_jit_info */
-
 MonoString *
 ves_icall_System_Exception_get_trace (MonoException *ex)
 {
@@ -224,7 +344,7 @@ ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info
                        sf->il_offset = 0;
 
                if (need_file_info) {
-                       if (location) {
+                       if (location && location->source_file) {
                                MONO_OBJECT_SETREF (sf, filename, mono_string_new (domain, location->source_file));
                                sf->line = location->row;
                                sf->column = location->column;
@@ -283,8 +403,6 @@ mono_walk_stack (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start
        }
 }
 
-#ifndef CUSTOM_STACK_WALK
-
 void
 mono_jit_walk_stack_from_ctx (MonoStackWalk func, MonoContext *start_ctx, gboolean do_il_offset, gpointer user_data)
 {
@@ -310,7 +428,7 @@ mono_jit_walk_stack_from_ctx (MonoStackWalk func, MonoContext *start_ctx, gboole
 #endif
        }
 
-       while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
+       while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
                ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
                g_assert (ji);
 
@@ -351,6 +469,7 @@ ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
        MonoJitInfo *ji, rji;
        MonoContext ctx, new_ctx;
        MonoDebugSourceLocation *location;
+       MonoMethod *last_method = NULL;
 
        MONO_ARCH_CONTEXT_DEF;
 
@@ -362,18 +481,9 @@ ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
        MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
 #endif
 
-       /* 
-        * FIXME: This is needed because of the LMF stuff which doesn't exist on ia64.
-        * Probably the whole mono_find_jit_info () stuff needs to be fixed so this isn't
-        * needed even on other platforms. This is also true for s390/s390x.
-        */
-#if    !defined(__ia64__) && !defined(__s390__) && !defined(__s390x__)
-       skip++;
-#endif
-
        do {
                ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
-
+               
                ctx = new_ctx;
                
                if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_SP (&ctx) >= jit_tls->end_of_stack)
@@ -384,8 +494,20 @@ ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
                    ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
                    ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
                    ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
-                   ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
+                   ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE ||
+                       ji->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
+                       continue;
+
+               if (ji->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && ji->method == last_method) {
+                       /*
+                        * FIXME: Native-to-managed wrappers sometimes show up twice.
+                        * Probably the whole mono_find_jit_info () stuff needs to be fixed so this 
+                        * isn't needed.
+                        */
                        continue;
+               }
+
+               last_method = ji->method;
 
                skip--;
 
@@ -415,8 +537,6 @@ ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
        return TRUE;
 }
 
-#endif /* CUSTOM_STACK_WALK */
-
 typedef struct {
        guint32 skips;
        MonoSecurityFrame *frame;
@@ -472,6 +592,10 @@ ves_icall_System_Security_SecurityFrame_GetSecurityFrame (gint32 skip)
        MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
 #endif
 
+#if    defined(__ia64__) || defined(__s390__) || defined(__s390x__)
+       skip--;
+#endif
+
        si.skips = skip;
        si.frame = NULL;
        mono_walk_stack (domain, jit_tls, &ctx, callback_get_first_frame_security_info, (gpointer)&si);
@@ -574,6 +698,10 @@ ves_icall_System_Security_SecurityFrame_GetSecurityStack (gint32 skip)
        MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityStack);
 #endif
 
+#if    defined(__ia64__) || defined(__s390__) || defined(__s390x__)
+       skip--;
+#endif
+
        ss.skips = skip;
        ss.count = 0;
        ss.maximum = MONO_CAS_INITIAL_STACK_SIZE;
@@ -583,7 +711,76 @@ ves_icall_System_Security_SecurityFrame_GetSecurityStack (gint32 skip)
        return ss.stack;
 }
 
-#ifndef CUSTOM_EXCEPTION_HANDLING
+static MonoClass*
+get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
+{
+       MonoClass *catch_class = ei->data.catch_class;
+       MonoGenericJitInfo *gi;
+       gpointer info;
+       MonoClass *class, *method_container_class;
+       MonoType *inflated_type;
+       MonoGenericContext context = { NULL, NULL };
+
+       if (!catch_class)
+               return NULL;
+
+       if (!ji->has_generic_jit_info)
+               return catch_class;
+
+       gi = mono_jit_info_get_generic_jit_info (ji);
+       if (!gi->has_this)
+               return catch_class;
+
+       if (gi->this_in_reg)
+               info = mono_arch_context_get_int_reg (ctx, gi->this_reg);
+       else
+               info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
+                               gi->this_offset);
+
+       g_assert (ji->method->is_inflated);
+
+       if (mono_method_get_context (ji->method)->method_inst) {
+               MonoMethodRuntimeGenericContext *mrgctx = info;
+
+               class = mrgctx->class_vtable->klass;
+               context.method_inst = mrgctx->method_inst;
+               g_assert (context.method_inst);
+       } else if ((ji->method->flags & METHOD_ATTRIBUTE_STATIC) || ji->method->klass->valuetype) {
+               MonoVTable *vtable = info;
+
+               class = vtable->klass;
+       } else {
+               MonoObject *this = info;
+
+               class = this->vtable->klass;
+       }
+
+       if (class->generic_class || class->generic_container)
+               context.class_inst = mini_class_get_context (class)->class_inst;
+
+       g_assert (!ji->method->klass->generic_container);
+       if (ji->method->klass->generic_class)
+               method_container_class = ji->method->klass->generic_class->container_class;
+       else
+               method_container_class = ji->method->klass;
+
+       if (class->generic_class)
+               g_assert (class->generic_class->container_class == method_container_class);
+       else
+               g_assert (!class->generic_container && class == method_container_class);
+
+       /* FIXME: we shouldn't inflate but instead put the
+          type in the rgctx and fetch it from there.  It
+          might be a good idea to do this lazily, i.e. only
+          when the exception is actually thrown, so as not to
+          waste space for exception clauses which might never
+          be encountered. */
+       inflated_type = mono_class_inflate_generic_type (&catch_class->byval_arg, &context);
+       catch_class = mono_class_from_mono_type (inflated_type);
+       mono_metadata_free_type (inflated_type);
+
+       return catch_class;
+}
 
 /**
  * mono_handle_exception_internal:
@@ -608,25 +805,8 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
        gboolean stack_overflow = FALSE;
        MonoContext initial_ctx;
        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
-        * can't handle that.
-        * Also, since the altstack is small, stack space intensive operations like
-        * JIT compilation should be avoided.
-        */
-       if (IS_ON_SIGALTSTACK (jit_tls)) {
-               /* 
-                * FIXME: disabling/enabling GC while already on a signal stack might
-                * not be safe either.
-                */
-               /* Have to reenable it later */
-               gc_disabled = TRUE;
-               mono_gc_disable ();
-       }
 
        g_assert (ctx != NULL);
        if (!obj) {
@@ -637,11 +817,12 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
 
        /*
         * Allocate a new exception object instead of the preconstructed ones.
-        * We can't do this in sigsegv_signal_handler, since GC is not yet
-        * disabled.
         */
        if (obj == domain->stack_overflow_ex) {
-               obj = mono_get_exception_stack_overflow ();
+               /*
+                * It is not a good idea to try and put even more pressure on the little stack available.
+                * obj = mono_get_exception_stack_overflow ();
+                */
                stack_overflow = TRUE;
        }
        else if (obj == domain->null_reference_ex) {
@@ -655,11 +836,21 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                mono_ex = NULL;
        }
 
+       if (mono_ex && jit_tls->class_cast_to && !strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
+               char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
+               char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
+               char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
+               mono_ex->message = mono_string_new (domain, msg);
+               g_free (from_name);
+               g_free (to_name);
+               g_free (msg);
+       }
+
        if (!call_filter)
-               call_filter = mono_arch_get_call_filter ();
+               call_filter = mono_get_call_filter ();
 
        if (!restore_context)
-               restore_context = mono_arch_get_restore_context ();
+               restore_context = mono_get_restore_context ();
 
        g_assert (jit_tls->end_of_stack);
        g_assert (jit_tls->abort_func);
@@ -672,6 +863,8 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                if (!mono_handle_exception_internal (&ctx_cp, obj, original_ip, TRUE, &first_filter_idx)) {
                        if (mono_break_on_exc)
                                G_BREAKPOINT ();
+                       // FIXME: This runs managed code so it might cause another stack overflow when
+                       // we are handling a stack overflow
                        mono_unhandled_exception (obj);
 
                        if (mono_debugger_unhandled_exception (original_ip, MONO_CONTEXT_GET_SP (ctx), obj)) {
@@ -706,6 +899,15 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                        g_assert_not_reached ();
                }
 
+               if (ji != (gpointer)-1 && !(ji->code_start <= MONO_CONTEXT_GET_IP (ctx) && (((guint8*)ji->code_start + ji->code_size >= (guint8*)MONO_CONTEXT_GET_IP (ctx))))) {
+                       /*
+                        * The exception was raised in native code and we got back to managed code 
+                        * using the LMF.
+                        */
+                       *ctx = new_ctx;
+                       continue;
+               }
+
                if (ji != (gpointer)-1) {
                        frame_count ++;
                        //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
@@ -744,13 +946,19 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                        MonoJitExceptionInfo *ei = &ji->clauses [i];
                                        gboolean filtered = FALSE;
 
-#ifdef __s390__
+#if defined(__s390__)
+                                       /* 
+                                        * This is required in cases where a try block starts immediately after
+                                        * a call which causes an exception. Testcase: tests/exception8.cs.
+                                        * FIXME: Clean this up.
+                                        */
                                        if (ei->try_start < MONO_CONTEXT_GET_IP (ctx) && 
 #else
                                        if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
 #endif
                                            MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
                                                /* catch block */
+                                               MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
 
                                                if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
                                                        /* store the exception object in bp + ei->exvar_offset */
@@ -760,6 +968,7 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                                if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
                                                        // mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
                                                        if (test_only) {
+                                                               mono_perfcounters->exceptions_filters++;
                                                                filtered = call_filter (ctx, ei->data.filter);
                                                                if (filtered && out_filter_idx)
                                                                        *out_filter_idx = filter_idx;
@@ -775,7 +984,7 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                                }
 
                                                if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
-                                                    mono_object_isinst (obj, ei->data.catch_class)) || filtered) {
+                                                    mono_object_isinst (obj, catch_class)) || filtered) {
                                                        if (test_only) {
                                                                if (mono_ex && !initial_trace_ips) {
                                                                        trace_ips = g_list_reverse (trace_ips);
@@ -786,8 +995,6 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                                                }
                                                                g_list_free (trace_ips);
 
-                                                               if (gc_disabled)
-                                                                       mono_gc_enable ();
                                                                return TRUE;
                                                        }
                                                        if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
@@ -796,9 +1003,10 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                                        mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
                                                        MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
                                                        *(mono_get_lmf_addr ()) = lmf;
+                                                       mono_perfcounters->exceptions_depth += frame_count;
+                                                       if (obj == domain->stack_overflow_ex)
+                                                               jit_tls->handling_stack_ovf = FALSE;
 
-                                                       if (gc_disabled)
-                                                               mono_gc_enable ();
                                                        return 0;
                                                }
                                                if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
@@ -817,6 +1025,7 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                                                g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
                                                        mono_profiler_exception_clause_handler (ji->method, ei->flags, i);
                                                        mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
+                                                       mono_perfcounters->exceptions_finallys++;
                                                        call_filter (ctx, ei->handler_start);
                                                }
                                                
@@ -830,34 +1039,11 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                *ctx = new_ctx;
 
                if (ji == (gpointer)-1) {
-                       if (gc_disabled)
-                               mono_gc_enable ();
 
                        if (!test_only) {
                                *(mono_get_lmf_addr ()) = lmf;
 
-                               if (IS_ON_SIGALTSTACK (jit_tls)) {
-                                       /* Switch back to normal stack */
-                                       if (stack_overflow) {
-                                               /* Free up some stack space */
-#ifndef MONO_ARCH_STACK_GROWS_UP
-                                               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);
-#else
-                                               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);
-#endif
-                                       }
-#ifdef MONO_CONTEXT_SET_FUNC
-                                       /* jit_tls->abort_func is a function descriptor on ia64 */
-                                       MONO_CONTEXT_SET_FUNC (&initial_ctx, (gssize)jit_tls->abort_func);
-#else
-                                       MONO_CONTEXT_SET_IP (&initial_ctx, (gssize)jit_tls->abort_func);
-#endif
-                                       restore_context (&initial_ctx);
-                               }
-                               else
-                                       jit_tls->abort_func (obj);
+                               jit_tls->abort_func (obj);
                                g_assert_not_reached ();
                        } else {
                                if (mono_ex && !initial_trace_ips) {
@@ -905,7 +1091,7 @@ mono_debugger_run_finally (MonoContext *start_ctx)
                return;
 
        if (!call_filter)
-               call_filter = mono_arch_get_call_filter ();
+               call_filter = mono_get_call_filter ();
 
        for (i = 0; i < ji->num_clauses; i++) {
                MonoJitExceptionInfo *ei = &ji->clauses [i];
@@ -927,51 +1113,43 @@ mono_debugger_run_finally (MonoContext *start_ctx)
 gboolean
 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
 {
+       if (!test_only)
+               mono_perfcounters->exceptions_thrown++;
        return mono_handle_exception_internal (ctx, obj, original_ip, test_only, NULL);
 }
 
-#endif /* CUSTOM_EXCEPTION_HANDLING */
-
 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
 
+#ifndef MONO_ARCH_USE_SIGACTION
+#error "Can't use sigaltstack without sigaction"
+#endif
+
 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
+       mono_thread_get_stack_bounds (&staddr, &stsize);
 
-#ifndef sun
-       pthread_attr_getstack( &attr, (void**)&staddr, &stsize );
-#endif
+       g_assert (staddr);
 
-       pthread_attr_destroy (&attr); 
+       tls->end_of_stack = staddr + stsize;
 
-       g_assert (staddr);
+       /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
 
-       g_assert ((current > staddr) && (current < staddr + stsize));
+       tls->stack_ovf_guard_base = staddr + mono_pagesize ();
+       tls->stack_ovf_guard_size = mono_pagesize () * 8;
 
-       tls->end_of_stack = staddr + stsize;
+       if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
+               /* mprotect can fail for the main thread stack */
+               gpointer gaddr = mono_valloc (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE|MONO_MMAP_PRIVATE|MONO_MMAP_ANON|MONO_MMAP_FIXED);
+               g_assert (gaddr == tls->stack_ovf_guard_base);
+       }
 
        /*
         * threads created by nptl does not seem to have a guard page, and
@@ -979,10 +1157,10 @@ mono_setup_altstack (MonoJitTlsData *tls)
         * Increasing stsize fools the SIGSEGV signal handler into thinking this
         * is a stack overflow exception.
         */
-       tls->stack_size = stsize + getpagesize ();
+       tls->stack_size = stsize + mono_pagesize ();
 
        /* 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 = mono_valloc (0, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_PRIVATE|MONO_MMAP_ANON);
        tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
 
        g_assert (tls->signal_stack);
@@ -1006,11 +1184,124 @@ mono_free_altstack (MonoJitTlsData *tls)
        g_assert (err == 0);
 
        if (tls->signal_stack)
-               munmap (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
+               mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
+}
+
+#else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
+
+void
+mono_setup_altstack (MonoJitTlsData *tls)
+{
+}
+
+void
+mono_free_altstack (MonoJitTlsData *tls)
+{
 }
 
 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
 
+static gboolean
+try_restore_stack_protection (MonoJitTlsData *jit_tls, int extra_bytes)
+{
+       gint32 unprotect_size = jit_tls->stack_ovf_guard_size;
+       /* we need to leave some room for throwing the exception */
+       while (unprotect_size >= 0 && (char*)jit_tls->stack_ovf_guard_base + unprotect_size > ((char*)&unprotect_size - extra_bytes))
+               unprotect_size -= mono_pagesize ();
+       /* at this point we could try and build a new domain->stack_overflow_ex, but only if there
+        * is sufficient stack
+        */
+       //fprintf (stderr, "restoring stack protection: %p-%p (%d)\n", jit_tls->stack_ovf_guard_base, (char*)jit_tls->stack_ovf_guard_base + unprotect_size, unprotect_size);
+       if (unprotect_size)
+               mono_mprotect (jit_tls->stack_ovf_guard_base, unprotect_size, MONO_MMAP_NONE);
+       return unprotect_size == jit_tls->stack_ovf_guard_size;
+}
+
+static void
+try_more_restore (void)
+{
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+       if (try_restore_stack_protection (jit_tls, 500))
+               jit_tls->restore_stack_prot = NULL;
+}
+
+static void
+restore_stack_protection (void)
+{
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+       MonoException *ex = mono_domain_get ()->stack_overflow_ex;
+       /* if we can't restore the stack protection, keep a callback installed so
+        * we'll try to restore as much stack as we can at each return from unmanaged
+        * code.
+        */
+       if (try_restore_stack_protection (jit_tls, 4096))
+               jit_tls->restore_stack_prot = NULL;
+       else
+               jit_tls->restore_stack_prot = try_more_restore_tramp;
+       /* here we also throw a stack overflow exception */
+       ex->trace_ips = NULL;
+       ex->stack_trace = NULL;
+       mono_raise_exception (ex);
+}
+
+gpointer
+mono_altstack_restore_prot (gssize *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
+{
+       void (*func)(void) = (gpointer)tramp_data;
+       func ();
+       return NULL;
+}
+
+gboolean
+mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
+{
+       /* we got a stack overflow in the soft-guard pages
+        * There are two cases:
+        * 1) managed code caused the overflow: we unprotect the soft-guard page
+        * and let the arch-specific code trigger the exception handling mechanism
+        * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
+        * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
+        * and hope we can continue with those enabled, at least until the hard-guard page
+        * is hit. The alternative to continuing here is to just print a message and abort.
+        * We may add in the future the code to protect the pages again in the codepath
+        * when we return from unmanaged to managed code.
+        */
+       if (jit_tls->stack_ovf_guard_size && fault_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
+                       fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
+               /* we unprotect the minimum amount we can */
+               guint32 guard_size;
+               gboolean handled = FALSE;
+
+               guard_size = jit_tls->stack_ovf_guard_size - (mono_pagesize () * SIZEOF_VOID_P / 4);
+               while (guard_size && fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + guard_size) {
+                       guard_size -= mono_pagesize ();
+               }
+               guard_size = jit_tls->stack_ovf_guard_size - guard_size;
+               /*fprintf (stderr, "unprotecting: %d\n", guard_size);*/
+               mono_mprotect ((char*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size - guard_size, guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
+#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
+               if (ji) {
+                       mono_arch_handle_altstack_exception (ctx, fault_addr, TRUE);
+                       handled = TRUE;
+               }
+#endif
+               if (!handled) {
+                       /* We print a message: after this even managed stack overflows
+                        * may crash the runtime
+                        */
+                       fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), fault_addr);
+                       if (!jit_tls->handling_stack_ovf) {
+                               jit_tls->restore_stack_prot = restore_stack_protection_tramp;
+                               jit_tls->handling_stack_ovf = 1;
+                       } else {
+                               /*fprintf (stderr, "Already handling stack overflow\n");*/
+                       }
+               }
+               return TRUE;
+       }
+       return FALSE;
+}
+
 static gboolean
 print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
 {
@@ -1026,6 +1317,22 @@ print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, g
        return FALSE;
 }
 
+static G_GNUC_UNUSED gboolean
+print_stack_frame_to_string (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed,
+                            gpointer data)
+{
+       GString *p = (GString*)data;
+
+       if (method) {
+               gchar *location = mono_debug_print_stack_frame (method, native_offset, mono_domain_get ());
+               g_string_append_printf (p, "  %s\n", location);
+               g_free (location);
+       } else
+               g_string_append_printf (p, "  at <unknown> <0x%05x>\n", native_offset);
+
+       return FALSE;
+}
+
 static gboolean handling_sigsegv = FALSE;
 
 /*
@@ -1040,26 +1347,28 @@ mono_handle_native_sigsegv (int signal, void *ctx)
 #ifndef PLATFORM_WIN32
        struct sigaction sa;
 #endif
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+
        if (handling_sigsegv)
                return;
 
        /* To prevent infinite loops when the stack walk causes a crash */
        handling_sigsegv = TRUE;
 
-       fprintf (stderr, "Stacktrace:\n\n");
+       /* !jit_tls means the thread was not registered with the runtime */
+       if (jit_tls) {
+               fprintf (stderr, "Stacktrace:\n\n");
 
-       mono_jit_walk_stack (print_stack_frame, TRUE, stderr);
+               mono_jit_walk_stack (print_stack_frame, TRUE, stderr);
 
-       fflush (stderr);
+               fflush (stderr);
+       }
 
 #ifdef HAVE_BACKTRACE_SYMBOLS
  {
        void *array [256];
        char **names;
-       char cmd [1024];
        int i, size;
-       gchar *out, *err;
-       gint exit_status;
        const char *signal_str = (signal == SIGSEGV) ? "SIGSEGV" : "SIGABRT";
 
        fprintf (stderr, "\nNative stacktrace:\n\n");
@@ -1075,15 +1384,66 @@ mono_handle_native_sigsegv (int signal, void *ctx)
 
        /* Try to get more meaningful information using gdb */
 
-#ifndef PLATFORM_WIN32
-       sprintf (cmd, "gdb --ex 'attach %ld' --ex 'info threads' --ex 'thread apply all bt' --batch", (long)getpid ());
-       {
-               int res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
+#if !defined(PLATFORM_WIN32) && defined(HAVE_SYS_SYSCALL_H) && defined(SYS_fork)
+       if (!mini_get_debug_options ()->no_gdb_backtrace) {
+               /* From g_spawn_command_line_sync () in eglib */
+               int res;
+               int stdout_pipe [2] = { -1, -1 };
+               pid_t pid;
+               const char *argv [16];
+               char buf1 [128];
+               int status;
+               char buffer [1024];
+
+               res = pipe (stdout_pipe);
+               g_assert (res != -1);
+                       
+               //pid = fork ();
+               /*
+                * glibc fork acquires some locks, so if the crash happened inside malloc/free,
+                * it will deadlock. Call the syscall directly instead.
+                */
+               pid = syscall (SYS_fork);
+               if (pid == 0) {
+                       close (stdout_pipe [0]);
+                       dup2 (stdout_pipe [1], STDOUT_FILENO);
+
+                       for (i = getdtablesize () - 1; i >= 3; i--)
+                               close (i);
+
+                       argv [0] = g_find_program_in_path ("gdb");
+                       if (argv [0] == NULL) {
+                               close (STDOUT_FILENO);
+                               exit (1);
+                       }
 
-               if (res) {
-                       fprintf (stderr, "\nDebug info from gdb:\n\n");
-                       fprintf (stderr, "%s\n", out);
+                       argv [1] = "-ex";
+                       sprintf (buf1, "attach %ld", (long)getpid ());
+                       argv [2] = buf1;
+                       argv [3] = "--ex";
+                       argv [4] = "info threads";
+                       argv [5] = "--ex";
+                       argv [6] = "thread apply all bt";
+                       argv [7] = "--batch";
+                       argv [8] = 0;
+
+                       execv (argv [0], (char**)argv);
+                       exit (1);
                }
+
+               close (stdout_pipe [1]);
+
+               fprintf (stderr, "\nDebug info from gdb:\n\n");
+
+               while (1) {
+                       int nread = read (stdout_pipe [0], buffer, 1024);
+
+                       if (nread <= 0)
+                               break;
+                       write (STDERR_FILENO, buffer, nread);
+               }               
+
+               waitpid (pid, &status, WNOHANG);
        }
 #endif
        /*
@@ -1121,36 +1481,43 @@ mono_handle_native_sigsegv (int signal, void *ctx)
  * mono_print_thread_dump:
  *
  *   Print information about the current thread to stdout.
+ * SIGCTX can be NULL, allowing this to be called from gdb.
  */
 void
 mono_print_thread_dump (void *sigctx)
 {
        MonoThread *thread = mono_thread_current ();
-#ifdef __i386__
+#if defined(__i386__) || defined(__x86_64__)
        MonoContext ctx;
 #endif
+       GString* text = g_string_new (0);
        char *name;
        GError *error = NULL;
 
        if (thread->name) {
                name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
                g_assert (!error);
-               fprintf (stdout, "\n\"%s\"", name);
+               g_string_append_printf (text, "\n\"%s\"", name);
                g_free (name);
        }
        else
-               fprintf (stdout, "\n\"\"");
+               g_string_append (text, "\n\"\"");
 
-       fprintf (stdout, " tid=0x%p this=0x%p:\n", (gpointer)(gsize)thread->tid, thread);
+       g_string_append_printf (text, " tid=0x%p this=0x%p:\n", (gpointer)(gsize)thread->tid, thread);
 
        /* FIXME: */
-#ifdef __i386__
-       mono_arch_sigctx_to_monoctx (sigctx, &ctx);
+#if defined(__i386__) || defined(__x86_64__)
+       if (!sigctx)
+               MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_print_thread_dump);
+       else
+               mono_arch_sigctx_to_monoctx (sigctx, &ctx);
 
-       mono_jit_walk_stack_from_ctx (print_stack_frame, &ctx, TRUE, stdout);
+       mono_jit_walk_stack_from_ctx (print_stack_frame_to_string, &ctx, TRUE, text);
 #else
        printf ("\t<Stack traces in thread dumps not supported on this platform>\n");
 #endif
 
+       fprintf (stdout, text->str);
+       g_string_free (text, TRUE);
        fflush (stdout);
 }