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-private.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
97 * Raw frame information is stored in MonoException.trace_ips as an IntPtr[].
98 * This structure represents one entry.
99 * This should consists of pointers only.
104 gpointer generic_info;
107 /* Number of words in trace_ips belonging to one entry */
108 #define TRACE_IP_ENTRY_SIZE (sizeof (ExceptionTraceIp) / sizeof (gpointer))
110 static gpointer restore_context_func, call_filter_func;
111 static gpointer throw_exception_func, rethrow_exception_func;
112 static gpointer throw_corlib_exception_func;
114 static gpointer try_more_restore_tramp = NULL;
115 static gpointer restore_stack_protection_tramp = NULL;
117 static void try_more_restore (void);
118 static void restore_stack_protection (void);
119 static void mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data);
120 static void mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx);
121 static void mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data);
122 static gboolean mono_current_thread_has_handle_block_guard (void);
123 static gboolean mono_install_handler_block_guard (MonoThreadUnwindState *ctx);
126 first_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer addr)
128 gpointer **data = (gpointer **)addr;
134 // FIXME: Happens with llvm_only
139 *data = MONO_CONTEXT_GET_SP (ctx);
145 mono_thread_get_managed_sp (void)
147 gpointer addr = NULL;
148 mono_walk_stack (first_managed, MONO_UNWIND_SIGNAL_SAFE, &addr);
153 mini_abort_threshold_offset (gpointer threshold, gpointer sp)
155 intptr_t stack_threshold = (intptr_t) threshold;
156 intptr_t stack_pointer = (intptr_t) sp;
158 const int direction = MONO_ARCH_STACK_GROWS_UP ? -1 : 1;
159 intptr_t magnitude = stack_pointer - stack_threshold;
161 return direction * magnitude;
165 mini_clear_abort_threshold (void)
167 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
168 jit_tls->abort_exc_stack_threshold = NULL;
172 mini_set_abort_threshold (MonoContext *ctx)
174 gpointer sp = MONO_CONTEXT_GET_SP (ctx);
175 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
176 // Only move it up, to avoid thrown/caught
177 // exceptions lower in the stack from triggering
179 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
180 if (!jit_tls->abort_exc_stack_threshold || above_threshold) {
181 jit_tls->abort_exc_stack_threshold = sp;
185 // Note: In the case that the frame is above where the thread abort
186 // was set we bump the threshold so that functions called from the new,
187 // higher threshold don't trigger the thread abort exception
188 static inline gboolean
189 mini_above_abort_threshold (void)
191 gpointer sp = mono_thread_get_managed_sp ();
192 MonoJitTlsData *jit_tls = (MonoJitTlsData*) mono_tls_get_jit_tls ();
197 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
200 jit_tls->abort_exc_stack_threshold = sp;
202 return above_threshold;
206 mono_get_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
209 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
215 mono_exceptions_init (void)
217 MonoRuntimeExceptionHandlingCallbacks cbs;
219 restore_context_func = mono_aot_get_trampoline ("restore_context");
220 call_filter_func = mono_aot_get_trampoline ("call_filter");
221 throw_exception_func = mono_aot_get_trampoline ("throw_exception");
222 rethrow_exception_func = mono_aot_get_trampoline ("rethrow_exception");
226 restore_context_func = mono_arch_get_restore_context (&info, FALSE);
227 mono_tramp_info_register (info, NULL);
228 call_filter_func = mono_arch_get_call_filter (&info, FALSE);
229 mono_tramp_info_register (info, NULL);
230 throw_exception_func = mono_arch_get_throw_exception (&info, FALSE);
231 mono_tramp_info_register (info, NULL);
232 rethrow_exception_func = mono_arch_get_rethrow_exception (&info, FALSE);
233 mono_tramp_info_register (info, NULL);
235 #ifdef MONO_ARCH_HAVE_RESTORE_STACK_SUPPORT
236 if (!mono_llvm_only) {
237 try_more_restore_tramp = mono_create_specific_trampoline (try_more_restore, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
238 restore_stack_protection_tramp = mono_create_specific_trampoline (restore_stack_protection, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
242 #ifdef MONO_ARCH_HAVE_EXCEPTIONS_INIT
243 mono_arch_exceptions_init ();
245 #ifdef ENABLE_INTERPRETER
246 if (mono_use_interpreter)
247 cbs.mono_walk_stack_with_ctx = interp_walk_stack_with_ctx;
250 cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
252 cbs.mono_walk_stack_with_state = mono_walk_stack_with_state;
255 cbs.mono_raise_exception = mono_llvm_raise_exception;
257 cbs.mono_raise_exception = (void (*)(MonoException *))mono_get_throw_exception ();
258 cbs.mono_raise_exception_with_ctx = mono_raise_exception_with_ctx;
259 cbs.mono_exception_walk_trace = mono_exception_walk_trace;
260 cbs.mono_install_handler_block_guard = mono_install_handler_block_guard;
261 cbs.mono_current_thread_has_handle_block_guard = mono_current_thread_has_handle_block_guard;
262 cbs.mono_clear_abort_threshold = mini_clear_abort_threshold;
263 cbs.mono_above_abort_threshold = mini_above_abort_threshold;
264 mono_install_eh_callbacks (&cbs);
265 mono_install_get_seq_point (mono_get_seq_point_for_native_offset);
269 mono_get_throw_exception (void)
271 g_assert (throw_exception_func);
272 return throw_exception_func;
276 mono_get_rethrow_exception (void)
278 g_assert (rethrow_exception_func);
279 return rethrow_exception_func;
283 mono_get_call_filter (void)
285 g_assert (call_filter_func);
286 return call_filter_func;
290 mono_get_restore_context (void)
292 g_assert (restore_context_func);
293 return restore_context_func;
297 mono_get_throw_corlib_exception (void)
299 gpointer code = NULL;
302 /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
303 if (throw_corlib_exception_func)
304 return throw_corlib_exception_func;
307 code = mono_aot_get_trampoline ("throw_corlib_exception");
309 code = mono_arch_get_throw_corlib_exception (&info, FALSE);
310 mono_tramp_info_register (info, NULL);
313 mono_memory_barrier ();
315 throw_corlib_exception_func = code;
317 return throw_corlib_exception_func;
321 * mono_get_throw_exception_addr:
323 * Return an address which stores the result of
324 * mono_get_throw_exception.
327 mono_get_throw_exception_addr (void)
329 return &throw_exception_func;
333 is_address_protected (MonoJitInfo *ji, MonoJitExceptionInfo *ei, gpointer ip)
335 MonoTryBlockHoleTableJitInfo *table;
340 if (ei->try_start > ip || ip >= ei->try_end)
343 if (!ji->has_try_block_holes)
346 table = mono_jit_info_get_try_block_hole_table_info (ji);
347 offset = (guint32)((char*)ip - (char*)ji->code_start);
348 clause = (guint16)(ei - ji->clauses);
349 g_assert (clause < ji->num_clauses);
351 for (i = 0; i < table->num_holes; ++i) {
352 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
353 if (ji->clauses [hole->clause].try_offset == ji->clauses [clause].try_offset && hole->offset <= offset && hole->offset + hole->length > offset)
359 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
362 static gboolean show_native_addresses = TRUE;
364 static gboolean show_native_addresses = FALSE;
367 static _Unwind_Reason_Code
368 build_stack_trace (struct _Unwind_Context *frame_ctx, void *state)
370 MonoDomain *domain = mono_domain_get ();
371 uintptr_t ip = _Unwind_GetIP (frame_ctx);
373 if (show_native_addresses || mono_jit_info_table_find (domain, (char*)ip)) {
374 GList **trace_ips = (GList **)state;
375 *trace_ips = g_list_prepend (*trace_ips, (gpointer)ip);
378 return _URC_NO_REASON;
382 get_unwind_backtrace (void)
386 _Unwind_Backtrace (build_stack_trace, &ips);
388 return g_slist_reverse (ips);
394 get_unwind_backtrace (void)
404 * Translate between the mono_arch_unwind_frame function and the old API.
407 find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
408 MonoContext *new_ctx, MonoLMF **lmf, gboolean *managed)
410 StackFrameInfo frame;
413 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
415 /* Avoid costly table lookup during stack overflow */
416 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
419 ji = mini_jit_info_table_find (domain, (char *)ip, NULL);
424 err = mono_arch_unwind_frame (domain, jit_tls, ji, ctx, new_ctx, lmf, NULL, &frame);
426 return (MonoJitInfo *)-1;
428 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
430 * Remove any unused lmf.
431 * Mask out the lower bits which might be used to hold additional information.
433 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
436 /* Convert between the new and the old APIs */
437 switch (frame.type) {
438 case FRAME_TYPE_MANAGED:
442 case FRAME_TYPE_TRAMPOLINE:
444 case FRAME_TYPE_MANAGED_TO_NATIVE:
448 memset (res, 0, sizeof (MonoJitInfo));
449 res->d.method = frame.method;
452 case FRAME_TYPE_DEBUGGER_INVOKE: {
456 * The normal exception handling code can't handle this frame, so just
459 ji = find_jit_info (domain, jit_tls, res, NULL, new_ctx, &tmp_ctx, lmf, managed);
460 memcpy (new_ctx, &tmp_ctx, sizeof (MonoContext));
464 g_assert_not_reached ();
469 /* mono_find_jit_info:
471 * This function is used to gather information from @ctx. It return the
472 * MonoJitInfo of the corresponding function, unwinds one stack frame and
473 * stores the resulting context into @new_ctx. It also stores a string
474 * describing the stack location into @trace (if not NULL), and modifies
475 * the @lmf if necessary. @native_offset return the IP offset from the
476 * start of the function or -1 if that info is not available.
479 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
480 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
484 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
486 MonoMethod *method = NULL;
497 ji = find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, lmf, &managed2);
499 if (ji == (gpointer)-1)
502 if (ji && !ji->is_trampoline)
503 method = jinfo_get_method (ji);
505 if (managed2 || (method && method->wrapper_type)) {
506 const char *real_ip, *start;
509 start = (const char *)ji->code_start;
511 /* ctx->ip points into native code */
512 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
514 real_ip = (const char*)ip;
516 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
517 offset = real_ip - start;
522 *native_offset = offset;
525 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
529 *trace = mono_debug_print_stack_frame (method, offset, domain);
532 char *fname = mono_method_full_name (jinfo_get_method (res), TRUE);
533 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
542 * mono_find_jit_info_ext:
544 * A version of mono_find_jit_info which returns all data in the StackFrameInfo
546 * A note about frames of type FRAME_TYPE_MANAGED_TO_NATIVE:
547 * - These frames are used to mark managed-to-native transitions, so CTX will refer to native
548 * code, and new_ctx will refer to the last managed frame. The caller should unwind once more
549 * to obtain the last managed frame.
550 * If SAVE_LOCATIONS is not NULL, it should point to an array of size MONO_MAX_IREGS.
551 * On return, it will be filled with the locations where callee saved registers are saved
552 * by the current frame. This is returned outside of StackFrameInfo because it can be
553 * quite large on some platforms.
554 * If ASYNC true, this function will be async safe, but some fields of frame and frame->ji will
558 mono_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls,
559 MonoJitInfo *prev_ji, MonoContext *ctx,
560 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
561 mgreg_t **save_locations,
562 StackFrameInfo *frame)
565 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
567 MonoDomain *target_domain = domain;
568 MonoMethod *method = NULL;
569 gboolean async = mono_thread_info_is_async_context ();
574 /* Avoid costly table lookup during stack overflow */
575 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
578 ji = mini_jit_info_table_find (domain, (char *)ip, &target_domain);
581 target_domain = domain;
584 memset (save_locations, 0, MONO_MAX_IREGS * sizeof (mgreg_t*));
586 err = mono_arch_unwind_frame (target_domain, jit_tls, ji, ctx, new_ctx, lmf, save_locations, frame);
590 if (frame->type != FRAME_TYPE_INTERP_TO_MANAGED && *lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
592 * Remove any unused lmf.
593 * Mask out the lower bits which might be used to hold additional information.
595 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
598 if (frame->ji && !frame->ji->is_trampoline && !frame->ji->async)
599 method = jinfo_get_method (frame->ji);
601 if (frame->type == FRAME_TYPE_MANAGED && method) {
602 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
603 frame->managed = TRUE;
606 if (frame->type == FRAME_TYPE_MANAGED_TO_NATIVE) {
608 * This type of frame is just a marker, the caller should unwind once more to get the
609 * last managed frame.
612 frame->method = NULL;
615 frame->native_offset = -1;
616 frame->domain = target_domain;
617 frame->async_context = async;
621 if (frame->type == FRAME_TYPE_MANAGED)
622 frame->method = method;
624 if (ji && (frame->managed || (method && method->wrapper_type))) {
625 const char *real_ip, *start;
627 start = (const char *)ji->code_start;
628 if (frame->type == FRAME_TYPE_MANAGED)
629 real_ip = (const char*)ip;
631 /* ctx->ip points into native code */
632 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
634 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
635 frame->native_offset = real_ip - start;
637 frame->native_offset = -1;
641 *trace = mono_debug_print_stack_frame (method, frame->native_offset, domain);
643 if (trace && frame->method) {
644 char *fname = mono_method_full_name (frame->method, TRUE);
645 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
655 MonoInterpStackIter interp_iter;
659 unwinder_init (Unwinder *unwinder)
661 memset (unwinder, 0, sizeof (Unwinder));
664 #if defined(__GNUC__) && defined(TARGET_ARM64)
665 /* gcc 4.9.2 seems to miscompile this on arm64 */
666 static __attribute__((optimize("O0"))) gboolean
670 unwinder_unwind_frame (Unwinder *unwinder,
671 MonoDomain *domain, MonoJitTlsData *jit_tls,
672 MonoJitInfo *prev_ji, MonoContext *ctx,
673 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
674 mgreg_t **save_locations,
675 StackFrameInfo *frame)
677 if (unwinder->in_interp) {
678 unwinder->in_interp = mono_interp_frame_iter_next (&unwinder->interp_iter, frame);
679 if (!unwinder->in_interp) {
680 return unwinder_unwind_frame (unwinder, domain, jit_tls, prev_ji, ctx, new_ctx, trace, lmf, save_locations, frame);
684 gboolean res = mono_find_jit_info_ext (domain, jit_tls, prev_ji, ctx, new_ctx, trace, lmf,
685 save_locations, frame);
688 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
689 unwinder->in_interp = TRUE;
690 mono_interp_frame_iter_init (&unwinder->interp_iter, frame->interp_exit_data);
697 * This function is async-safe.
700 get_generic_info_from_stack_frame (MonoJitInfo *ji, MonoContext *ctx)
702 MonoGenericJitInfo *gi;
706 if (!ji->has_generic_jit_info)
708 gi = mono_jit_info_get_generic_jit_info (ji);
714 * Search location list if available, it contains the precise location of the
715 * argument for every pc offset, even if the method was interrupted while it was in
719 int offset = (mgreg_t)MONO_CONTEXT_GET_IP (ctx) - (mgreg_t)ji->code_start;
722 for (i = 0; i < gi->nlocs; ++i) {
723 MonoDwarfLocListEntry *entry = &gi->locations [i];
725 if (offset >= entry->from && (offset < entry->to || entry->to == 0)) {
727 info = (gpointer)mono_arch_context_get_int_reg (ctx, entry->reg);
729 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, entry->reg) + entry->offset);
733 g_assert (i < gi->nlocs);
736 info = (gpointer)mono_arch_context_get_int_reg (ctx, gi->this_reg);
738 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
742 method = jinfo_get_method (ji);
743 if (mono_method_get_context (method)->method_inst) {
744 /* A MonoMethodRuntimeGenericContext* */
746 } else if ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype) {
750 /* Avoid returning a managed object */
751 MonoObject *this_obj = (MonoObject *)info;
753 return this_obj->vtable;
758 * generic_info is either a MonoMethodRuntimeGenericContext or a MonoVTable.
760 static MonoGenericContext
761 get_generic_context_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
763 MonoGenericContext context = { NULL, NULL };
764 MonoClass *klass, *method_container_class;
767 g_assert (generic_info);
769 method = jinfo_get_method (ji);
770 g_assert (method->is_inflated);
771 if (mono_method_get_context (method)->method_inst) {
772 MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext *)generic_info;
774 klass = mrgctx->class_vtable->klass;
775 context.method_inst = mrgctx->method_inst;
776 g_assert (context.method_inst);
778 MonoVTable *vtable = (MonoVTable *)generic_info;
780 klass = vtable->klass;
783 //g_assert (!mono_class_is_gtd (method->klass));
784 if (mono_class_is_ginst (method->klass))
785 method_container_class = mono_class_get_generic_class (method->klass)->container_class;
787 method_container_class = method->klass;
789 /* class might refer to a subclass of method's class */
790 while (!(klass == method->klass || (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->container_class == method_container_class))) {
791 klass = klass->parent;
795 if (mono_class_is_ginst (klass) || mono_class_is_gtd (klass))
796 context.class_inst = mini_class_get_context (klass)->class_inst;
798 if (mono_class_is_ginst (klass))
799 g_assert (mono_class_has_parent_and_ignore_generics (mono_class_get_generic_class (klass)->container_class, method_container_class));
801 g_assert (mono_class_has_parent_and_ignore_generics (klass, method_container_class));
807 get_method_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
810 MonoGenericContext context;
813 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
814 return jinfo_get_method (ji);
815 context = get_generic_context_from_stack_frame (ji, generic_info);
817 method = jinfo_get_method (ji);
818 method = mono_method_get_declaring_generic_method (method);
819 method = mono_class_inflate_generic_method_checked (method, &context, &error);
820 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
826 * mono_exception_walk_native_trace:
827 * \param ex The exception object whose frames should be walked
828 * \param func callback to call for each stack frame
829 * \param user_data data passed to the callback
830 * This function walks the stacktrace of an exception. For
831 * each frame the callback function is called with the relevant info.
832 * The walk ends when no more stack frames are found or when the callback
833 * returns a TRUE value.
837 mono_exception_walk_trace (MonoException *ex, MonoExceptionFrameWalk func, gpointer user_data)
839 MONO_REQ_GC_UNSAFE_MODE;
841 MonoDomain *domain = mono_domain_get ();
842 MonoArray *ta = ex->trace_ips;
848 len = mono_array_length (ta) / TRACE_IP_ENTRY_SIZE;
849 for (i = 0; i < len; i++) {
850 ExceptionTraceIp trace_ip;
852 memcpy (&trace_ip, mono_array_addr_fast (ta, ExceptionTraceIp, i), sizeof (ExceptionTraceIp));
853 gpointer ip = trace_ip.ip;
854 gpointer generic_info = trace_ip.generic_info;
855 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)ip);
858 if (func (NULL, ip, 0, FALSE, user_data))
861 MonoMethod *method = get_method_from_stack_frame (ji, generic_info);
862 if (func (method, ji->code_start, (char *) ip - (char *) ji->code_start, TRUE, user_data))
871 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
874 MonoDomain *domain = mono_domain_get ();
876 MonoArray *ta = exc->trace_ips;
877 MonoDebugSourceLocation *location;
881 /* Exception is not thrown yet */
882 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, 0, &error);
883 mono_error_set_pending_exception (&error);
887 len = mono_array_length (ta) / TRACE_IP_ENTRY_SIZE;
889 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0, &error);
890 if (mono_error_set_pending_exception (&error))
893 for (i = skip; i < len; i++) {
895 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, &error);
896 if (!mono_error_ok (&error)) {
897 mono_error_set_pending_exception (&error);
900 ExceptionTraceIp trace_ip;
901 memcpy (&trace_ip, mono_array_addr_fast (ta, ExceptionTraceIp, i), sizeof (ExceptionTraceIp));
902 gpointer ip = trace_ip.ip;
903 gpointer generic_info = trace_ip.generic_info;
906 ji = mono_jit_info_table_find (domain, (char *)ip);
908 /* Unmanaged frame */
909 mono_array_setref (res, i, sf);
913 g_assert (ji != NULL);
916 /* Can't resolve actual method */
917 method = jinfo_get_method (ji);
919 method = get_method_from_stack_frame (ji, generic_info);
920 if (jinfo_get_method (ji)->wrapper_type) {
924 s = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION);
925 MonoString *name = mono_string_new_checked (domain, s, &error);
927 if (!is_ok (&error)) {
928 mono_error_set_pending_exception (&error);
931 MONO_OBJECT_SETREF (sf, internal_method_name, name);
934 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, &error);
935 if (!mono_error_ok (&error)) {
936 mono_error_set_pending_exception (&error);
939 MONO_OBJECT_SETREF (sf, method, rm);
942 sf->method_index = ji->from_aot ? mono_aot_find_method_index (method) : 0xffffff;
943 sf->method_address = (gsize) ji->code_start;
944 sf->native_offset = (char *)ip - (char *)ji->code_start;
947 * mono_debug_lookup_source_location() returns both the file / line number information
948 * and the IL offset. Note that computing the IL offset is already an expensive
949 * operation, so we shouldn't call this method twice.
951 location = mono_debug_lookup_source_location (jinfo_get_method (ji), sf->native_offset, domain);
953 sf->il_offset = location->il_offset;
956 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (ji), sf->native_offset, NULL, &sp))
957 sf->il_offset = sp.il_offset;
962 if (need_file_info) {
963 if (location && location->source_file) {
964 MonoString *filename = mono_string_new_checked (domain, location->source_file, &error);
965 if (!is_ok (&error)) {
966 mono_error_set_pending_exception (&error);
969 MONO_OBJECT_SETREF (sf, filename, filename);
970 sf->line = location->row;
971 sf->column = location->column;
973 sf->line = sf->column = 0;
978 mono_debug_free_source_location (location);
979 mono_array_setref (res, i, sf);
986 mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
989 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
990 if (jit_tls && jit_tls->orig_ex_ctx_set)
991 start_ctx = &jit_tls->orig_ex_ctx;
993 mono_walk_stack_with_ctx (func, start_ctx, unwind_options, user_data);
996 * mono_walk_stack_with_ctx:
997 * Unwind the current thread starting at \p start_ctx.
998 * If \p start_ctx is null, we capture the current context.
1001 mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
1003 MonoContext extra_ctx;
1004 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
1005 MONO_ARCH_CONTEXT_DEF
1007 if (!thread || !thread->jit_data)
1011 mono_arch_flush_register_windows ();
1013 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1014 MONO_INIT_CONTEXT_FROM_CURRENT (&extra_ctx);
1016 MONO_INIT_CONTEXT_FROM_FUNC (&extra_ctx, mono_walk_stack_with_ctx);
1018 start_ctx = &extra_ctx;
1021 mono_walk_stack_full (func, start_ctx, mono_domain_get (), (MonoJitTlsData *)thread->jit_data, mono_get_lmf (), unwind_options, user_data);
1025 * mono_walk_stack_with_state:
1026 * Unwind a thread described by \p state.
1028 * State must be valid (state->valid == TRUE).
1030 * If you are using this function to unwind another thread, make sure it is suspended.
1032 * If \p state is null, we capture the current context.
1035 mono_walk_stack_with_state (MonoJitStackWalk func, MonoThreadUnwindState *state, MonoUnwindOptions unwind_options, void *user_data)
1037 MonoThreadUnwindState extra_state;
1039 g_assert (!mono_thread_info_is_async_context ());
1040 if (!mono_thread_state_init_from_current (&extra_state))
1042 state = &extra_state;
1045 g_assert (state->valid);
1047 if (!state->unwind_data [MONO_UNWIND_DATA_DOMAIN])
1051 mono_walk_stack_full (func,
1053 (MonoDomain *)state->unwind_data [MONO_UNWIND_DATA_DOMAIN],
1054 (MonoJitTlsData *)state->unwind_data [MONO_UNWIND_DATA_JIT_TLS],
1055 (MonoLMF *)state->unwind_data [MONO_UNWIND_DATA_LMF],
1056 unwind_options, user_data);
1060 mono_walk_stack (MonoJitStackWalk func, MonoUnwindOptions options, void *user_data)
1062 MonoThreadUnwindState state;
1063 if (!mono_thread_state_init_from_current (&state))
1065 mono_walk_stack_with_state (func, &state, options, user_data);
1069 * mono_walk_stack_full:
1070 * \param func callback to call for each stack frame
1071 * \param domain starting appdomain, can be NULL to use the current domain
1072 * \param unwind_options what extra information the unwinder should gather
1073 * \param start_ctx starting state of the stack walk, can be NULL.
1074 * \param thread the thread whose stack to walk, can be NULL to use the current thread
1075 * \param lmf the LMF of \p thread, can be NULL to use the LMF of the current thread
1076 * \param user_data data passed to the callback
1077 * This function walks the stack of a thread, starting from the state
1078 * represented by \p start_ctx. For each frame the callback
1079 * function is called with the relevant info. The walk ends when no more
1080 * managed stack frames are found or when the callback returns a TRUE value.
1083 mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data)
1086 MonoContext ctx, new_ctx;
1087 StackFrameInfo frame;
1089 mgreg_t *reg_locations [MONO_MAX_IREGS];
1090 mgreg_t *new_reg_locations [MONO_MAX_IREGS];
1091 gboolean get_reg_locations = unwind_options & MONO_UNWIND_REG_LOCATIONS;
1092 gboolean async = mono_thread_info_is_async_context ();
1095 if (mono_llvm_only) {
1101 ips = get_unwind_backtrace ();
1102 for (l = ips; l; l = l->next) {
1103 guint8 *ip = (guint8*)l->data;
1104 memset (&frame, 0, sizeof (StackFrameInfo));
1105 frame.ji = mini_jit_info_table_find (domain, (char*)ip, &frame.domain);
1106 if (!frame.ji || frame.ji->is_trampoline)
1108 frame.type = FRAME_TYPE_MANAGED;
1109 frame.method = jinfo_get_method (frame.ji);
1110 // FIXME: Cannot lookup the actual method
1111 frame.actual_method = frame.method;
1112 if (frame.type == FRAME_TYPE_MANAGED) {
1113 if (!frame.method->wrapper_type || frame.method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
1114 frame.managed = TRUE;
1116 frame.native_offset = ip - (guint8*)frame.ji->code_start;
1117 frame.il_offset = -1;
1119 if (func (&frame, NULL, user_data))
1126 g_assert (start_ctx);
1129 /*The LMF will be null if the target have no managed frames.*/
1130 /* g_assert (lmf); */
1133 g_assert (unwind_options == MONO_UNWIND_NONE);
1135 memcpy (&ctx, start_ctx, sizeof (MonoContext));
1136 memset (reg_locations, 0, sizeof (reg_locations));
1138 unwinder_init (&unwinder);
1140 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
1142 res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, get_reg_locations ? new_reg_locations : NULL, &frame);
1146 if ((unwind_options & MONO_UNWIND_LOOKUP_IL_OFFSET) && frame.ji && !frame.ji->is_trampoline) {
1147 MonoDebugSourceLocation *source;
1149 source = mono_debug_lookup_source_location (jinfo_get_method (frame.ji), frame.native_offset, domain);
1151 il_offset = source->il_offset;
1154 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (frame.ji), frame.native_offset, NULL, &sp))
1155 il_offset = sp.il_offset;
1159 mono_debug_free_source_location (source);
1163 frame.il_offset = il_offset;
1165 if ((unwind_options & MONO_UNWIND_LOOKUP_ACTUAL_METHOD) && frame.ji && !frame.ji->is_trampoline) {
1166 frame.actual_method = get_method_from_stack_frame (frame.ji, get_generic_info_from_stack_frame (frame.ji, &ctx));
1168 frame.actual_method = frame.method;
1171 if (get_reg_locations)
1172 frame.reg_locations = reg_locations;
1174 if (func (&frame, &ctx, user_data))
1177 if (get_reg_locations) {
1178 for (i = 0; i < MONO_MAX_IREGS; ++i)
1179 if (new_reg_locations [i])
1180 reg_locations [i] = new_reg_locations [i];
1188 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
1189 MonoReflectionMethod **method,
1190 gint32 *iloffset, gint32 *native_offset,
1191 MonoString **file, gint32 *line, gint32 *column)
1194 MonoDomain *domain = mono_domain_get ();
1195 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1196 MonoLMF *lmf = mono_get_lmf ();
1197 MonoJitInfo *ji = NULL;
1198 MonoContext ctx, new_ctx;
1199 MonoDebugSourceLocation *location;
1200 MonoMethod *jmethod = NULL, *actual_method;
1201 StackFrameInfo frame;
1206 MONO_ARCH_CONTEXT_DEF;
1208 if (mono_llvm_only) {
1210 MonoDomain *frame_domain;
1211 guint8 *frame_ip = NULL;
1213 /* FIXME: Generalize this code with an interface which returns an array of StackFrame structures */
1215 ips = get_unwind_backtrace ();
1216 for (l = ips; l && skip >= 0; l = l->next) {
1217 guint8 *ip = (guint8*)l->data;
1221 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &frame_domain);
1222 if (!ji || ji->is_trampoline)
1225 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1226 jmethod = jinfo_get_method (ji);
1227 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1234 /* No way to resolve generic instances */
1235 actual_method = jmethod;
1236 *native_offset = frame_ip - (guint8*)ji->code_start;
1238 mono_arch_flush_register_windows ();
1240 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1241 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
1243 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
1246 unwinder_init (&unwinder);
1251 res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1254 switch (frame.type) {
1255 case FRAME_TYPE_MANAGED_TO_NATIVE:
1256 case FRAME_TYPE_DEBUGGER_INVOKE:
1257 case FRAME_TYPE_TRAMPOLINE:
1258 case FRAME_TYPE_INTERP_TO_MANAGED:
1260 case FRAME_TYPE_INTERP:
1265 *native_offset = frame.native_offset;
1267 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1268 jmethod = jinfo_get_method (ji);
1269 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1274 } while (skip >= 0);
1276 if (frame.type == FRAME_TYPE_INTERP) {
1277 jmethod = frame.method;
1278 actual_method = frame.actual_method;
1279 *native_offset = frame.native_offset;
1281 actual_method = get_method_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, &ctx));
1285 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, actual_method, NULL, &error);
1286 if (!mono_error_ok (&error)) {
1287 mono_error_set_pending_exception (&error);
1290 mono_gc_wbarrier_generic_store (method, (MonoObject*) rm);
1292 if (il_offset != -1) {
1293 location = mono_debug_lookup_source_location_by_il (jmethod, il_offset, domain);
1295 location = mono_debug_lookup_source_location (jmethod, *native_offset, domain);
1298 *iloffset = location->il_offset;
1302 if (need_file_info) {
1304 MonoString *filename = mono_string_new_checked (domain, location->source_file, &error);
1305 if (!is_ok (&error)) {
1306 mono_error_set_pending_exception (&error);
1309 mono_gc_wbarrier_generic_store (file, (MonoObject*)filename);
1310 *line = location->row;
1311 *column = location->column;
1314 *line = *column = 0;
1318 mono_debug_free_source_location (location);
1324 get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
1327 MonoClass *catch_class = ei->data.catch_class;
1328 MonoType *inflated_type;
1329 MonoGenericContext context;
1331 /*MonoJitExceptionInfo::data is an union used by filter and finally clauses too.*/
1332 if (!catch_class || ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
1335 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
1337 context = get_generic_context_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, ctx));
1339 /* FIXME: we shouldn't inflate but instead put the
1340 type in the rgctx and fetch it from there. It
1341 might be a good idea to do this lazily, i.e. only
1342 when the exception is actually thrown, so as not to
1343 waste space for exception clauses which might never
1345 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
1346 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
1348 catch_class = mono_class_from_mono_type (inflated_type);
1349 mono_metadata_free_type (inflated_type);
1355 * mini_jit_info_table_find_ext:
1357 * Same as mono_jit_info_table_find, but search all the domains of the current thread
1358 * if ADDR is not found in DOMAIN. The domain where the method was found is stored into
1359 * OUT_DOMAIN if it is not NULL.
1362 mini_jit_info_table_find_ext (MonoDomain *domain, char *addr, gboolean allow_trampolines, MonoDomain **out_domain)
1365 MonoInternalThread *t = mono_thread_internal_current ();
1371 ji = mono_jit_info_table_find_internal (domain, addr, TRUE, allow_trampolines);
1374 *out_domain = domain;
1378 /* maybe it is shared code, so we also search in the root domain */
1379 if (domain != mono_get_root_domain ()) {
1380 ji = mono_jit_info_table_find_internal (mono_get_root_domain (), addr, TRUE, allow_trampolines);
1383 *out_domain = mono_get_root_domain ();
1391 refs = (gpointer *)((t->appdomain_refs) ? *(gpointer *) t->appdomain_refs : NULL);
1392 for (; refs && *refs; refs++) {
1393 if (*refs != domain && *refs != mono_get_root_domain ()) {
1394 ji = mono_jit_info_table_find_internal ((MonoDomain*) *refs, addr, TRUE, allow_trampolines);
1397 *out_domain = (MonoDomain*) *refs;
1407 mini_jit_info_table_find (MonoDomain *domain, char *addr, MonoDomain **out_domain)
1409 return mini_jit_info_table_find_ext (domain, addr, FALSE, out_domain);
1412 /* Class lazy loading functions */
1413 static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute")
1416 * wrap_non_exception_throws:
1418 * Determine whenever M's assembly has a RuntimeCompatibilityAttribute with the
1419 * WrapNonExceptionThrows flag set.
1422 wrap_non_exception_throws (MonoMethod *m)
1425 MonoAssembly *ass = m->klass->image->assembly;
1426 MonoCustomAttrInfo* attrs;
1429 gboolean val = FALSE;
1432 if (ass->wrap_non_exception_throws_inited)
1433 return ass->wrap_non_exception_throws;
1435 klass = mono_class_get_runtime_compat_attr_class ();
1437 attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
1438 mono_error_cleanup (&error); /* FIXME don't swallow the error */
1440 for (i = 0; i < attrs->num_attrs; ++i) {
1441 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1443 int num_named, named_type, name_len;
1446 if (!attr->ctor || attr->ctor->klass != klass)
1448 /* Decode the RuntimeCompatibilityAttribute. See reflection.c */
1449 p = (const char*)attr->data;
1450 g_assert (read16 (p) == 0x0001);
1452 num_named = read16 (p);
1458 /* data_type = *p; */
1461 if (named_type != 0x54)
1463 name_len = mono_metadata_decode_blob_size (p, &p);
1464 name = (char *)g_malloc (name_len + 1);
1465 memcpy (name, p, name_len);
1466 name [name_len] = 0;
1468 g_assert (!strcmp (name, "WrapNonExceptionThrows"));
1470 /* The value is a BOOLEAN */
1473 mono_custom_attrs_free (attrs);
1476 ass->wrap_non_exception_throws = val;
1477 mono_memory_barrier ();
1478 ass->wrap_non_exception_throws_inited = TRUE;
1483 #define MAX_UNMANAGED_BACKTRACE 128
1485 build_native_trace (MonoError *error)
1488 /* This puppy only makes sense on mobile, IOW, ARM. */
1489 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
1491 void *native_trace [MAX_UNMANAGED_BACKTRACE];
1494 size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
1500 res = mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, size, error);
1501 return_val_if_nok (error, NULL);
1503 for (i = 0; i < size; i++)
1504 mono_array_set (res, gpointer, i, native_trace [i]);
1512 setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, GList **trace_ips)
1515 *trace_ips = g_list_reverse (*trace_ips);
1517 MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
1518 mono_error_assert_ok (&error);
1519 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
1520 MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace (&error));
1521 mono_error_assert_ok (&error);
1522 if (dynamic_methods) {
1523 /* These methods could go away anytime, so save a reference to them in the exception object */
1525 MonoMList *list = NULL;
1527 for (l = dynamic_methods; l; l = l->next) {
1529 MonoDomain *domain = mono_domain_get ();
1531 if (domain->method_to_dyn_method) {
1532 mono_domain_lock (domain);
1533 dis_link = (guint32)(size_t)g_hash_table_lookup (domain->method_to_dyn_method, l->data);
1534 mono_domain_unlock (domain);
1536 MonoObject *o = mono_gchandle_get_target (dis_link);
1538 list = mono_mlist_prepend_checked (list, o, &error);
1539 mono_error_assert_ok (&error);
1545 MONO_OBJECT_SETREF (mono_ex, dynamic_methods, list);
1548 g_list_free (*trace_ips);
1553 * mono_handle_exception_internal_first_pass:
1555 * The first pass of exception handling. Unwind the stack until a catch clause which can catch
1556 * OBJ is found. Run the index of the filter clause which caught the exception into
1557 * OUT_FILTER_IDX. Return TRUE if the exception is caught, FALSE otherwise.
1560 mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filter_idx, MonoJitInfo **out_ji, MonoJitInfo **out_prev_ji, MonoObject *non_exception)
1563 MonoDomain *domain = mono_domain_get ();
1564 MonoJitInfo *ji = NULL;
1565 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1566 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1567 MonoLMF *lmf = mono_get_lmf ();
1568 GList *trace_ips = NULL;
1569 GSList *dynamic_methods = NULL;
1570 MonoException *mono_ex;
1571 gboolean stack_overflow = FALSE;
1572 MonoContext initial_ctx;
1574 int frame_count = 0;
1581 g_assert (ctx != NULL);
1583 if (obj == (MonoObject *)domain->stack_overflow_ex)
1584 stack_overflow = TRUE;
1586 mono_ex = (MonoException*)obj;
1587 MonoArray *initial_trace_ips = mono_ex->trace_ips;
1588 if (initial_trace_ips) {
1589 int len = mono_array_length (initial_trace_ips) / TRACE_IP_ENTRY_SIZE;
1591 for (i = 0; i < (len - 1); i++) {
1592 for (int j = 0; j < TRACE_IP_ENTRY_SIZE; ++j) {
1593 gpointer p = mono_array_get (initial_trace_ips, gpointer, (i * TRACE_IP_ENTRY_SIZE) + j);
1594 trace_ips = g_list_prepend (trace_ips, p);
1599 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1600 mono_error_assert_ok (&error);
1605 call_filter = (int (*) (MonoContext *, void *))mono_get_call_filter ();
1607 g_assert (jit_tls->end_of_stack);
1608 g_assert (jit_tls->abort_func);
1611 *out_filter_idx = -1;
1615 *out_prev_ji = NULL;
1619 unwinder_init (&unwinder);
1622 MonoContext new_ctx;
1624 int clause_index_start = 0;
1625 gboolean unwind_res = TRUE;
1627 StackFrameInfo frame;
1632 unwind_res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1634 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1635 g_slist_free (dynamic_methods);
1639 switch (frame.type) {
1640 case FRAME_TYPE_DEBUGGER_INVOKE:
1641 case FRAME_TYPE_MANAGED_TO_NATIVE:
1642 case FRAME_TYPE_TRAMPOLINE:
1643 case FRAME_TYPE_INTERP_TO_MANAGED:
1646 case FRAME_TYPE_INTERP:
1647 case FRAME_TYPE_MANAGED:
1650 g_assert_not_reached ();
1654 in_interp = frame.type == FRAME_TYPE_INTERP;
1659 ip = (guint8*)ji->code_start + frame.native_offset;
1661 ip = MONO_CONTEXT_GET_IP (ctx);
1664 method = jinfo_get_method (ji);
1665 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1667 if (mini_get_debug_options ()->reverse_pinvoke_exceptions && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
1668 g_error ("A native frame was found while unwinding the stack after an exception.\n"
1669 "The native frame called the managed method:\n%s\n",
1670 mono_method_full_name (method, TRUE));
1673 if (method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
1674 // avoid giant stack traces during a stack overflow
1675 if (frame_count < 1000) {
1676 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1677 trace_ips = g_list_prepend (trace_ips, get_generic_info_from_stack_frame (ji, ctx));
1681 if (method->dynamic)
1682 dynamic_methods = g_slist_prepend (dynamic_methods, method);
1684 if (stack_overflow) {
1685 if (MONO_ARCH_STACK_GROWS_UP)
1686 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1688 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1690 free_stack = 0xffffff;
1693 for (i = clause_index_start; i < ji->num_clauses; i++) {
1694 MonoJitExceptionInfo *ei = &ji->clauses [i];
1695 gboolean filtered = FALSE;
1698 * During stack overflow, wait till the unwinding frees some stack
1699 * space before running handlers/finalizers.
1701 if (free_stack <= (64 * 1024))
1704 if (is_address_protected (ji, ei, ip)) {
1706 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1709 * Have to unwrap RuntimeWrappedExceptions if the
1710 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1712 if (non_exception && !wrap_non_exception_throws (method))
1713 ex_obj = non_exception;
1717 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1718 #ifndef DISABLE_PERFCOUNTERS
1719 mono_perfcounters->exceptions_filters++;
1722 #ifndef MONO_CROSS_COMPILE
1723 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1725 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1727 /* Can't pass the ex object in a register yet to filter clauses, because call_filter () might not support it */
1728 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1730 g_assert (!ji->from_llvm);
1731 /* store the exception object in bp + ei->exvar_offset */
1732 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1736 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1738 * Pass the original il clause index to the landing pad so it can
1739 * branch to the landing pad associated with the il clause.
1740 * This is needed because llvm compiled code assumes that the EH
1741 * code always branches to the innermost landing pad.
1744 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1747 mono_debugger_agent_begin_exception_filter (mono_ex, ctx, &initial_ctx);
1748 filtered = call_filter (ctx, ei->data.filter);
1749 mono_debugger_agent_end_exception_filter (mono_ex, ctx, &initial_ctx);
1750 if (filtered && out_filter_idx)
1751 *out_filter_idx = filter_idx;
1757 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1758 g_slist_free (dynamic_methods);
1759 /* mono_debugger_agent_handle_exception () needs this */
1760 mini_set_abort_threshold (ctx);
1761 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1766 MonoError isinst_error;
1767 error_init (&isinst_error);
1768 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (ex_obj, catch_class, &error)) {
1769 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1770 g_slist_free (dynamic_methods);
1775 /* mono_debugger_agent_handle_exception () needs this */
1777 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1780 mono_error_cleanup (&isinst_error);
1787 g_assert_not_reached ();
1791 * mono_handle_exception_internal:
1792 * \param ctx saved processor state
1793 * \param obj the exception object
1794 * \param resume whenever to resume unwinding based on the state in \c MonoJitTlsData.
1797 mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resume, MonoJitInfo **out_ji)
1800 MonoDomain *domain = mono_domain_get ();
1801 MonoJitInfo *ji, *prev_ji;
1802 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1803 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1804 MonoLMF *lmf = mono_get_lmf ();
1805 MonoException *mono_ex;
1806 gboolean stack_overflow = FALSE;
1807 MonoContext initial_ctx;
1809 int frame_count = 0;
1810 gint32 filter_idx, first_filter_idx = 0;
1813 MonoObject *non_exception = NULL;
1817 g_assert (ctx != NULL);
1819 MonoException *ex = mono_get_exception_null_reference ();
1820 MonoString *msg = mono_string_new_checked (domain, "Object reference not set to an instance of an object", &error);
1821 mono_error_assert_ok (&error);
1822 MONO_OBJECT_SETREF (ex, message, msg);
1823 obj = (MonoObject *)ex;
1827 * Allocate a new exception object instead of the preconstructed ones.
1829 if (obj == (MonoObject *)domain->stack_overflow_ex) {
1831 * It is not a good idea to try and put even more pressure on the little stack available.
1832 * obj = mono_get_exception_stack_overflow ();
1834 stack_overflow = TRUE;
1836 else if (obj == (MonoObject *)domain->null_reference_ex) {
1837 obj = (MonoObject *)mono_get_exception_null_reference ();
1840 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1841 mono_error_assert_ok (&error);
1842 non_exception = obj;
1843 obj = (MonoObject *)mono_get_exception_runtime_wrapped_checked (obj, &error);
1844 mono_error_assert_ok (&error);
1847 mono_ex = (MonoException*)obj;
1849 if (mini_get_debug_options ()->suspend_on_exception) {
1850 mono_runtime_printf_err ("Exception thrown, suspending...");
1855 if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1856 mono_ex = (MonoException*)obj;
1858 mono_error_assert_ok (&error);
1862 if (mono_ex && jit_tls->class_cast_from) {
1863 if (!strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
1864 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1865 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1866 char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
1867 mono_ex->message = mono_string_new_checked (domain, msg, &error);
1870 if (!is_ok (&error)) {
1871 mono_runtime_printf_err ("Error creating class cast exception message '%s'\n", msg);
1872 mono_error_assert_ok (&error);
1876 if (!strcmp (mono_ex->object.vtable->klass->name, "ArrayTypeMismatchException")) {
1877 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1878 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1879 char *msg = g_strdup_printf ("Source array of type '%s' cannot be cast to destination array type '%s'.", from_name, to_name);
1880 mono_ex->message = mono_string_new_checked (domain, msg, &error);
1883 if (!is_ok (&error)) {
1884 mono_runtime_printf_err ("Error creating array type mismatch exception message '%s'\n", msg);
1885 mono_error_assert_ok (&error);
1892 call_filter = (int (*)(MonoContext *, void*))mono_get_call_filter ();
1894 g_assert (jit_tls->end_of_stack);
1895 g_assert (jit_tls->abort_func);
1898 * We set orig_ex_ctx_set to TRUE/FALSE around profiler calls to make sure it doesn't
1899 * end up being TRUE on any code path.
1901 memcpy (&jit_tls->orig_ex_ctx, ctx, sizeof (MonoContext));
1906 MonoContext ctx_cp = *ctx;
1907 if (mono_trace_is_enabled ()) {
1908 MonoMethod *system_exception_get_message = mono_class_get_method_from_name (mono_defaults.exception_class, "get_Message", 0);
1909 MonoMethod *get_message = system_exception_get_message == NULL ? NULL : mono_object_get_virtual_method (obj, system_exception_get_message);
1910 MonoObject *message;
1911 const char *type_name = mono_class_get_name (mono_object_class (mono_ex));
1913 if (get_message == NULL) {
1915 } else if (!strcmp (type_name, "OutOfMemoryException") || !strcmp (type_name, "StackOverflowException")) {
1917 msg = g_strdup_printf ("(No exception message for: %s)\n", type_name);
1919 MonoObject *exc = NULL;
1920 message = mono_runtime_try_invoke (get_message, obj, NULL, &exc, &error);
1921 g_assert (exc == NULL);
1922 mono_error_assert_ok (&error);
1926 msg = mono_string_to_utf8_checked ((MonoString *) message, &error);
1927 if (!is_ok (&error)) {
1928 mono_error_cleanup (&error);
1929 msg = g_strdup ("(error while display System.Exception.Message property)");
1932 msg = g_strdup ("(System.Exception.Message property not available)");
1935 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);
1937 if (mono_ex && mono_trace_eval_exception (mono_object_class (mono_ex)))
1938 mono_print_thread_dump_from_ctx (ctx);
1940 jit_tls->orig_ex_ctx_set = TRUE;
1941 MONO_PROFILER_RAISE (exception_throw, (obj));
1942 jit_tls->orig_ex_ctx_set = FALSE;
1944 res = mono_handle_exception_internal_first_pass (&ctx_cp, obj, &first_filter_idx, &ji, &prev_ji, non_exception);
1947 if (mini_get_debug_options ()->break_on_exc)
1949 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1951 if (mini_get_debug_options ()->suspend_on_unhandled) {
1952 mono_runtime_printf_err ("Unhandled exception, suspending...");
1957 // FIXME: This runs managed code so it might cause another stack overflow when
1958 // we are handling a stack overflow
1959 mini_set_abort_threshold (ctx);
1960 mono_unhandled_exception (obj);
1962 gboolean unhandled = FALSE;
1965 * The exceptions caught by the mono_runtime_invoke_checked () calls
1966 * in the threadpool needs to be treated as unhandled (#669836).
1968 * FIXME: The check below is hackish, but its hard to distinguish
1969 * these runtime invoke calls from others in the runtime.
1971 if (ji && jinfo_get_method (ji)->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1972 if (prev_ji && jinfo_get_method (prev_ji) == mono_defaults.threadpool_perform_wait_callback_method)
1977 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1979 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, &ctx_cp);
1988 unwinder_init (&unwinder);
1991 MonoContext new_ctx;
1993 int clause_index_start = 0;
1994 gboolean unwind_res = TRUE;
1995 StackFrameInfo frame;
2000 ji = jit_tls->resume_state.ji;
2001 new_ctx = jit_tls->resume_state.new_ctx;
2002 clause_index_start = jit_tls->resume_state.clause_index;
2003 lmf = jit_tls->resume_state.lmf;
2004 first_filter_idx = jit_tls->resume_state.first_filter_idx;
2005 filter_idx = jit_tls->resume_state.filter_idx;
2008 unwind_res = unwinder_unwind_frame (&unwinder, domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
2010 *(mono_get_lmf_addr ()) = lmf;
2012 jit_tls->abort_func (obj);
2013 g_assert_not_reached ();
2015 switch (frame.type) {
2016 case FRAME_TYPE_DEBUGGER_INVOKE:
2017 case FRAME_TYPE_MANAGED_TO_NATIVE:
2018 case FRAME_TYPE_TRAMPOLINE:
2021 case FRAME_TYPE_INTERP_TO_MANAGED:
2023 case FRAME_TYPE_INTERP:
2024 case FRAME_TYPE_MANAGED:
2027 g_assert_not_reached ();
2030 in_interp = frame.type == FRAME_TYPE_INTERP;
2035 ip = (guint8*)ji->code_start + frame.native_offset;
2037 ip = MONO_CONTEXT_GET_IP (ctx);
2039 method = jinfo_get_method (ji);
2041 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
2043 if (stack_overflow) {
2044 if (MONO_ARCH_STACK_GROWS_UP)
2045 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
2047 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
2049 free_stack = 0xffffff;
2052 for (i = clause_index_start; i < ji->num_clauses; i++) {
2053 MonoJitExceptionInfo *ei = &ji->clauses [i];
2054 gboolean filtered = FALSE;
2057 * During stack overflow, wait till the unwinding frees some stack
2058 * space before running handlers/finalizers.
2060 if (free_stack <= (64 * 1024))
2063 if (is_address_protected (ji, ei, ip)) {
2065 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
2068 * Have to unwrap RuntimeWrappedExceptions if the
2069 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
2071 if (non_exception && !wrap_non_exception_throws (method))
2072 ex_obj = non_exception;
2076 if (((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER))) {
2077 #ifndef MONO_CROSS_COMPILE
2078 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
2079 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
2081 g_assert (!ji->from_llvm);
2082 /* store the exception object in bp + ei->exvar_offset */
2083 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
2088 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
2090 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
2093 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2095 * Filter clauses should only be run in the
2096 * first pass of exception handling.
2098 filtered = (filter_idx == first_filter_idx);
2102 error_init (&error);
2103 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
2104 mono_object_isinst_checked (ex_obj, catch_class, &error)) || filtered) {
2106 * This guards against the situation that we abort a thread that is executing a finally clause
2107 * that was called by the EH machinery. It won't have a guard trampoline installed, so we must
2108 * check for this situation here and resume interruption if we are below the guarded block.
2110 if (G_UNLIKELY (jit_tls->handler_block)) {
2111 gboolean is_outside = FALSE;
2112 gpointer prot_bp = MONO_CONTEXT_GET_BP (&jit_tls->handler_block_context);
2113 gpointer catch_bp = MONO_CONTEXT_GET_BP (ctx);
2114 //FIXME make this stack direction aware
2116 if (catch_bp > prot_bp) {
2118 } else if (catch_bp == prot_bp) {
2119 /* Can be either try { try { } catch {} } finally {} or try { try { } finally {} } catch {}
2120 * So we check if the catch handler_start is protected by the guarded handler protected region
2123 * If there is an outstanding guarded_block return address, it means the current thread must be aborted.
2124 * This is the only way to reach out the guarded block as other cases are handled by the trampoline.
2125 * There aren't any further finally/fault handler blocks down the stack over this exception.
2126 * This must be ensured by the code that installs the guard trampoline.
2128 g_assert (ji == mini_jit_info_table_find (domain, (char *)MONO_CONTEXT_GET_IP (&jit_tls->handler_block_context), NULL));
2130 if (!is_address_protected (ji, jit_tls->handler_block, ei->handler_start)) {
2135 jit_tls->handler_block = NULL;
2136 mono_thread_resume_interruption (TRUE); /*We ignore the exception here, it will be raised later*/
2140 if (mono_trace_is_enabled () && mono_trace_eval (method))
2141 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2142 jit_tls->orig_ex_ctx_set = TRUE;
2143 MONO_PROFILER_RAISE (exception_clause, (method, i, ei->flags, ex_obj));
2144 jit_tls->orig_ex_ctx_set = FALSE;
2145 mini_set_abort_threshold (ctx);
2149 * ctx->pc points into the interpreter, after the call which transitioned to
2150 * JITted code. Store the unwind state into the
2151 * interpeter state, then resume, the interpreter will unwind itself until
2152 * it reaches the target frame and will continue execution from there.
2153 * The resuming is kinda hackish, from the native code standpoint, it looks
2154 * like the call which transitioned to JITted code has succeeded, but the
2155 * return value register etc. is not set, so we have to be careful.
2157 mono_interp_set_resume_state (jit_tls, mono_ex, frame.interp_frame, ei->handler_start);
2158 /* Undo the IP adjustment done by mono_arch_unwind_frame () */
2159 #if defined(TARGET_AMD64)
2160 ctx->gregs [AMD64_RIP] ++;
2161 #elif defined(TARGET_ARM)
2163 if (mono_arm_thumb_supported ())
2165 #elif defined(TARGET_ARM64)
2171 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2174 #ifndef DISABLE_PERFCOUNTERS
2175 mono_perfcounters->exceptions_depth += frame_count;
2177 if (obj == (MonoObject *)domain->stack_overflow_ex)
2178 jit_tls->handling_stack_ovf = FALSE;
2182 mono_error_cleanup (&error);
2183 if (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
2184 if (mono_trace_is_enabled () && mono_trace_eval (method))
2185 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2186 jit_tls->orig_ex_ctx_set = TRUE;
2187 MONO_PROFILER_RAISE (exception_clause, (method, i, ei->flags, ex_obj));
2188 jit_tls->orig_ex_ctx_set = FALSE;
2190 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2191 if (mono_trace_is_enabled () && mono_trace_eval (method))
2192 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2193 jit_tls->orig_ex_ctx_set = TRUE;
2194 MONO_PROFILER_RAISE (exception_clause, (method, i, ei->flags, ex_obj));
2195 jit_tls->orig_ex_ctx_set = FALSE;
2196 #ifndef DISABLE_PERFCOUNTERS
2197 mono_perfcounters->exceptions_finallys++;
2200 if (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2202 if (ji->from_llvm) {
2204 * LLVM compiled finally handlers follow the design
2205 * of the c++ ehabi, i.e. they call a resume function
2206 * at the end instead of returning to the caller.
2207 * So save the exception handling state,
2208 * mono_resume_unwind () will call us again to continue
2211 jit_tls->resume_state.ex_obj = obj;
2212 jit_tls->resume_state.ji = ji;
2213 jit_tls->resume_state.clause_index = i + 1;
2214 jit_tls->resume_state.ctx = *ctx;
2215 jit_tls->resume_state.new_ctx = new_ctx;
2216 jit_tls->resume_state.lmf = lmf;
2217 jit_tls->resume_state.first_filter_idx = first_filter_idx;
2218 jit_tls->resume_state.filter_idx = filter_idx;
2219 mini_set_abort_threshold (ctx);
2220 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2223 mini_set_abort_threshold (ctx);
2225 mono_interp_run_finally (&frame, i, ei->handler_start);
2227 call_filter (ctx, ei->handler_start);
2233 if (MONO_PROFILER_ENABLED (method_exception_leave) &&
2234 mono_profiler_get_call_instrumentation_flags (method) & MONO_PROFILER_CALL_INSTRUMENTATION_EXCEPTION_LEAVE) {
2235 jit_tls->orig_ex_ctx_set = TRUE;
2236 MONO_PROFILER_RAISE (method_exception_leave, (method, ex_obj));
2237 jit_tls->orig_ex_ctx_set = FALSE;
2243 g_assert_not_reached ();
2247 * mono_debugger_run_finally:
2248 * \param start_ctx saved processor state
2249 * This method is called by the Mono Debugger to call all \c finally clauses of the
2250 * current stack frame. It's used when the user issues a \c return command to make
2251 * the current stack frame return. After returning from this method, the debugger
2252 * unwinds the stack one frame and gives control back to the user.
2253 * NOTE: This method is only used when running inside the Mono Debugger.
2256 mono_debugger_run_finally (MonoContext *start_ctx)
2258 static int (*call_filter) (MonoContext *, gpointer) = NULL;
2259 MonoDomain *domain = mono_domain_get ();
2260 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2261 MonoLMF *lmf = mono_get_lmf ();
2262 MonoContext ctx, new_ctx;
2263 MonoJitInfo *ji, rji;
2268 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
2269 if (!ji || ji == (gpointer)-1)
2273 call_filter = (int (*)(MonoContext *, void *))mono_get_call_filter ();
2275 for (i = 0; i < ji->num_clauses; i++) {
2276 MonoJitExceptionInfo *ei = &ji->clauses [i];
2278 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (&ctx)) &&
2279 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
2280 call_filter (&ctx, ei->handler_start);
2286 * mono_handle_exception:
2287 * \param ctx saved processor state
2288 * \param obj the exception object
2290 * Handle the exception OBJ starting from the state CTX. Modify CTX to point to the handler clause if the exception is caught, and
2294 mono_handle_exception (MonoContext *ctx, MonoObject *obj)
2296 MONO_REQ_GC_UNSAFE_MODE;
2298 #ifndef DISABLE_PERFCOUNTERS
2299 mono_perfcounters->exceptions_thrown++;
2302 return mono_handle_exception_internal (ctx, obj, FALSE, NULL);
2305 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2307 #ifndef MONO_ARCH_USE_SIGACTION
2308 #error "Can't use sigaltstack without sigaction"
2311 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
2314 mono_setup_altstack (MonoJitTlsData *tls)
2318 guint8 *staddr = NULL;
2320 if (mono_running_on_valgrind ())
2323 mono_thread_info_get_stack_bounds (&staddr, &stsize);
2327 tls->end_of_stack = staddr + stsize;
2328 tls->stack_size = stsize;
2330 /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
2332 tls->stack_ovf_guard_base = staddr + mono_pagesize ();
2333 tls->stack_ovf_guard_size = ALIGN_TO (8 * 4096, mono_pagesize ());
2335 g_assert ((guint8*)&sa >= (guint8*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size);
2337 if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
2338 /* mprotect can fail for the main thread stack */
2339 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);
2340 g_assert (gaddr == tls->stack_ovf_guard_base);
2341 tls->stack_ovf_valloced = TRUE;
2344 /* Setup an alternate signal stack */
2345 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);
2346 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2348 g_assert (tls->signal_stack);
2350 sa.ss_sp = tls->signal_stack;
2351 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2353 g_assert (sigaltstack (&sa, NULL) == 0);
2355 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);
2359 mono_free_altstack (MonoJitTlsData *tls)
2364 sa.ss_sp = tls->signal_stack;
2365 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2366 sa.ss_flags = SS_DISABLE;
2367 err = sigaltstack (&sa, NULL);
2368 g_assert (err == 0);
2370 if (tls->signal_stack)
2371 mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MEM_ACCOUNT_EXCEPTIONS);
2372 if (tls->stack_ovf_valloced)
2373 mono_vfree (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MEM_ACCOUNT_EXCEPTIONS);
2375 mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
2378 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2381 mono_setup_altstack (MonoJitTlsData *tls)
2386 mono_free_altstack (MonoJitTlsData *tls)
2390 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2393 try_restore_stack_protection (MonoJitTlsData *jit_tls, int extra_bytes)
2395 gint32 unprotect_size = jit_tls->stack_ovf_guard_size;
2396 /* we need to leave some room for throwing the exception */
2397 while (unprotect_size >= 0 && (char*)jit_tls->stack_ovf_guard_base + unprotect_size > ((char*)&unprotect_size - extra_bytes))
2398 unprotect_size -= mono_pagesize ();
2399 /* at this point we could try and build a new domain->stack_overflow_ex, but only if there
2400 * is sufficient stack
2402 //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);
2404 mono_mprotect (jit_tls->stack_ovf_guard_base, unprotect_size, MONO_MMAP_NONE);
2405 return unprotect_size == jit_tls->stack_ovf_guard_size;
2408 static G_GNUC_UNUSED void
2409 try_more_restore (void)
2411 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2412 if (try_restore_stack_protection (jit_tls, 500))
2413 jit_tls->restore_stack_prot = NULL;
2416 static G_GNUC_UNUSED void
2417 restore_stack_protection (void)
2419 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2420 MonoException *ex = mono_domain_get ()->stack_overflow_ex;
2421 /* if we can't restore the stack protection, keep a callback installed so
2422 * we'll try to restore as much stack as we can at each return from unmanaged
2425 if (try_restore_stack_protection (jit_tls, 4096))
2426 jit_tls->restore_stack_prot = NULL;
2428 jit_tls->restore_stack_prot = try_more_restore_tramp;
2429 /* here we also throw a stack overflow exception */
2430 ex->trace_ips = NULL;
2431 ex->stack_trace = NULL;
2432 mono_raise_exception (ex);
2436 mono_altstack_restore_prot (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
2438 MONO_REQ_GC_UNSAFE_MODE;
2440 void (*func)(void) = (void (*)(void))tramp_data;
2446 mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, guint8* fault_addr)
2451 /* we got a stack overflow in the soft-guard pages
2452 * There are two cases:
2453 * 1) managed code caused the overflow: we unprotect the soft-guard page
2454 * and let the arch-specific code trigger the exception handling mechanism
2455 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
2456 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
2457 * and hope we can continue with those enabled, at least until the hard-guard page
2458 * is hit. The alternative to continuing here is to just print a message and abort.
2459 * We may add in the future the code to protect the pages again in the codepath
2460 * when we return from unmanaged to managed code.
2462 if (jit_tls->stack_ovf_guard_size && fault_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
2463 fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
2464 /* we unprotect the minimum amount we can */
2466 gboolean handled = FALSE;
2468 guard_size = jit_tls->stack_ovf_guard_size - (mono_pagesize () * SIZEOF_VOID_P / 4);
2469 while (guard_size && fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + guard_size) {
2470 guard_size -= mono_pagesize ();
2472 guard_size = jit_tls->stack_ovf_guard_size - guard_size;
2473 /*fprintf (stderr, "unprotecting: %d\n", guard_size);*/
2474 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);
2475 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2477 mono_arch_handle_altstack_exception (ctx, siginfo, fault_addr, TRUE);
2482 /* We print a message: after this even managed stack overflows
2483 * may crash the runtime
2485 mono_runtime_printf_err ("Stack overflow in unmanaged: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2486 if (!jit_tls->handling_stack_ovf) {
2487 jit_tls->restore_stack_prot = restore_stack_protection_tramp;
2488 jit_tls->handling_stack_ovf = 1;
2490 /*fprintf (stderr, "Already handling stack overflow\n");*/
2499 MonoMethod *omethod;
2501 } PrintOverflowUserData;
2503 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2505 print_overflow_stack_frame (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2507 MonoMethod *method = NULL;
2508 PrintOverflowUserData *user_data = (PrintOverflowUserData *)data;
2511 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2512 method = jinfo_get_method (frame->ji);
2515 if (user_data->count == 0) {
2516 /* The first frame is in its prolog, so a line number cannot be computed */
2517 user_data->count ++;
2521 /* If this is a one method overflow, skip the other instances */
2522 if (method == user_data->omethod)
2525 location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2526 mono_runtime_printf_err (" %s", location);
2529 if (user_data->count == 1) {
2530 mono_runtime_printf_err (" <...>");
2531 user_data->omethod = method;
2533 user_data->omethod = NULL;
2536 user_data->count ++;
2538 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2545 mono_handle_hard_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
2547 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2548 PrintOverflowUserData ud;
2552 /* we don't do much now, but we can warn the user with a useful message */
2553 mono_runtime_printf_err ("Stack overflow: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2555 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2556 mono_sigctx_to_monoctx (ctx, &mctx);
2558 mono_runtime_printf_err ("Stacktrace:");
2560 memset (&ud, 0, sizeof (ud));
2562 mono_walk_stack_with_ctx (print_overflow_stack_frame, &mctx, MONO_UNWIND_LOOKUP_ACTUAL_METHOD, &ud);
2564 if (ji && !ji->is_trampoline && jinfo_get_method (ji))
2565 mono_runtime_printf_err ("At %s", mono_method_full_name (jinfo_get_method (ji), TRUE));
2567 mono_runtime_printf_err ("At <unmanaged>.");
2574 print_stack_frame_to_stderr (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2576 MonoMethod *method = NULL;
2578 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2579 method = jinfo_get_method (frame->ji);
2582 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2583 mono_runtime_printf_err (" %s", location);
2586 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2591 static G_GNUC_UNUSED gboolean
2592 print_stack_frame_to_string (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2594 GString *p = (GString*)data;
2595 MonoMethod *method = NULL;
2597 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2598 method = jinfo_get_method (frame->ji);
2600 if (method && frame->domain) {
2601 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
2602 g_string_append_printf (p, " %s\n", location);
2605 g_string_append_printf (p, " at <unknown> <0x%05x>\n", frame->native_offset);
2610 #ifndef MONO_CROSS_COMPILE
2612 static void print_process_map (void)
2615 FILE *fp = fopen ("/proc/self/maps", "r");
2619 mono_runtime_printf_err ("no /proc/self/maps, not on linux?\n");
2623 mono_runtime_printf_err ("/proc/self/maps:");
2625 while (fgets (line, sizeof (line), fp)) {
2627 size_t len = strlen (line) - 1;
2628 if (len >= 0 && line [len] == '\n')
2631 mono_runtime_printf_err ("%s", line);
2640 static gboolean handle_crash_loop = FALSE;
2643 * mono_handle_native_crash:
2645 * Handle a native crash (e.g. SIGSEGV) while in native code by
2646 * printing diagnostic information and aborting.
2649 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2651 #ifdef MONO_ARCH_USE_SIGACTION
2652 struct sigaction sa;
2654 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2656 if (handle_crash_loop)
2659 if (mini_get_debug_options ()->suspend_on_native_crash) {
2660 mono_runtime_printf_err ("Received %s, suspending...", signal);
2671 /* prevent infinite loops in crash handling */
2672 handle_crash_loop = TRUE;
2674 /* !jit_tls means the thread was not registered with the runtime */
2675 if (jit_tls && mono_thread_internal_current ()) {
2676 mono_runtime_printf_err ("Stacktrace:\n");
2678 /* FIXME: Is MONO_UNWIND_LOOKUP_IL_OFFSET correct here? */
2679 mono_walk_stack (print_stack_frame_to_stderr, MONO_UNWIND_LOOKUP_IL_OFFSET, NULL);
2682 print_process_map ();
2684 #ifdef HAVE_BACKTRACE_SYMBOLS
2690 mono_runtime_printf_err ("\nNative stacktrace:\n");
2692 size = backtrace (array, 256);
2693 names = backtrace_symbols (array, size);
2694 for (i =0; i < size; ++i) {
2695 mono_runtime_printf_err ("\t%s", names [i]);
2699 /* Try to get more meaningful information using gdb */
2701 #if !defined(HOST_WIN32) && defined(HAVE_SYS_SYSCALL_H) && defined(SYS_fork)
2702 if (!mini_get_debug_options ()->no_gdb_backtrace) {
2703 /* From g_spawn_command_line_sync () in eglib */
2706 pid_t crashed_pid = getpid ();
2709 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
2710 * it will deadlock. Call the syscall directly instead.
2712 #if defined(HOST_ANDROID)
2713 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
2714 g_assert_not_reached ();
2715 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
2716 pid = (pid_t) syscall (SYS_fork);
2717 #elif defined(HOST_DARWIN) && HAVE_FORK
2718 pid = (pid_t) fork ();
2720 g_assert_not_reached ();
2723 #if defined (HAVE_PRCTL) && defined(PR_SET_PTRACER)
2725 // Allow gdb to attach to the process even if ptrace_scope sysctl variable is set to
2726 // a value other than 0 (the most permissive ptrace scope). Most modern Linux
2727 // distributions set the scope to 1 which allows attaching only to direct children of
2728 // the current process
2729 prctl (PR_SET_PTRACER, pid, 0, 0, 0);
2733 dup2 (STDERR_FILENO, STDOUT_FILENO);
2735 mono_gdb_render_native_backtraces (crashed_pid);
2739 mono_runtime_printf_err ("\nDebug info from gdb:\n");
2740 waitpid (pid, &status, 0);
2746 /* set DUMPABLE for this process so debuggerd can attach with ptrace(2), see:
2747 * https://android.googlesource.com/platform/bionic/+/151da681000c07da3c24cd30a3279b1ca017f452/linker/debugger.cpp#206
2748 * this has changed on later versions of Android. Also, we don't want to
2749 * set this on start-up as DUMPABLE has security implications. */
2750 prctl (PR_SET_DUMPABLE, 1);
2752 mono_runtime_printf_err ("\nNo native Android stacktrace (see debuggerd output).\n");
2757 * A SIGSEGV indicates something went very wrong so we can no longer depend
2758 * on anything working. So try to print out lots of diagnostics, starting
2759 * with ones which have a greater chance of working.
2761 mono_runtime_printf_err (
2763 "=================================================================\n"
2764 "Got a %s while executing native code. This usually indicates\n"
2765 "a fatal error in the mono runtime or one of the native libraries \n"
2766 "used by your application.\n"
2767 "=================================================================\n",
2770 #ifdef MONO_ARCH_USE_SIGACTION
2771 sa.sa_handler = SIG_DFL;
2772 sigemptyset (&sa.sa_mask);
2775 /* Remove our SIGABRT handler */
2776 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
2778 /* On some systems we get a SIGILL when calling abort (), because it might
2779 * fail to raise SIGABRT */
2780 g_assert (sigaction (SIGILL, &sa, NULL) != -1);
2783 if (!mono_do_crash_chaining) {
2784 /*Android abort is a fluke, it doesn't abort, it triggers another segv. */
2785 #if defined (HOST_ANDROID)
2796 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2798 g_assert_not_reached ();
2801 #endif /* !MONO_CROSS_COMPILE */
2804 mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
2806 MonoInternalThread *thread = mono_thread_internal_current ();
2807 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2812 GError *error = NULL;
2817 text = g_string_new (0);
2819 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
2821 g_string_append_printf (text, "\n\"%s\"", name);
2824 else if (thread->threadpool_thread)
2825 g_string_append (text, "\n\"<threadpool thread>\"");
2827 g_string_append (text, "\n\"<unnamed thread>\"");
2829 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
2830 mono_thread_internal_describe (thread, text);
2831 g_string_append (text, "\n");
2833 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2835 memcpy (&ctx, start_ctx, sizeof (MonoContext));
2837 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_print_thread_dump);
2839 mono_sigctx_to_monoctx (sigctx, &ctx);
2841 mono_walk_stack_with_ctx (print_stack_frame_to_string, &ctx, MONO_UNWIND_LOOKUP_ALL, text);
2843 mono_runtime_printf ("\t<Stack traces in thread dumps not supported on this platform>");
2846 mono_runtime_printf ("%s", text->str);
2848 #if HOST_WIN32 && TARGET_WIN32 && _DEBUG
2849 OutputDebugStringA(text->str);
2852 g_string_free (text, TRUE);
2853 mono_runtime_stdout_fflush ();
2857 * mono_print_thread_dump:
2859 * Print information about the current thread to stdout.
2860 * \p sigctx can be NULL, allowing this to be called from gdb.
2863 mono_print_thread_dump (void *sigctx)
2865 mono_print_thread_dump_internal (sigctx, NULL);
2869 mono_print_thread_dump_from_ctx (MonoContext *ctx)
2871 mono_print_thread_dump_internal (NULL, ctx);
2875 * mono_resume_unwind:
2877 * This is called by a trampoline from LLVM compiled finally clauses to continue
2881 mono_resume_unwind (MonoContext *ctx)
2883 MONO_REQ_GC_UNSAFE_MODE;
2885 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2886 MonoContext new_ctx;
2888 MONO_CONTEXT_SET_IP (ctx, MONO_CONTEXT_GET_IP (&jit_tls->resume_state.ctx));
2889 MONO_CONTEXT_SET_SP (ctx, MONO_CONTEXT_GET_SP (&jit_tls->resume_state.ctx));
2892 mono_handle_exception_internal (&new_ctx, (MonoObject *)jit_tls->resume_state.ex_obj, TRUE, NULL);
2894 mono_restore_context (&new_ctx);
2900 MonoJitExceptionInfo *ei;
2901 } FindHandlerBlockData;
2904 find_last_handler_block (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2908 FindHandlerBlockData *pdata = (FindHandlerBlockData *)data;
2909 MonoJitInfo *ji = frame->ji;
2914 ip = MONO_CONTEXT_GET_IP (ctx);
2916 for (i = 0; i < ji->num_clauses; ++i) {
2917 MonoJitExceptionInfo *ei = ji->clauses + i;
2918 if (ei->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2920 /*If ip points to the first instruction it means the handler block didn't start
2921 so we can leave its execution to the EH machinery*/
2922 if (ei->handler_start <= ip && ip < ei->data.handler_end) {
2934 install_handler_block_guard (MonoJitInfo *ji, MonoContext *ctx)
2937 MonoJitExceptionInfo *clause = NULL;
2941 ip = MONO_CONTEXT_GET_IP (ctx);
2943 for (i = 0; i < ji->num_clauses; ++i) {
2944 clause = &ji->clauses [i];
2945 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2947 if (clause->handler_start <= ip && clause->data.handler_end > ip)
2951 /*no matching finally */
2952 if (i == ji->num_clauses)
2956 bp = (guint8*)MONO_CONTEXT_GET_BP (ctx);
2957 *(bp + clause->exvar_offset) = 1;
2961 * Finds the bottom handler block running and install a block guard if needed.
2964 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2966 FindHandlerBlockData data = { 0 };
2967 MonoJitTlsData *jit_tls = (MonoJitTlsData *)ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS];
2969 /* Guard against a null MonoJitTlsData. This can happens if the thread receives the
2970 * interrupt signal before the JIT has time to initialize its TLS data for the given thread.
2972 if (!jit_tls || jit_tls->handler_block)
2975 /* Do an async safe stack walk */
2976 mono_thread_info_set_is_async_context (TRUE);
2977 mono_walk_stack_with_state (find_last_handler_block, ctx, MONO_UNWIND_NONE, &data);
2978 mono_thread_info_set_is_async_context (FALSE);
2983 memcpy (&jit_tls->handler_block_context, &data.ctx, sizeof (MonoContext));
2985 install_handler_block_guard (data.ji, &data.ctx);
2987 jit_tls->handler_block = data.ei;
2993 mono_current_thread_has_handle_block_guard (void)
2995 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2996 return jit_tls && jit_tls->handler_block != NULL;
3000 mono_set_cast_details (MonoClass *from, MonoClass *to)
3002 MonoJitTlsData *jit_tls = NULL;
3004 if (mini_get_debug_options ()->better_cast_details) {
3005 jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
3006 jit_tls->class_cast_from = from;
3007 jit_tls->class_cast_to = to;
3012 /*returns false if the thread is not attached*/
3014 mono_thread_state_init_from_sigctx (MonoThreadUnwindState *ctx, void *sigctx)
3016 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
3017 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3024 mono_sigctx_to_monoctx (sigctx, &ctx->ctx);
3026 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3027 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3028 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
3031 mono_thread_state_init (ctx);
3034 if (!ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] || !ctx->unwind_data [MONO_UNWIND_DATA_LMF])
3040 g_error ("Implement mono_arch_sigctx_to_monoctx for the current target");
3046 mono_thread_state_init (MonoThreadUnwindState *ctx)
3048 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3050 #if defined(MONO_CROSS_COMPILE)
3051 ctx->valid = FALSE; //A cross compiler doesn't need to suspend.
3052 #elif MONO_ARCH_HAS_MONO_CONTEXT
3053 MONO_CONTEXT_GET_CURRENT (ctx->ctx);
3055 g_error ("Use a null sigctx requires a working mono-context");
3058 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3059 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3060 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread ? thread->jit_data : NULL;
3066 mono_thread_state_init_from_monoctx (MonoThreadUnwindState *ctx, MonoContext *mctx)
3068 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3075 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3076 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3077 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
3082 /*returns false if the thread is not attached*/
3084 mono_thread_state_init_from_current (MonoThreadUnwindState *ctx)
3086 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
3087 MONO_ARCH_CONTEXT_DEF
3089 mono_arch_flush_register_windows ();
3091 if (!thread || !thread->jit_data) {
3095 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
3096 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx->ctx);
3098 MONO_INIT_CONTEXT_FROM_FUNC (&ctx->ctx, mono_thread_state_init_from_current);
3101 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
3102 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
3103 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
3109 mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx)
3111 mono_handle_exception (ctx, (MonoObject *)exc);
3112 mono_restore_context (ctx);
3115 /*FIXME Move all monoctx -> sigctx conversion to signal handlers once all archs support utils/mono-context */
3117 mono_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
3119 #ifdef MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK
3120 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
3121 jit_tls->ex_ctx = *ctx;
3123 mono_arch_setup_async_callback (ctx, async_cb, user_data);
3125 g_error ("This target doesn't support mono_arch_setup_async_callback");
3130 * mono_restore_context:
3132 * Call the architecture specific restore context function.
3135 mono_restore_context (MonoContext *ctx)
3137 static void (*restore_context) (MonoContext *);
3139 if (!restore_context)
3140 restore_context = (void (*)(MonoContext *))mono_get_restore_context ();
3141 restore_context (ctx);
3142 g_assert_not_reached ();
3146 * mono_jinfo_get_unwind_info:
3148 * Return the unwind info for JI.
3151 mono_jinfo_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3153 if (ji->has_unwind_info) {
3154 /* The address/length in the MonoJitInfo structure itself */
3155 MonoUnwindJitInfo *info = mono_jit_info_get_unwind_info (ji);
3156 *unwind_info_len = info->unw_info_len;
3157 return info->unw_info;
3158 } else if (ji->from_aot)
3159 return mono_aot_get_unwind_info (ji, unwind_info_len);
3161 return mono_get_cached_unwind_info (ji->unwind_info, unwind_info_len);
3165 mono_jinfo_get_epilog_size (MonoJitInfo *ji)
3167 MonoArchEHJitInfo *info;
3169 info = mono_jit_info_get_arch_eh_info (ji);
3172 return info->epilog_size;
3176 * LLVM/Bitcode exception handling.
3180 throw_exception (MonoObject *ex, gboolean rethrow)
3182 MONO_REQ_GC_UNSAFE_MODE;
3185 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3186 MonoException *mono_ex;
3188 if (!mono_object_isinst_checked (ex, mono_defaults.exception_class, &error)) {
3189 mono_error_assert_ok (&error);
3190 mono_ex = mono_get_exception_runtime_wrapped_checked (ex, &error);
3191 mono_error_assert_ok (&error);
3192 jit_tls->thrown_non_exc = mono_gchandle_new (ex, FALSE);
3195 mono_ex = (MonoException*)ex;
3198 jit_tls->thrown_exc = mono_gchandle_new ((MonoObject*)mono_ex, FALSE);
3201 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
3202 GList *l, *ips = NULL;
3205 _Unwind_Backtrace (build_stack_trace, &ips);
3206 /* The list contains ip-gshared info pairs */
3208 ips = g_list_reverse (ips);
3209 for (l = ips; l; l = l->next) {
3210 trace = g_list_append (trace, l->data);
3211 trace = g_list_append (trace, NULL);
3213 MonoArray *ips_arr = mono_glist_to_array (trace, mono_defaults.int_class, &error);
3214 mono_error_assert_ok (&error);
3215 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3217 g_list_free (trace);
3221 mono_llvm_cpp_throw_exception ();
3225 mono_llvm_throw_exception (MonoObject *ex)
3227 throw_exception (ex, FALSE);
3231 mono_llvm_rethrow_exception (MonoObject *ex)
3233 throw_exception (ex, TRUE);
3237 mono_llvm_raise_exception (MonoException *e)
3239 mono_llvm_throw_exception ((MonoObject*)e);
3243 mono_llvm_throw_corlib_exception (guint32 ex_token_index)
3245 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
3248 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
3250 mono_llvm_throw_exception ((MonoObject*)ex);
3254 * mono_llvm_resume_exception:
3256 * Resume exception propagation.
3259 mono_llvm_resume_exception (void)
3261 mono_llvm_cpp_throw_exception ();
3265 * mono_llvm_load_exception:
3267 * Return the currently thrown exception.
3270 mono_llvm_load_exception (void)
3273 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3275 MonoException *mono_ex = (MonoException*)mono_gchandle_get_target (jit_tls->thrown_exc);
3277 if (mono_ex->trace_ips) {
3278 GList *trace_ips = NULL;
3279 gpointer ip = __builtin_return_address (0);
3281 size_t upper = mono_array_length (mono_ex->trace_ips);
3283 for (int i = 0; i < upper; i += TRACE_IP_ENTRY_SIZE) {
3284 gpointer curr_ip = mono_array_get (mono_ex->trace_ips, gpointer, i);
3285 for (int j = 0; j < TRACE_IP_ENTRY_SIZE; ++j) {
3286 gpointer p = mono_array_get (mono_ex->trace_ips, gpointer, i + j);
3287 trace_ips = g_list_append (trace_ips, p);
3293 // FIXME: Does this work correctly for rethrows?
3294 // We may be discarding useful information
3295 // when this gets GC'ed
3296 MonoArray *ips_arr = mono_glist_to_array (trace_ips, mono_defaults.int_class, &error);
3297 mono_error_assert_ok (&error);
3298 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3299 g_list_free (trace_ips);
3302 //MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
3304 MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, 0, &error));
3305 mono_error_assert_ok (&error);
3306 MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new_checked (mono_domain_get (), mono_defaults.stack_frame_class, 0, &error));
3307 mono_error_assert_ok (&error);
3310 return &mono_ex->object;
3314 * mono_llvm_clear_exception:
3316 * Mark the currently thrown exception as handled.
3319 mono_llvm_clear_exception (void)
3321 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3322 mono_gchandle_free (jit_tls->thrown_exc);
3323 jit_tls->thrown_exc = 0;
3324 if (jit_tls->thrown_non_exc)
3325 mono_gchandle_free (jit_tls->thrown_non_exc);
3326 jit_tls->thrown_non_exc = 0;
3328 mono_memory_barrier ();
3332 * mono_llvm_match_exception:
3334 * Return the innermost clause containing REGION_START-REGION_END which can handle
3335 * the current exception.
3338 mono_llvm_match_exception (MonoJitInfo *jinfo, guint32 region_start, guint32 region_end, gpointer rgctx, MonoObject *this_obj)
3341 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3345 g_assert (jit_tls->thrown_exc);
3346 exc = mono_gchandle_get_target (jit_tls->thrown_exc);
3347 if (jit_tls->thrown_non_exc) {
3349 * Have to unwrap RuntimeWrappedExceptions if the
3350 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
3352 if (!wrap_non_exception_throws (jinfo_get_method (jinfo)))
3353 exc = mono_gchandle_get_target (jit_tls->thrown_non_exc);
3356 for (int i = 0; i < jinfo->num_clauses; i++) {
3357 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3358 MonoClass *catch_class;
3360 if (! (ei->try_offset == region_start && ei->try_offset + ei->try_len == region_end) )
3363 catch_class = ei->data.catch_class;
3364 if (mono_class_is_open_constructed_type (&catch_class->byval_arg)) {
3365 MonoGenericContext context;
3366 MonoType *inflated_type;
3368 g_assert (rgctx || this_obj);
3369 context = get_generic_context_from_stack_frame (jinfo, rgctx ? rgctx : this_obj->vtable);
3370 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
3371 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3373 catch_class = mono_class_from_mono_type (inflated_type);
3374 mono_metadata_free_type (inflated_type);
3377 // FIXME: Handle edge cases handled in get_exception_catch_class
3378 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (exc, catch_class, &error)) {
3379 index = ei->clause_index;
3382 mono_error_assert_ok (&error);
3384 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3385 g_assert_not_reached ();
3394 mono_debug_personality (int a, _Unwind_Action b,
3395 uint64_t c, struct _Unwind_Exception *d, struct _Unwind_Context *e)
3397 g_assert_not_reached ();
3401 mono_debug_personality (void);
3404 mono_debug_personality (void)
3406 g_assert_not_reached ();