2 * mini-exceptions.c: generic exception support
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Mono Team (mono-list@lists.ximian.com)
8 * Copyright 2001-2003 Ximian, Inc.
9 * Copyright 2003-2008 Novell, Inc.
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
22 #ifdef HAVE_EXECINFO_H
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
30 #ifdef HAVE_SYS_WAIT_H
38 #ifdef HAVE_SYS_SYSCALL_H
39 #include <sys/syscall.h>
42 #ifdef HAVE_SYS_PRCTL_H
43 #include <sys/prctl.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/tabledefs.h>
52 #include <mono/metadata/threads.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/metadata/debug-helpers.h>
55 #include <mono/metadata/exception.h>
56 #include <mono/metadata/exception-internals.h>
57 #include <mono/metadata/object-internals.h>
58 #include <mono/metadata/reflection-internals.h>
59 #include <mono/metadata/gc-internals.h>
60 #include <mono/metadata/mono-debug.h>
61 #include <mono/metadata/profiler.h>
62 #include <mono/metadata/mono-endian.h>
63 #include <mono/metadata/environment.h>
64 #include <mono/metadata/mono-mlist.h>
65 #include <mono/utils/mono-mmap.h>
66 #include <mono/utils/mono-logger-internals.h>
67 #include <mono/utils/mono-error.h>
68 #include <mono/utils/mono-error-internals.h>
72 #include "debugger-agent.h"
73 #include "seq-points.h"
74 #include "llvm-runtime.h"
75 #include "mini-llvm.h"
78 #include "mini-llvm-cpp.h"
81 #ifndef MONO_ARCH_CONTEXT_DEF
82 #define MONO_ARCH_CONTEXT_DEF
85 #ifndef MONO_ARCH_STACK_GROWS_UP
86 #define MONO_ARCH_STACK_GROWS_UP 0
89 static gpointer restore_context_func, call_filter_func;
90 static gpointer throw_exception_func, rethrow_exception_func;
91 static gpointer throw_corlib_exception_func;
93 static gpointer try_more_restore_tramp = NULL;
94 static gpointer restore_stack_protection_tramp = NULL;
96 static void try_more_restore (void);
97 static void restore_stack_protection (void);
98 static void mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data);
99 static void mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx);
100 static void mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data);
101 static gboolean mono_current_thread_has_handle_block_guard (void);
104 first_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer addr)
106 gpointer **data = (gpointer **)addr;
111 *data = MONO_CONTEXT_GET_SP(ctx);
117 mono_thread_get_managed_sp (void)
119 gpointer addr = NULL;
120 mono_walk_stack (first_managed, MONO_UNWIND_SIGNAL_SAFE, &addr);
125 mini_abort_threshold_offset (gpointer threshold, gpointer sp)
127 intptr_t stack_threshold = (intptr_t) threshold;
128 intptr_t stack_pointer = (intptr_t) sp;
130 const int direction = MONO_ARCH_STACK_GROWS_UP ? -1 : 1;
131 intptr_t magnitude = stack_pointer - stack_threshold;
133 return direction * magnitude;
137 mini_clear_abort_threshold (void)
139 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
140 jit_tls->abort_exc_stack_threshold = NULL;
144 mini_set_abort_threshold (MonoContext *ctx)
146 gpointer sp = MONO_CONTEXT_GET_SP (ctx);
147 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
148 // Only move it up, to avoid thrown/caught
149 // exceptions lower in the stack from triggering
151 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
152 if (!jit_tls->abort_exc_stack_threshold || above_threshold) {
153 jit_tls->abort_exc_stack_threshold = sp;
157 // Note: In the case that the frame is above where the thread abort
158 // was set we bump the threshold so that functions called from the new,
159 // higher threshold don't trigger the thread abort exception
160 static inline gboolean
161 mini_above_abort_threshold (void)
163 gpointer sp = mono_thread_get_managed_sp ();
164 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
166 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
169 jit_tls->abort_exc_stack_threshold = sp;
171 return above_threshold;
175 mono_exceptions_init (void)
177 MonoRuntimeExceptionHandlingCallbacks cbs;
179 restore_context_func = mono_aot_get_trampoline ("restore_context");
180 call_filter_func = mono_aot_get_trampoline ("call_filter");
181 throw_exception_func = mono_aot_get_trampoline ("throw_exception");
182 rethrow_exception_func = mono_aot_get_trampoline ("rethrow_exception");
186 restore_context_func = mono_arch_get_restore_context (&info, FALSE);
187 mono_tramp_info_register (info, NULL);
188 call_filter_func = mono_arch_get_call_filter (&info, FALSE);
189 mono_tramp_info_register (info, NULL);
190 throw_exception_func = mono_arch_get_throw_exception (&info, FALSE);
191 mono_tramp_info_register (info, NULL);
192 rethrow_exception_func = mono_arch_get_rethrow_exception (&info, FALSE);
193 mono_tramp_info_register (info, NULL);
195 #ifdef MONO_ARCH_HAVE_RESTORE_STACK_SUPPORT
196 if (!mono_llvm_only) {
197 try_more_restore_tramp = mono_create_specific_trampoline (try_more_restore, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
198 restore_stack_protection_tramp = mono_create_specific_trampoline (restore_stack_protection, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
202 #ifdef MONO_ARCH_HAVE_EXCEPTIONS_INIT
203 mono_arch_exceptions_init ();
205 cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
206 cbs.mono_walk_stack_with_state = mono_walk_stack_with_state;
209 cbs.mono_raise_exception = mono_llvm_raise_exception;
211 cbs.mono_raise_exception = (void (*)(MonoException *))mono_get_throw_exception ();
212 cbs.mono_raise_exception_with_ctx = mono_raise_exception_with_ctx;
213 cbs.mono_exception_walk_trace = mono_exception_walk_trace;
214 cbs.mono_install_handler_block_guard = mono_install_handler_block_guard;
215 cbs.mono_current_thread_has_handle_block_guard = mono_current_thread_has_handle_block_guard;
216 cbs.mono_clear_abort_threshold = mini_clear_abort_threshold;
217 cbs.mono_above_abort_threshold = mini_above_abort_threshold;
218 mono_install_eh_callbacks (&cbs);
222 mono_get_throw_exception (void)
224 g_assert (throw_exception_func);
225 return throw_exception_func;
229 mono_get_rethrow_exception (void)
231 g_assert (rethrow_exception_func);
232 return rethrow_exception_func;
236 mono_get_call_filter (void)
238 g_assert (call_filter_func);
239 return call_filter_func;
243 mono_get_restore_context (void)
245 g_assert (restore_context_func);
246 return restore_context_func;
250 mono_get_throw_corlib_exception (void)
252 gpointer code = NULL;
255 /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
256 if (throw_corlib_exception_func)
257 return throw_corlib_exception_func;
260 code = mono_aot_get_trampoline ("throw_corlib_exception");
262 code = mono_arch_get_throw_corlib_exception (&info, FALSE);
263 mono_tramp_info_register (info, NULL);
266 mono_memory_barrier ();
268 throw_corlib_exception_func = code;
270 return throw_corlib_exception_func;
274 * mono_get_throw_exception_addr:
276 * Return an address which stores the result of
277 * mono_get_throw_exception.
280 mono_get_throw_exception_addr (void)
282 return &throw_exception_func;
286 is_address_protected (MonoJitInfo *ji, MonoJitExceptionInfo *ei, gpointer ip)
288 MonoTryBlockHoleTableJitInfo *table;
293 if (ei->try_start > ip || ip >= ei->try_end)
296 if (!ji->has_try_block_holes)
299 table = mono_jit_info_get_try_block_hole_table_info (ji);
300 offset = (guint32)((char*)ip - (char*)ji->code_start);
301 clause = (guint16)(ei - ji->clauses);
302 g_assert (clause < ji->num_clauses);
304 for (i = 0; i < table->num_holes; ++i) {
305 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
306 if (hole->clause == clause && hole->offset <= offset && hole->offset + hole->length > offset)
312 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
315 static gboolean show_native_addresses = TRUE;
317 static gboolean show_native_addresses = FALSE;
320 static _Unwind_Reason_Code
321 build_stack_trace (struct _Unwind_Context *frame_ctx, void *state)
323 MonoDomain *domain = mono_domain_get ();
324 uintptr_t ip = _Unwind_GetIP (frame_ctx);
326 if (show_native_addresses || mono_jit_info_table_find (domain, (char*)ip)) {
327 GList **trace_ips = (GList **)state;
328 *trace_ips = g_list_prepend (*trace_ips, (gpointer)ip);
331 return _URC_NO_REASON;
335 get_unwind_backtrace (void)
339 _Unwind_Backtrace (build_stack_trace, &ips);
341 return g_slist_reverse (ips);
347 get_unwind_backtrace (void)
357 * Translate between the mono_arch_unwind_frame function and the old API.
360 find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
361 MonoContext *new_ctx, MonoLMF **lmf, gboolean *managed)
363 StackFrameInfo frame;
366 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
368 /* Avoid costly table lookup during stack overflow */
369 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
372 ji = mini_jit_info_table_find (domain, (char *)ip, NULL);
377 err = mono_arch_unwind_frame (domain, jit_tls, ji, ctx, new_ctx, lmf, NULL, &frame);
379 return (MonoJitInfo *)-1;
381 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
383 * Remove any unused lmf.
384 * Mask out the lower bits which might be used to hold additional information.
386 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
389 /* Convert between the new and the old APIs */
390 switch (frame.type) {
391 case FRAME_TYPE_MANAGED:
395 case FRAME_TYPE_TRAMPOLINE:
397 case FRAME_TYPE_MANAGED_TO_NATIVE:
401 memset (res, 0, sizeof (MonoJitInfo));
402 res->d.method = frame.method;
405 case FRAME_TYPE_DEBUGGER_INVOKE: {
409 * The normal exception handling code can't handle this frame, so just
412 ji = find_jit_info (domain, jit_tls, res, NULL, new_ctx, &tmp_ctx, lmf, managed);
413 memcpy (new_ctx, &tmp_ctx, sizeof (MonoContext));
417 g_assert_not_reached ();
422 /* mono_find_jit_info:
424 * This function is used to gather information from @ctx. It return the
425 * MonoJitInfo of the corresponding function, unwinds one stack frame and
426 * stores the resulting context into @new_ctx. It also stores a string
427 * describing the stack location into @trace (if not NULL), and modifies
428 * the @lmf if necessary. @native_offset return the IP offset from the
429 * start of the function or -1 if that info is not available.
432 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
433 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
437 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
439 MonoMethod *method = NULL;
450 ji = find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, lmf, &managed2);
452 if (ji == (gpointer)-1)
455 if (ji && !ji->is_trampoline)
456 method = jinfo_get_method (ji);
458 if (managed2 || (method && method->wrapper_type)) {
459 const char *real_ip, *start;
462 start = (const char *)ji->code_start;
464 /* ctx->ip points into native code */
465 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
467 real_ip = (const char*)ip;
469 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
470 offset = real_ip - start;
475 *native_offset = offset;
478 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
482 *trace = mono_debug_print_stack_frame (method, offset, domain);
485 char *fname = mono_method_full_name (jinfo_get_method (res), TRUE);
486 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
495 * mono_find_jit_info_ext:
497 * A version of mono_find_jit_info which returns all data in the StackFrameInfo
499 * A note about frames of type FRAME_TYPE_MANAGED_TO_NATIVE:
500 * - These frames are used to mark managed-to-native transitions, so CTX will refer to native
501 * code, and new_ctx will refer to the last managed frame. The caller should unwind once more
502 * to obtain the last managed frame.
503 * If SAVE_LOCATIONS is not NULL, it should point to an array of size MONO_MAX_IREGS.
504 * On return, it will be filled with the locations where callee saved registers are saved
505 * by the current frame. This is returned outside of StackFrameInfo because it can be
506 * quite large on some platforms.
507 * If ASYNC true, this function will be async safe, but some fields of frame and frame->ji will
511 mono_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls,
512 MonoJitInfo *prev_ji, MonoContext *ctx,
513 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
514 mgreg_t **save_locations,
515 StackFrameInfo *frame)
518 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
520 MonoDomain *target_domain = domain;
521 MonoMethod *method = NULL;
522 gboolean async = mono_thread_info_is_async_context ();
527 /* Avoid costly table lookup during stack overflow */
528 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
531 ji = mini_jit_info_table_find (domain, (char *)ip, &target_domain);
534 target_domain = domain;
537 memset (save_locations, 0, MONO_MAX_IREGS * sizeof (mgreg_t*));
539 err = mono_arch_unwind_frame (target_domain, jit_tls, ji, ctx, new_ctx, lmf, save_locations, frame);
543 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
545 * Remove any unused lmf.
546 * Mask out the lower bits which might be used to hold additional information.
548 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
551 if (frame->ji && !frame->ji->is_trampoline && !frame->ji->async)
552 method = jinfo_get_method (frame->ji);
554 if (frame->type == FRAME_TYPE_MANAGED && method) {
555 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
556 frame->managed = TRUE;
559 if (frame->type == FRAME_TYPE_MANAGED_TO_NATIVE) {
561 * This type of frame is just a marker, the caller should unwind once more to get the
562 * last managed frame.
565 frame->method = NULL;
568 frame->native_offset = -1;
569 frame->domain = target_domain;
570 frame->async_context = async;
574 if (frame->type == FRAME_TYPE_MANAGED)
575 frame->method = method;
577 if (ji && (frame->managed || (method && method->wrapper_type))) {
578 const char *real_ip, *start;
580 start = (const char *)ji->code_start;
581 if (frame->type == FRAME_TYPE_MANAGED)
582 real_ip = (const char*)ip;
584 /* ctx->ip points into native code */
585 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
587 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
588 frame->native_offset = real_ip - start;
590 frame->native_offset = -1;
594 *trace = mono_debug_print_stack_frame (method, frame->native_offset, domain);
596 if (trace && frame->method) {
597 char *fname = mono_method_full_name (frame->method, TRUE);
598 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
607 * This function is async-safe.
610 get_generic_info_from_stack_frame (MonoJitInfo *ji, MonoContext *ctx)
612 MonoGenericJitInfo *gi;
616 if (!ji->has_generic_jit_info)
618 gi = mono_jit_info_get_generic_jit_info (ji);
624 * Search location list if available, it contains the precise location of the
625 * argument for every pc offset, even if the method was interrupted while it was in
629 int offset = (mgreg_t)MONO_CONTEXT_GET_IP (ctx) - (mgreg_t)ji->code_start;
632 for (i = 0; i < gi->nlocs; ++i) {
633 MonoDwarfLocListEntry *entry = &gi->locations [i];
635 if (offset >= entry->from && (offset < entry->to || entry->to == 0)) {
637 info = (gpointer)mono_arch_context_get_int_reg (ctx, entry->reg);
639 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, entry->reg) + entry->offset);
643 g_assert (i < gi->nlocs);
646 info = (gpointer)mono_arch_context_get_int_reg (ctx, gi->this_reg);
648 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
652 method = jinfo_get_method (ji);
653 if (mono_method_get_context (method)->method_inst) {
654 /* A MonoMethodRuntimeGenericContext* */
656 } else if ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype) {
660 /* Avoid returning a managed object */
661 MonoObject *this_obj = (MonoObject *)info;
663 return this_obj->vtable;
668 * generic_info is either a MonoMethodRuntimeGenericContext or a MonoVTable.
670 static MonoGenericContext
671 get_generic_context_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
673 MonoGenericContext context = { NULL, NULL };
674 MonoClass *klass, *method_container_class;
677 g_assert (generic_info);
679 method = jinfo_get_method (ji);
680 g_assert (method->is_inflated);
681 if (mono_method_get_context (method)->method_inst) {
682 MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext *)generic_info;
684 klass = mrgctx->class_vtable->klass;
685 context.method_inst = mrgctx->method_inst;
686 g_assert (context.method_inst);
688 MonoVTable *vtable = (MonoVTable *)generic_info;
690 klass = vtable->klass;
693 //g_assert (!mono_class_is_gtd (method->klass));
694 if (mono_class_is_ginst (method->klass))
695 method_container_class = mono_class_get_generic_class (method->klass)->container_class;
697 method_container_class = method->klass;
699 /* class might refer to a subclass of method's class */
700 while (!(klass == method->klass || (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->container_class == method_container_class))) {
701 klass = klass->parent;
705 if (mono_class_is_ginst (klass) || mono_class_is_gtd (klass))
706 context.class_inst = mini_class_get_context (klass)->class_inst;
708 if (mono_class_is_ginst (klass))
709 g_assert (mono_class_has_parent_and_ignore_generics (mono_class_get_generic_class (klass)->container_class, method_container_class));
711 g_assert (mono_class_has_parent_and_ignore_generics (klass, method_container_class));
717 get_method_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
720 MonoGenericContext context;
723 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
724 return jinfo_get_method (ji);
725 context = get_generic_context_from_stack_frame (ji, generic_info);
727 method = jinfo_get_method (ji);
728 method = mono_method_get_declaring_generic_method (method);
729 method = mono_class_inflate_generic_method_checked (method, &context, &error);
730 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
736 * mono_exception_walk_native_trace:
737 * @ex: The exception object whose frames should be walked
738 * @func: callback to call for each stack frame
739 * @user_data: data passed to the callback
741 * This function walks the stacktrace of an exception. For
742 * each frame the callback function is called with the relevant info.
743 * The walk ends when no more stack frames are found or when the callback
744 * returns a TRUE value.
748 mono_exception_walk_trace (MonoException *ex, MonoExceptionFrameWalk func, gpointer user_data)
750 MONO_REQ_GC_UNSAFE_MODE;
752 MonoDomain *domain = mono_domain_get ();
753 MonoArray *ta = ex->trace_ips;
759 len = mono_array_length (ta) >> 1;
760 for (i = 0; i < len; i++) {
761 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
762 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
763 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)ip);
766 if (func (NULL, ip, 0, FALSE, user_data))
769 MonoMethod *method = get_method_from_stack_frame (ji, generic_info);
770 if (func (method, ji->code_start, (char *) ip - (char *) ji->code_start, TRUE, user_data))
779 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
782 MonoDomain *domain = mono_domain_get ();
784 MonoArray *ta = exc->trace_ips;
785 MonoDebugSourceLocation *location;
789 /* Exception is not thrown yet */
790 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, 0, &error);
791 mono_error_set_pending_exception (&error);
795 len = mono_array_length (ta) >> 1;
797 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0, &error);
798 if (mono_error_set_pending_exception (&error))
801 for (i = skip; i < len; i++) {
803 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, &error);
804 if (!mono_error_ok (&error)) {
805 mono_error_set_pending_exception (&error);
808 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
809 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
812 ji = mono_jit_info_table_find (domain, (char *)ip);
814 /* Unmanaged frame */
815 mono_array_setref (res, i, sf);
819 g_assert (ji != NULL);
822 /* Can't resolve actual method */
823 method = jinfo_get_method (ji);
825 method = get_method_from_stack_frame (ji, generic_info);
826 if (jinfo_get_method (ji)->wrapper_type) {
830 s = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION);
831 MONO_OBJECT_SETREF (sf, internal_method_name, mono_string_new (domain, s));
835 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, &error);
836 if (!mono_error_ok (&error)) {
837 mono_error_set_pending_exception (&error);
840 MONO_OBJECT_SETREF (sf, method, rm);
843 sf->method_index = ji->from_aot ? mono_aot_find_method_index (method) : 0xffffff;
844 sf->method_address = (gsize) ji->code_start;
845 sf->native_offset = (char *)ip - (char *)ji->code_start;
848 * mono_debug_lookup_source_location() returns both the file / line number information
849 * and the IL offset. Note that computing the IL offset is already an expensive
850 * operation, so we shouldn't call this method twice.
852 location = mono_debug_lookup_source_location (jinfo_get_method (ji), sf->native_offset, domain);
854 sf->il_offset = location->il_offset;
857 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (ji), sf->native_offset, NULL, &sp))
858 sf->il_offset = sp.il_offset;
863 if (need_file_info) {
864 if (location && location->source_file) {
865 MONO_OBJECT_SETREF (sf, filename, mono_string_new (domain, location->source_file));
866 sf->line = location->row;
867 sf->column = location->column;
869 sf->line = sf->column = 0;
874 mono_debug_free_source_location (location);
875 mono_array_setref (res, i, sf);
882 mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
885 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
886 if (jit_tls && jit_tls->orig_ex_ctx_set)
887 start_ctx = &jit_tls->orig_ex_ctx;
889 mono_walk_stack_with_ctx (func, start_ctx, unwind_options, user_data);
892 * mono_walk_stack_with_ctx:
894 * Unwind the current thread starting at @start_ctx.
896 * If @start_ctx is null, we capture the current context.
899 mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
901 MonoContext extra_ctx;
902 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
903 MONO_ARCH_CONTEXT_DEF
905 if (!thread || !thread->jit_data)
909 mono_arch_flush_register_windows ();
911 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
912 MONO_INIT_CONTEXT_FROM_CURRENT (&extra_ctx);
914 MONO_INIT_CONTEXT_FROM_FUNC (&extra_ctx, mono_walk_stack_with_ctx);
916 start_ctx = &extra_ctx;
919 mono_walk_stack_full (func, start_ctx, mono_domain_get (), (MonoJitTlsData *)thread->jit_data, mono_get_lmf (), unwind_options, user_data);
923 * mono_walk_stack_with_state:
925 * Unwind a thread described by @state.
927 * State must be valid (state->valid == TRUE).
929 * If you are using this function to unwind another thread, make sure it is suspended.
931 * If @state is null, we capture the current context.
934 mono_walk_stack_with_state (MonoJitStackWalk func, MonoThreadUnwindState *state, MonoUnwindOptions unwind_options, void *user_data)
936 MonoThreadUnwindState extra_state;
938 g_assert (!mono_thread_info_is_async_context ());
939 if (!mono_thread_state_init_from_current (&extra_state))
941 state = &extra_state;
944 g_assert (state->valid);
946 if (!state->unwind_data [MONO_UNWIND_DATA_DOMAIN])
950 mono_walk_stack_full (func,
952 (MonoDomain *)state->unwind_data [MONO_UNWIND_DATA_DOMAIN],
953 (MonoJitTlsData *)state->unwind_data [MONO_UNWIND_DATA_JIT_TLS],
954 (MonoLMF *)state->unwind_data [MONO_UNWIND_DATA_LMF],
955 unwind_options, user_data);
959 mono_walk_stack (MonoJitStackWalk func, MonoUnwindOptions options, void *user_data)
961 MonoThreadUnwindState state;
962 if (!mono_thread_state_init_from_current (&state))
964 mono_walk_stack_with_state (func, &state, options, user_data);
968 * mono_walk_stack_full:
969 * @func: callback to call for each stack frame
970 * @domain: starting appdomain, can be NULL to use the current domain
971 * @unwind_options: what extra information the unwinder should gather
972 * @start_ctx: starting state of the stack walk, can be NULL.
973 * @thread: the thread whose stack to walk, can be NULL to use the current thread
974 * @lmf: the LMF of @thread, can be NULL to use the LMF of the current thread
975 * @user_data: data passed to the callback
977 * This function walks the stack of a thread, starting from the state
978 * represented by start_ctx. For each frame the callback
979 * function is called with the relevant info. The walk ends when no more
980 * managed stack frames are found or when the callback returns a TRUE value.
983 mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data)
986 MonoContext ctx, new_ctx;
987 StackFrameInfo frame;
989 mgreg_t *reg_locations [MONO_MAX_IREGS];
990 mgreg_t *new_reg_locations [MONO_MAX_IREGS];
991 gboolean get_reg_locations = unwind_options & MONO_UNWIND_REG_LOCATIONS;
992 gboolean async = mono_thread_info_is_async_context ();
994 if (mono_llvm_only) {
1000 ips = get_unwind_backtrace ();
1001 for (l = ips; l; l = l->next) {
1002 guint8 *ip = (guint8*)l->data;
1003 memset (&frame, 0, sizeof (StackFrameInfo));
1004 frame.ji = mini_jit_info_table_find (domain, (char*)ip, &frame.domain);
1005 if (!frame.ji || frame.ji->is_trampoline)
1007 frame.type = FRAME_TYPE_MANAGED;
1008 frame.method = jinfo_get_method (frame.ji);
1009 // FIXME: Cannot lookup the actual method
1010 frame.actual_method = frame.method;
1011 if (frame.type == FRAME_TYPE_MANAGED) {
1012 if (!frame.method->wrapper_type || frame.method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
1013 frame.managed = TRUE;
1015 frame.native_offset = ip - (guint8*)frame.ji->code_start;
1016 frame.il_offset = -1;
1018 if (func (&frame, NULL, user_data))
1025 g_assert (start_ctx);
1028 /*The LMF will be null if the target have no managed frames.*/
1029 /* g_assert (lmf); */
1032 g_assert (unwind_options == MONO_UNWIND_NONE);
1034 memcpy (&ctx, start_ctx, sizeof (MonoContext));
1035 memset (reg_locations, 0, sizeof (reg_locations));
1037 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
1039 res = mono_find_jit_info_ext (domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, get_reg_locations ? new_reg_locations : NULL, &frame);
1043 if ((unwind_options & MONO_UNWIND_LOOKUP_IL_OFFSET) && frame.ji && !frame.ji->is_trampoline) {
1044 MonoDebugSourceLocation *source;
1046 source = mono_debug_lookup_source_location (jinfo_get_method (frame.ji), frame.native_offset, domain);
1048 il_offset = source->il_offset;
1051 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (frame.ji), frame.native_offset, NULL, &sp))
1052 il_offset = sp.il_offset;
1056 mono_debug_free_source_location (source);
1060 frame.il_offset = il_offset;
1062 if ((unwind_options & MONO_UNWIND_LOOKUP_ACTUAL_METHOD) && frame.ji && !frame.ji->is_trampoline) {
1063 frame.actual_method = get_method_from_stack_frame (frame.ji, get_generic_info_from_stack_frame (frame.ji, &ctx));
1065 frame.actual_method = frame.method;
1068 if (get_reg_locations)
1069 frame.reg_locations = reg_locations;
1071 if (func (&frame, &ctx, user_data))
1074 if (get_reg_locations) {
1075 for (i = 0; i < MONO_MAX_IREGS; ++i)
1076 if (new_reg_locations [i])
1077 reg_locations [i] = new_reg_locations [i];
1085 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
1086 MonoReflectionMethod **method,
1087 gint32 *iloffset, gint32 *native_offset,
1088 MonoString **file, gint32 *line, gint32 *column)
1091 MonoDomain *domain = mono_domain_get ();
1092 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
1093 MonoLMF *lmf = mono_get_lmf ();
1094 MonoJitInfo *ji = NULL;
1095 MonoContext ctx, new_ctx;
1096 MonoDebugSourceLocation *location;
1097 MonoMethod *jmethod = NULL, *actual_method;
1098 StackFrameInfo frame;
1101 MONO_ARCH_CONTEXT_DEF;
1103 if (mono_llvm_only) {
1105 MonoDomain *frame_domain;
1106 guint8 *frame_ip = NULL;
1108 /* FIXME: Generalize this code with an interface which returns an array of StackFrame structures */
1110 ips = get_unwind_backtrace ();
1111 for (l = ips; l && skip >= 0; l = l->next) {
1112 guint8 *ip = (guint8*)l->data;
1116 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &frame_domain);
1117 if (!ji || ji->is_trampoline)
1120 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1121 jmethod = jinfo_get_method (ji);
1122 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1129 /* No way to resolve generic instances */
1130 actual_method = jmethod;
1131 *native_offset = frame_ip - (guint8*)ji->code_start;
1133 mono_arch_flush_register_windows ();
1135 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1136 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
1138 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
1144 res = mono_find_jit_info_ext (domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1148 if (frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1149 frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1150 frame.type == FRAME_TYPE_TRAMPOLINE)
1154 *native_offset = frame.native_offset;
1156 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1157 jmethod = jinfo_get_method (ji);
1158 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1161 } while (skip >= 0);
1163 actual_method = get_method_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, &ctx));
1166 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, actual_method, NULL, &error);
1167 if (!mono_error_ok (&error)) {
1168 mono_error_set_pending_exception (&error);
1171 mono_gc_wbarrier_generic_store (method, (MonoObject*) rm);
1173 location = mono_debug_lookup_source_location (jmethod, *native_offset, domain);
1175 *iloffset = location->il_offset;
1179 if (need_file_info) {
1181 mono_gc_wbarrier_generic_store (file, (MonoObject*) mono_string_new (domain, location->source_file));
1182 *line = location->row;
1183 *column = location->column;
1186 *line = *column = 0;
1190 mono_debug_free_source_location (location);
1196 get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
1199 MonoClass *catch_class = ei->data.catch_class;
1200 MonoType *inflated_type;
1201 MonoGenericContext context;
1203 /*MonoJitExceptionInfo::data is an union used by filter and finally clauses too.*/
1204 if (!catch_class || ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
1207 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
1209 context = get_generic_context_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, ctx));
1211 /* FIXME: we shouldn't inflate but instead put the
1212 type in the rgctx and fetch it from there. It
1213 might be a good idea to do this lazily, i.e. only
1214 when the exception is actually thrown, so as not to
1215 waste space for exception clauses which might never
1217 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
1218 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
1220 catch_class = mono_class_from_mono_type (inflated_type);
1221 mono_metadata_free_type (inflated_type);
1227 * mini_jit_info_table_find_ext:
1229 * Same as mono_jit_info_table_find, but search all the domains of the current thread
1230 * if ADDR is not found in DOMAIN. The domain where the method was found is stored into
1231 * OUT_DOMAIN if it is not NULL.
1234 mini_jit_info_table_find_ext (MonoDomain *domain, char *addr, gboolean allow_trampolines, MonoDomain **out_domain)
1237 MonoInternalThread *t = mono_thread_internal_current ();
1243 ji = mono_jit_info_table_find_internal (domain, addr, TRUE, allow_trampolines);
1246 *out_domain = domain;
1250 /* maybe it is shared code, so we also search in the root domain */
1251 if (domain != mono_get_root_domain ()) {
1252 ji = mono_jit_info_table_find_internal (mono_get_root_domain (), addr, TRUE, allow_trampolines);
1255 *out_domain = mono_get_root_domain ();
1263 refs = (gpointer *)((t->appdomain_refs) ? *(gpointer *) t->appdomain_refs : NULL);
1264 for (; refs && *refs; refs++) {
1265 if (*refs != domain && *refs != mono_get_root_domain ()) {
1266 ji = mono_jit_info_table_find_internal ((MonoDomain*) *refs, addr, TRUE, allow_trampolines);
1269 *out_domain = (MonoDomain*) *refs;
1279 mini_jit_info_table_find (MonoDomain *domain, char *addr, MonoDomain **out_domain)
1281 return mini_jit_info_table_find_ext (domain, addr, FALSE, out_domain);
1284 /* Class lazy loading functions */
1285 static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, System.Runtime.CompilerServices, RuntimeCompatibilityAttribute)
1288 * wrap_non_exception_throws:
1290 * Determine whenever M's assembly has a RuntimeCompatibilityAttribute with the
1291 * WrapNonExceptionThrows flag set.
1294 wrap_non_exception_throws (MonoMethod *m)
1297 MonoAssembly *ass = m->klass->image->assembly;
1298 MonoCustomAttrInfo* attrs;
1301 gboolean val = FALSE;
1304 if (ass->wrap_non_exception_throws_inited)
1305 return ass->wrap_non_exception_throws;
1307 klass = mono_class_get_runtime_compat_attr_class ();
1309 attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
1310 mono_error_cleanup (&error); /* FIXME don't swallow the error */
1312 for (i = 0; i < attrs->num_attrs; ++i) {
1313 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1315 int num_named, named_type, name_len;
1318 if (!attr->ctor || attr->ctor->klass != klass)
1320 /* Decode the RuntimeCompatibilityAttribute. See reflection.c */
1321 p = (const char*)attr->data;
1322 g_assert (read16 (p) == 0x0001);
1324 num_named = read16 (p);
1330 /* data_type = *p; */
1333 if (named_type != 0x54)
1335 name_len = mono_metadata_decode_blob_size (p, &p);
1336 name = (char *)g_malloc (name_len + 1);
1337 memcpy (name, p, name_len);
1338 name [name_len] = 0;
1340 g_assert (!strcmp (name, "WrapNonExceptionThrows"));
1342 /* The value is a BOOLEAN */
1345 mono_custom_attrs_free (attrs);
1348 ass->wrap_non_exception_throws = val;
1349 mono_memory_barrier ();
1350 ass->wrap_non_exception_throws_inited = TRUE;
1355 #define MAX_UNMANAGED_BACKTRACE 128
1357 build_native_trace (MonoError *error)
1359 mono_error_init (error);
1360 /* This puppy only makes sense on mobile, IOW, ARM. */
1361 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
1363 void *native_trace [MAX_UNMANAGED_BACKTRACE];
1366 size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
1372 res = mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, size, error);
1373 return_val_if_nok (error, NULL);
1375 for (i = 0; i < size; i++)
1376 mono_array_set (res, gpointer, i, native_trace [i]);
1384 setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, MonoArray *initial_trace_ips, GList **trace_ips)
1386 if (mono_ex && !initial_trace_ips) {
1387 *trace_ips = g_list_reverse (*trace_ips);
1389 MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
1390 mono_error_assert_ok (&error);
1391 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
1392 MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace (&error));
1393 mono_error_assert_ok (&error);
1394 if (dynamic_methods) {
1395 /* These methods could go away anytime, so save a reference to them in the exception object */
1397 MonoMList *list = NULL;
1399 for (l = dynamic_methods; l; l = l->next) {
1401 MonoDomain *domain = mono_domain_get ();
1403 if (domain->method_to_dyn_method) {
1404 mono_domain_lock (domain);
1405 dis_link = (guint32)(size_t)g_hash_table_lookup (domain->method_to_dyn_method, l->data);
1406 mono_domain_unlock (domain);
1408 MonoObject *o = mono_gchandle_get_target (dis_link);
1410 list = mono_mlist_prepend_checked (list, o, &error);
1411 mono_error_assert_ok (&error);
1417 MONO_OBJECT_SETREF (mono_ex, dynamic_methods, list);
1420 g_list_free (*trace_ips);
1425 * mono_handle_exception_internal_first_pass:
1427 * The first pass of exception handling. Unwind the stack until a catch clause which can catch
1428 * OBJ is found. Run the index of the filter clause which caught the exception into
1429 * OUT_FILTER_IDX. Return TRUE if the exception is caught, FALSE otherwise.
1432 mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filter_idx, MonoJitInfo **out_ji, MonoJitInfo **out_prev_ji, MonoObject *non_exception)
1435 MonoDomain *domain = mono_domain_get ();
1436 MonoJitInfo *ji = NULL;
1437 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1438 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
1439 MonoLMF *lmf = mono_get_lmf ();
1440 MonoArray *initial_trace_ips = NULL;
1441 GList *trace_ips = NULL;
1442 GSList *dynamic_methods = NULL;
1443 MonoException *mono_ex;
1444 gboolean stack_overflow = FALSE;
1445 MonoContext initial_ctx;
1447 int frame_count = 0;
1452 g_assert (ctx != NULL);
1454 if (obj == (MonoObject *)domain->stack_overflow_ex)
1455 stack_overflow = TRUE;
1457 mono_ex = (MonoException*)obj;
1458 initial_trace_ips = mono_ex->trace_ips;
1460 if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1461 mono_ex = (MonoException*)obj;
1462 initial_trace_ips = mono_ex->trace_ips;
1464 mono_error_assert_ok (&error);
1469 call_filter = (int (*) (MonoContext *, void *))mono_get_call_filter ();
1471 g_assert (jit_tls->end_of_stack);
1472 g_assert (jit_tls->abort_func);
1475 *out_filter_idx = -1;
1479 *out_prev_ji = NULL;
1484 MonoContext new_ctx;
1486 int clause_index_start = 0;
1487 gboolean unwind_res = TRUE;
1489 StackFrameInfo frame;
1494 unwind_res = mono_find_jit_info_ext (domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1496 if (frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1497 frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1498 frame.type == FRAME_TYPE_TRAMPOLINE) {
1502 g_assert (frame.type == FRAME_TYPE_MANAGED);
1507 setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
1508 g_slist_free (dynamic_methods);
1513 method = jinfo_get_method (ji);
1514 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1516 if (mini_get_debug_options ()->reverse_pinvoke_exceptions && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
1517 g_error ("A native frame was found while unwinding the stack after an exception.\n"
1518 "The native frame called the managed method:\n%s\n",
1519 mono_method_full_name (method, TRUE));
1522 if (method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
1524 * Avoid overwriting the stack trace if the exception is
1525 * rethrown. Also avoid giant stack traces during a stack
1528 if (!initial_trace_ips && (frame_count < 1000)) {
1529 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1530 trace_ips = g_list_prepend (trace_ips,
1531 get_generic_info_from_stack_frame (ji, ctx));
1535 if (method->dynamic)
1536 dynamic_methods = g_slist_prepend (dynamic_methods, method);
1538 if (stack_overflow) {
1539 if (MONO_ARCH_STACK_GROWS_UP)
1540 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1542 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1544 free_stack = 0xffffff;
1547 for (i = clause_index_start; i < ji->num_clauses; i++) {
1548 MonoJitExceptionInfo *ei = &ji->clauses [i];
1549 gboolean filtered = FALSE;
1552 * During stack overflow, wait till the unwinding frees some stack
1553 * space before running handlers/finalizers.
1555 if (free_stack <= (64 * 1024))
1558 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
1560 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1563 * Have to unwrap RuntimeWrappedExceptions if the
1564 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1566 if (non_exception && !wrap_non_exception_throws (method))
1567 ex_obj = non_exception;
1571 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1572 gboolean is_user_frame = method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD;
1573 #ifndef DISABLE_PERFCOUNTERS
1574 mono_perfcounters->exceptions_filters++;
1577 Here's the thing, if this is a filter clause done by a wrapper like runtime invoke, we don't want to
1578 trim the stackframe since if it returns FALSE we lose information.
1580 FIXME Not 100% sure if it's a good idea even with user clauses.
1583 setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
1585 #ifndef MONO_CROSS_COMPILE
1586 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1588 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1590 /* Can't pass the ex object in a register yet to filter clauses, because call_filter () might not support it */
1591 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1593 g_assert (!ji->from_llvm);
1594 /* store the exception object in bp + ei->exvar_offset */
1595 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1599 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1601 * Pass the original il clause index to the landing pad so it can
1602 * branch to the landing pad associated with the il clause.
1603 * This is needed because llvm compiled code assumes that the EH
1604 * code always branches to the innermost landing pad.
1607 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1610 mono_debugger_agent_begin_exception_filter (mono_ex, ctx, &initial_ctx);
1611 filtered = call_filter (ctx, ei->data.filter);
1612 mono_debugger_agent_end_exception_filter (mono_ex, ctx, &initial_ctx);
1613 if (filtered && out_filter_idx)
1614 *out_filter_idx = filter_idx;
1621 setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
1622 g_slist_free (dynamic_methods);
1623 /* mono_debugger_agent_handle_exception () needs this */
1624 mini_set_abort_threshold (ctx);
1625 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1630 MonoError isinst_error;
1631 mono_error_init (&isinst_error);
1632 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (ex_obj, catch_class, &error)) {
1633 setup_stack_trace (mono_ex, dynamic_methods, initial_trace_ips, &trace_ips);
1634 g_slist_free (dynamic_methods);
1639 /* mono_debugger_agent_handle_exception () needs this */
1640 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1643 mono_error_cleanup (&isinst_error);
1650 g_assert_not_reached ();
1654 * mono_handle_exception_internal:
1655 * @ctx: saved processor state
1656 * @obj: the exception object
1657 * @resume: whenever to resume unwinding based on the state in MonoJitTlsData.
1660 mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resume, MonoJitInfo **out_ji)
1663 MonoDomain *domain = mono_domain_get ();
1664 MonoJitInfo *ji, *prev_ji;
1665 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1666 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
1667 MonoLMF *lmf = mono_get_lmf ();
1668 MonoException *mono_ex;
1669 gboolean stack_overflow = FALSE;
1670 MonoContext initial_ctx;
1672 int frame_count = 0;
1673 gint32 filter_idx, first_filter_idx = 0;
1676 MonoObject *non_exception = NULL;
1678 g_assert (ctx != NULL);
1680 MonoException *ex = mono_get_exception_null_reference ();
1681 MONO_OBJECT_SETREF (ex, message, mono_string_new (domain, "Object reference not set to an instance of an object"));
1682 obj = (MonoObject *)ex;
1686 * Allocate a new exception object instead of the preconstructed ones.
1688 if (obj == (MonoObject *)domain->stack_overflow_ex) {
1690 * It is not a good idea to try and put even more pressure on the little stack available.
1691 * obj = mono_get_exception_stack_overflow ();
1693 stack_overflow = TRUE;
1695 else if (obj == (MonoObject *)domain->null_reference_ex) {
1696 obj = (MonoObject *)mono_get_exception_null_reference ();
1699 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1700 mono_error_assert_ok (&error);
1701 non_exception = obj;
1702 obj = (MonoObject *)mono_get_exception_runtime_wrapped_checked (obj, &error);
1703 mono_error_assert_ok (&error);
1706 mono_ex = (MonoException*)obj;
1708 if (mini_get_debug_options ()->suspend_on_exception) {
1709 mono_runtime_printf_err ("Exception thrown, suspending...");
1714 if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1715 mono_ex = (MonoException*)obj;
1717 mono_error_assert_ok (&error);
1721 if (mono_ex && jit_tls->class_cast_from) {
1722 if (!strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
1723 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1724 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1725 char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
1726 mono_ex->message = mono_string_new (domain, msg);
1731 if (!strcmp (mono_ex->object.vtable->klass->name, "ArrayTypeMismatchException")) {
1732 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1733 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1734 char *msg = g_strdup_printf ("Source array of type '%s' cannot be cast to destination array type '%s'.", from_name, to_name);
1735 mono_ex->message = mono_string_new (domain, msg);
1743 call_filter = (int (*)(MonoContext *, void*))mono_get_call_filter ();
1745 g_assert (jit_tls->end_of_stack);
1746 g_assert (jit_tls->abort_func);
1749 * We set orig_ex_ctx_set to TRUE/FALSE around profiler calls to make sure it doesn't
1750 * end up being TRUE on any code path.
1752 memcpy (&jit_tls->orig_ex_ctx, ctx, sizeof (MonoContext));
1757 MonoContext ctx_cp = *ctx;
1758 if (mono_trace_is_enabled ()) {
1759 MonoMethod *system_exception_get_message = mono_class_get_method_from_name (mono_defaults.exception_class, "get_Message", 0);
1760 MonoMethod *get_message = system_exception_get_message == NULL ? NULL : mono_object_get_virtual_method (obj, system_exception_get_message);
1761 MonoObject *message;
1762 const char *type_name = mono_class_get_name (mono_object_class (mono_ex));
1764 if (get_message == NULL) {
1766 } else if (!strcmp (type_name, "OutOfMemoryException") || !strcmp (type_name, "StackOverflowException")) {
1768 msg = g_strdup_printf ("(No exception message for: %s)\n", type_name);
1770 MonoObject *exc = NULL;
1771 message = mono_runtime_try_invoke (get_message, obj, NULL, &exc, &error);
1772 g_assert (exc == NULL);
1773 mono_error_assert_ok (&error);
1777 msg = mono_string_to_utf8_checked ((MonoString *) message, &error);
1778 if (!is_ok (&error)) {
1779 mono_error_cleanup (&error);
1780 msg = g_strdup ("(error while display System.Exception.Message property)");
1783 msg = g_strdup ("(System.Exception.Message property not available)");
1786 g_print ("[%p:] EXCEPTION handling: %s.%s: %s\n", (void*)mono_native_thread_id_get (), mono_object_class (obj)->name_space, mono_object_class (obj)->name, msg);
1788 if (mono_ex && mono_trace_eval_exception (mono_object_class (mono_ex)))
1789 mono_print_thread_dump_from_ctx (ctx);
1791 jit_tls->orig_ex_ctx_set = TRUE;
1792 mono_profiler_exception_thrown (obj);
1793 jit_tls->orig_ex_ctx_set = FALSE;
1795 res = mono_handle_exception_internal_first_pass (&ctx_cp, obj, &first_filter_idx, &ji, &prev_ji, non_exception);
1798 if (mini_get_debug_options ()->break_on_exc)
1800 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1802 if (mini_get_debug_options ()->suspend_on_unhandled) {
1803 mono_runtime_printf_err ("Unhandled exception, suspending...");
1808 // FIXME: This runs managed code so it might cause another stack overflow when
1809 // we are handling a stack overflow
1810 mini_set_abort_threshold (ctx);
1811 mono_unhandled_exception (obj);
1813 gboolean unhandled = FALSE;
1816 * The exceptions caught by the mono_runtime_invoke_checked () calls
1817 * in the threadpool needs to be treated as unhandled (#669836).
1819 * FIXME: The check below is hackish, but its hard to distinguish
1820 * these runtime invoke calls from others in the runtime.
1822 if (ji && jinfo_get_method (ji)->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1823 if (prev_ji && jinfo_get_method (prev_ji) == mono_defaults.threadpool_perform_wait_callback_method)
1828 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1830 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, &ctx_cp);
1840 MonoContext new_ctx;
1842 int clause_index_start = 0;
1843 gboolean unwind_res = TRUE;
1847 ji = jit_tls->resume_state.ji;
1848 new_ctx = jit_tls->resume_state.new_ctx;
1849 clause_index_start = jit_tls->resume_state.clause_index;
1850 lmf = jit_tls->resume_state.lmf;
1851 first_filter_idx = jit_tls->resume_state.first_filter_idx;
1852 filter_idx = jit_tls->resume_state.filter_idx;
1854 StackFrameInfo frame;
1856 unwind_res = mono_find_jit_info_ext (domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1858 if (frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1859 frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1860 frame.type == FRAME_TYPE_TRAMPOLINE) {
1864 g_assert (frame.type == FRAME_TYPE_MANAGED);
1870 *(mono_get_lmf_addr ()) = lmf;
1872 jit_tls->abort_func (obj);
1873 g_assert_not_reached ();
1876 method = jinfo_get_method (ji);
1878 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1880 if (stack_overflow) {
1881 if (MONO_ARCH_STACK_GROWS_UP)
1882 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1884 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1886 free_stack = 0xffffff;
1889 for (i = clause_index_start; i < ji->num_clauses; i++) {
1890 MonoJitExceptionInfo *ei = &ji->clauses [i];
1891 gboolean filtered = FALSE;
1894 * During stack overflow, wait till the unwinding frees some stack
1895 * space before running handlers/finalizers.
1897 if (free_stack <= (64 * 1024))
1900 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
1902 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1905 * Have to unwrap RuntimeWrappedExceptions if the
1906 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1908 if (non_exception && !wrap_non_exception_throws (method))
1909 ex_obj = non_exception;
1913 if (((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER))) {
1914 #ifndef MONO_CROSS_COMPILE
1915 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1916 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1918 g_assert (!ji->from_llvm);
1919 /* store the exception object in bp + ei->exvar_offset */
1920 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1925 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1927 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1930 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1932 * Filter clauses should only be run in the
1933 * first pass of exception handling.
1935 filtered = (filter_idx == first_filter_idx);
1939 mono_error_init (&error);
1940 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
1941 mono_object_isinst_checked (ex_obj, catch_class, &error)) || filtered) {
1943 * This guards against the situation that we abort a thread that is executing a finally clause
1944 * that was called by the EH machinery. It won't have a guard trampoline installed, so we must
1945 * check for this situation here and resume interruption if we are below the guarded block.
1947 if (G_UNLIKELY (jit_tls->handler_block_return_address)) {
1948 gboolean is_outside = FALSE;
1949 gpointer prot_bp = MONO_CONTEXT_GET_BP (&jit_tls->handler_block_context);
1950 gpointer catch_bp = MONO_CONTEXT_GET_BP (ctx);
1951 //FIXME make this stack direction aware
1952 if (catch_bp > prot_bp) {
1954 } else if (catch_bp == prot_bp) {
1955 /* Can be either try { try { } catch {} } finally {} or try { try { } finally {} } catch {}
1956 * So we check if the catch handler_start is protected by the guarded handler protected region
1959 * If there is an outstanding guarded_block return address, it means the current thread must be aborted.
1960 * This is the only way to reach out the guarded block as other cases are handled by the trampoline.
1961 * There aren't any further finally/fault handler blocks down the stack over this exception.
1962 * This must be ensured by the code that installs the guard trampoline.
1964 g_assert (ji == mini_jit_info_table_find (domain, (char *)MONO_CONTEXT_GET_IP (&jit_tls->handler_block_context), NULL));
1966 if (!is_address_protected (ji, jit_tls->handler_block, ei->handler_start)) {
1971 jit_tls->handler_block_return_address = NULL;
1972 jit_tls->handler_block = NULL;
1973 mono_thread_resume_interruption (); /*We ignore the exception here, it will be raised later*/
1977 if (mono_trace_is_enabled () && mono_trace_eval (method))
1978 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (method, TRUE));
1979 jit_tls->orig_ex_ctx_set = TRUE;
1980 mono_profiler_exception_clause_handler (method, ei->flags, i);
1981 jit_tls->orig_ex_ctx_set = FALSE;
1982 mini_set_abort_threshold (ctx);
1983 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1985 #ifndef DISABLE_PERFCOUNTERS
1986 mono_perfcounters->exceptions_depth += frame_count;
1988 if (obj == (MonoObject *)domain->stack_overflow_ex)
1989 jit_tls->handling_stack_ovf = FALSE;
1993 mono_error_cleanup (&error);
1994 if (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
1995 if (mono_trace_is_enabled () && mono_trace_eval (method))
1996 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (method, TRUE));
1997 jit_tls->orig_ex_ctx_set = TRUE;
1998 mono_profiler_exception_clause_handler (method, ei->flags, i);
1999 jit_tls->orig_ex_ctx_set = FALSE;
2000 mini_set_abort_threshold (ctx);
2001 call_filter (ctx, ei->handler_start);
2003 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2004 if (mono_trace_is_enabled () && mono_trace_eval (method))
2005 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2006 jit_tls->orig_ex_ctx_set = TRUE;
2007 mono_profiler_exception_clause_handler (method, ei->flags, i);
2008 jit_tls->orig_ex_ctx_set = FALSE;
2009 #ifndef DISABLE_PERFCOUNTERS
2010 mono_perfcounters->exceptions_finallys++;
2013 if (ji->from_llvm) {
2015 * LLVM compiled finally handlers follow the design
2016 * of the c++ ehabi, i.e. they call a resume function
2017 * at the end instead of returning to the caller.
2018 * So save the exception handling state,
2019 * mono_resume_unwind () will call us again to continue
2022 jit_tls->resume_state.ex_obj = obj;
2023 jit_tls->resume_state.ji = ji;
2024 jit_tls->resume_state.clause_index = i + 1;
2025 jit_tls->resume_state.ctx = *ctx;
2026 jit_tls->resume_state.new_ctx = new_ctx;
2027 jit_tls->resume_state.lmf = lmf;
2028 jit_tls->resume_state.first_filter_idx = first_filter_idx;
2029 jit_tls->resume_state.filter_idx = filter_idx;
2030 mini_set_abort_threshold (ctx);
2031 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2034 mini_set_abort_threshold (ctx);
2035 call_filter (ctx, ei->handler_start);
2041 jit_tls->orig_ex_ctx_set = TRUE;
2042 mono_profiler_exception_method_leave (method);
2043 jit_tls->orig_ex_ctx_set = FALSE;
2048 g_assert_not_reached ();
2052 * mono_debugger_run_finally:
2053 * @start_ctx: saved processor state
2055 * This method is called by the Mono Debugger to call all `finally' clauses of the
2056 * current stack frame. It's used when the user issues a `return' command to make
2057 * the current stack frame return. After returning from this method, the debugger
2058 * unwinds the stack one frame and gives control back to the user.
2060 * NOTE: This method is only used when running inside the Mono Debugger.
2063 mono_debugger_run_finally (MonoContext *start_ctx)
2065 static int (*call_filter) (MonoContext *, gpointer) = NULL;
2066 MonoDomain *domain = mono_domain_get ();
2067 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2068 MonoLMF *lmf = mono_get_lmf ();
2069 MonoContext ctx, new_ctx;
2070 MonoJitInfo *ji, rji;
2075 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
2076 if (!ji || ji == (gpointer)-1)
2080 call_filter = (int (*)(MonoContext *, void *))mono_get_call_filter ();
2082 for (i = 0; i < ji->num_clauses; i++) {
2083 MonoJitExceptionInfo *ei = &ji->clauses [i];
2085 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (&ctx)) &&
2086 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
2087 call_filter (&ctx, ei->handler_start);
2093 * mono_handle_exception:
2094 * @ctx: saved processor state
2095 * @obj: the exception object
2098 mono_handle_exception (MonoContext *ctx, MonoObject *obj)
2100 MONO_REQ_GC_UNSAFE_MODE;
2102 #ifndef DISABLE_PERFCOUNTERS
2103 mono_perfcounters->exceptions_thrown++;
2106 return mono_handle_exception_internal (ctx, obj, FALSE, NULL);
2109 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2111 #ifndef MONO_ARCH_USE_SIGACTION
2112 #error "Can't use sigaltstack without sigaction"
2115 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
2118 mono_setup_altstack (MonoJitTlsData *tls)
2122 guint8 *staddr = NULL;
2124 if (mono_running_on_valgrind ())
2127 mono_thread_info_get_stack_bounds (&staddr, &stsize);
2131 tls->end_of_stack = staddr + stsize;
2132 tls->stack_size = stsize;
2134 /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
2136 tls->stack_ovf_guard_base = staddr + mono_pagesize ();
2137 tls->stack_ovf_guard_size = ALIGN_TO (8 * 4096, mono_pagesize ());
2139 g_assert ((guint8*)&sa >= (guint8*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size);
2141 if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
2142 /* mprotect can fail for the main thread stack */
2143 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, MONO_MEM_ACCOUNT_EXCEPTIONS);
2144 g_assert (gaddr == tls->stack_ovf_guard_base);
2145 tls->stack_ovf_valloced = TRUE;
2148 /* Setup an alternate signal stack */
2149 tls->signal_stack = mono_valloc (0, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_PRIVATE|MONO_MMAP_ANON, MONO_MEM_ACCOUNT_EXCEPTIONS);
2150 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2152 g_assert (tls->signal_stack);
2154 sa.ss_sp = tls->signal_stack;
2155 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2157 g_assert (sigaltstack (&sa, NULL) == 0);
2159 mono_gc_register_altstack ((char*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size, (char*)staddr + stsize - ((char*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size), tls->signal_stack, tls->signal_stack_size);
2163 mono_free_altstack (MonoJitTlsData *tls)
2168 sa.ss_sp = tls->signal_stack;
2169 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2170 sa.ss_flags = SS_DISABLE;
2171 err = sigaltstack (&sa, NULL);
2172 g_assert (err == 0);
2174 if (tls->signal_stack)
2175 mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MEM_ACCOUNT_EXCEPTIONS);
2176 if (tls->stack_ovf_valloced)
2177 mono_vfree (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MEM_ACCOUNT_EXCEPTIONS);
2179 mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
2182 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2185 mono_setup_altstack (MonoJitTlsData *tls)
2190 mono_free_altstack (MonoJitTlsData *tls)
2194 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2197 try_restore_stack_protection (MonoJitTlsData *jit_tls, int extra_bytes)
2199 gint32 unprotect_size = jit_tls->stack_ovf_guard_size;
2200 /* we need to leave some room for throwing the exception */
2201 while (unprotect_size >= 0 && (char*)jit_tls->stack_ovf_guard_base + unprotect_size > ((char*)&unprotect_size - extra_bytes))
2202 unprotect_size -= mono_pagesize ();
2203 /* at this point we could try and build a new domain->stack_overflow_ex, but only if there
2204 * is sufficient stack
2206 //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);
2208 mono_mprotect (jit_tls->stack_ovf_guard_base, unprotect_size, MONO_MMAP_NONE);
2209 return unprotect_size == jit_tls->stack_ovf_guard_size;
2212 static G_GNUC_UNUSED void
2213 try_more_restore (void)
2215 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2216 if (try_restore_stack_protection (jit_tls, 500))
2217 jit_tls->restore_stack_prot = NULL;
2220 static G_GNUC_UNUSED void
2221 restore_stack_protection (void)
2223 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2224 MonoException *ex = mono_domain_get ()->stack_overflow_ex;
2225 /* if we can't restore the stack protection, keep a callback installed so
2226 * we'll try to restore as much stack as we can at each return from unmanaged
2229 if (try_restore_stack_protection (jit_tls, 4096))
2230 jit_tls->restore_stack_prot = NULL;
2232 jit_tls->restore_stack_prot = try_more_restore_tramp;
2233 /* here we also throw a stack overflow exception */
2234 ex->trace_ips = NULL;
2235 ex->stack_trace = NULL;
2236 mono_raise_exception (ex);
2240 mono_altstack_restore_prot (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
2242 MONO_REQ_GC_UNSAFE_MODE;
2244 void (*func)(void) = (void (*)(void))tramp_data;
2250 mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, guint8* fault_addr)
2255 /* we got a stack overflow in the soft-guard pages
2256 * There are two cases:
2257 * 1) managed code caused the overflow: we unprotect the soft-guard page
2258 * and let the arch-specific code trigger the exception handling mechanism
2259 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
2260 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
2261 * and hope we can continue with those enabled, at least until the hard-guard page
2262 * is hit. The alternative to continuing here is to just print a message and abort.
2263 * We may add in the future the code to protect the pages again in the codepath
2264 * when we return from unmanaged to managed code.
2266 if (jit_tls->stack_ovf_guard_size && fault_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
2267 fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
2268 /* we unprotect the minimum amount we can */
2270 gboolean handled = FALSE;
2272 guard_size = jit_tls->stack_ovf_guard_size - (mono_pagesize () * SIZEOF_VOID_P / 4);
2273 while (guard_size && fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + guard_size) {
2274 guard_size -= mono_pagesize ();
2276 guard_size = jit_tls->stack_ovf_guard_size - guard_size;
2277 /*fprintf (stderr, "unprotecting: %d\n", guard_size);*/
2278 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);
2279 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2281 mono_arch_handle_altstack_exception (ctx, siginfo, fault_addr, TRUE);
2286 /* We print a message: after this even managed stack overflows
2287 * may crash the runtime
2289 mono_runtime_printf_err ("Stack overflow in unmanaged: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2290 if (!jit_tls->handling_stack_ovf) {
2291 jit_tls->restore_stack_prot = restore_stack_protection_tramp;
2292 jit_tls->handling_stack_ovf = 1;
2294 /*fprintf (stderr, "Already handling stack overflow\n");*/
2303 MonoMethod *omethod;
2305 } PrintOverflowUserData;
2307 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2309 print_overflow_stack_frame (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2311 MonoMethod *method = NULL;
2312 PrintOverflowUserData *user_data = (PrintOverflowUserData *)data;
2315 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2316 method = jinfo_get_method (frame->ji);
2319 if (user_data->count == 0) {
2320 /* The first frame is in its prolog, so a line number cannot be computed */
2321 user_data->count ++;
2325 /* If this is a one method overflow, skip the other instances */
2326 if (method == user_data->omethod)
2329 location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2330 mono_runtime_printf_err (" %s", location);
2333 if (user_data->count == 1) {
2334 mono_runtime_printf_err (" <...>");
2335 user_data->omethod = method;
2337 user_data->omethod = NULL;
2340 user_data->count ++;
2342 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2349 mono_handle_hard_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
2351 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2352 PrintOverflowUserData ud;
2356 /* we don't do much now, but we can warn the user with a useful message */
2357 mono_runtime_printf_err ("Stack overflow: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2359 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2360 mono_sigctx_to_monoctx (ctx, &mctx);
2362 mono_runtime_printf_err ("Stacktrace:");
2364 memset (&ud, 0, sizeof (ud));
2366 mono_walk_stack_with_ctx (print_overflow_stack_frame, &mctx, MONO_UNWIND_LOOKUP_ACTUAL_METHOD, &ud);
2368 if (ji && !ji->is_trampoline && jinfo_get_method (ji))
2369 mono_runtime_printf_err ("At %s", mono_method_full_name (jinfo_get_method (ji), TRUE));
2371 mono_runtime_printf_err ("At <unmanaged>.");
2378 print_stack_frame_to_stderr (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2380 MonoMethod *method = NULL;
2382 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2383 method = jinfo_get_method (frame->ji);
2386 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2387 mono_runtime_printf_err (" %s", location);
2390 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2395 static G_GNUC_UNUSED gboolean
2396 print_stack_frame_to_string (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2398 GString *p = (GString*)data;
2399 MonoMethod *method = NULL;
2401 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2402 method = jinfo_get_method (frame->ji);
2404 if (method && frame->domain) {
2405 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
2406 g_string_append_printf (p, " %s\n", location);
2409 g_string_append_printf (p, " at <unknown> <0x%05x>\n", frame->native_offset);
2414 #ifndef MONO_CROSS_COMPILE
2416 static gboolean handling_sigsegv = FALSE;
2419 * mono_handle_native_sigsegv:
2421 * Handle a SIGSEGV received while in native code by printing diagnostic
2422 * information and aborting.
2425 mono_handle_native_sigsegv (int signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2427 #ifdef MONO_ARCH_USE_SIGACTION
2428 struct sigaction sa;
2430 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2431 const char *signal_str = (signal == SIGSEGV) ? "SIGSEGV" : "SIGABRT";
2433 if (handling_sigsegv)
2436 if (mini_get_debug_options ()->suspend_on_sigsegv) {
2437 mono_runtime_printf_err ("Received SIGSEGV, suspending...");
2448 /* To prevent infinite loops when the stack walk causes a crash */
2449 handling_sigsegv = TRUE;
2451 /* !jit_tls means the thread was not registered with the runtime */
2452 if (jit_tls && mono_thread_internal_current ()) {
2453 mono_runtime_printf_err ("Stacktrace:\n");
2455 /* FIXME: Is MONO_UNWIND_LOOKUP_IL_OFFSET correct here? */
2456 mono_walk_stack (print_stack_frame_to_stderr, MONO_UNWIND_LOOKUP_IL_OFFSET, NULL);
2459 #ifdef HAVE_BACKTRACE_SYMBOLS
2465 mono_runtime_printf_err ("\nNative stacktrace:\n");
2467 size = backtrace (array, 256);
2468 names = backtrace_symbols (array, size);
2469 for (i =0; i < size; ++i) {
2470 mono_runtime_printf_err ("\t%s", names [i]);
2474 /* Try to get more meaningful information using gdb */
2476 #if !defined(HOST_WIN32) && defined(HAVE_SYS_SYSCALL_H) && defined(SYS_fork)
2477 if (!mini_get_debug_options ()->no_gdb_backtrace) {
2478 /* From g_spawn_command_line_sync () in eglib */
2481 pid_t crashed_pid = getpid ();
2485 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
2486 * it will deadlock. Call the syscall directly instead.
2488 pid = mono_runtime_syscall_fork ();
2489 #if defined (HAVE_PRCTL) && defined(PR_SET_PTRACER)
2491 // Allow gdb to attach to the process even if ptrace_scope sysctl variable is set to
2492 // a value other than 0 (the most permissive ptrace scope). Most modern Linux
2493 // distributions set the scope to 1 which allows attaching only to direct children of
2494 // the current process
2495 prctl (PR_SET_PTRACER, pid, 0, 0, 0);
2499 dup2 (STDERR_FILENO, STDOUT_FILENO);
2501 mono_gdb_render_native_backtraces (crashed_pid);
2505 mono_runtime_printf_err ("\nDebug info from gdb:\n");
2506 waitpid (pid, &status, 0);
2511 mono_exception_native_unwind (ctx, info);
2515 * A SIGSEGV indicates something went very wrong so we can no longer depend
2516 * on anything working. So try to print out lots of diagnostics, starting
2517 * with ones which have a greater chance of working.
2519 mono_runtime_printf_err (
2521 "=================================================================\n"
2522 "Got a %s while executing native code. This usually indicates\n"
2523 "a fatal error in the mono runtime or one of the native libraries \n"
2524 "used by your application.\n"
2525 "=================================================================\n",
2529 #ifdef MONO_ARCH_USE_SIGACTION
2531 /* Remove our SIGABRT handler */
2532 sa.sa_handler = SIG_DFL;
2533 sigemptyset (&sa.sa_mask);
2536 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
2540 if (!mono_do_crash_chaining) {
2541 /*Android abort is a fluke, it doesn't abort, it triggers another segv. */
2542 #if defined (PLATFORM_ANDROID)
2553 mono_handle_native_sigsegv (int signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2555 g_assert_not_reached ();
2558 #endif /* !MONO_CROSS_COMPILE */
2561 mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
2563 MonoInternalThread *thread = mono_thread_internal_current ();
2564 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2569 GError *error = NULL;
2574 text = g_string_new (0);
2576 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
2578 g_string_append_printf (text, "\n\"%s\"", name);
2581 else if (thread->threadpool_thread)
2582 g_string_append (text, "\n\"<threadpool thread>\"");
2584 g_string_append (text, "\n\"<unnamed thread>\"");
2586 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
2587 mono_thread_internal_describe (thread, text);
2588 g_string_append (text, "\n");
2590 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2592 memcpy (&ctx, start_ctx, sizeof (MonoContext));
2594 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_print_thread_dump);
2596 mono_sigctx_to_monoctx (sigctx, &ctx);
2598 mono_walk_stack_with_ctx (print_stack_frame_to_string, &ctx, MONO_UNWIND_LOOKUP_ALL, text);
2600 mono_runtime_printf ("\t<Stack traces in thread dumps not supported on this platform>");
2603 mono_runtime_printf ("%s", text->str);
2605 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
2606 OutputDebugStringA(text->str);
2609 g_string_free (text, TRUE);
2610 mono_runtime_stdout_fflush ();
2614 * mono_print_thread_dump:
2616 * Print information about the current thread to stdout.
2617 * SIGCTX can be NULL, allowing this to be called from gdb.
2620 mono_print_thread_dump (void *sigctx)
2622 mono_print_thread_dump_internal (sigctx, NULL);
2626 mono_print_thread_dump_from_ctx (MonoContext *ctx)
2628 mono_print_thread_dump_internal (NULL, ctx);
2632 * mono_resume_unwind:
2634 * This is called by a trampoline from LLVM compiled finally clauses to continue
2638 mono_resume_unwind (MonoContext *ctx)
2640 MONO_REQ_GC_UNSAFE_MODE;
2642 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2643 MonoContext new_ctx;
2645 MONO_CONTEXT_SET_IP (ctx, MONO_CONTEXT_GET_IP (&jit_tls->resume_state.ctx));
2646 MONO_CONTEXT_SET_SP (ctx, MONO_CONTEXT_GET_SP (&jit_tls->resume_state.ctx));
2649 mono_handle_exception_internal (&new_ctx, (MonoObject *)jit_tls->resume_state.ex_obj, TRUE, NULL);
2651 mono_restore_context (&new_ctx);
2654 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
2659 MonoJitExceptionInfo *ei;
2660 } FindHandlerBlockData;
2663 find_last_handler_block (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2667 FindHandlerBlockData *pdata = (FindHandlerBlockData *)data;
2668 MonoJitInfo *ji = frame->ji;
2673 ip = MONO_CONTEXT_GET_IP (ctx);
2675 for (i = 0; i < ji->num_clauses; ++i) {
2676 MonoJitExceptionInfo *ei = ji->clauses + i;
2677 if (ei->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2679 /*If ip points to the first instruction it means the handler block didn't start
2680 so we can leave its execution to the EH machinery*/
2681 if (ei->handler_start < ip && ip < ei->data.handler_end) {
2693 install_handler_block_guard (MonoJitInfo *ji, MonoContext *ctx)
2696 MonoJitExceptionInfo *clause = NULL;
2699 ip = MONO_CONTEXT_GET_IP (ctx);
2701 for (i = 0; i < ji->num_clauses; ++i) {
2702 clause = &ji->clauses [i];
2703 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2705 if (clause->handler_start < ip && clause->data.handler_end > ip)
2709 /*no matching finally */
2710 if (i == ji->num_clauses)
2713 /*If we stopped on the instruction right before the try, we haven't actually started executing it*/
2714 if (ip == clause->handler_start)
2717 return mono_arch_install_handler_block_guard (ji, clause, ctx, mono_create_handler_block_trampoline ());
2721 * Finds the bottom handler block running and install a block guard if needed.
2724 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2726 FindHandlerBlockData data = { 0 };
2727 MonoJitTlsData *jit_tls = (MonoJitTlsData *)ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS];
2730 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
2735 /* Guard against a null MonoJitTlsData. This can happens if the thread receives the
2736 * interrupt signal before the JIT has time to initialize its TLS data for the given thread.
2738 if (!jit_tls || jit_tls->handler_block_return_address)
2741 /* Do an async safe stack walk */
2742 mono_thread_info_set_is_async_context (TRUE);
2743 mono_walk_stack_with_state (find_last_handler_block, ctx, MONO_UNWIND_NONE, &data);
2744 mono_thread_info_set_is_async_context (FALSE);
2749 memcpy (&jit_tls->handler_block_context, &data.ctx, sizeof (MonoContext));
2751 resume_ip = install_handler_block_guard (data.ji, &data.ctx);
2752 if (resume_ip == NULL)
2755 jit_tls->handler_block_return_address = resume_ip;
2756 jit_tls->handler_block = data.ei;
2762 mono_current_thread_has_handle_block_guard (void)
2764 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2765 return jit_tls && jit_tls->handler_block_return_address != NULL;
2770 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2776 mono_current_thread_has_handle_block_guard (void)
2784 mono_set_cast_details (MonoClass *from, MonoClass *to)
2786 MonoJitTlsData *jit_tls = NULL;
2788 if (mini_get_debug_options ()->better_cast_details) {
2789 jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2790 jit_tls->class_cast_from = from;
2791 jit_tls->class_cast_to = to;
2796 /*returns false if the thread is not attached*/
2798 mono_thread_state_init_from_sigctx (MonoThreadUnwindState *ctx, void *sigctx)
2800 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2801 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2804 g_error ("Invoked mono_thread_state_init_from_sigctx from non-Mono thread");
2809 mono_sigctx_to_monoctx (sigctx, &ctx->ctx);
2811 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2812 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2813 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2816 mono_thread_state_init (ctx);
2819 if (!ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] || !ctx->unwind_data [MONO_UNWIND_DATA_LMF])
2825 g_error ("Implement mono_arch_sigctx_to_monoctx for the current target");
2831 mono_thread_state_init (MonoThreadUnwindState *ctx)
2833 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2835 #if defined(MONO_CROSS_COMPILE)
2836 ctx->valid = FALSE; //A cross compiler doesn't need to suspend.
2837 #elif MONO_ARCH_HAS_MONO_CONTEXT
2838 MONO_CONTEXT_GET_CURRENT (ctx->ctx);
2840 g_error ("Use a null sigctx requires a working mono-context");
2843 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2844 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2845 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread ? thread->jit_data : NULL;
2851 mono_thread_state_init_from_monoctx (MonoThreadUnwindState *ctx, MonoContext *mctx)
2853 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2860 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2861 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2862 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2867 /*returns false if the thread is not attached*/
2869 mono_thread_state_init_from_current (MonoThreadUnwindState *ctx)
2871 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2872 MONO_ARCH_CONTEXT_DEF
2874 mono_arch_flush_register_windows ();
2876 if (!thread || !thread->jit_data) {
2880 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
2881 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx->ctx);
2883 MONO_INIT_CONTEXT_FROM_FUNC (&ctx->ctx, mono_thread_state_init_from_current);
2886 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2887 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2888 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2894 mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx)
2896 mono_handle_exception (ctx, (MonoObject *)exc);
2897 mono_restore_context (ctx);
2900 /*FIXME Move all monoctx -> sigctx conversion to signal handlers once all archs support utils/mono-context */
2902 mono_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
2904 #ifdef MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK
2905 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2906 jit_tls->ex_ctx = *ctx;
2908 mono_arch_setup_async_callback (ctx, async_cb, user_data);
2910 g_error ("This target doesn't support mono_arch_setup_async_callback");
2915 * mono_restore_context:
2917 * Call the architecture specific restore context function.
2920 mono_restore_context (MonoContext *ctx)
2922 static void (*restore_context) (MonoContext *);
2924 if (!restore_context)
2925 restore_context = (void (*)(MonoContext *))mono_get_restore_context ();
2926 restore_context (ctx);
2927 g_assert_not_reached ();
2931 * mono_jinfo_get_unwind_info:
2933 * Return the unwind info for JI.
2936 mono_jinfo_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2939 return mono_aot_get_unwind_info (ji, unwind_info_len);
2941 return mono_get_cached_unwind_info (ji->unwind_info, unwind_info_len);
2945 mono_jinfo_get_epilog_size (MonoJitInfo *ji)
2947 MonoArchEHJitInfo *info;
2949 info = mono_jit_info_get_arch_eh_info (ji);
2952 return info->epilog_size;
2956 * LLVM/Bitcode exception handling.
2960 throw_exception (MonoObject *ex, gboolean rethrow)
2962 MONO_REQ_GC_UNSAFE_MODE;
2965 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
2966 MonoException *mono_ex;
2968 if (!mono_object_isinst_checked (ex, mono_defaults.exception_class, &error)) {
2969 mono_error_assert_ok (&error);
2970 mono_ex = mono_get_exception_runtime_wrapped_checked (ex, &error);
2971 mono_error_assert_ok (&error);
2972 jit_tls->thrown_non_exc = mono_gchandle_new (ex, FALSE);
2975 mono_ex = (MonoException*)ex;
2978 jit_tls->thrown_exc = mono_gchandle_new ((MonoObject*)mono_ex, FALSE);
2981 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
2982 GList *l, *ips = NULL;
2985 _Unwind_Backtrace (build_stack_trace, &ips);
2986 /* The list contains ip-gshared info pairs */
2988 ips = g_list_reverse (ips);
2989 for (l = ips; l; l = l->next) {
2990 trace = g_list_append (trace, l->data);
2991 trace = g_list_append (trace, NULL);
2993 MonoArray *ips_arr = mono_glist_to_array (trace, mono_defaults.int_class, &error);
2994 mono_error_assert_ok (&error);
2995 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
2997 g_list_free (trace);
3001 mono_llvm_cpp_throw_exception ();
3005 mono_llvm_throw_exception (MonoObject *ex)
3007 throw_exception (ex, FALSE);
3011 mono_llvm_rethrow_exception (MonoObject *ex)
3013 throw_exception (ex, TRUE);
3017 mono_llvm_raise_exception (MonoException *e)
3019 mono_llvm_throw_exception ((MonoObject*)e);
3023 mono_llvm_throw_corlib_exception (guint32 ex_token_index)
3025 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
3028 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
3030 mono_llvm_throw_exception ((MonoObject*)ex);
3034 * mono_llvm_resume_exception:
3036 * Resume exception propagation.
3039 mono_llvm_resume_exception (void)
3041 mono_llvm_cpp_throw_exception ();
3045 * mono_llvm_load_exception:
3047 * Return the currently thrown exception.
3050 mono_llvm_load_exception (void)
3053 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3055 MonoException *mono_ex = (MonoException*)mono_gchandle_get_target (jit_tls->thrown_exc);
3057 if (mono_ex->trace_ips) {
3058 GList *trace_ips = NULL;
3059 gpointer ip = __builtin_return_address (0);
3061 size_t upper = mono_array_length (mono_ex->trace_ips);
3063 for (int i = 0; i < upper; i+= 2) {
3064 gpointer curr_ip = mono_array_get (mono_ex->trace_ips, gpointer, i);
3065 gpointer curr_info = mono_array_get (mono_ex->trace_ips, gpointer, i + 1);
3066 trace_ips = g_list_append (trace_ips, curr_ip);
3067 trace_ips = g_list_append (trace_ips, curr_info);
3073 // FIXME: Does this work correctly for rethrows?
3074 // We may be discarding useful information
3075 // when this gets GC'ed
3076 MonoArray *ips_arr = mono_glist_to_array (trace_ips, mono_defaults.int_class, &error);
3077 mono_error_assert_ok (&error);
3078 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3079 g_list_free (trace_ips);
3082 //MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
3084 MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, 0, &error));
3085 mono_error_assert_ok (&error);
3086 MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new_checked (mono_domain_get (), mono_defaults.stack_frame_class, 0, &error));
3087 mono_error_assert_ok (&error);
3090 return &mono_ex->object;
3094 * mono_llvm_clear_exception:
3096 * Mark the currently thrown exception as handled.
3099 mono_llvm_clear_exception (void)
3101 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3102 mono_gchandle_free (jit_tls->thrown_exc);
3103 jit_tls->thrown_exc = 0;
3104 if (jit_tls->thrown_non_exc)
3105 mono_gchandle_free (jit_tls->thrown_non_exc);
3106 jit_tls->thrown_non_exc = 0;
3108 mono_memory_barrier ();
3112 * mono_llvm_match_exception:
3114 * Return the innermost clause containing REGION_START-REGION_END which can handle
3115 * the current exception.
3118 mono_llvm_match_exception (MonoJitInfo *jinfo, guint32 region_start, guint32 region_end, gpointer rgctx, MonoObject *this_obj)
3121 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3125 g_assert (jit_tls->thrown_exc);
3126 exc = mono_gchandle_get_target (jit_tls->thrown_exc);
3127 if (jit_tls->thrown_non_exc) {
3129 * Have to unwrap RuntimeWrappedExceptions if the
3130 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
3132 if (!wrap_non_exception_throws (jinfo_get_method (jinfo)))
3133 exc = mono_gchandle_get_target (jit_tls->thrown_non_exc);
3136 for (int i = 0; i < jinfo->num_clauses; i++) {
3137 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3138 MonoClass *catch_class;
3140 if (! (ei->try_offset == region_start && ei->try_offset + ei->try_len == region_end) )
3143 catch_class = ei->data.catch_class;
3144 if (mono_class_is_open_constructed_type (&catch_class->byval_arg)) {
3145 MonoGenericContext context;
3146 MonoType *inflated_type;
3148 g_assert (rgctx || this_obj);
3149 context = get_generic_context_from_stack_frame (jinfo, rgctx ? rgctx : this_obj->vtable);
3150 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
3151 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3153 catch_class = mono_class_from_mono_type (inflated_type);
3154 mono_metadata_free_type (inflated_type);
3157 // FIXME: Handle edge cases handled in get_exception_catch_class
3158 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (exc, catch_class, &error)) {
3159 index = ei->clause_index;
3162 mono_error_assert_ok (&error);
3164 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3165 g_assert_not_reached ();
3174 mono_debug_personality (int a, _Unwind_Action b,
3175 uint64_t c, struct _Unwind_Exception *d, struct _Unwind_Context *e)
3177 g_assert_not_reached ();
3181 mono_debug_personality (void);
3184 mono_debug_personality (void)
3186 g_assert_not_reached ();