2 * mini-exceptions.c: generic exception support
5 * Dietmar Maurer (dietmar@ximian.com)
7 * (C) 2001 Ximian, Inc.
15 #ifdef HAVE_EXECINFO_H
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/debug-helpers.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/gc-internal.h>
25 #include <mono/metadata/mono-debug.h>
30 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
35 /* FreeBSD and NetBSD need SA_STACK and MAP_ANON re-definitions */
36 # if defined(__FreeBSD__) || defined(__NetBSD__)
38 # define SA_STACK SA_ONSTACK
40 # ifndef MAP_ANONYMOUS
41 # define MAP_ANONYMOUS MAP_ANON
45 #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)))
47 #ifndef MONO_ARCH_CONTEXT_DEF
48 #define MONO_ARCH_CONTEXT_DEF
51 #ifndef mono_find_jit_info
53 /* mono_find_jit_info:
55 * This function is used to gather information from @ctx. It return the
56 * MonoJitInfo of the corresponding function, unwinds one stack frame and
57 * stores the resulting context into @new_ctx. It also stores a string
58 * describing the stack location into @trace (if not NULL), and modifies
59 * the @lmf if necessary. @native_offset return the IP offset from the
60 * start of the function or -1 if that info is not available.
63 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
64 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
68 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
80 ji = mono_arch_find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, NULL, lmf, NULL, &managed2);
82 if (ji == (gpointer)-1)
85 if (managed2 || ji->method->wrapper_type) {
86 const char *real_ip, *start;
89 start = (const char *)ji->code_start;
91 /* ctx->ip points into native code */
92 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
94 real_ip = (const char*)ip;
96 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
97 offset = real_ip - start;
102 *native_offset = offset;
105 if (!ji->method->wrapper_type)
109 *trace = mono_debug_print_stack_frame (ji->method, offset, domain);
112 char *fname = mono_method_full_name (res->method, TRUE);
113 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
121 #endif /* mono_find_jit_info */
124 ves_icall_System_Exception_get_trace (MonoException *ex)
126 MonoDomain *domain = mono_domain_get ();
128 MonoArray *ta = ex->trace_ips;
133 /* Exception is not thrown yet */
136 len = mono_array_length (ta);
137 trace_str = g_string_new ("");
138 for (i = 0; i < len; i++) {
140 gpointer ip = mono_array_get (ta, gpointer, i);
142 ji = mono_jit_info_table_find (domain, ip);
144 /* Unmanaged frame */
145 g_string_append_printf (trace_str, "in (unmanaged) %p\n", ip);
150 address = (char *)ip - (char *)ji->code_start;
151 location = mono_debug_print_stack_frame (
152 ji->method, address, ex->object.vtable->domain);
154 g_string_append_printf (trace_str, "%s\n", location);
159 res = mono_string_new (ex->object.vtable->domain, trace_str->str);
160 g_string_free (trace_str, TRUE);
166 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
168 MonoDomain *domain = mono_domain_get ();
170 MonoArray *ta = exc->trace_ips;
171 MonoDebugSourceLocation *location;
175 /* Exception is not thrown yet */
176 return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
179 len = mono_array_length (ta);
181 res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
183 for (i = skip; i < len; i++) {
185 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
186 gpointer ip = mono_array_get (ta, gpointer, i);
188 ji = mono_jit_info_table_find (domain, ip);
190 /* Unmanaged frame */
191 mono_array_setref (res, i, sf);
195 g_assert (ji != NULL);
197 if (ji->method->wrapper_type) {
201 s = mono_method_full_name (ji->method, TRUE);
202 MONO_OBJECT_SETREF (sf, internal_method_name, mono_string_new (domain, s));
206 MONO_OBJECT_SETREF (sf, method, mono_method_get_object (domain, ji->method, NULL));
207 sf->native_offset = (char *)ip - (char *)ji->code_start;
210 * mono_debug_lookup_source_location() returns both the file / line number information
211 * and the IL offset. Note that computing the IL offset is already an expensive
212 * operation, so we shouldn't call this method twice.
214 location = mono_debug_lookup_source_location (ji->method, sf->native_offset, domain);
216 sf->il_offset = location->il_offset;
220 if (need_file_info) {
222 MONO_OBJECT_SETREF (sf, filename, mono_string_new (domain, location->source_file));
223 sf->line = location->row;
224 sf->column = location->column;
226 sf->line = sf->column = 0;
231 mono_debug_free_source_location (location);
232 mono_array_setref (res, i, sf);
240 * @domain: starting appdomain
241 * @jit_tls: JIT data for the thread
242 * @start_ctx: starting state of the stack frame
243 * @func: callback to call for each stack frame
244 * @user_data: data passed to the callback
246 * This function walks the stack of a thread, starting from the state
247 * represented by jit_tls and start_ctx. For each frame the callback
248 * function is called with the relevant info. The walk ends when no more
249 * managed stack frames are found or when the callback returns a TRUE value.
250 * Note that the function can be used to walk the stack of a thread
251 * different from the current.
254 mono_walk_stack (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start_ctx, MonoStackFrameWalk func, gpointer user_data)
256 MonoLMF *lmf = jit_tls->lmf;
257 MonoJitInfo *ji, rji;
260 MonoContext ctx, new_ctx;
264 while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
266 * FIXME: mono_find_jit_info () will need to be able to return a different
267 * MonoDomain when apddomain transitions are found on the stack.
269 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
270 if (!ji || ji == (gpointer)-1)
273 if (func (domain, &new_ctx, ji, user_data))
280 #ifndef CUSTOM_STACK_WALK
283 mono_jit_walk_stack_from_ctx (MonoStackWalk func, MonoContext *start_ctx, gboolean do_il_offset, gpointer user_data)
285 MonoDomain *domain = mono_domain_get ();
286 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
287 MonoLMF *lmf = jit_tls->lmf;
288 MonoJitInfo *ji, rji;
289 gint native_offset, il_offset;
291 MonoContext ctx, new_ctx;
293 MONO_ARCH_CONTEXT_DEF
295 mono_arch_flush_register_windows ();
298 memcpy (&ctx, start_ctx, sizeof (MonoContext));
300 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
301 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
303 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_jit_walk_stack_from_ctx);
307 while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
308 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
311 if (ji == (gpointer)-1)
315 MonoDebugSourceLocation *source;
317 source = mono_debug_lookup_source_location (ji->method, native_offset, domain);
318 il_offset = source ? source->il_offset : -1;
319 mono_debug_free_source_location (source);
323 if (func (ji->method, native_offset, il_offset, managed, user_data))
331 mono_jit_walk_stack (MonoStackWalk func, gboolean do_il_offset, gpointer user_data)
333 mono_jit_walk_stack_from_ctx (func, NULL, do_il_offset, user_data);
337 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
338 MonoReflectionMethod **method,
339 gint32 *iloffset, gint32 *native_offset,
340 MonoString **file, gint32 *line, gint32 *column)
342 MonoDomain *domain = mono_domain_get ();
343 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
344 MonoLMF *lmf = jit_tls->lmf;
345 MonoJitInfo *ji, rji;
346 MonoContext ctx, new_ctx;
347 MonoDebugSourceLocation *location;
349 MONO_ARCH_CONTEXT_DEF;
351 mono_arch_flush_register_windows ();
353 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
354 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
356 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
360 * FIXME: This is needed because of the LMF stuff which doesn't exist on ia64.
361 * Probably the whole mono_find_jit_info () stuff needs to be fixed so this isn't
362 * needed even on other platforms. This is also true for s390/s390x.
364 #if !defined(__ia64__) && !defined(__s390__) && !defined(__s390x__)
369 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
373 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
376 /* skip all wrappers ??*/
377 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
378 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
379 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
380 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
381 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
388 *method = mono_method_get_object (domain, ji->method, NULL);
390 location = mono_debug_lookup_source_location (ji->method, *native_offset, domain);
392 *iloffset = location->il_offset;
396 if (need_file_info) {
398 *file = mono_string_new (domain, location->source_file);
399 *line = location->row;
400 *column = location->column;
407 mono_debug_free_source_location (location);
412 #endif /* CUSTOM_STACK_WALK */
416 MonoSecurityFrame *frame;
417 } MonoFrameSecurityInfo;
420 callback_get_first_frame_security_info (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
422 MonoFrameSecurityInfo *si = (MonoFrameSecurityInfo*) data;
424 /* FIXME: skip all wrappers ?? probably not - case by case testing is required */
425 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
426 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
427 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
428 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
429 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE) {
438 si->frame = mono_declsec_create_frame (domain, ji);
440 /* Stop - we only want the first frame (e.g. LinkDemand and InheritanceDemand) */
445 * ves_icall_System_Security_SecurityFrame_GetSecurityFrame:
446 * @skip: the number of stack frames to skip
448 * This function returns a the security informations of a single stack frame
449 * (after the skipped ones). This is required for [NonCas]LinkDemand[Choice]
450 * and [NonCas]InheritanceDemand[Choice] as only the caller security is
454 ves_icall_System_Security_SecurityFrame_GetSecurityFrame (gint32 skip)
456 MonoDomain *domain = mono_domain_get ();
457 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
458 MonoFrameSecurityInfo si;
461 MONO_ARCH_CONTEXT_DEF
463 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
464 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
466 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
471 mono_walk_stack (domain, jit_tls, &ctx, callback_get_first_frame_security_info, (gpointer)&si);
473 return (si.skips == 0) ? si.frame : NULL;
485 grow_array (MonoSecurityStack *stack)
487 MonoDomain *domain = mono_domain_get ();
488 guint32 newsize = (stack->maximum << 1);
489 MonoArray *newstack = mono_array_new (domain, mono_defaults.runtimesecurityframe_class, newsize);
491 for (i=0; i < stack->maximum; i++) {
492 gpointer frame = mono_array_get (stack->stack, gpointer, i);
493 mono_array_setref (newstack, i, frame);
495 stack->maximum = newsize;
496 stack->stack = newstack;
500 callback_get_stack_frames_security_info (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
502 MonoSecurityStack *ss = (MonoSecurityStack*) data;
504 /* FIXME: skip all wrappers ?? probably not - case by case testing is required */
505 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
506 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
507 ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
508 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
509 ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE) {
518 if (ss->count == ss->maximum)
521 mono_array_setref (ss->stack, ss->count++, mono_declsec_create_frame (domain, ji));
523 /* continue down the stack */
528 glist_to_array (GList *list, MonoClass *eclass)
530 MonoDomain *domain = mono_domain_get ();
537 len = g_list_length (list);
538 res = mono_array_new (domain, eclass, len);
540 for (i = 0; list; list = list->next, i++)
541 mono_array_set (res, gpointer, i, list->data);
547 * ves_icall_System_Security_SecurityFrame_GetSecurityStack:
548 * @skip: the number of stack frames to skip
550 * This function returns an managed array of containing the security
551 * informations for each frame (after the skipped ones). This is used for
552 * [NonCas]Demand[Choice] where the complete evaluation of the stack is
556 ves_icall_System_Security_SecurityFrame_GetSecurityStack (gint32 skip)
558 MonoDomain *domain = mono_domain_get ();
559 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
560 MonoSecurityStack ss;
563 MONO_ARCH_CONTEXT_DEF
565 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
566 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
568 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityStack);
573 ss.maximum = MONO_CAS_INITIAL_STACK_SIZE;
574 ss.stack = mono_array_new (domain, mono_defaults.runtimesecurityframe_class, ss.maximum);
575 mono_walk_stack (domain, jit_tls, &ctx, callback_get_stack_frames_security_info, (gpointer)&ss);
576 /* g_warning ("STACK RESULT: %d out of %d", ss.count, ss.maximum); */
580 #ifndef CUSTOM_EXCEPTION_HANDLING
583 * mono_handle_exception_internal:
584 * @ctx: saved processor state
585 * @obj: the exception object
586 * @test_only: only test if the exception is caught, but dont call handlers
587 * @out_filter_idx: out parameter. if test_only is true, set to the index of
588 * the first filter clause which caught the exception.
591 mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only, gint32 *out_filter_idx)
593 MonoDomain *domain = mono_domain_get ();
594 MonoJitInfo *ji, rji;
595 static int (*call_filter) (MonoContext *, gpointer) = NULL;
596 static void (*restore_context) (void *);
597 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
598 MonoLMF *lmf = jit_tls->lmf;
599 MonoArray *initial_trace_ips = NULL;
600 GList *trace_ips = NULL;
601 MonoException *mono_ex;
602 gboolean stack_overflow = FALSE;
603 MonoContext initial_ctx;
605 gboolean gc_disabled = FALSE;
606 gboolean has_dynamic_methods = FALSE;
607 gint32 filter_idx, first_filter_idx;
610 * This function might execute on an alternate signal stack, and Boehm GC
612 * Also, since the altstack is small, stack space intensive operations like
613 * JIT compilation should be avoided.
615 if (IS_ON_SIGALTSTACK (jit_tls)) {
617 * FIXME: disabling/enabling GC while already on a signal stack might
618 * not be safe either.
620 /* Have to reenable it later */
625 g_assert (ctx != NULL);
627 MonoException *ex = mono_get_exception_null_reference ();
628 MONO_OBJECT_SETREF (ex, message, mono_string_new (domain, "Object reference not set to an instance of an object"));
629 obj = (MonoObject *)ex;
633 * Allocate a new exception object instead of the preconstructed ones.
634 * We can't do this in sigsegv_signal_handler, since GC is not yet
637 if (obj == domain->stack_overflow_ex) {
638 obj = mono_get_exception_stack_overflow ();
639 stack_overflow = TRUE;
641 else if (obj == domain->null_reference_ex) {
642 obj = mono_get_exception_null_reference ();
645 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
646 mono_ex = (MonoException*)obj;
647 initial_trace_ips = mono_ex->trace_ips;
653 call_filter = mono_arch_get_call_filter ();
655 if (!restore_context)
656 restore_context = mono_arch_get_restore_context ();
658 g_assert (jit_tls->end_of_stack);
659 g_assert (jit_tls->abort_func);
662 MonoContext ctx_cp = *ctx;
663 if (mono_trace_is_enabled ())
664 g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
665 if (!mono_handle_exception_internal (&ctx_cp, obj, original_ip, TRUE, &first_filter_idx)) {
666 if (mono_break_on_exc)
668 mono_unhandled_exception (obj);
670 if (mono_debugger_unhandled_exception (original_ip, MONO_CONTEXT_GET_SP (ctx), obj)) {
672 * If this returns true, then we're running inside the
673 * Mono Debugger and the debugger wants us to restore the
674 * context and continue (normally, the debugger inserts
675 * a breakpoint on the `original_ip', so it regains control
676 * immediately after restoring the context).
678 MONO_CONTEXT_SET_IP (ctx, original_ip);
679 restore_context (ctx);
680 g_assert_not_reached ();
686 *out_filter_idx = -1;
689 memset (&rji, 0, sizeof (rji));
695 ji = mono_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx,
696 NULL, &lmf, NULL, NULL);
698 g_warning ("Exception inside function without unwind info");
699 g_assert_not_reached ();
702 if (ji != (gpointer)-1) {
704 //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
706 if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
708 * Avoid overwriting the stack trace if the exception is
709 * rethrown. Also avoid giant stack traces during a stack
712 if (!initial_trace_ips && (frame_count < 1000)) {
713 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
717 if (ji->method->dynamic)
718 has_dynamic_methods = TRUE;
721 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
723 free_stack = 0xffffff;
726 * During stack overflow, wait till the unwinding frees some stack
727 * space before running handlers/finalizers.
729 if ((free_stack > (64 * 1024)) && ji->num_clauses) {
732 for (i = 0; i < ji->num_clauses; i++) {
733 MonoJitExceptionInfo *ei = &ji->clauses [i];
734 gboolean filtered = FALSE;
737 if (ei->try_start < MONO_CONTEXT_GET_IP (ctx) &&
739 if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) &&
741 MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) {
744 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
745 /* store the exception object in cfg->excvar */
746 g_assert (ei->exvar_offset);
747 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = obj;
750 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
751 // mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
753 filtered = call_filter (ctx, ei->data.filter);
754 if (filtered && out_filter_idx)
755 *out_filter_idx = filter_idx;
759 * Filter clauses should only be run in the
760 * first pass of exception handling.
762 filtered = (filter_idx == first_filter_idx);
767 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
768 mono_object_isinst (obj, ei->data.catch_class)) || filtered) {
770 if (mono_ex && !initial_trace_ips) {
771 trace_ips = g_list_reverse (trace_ips);
772 MONO_OBJECT_SETREF (mono_ex, trace_ips, glist_to_array (trace_ips, mono_defaults.int_class));
773 if (has_dynamic_methods)
774 /* These methods could go away anytime, so compute the stack trace now */
775 MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
777 g_list_free (trace_ips);
783 if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
784 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
785 mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
786 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
793 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) &&
794 MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
795 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
796 if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
797 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
798 mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
799 call_filter (ctx, ei->handler_start);
809 if (ji == (gpointer)-1) {
816 if (IS_ON_SIGALTSTACK (jit_tls)) {
817 /* Switch back to normal stack */
818 if (stack_overflow) {
819 /* Free up some stack space */
820 MONO_CONTEXT_SET_SP (&initial_ctx, (gssize)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
821 g_assert ((gssize)MONO_CONTEXT_GET_SP (&initial_ctx) < (gssize)jit_tls->end_of_stack);
823 #ifdef MONO_CONTEXT_SET_FUNC
824 /* jit_tls->abort_func is a function descriptor on ia64 */
825 MONO_CONTEXT_SET_FUNC (&initial_ctx, (gssize)jit_tls->abort_func);
827 MONO_CONTEXT_SET_IP (&initial_ctx, (gssize)jit_tls->abort_func);
829 restore_context (&initial_ctx);
832 jit_tls->abort_func (obj);
833 g_assert_not_reached ();
835 if (mono_ex && !initial_trace_ips) {
836 trace_ips = g_list_reverse (trace_ips);
837 MONO_OBJECT_SETREF (mono_ex, trace_ips, glist_to_array (trace_ips, mono_defaults.int_class));
838 if (has_dynamic_methods)
839 /* These methods could go away anytime, so compute the stack trace now */
840 MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
842 g_list_free (trace_ips);
848 g_assert_not_reached ();
852 * mono_debugger_run_finally:
853 * @start_ctx: saved processor state
855 * This method is called by the Mono Debugger to call all `finally' clauses of the
856 * current stack frame. It's used when the user issues a `return' command to make
857 * the current stack frame return. After returning from this method, the debugger
858 * unwinds the stack one frame and gives control back to the user.
860 * NOTE: This method is only used when running inside the Mono Debugger.
863 mono_debugger_run_finally (MonoContext *start_ctx)
865 static int (*call_filter) (MonoContext *, gpointer) = NULL;
866 MonoDomain *domain = mono_domain_get ();
867 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
868 MonoLMF *lmf = jit_tls->lmf;
869 MonoContext ctx, new_ctx;
870 MonoJitInfo *ji, rji;
875 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
876 if (!ji || ji == (gpointer)-1)
880 call_filter = mono_arch_get_call_filter ();
882 for (i = 0; i < ji->num_clauses; i++) {
883 MonoJitExceptionInfo *ei = &ji->clauses [i];
885 if ((ei->try_start <= MONO_CONTEXT_GET_IP (&ctx)) &&
886 (MONO_CONTEXT_GET_IP (&ctx) < ei->try_end) &&
887 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
888 call_filter (&ctx, ei->handler_start);
894 * mono_handle_exception:
895 * @ctx: saved processor state
896 * @obj: the exception object
897 * @test_only: only test if the exception is caught, but dont call handlers
900 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
902 return mono_handle_exception_internal (ctx, obj, original_ip, test_only, NULL);
905 #endif /* CUSTOM_EXCEPTION_HANDLING */
907 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
910 mono_setup_altstack (MonoJitTlsData *tls)
912 pthread_t self = pthread_self();
915 struct sigaltstack sa;
916 guint8 *staddr = NULL;
917 guint8 *current = (guint8*)&staddr;
919 if (mono_running_on_valgrind ())
922 /* Determine stack boundaries */
923 pthread_attr_init( &attr );
924 #ifdef HAVE_PTHREAD_GETATTR_NP
925 pthread_getattr_np( self, &attr );
927 #ifdef HAVE_PTHREAD_ATTR_GET_NP
928 pthread_attr_get_np( self, &attr );
930 pthread_attr_getstacksize( &attr, &stsize );
932 #error "Not implemented"
937 pthread_attr_getstack( &attr, (void**)&staddr, &stsize );
940 pthread_attr_destroy (&attr);
944 g_assert ((current > staddr) && (current < staddr + stsize));
946 tls->end_of_stack = staddr + stsize;
949 * threads created by nptl does not seem to have a guard page, and
950 * since the main thread is not created by us, we can't even set one.
951 * Increasing stsize fools the SIGSEGV signal handler into thinking this
952 * is a stack overflow exception.
954 tls->stack_size = stsize + getpagesize ();
956 /* Setup an alternate signal stack */
957 tls->signal_stack = mmap (0, MONO_ARCH_SIGNAL_STACK_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
958 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
960 g_assert (tls->signal_stack);
962 sa.ss_sp = tls->signal_stack;
963 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
964 sa.ss_flags = SS_ONSTACK;
965 sigaltstack (&sa, NULL);
969 mono_free_altstack (MonoJitTlsData *tls)
971 struct sigaltstack sa;
974 sa.ss_sp = tls->signal_stack;
975 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
976 sa.ss_flags = SS_DISABLE;
977 err = sigaltstack (&sa, NULL);
980 if (tls->signal_stack)
981 munmap (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
984 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
987 print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
989 FILE *stream = (FILE*)data;
992 gchar *location = mono_debug_print_stack_frame (method, native_offset, mono_domain_get ());
993 fprintf (stream, " %s\n", location);
996 fprintf (stream, " at <unknown> <0x%05x>\n", native_offset);
1001 static gboolean handling_sigsegv = FALSE;
1004 * mono_handle_native_sigsegv:
1006 * Handle a SIGSEGV received while in native code by printing diagnostic
1007 * information and aborting.
1010 mono_handle_native_sigsegv (int signal, void *ctx)
1012 #ifndef PLATFORM_WIN32
1013 struct sigaction sa;
1015 const char *signal_str = (signal == SIGSEGV) ? "SIGSEGV" : "SIGABRT";
1017 if (handling_sigsegv)
1020 /* To prevent infinite loops when the stack walk causes a crash */
1021 handling_sigsegv = TRUE;
1024 * A SIGSEGV indicates something went very wrong so we can no longer depend
1025 * on anything working. So try to print out lots of diagnostics, starting
1026 * with ones which have a greater chance of working.
1030 "=================================================================\n"
1031 "Got a %s while executing native code. This usually indicates\n"
1032 "a fatal error in the mono runtime or one of the native libraries \n"
1033 "used by your application.\n"
1034 "=================================================================\n"
1037 fprintf (stderr, "Stacktrace:\n\n");
1039 mono_jit_walk_stack (print_stack_frame, TRUE, stderr);
1043 #ifdef HAVE_BACKTRACE_SYMBOLS
1052 fprintf (stderr, "\nNative stacktrace:\n\n");
1054 size = backtrace (array, 256);
1055 names = backtrace_symbols (array, size);
1056 for (i =0; i < size; ++i) {
1057 fprintf (stderr, "\t%s\n", names [i]);
1063 /* Try to get more meaningful information using gdb */
1065 #ifndef PLATFORM_WIN32
1066 sprintf (cmd, "gdb --ex 'attach %ld' --ex 'info threads' --ex 'thread apply all bt' --batch", (long)getpid ());
1068 int res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1071 fprintf (stderr, "\nDebug info from gdb:\n\n");
1072 fprintf (stderr, "%s\n", out);
1079 #ifndef PLATFORM_WIN32
1081 /* Remove our SIGABRT handler */
1082 sa.sa_handler = SIG_DFL;
1083 sigemptyset (&sa.sa_mask);
1086 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
1094 * mono_print_thread_dump:
1096 * Print information about the current thread to stdout.
1099 mono_print_thread_dump (void *sigctx)
1101 MonoThread *thread = mono_thread_current ();
1106 GError *error = NULL;
1109 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
1111 fprintf (stdout, "\n\"%s\"", name);
1115 fprintf (stdout, "\n\"\"");
1117 fprintf (stdout, " tid=0x%p this=0x%p:\n", (gpointer)(gsize)thread->tid, thread);
1121 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
1123 mono_jit_walk_stack_from_ctx (print_stack_frame, &ctx, TRUE, stdout);
1125 printf ("\t<Stack traces in thread dumps not supported on this platform>\n");