2 * mini-exceptions.c: generic exception support
5 * Dietmar Maurer (dietmar@ximian.com)
7 * (C) 2001 Ximian, Inc.
15 #ifdef HAVE_EXECINFO_H
19 #ifndef PLATFORM_WIN32
20 #include <sys/types.h>
24 #include <mono/metadata/appdomain.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/threads-types.h>
28 #include <mono/metadata/debug-helpers.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/mono-debug.h>
32 #include <mono/metadata/profiler.h>
33 #include <mono/utils/mono-mmap.h>
41 #ifndef MONO_ARCH_CONTEXT_DEF
42 #define MONO_ARCH_CONTEXT_DEF
46 mono_exceptions_init (void)
48 #ifndef CUSTOM_EXCEPTION_HANDLING
49 mono_arch_get_restore_context ();
50 mono_arch_get_call_filter ();
51 mono_arch_get_throw_exception ();
52 mono_arch_get_rethrow_exception ();
56 #ifndef mono_find_jit_info
58 /* mono_find_jit_info:
60 * This function is used to gather information from @ctx. It return the
61 * MonoJitInfo of the corresponding function, unwinds one stack frame and
62 * stores the resulting context into @new_ctx. It also stores a string
63 * describing the stack location into @trace (if not NULL), and modifies
64 * the @lmf if necessary. @native_offset return the IP offset from the
65 * start of the function or -1 if that info is not available.
68 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
69 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
73 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
85 ji = mono_arch_find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, NULL, lmf, NULL, &managed2);
87 if (ji == (gpointer)-1)
90 if (managed2 || ji->method->wrapper_type) {
91 const char *real_ip, *start;
94 start = (const char *)ji->code_start;
96 /* ctx->ip points into native code */
97 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
99 real_ip = (const char*)ip;
101 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
102 offset = real_ip - start;
107 *native_offset = offset;
110 if (!ji->method->wrapper_type)
114 *trace = mono_debug_print_stack_frame (ji->method, offset, domain);
117 char *fname = mono_method_full_name (res->method, TRUE);
118 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
126 #endif /* mono_find_jit_info */
129 ves_icall_System_Exception_get_trace (MonoException *ex)
131 MonoDomain *domain = mono_domain_get ();
133 MonoArray *ta = ex->trace_ips;
138 /* Exception is not thrown yet */
141 len = mono_array_length (ta);
142 trace_str = g_string_new ("");
143 for (i = 0; i < len; i++) {
145 gpointer ip = mono_array_get (ta, gpointer, i);
147 ji = mono_jit_info_table_find (domain, ip);
149 /* Unmanaged frame */
150 g_string_append_printf (trace_str, "in (unmanaged) %p\n", ip);
155 address = (char *)ip - (char *)ji->code_start;
156 location = mono_debug_print_stack_frame (
157 ji->method, address, ex->object.vtable->domain);
159 g_string_append_printf (trace_str, "%s\n", location);
164 res = mono_string_new (ex->object.vtable->domain, trace_str->str);
165 g_string_free (trace_str, TRUE);
171 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
173 MonoDomain *domain = mono_domain_get ();
175 MonoArray *ta = exc->trace_ips;
176 MonoDebugSourceLocation *location;
180 /* Exception is not thrown yet */
181 return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
184 len = mono_array_length (ta);
186 res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
188 for (i = skip; i < len; i++) {
190 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
191 gpointer ip = mono_array_get (ta, gpointer, i);
193 ji = mono_jit_info_table_find (domain, ip);
195 /* Unmanaged frame */
196 mono_array_setref (res, i, sf);
200 g_assert (ji != NULL);
202 if (ji->method->wrapper_type) {
206 s = mono_method_full_name (ji->method, TRUE);
207 MONO_OBJECT_SETREF (sf, internal_method_name, mono_string_new (domain, s));
211 MONO_OBJECT_SETREF (sf, method, mono_method_get_object (domain, ji->method, NULL));
212 sf->native_offset = (char *)ip - (char *)ji->code_start;
215 * mono_debug_lookup_source_location() returns both the file / line number information
216 * and the IL offset. Note that computing the IL offset is already an expensive
217 * operation, so we shouldn't call this method twice.
219 location = mono_debug_lookup_source_location (ji->method, sf->native_offset, domain);
221 sf->il_offset = location->il_offset;
225 if (need_file_info) {
227 MONO_OBJECT_SETREF (sf, filename, mono_string_new (domain, location->source_file));
228 sf->line = location->row;
229 sf->column = location->column;
231 sf->line = sf->column = 0;
236 mono_debug_free_source_location (location);
237 mono_array_setref (res, i, sf);
245 * @domain: starting appdomain
246 * @jit_tls: JIT data for the thread
247 * @start_ctx: starting state of the stack frame
248 * @func: callback to call for each stack frame
249 * @user_data: data passed to the callback
251 * This function walks the stack of a thread, starting from the state
252 * represented by jit_tls and start_ctx. For each frame the callback
253 * function is called with the relevant info. The walk ends when no more
254 * managed stack frames are found or when the callback returns a TRUE value.
255 * Note that the function can be used to walk the stack of a thread
256 * different from the current.
259 mono_walk_stack (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start_ctx, MonoStackFrameWalk func, gpointer user_data)
261 MonoLMF *lmf = mono_get_lmf ();
262 MonoJitInfo *ji, rji;
265 MonoContext ctx, new_ctx;
269 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
271 * FIXME: mono_find_jit_info () will need to be able to return a different
272 * MonoDomain when apddomain transitions are found on the stack.
274 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
275 if (!ji || ji == (gpointer)-1)
278 if (func (domain, &new_ctx, ji, user_data))
285 #ifndef CUSTOM_STACK_WALK
288 mono_jit_walk_stack_from_ctx (MonoStackWalk func, MonoContext *start_ctx, gboolean do_il_offset, gpointer user_data)
290 MonoDomain *domain = mono_domain_get ();
291 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
292 MonoLMF *lmf = mono_get_lmf ();
293 MonoJitInfo *ji, rji;
294 gint native_offset, il_offset;
296 MonoContext ctx, new_ctx;
298 MONO_ARCH_CONTEXT_DEF
300 mono_arch_flush_register_windows ();
303 memcpy (&ctx, start_ctx, sizeof (MonoContext));
305 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
306 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
308 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_jit_walk_stack_from_ctx);
312 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
313 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
316 if (ji == (gpointer)-1)
320 MonoDebugSourceLocation *source;
322 source = mono_debug_lookup_source_location (ji->method, native_offset, domain);
323 il_offset = source ? source->il_offset : -1;
324 mono_debug_free_source_location (source);
328 if (func (ji->method, native_offset, il_offset, managed, user_data))
336 mono_jit_walk_stack (MonoStackWalk func, gboolean do_il_offset, gpointer user_data)
338 mono_jit_walk_stack_from_ctx (func, NULL, do_il_offset, user_data);
342 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
343 MonoReflectionMethod **method,
344 gint32 *iloffset, gint32 *native_offset,
345 MonoString **file, gint32 *line, gint32 *column)
347 MonoDomain *domain = mono_domain_get ();
348 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
349 MonoLMF *lmf = mono_get_lmf ();
350 MonoJitInfo *ji, rji;
351 MonoContext ctx, new_ctx;
352 MonoDebugSourceLocation *location;
353 MonoMethod *last_method = NULL;
355 MONO_ARCH_CONTEXT_DEF;
357 mono_arch_flush_register_windows ();
359 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
360 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
362 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
366 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
370 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_SP (&ctx) >= jit_tls->end_of_stack)
373 /* skip all wrappers ??*/
374 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
375 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
376 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
377 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
378 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE ||
379 ji->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
382 if (ji->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && ji->method == last_method) {
384 * FIXME: Native-to-managed wrappers sometimes show up twice.
385 * Probably the whole mono_find_jit_info () stuff needs to be fixed so this
391 last_method = ji->method;
397 *method = mono_method_get_object (domain, ji->method, NULL);
399 location = mono_debug_lookup_source_location (ji->method, *native_offset, domain);
401 *iloffset = location->il_offset;
405 if (need_file_info) {
407 *file = mono_string_new (domain, location->source_file);
408 *line = location->row;
409 *column = location->column;
416 mono_debug_free_source_location (location);
421 #endif /* CUSTOM_STACK_WALK */
425 MonoSecurityFrame *frame;
426 } MonoFrameSecurityInfo;
429 callback_get_first_frame_security_info (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
431 MonoFrameSecurityInfo *si = (MonoFrameSecurityInfo*) data;
433 /* FIXME: skip all wrappers ?? probably not - case by case testing is required */
434 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
435 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
436 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
437 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
438 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE) {
447 si->frame = mono_declsec_create_frame (domain, ji);
449 /* Stop - we only want the first frame (e.g. LinkDemand and InheritanceDemand) */
454 * ves_icall_System_Security_SecurityFrame_GetSecurityFrame:
455 * @skip: the number of stack frames to skip
457 * This function returns a the security informations of a single stack frame
458 * (after the skipped ones). This is required for [NonCas]LinkDemand[Choice]
459 * and [NonCas]InheritanceDemand[Choice] as only the caller security is
463 ves_icall_System_Security_SecurityFrame_GetSecurityFrame (gint32 skip)
465 MonoDomain *domain = mono_domain_get ();
466 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
467 MonoFrameSecurityInfo si;
470 MONO_ARCH_CONTEXT_DEF
472 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
473 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
475 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
478 #if defined(__ia64__) || defined(__s390__) || defined(__s390x__)
484 mono_walk_stack (domain, jit_tls, &ctx, callback_get_first_frame_security_info, (gpointer)&si);
486 return (si.skips == 0) ? si.frame : NULL;
498 grow_array (MonoSecurityStack *stack)
500 MonoDomain *domain = mono_domain_get ();
501 guint32 newsize = (stack->maximum << 1);
502 MonoArray *newstack = mono_array_new (domain, mono_defaults.runtimesecurityframe_class, newsize);
504 for (i=0; i < stack->maximum; i++) {
505 gpointer frame = mono_array_get (stack->stack, gpointer, i);
506 mono_array_setref (newstack, i, frame);
508 stack->maximum = newsize;
509 stack->stack = newstack;
513 callback_get_stack_frames_security_info (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
515 MonoSecurityStack *ss = (MonoSecurityStack*) data;
517 /* FIXME: skip all wrappers ?? probably not - case by case testing is required */
518 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
519 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
520 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
521 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
522 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE) {
531 if (ss->count == ss->maximum)
534 mono_array_setref (ss->stack, ss->count++, mono_declsec_create_frame (domain, ji));
536 /* continue down the stack */
541 glist_to_array (GList *list, MonoClass *eclass)
543 MonoDomain *domain = mono_domain_get ();
550 len = g_list_length (list);
551 res = mono_array_new (domain, eclass, len);
553 for (i = 0; list; list = list->next, i++)
554 mono_array_set (res, gpointer, i, list->data);
560 * ves_icall_System_Security_SecurityFrame_GetSecurityStack:
561 * @skip: the number of stack frames to skip
563 * This function returns an managed array of containing the security
564 * informations for each frame (after the skipped ones). This is used for
565 * [NonCas]Demand[Choice] where the complete evaluation of the stack is
569 ves_icall_System_Security_SecurityFrame_GetSecurityStack (gint32 skip)
571 MonoDomain *domain = mono_domain_get ();
572 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
573 MonoSecurityStack ss;
576 MONO_ARCH_CONTEXT_DEF
578 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
579 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
581 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityStack);
584 #if defined(__ia64__) || defined(__s390__) || defined(__s390x__)
590 ss.maximum = MONO_CAS_INITIAL_STACK_SIZE;
591 ss.stack = mono_array_new (domain, mono_defaults.runtimesecurityframe_class, ss.maximum);
592 mono_walk_stack (domain, jit_tls, &ctx, callback_get_stack_frames_security_info, (gpointer)&ss);
593 /* g_warning ("STACK RESULT: %d out of %d", ss.count, ss.maximum); */
597 #ifndef CUSTOM_EXCEPTION_HANDLING
600 get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
602 MonoClass *catch_class = ei->data.catch_class;
604 if (ji->has_generic_jit_info) {
605 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (ji);
608 MonoType *inflated_type;
611 info = mono_arch_context_get_int_reg (ctx, gi->this_reg);
613 info = *(gpointer*)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
616 if (ji->method->flags & METHOD_ATTRIBUTE_STATIC) {
617 MonoRuntimeGenericContext *rgctx = info;
619 class = rgctx->vtable->klass;
621 MonoObject *this = info;
623 class = this->vtable->klass;
626 /* FIXME: we shouldn't inflate but instead put the
627 type in the rgctx and fetch it from there. It
628 might be a good idea to do this lazily, i.e. only
629 when the exception is actually thrown, so as not to
630 waste space for exception clauses which might never
632 inflated_type = mono_class_inflate_generic_type (&catch_class->byval_arg,
633 mini_class_get_context (class));
634 catch_class = mono_class_from_mono_type (inflated_type);
635 g_free (inflated_type);
642 * mono_handle_exception_internal:
643 * @ctx: saved processor state
644 * @obj: the exception object
645 * @test_only: only test if the exception is caught, but dont call handlers
646 * @out_filter_idx: out parameter. if test_only is true, set to the index of
647 * the first filter clause which caught the exception.
650 mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only, gint32 *out_filter_idx)
652 MonoDomain *domain = mono_domain_get ();
653 MonoJitInfo *ji, rji;
654 static int (*call_filter) (MonoContext *, gpointer) = NULL;
655 static void (*restore_context) (void *);
656 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
657 MonoLMF *lmf = mono_get_lmf ();
658 MonoArray *initial_trace_ips = NULL;
659 GList *trace_ips = NULL;
660 MonoException *mono_ex;
661 gboolean stack_overflow = FALSE;
662 MonoContext initial_ctx;
664 gboolean has_dynamic_methods = FALSE;
665 gint32 filter_idx, first_filter_idx;
667 g_assert (ctx != NULL);
669 MonoException *ex = mono_get_exception_null_reference ();
670 MONO_OBJECT_SETREF (ex, message, mono_string_new (domain, "Object reference not set to an instance of an object"));
671 obj = (MonoObject *)ex;
675 * Allocate a new exception object instead of the preconstructed ones.
677 if (obj == domain->stack_overflow_ex) {
678 obj = mono_get_exception_stack_overflow ();
679 stack_overflow = TRUE;
681 else if (obj == domain->null_reference_ex) {
682 obj = mono_get_exception_null_reference ();
685 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
686 mono_ex = (MonoException*)obj;
687 initial_trace_ips = mono_ex->trace_ips;
692 if (mono_ex && jit_tls->class_cast_to && !strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
693 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
694 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
695 char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
696 mono_ex->message = mono_string_new (domain, msg);
703 call_filter = mono_arch_get_call_filter ();
705 if (!restore_context)
706 restore_context = mono_arch_get_restore_context ();
708 g_assert (jit_tls->end_of_stack);
709 g_assert (jit_tls->abort_func);
712 MonoContext ctx_cp = *ctx;
713 if (mono_trace_is_enabled ())
714 g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
715 mono_profiler_exception_thrown (obj);
716 if (!mono_handle_exception_internal (&ctx_cp, obj, original_ip, TRUE, &first_filter_idx)) {
717 if (mono_break_on_exc)
719 // FIXME: This runs managed code so it might cause another stack overflow when
720 // we are handling a stack overflow
721 mono_unhandled_exception (obj);
723 if (mono_debugger_unhandled_exception (original_ip, MONO_CONTEXT_GET_SP (ctx), obj)) {
725 * If this returns true, then we're running inside the
726 * Mono Debugger and the debugger wants us to restore the
727 * context and continue (normally, the debugger inserts
728 * a breakpoint on the `original_ip', so it regains control
729 * immediately after restoring the context).
731 MONO_CONTEXT_SET_IP (ctx, original_ip);
732 restore_context (ctx);
733 g_assert_not_reached ();
739 *out_filter_idx = -1;
742 memset (&rji, 0, sizeof (rji));
748 ji = mono_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx,
749 NULL, &lmf, NULL, NULL);
751 g_warning ("Exception inside function without unwind info");
752 g_assert_not_reached ();
755 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))))) {
757 * The exception was raised in native code and we got back to managed code
764 if (ji != (gpointer)-1) {
766 //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
768 if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
770 * Avoid overwriting the stack trace if the exception is
771 * rethrown. Also avoid giant stack traces during a stack
774 if (!initial_trace_ips && (frame_count < 1000)) {
775 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
779 if (ji->method->dynamic)
780 has_dynamic_methods = TRUE;
783 #ifndef MONO_ARCH_STACK_GROWS_UP
784 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
786 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
789 free_stack = 0xffffff;
792 * During stack overflow, wait till the unwinding frees some stack
793 * space before running handlers/finalizers.
795 if ((free_stack > (64 * 1024)) && ji->num_clauses) {
798 for (i = 0; i < ji->num_clauses; i++) {
799 MonoJitExceptionInfo *ei = &ji->clauses [i];
800 gboolean filtered = FALSE;
803 if (ei->try_start < MONO_CONTEXT_GET_IP (ctx) &&
805 if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) &&
807 MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) {
809 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
811 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
812 /* store the exception object in bp + ei->exvar_offset */
813 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = obj;
816 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
817 // mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
819 filtered = call_filter (ctx, ei->data.filter);
820 if (filtered && out_filter_idx)
821 *out_filter_idx = filter_idx;
825 * Filter clauses should only be run in the
826 * first pass of exception handling.
828 filtered = (filter_idx == first_filter_idx);
833 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
834 mono_object_isinst (obj, catch_class)) || filtered) {
836 if (mono_ex && !initial_trace_ips) {
837 trace_ips = g_list_reverse (trace_ips);
838 MONO_OBJECT_SETREF (mono_ex, trace_ips, glist_to_array (trace_ips, mono_defaults.int_class));
839 if (has_dynamic_methods)
840 /* These methods could go away anytime, so compute the stack trace now */
841 MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
843 g_list_free (trace_ips);
847 if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
848 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
849 mono_profiler_exception_clause_handler (ji->method, ei->flags, i);
850 mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
851 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
852 *(mono_get_lmf_addr ()) = lmf;
856 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) &&
857 MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
858 (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT)) {
859 if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
860 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
861 mono_profiler_exception_clause_handler (ji->method, ei->flags, i);
862 mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
863 call_filter (ctx, ei->handler_start);
865 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) &&
866 MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
867 (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
868 if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
869 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
870 mono_profiler_exception_clause_handler (ji->method, ei->flags, i);
871 mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
872 call_filter (ctx, ei->handler_start);
879 mono_profiler_exception_method_leave (ji->method);
884 if (ji == (gpointer)-1) {
887 *(mono_get_lmf_addr ()) = lmf;
889 jit_tls->abort_func (obj);
890 g_assert_not_reached ();
892 if (mono_ex && !initial_trace_ips) {
893 trace_ips = g_list_reverse (trace_ips);
894 MONO_OBJECT_SETREF (mono_ex, trace_ips, glist_to_array (trace_ips, mono_defaults.int_class));
895 if (has_dynamic_methods)
896 /* These methods could go away anytime, so compute the stack trace now */
897 MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
899 g_list_free (trace_ips);
905 g_assert_not_reached ();
909 * mono_debugger_run_finally:
910 * @start_ctx: saved processor state
912 * This method is called by the Mono Debugger to call all `finally' clauses of the
913 * current stack frame. It's used when the user issues a `return' command to make
914 * the current stack frame return. After returning from this method, the debugger
915 * unwinds the stack one frame and gives control back to the user.
917 * NOTE: This method is only used when running inside the Mono Debugger.
920 mono_debugger_run_finally (MonoContext *start_ctx)
922 static int (*call_filter) (MonoContext *, gpointer) = NULL;
923 MonoDomain *domain = mono_domain_get ();
924 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
925 MonoLMF *lmf = mono_get_lmf ();
926 MonoContext ctx, new_ctx;
927 MonoJitInfo *ji, rji;
932 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
933 if (!ji || ji == (gpointer)-1)
937 call_filter = mono_arch_get_call_filter ();
939 for (i = 0; i < ji->num_clauses; i++) {
940 MonoJitExceptionInfo *ei = &ji->clauses [i];
942 if ((ei->try_start <= MONO_CONTEXT_GET_IP (&ctx)) &&
943 (MONO_CONTEXT_GET_IP (&ctx) < ei->try_end) &&
944 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
945 call_filter (&ctx, ei->handler_start);
951 * mono_handle_exception:
952 * @ctx: saved processor state
953 * @obj: the exception object
954 * @test_only: only test if the exception is caught, but dont call handlers
957 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
959 return mono_handle_exception_internal (ctx, obj, original_ip, test_only, NULL);
962 #endif /* CUSTOM_EXCEPTION_HANDLING */
964 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
966 #ifndef MONO_ARCH_USE_SIGACTION
967 #error "Can't use sigaltstack without sigaction"
971 mono_setup_altstack (MonoJitTlsData *tls)
974 struct sigaltstack sa;
975 guint8 *staddr = NULL;
977 if (mono_running_on_valgrind ())
980 mono_thread_get_stack_bounds (&staddr, &stsize);
984 tls->end_of_stack = staddr + stsize;
986 /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
988 tls->stack_ovf_guard_base = staddr + mono_pagesize ();
989 tls->stack_ovf_guard_size = mono_pagesize () * 8;
991 if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
992 /* mprotect can fail for the main thread stack */
993 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);
994 g_assert (gaddr == tls->stack_ovf_guard_base);
998 * threads created by nptl does not seem to have a guard page, and
999 * since the main thread is not created by us, we can't even set one.
1000 * Increasing stsize fools the SIGSEGV signal handler into thinking this
1001 * is a stack overflow exception.
1003 tls->stack_size = stsize + mono_pagesize ();
1005 /* Setup an alternate signal stack */
1006 tls->signal_stack = mono_valloc (0, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC|MONO_MMAP_PRIVATE|MONO_MMAP_ANON);
1007 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
1009 g_assert (tls->signal_stack);
1011 sa.ss_sp = tls->signal_stack;
1012 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
1013 sa.ss_flags = SS_ONSTACK;
1014 sigaltstack (&sa, NULL);
1018 mono_free_altstack (MonoJitTlsData *tls)
1020 struct sigaltstack sa;
1023 sa.ss_sp = tls->signal_stack;
1024 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
1025 sa.ss_flags = SS_DISABLE;
1026 err = sigaltstack (&sa, NULL);
1027 g_assert (err == 0);
1029 if (tls->signal_stack)
1030 mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
1033 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
1036 mono_setup_altstack (MonoJitTlsData *tls)
1041 mono_free_altstack (MonoJitTlsData *tls)
1045 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
1048 print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
1050 FILE *stream = (FILE*)data;
1053 gchar *location = mono_debug_print_stack_frame (method, native_offset, mono_domain_get ());
1054 fprintf (stream, " %s\n", location);
1057 fprintf (stream, " at <unknown> <0x%05x>\n", native_offset);
1063 print_stack_frame_to_string (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed,
1066 GString *p = (GString*)data;
1069 gchar *location = mono_debug_print_stack_frame (method, native_offset, mono_domain_get ());
1070 g_string_append_printf (p, " %s\n", location);
1073 g_string_append_printf (p, " at <unknown> <0x%05x>\n", native_offset);
1078 static gboolean handling_sigsegv = FALSE;
1081 * mono_handle_native_sigsegv:
1083 * Handle a SIGSEGV received while in native code by printing diagnostic
1084 * information and aborting.
1087 mono_handle_native_sigsegv (int signal, void *ctx)
1089 #ifndef PLATFORM_WIN32
1090 struct sigaction sa;
1092 if (handling_sigsegv)
1095 /* To prevent infinite loops when the stack walk causes a crash */
1096 handling_sigsegv = TRUE;
1098 fprintf (stderr, "Stacktrace:\n\n");
1100 mono_jit_walk_stack (print_stack_frame, TRUE, stderr);
1104 #ifdef HAVE_BACKTRACE_SYMBOLS
1112 const char *signal_str = (signal == SIGSEGV) ? "SIGSEGV" : "SIGABRT";
1114 fprintf (stderr, "\nNative stacktrace:\n\n");
1116 size = backtrace (array, 256);
1117 names = backtrace_symbols (array, size);
1118 for (i =0; i < size; ++i) {
1119 fprintf (stderr, "\t%s\n", names [i]);
1125 /* Try to get more meaningful information using gdb */
1127 #ifndef PLATFORM_WIN32
1128 sprintf (cmd, "gdb --ex 'attach %ld' --ex 'info threads' --ex 'thread apply all bt' --batch", (long)getpid ());
1130 int res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1133 fprintf (stderr, "\nDebug info from gdb:\n\n");
1134 fprintf (stderr, "%s\n", out);
1139 * A SIGSEGV indicates something went very wrong so we can no longer depend
1140 * on anything working. So try to print out lots of diagnostics, starting
1141 * with ones which have a greater chance of working.
1145 "=================================================================\n"
1146 "Got a %s while executing native code. This usually indicates\n"
1147 "a fatal error in the mono runtime or one of the native libraries \n"
1148 "used by your application.\n"
1149 "=================================================================\n"
1155 #ifndef PLATFORM_WIN32
1157 /* Remove our SIGABRT handler */
1158 sa.sa_handler = SIG_DFL;
1159 sigemptyset (&sa.sa_mask);
1162 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
1170 * mono_print_thread_dump:
1172 * Print information about the current thread to stdout.
1175 mono_print_thread_dump (void *sigctx)
1177 MonoThread *thread = mono_thread_current ();
1178 #if defined(__i386__) || defined(__x86_64__)
1181 GString* text = g_string_new (0);
1183 GError *error = NULL;
1186 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
1188 g_string_append_printf (text, "\n\"%s\"", name);
1192 g_string_append (text, "\n\"\"");
1194 g_string_append_printf (text, " tid=0x%p this=0x%p:\n", (gpointer)(gsize)thread->tid, thread);
1197 #if defined(__i386__) || defined(__x86_64__)
1198 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
1200 mono_jit_walk_stack_from_ctx (print_stack_frame_to_string, &ctx, TRUE, text);
1202 printf ("\t<Stack traces in thread dumps not supported on this platform>\n");
1205 fprintf (stdout, text->str);
1206 g_string_free (text, TRUE);