Merge pull request #4621 from alexanderkyte/strdup_env
[mono.git] / mono / mini / mini-exceptions.c
index c69678b593d2c848366d33b2b398a1d5a0475bb9..cacc74c49bc360f876d124fc3fa8a851b479dea7 100644 (file)
@@ -1,5 +1,6 @@
-/*
- * mini-exceptions.c: generic exception support
+/**
+ * \file
+ * generic exception support
  *
  * Authors:
  *   Dietmar Maurer (dietmar@ximian.com)
@@ -73,6 +74,7 @@
 #include "seq-points.h"
 #include "llvm-runtime.h"
 #include "mini-llvm.h"
+#include "interp/interp.h"
 
 #ifdef ENABLE_LLVM
 #include "mini-llvm-cpp.h"
@@ -180,6 +182,15 @@ mini_above_abort_threshold (void)
        return above_threshold;
 }
 
+static int
+mono_get_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
+{
+       SeqPoint sp;
+       if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
+               return sp.il_offset;
+       return -1;
+}
+
 void
 mono_exceptions_init (void)
 {
@@ -211,7 +222,13 @@ mono_exceptions_init (void)
 #ifdef MONO_ARCH_HAVE_EXCEPTIONS_INIT
        mono_arch_exceptions_init ();
 #endif
-       cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
+#ifdef ENABLE_INTERPRETER
+       if (mono_use_interpreter)
+               cbs.mono_walk_stack_with_ctx = interp_walk_stack_with_ctx;
+       else
+#endif
+               cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
+
        cbs.mono_walk_stack_with_state = mono_walk_stack_with_state;
 
        if (mono_llvm_only)
@@ -225,6 +242,7 @@ mono_exceptions_init (void)
        cbs.mono_clear_abort_threshold = mini_clear_abort_threshold;
        cbs.mono_above_abort_threshold = mini_above_abort_threshold;
        mono_install_eh_callbacks (&cbs);
+       mono_install_get_seq_point (mono_get_seq_point_for_native_offset);
 }
 
 gpointer
@@ -743,10 +761,9 @@ get_method_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
 
 /**
  * mono_exception_walk_native_trace:
- * @ex: The exception object whose frames should be walked
- * @func: callback to call for each stack frame
- * @user_data: data passed to the callback
- *
+ * \param ex The exception object whose frames should be walked
+ * \param func callback to call for each stack frame
+ * \param user_data data passed to the callback
  * This function walks the stacktrace of an exception. For
  * each frame the callback function is called with the relevant info.
  * The walk ends when no more stack frames are found or when the callback
@@ -899,10 +916,8 @@ mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx,
 }
 /**
  * mono_walk_stack_with_ctx:
- *
- * Unwind the current thread starting at @start_ctx.
- * 
- * If @start_ctx is null, we capture the current context.
+ * Unwind the current thread starting at \p start_ctx.
+ * If \p start_ctx is null, we capture the current context.
  */
 void
 mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
@@ -930,14 +945,13 @@ mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnw
 
 /**
  * mono_walk_stack_with_state:
- *
- * Unwind a thread described by @state.
+ * Unwind a thread described by \p state.
  *
  * State must be valid (state->valid == TRUE).
  *
  * If you are using this function to unwind another thread, make sure it is suspended.
  * 
- * If @state is null, we capture the current context.
+ * If \p state is null, we capture the current context.
  */
 void
 mono_walk_stack_with_state (MonoJitStackWalk func, MonoThreadUnwindState *state, MonoUnwindOptions unwind_options, void *user_data)
