3 * generic exception support
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Mono Team (mono-list@lists.ximian.com)
9 * Copyright 2001-2003 Ximian, Inc.
10 * Copyright 2003-2008 Novell, Inc.
11 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
23 #ifdef HAVE_EXECINFO_H
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
31 #ifdef HAVE_SYS_WAIT_H
39 #ifdef HAVE_SYS_SYSCALL_H
40 #include <sys/syscall.h>
43 #ifdef HAVE_SYS_PRCTL_H
44 #include <sys/prctl.h>
51 #include <mono/metadata/appdomain.h>
52 #include <mono/metadata/tabledefs.h>
53 #include <mono/metadata/threads.h>
54 #include <mono/metadata/threads-types.h>
55 #include <mono/metadata/debug-helpers.h>
56 #include <mono/metadata/exception.h>
57 #include <mono/metadata/exception-internals.h>
58 #include <mono/metadata/object-internals.h>
59 #include <mono/metadata/reflection-internals.h>
60 #include <mono/metadata/gc-internals.h>
61 #include <mono/metadata/debug-internals.h>
62 #include <mono/metadata/mono-debug.h>
63 #include <mono/metadata/profiler.h>
64 #include <mono/metadata/mono-endian.h>
65 #include <mono/metadata/environment.h>
66 #include <mono/metadata/mono-mlist.h>
67 #include <mono/utils/mono-mmap.h>
68 #include <mono/utils/mono-logger-internals.h>
69 #include <mono/utils/mono-error.h>
70 #include <mono/utils/mono-error-internals.h>
74 #include "debugger-agent.h"
75 #include "seq-points.h"
76 #include "llvm-runtime.h"
77 #include "mini-llvm.h"
78 #include "interp/interp.h"
81 #include "mini-llvm-cpp.h"
88 #ifndef MONO_ARCH_CONTEXT_DEF
89 #define MONO_ARCH_CONTEXT_DEF
92 #ifndef MONO_ARCH_STACK_GROWS_UP
93 #define MONO_ARCH_STACK_GROWS_UP 0
96 static gpointer restore_context_func, call_filter_func;
97 static gpointer throw_exception_func, rethrow_exception_func;
98 static gpointer throw_corlib_exception_func;
100 static gpointer try_more_restore_tramp = NULL;
101 static gpointer restore_stack_protection_tramp = NULL;
103 static void try_more_restore (void);
104 static void restore_stack_protection (void);
105 static void mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data);
106 static void mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx);
107 static void mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data);
108 static gboolean mono_current_thread_has_handle_block_guard (void);
111 first_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer addr)
113 gpointer **data = (gpointer **)addr;
119 // FIXME: Happens with llvm_only
124 *data = MONO_CONTEXT_GET_SP (ctx);
130 mono_thread_get_managed_sp (void)
132 gpointer addr = NULL;
133 mono_walk_stack (first_managed, MONO_UNWIND_SIGNAL_SAFE, &addr);
138 mini_abort_threshold_offset (gpointer threshold, gpointer sp)
140 intptr_t stack_threshold = (intptr_t) threshold;
141 intptr_t stack_pointer = (intptr_t) sp;
143 const int direction = MONO_ARCH_STACK_GROWS_UP ? -1 : 1;
144 intptr_t magnitude = stack_pointer - stack_threshold;
146 return direction * magnitude;
150 mini_clear_abort_threshold (void)
152 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
153 jit_tls->abort_exc_stack_threshold = NULL;
157 mini_set_abort_threshold (MonoContext *ctx)
159 gpointer sp = MONO_CONTEXT_GET_SP (ctx);
160 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
161 // Only move it up, to avoid thrown/caught
162 // exceptions lower in the stack from triggering
164 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
165 if (!jit_tls->abort_exc_stack_threshold || above_threshold) {
166 jit_tls->abort_exc_stack_threshold = sp;
170 // Note: In the case that the frame is above where the thread abort
171 // was set we bump the threshold so that functions called from the new,
172 // higher threshold don't trigger the thread abort exception
173 static inline gboolean
174 mini_above_abort_threshold (void)
176 gpointer sp = mono_thread_get_managed_sp ();
177 MonoJitTlsData *jit_tls = (MonoJitTlsData*) mono_tls_get_jit_tls ();
182 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
185 jit_tls->abort_exc_stack_threshold = sp;
187 return above_threshold;
191 mono_get_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
194 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
200 mono_exceptions_init (void)
202 MonoRuntimeExceptionHandlingCallbacks cbs;
204 restore_context_func = mono_aot_get_trampoline ("restore_context");
205 call_filter_func = mono_aot_get_trampoline ("call_filter");
206 throw_exception_func = mono_aot_get_trampoline ("throw_exception");
207 rethrow_exception_func = mono_aot_get_trampoline ("rethrow_exception");
211 restore_context_func = mono_arch_get_restore_context (&info, FALSE);
212 mono_tramp_info_register (info, NULL);
213 call_filter_func = mono_arch_get_call_filter (&info, FALSE);
214 mono_tramp_info_register (info, NULL);
215 throw_exception_func = mono_arch_get_throw_exception (&info, FALSE);
216 mono_tramp_info_register (info, NULL);
217 rethrow_exception_func = mono_arch_get_rethrow_exception (&info, FALSE);
218 mono_tramp_info_register (info, NULL);
220 #ifdef MONO_ARCH_HAVE_RESTORE_STACK_SUPPORT
221 if (!mono_llvm_only) {
222 try_more_restore_tramp = mono_create_specific_trampoline (try_more_restore, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
223 restore_stack_protection_tramp = mono_create_specific_trampoline (restore_stack_protection, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
227 #ifdef MONO_ARCH_HAVE_EXCEPTIONS_INIT
228 mono_arch_exceptions_init ();
230 #ifdef ENABLE_INTERPRETER
231 if (mono_use_interpreter)
232 cbs.mono_walk_stack_with_ctx = interp_walk_stack_with_ctx;
235 cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
237 cbs.mono_walk_stack_with_state = mono_walk_stack_with_state;
240 cbs.mono_raise_exception = mono_llvm_raise_exception;
242 cbs.mono_raise_exception = (void (*)(MonoException *))mono_get_throw_exception ();
243 cbs.mono_raise_exception_with_ctx = mono_raise_exception_with_ctx;
244 cbs.mono_exception_walk_trace = mono_exception_walk_trace;
245 cbs.mono_install_handler_block_guard = mono_install_handler_block_guard;
246 cbs.mono_current_thread_has_handle_block_guard = mono_current_thread_has_handle_block_guard;
247 cbs.mono_clear_abort_threshold = mini_clear_abort_threshold;
248 cbs.mono_above_abort_threshold = mini_above_abort_threshold;
249 mono_install_eh_callbacks (&cbs);
250 mono_install_get_seq_point (mono_get_seq_point_for_native_offset);
254 mono_get_throw_exception (void)
256 g_assert (throw_exception_func);
257 return throw_exception_func;
261 mono_get_rethrow_exception (void)
263 g_assert (rethrow_exception_func);
264 return rethrow_exception_func;
268 mono_get_call_filter (void)
270 g_assert (call_filter_func);
271 return call_filter_func;
275 mono_get_restore_context (void)
277 g_assert (restore_context_func);
278 return restore_context_func;
282 mono_get_throw_corlib_exception (void)
284 gpointer code = NULL;
287 /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
288 if (throw_corlib_exception_func)
289 return throw_corlib_exception_func;
292 code = mono_aot_get_trampoline ("throw_corlib_exception");
294 code = mono_arch_get_throw_corlib_exception (&info, FALSE);
295 mono_tramp_info_register (info, NULL);
298 mono_memory_barrier ();
300 throw_corlib_exception_func = code;
302 return throw_corlib_exception_func;
306 * mono_get_throw_exception_addr:
308 * Return an address which stores the result of
309 * mono_get_throw_exception.
312 mono_get_throw_exception_addr (void)
314 return &throw_exception_func;
318 is_address_protected (MonoJitInfo *ji, MonoJitExceptionInfo *ei, gpointer ip)
320 MonoTryBlockHoleTableJitInfo *table;
325 if (ei->try_start > ip || ip >= ei->try_end)
328 if (!ji->has_try_block_holes)
331 table = mono_jit_info_get_try_block_hole_table_info (ji);
332 offset = (guint32)((char*)ip - (char*)ji->code_start);
333 clause = (guint16)(ei - ji->clauses);
334 g_assert (clause < ji->num_clauses);
336 for (i = 0; i < table->num_holes; ++i) {
337 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
338 if (hole->clause == clause && hole->offset <= offset && hole->offset + hole->length > offset)
344 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
347 static gboolean show_native_addresses = TRUE;
349 static gboolean show_native_addresses = FALSE;
352 static _Unwind_Reason_Code
353 build_stack_trace (struct _Unwind_Context *frame_ctx, void *state)
355 MonoDomain *domain = mono_domain_get ();
356 uintptr_t ip = _Unwind_GetIP (frame_ctx);
358 if (show_native_addresses || mono_jit_info_table_find (domain, (char*)ip)) {
359 GList **trace_ips = (GList **)state;
360 *trace_ips = g_list_prepend (*trace_ips, (gpointer)ip);
363 return _URC_NO_REASON;
367 get_unwind_backtrace (void)
371 _Unwind_Backtrace (build_stack_trace, &ips);
373 return g_slist_reverse (ips);
379 get_unwind_backtrace (void)
389 * Translate between the mono_arch_unwind_frame function and the old API.
392 find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
393 MonoContext *new_ctx, MonoLMF **lmf, gboolean *managed)
395 StackFrameInfo frame;
398 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
400 /* Avoid costly table lookup during stack overflow */
401 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
404 ji = mini_jit_info_table_find (domain, (char *)ip, NULL);
409 err = mono_arch_unwind_frame (domain, jit_tls, ji, ctx, new_ctx, lmf, NULL, &frame);
411 return (MonoJitInfo *)-1;
413 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
415 * Remove any unused lmf.
416 * Mask out the lower bits which might be used to hold additional information.
418 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
421 /* Convert between the new and the old APIs */
422 switch (frame.type) {
423 case FRAME_TYPE_MANAGED:
427 case FRAME_TYPE_TRAMPOLINE:
429 case FRAME_TYPE_MANAGED_TO_NATIVE:
433 memset (res, 0, sizeof (MonoJitInfo));
434 res->d.method = frame.method;
437 case FRAME_TYPE_DEBUGGER_INVOKE: {
441 * The normal exception handling code can't handle this frame, so just
444 ji = find_jit_info (domain, jit_tls, res, NULL, new_ctx, &tmp_ctx, lmf, managed);
445 memcpy (new_ctx, &tmp_ctx, sizeof (MonoContext));
449 g_assert_not_reached ();
454 /* mono_find_jit_info:
456 * This function is used to gather information from @ctx. It return the
457 * MonoJitInfo of the corresponding function, unwinds one stack frame and
458 * stores the resulting context into @new_ctx. It also stores a string
459 * describing the stack location into @trace (if not NULL), and modifies
460 * the @lmf if necessary. @native_offset return the IP offset from the
461 * start of the function or -1 if that info is not available.
464 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
465 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
469 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
471 MonoMethod *method = NULL;
482 ji = find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, lmf, &managed2);
484 if (ji == (gpointer)-1)
487 if (ji && !ji->is_trampoline)
488 method = jinfo_get_method (ji);
490 if (managed2 || (method && method->wrapper_type)) {
491 const char *real_ip, *start;
494 start = (const char *)ji->code_start;
496 /* ctx->ip points into native code */
497 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
499 real_ip = (const char*)ip;
501 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
502 offset = real_ip - start;
507 *native_offset = offset;
510 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
514 *trace = mono_debug_print_stack_frame (method, offset, domain);
517 char *fname = mono_method_full_name (jinfo_get_method (res), TRUE);
518 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
527 * mono_find_jit_info_ext:
529 * A version of mono_find_jit_info which returns all data in the StackFrameInfo
531 * A note about frames of type FRAME_TYPE_MANAGED_TO_NATIVE:
532 * - These frames are used to mark managed-to-native transitions, so CTX will refer to native
533 * code, and new_ctx will refer to the last managed frame. The caller should unwind once more
534 * to obtain the last managed frame.
535 * If SAVE_LOCATIONS is not NULL, it should point to an array of size MONO_MAX_IREGS.
536 * On return, it will be filled with the locations where callee saved registers are saved
537 * by the current frame. This is returned outside of StackFrameInfo because it can be
538 * quite large on some platforms.
539 * If ASYNC true, this function will be async safe, but some fields of frame and frame->ji will
543 mono_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls,
544 MonoJitInfo *prev_ji, MonoContext *ctx,
545 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
546 mgreg_t **save_locations,
547 StackFrameInfo *frame)
550 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
552 MonoDomain *target_domain = domain;
553 MonoMethod *method = NULL;
554 gboolean async = mono_thread_info_is_async_context ();
559 /* Avoid costly table lookup during stack overflow */
560 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
563 ji = mini_jit_info_table_find (domain, (char *)ip, &target_domain);
566 target_domain = domain;
569 memset (save_locations, 0, MONO_MAX_IREGS * sizeof (mgreg_t*));
571 err = mono_arch_unwind_frame (target_domain, jit_tls, ji, ctx, new_ctx, lmf, save_locations, frame);
575 if (frame->type != FRAME_TYPE_INTERP_TO_MANAGED && *lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
577 * Remove any unused lmf.
578 * Mask out the lower bits which might be used to hold additional information.
580 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
583 if (frame->ji && !frame->ji->is_trampoline && !frame->ji->async)
584 method = jinfo_get_method (frame->ji);
586 if (frame->type == FRAME_TYPE_MANAGED && method) {
587 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
588 frame->managed = TRUE;
591 if (frame->type == FRAME_TYPE_MANAGED_TO_NATIVE) {
593 * This type of frame is just a marker, the caller should unwind once more to get the
594 * last managed frame.
597 frame->method = NULL;
600 frame->native_offset = -1;
601 frame->domain = target_domain;
602 frame->async_context = async;
606 if (frame->type == FRAME_TYPE_MANAGED)
607 frame->method = method;
609 if (ji && (frame->managed || (method && method->wrapper_type))) {
610 const char *real_ip, *start;
612 start = (const char *)ji->code_start;
613 if (frame->type == FRAME_TYPE_MANAGED)
614 real_ip = (const char*)ip;
616 /* ctx->ip points into native code */
617 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
619 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
620 frame->native_offset = real_ip - start;
622 frame->native_offset = -1;
626 *trace = mono_debug_print_stack_frame (method, frame->native_offset, domain);
628 if (trace && frame->method) {
629 char *fname = mono_method_full_name (frame->method, TRUE);
630 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
640 MonoInterpStackIter interp_iter;
644 unwinder_init (Unwinder *unwinder)
646 memset (unwinder, 0, sizeof (Unwinder));
649 #if defined(__GNUC__) && defined(TARGET_ARM64)
650 /* gcc 4.9.2 seems to miscompile this on arm64 */
651 static __attribute__((optimize("O0"))) gboolean
655 unwinder_unwind_frame (Unwinder *unwinder,
656 MonoDomain *domain, MonoJitTlsData *jit_tls,
657 MonoJitInfo *prev_ji, MonoContext *ctx,
658 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
659 mgreg_t **save_locations,
660 StackFrameInfo *frame)
662 if (unwinder->in_interp) {
663 unwinder->in_interp = mono_interp_frame_iter_next (&unwinder->interp_iter, frame);
664 if (!unwinder->in_interp) {
665 return unwinder_unwind_frame (unwinder, domain, jit_tls, prev_ji, ctx, new_ctx, trace, lmf, save_locations, frame);
669 gboolean res = mono_find_jit_info_ext (domain, jit_tls, prev_ji, ctx, new_ctx, trace, lmf,
670 save_locations, frame);
673 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
674 unwinder->in_interp = TRUE;
675 mono_interp_frame_iter_init (&unwinder->interp_iter, frame->interp_exit_data);
682 * This function is async-safe.
685 get_generic_info_from_stack_frame (MonoJitInfo *ji, MonoContext *ctx)
687 MonoGenericJitInfo *gi;
691 if (!ji->has_generic_jit_info)
693 gi = mono_jit_info_get_generic_jit_info (ji);
699 * Search location list if available, it contains the precise location of the
700 * argument for every pc offset, even if the method was interrupted while it was in
704 int offset = (mgreg_t)MONO_CONTEXT_GET_IP (ctx) - (mgreg_t)ji->code_start;
707 for (i = 0; i < gi->nlocs; ++i) {
708 MonoDwarfLocListEntry *entry = &gi->locations [i];
710 if (offset >= entry->from && (offset < entry->to || entry->to == 0)) {
712 info = (gpointer)mono_arch_context_get_int_reg (ctx, entry->reg);
714 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, entry->reg) + entry->offset);
718 g_assert (i < gi->nlocs);
721 info = (gpointer)mono_arch_context_get_int_reg (ctx, gi->this_reg);
723 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
727 method = jinfo_get_method (ji);
728 if (mono_method_get_context (method)->method_inst) {
729 /* A MonoMethodRuntimeGenericContext* */
731 } else if ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype) {
735 /* Avoid returning a managed object */
736 MonoObject *this_obj = (MonoObject *)info;
738 return this_obj->vtable;
743 * generic_info is either a MonoMethodRuntimeGenericContext or a MonoVTable.
745 static MonoGenericContext
746 get_generic_context_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
748 MonoGenericContext context = { NULL, NULL };
749 MonoClass *klass, *method_container_class;
752 g_assert (generic_info);
754 method = jinfo_get_method (ji);
755 g_assert (method->is_inflated);
756 if (mono_method_get_context (method)->method_inst) {
757 MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext *)generic_info;
759 klass = mrgctx->class_vtable->klass;
760 context.method_inst = mrgctx->method_inst;
761 g_assert (context.method_inst);
763 MonoVTable *vtable = (MonoVTable *)generic_info;
765 klass = vtable->klass;
768 //g_assert (!mono_class_is_gtd (method->klass));
769 if (mono_class_is_ginst (method->klass))
770 method_container_class = mono_class_get_generic_class (method->klass)->container_class;
772 method_container_class = method->klass;
774 /* class might refer to a subclass of method's class */
775 while (!(klass == method->klass || (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->container_class == method_container_class))) {
776 klass = klass->parent;
780 if (mono_class_is_ginst (klass) || mono_class_is_gtd (klass))
781 context.class_inst = mini_class_get_context (klass)->class_inst;
783 if (mono_class_is_ginst (klass))
784 g_assert (mono_class_has_parent_and_ignore_generics (mono_class_get_generic_class (klass)->container_class, method_container_class));
786 g_assert (mono_class_has_parent_and_ignore_generics (klass, method_container_class));
792 get_method_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
795 MonoGenericContext context;
798 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
799 return jinfo_get_method (ji);
800 context = get_generic_context_from_stack_frame (ji, generic_info);
802 method = jinfo_get_method (ji);
803 method = mono_method_get_declaring_generic_method (method);
804 method = mono_class_inflate_generic_method_checked (method, &context, &error);
805 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
811 * mono_exception_walk_native_trace:
812 * \param ex The exception object whose frames should be walked
813 * \param func callback to call for each stack frame
814 * \param user_data data passed to the callback
815 * This function walks the stacktrace of an exception. For
816 * each frame the callback function is called with the relevant info.
817 * The walk ends when no more stack frames are found or when the callback
818 * returns a TRUE value.
822 mono_exception_walk_trace (MonoException *ex, MonoExceptionFrameWalk func, gpointer user_data)
824 MONO_REQ_GC_UNSAFE_MODE;
826 MonoDomain *domain = mono_domain_get ();
827 MonoArray *ta = ex->trace_ips;
833 len = mono_array_length (ta) >> 1;
834 for (i = 0; i < len; i++) {
835 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
836 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
837 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)ip);
840 if (func (NULL, ip, 0, FALSE, user_data))
843 MonoMethod *method = get_method_from_stack_frame (ji, generic_info);
844 if (func (method, ji->code_start, (char *) ip - (char *) ji->code_start, TRUE, user_data))
853 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
856 MonoDomain *domain = mono_domain_get ();
858 MonoArray *ta = exc->trace_ips;
859 MonoDebugSourceLocation *location;
863 /* Exception is not thrown yet */
864 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, 0, &error);
865 mono_error_set_pending_exception (&error);
869 len = mono_array_length (ta) >> 1;
871 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0, &error);
872 if (mono_error_set_pending_exception (&error))
875 for (i = skip; i < len; i++) {
877 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, &error);
878 if (!mono_error_ok (&error)) {
879 mono_error_set_pending_exception (&error);
882 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
883 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
886 ji = mono_jit_info_table_find (domain, (char *)ip);
888 /* Unmanaged frame */
889 mono_array_setref (res, i, sf);
893 g_assert (ji != NULL);
896 /* Can't resolve actual method */
897 method = jinfo_get_method (ji);
899 method = get_method_from_stack_frame (ji, generic_info);
900 if (jinfo_get_method (ji)->wrapper_type) {
904 s = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION);
905 MonoString *name = mono_string_new_checked (domain, s, &error);
907 if (!is_ok (&error)) {
908 mono_error_set_pending_exception (&error);
911 MONO_OBJECT_SETREF (sf, internal_method_name, name);
914 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, &error);
915 if (!mono_error_ok (&error)) {
916 mono_error_set_pending_exception (&error);
919 MONO_OBJECT_SETREF (sf, method, rm);
922 sf->method_index = ji->from_aot ? mono_aot_find_method_index (method) : 0xffffff;
923 sf->method_address = (gsize) ji->code_start;
924 sf->native_offset = (char *)ip - (char *)ji->code_start;
927 * mono_debug_lookup_source_location() returns both the file / line number information
928 * and the IL offset. Note that computing the IL offset is already an expensive
929 * operation, so we shouldn't call this method twice.
931 location = mono_debug_lookup_source_location (jinfo_get_method (ji), sf->native_offset, domain);
933 sf->il_offset = location->il_offset;
936 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (ji), sf->native_offset, NULL, &sp))
937 sf->il_offset = sp.il_offset;
942 if (need_file_info) {
943 if (location && location->source_file) {
944 MonoString *filename = mono_string_new_checked (domain, location->source_file, &error);
945 if (!is_ok (&error)) {
946 mono_error_set_pending_exception (&error);
949 MONO_OBJECT_SETREF (sf, filename, filename);
950 sf->line = location->row;
951 sf->column = location->column;
953 sf->line = sf->column = 0;
958 mono_debug_free_source_location (location);
959 mono_array_setref (res, i, sf);
966 mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
969 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
970 if (jit_tls && jit_tls->orig_ex_ctx_set)
971 start_ctx = &jit_tls->orig_ex_ctx;
973 mono_walk_stack_with_ctx (func, start_ctx, unwind_options, user_data);
976 * mono_walk_stack_with_ctx:
977 * Unwind the current thread starting at \p start_ctx.
978 * If \p start_ctx is null, we capture the current context.
981 mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
983 MonoContext extra_ctx;
984 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
985 MONO_ARCH_CONTEXT_DEF
987 if (!thread || !thread->jit_data)
991 mono_arch_flush_register_windows ();
993 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
994 MONO_INIT_CONTEXT_FROM_CURRENT (&extra_ctx);
996 MONO_INIT_CONTEXT_FROM_FUNC (&extra_ctx, mono_walk_stack_with_ctx);
998 start_ctx = &extra_ctx;
1001 mono_walk_stack_full (func, start_ctx, mono_domain_get (), (MonoJitTlsData *)thread->jit_data, mono_get_lmf (), unwind_options, user_data);
1005 * mono_walk_stack_with_state:
1006 * Unwind a thread described by \p state.
1008 * State must be valid (state->valid == TRUE).
1010 * If you are using this function to unwind another thread, make sure it is suspended.
1012 * If \p state is null, we capture the current context.
1015 mono_walk_stack_with_state (MonoJitStackWalk func, MonoThreadUnwindState *state, MonoUnwindOptions unwind_options, void *user_data)
1017 MonoThreadUnwindState extra_state;
1019 g_assert (!mono_thread_info_is_async_context ());
1020 if (!mono_thread_state_init_from_current (&extra_state))
1022 state = &extra_state;
1025 g_assert (state->valid);
1027 if (!state->unwind_data [MONO_UNWIND_DATA_DOMAIN])
1031 mono_walk_stack_full (func,
1033 (MonoDomain *)state->unwind_data [MONO_UNWIND_DATA_DOMAIN],
1034 (MonoJitTlsData *)state->unwind_data [MONO_UNWIND_DATA_JIT_TLS],
1035 (MonoLMF *)state->unwind_data [MONO_UNWIND_DATA_LMF],
1036 unwind_options, user_data);
1040 mono_walk_stack (MonoJitStackWalk func, MonoUnwindOptions options, void *user_data)
1042 MonoThreadUnwindState state;
1043 if (!mono_thread_state_init_from_current (&state))
1045 mono_walk_stack_with_state (func, &state, options, user_data);
1049 * mono_walk_stack_full:
1050 * \param func callback to call for each stack frame
1051 * \param domain starting appdomain, can be NULL to use the current domain
1052 * \param unwind_options what extra information the unwinder should gather
1053 * \param start_ctx starting state of the stack walk, can be NULL.
1054 * \param thread the thread whose stack to walk, can be NULL to use the current thread
1055 * \param lmf the LMF of \p thread, can be NULL to use the LMF of the current thread
1056 * \param user_data data passed to the callback
1057 * This function walks the stack of a thread, starting from the state
1058 * represented by \p start_ctx. For each frame the callback
1059 * function is called with the relevant info. The walk ends when no more
1060 * managed stack frames are found or when the callback returns a TRUE value.
1063 mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data)
1066 MonoContext ctx, new_ctx;
1067 StackFrameInfo frame;
1069 mgreg_t *reg_locations [MONO_MAX_IREGS];
1070 mgreg_t *new_reg_locations [MONO_MAX_IREGS];
1071 gboolean get_reg_locations = unwind_options & MONO_UNWIND_REG_LOCATIONS;
1072 gboolean async = mono_thread_info_is_async_context ();
1075 if (mono_llvm_only) {
1081 ips = get_unwind_backtrace ();
1082 for (l = ips; l; l = l->next) {
1083 guint8 *ip = (guint8*)l->data;
1084 memset (&frame, 0, sizeof (StackFrameInfo));
1085 frame.ji = mini_jit_info_table_find (domain, (char*)ip, &frame.domain);
1086 if (!frame.ji || frame.ji->is_trampoline)
1088 frame.type = FRAME_TYPE_MANAGED;
1089 frame.method = jinfo_get_method (frame.ji);
1090 // FIXME: Cannot lookup the actual method
1091 frame.actual_method = frame.method;
1092 if (frame.type == FRAME_TYPE_MANAGED) {
1093 if (!frame.method->wrapper_type || frame.method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
1094 frame.managed = TRUE;
1096 frame.native_offset = ip - (guint8*)frame.ji->code_start;
1097 frame.il_offset = -1;
1099 if (func (&frame, NULL, user_data))
1106 g_assert (start_ctx);
1109 /*The LMF will be null if the target have no managed frames.*/
1110 /* g_assert (lmf); */
1113 g_assert (unwind_options == MONO_UNWIND_NONE);
1115 memcpy (&ctx, start_ctx, sizeof (MonoContext));
1116 memset (reg_locations, 0, sizeof (reg_locations));
1118 unwinder_init (&unwinder);
1120 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
1122 res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, get_reg_locations ? new_reg_locations : NULL, &frame);
1126 if ((unwind_options & MONO_UNWIND_LOOKUP_IL_OFFSET) && frame.ji && !frame.ji->is_trampoline) {
1127 MonoDebugSourceLocation *source;
1129 source = mono_debug_lookup_source_location (jinfo_get_method (frame.ji), frame.native_offset, domain);
1131 il_offset = source->il_offset;
1134 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (frame.ji), frame.native_offset, NULL, &sp))
1135 il_offset = sp.il_offset;
1139 mono_debug_free_source_location (source);
1143 frame.il_offset = il_offset;
1145 if ((unwind_options & MONO_UNWIND_LOOKUP_ACTUAL_METHOD) && frame.ji && !frame.ji->is_trampoline) {
1146 frame.actual_method = get_method_from_stack_frame (frame.ji, get_generic_info_from_stack_frame (frame.ji, &ctx));
1148 frame.actual_method = frame.method;
1151 if (get_reg_locations)
1152 frame.reg_locations = reg_locations;
1154 if (func (&frame, &ctx, user_data))
1157 if (get_reg_locations) {
1158 for (i = 0; i < MONO_MAX_IREGS; ++i)
1159 if (new_reg_locations [i])
1160 reg_locations [i] = new_reg_locations [i];
1168 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
1169 MonoReflectionMethod **method,
1170 gint32 *iloffset, gint32 *native_offset,
1171 MonoString **file, gint32 *line, gint32 *column)
1174 MonoDomain *domain = mono_domain_get ();
1175 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1176 MonoLMF *lmf = mono_get_lmf ();
1177 MonoJitInfo *ji = NULL;
1178 MonoContext ctx, new_ctx;
1179 MonoDebugSourceLocation *location;
1180 MonoMethod *jmethod = NULL, *actual_method;
1181 StackFrameInfo frame;
1186 MONO_ARCH_CONTEXT_DEF;
1188 if (mono_llvm_only) {
1190 MonoDomain *frame_domain;
1191 guint8 *frame_ip = NULL;
1193 /* FIXME: Generalize this code with an interface which returns an array of StackFrame structures */
1195 ips = get_unwind_backtrace ();
1196 for (l = ips; l && skip >= 0; l = l->next) {
1197 guint8 *ip = (guint8*)l->data;
1201 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &frame_domain);
1202 if (!ji || ji->is_trampoline)
1205 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1206 jmethod = jinfo_get_method (ji);
1207 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1214 /* No way to resolve generic instances */
1215 actual_method = jmethod;
1216 *native_offset = frame_ip - (guint8*)ji->code_start;
1218 mono_arch_flush_register_windows ();
1220 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1221 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
1223 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
1226 unwinder_init (&unwinder);
1231 res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1234 switch (frame.type) {
1235 case FRAME_TYPE_MANAGED_TO_NATIVE:
1236 case FRAME_TYPE_DEBUGGER_INVOKE:
1237 case FRAME_TYPE_TRAMPOLINE:
1238 case FRAME_TYPE_INTERP_TO_MANAGED:
1240 case FRAME_TYPE_INTERP:
1245 *native_offset = frame.native_offset;
1247 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1248 jmethod = jinfo_get_method (ji);
1249 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1254 } while (skip >= 0);
1256 if (frame.type == FRAME_TYPE_INTERP) {
1257 jmethod = frame.method;
1258 actual_method = frame.actual_method;
1259 *native_offset = frame.native_offset;
1261 actual_method = get_method_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, &ctx));
1265 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, actual_method, NULL, &error);
1266 if (!mono_error_ok (&error)) {
1267 mono_error_set_pending_exception (&error);
1270 mono_gc_wbarrier_generic_store (method, (MonoObject*) rm);
1272 if (il_offset != -1) {
1273 location = mono_debug_lookup_source_location_by_il (jmethod, il_offset, domain);
1275 location = mono_debug_lookup_source_location (jmethod, *native_offset, domain);
1278 *iloffset = location->il_offset;
1282 if (need_file_info) {
1284 MonoString *filename = mono_string_new_checked (domain, location->source_file, &error);
1285 if (!is_ok (&error)) {
1286 mono_error_set_pending_exception (&error);
1289 mono_gc_wbarrier_generic_store (file, (MonoObject*)filename);
1290 *line = location->row;
1291 *column = location->column;
1294 *line = *column = 0;
1298 mono_debug_free_source_location (location);
1304 get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
1307 MonoClass *catch_class = ei->data.catch_class;
1308 MonoType *inflated_type;
1309 MonoGenericContext context;
1311 /*MonoJitExceptionInfo::data is an union used by filter and finally clauses too.*/
1312 if (!catch_class || ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
1315 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
1317 context = get_generic_context_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, ctx));
1319 /* FIXME: we shouldn't inflate but instead put the
1320 type in the rgctx and fetch it from there. It
1321 might be a good idea to do this lazily, i.e. only
1322 when the exception is actually thrown, so as not to
1323 waste space for exception clauses which might never
1325 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
1326 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
1328 catch_class = mono_class_from_mono_type (inflated_type);
1329 mono_metadata_free_type (inflated_type);
1335 * mini_jit_info_table_find_ext:
1337 * Same as mono_jit_info_table_find, but search all the domains of the current thread
1338 * if ADDR is not found in DOMAIN. The domain where the method was found is stored into
1339 * OUT_DOMAIN if it is not NULL.
1342 mini_jit_info_table_find_ext (MonoDomain *domain, char *addr, gboolean allow_trampolines, MonoDomain **out_domain)
1345 MonoInternalThread *t = mono_thread_internal_current ();
1351 ji = mono_jit_info_table_find_internal (domain, addr, TRUE, allow_trampolines);
1354 *out_domain = domain;
1358 /* maybe it is shared code, so we also search in the root domain */
1359 if (domain != mono_get_root_domain ()) {
1360 ji = mono_jit_info_table_find_internal (mono_get_root_domain (), addr, TRUE, allow_trampolines);
1363 *out_domain = mono_get_root_domain ();
1371 refs = (gpointer *)((t->appdomain_refs) ? *(gpointer *) t->appdomain_refs : NULL);
1372 for (; refs && *refs; refs++) {
1373 if (*refs != domain && *refs != mono_get_root_domain ()) {
1374 ji = mono_jit_info_table_find_internal ((MonoDomain*) *refs, addr, TRUE, allow_trampolines);
1377 *out_domain = (MonoDomain*) *refs;
1387 mini_jit_info_table_find (MonoDomain *domain, char *addr, MonoDomain **out_domain)
1389 return mini_jit_info_table_find_ext (domain, addr, FALSE, out_domain);
1392 /* Class lazy loading functions */
1393 static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute")
1396 * wrap_non_exception_throws:
1398 * Determine whenever M's assembly has a RuntimeCompatibilityAttribute with the
1399 * WrapNonExceptionThrows flag set.
1402 wrap_non_exception_throws (MonoMethod *m)
1405 MonoAssembly *ass = m->klass->image->assembly;
1406 MonoCustomAttrInfo* attrs;
1409 gboolean val = FALSE;
1412 if (ass->wrap_non_exception_throws_inited)
1413 return ass->wrap_non_exception_throws;
1415 klass = mono_class_get_runtime_compat_attr_class ();
1417 attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
1418 mono_error_cleanup (&error); /* FIXME don't swallow the error */
1420 for (i = 0; i < attrs->num_attrs; ++i) {
1421 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1423 int num_named, named_type, name_len;
1426 if (!attr->ctor || attr->ctor->klass != klass)
1428 /* Decode the RuntimeCompatibilityAttribute. See reflection.c */
1429 p = (const char*)attr->data;
1430 g_assert (read16 (p) == 0x0001);
1432 num_named = read16 (p);
1438 /* data_type = *p; */
1441 if (named_type != 0x54)
1443 name_len = mono_metadata_decode_blob_size (p, &p);
1444 name = (char *)g_malloc (name_len + 1);
1445 memcpy (name, p, name_len);
1446 name [name_len] = 0;
1448 g_assert (!strcmp (name, "WrapNonExceptionThrows"));
1450 /* The value is a BOOLEAN */
1453 mono_custom_attrs_free (attrs);
1456 ass->wrap_non_exception_throws = val;
1457 mono_memory_barrier ();
1458 ass->wrap_non_exception_throws_inited = TRUE;
1463 #define MAX_UNMANAGED_BACKTRACE 128
1465 build_native_trace (MonoError *error)
1468 /* This puppy only makes sense on mobile, IOW, ARM. */
1469 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
1471 void *native_trace [MAX_UNMANAGED_BACKTRACE];
1474 size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
1480 res = mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, size, error);
1481 return_val_if_nok (error, NULL);
1483 for (i = 0; i < size; i++)
1484 mono_array_set (res, gpointer, i, native_trace [i]);
1492 setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, GList **trace_ips)
1495 *trace_ips = g_list_reverse (*trace_ips);
1497 MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
1498 mono_error_assert_ok (&error);
1499 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
1500 MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace (&error));
1501 mono_error_assert_ok (&error);
1502 if (dynamic_methods) {
1503 /* These methods could go away anytime, so save a reference to them in the exception object */
1505 MonoMList *list = NULL;
1507 for (l = dynamic_methods; l; l = l->next) {
1509 MonoDomain *domain = mono_domain_get ();
1511 if (domain->method_to_dyn_method) {
1512 mono_domain_lock (domain);
1513 dis_link = (guint32)(size_t)g_hash_table_lookup (domain->method_to_dyn_method, l->data);
1514 mono_domain_unlock (domain);
1516 MonoObject *o = mono_gchandle_get_target (dis_link);
1518 list = mono_mlist_prepend_checked (list, o, &error);
1519 mono_error_assert_ok (&error);
1525 MONO_OBJECT_SETREF (mono_ex, dynamic_methods, list);
1528 g_list_free (*trace_ips);
1533 * mono_handle_exception_internal_first_pass:
1535 * The first pass of exception handling. Unwind the stack until a catch clause which can catch
1536 * OBJ is found. Run the index of the filter clause which caught the exception into
1537 * OUT_FILTER_IDX. Return TRUE if the exception is caught, FALSE otherwise.
1540 mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filter_idx, MonoJitInfo **out_ji, MonoJitInfo **out_prev_ji, MonoObject *non_exception)
1543 MonoDomain *domain = mono_domain_get ();
1544 MonoJitInfo *ji = NULL;
1545 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1546 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1547 MonoLMF *lmf = mono_get_lmf ();
1548 GList *trace_ips = NULL;
1549 GSList *dynamic_methods = NULL;
1550 MonoException *mono_ex;
1551 gboolean stack_overflow = FALSE;
1552 MonoContext initial_ctx;
1554 int frame_count = 0;
1561 g_assert (ctx != NULL);
1563 if (obj == (MonoObject *)domain->stack_overflow_ex)
1564 stack_overflow = TRUE;
1566 mono_ex = (MonoException*)obj;
1567 MonoArray *initial_trace_ips = mono_ex->trace_ips;
1568 if (initial_trace_ips) {
1569 int len = mono_array_length (initial_trace_ips) >> 1;
1571 for (i = 0; i < (len - 1); i++) {
1572 gpointer ip = mono_array_get (initial_trace_ips, gpointer, i * 2 + 0);
1573 gpointer generic_info = mono_array_get (initial_trace_ips, gpointer, i * 2 + 1);
1574 trace_ips = g_list_prepend (trace_ips, ip);
1575 trace_ips = g_list_prepend (trace_ips, generic_info);
1579 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1580 mono_error_assert_ok (&error);
1585 call_filter = (int (*) (MonoContext *, void *))mono_get_call_filter ();
1587 g_assert (jit_tls->end_of_stack);
1588 g_assert (jit_tls->abort_func);
1591 *out_filter_idx = -1;
1595 *out_prev_ji = NULL;
1599 unwinder_init (&unwinder);
1602 MonoContext new_ctx;
1604 int clause_index_start = 0;
1605 gboolean unwind_res = TRUE;
1607 StackFrameInfo frame;
1612 unwind_res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1614 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1615 g_slist_free (dynamic_methods);
1619 switch (frame.type) {
1620 case FRAME_TYPE_DEBUGGER_INVOKE:
1621 case FRAME_TYPE_MANAGED_TO_NATIVE:
1622 case FRAME_TYPE_TRAMPOLINE:
1623 case FRAME_TYPE_INTERP_TO_MANAGED:
1626 case FRAME_TYPE_INTERP:
1627 case FRAME_TYPE_MANAGED:
1630 g_assert_not_reached ();
1634 in_interp = frame.type == FRAME_TYPE_INTERP;
1639 ip = (guint8*)ji->code_start + frame.native_offset;
1641 ip = MONO_CONTEXT_GET_IP (ctx);
1644 method = jinfo_get_method (ji);
1645 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1647 if (mini_get_debug_options ()->reverse_pinvoke_exceptions && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
1648 g_error ("A native frame was found while unwinding the stack after an exception.\n"
1649 "The native frame called the managed method:\n%s\n",
1650 mono_method_full_name (method, TRUE));
1653 if (method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
1654 // avoid giant stack traces during a stack overflow
1655 if (frame_count < 1000) {
1656 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1657 trace_ips = g_list_prepend (trace_ips, get_generic_info_from_stack_frame (ji, ctx));
1661 if (method->dynamic)
1662 dynamic_methods = g_slist_prepend (dynamic_methods, method);
1664 if (stack_overflow) {
1665 if (MONO_ARCH_STACK_GROWS_UP)
1666 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1668 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1670 free_stack = 0xffffff;
1673 for (i = clause_index_start; i < ji->num_clauses; i++) {
1674 MonoJitExceptionInfo *ei = &ji->clauses [i];
1675 gboolean filtered = FALSE;
1678 * During stack overflow, wait till the unwinding frees some stack
1679 * space before running handlers/finalizers.
1681 if (free_stack <= (64 * 1024))
1684 if (is_address_protected (ji, ei, ip)) {
1686 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1689 * Have to unwrap RuntimeWrappedExceptions if the
1690 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1692 if (non_exception && !wrap_non_exception_throws (method))
1693 ex_obj = non_exception;
1697 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1698 #ifndef DISABLE_PERFCOUNTERS
1699 mono_perfcounters->exceptions_filters++;
1702 #ifndef MONO_CROSS_COMPILE
1703 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1705 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1707 /* Can't pass the ex object in a register yet to filter clauses, because call_filter () might not support it */
1708 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1710 g_assert (!ji->from_llvm);
1711 /* store the exception object in bp + ei->exvar_offset */
1712 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1716 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1718 * Pass the original il clause index to the landing pad so it can
1719 * branch to the landing pad associated with the il clause.
1720 * This is needed because llvm compiled code assumes that the EH
1721 * code always branches to the innermost landing pad.
1724 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1727 mono_debugger_agent_begin_exception_filter (mono_ex, ctx, &initial_ctx);
1728 filtered = call_filter (ctx, ei->data.filter);
1729 mono_debugger_agent_end_exception_filter (mono_ex, ctx, &initial_ctx);
1730 if (filtered && out_filter_idx)
1731 *out_filter_idx = filter_idx;
1737 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1738 g_slist_free (dynamic_methods);
1739 /* mono_debugger_agent_handle_exception () needs this */
1740 mini_set_abort_threshold (ctx);
1741 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1746 MonoError isinst_error;
1747 error_init (&isinst_error);
1748 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (ex_obj, catch_class, &error)) {
1749 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1750 g_slist_free (dynamic_methods);
1755 /* mono_debugger_agent_handle_exception () needs this */
1757 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1760 mono_error_cleanup (&isinst_error);
1767 g_assert_not_reached ();
1771 * mono_handle_exception_internal:
1772 * \param ctx saved processor state
1773 * \param obj the exception object
1774 * \param resume whenever to resume unwinding based on the state in \c MonoJitTlsData.
1777 mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resume, MonoJitInfo **out_ji)
1780 MonoDomain *domain = mono_domain_get ();
1781 MonoJitInfo *ji, *prev_ji;
1782 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1783 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1784 MonoLMF *lmf = mono_get_lmf ();
1785 MonoException *mono_ex;
1786 gboolean stack_overflow = FALSE;
1787 MonoContext initial_ctx;
1789 int frame_count = 0;
1790 gint32 filter_idx, first_filter_idx = 0;
1793 MonoObject *non_exception = NULL;
1797 g_assert (ctx != NULL);
1799 MonoException *ex = mono_get_exception_null_reference ();
1800 MonoString *msg = mono_string_new_checked (domain, "Object reference not set to an instance of an object", &error);
1801 mono_error_assert_ok (&error);
1802 MONO_OBJECT_SETREF (ex, message, msg);
1803 obj = (MonoObject *)ex;
1807 * Allocate a new exception object instead of the preconstructed ones.
1809 if (obj == (MonoObject *)domain->stack_overflow_ex) {
1811 * It is not a good idea to try and put even more pressure on the little stack available.
1812 * obj = mono_get_exception_stack_overflow ();
1814 stack_overflow = TRUE;
1816 else if (obj == (MonoObject *)domain->null_reference_ex) {
1817 obj = (MonoObject *)mono_get_exception_null_reference ();
1820 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1821 mono_error_assert_ok (&error);
1822 non_exception = obj;
1823 obj = (MonoObject *)mono_get_exception_runtime_wrapped_checked (obj, &error);
1824 mono_error_assert_ok (&error);
1827 mono_ex = (MonoException*)obj;
1829 if (mini_get_debug_options ()->suspend_on_exception) {
1830 mono_runtime_printf_err ("Exception thrown, suspending...");
1835 if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1836 mono_ex = (MonoException*)obj;
1838 mono_error_assert_ok (&error);
1842 if (mono_ex && jit_tls->class_cast_from) {
1843 if (!strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
1844 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1845 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1846 char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
1847 mono_ex->message = mono_string_new_checked (domain, msg, &error);
1850 if (!is_ok (&error)) {
1851 mono_runtime_printf_err ("Error creating class cast exception message '%s'\n", msg);
1852 mono_error_assert_ok (&error);
1856 if (!strcmp (mono_ex->object.vtable->klass->name, "ArrayTypeMismatchException")) {
1857 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1858 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1859 char *msg = g_strdup_printf ("Source array of type '%s' cannot be cast to destination array type '%s'.", from_name, to_name);
1860 mono_ex->message = mono_string_new_checked (domain, msg, &error);
1863 if (!is_ok (&error)) {
1864 mono_runtime_printf_err ("Error creating array type mismatch exception message '%s'\n", msg);
1865 mono_error_assert_ok (&error);
1872 call_filter = (int (*)(MonoContext *, void*))mono_get_call_filter ();
1874 g_assert (jit_tls->end_of_stack);
1875 g_assert (jit_tls->abort_func);
1878 * We set orig_ex_ctx_set to TRUE/FALSE around profiler calls to make sure it doesn't
1879 * end up being TRUE on any code path.
1881 memcpy (&jit_tls->orig_ex_ctx, ctx, sizeof (MonoContext));
1886 MonoContext ctx_cp = *ctx;
1887 if (mono_trace_is_enabled ()) {
1888 MonoMethod *system_exception_get_message = mono_class_get_method_from_name (mono_defaults.exception_class, "get_Message", 0);
1889 MonoMethod *get_message = system_exception_get_message == NULL ? NULL : mono_object_get_virtual_method (obj, system_exception_get_message);
1890 MonoObject *message;
1891 const char *type_name = mono_class_get_name (mono_object_class (mono_ex));
1893 if (get_message == NULL) {
1895 } else if (!strcmp (type_name, "OutOfMemoryException") || !strcmp (type_name, "StackOverflowException")) {
1897 msg = g_strdup_printf ("(No exception message for: %s)\n", type_name);
1899 MonoObject *exc = NULL;
1900 message = mono_runtime_try_invoke (get_message, obj, NULL, &exc, &error);
1901 g_assert (exc == NULL);
1902 mono_error_assert_ok (&error);
1906 msg = mono_string_to_utf8_checked ((MonoString *) message, &error);
1907 if (!is_ok (&error)) {
1908 mono_error_cleanup (&error);
1909 msg = g_strdup ("(error while display System.Exception.Message property)");
1912 msg = g_strdup ("(System.Exception.Message property not available)");
1915 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);
1917 if (mono_ex && mono_trace_eval_exception (mono_object_class (mono_ex)))
1918 mono_print_thread_dump_from_ctx (ctx);
1920 jit_tls->orig_ex_ctx_set = TRUE;
1921 mono_profiler_exception_thrown (obj);
1922 jit_tls->orig_ex_ctx_set = FALSE;
1924 res = mono_handle_exception_internal_first_pass (&ctx_cp, obj, &first_filter_idx, &ji, &prev_ji, non_exception);
1927 if (mini_get_debug_options ()->break_on_exc)
1929 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1931 if (mini_get_debug_options ()->suspend_on_unhandled) {
1932 mono_runtime_printf_err ("Unhandled exception, suspending...");
1937 // FIXME: This runs managed code so it might cause another stack overflow when
1938 // we are handling a stack overflow
1939 mini_set_abort_threshold (ctx);
1940 mono_unhandled_exception (obj);
1942 gboolean unhandled = FALSE;
1945 * The exceptions caught by the mono_runtime_invoke_checked () calls
1946 * in the threadpool needs to be treated as unhandled (#669836).
1948 * FIXME: The check below is hackish, but its hard to distinguish
1949 * these runtime invoke calls from others in the runtime.
1951 if (ji && jinfo_get_method (ji)->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1952 if (prev_ji && jinfo_get_method (prev_ji) == mono_defaults.threadpool_perform_wait_callback_method)
1957 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1959 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, &ctx_cp);
1968 unwinder_init (&unwinder);
1971 MonoContext new_ctx;
1973 int clause_index_start = 0;
1974 gboolean unwind_res = TRUE;
1975 StackFrameInfo frame;
1980 ji = jit_tls->resume_state.ji;
1981 new_ctx = jit_tls->resume_state.new_ctx;
1982 clause_index_start = jit_tls->resume_state.clause_index;
1983 lmf = jit_tls->resume_state.lmf;
1984 first_filter_idx = jit_tls->resume_state.first_filter_idx;
1985 filter_idx = jit_tls->resume_state.filter_idx;
1988 unwind_res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1990 *(mono_get_lmf_addr ()) = lmf;
1992 jit_tls->abort_func (obj);
1993 g_assert_not_reached ();
1995 switch (frame.type) {
1996 case FRAME_TYPE_DEBUGGER_INVOKE:
1997 case FRAME_TYPE_MANAGED_TO_NATIVE:
1998 case FRAME_TYPE_TRAMPOLINE:
2001 case FRAME_TYPE_INTERP_TO_MANAGED:
2003 case FRAME_TYPE_INTERP:
2004 case FRAME_TYPE_MANAGED:
2007 g_assert_not_reached ();
2010 in_interp = frame.type == FRAME_TYPE_INTERP;
2015 ip = (guint8*)ji->code_start + frame.native_offset;
2017 ip = MONO_CONTEXT_GET_IP (ctx);
2019 method = jinfo_get_method (ji);
2021 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
2023 if (stack_overflow) {
2024 if (MONO_ARCH_STACK_GROWS_UP)
2025 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
2027 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
2029 free_stack = 0xffffff;
2032 for (i = clause_index_start; i < ji->num_clauses; i++) {
2033 MonoJitExceptionInfo *ei = &ji->clauses [i];
2034 gboolean filtered = FALSE;
2037 * During stack overflow, wait till the unwinding frees some stack
2038 * space before running handlers/finalizers.
2040 if (free_stack <= (64 * 1024))
2043 if (is_address_protected (ji, ei, ip)) {
2045 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
2048 * Have to unwrap RuntimeWrappedExceptions if the
2049 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
2051 if (non_exception && !wrap_non_exception_throws (method))
2052 ex_obj = non_exception;
2056 if (((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER))) {
2057 #ifndef MONO_CROSS_COMPILE
2058 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
2059 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
2061 g_assert (!ji->from_llvm);
2062 /* store the exception object in bp + ei->exvar_offset */
2063 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
2068 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
2070 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
2073 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2075 * Filter clauses should only be run in the
2076 * first pass of exception handling.
2078 filtered = (filter_idx == first_filter_idx);
2082 error_init (&error);
2083 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
2084 mono_object_isinst_checked (ex_obj, catch_class, &error)) || filtered) {
2086 * This guards against the situation that we abort a thread that is executing a finally clause
2087 * that was called by the EH machinery. It won't have a guard trampoline installed, so we must
2088 * check for this situation here and resume interruption if we are below the guarded block.
2090 if (G_UNLIKELY (jit_tls->handler_block_return_address)) {
2091 gboolean is_outside = FALSE;
2092 gpointer prot_bp = MONO_CONTEXT_GET_BP (&jit_tls->handler_block_context);
2093 gpointer catch_bp = MONO_CONTEXT_GET_BP (ctx);
2094 //FIXME make this stack direction aware
2095 if (catch_bp > prot_bp) {
2097 } else if (catch_bp == prot_bp) {
2098 /* Can be either try { try { } catch {} } finally {} or try { try { } finally {} } catch {}
2099 * So we check if the catch handler_start is protected by the guarded handler protected region
2102 * If there is an outstanding guarded_block return address, it means the current thread must be aborted.
2103 * This is the only way to reach out the guarded block as other cases are handled by the trampoline.
2104 * There aren't any further finally/fault handler blocks down the stack over this exception.
2105 * This must be ensured by the code that installs the guard trampoline.
2107 g_assert (ji == mini_jit_info_table_find (domain, (char *)MONO_CONTEXT_GET_IP (&jit_tls->handler_block_context), NULL));
2109 if (!is_address_protected (ji, jit_tls->handler_block, ei->handler_start)) {
2114 jit_tls->handler_block_return_address = NULL;
2115 jit_tls->handler_block = NULL;
2116 mono_thread_resume_interruption (TRUE); /*We ignore the exception here, it will be raised later*/
2120 if (mono_trace_is_enabled () && mono_trace_eval (method))
2121 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2122 jit_tls->orig_ex_ctx_set = TRUE;
2123 mono_profiler_exception_clause_handler (method, ei->flags, i);
2124 jit_tls->orig_ex_ctx_set = FALSE;
2125 mini_set_abort_threshold (ctx);
2129 * ctx->pc points into the interpreter, after the call which transitioned to
2130 * JITted code. Store the unwind state into the
2131 * interpeter state, then resume, the interpreter will unwind itself until
2132 * it reaches the target frame and will continue execution from there.
2133 * The resuming is kinda hackish, from the native code standpoint, it looks
2134 * like the call which transitioned to JITted code has succeeded, but the
2135 * return value register etc. is not set, so we have to be careful.
2137 mono_interp_set_resume_state (jit_tls, mono_ex, frame.interp_frame, ei->handler_start);
2138 /* Undo the IP adjustment done by mono_arch_unwind_frame () */
2139 #if defined(TARGET_AMD64)
2140 ctx->gregs [AMD64_RIP] ++;
2141 #elif defined(TARGET_ARM)
2143 if (mono_arm_thumb_supported ())
2145 #elif defined(TARGET_ARM64)
2151 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2154 #ifndef DISABLE_PERFCOUNTERS
2155 mono_perfcounters->exceptions_depth += frame_count;
2157 if (obj == (MonoObject *)domain->stack_overflow_ex)
2158 jit_tls->handling_stack_ovf = FALSE;
2162 mono_error_cleanup (&error);
2163 if (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
2164 if (mono_trace_is_enabled () && mono_trace_eval (method))
2165 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2166 jit_tls->orig_ex_ctx_set = TRUE;
2167 mono_profiler_exception_clause_handler (method, ei->flags, i);
2168 jit_tls->orig_ex_ctx_set = FALSE;
2169 mini_set_abort_threshold (ctx);
2170 call_filter (ctx, ei->handler_start);
2172 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2173 if (mono_trace_is_enabled () && mono_trace_eval (method))
2174 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2175 jit_tls->orig_ex_ctx_set = TRUE;
2176 mono_profiler_exception_clause_handler (method, ei->flags, i);
2177 jit_tls->orig_ex_ctx_set = FALSE;
2178 #ifndef DISABLE_PERFCOUNTERS
2179 mono_perfcounters->exceptions_finallys++;
2182 if (ji->from_llvm) {
2184 * LLVM compiled finally handlers follow the design
2185 * of the c++ ehabi, i.e. they call a resume function
2186 * at the end instead of returning to the caller.
2187 * So save the exception handling state,
2188 * mono_resume_unwind () will call us again to continue
2191 jit_tls->resume_state.ex_obj = obj;
2192 jit_tls->resume_state.ji = ji;
2193 jit_tls->resume_state.clause_index = i + 1;
2194 jit_tls->resume_state.ctx = *ctx;
2195 jit_tls->resume_state.new_ctx = new_ctx;
2196 jit_tls->resume_state.lmf = lmf;
2197 jit_tls->resume_state.first_filter_idx = first_filter_idx;
2198 jit_tls->resume_state.filter_idx = filter_idx;
2199 mini_set_abort_threshold (ctx);
2200 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2203 mini_set_abort_threshold (ctx);
2205 mono_interp_run_finally (&frame, i, ei->handler_start);
2207 call_filter (ctx, ei->handler_start);
2213 jit_tls->orig_ex_ctx_set = TRUE;
2214 mono_profiler_exception_method_leave (method);
2215 jit_tls->orig_ex_ctx_set = FALSE;
2220 g_assert_not_reached ();
2224 * mono_debugger_run_finally:
2225 * \param start_ctx saved processor state
2226 * This method is called by the Mono Debugger to call all \c finally clauses of the
2227 * current stack frame. It's used when the user issues a \c return command to make
2228 * the current stack frame return. After returning from this method, the debugger
2229 * unwinds the stack one frame and gives control back to the user.
2230 * NOTE: This method is only used when running inside the Mono Debugger.
2233 mono_debugger_run_finally (MonoContext *start_ctx)
2235 static int (*call_filter) (MonoContext *, gpointer) = NULL;
2236 MonoDomain *domain = mono_domain_get ();
2237 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2238 MonoLMF *lmf = mono_get_lmf ();
2239 MonoContext ctx, new_ctx;
2240 MonoJitInfo *ji, rji;
2245 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
2246 if (!ji || ji == (gpointer)-1)
2250 call_filter = (int (*)(MonoContext *, void *))mono_get_call_filter ();
2252 for (i = 0; i < ji->num_clauses; i++) {
2253 MonoJitExceptionInfo *ei = &ji->clauses [i];
2255 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (&ctx)) &&
2256 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
2257 call_filter (&ctx, ei->handler_start);
2263 * mono_handle_exception:
2264 * \param ctx saved processor state
2265 * \param obj the exception object
2267 * Handle the exception OBJ starting from the state CTX. Modify CTX to point to the handler clause if the exception is caught, and
2271 mono_handle_exception (MonoContext *ctx, MonoObject *obj)
2273 MONO_REQ_GC_UNSAFE_MODE;
2275 #ifndef DISABLE_PERFCOUNTERS
2276 mono_perfcounters->exceptions_thrown++;
2279 return mono_handle_exception_internal (ctx, obj, FALSE, NULL);
2282 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2284 #ifndef MONO_ARCH_USE_SIGACTION
2285 #error "Can't use sigaltstack without sigaction"
2288 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
2291 mono_setup_altstack (MonoJitTlsData *tls)
2295 guint8 *staddr = NULL;
2297 if (mono_running_on_valgrind ())
2300 mono_thread_info_get_stack_bounds (&staddr, &stsize);
2304 tls->end_of_stack = staddr + stsize;
2305 tls->stack_size = stsize;
2307 /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
2309 tls->stack_ovf_guard_base = staddr + mono_pagesize ();
2310 tls->stack_ovf_guard_size = ALIGN_TO (8 * 4096, mono_pagesize ());
2312 g_assert ((guint8*)&sa >= (guint8*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size);
2314 if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
2315 /* mprotect can fail for the main thread stack */
2316 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);
2317 g_assert (gaddr == tls->stack_ovf_guard_base);
2318 tls->stack_ovf_valloced = TRUE;
2321 /* Setup an alternate signal stack */
2322 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);
2323 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2325 g_assert (tls->signal_stack);
2327 sa.ss_sp = tls->signal_stack;
2328 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2330 g_assert (sigaltstack (&sa, NULL) == 0);
2332 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);
2336 mono_free_altstack (MonoJitTlsData *tls)
2341 sa.ss_sp = tls->signal_stack;
2342 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2343 sa.ss_flags = SS_DISABLE;
2344 err = sigaltstack (&sa, NULL);
2345 g_assert (err == 0);
2347 if (tls->signal_stack)
2348 mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MEM_ACCOUNT_EXCEPTIONS);
2349 if (tls->stack_ovf_valloced)
2350 mono_vfree (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MEM_ACCOUNT_EXCEPTIONS);
2352 mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
2355 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2358 mono_setup_altstack (MonoJitTlsData *tls)
2363 mono_free_altstack (MonoJitTlsData *tls)
2367 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2370 try_restore_stack_protection (MonoJitTlsData *jit_tls, int extra_bytes)
2372 gint32 unprotect_size = jit_tls->stack_ovf_guard_size;
2373 /* we need to leave some room for throwing the exception */
2374 while (unprotect_size >= 0 && (char*)jit_tls->stack_ovf_guard_base + unprotect_size > ((char*)&unprotect_size - extra_bytes))
2375 unprotect_size -= mono_pagesize ();
2376 /* at this point we could try and build a new domain->stack_overflow_ex, but only if there
2377 * is sufficient stack
2379 //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);
2381 mono_mprotect (jit_tls->stack_ovf_guard_base, unprotect_size, MONO_MMAP_NONE);
2382 return unprotect_size == jit_tls->stack_ovf_guard_size;
2385 static G_GNUC_UNUSED void
2386 try_more_restore (void)
2388 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2389 if (try_restore_stack_protection (jit_tls, 500))
2390 jit_tls->restore_stack_prot = NULL;
2393 static G_GNUC_UNUSED void
2394 restore_stack_protection (void)
2396 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2397 MonoException *ex = mono_domain_get ()->stack_overflow_ex;
2398 /* if we can't restore the stack protection, keep a callback installed so
2399 * we'll try to restore as much stack as we can at each return from unmanaged
2402 if (try_restore_stack_protection (jit_tls, 4096))
2403 jit_tls->restore_stack_prot = NULL;
2405 jit_tls->restore_stack_prot = try_more_restore_tramp;
2406 /* here we also throw a stack overflow exception */
2407 ex->trace_ips = NULL;
2408 ex->stack_trace = NULL;
2409 mono_raise_exception (ex);
2413 mono_altstack_restore_prot (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
2415 MONO_REQ_GC_UNSAFE_MODE;
2417 void (*func)(void) = (void (*)(void))tramp_data;
2423 mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, guint8* fault_addr)
2428 /* we got a stack overflow in the soft-guard pages
2429 * There are two cases:
2430 * 1) managed code caused the overflow: we unprotect the soft-guard page
2431 * and let the arch-specific code trigger the exception handling mechanism
2432 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
2433 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
2434 * and hope we can continue with those enabled, at least until the hard-guard page
2435 * is hit. The alternative to continuing here is to just print a message and abort.
2436 * We may add in the future the code to protect the pages again in the codepath
2437 * when we return from unmanaged to managed code.
2439 if (jit_tls->stack_ovf_guard_size && fault_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
2440 fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
2441 /* we unprotect the minimum amount we can */
2443 gboolean handled = FALSE;
2445 guard_size = jit_tls->stack_ovf_guard_size - (mono_pagesize () * SIZEOF_VOID_P / 4);
2446 while (guard_size && fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + guard_size) {
2447 guard_size -= mono_pagesize ();
2449 guard_size = jit_tls->stack_ovf_guard_size - guard_size;
2450 /*fprintf (stderr, "unprotecting: %d\n", guard_size);*/
2451 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);
2452 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2454 mono_arch_handle_altstack_exception (ctx, siginfo, fault_addr, TRUE);
2459 /* We print a message: after this even managed stack overflows
2460 * may crash the runtime
2462 mono_runtime_printf_err ("Stack overflow in unmanaged: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2463 if (!jit_tls->handling_stack_ovf) {
2464 jit_tls->restore_stack_prot = restore_stack_protection_tramp;
2465 jit_tls->handling_stack_ovf = 1;
2467 /*fprintf (stderr, "Already handling stack overflow\n");*/
2476 MonoMethod *omethod;
2478 } PrintOverflowUserData;
2480 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2482 print_overflow_stack_frame (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2484 MonoMethod *method = NULL;
2485 PrintOverflowUserData *user_data = (PrintOverflowUserData *)data;
2488 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2489 method = jinfo_get_method (frame->ji);
2492 if (user_data->count == 0) {
2493 /* The first frame is in its prolog, so a line number cannot be computed */
2494 user_data->count ++;
2498 /* If this is a one method overflow, skip the other instances */
2499 if (method == user_data->omethod)
2502 location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2503 mono_runtime_printf_err (" %s", location);
2506 if (user_data->count == 1) {
2507 mono_runtime_printf_err (" <...>");
2508 user_data->omethod = method;
2510 user_data->omethod = NULL;
2513 user_data->count ++;
2515 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2522 mono_handle_hard_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
2524 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2525 PrintOverflowUserData ud;
2529 /* we don't do much now, but we can warn the user with a useful message */
2530 mono_runtime_printf_err ("Stack overflow: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2532 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2533 mono_sigctx_to_monoctx (ctx, &mctx);
2535 mono_runtime_printf_err ("Stacktrace:");
2537 memset (&ud, 0, sizeof (ud));
2539 mono_walk_stack_with_ctx (print_overflow_stack_frame, &mctx, MONO_UNWIND_LOOKUP_ACTUAL_METHOD, &ud);
2541 if (ji && !ji->is_trampoline && jinfo_get_method (ji))
2542 mono_runtime_printf_err ("At %s", mono_method_full_name (jinfo_get_method (ji), TRUE));
2544 mono_runtime_printf_err ("At <unmanaged>.");
2551 print_stack_frame_to_stderr (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2553 MonoMethod *method = NULL;
2555 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2556 method = jinfo_get_method (frame->ji);
2559 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2560 mono_runtime_printf_err (" %s", location);
2563 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2568 static G_GNUC_UNUSED gboolean
2569 print_stack_frame_to_string (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2571 GString *p = (GString*)data;
2572 MonoMethod *method = NULL;
2574 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2575 method = jinfo_get_method (frame->ji);
2577 if (method && frame->domain) {
2578 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
2579 g_string_append_printf (p, " %s\n", location);
2582 g_string_append_printf (p, " at <unknown> <0x%05x>\n", frame->native_offset);
2587 #ifndef MONO_CROSS_COMPILE
2589 static void print_process_map (void)
2592 FILE *fp = fopen ("/proc/self/maps", "r");
2596 mono_runtime_printf_err ("no /proc/self/maps, not on linux?\n");
2600 mono_runtime_printf_err ("/proc/self/maps:");
2602 while (fgets (line, sizeof (line), fp)) {
2604 size_t len = strlen (line) - 1;
2605 if (len >= 0 && line [len] == '\n')
2608 mono_runtime_printf_err ("%s", line);
2617 static gboolean handle_crash_loop = FALSE;
2620 * mono_handle_native_crash:
2622 * Handle a native crash (e.g. SIGSEGV) while in native code by
2623 * printing diagnostic information and aborting.
2626 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2628 #ifdef MONO_ARCH_USE_SIGACTION
2629 struct sigaction sa;
2631 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2633 if (handle_crash_loop)
2636 if (mini_get_debug_options ()->suspend_on_native_crash) {
2637 mono_runtime_printf_err ("Received %s, suspending...", signal);
2648 /* prevent infinite loops in crash handling */
2649 handle_crash_loop = TRUE;
2651 /* !jit_tls means the thread was not registered with the runtime */
2652 if (jit_tls && mono_thread_internal_current ()) {
2653 mono_runtime_printf_err ("Stacktrace:\n");
2655 /* FIXME: Is MONO_UNWIND_LOOKUP_IL_OFFSET correct here? */
2656 mono_walk_stack (print_stack_frame_to_stderr, MONO_UNWIND_LOOKUP_IL_OFFSET, NULL);
2659 print_process_map ();
2661 #ifdef HAVE_BACKTRACE_SYMBOLS
2667 mono_runtime_printf_err ("\nNative stacktrace:\n");
2669 size = backtrace (array, 256);
2670 names = backtrace_symbols (array, size);
2671 for (i =0; i < size; ++i) {
2672 mono_runtime_printf_err ("\t%s", names [i]);
2676 /* Try to get more meaningful information using gdb */
2678 #if !defined(HOST_WIN32) && defined(HAVE_SYS_SYSCALL_H) && defined(SYS_fork)
2679 if (!mini_get_debug_options ()->no_gdb_backtrace) {
2680 /* From g_spawn_command_line_sync () in eglib */
2683 pid_t crashed_pid = getpid ();
2686 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
2687 * it will deadlock. Call the syscall directly instead.
2689 #if defined(PLATFORM_ANDROID)
2690 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
2691 g_assert_not_reached ();
2692 #elif !defined(PLATFORM_MACOSX) && defined(SYS_fork)
2693 pid = (pid_t) syscall (SYS_fork);
2694 #elif defined(PLATFORM_MACOSX) && HAVE_FORK
2695 pid = (pid_t) fork ();
2697 g_assert_not_reached ();
2700 #if defined (HAVE_PRCTL) && defined(PR_SET_PTRACER)
2702 // Allow gdb to attach to the process even if ptrace_scope sysctl variable is set to
2703 // a value other than 0 (the most permissive ptrace scope). Most modern Linux
2704 // distributions set the scope to 1 which allows attaching only to direct children of
2705 // the current process
2706 prctl (PR_SET_PTRACER, pid, 0, 0, 0);
2710 dup2 (STDERR_FILENO, STDOUT_FILENO);
2712 mono_gdb_render_native_backtraces (crashed_pid);
2716 mono_runtime_printf_err ("\nDebug info from gdb:\n");
2717 waitpid (pid, &status, 0);
2722 #ifdef PLATFORM_ANDROID
2723 /* set DUMPABLE for this process so debuggerd can attach with ptrace(2), see:
2724 * https://android.googlesource.com/platform/bionic/+/151da681000c07da3c24cd30a3279b1ca017f452/linker/debugger.cpp#206
2725 * this has changed on later versions of Android. Also, we don't want to
2726 * set this on start-up as DUMPABLE has security implications. */
2727 prctl (PR_SET_DUMPABLE, 1);
2729 mono_runtime_printf_err ("\nNo native Android stacktrace (see debuggerd output).\n");
2734 * A SIGSEGV indicates something went very wrong so we can no longer depend
2735 * on anything working. So try to print out lots of diagnostics, starting
2736 * with ones which have a greater chance of working.
2738 mono_runtime_printf_err (
2740 "=================================================================\n"
2741 "Got a %s while executing native code. This usually indicates\n"
2742 "a fatal error in the mono runtime or one of the native libraries \n"
2743 "used by your application.\n"
2744 "=================================================================\n",
2747 #ifdef MONO_ARCH_USE_SIGACTION
2748 sa.sa_handler = SIG_DFL;
2749 sigemptyset (&sa.sa_mask);
2752 /* Remove our SIGABRT handler */
2753 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
2755 /* On some systems we get a SIGILL when calling abort (), because it might
2756 * fail to raise SIGABRT */
2757 g_assert (sigaction (SIGILL, &sa, NULL) != -1);
2760 if (!mono_do_crash_chaining) {
2761 /*Android abort is a fluke, it doesn't abort, it triggers another segv. */
2762 #if defined (PLATFORM_ANDROID)
2773 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2775 g_assert_not_reached ();
2778 #endif /* !MONO_CROSS_COMPILE */
2781 mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
2783 MonoInternalThread *thread = mono_thread_internal_current ();
2784 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2789 GError *error = NULL;
2794 text = g_string_new (0);
2796 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
2798 g_string_append_printf (text, "\n\"%s\"", name);
2801 else if (thread->threadpool_thread)
2802 g_string_append (text, "\n\"<threadpool thread>\"");
2804 g_string_append (text, "\n\"<unnamed thread>\"");
2806 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
2807 mono_thread_internal_describe (thread, text);
2808 g_string_append (text, "\n");
2810 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2812 memcpy (&ctx, start_ctx, sizeof (MonoContext));
2814 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_print_thread_dump);
2816 mono_sigctx_to_monoctx (sigctx, &ctx);
2818 mono_walk_stack_with_ctx (print_stack_frame_to_string, &ctx, MONO_UNWIND_LOOKUP_ALL, text);
2820 mono_runtime_printf ("\t<Stack traces in thread dumps not supported on this platform>");
2823 mono_runtime_printf ("%s", text->str);
2825 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
2826 OutputDebugStringA(text->str);
2829 g_string_free (text, TRUE);
2830 mono_runtime_stdout_fflush ();
2834 * mono_print_thread_dump:
2836 * Print information about the current thread to stdout.
2837 * \p sigctx can be NULL, allowing this to be called from gdb.
2840 mono_print_thread_dump (void *sigctx)
2842 mono_print_thread_dump_internal (sigctx, NULL);
2846 mono_print_thread_dump_from_ctx (MonoContext *ctx)
2848 mono_print_thread_dump_internal (NULL, ctx);
2852 * mono_resume_unwind:
2854 * This is called by a trampoline from LLVM compiled finally clauses to continue
2858 mono_resume_unwind (MonoContext *ctx)
2860 MONO_REQ_GC_UNSAFE_MODE;
2862 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2863 MonoContext new_ctx;
2865 MONO_CONTEXT_SET_IP (ctx, MONO_CONTEXT_GET_IP (&jit_tls->resume_state.ctx));
2866 MONO_CONTEXT_SET_SP (ctx, MONO_CONTEXT_GET_SP (&jit_tls->resume_state.ctx));
2869 mono_handle_exception_internal (&new_ctx, (MonoObject *)jit_tls->resume_state.ex_obj, TRUE, NULL);
2871 mono_restore_context (&new_ctx);
2874 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
2879 MonoJitExceptionInfo *ei;
2880 } FindHandlerBlockData;
2883 find_last_handler_block (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2887 FindHandlerBlockData *pdata = (FindHandlerBlockData *)data;
2888 MonoJitInfo *ji = frame->ji;
2893 ip = MONO_CONTEXT_GET_IP (ctx);
2895 for (i = 0; i < ji->num_clauses; ++i) {
2896 MonoJitExceptionInfo *ei = ji->clauses + i;
2897 if (ei->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2899 /*If ip points to the first instruction it means the handler block didn't start
2900 so we can leave its execution to the EH machinery*/
2901 if (ei->handler_start < ip && ip < ei->data.handler_end) {
2913 install_handler_block_guard (MonoJitInfo *ji, MonoContext *ctx)
2916 MonoJitExceptionInfo *clause = NULL;
2919 ip = MONO_CONTEXT_GET_IP (ctx);
2921 for (i = 0; i < ji->num_clauses; ++i) {
2922 clause = &ji->clauses [i];
2923 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2925 if (clause->handler_start < ip && clause->data.handler_end > ip)
2929 /*no matching finally */
2930 if (i == ji->num_clauses)
2933 /*If we stopped on the instruction right before the try, we haven't actually started executing it*/
2934 if (ip == clause->handler_start)
2937 return mono_arch_install_handler_block_guard (ji, clause, ctx, mono_create_handler_block_trampoline ());
2941 * Finds the bottom handler block running and install a block guard if needed.
2944 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2946 FindHandlerBlockData data = { 0 };
2947 MonoJitTlsData *jit_tls = (MonoJitTlsData *)ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS];
2950 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
2955 /* Guard against a null MonoJitTlsData. This can happens if the thread receives the
2956 * interrupt signal before the JIT has time to initialize its TLS data for the given thread.
2958 if (!jit_tls || jit_tls->handler_block_return_address)
2961 /* Do an async safe stack walk */
2962 mono_thread_info_set_is_async_context (TRUE);
2963 mono_walk_stack_with_state (find_last_handler_block, ctx, MONO_UNWIND_NONE, &data);
2964 mono_thread_info_set_is_async_context (FALSE);
2969 memcpy (&jit_tls->handler_block_context, &data.ctx, sizeof (MonoContext));
2971 resume_ip = install_handler_block_guard (data.ji, &data.ctx);
2972 if (resume_ip == NULL)
2975 jit_tls->handler_block_return_address = resume_ip;
2976 jit_tls->handler_block = data.ei;
2982 mono_current_thread_has_handle_block_guard (void)
2984 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2985 return jit_tls && jit_tls->handler_block_return_address != NULL;
2990 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2996 mono_current_thread_has_handle_block_guard (void)
3004 mono_set_cast_details (MonoClass *from, MonoClass *to)
3006 MonoJitTlsData *jit_tls = NULL;
3008 if (mini_get_debug_options ()->better_cast_details) {
3009 jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
3010 jit_tls->class_cast_from = from;
3011 jit_tls->class_cast_to = to;
3016 /*returns false if the thread is not attached*/
3018 mono_thread_state_init_from_sigctx (MonoThreadUnwindState *ctx, void *sigctx)
3020 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
3021 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3028 mono_sigctx_to_monoctx (sigctx, &ctx->ctx);
3030 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3031 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3032 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
3035 mono_thread_state_init (ctx);
3038 if (!ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] || !ctx->unwind_data [MONO_UNWIND_DATA_LMF])
3044 g_error ("Implement mono_arch_sigctx_to_monoctx for the current target");
3050 mono_thread_state_init (MonoThreadUnwindState *ctx)
3052 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3054 #if defined(MONO_CROSS_COMPILE)
3055 ctx->valid = FALSE; //A cross compiler doesn't need to suspend.
3056 #elif MONO_ARCH_HAS_MONO_CONTEXT
3057 MONO_CONTEXT_GET_CURRENT (ctx->ctx);
3059 g_error ("Use a null sigctx requires a working mono-context");
3062 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3063 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3064 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread ? thread->jit_data : NULL;
3070 mono_thread_state_init_from_monoctx (MonoThreadUnwindState *ctx, MonoContext *mctx)
3072 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3079 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3080 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3081 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
3086 /*returns false if the thread is not attached*/
3088 mono_thread_state_init_from_current (MonoThreadUnwindState *ctx)
3090 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3091 MONO_ARCH_CONTEXT_DEF
3093 mono_arch_flush_register_windows ();
3095 if (!thread || !thread->jit_data) {
3099 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
3100 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx->ctx);
3102 MONO_INIT_CONTEXT_FROM_FUNC (&ctx->ctx, mono_thread_state_init_from_current);
3105 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3106 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3107 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
3113 mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx)
3115 mono_handle_exception (ctx, (MonoObject *)exc);
3116 mono_restore_context (ctx);
3119 /*FIXME Move all monoctx -> sigctx conversion to signal handlers once all archs support utils/mono-context */
3121 mono_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
3123 #ifdef MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK
3124 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
3125 jit_tls->ex_ctx = *ctx;
3127 mono_arch_setup_async_callback (ctx, async_cb, user_data);
3129 g_error ("This target doesn't support mono_arch_setup_async_callback");
3134 * mono_restore_context:
3136 * Call the architecture specific restore context function.
3139 mono_restore_context (MonoContext *ctx)
3141 static void (*restore_context) (MonoContext *);
3143 if (!restore_context)
3144 restore_context = (void (*)(MonoContext *))mono_get_restore_context ();
3145 restore_context (ctx);
3146 g_assert_not_reached ();
3150 * mono_jinfo_get_unwind_info:
3152 * Return the unwind info for JI.
3155 mono_jinfo_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3157 if (ji->has_unwind_info) {
3158 /* The address/length in the MonoJitInfo structure itself */
3159 MonoUnwindJitInfo *info = mono_jit_info_get_unwind_info (ji);
3160 *unwind_info_len = info->unw_info_len;
3161 return info->unw_info;
3162 } else if (ji->from_aot)
3163 return mono_aot_get_unwind_info (ji, unwind_info_len);
3165 return mono_get_cached_unwind_info (ji->unwind_info, unwind_info_len);
3169 mono_jinfo_get_epilog_size (MonoJitInfo *ji)
3171 MonoArchEHJitInfo *info;
3173 info = mono_jit_info_get_arch_eh_info (ji);
3176 return info->epilog_size;
3180 * LLVM/Bitcode exception handling.
3184 throw_exception (MonoObject *ex, gboolean rethrow)
3186 MONO_REQ_GC_UNSAFE_MODE;
3189 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3190 MonoException *mono_ex;
3192 if (!mono_object_isinst_checked (ex, mono_defaults.exception_class, &error)) {
3193 mono_error_assert_ok (&error);
3194 mono_ex = mono_get_exception_runtime_wrapped_checked (ex, &error);
3195 mono_error_assert_ok (&error);
3196 jit_tls->thrown_non_exc = mono_gchandle_new (ex, FALSE);
3199 mono_ex = (MonoException*)ex;
3202 jit_tls->thrown_exc = mono_gchandle_new ((MonoObject*)mono_ex, FALSE);
3205 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
3206 GList *l, *ips = NULL;
3209 _Unwind_Backtrace (build_stack_trace, &ips);
3210 /* The list contains ip-gshared info pairs */
3212 ips = g_list_reverse (ips);
3213 for (l = ips; l; l = l->next) {
3214 trace = g_list_append (trace, l->data);
3215 trace = g_list_append (trace, NULL);
3217 MonoArray *ips_arr = mono_glist_to_array (trace, mono_defaults.int_class, &error);
3218 mono_error_assert_ok (&error);
3219 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3221 g_list_free (trace);
3225 mono_llvm_cpp_throw_exception ();
3229 mono_llvm_throw_exception (MonoObject *ex)
3231 throw_exception (ex, FALSE);
3235 mono_llvm_rethrow_exception (MonoObject *ex)
3237 throw_exception (ex, TRUE);
3241 mono_llvm_raise_exception (MonoException *e)
3243 mono_llvm_throw_exception ((MonoObject*)e);
3247 mono_llvm_throw_corlib_exception (guint32 ex_token_index)
3249 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
3252 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
3254 mono_llvm_throw_exception ((MonoObject*)ex);
3258 * mono_llvm_resume_exception:
3260 * Resume exception propagation.
3263 mono_llvm_resume_exception (void)
3265 mono_llvm_cpp_throw_exception ();
3269 * mono_llvm_load_exception:
3271 * Return the currently thrown exception.
3274 mono_llvm_load_exception (void)
3277 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3279 MonoException *mono_ex = (MonoException*)mono_gchandle_get_target (jit_tls->thrown_exc);
3281 if (mono_ex->trace_ips) {
3282 GList *trace_ips = NULL;
3283 gpointer ip = __builtin_return_address (0);
3285 size_t upper = mono_array_length (mono_ex->trace_ips);
3287 for (int i = 0; i < upper; i+= 2) {
3288 gpointer curr_ip = mono_array_get (mono_ex->trace_ips, gpointer, i);
3289 gpointer curr_info = mono_array_get (mono_ex->trace_ips, gpointer, i + 1);
3290 trace_ips = g_list_append (trace_ips, curr_ip);
3291 trace_ips = g_list_append (trace_ips, curr_info);
3297 // FIXME: Does this work correctly for rethrows?
3298 // We may be discarding useful information
3299 // when this gets GC'ed
3300 MonoArray *ips_arr = mono_glist_to_array (trace_ips, mono_defaults.int_class, &error);
3301 mono_error_assert_ok (&error);
3302 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3303 g_list_free (trace_ips);
3306 //MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
3308 MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, 0, &error));
3309 mono_error_assert_ok (&error);
3310 MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new_checked (mono_domain_get (), mono_defaults.stack_frame_class, 0, &error));
3311 mono_error_assert_ok (&error);
3314 return &mono_ex->object;
3318 * mono_llvm_clear_exception:
3320 * Mark the currently thrown exception as handled.
3323 mono_llvm_clear_exception (void)
3325 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3326 mono_gchandle_free (jit_tls->thrown_exc);
3327 jit_tls->thrown_exc = 0;
3328 if (jit_tls->thrown_non_exc)
3329 mono_gchandle_free (jit_tls->thrown_non_exc);
3330 jit_tls->thrown_non_exc = 0;
3332 mono_memory_barrier ();
3336 * mono_llvm_match_exception:
3338 * Return the innermost clause containing REGION_START-REGION_END which can handle
3339 * the current exception.
3342 mono_llvm_match_exception (MonoJitInfo *jinfo, guint32 region_start, guint32 region_end, gpointer rgctx, MonoObject *this_obj)
3345 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3349 g_assert (jit_tls->thrown_exc);
3350 exc = mono_gchandle_get_target (jit_tls->thrown_exc);
3351 if (jit_tls->thrown_non_exc) {
3353 * Have to unwrap RuntimeWrappedExceptions if the
3354 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
3356 if (!wrap_non_exception_throws (jinfo_get_method (jinfo)))
3357 exc = mono_gchandle_get_target (jit_tls->thrown_non_exc);
3360 for (int i = 0; i < jinfo->num_clauses; i++) {
3361 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3362 MonoClass *catch_class;
3364 if (! (ei->try_offset == region_start && ei->try_offset + ei->try_len == region_end) )
3367 catch_class = ei->data.catch_class;
3368 if (mono_class_is_open_constructed_type (&catch_class->byval_arg)) {
3369 MonoGenericContext context;
3370 MonoType *inflated_type;
3372 g_assert (rgctx || this_obj);
3373 context = get_generic_context_from_stack_frame (jinfo, rgctx ? rgctx : this_obj->vtable);
3374 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
3375 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3377 catch_class = mono_class_from_mono_type (inflated_type);
3378 mono_metadata_free_type (inflated_type);
3381 // FIXME: Handle edge cases handled in get_exception_catch_class
3382 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (exc, catch_class, &error)) {
3383 index = ei->clause_index;
3386 mono_error_assert_ok (&error);
3388 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3389 g_assert_not_reached ();
3398 mono_debug_personality (int a, _Unwind_Action b,
3399 uint64_t c, struct _Unwind_Exception *d, struct _Unwind_Context *e)
3401 g_assert_not_reached ();
3405 mono_debug_personality (void);
3408 mono_debug_personality (void)
3410 g_assert_not_reached ();