@@ -975,16 +989,15 @@ mono_walk_stack (MonoJitStackWalk func, MonoUnwindOptions options, void *user_da
 
 /**
  * mono_walk_stack_full:
- * @func: callback to call for each stack frame
- * @domain: starting appdomain, can be NULL to use the current domain
- * @unwind_options: what extra information the unwinder should gather
- * @start_ctx: starting state of the stack walk, can be NULL.
- * @thread: the thread whose stack to walk, can be NULL to use the current thread
- * @lmf: the LMF of @thread, can be NULL to use the LMF of the current thread
- * @user_data: data passed to the callback
- *
+ * \param func callback to call for each stack frame
+ * \param domain starting appdomain, can be NULL to use the current domain
+ * \param unwind_options what extra information the unwinder should gather
+ * \param start_ctx starting state of the stack walk, can be NULL.
+ * \param thread the thread whose stack to walk, can be NULL to use the current thread
+ * \param lmf the LMF of \p thread, can be NULL to use the LMF of the current thread
+ * \param user_data data passed to the callback
  * This function walks the stack of a thread, starting from the state
- * represented by start_ctx. For each frame the callback
+ * represented by \p start_ctx. For each frame the callback
  * function is called with the relevant info. The walk ends when no more
  * managed stack frames are found or when the callback returns a TRUE value.
  */
@@ -1291,7 +1304,7 @@ mini_jit_info_table_find (MonoDomain *domain, char *addr, MonoDomain **out_domai
 }
 
 /* Class lazy loading functions */
-static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, System.Runtime.CompilerServices, RuntimeCompatibilityAttribute)
+static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute")
 
 /*
  * wrap_non_exception_throws:
@@ -1365,7 +1378,7 @@ wrap_non_exception_throws (MonoMethod *m)
 static MonoArray*
 build_native_trace (MonoError *error)
 {
-       mono_error_init (error);
+       error_init (error);
 /* This puppy only makes sense on mobile, IOW, ARM. */
 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
        MonoArray *res;
@@ -1390,9 +1403,9 @@ build_native_trace (MonoError *error)
 }
 
 static void
-setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, MonoArray *initial_trace_ips, GList **trace_ips)
+setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, GList **trace_ips)
 {
-       if (mono_ex && !initial_trace_ips) {
+       if (mono_ex) {
                *trace_ips = g_list_reverse (*trace_ips);
                MonoError error;
                MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
@@ -1446,7 +1459,6 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
        static int (*call_filter) (MonoContext *, gpointer) = NULL;
        MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
        MonoLMF *lmf = mono_get_lmf ();
-       MonoArray *initial_trace_ips = NULL;
        GList *trace_ips = NULL;
        GSList *dynamic_methods = NULL;
        MonoException *mono_ex;
@@ -1464,12 +1476,19 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
                stack_overflow = TRUE;
 
        mono_ex = (MonoException*)obj;
-       initial_trace_ips = mono_ex->trace_ips;
+       MonoArray *initial_trace_ips = mono_ex->trace_ips;
+       if (initial_trace_ips) {
+               int len = mono_array_length (initial_trace_ips) >> 1;
+
+               for (i = 0; i < (len - 1); i++) {
+                       gpointer ip = mono_array_get (initial_trace_ips, gpointer, i * 2 + 0);
+                       gpointer generic_info = mono_array_get (initial_trace_ips, gpointer, i * 2 + 1);
+                       trace_ips = g_list_prepend (trace_ips, ip);
+                       trace_ips = g_list_prepend (trace_ips, generic_info);
+               }
+       }
 
-       if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
-               mono_ex = (MonoException*)obj;
-               initial_trace_ips = mono_ex->trace_ips;
-       } else {
+       if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
                mono_error_assert_ok (&error);
                mono_ex = NULL;
        }
@@ -1513,7 +1532,7 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
                }
 
                if (!unwind_res) {
-                       setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
+                       setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
                        g_slist_free (dynamic_methods);
                        return FALSE;
                }
@@ -1529,15 +1548,10 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
                }
 
                if (method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
-                       /* 
-                        * Avoid overwriting the stack trace if the exception is
-                        * rethrown. Also avoid giant stack traces during a stack
-                        * overflow.
-                        */
-                       if (!initial_trace_ips && (frame_count < 1000)) {
+                       // avoid giant stack traces during a stack overflow
+                       if (frame_count < 1000) {
                                trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
-                               trace_ips = g_list_prepend (trace_ips,
-                                                                                       get_generic_info_from_stack_frame (ji, ctx));
+                               trace_ips = g_list_prepend (trace_ips, get_generic_info_from_stack_frame (ji, ctx));
                        }
                }
 
@@ -1578,18 +1592,9 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
                                        ex_obj = obj;
 
                                if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
-                                       gboolean is_user_frame = method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD;
 #ifndef DISABLE_PERFCOUNTERS
                                        mono_perfcounters->exceptions_filters++;
 #endif
-                                       /*
-                                       Here's the thing, if this is a filter clause done by a wrapper like runtime invoke, we don't want to
-                                       trim the stackframe since if it returns FALSE we lose information.
-
-                                       FIXME Not 100% sure if it's a good idea even with user clauses.
-                                       */
-                                       if (is_user_frame)
-                                               setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
 
 #ifndef MONO_CROSS_COMPILE
 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
@@ -1626,8 +1631,7 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
                                        filter_idx ++;
 
                                        if (filtered) {
-                                               if (!is_user_frame)
-                                                       setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
+                                               setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
                                                g_slist_free (dynamic_methods);
                                                /* mono_debugger_agent_handle_exception () needs this */
                                                mini_set_abort_threshold (ctx);
@@ -1637,9 +1641,9 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
                                }
 
                                MonoError isinst_error;
-                               mono_error_init (&isinst_error);
+                               error_init (&isinst_error);
                                if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (ex_obj, catch_class, &error)) {
-                                       setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
+                                       setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
                                        g_slist_free (dynamic_methods);
 
                                        if (out_ji)
@@ -1661,9 +1665,9 @@ mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gi
 
 /**
  * mono_handle_exception_internal:
- * @ctx: saved processor state
- * @obj: the exception object
- * @resume: whenever to resume unwinding based on the state in MonoJitTlsData.
+ * \param ctx saved processor state
+ * \param obj the exception object
+ * \param resume whenever to resume unwinding based on the state in \c MonoJitTlsData.
  */
 static gboolean
 mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resume, MonoJitInfo **out_ji)
@@ -1945,7 +1949,7 @@ mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resu
                                        filter_idx ++;
                                }
 
-                               mono_error_init (&error);
+                               error_init (&error);
                                if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
                                     mono_object_isinst_checked (ex_obj, catch_class, &error)) || filtered) {
                                        /*
@@ -1979,7 +1983,7 @@ mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resu
                                                if (is_outside) {
                                                        jit_tls->handler_block_return_address = NULL;
                                                        jit_tls->handler_block = NULL;
-                                                       mono_thread_resume_interruption (); /*We ignore the exception here, it will be raised later*/
+                                                       mono_thread_resume_interruption (TRUE); /*We ignore the exception here, it will be raised later*/
                                                }
                                        }
 
@@ -2059,13 +2063,11 @@ mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resu
 
 /**
  * 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
+ * \param start_ctx saved processor state
+ * This method is called by the Mono Debugger to call all \c finally clauses of the
+ * current stack frame.  It's used when the user issues a \c 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
@@ -2100,8 +2102,8 @@ mono_debugger_run_finally (MonoContext *start_ctx)
 
 /**
  * mono_handle_exception:
- * @ctx: saved processor state
- * @obj: the exception object
+ * \param ctx saved processor state
+ * \param obj the exception object
  */
 gboolean
 mono_handle_exception (MonoContext *ctx, MonoObject *obj)
@@ -2422,6 +2424,34 @@ print_stack_frame_to_string (StackFrameInfo *frame, MonoContext *ctx, gpointer d
 
 #ifndef MONO_CROSS_COMPILE
 
+static void print_process_map (void)
+{
+#ifdef __linux__
+       FILE *fp = fopen ("/proc/self/maps", "r");
+       char line [256];
+
+       if (fp == NULL) {
+               mono_runtime_printf_err ("no /proc/self/maps, not on linux?\n");
+               return;
+       }
+
+       mono_runtime_printf_err ("/proc/self/maps:");
+
+       while (fgets (line, sizeof (line), fp)) {
+               // strip newline
+               size_t len = strlen (line) - 1;
+               if (len >= 0 && line [len] == '\n')
+                       line [len] = '\0';
+
+               mono_runtime_printf_err ("%s", line);
+       }
+
+       fclose (fp);
+#else
+       /* do nothing */
+#endif
+}
+
 static gboolean handling_sigsegv = FALSE;
 
 /*
@@ -2438,10 +2468,12 @@ mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_T
 #endif
        MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
 
-       if (handling_sigsegv)
+       gboolean is_sigsegv = !strcmp ("SIGSEGV", signal);
+
+       if (handling_sigsegv && is_sigsegv)
                return;
 
-       if (mini_get_debug_options ()->suspend_on_sigsegv) {
+       if (mini_get_debug_options ()->suspend_on_native_crash) {
                mono_runtime_printf_err ("Received %s, suspending...", signal);
 #ifdef HOST_WIN32
                while (1)
@@ -2454,7 +2486,8 @@ mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_T
        }
 
        /* To prevent infinite loops when the stack walk causes a crash */
-       handling_sigsegv = TRUE;
+       if (is_sigsegv)
+               handling_sigsegv = TRUE;
 
        /* !jit_tls means the thread was not registered with the runtime */
        if (jit_tls && mono_thread_internal_current ()) {
@@ -2464,6 +2497,8 @@ mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_T
                mono_walk_stack (print_stack_frame_to_stderr, MONO_UNWIND_LOOKUP_IL_OFFSET, NULL);
        }
 
+       print_process_map ();
+
 #ifdef HAVE_BACKTRACE_SYMBOLS
  {
        void *array [256];
@@ -2488,12 +2523,21 @@ mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_T
                int status;
                pid_t crashed_pid = getpid ();
 
-               //pid = fork ();
                /*
                 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
                 * it will deadlock. Call the syscall directly instead.
                 */
-               pid = mono_runtime_syscall_fork ();
+#if defined(PLATFORM_ANDROID)
+               /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
+               g_assert_not_reached ();
+#elif !defined(PLATFORM_MACOSX) && defined(SYS_fork)
+               pid = (pid_t) syscall (SYS_fork);
+#elif defined(PLATFORM_MACOSX) && HAVE_FORK
+               pid = (pid_t) fork ();
+#else
+               g_assert_not_reached ();
+#endif
+
 #if defined (HAVE_PRCTL) && defined(PR_SET_PTRACER)
                if (pid > 0) {
                        // Allow gdb to attach to the process even if ptrace_scope sysctl variable is set to
@@ -2516,7 +2560,15 @@ mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_T
 #endif
  }
 #else
-       mono_exception_native_unwind (ctx, info);
+#ifdef PLATFORM_ANDROID
+       /* set DUMPABLE for this process so debuggerd can attach with ptrace(2), see:
+        * https://android.googlesource.com/platform/bionic/+/151da681000c07da3c24cd30a3279b1ca017f452/linker/debugger.cpp#206
+        * this has changed on later versions of Android.  Also, we don't want to
+        * set this on start-up as DUMPABLE has security implications. */
+       prctl (PR_SET_DUMPABLE, 1);
+
+       mono_runtime_printf_err ("\nNo native Android stacktrace (see debuggerd output).\n");
+#endif
 #endif
 
        /*
@@ -2533,16 +2585,17 @@ mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_T
                         "=================================================================\n",
                        signal);
 
-
 #ifdef MONO_ARCH_USE_SIGACTION
-
-       /* Remove our SIGABRT handler */
        sa.sa_handler = SIG_DFL;
        sigemptyset (&sa.sa_mask);
        sa.sa_flags = 0;
 
+       /* Remove our SIGABRT handler */
        g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
 
+       /* On some systems we get a SIGILL when calling abort (), because it might
+        * fail to raise SIGABRT */
+       g_assert (sigaction (SIGILL, &sa, NULL) != -1);
 #endif
 
        if (!mono_do_crash_chaining) {
@@ -2618,11 +2671,11 @@ mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
        mono_runtime_stdout_fflush ();
 }
 
-/*
+/**
  * mono_print_thread_dump:
  *
- *   Print information about the current thread to stdout.
- * SIGCTX can be NULL, allowing this to be called from gdb.
+ * Print information about the current thread to stdout.
+ * \p sigctx can be NULL, allowing this to be called from gdb.
  */
 void
 mono_print_thread_dump (void *sigctx)
@@ -2809,7 +2862,6 @@ mono_thread_state_init_from_sigctx (MonoThreadUnwindState *ctx, void *sigctx)
        MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
        if (!thread) {
                ctx->valid = FALSE;
-               g_error ("Invoked mono_thread_state_init_from_sigctx from non-Mono thread");
                return FALSE;
        }