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/mono-debug.h>
62 #include <mono/metadata/profiler.h>
63 #include <mono/metadata/mono-endian.h>
64 #include <mono/metadata/environment.h>
65 #include <mono/metadata/mono-mlist.h>
66 #include <mono/utils/mono-mmap.h>
67 #include <mono/utils/mono-logger-internals.h>
68 #include <mono/utils/mono-error.h>
69 #include <mono/utils/mono-error-internals.h>
73 #include "debugger-agent.h"
74 #include "seq-points.h"
75 #include "llvm-runtime.h"
76 #include "mini-llvm.h"
77 #include "interp/interp.h"
80 #include "mini-llvm-cpp.h"
83 #ifndef MONO_ARCH_CONTEXT_DEF
84 #define MONO_ARCH_CONTEXT_DEF
87 #ifndef MONO_ARCH_STACK_GROWS_UP
88 #define MONO_ARCH_STACK_GROWS_UP 0
91 static gpointer restore_context_func, call_filter_func;
92 static gpointer throw_exception_func, rethrow_exception_func;
93 static gpointer throw_corlib_exception_func;
95 static gpointer try_more_restore_tramp = NULL;
96 static gpointer restore_stack_protection_tramp = NULL;
98 static void try_more_restore (void);
99 static void restore_stack_protection (void);
100 static void mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data);
101 static void mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx);
102 static void mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data);
103 static gboolean mono_current_thread_has_handle_block_guard (void);
106 first_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer addr)
108 gpointer **data = (gpointer **)addr;
114 // FIXME: Happens with llvm_only
119 *data = MONO_CONTEXT_GET_SP (ctx);
125 mono_thread_get_managed_sp (void)
127 gpointer addr = NULL;
128 mono_walk_stack (first_managed, MONO_UNWIND_SIGNAL_SAFE, &addr);
133 mini_abort_threshold_offset (gpointer threshold, gpointer sp)
135 intptr_t stack_threshold = (intptr_t) threshold;
136 intptr_t stack_pointer = (intptr_t) sp;
138 const int direction = MONO_ARCH_STACK_GROWS_UP ? -1 : 1;
139 intptr_t magnitude = stack_pointer - stack_threshold;
141 return direction * magnitude;
145 mini_clear_abort_threshold (void)
147 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
148 jit_tls->abort_exc_stack_threshold = NULL;
152 mini_set_abort_threshold (MonoContext *ctx)
154 gpointer sp = MONO_CONTEXT_GET_SP (ctx);
155 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
156 // Only move it up, to avoid thrown/caught
157 // exceptions lower in the stack from triggering
159 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
160 if (!jit_tls->abort_exc_stack_threshold || above_threshold) {
161 jit_tls->abort_exc_stack_threshold = sp;
165 // Note: In the case that the frame is above where the thread abort
166 // was set we bump the threshold so that functions called from the new,
167 // higher threshold don't trigger the thread abort exception
168 static inline gboolean
169 mini_above_abort_threshold (void)
171 gpointer sp = mono_thread_get_managed_sp ();
172 MonoJitTlsData *jit_tls = (MonoJitTlsData*) mono_tls_get_jit_tls ();
177 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
180 jit_tls->abort_exc_stack_threshold = sp;
182 return above_threshold;
186 mono_get_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
189 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
195 mono_exceptions_init (void)
197 MonoRuntimeExceptionHandlingCallbacks cbs;
199 restore_context_func = mono_aot_get_trampoline ("restore_context");
200 call_filter_func = mono_aot_get_trampoline ("call_filter");
201 throw_exception_func = mono_aot_get_trampoline ("throw_exception");
202 rethrow_exception_func = mono_aot_get_trampoline ("rethrow_exception");
206 restore_context_func = mono_arch_get_restore_context (&info, FALSE);
207 mono_tramp_info_register (info, NULL);
208 call_filter_func = mono_arch_get_call_filter (&info, FALSE);
209 mono_tramp_info_register (info, NULL);
210 throw_exception_func = mono_arch_get_throw_exception (&info, FALSE);
211 mono_tramp_info_register (info, NULL);
212 rethrow_exception_func = mono_arch_get_rethrow_exception (&info, FALSE);
213 mono_tramp_info_register (info, NULL);
215 #ifdef MONO_ARCH_HAVE_RESTORE_STACK_SUPPORT
216 if (!mono_llvm_only) {
217 try_more_restore_tramp = mono_create_specific_trampoline (try_more_restore, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
218 restore_stack_protection_tramp = mono_create_specific_trampoline (restore_stack_protection, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
222 #ifdef MONO_ARCH_HAVE_EXCEPTIONS_INIT
223 mono_arch_exceptions_init ();
225 #ifdef ENABLE_INTERPRETER
226 if (mono_use_interpreter)
227 cbs.mono_walk_stack_with_ctx = interp_walk_stack_with_ctx;
230 cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
232 cbs.mono_walk_stack_with_state = mono_walk_stack_with_state;
235 cbs.mono_raise_exception = mono_llvm_raise_exception;
237 cbs.mono_raise_exception = (void (*)(MonoException *))mono_get_throw_exception ();
238 cbs.mono_raise_exception_with_ctx = mono_raise_exception_with_ctx;
239 cbs.mono_exception_walk_trace = mono_exception_walk_trace;
240 cbs.mono_install_handler_block_guard = mono_install_handler_block_guard;
241 cbs.mono_current_thread_has_handle_block_guard = mono_current_thread_has_handle_block_guard;
242 cbs.mono_clear_abort_threshold = mini_clear_abort_threshold;
243 cbs.mono_above_abort_threshold = mini_above_abort_threshold;
244 mono_install_eh_callbacks (&cbs);
245 mono_install_get_seq_point (mono_get_seq_point_for_native_offset);
249 mono_get_throw_exception (void)
251 g_assert (throw_exception_func);
252 return throw_exception_func;
256 mono_get_rethrow_exception (void)
258 g_assert (rethrow_exception_func);
259 return rethrow_exception_func;
263 mono_get_call_filter (void)
265 g_assert (call_filter_func);
266 return call_filter_func;
270 mono_get_restore_context (void)
272 g_assert (restore_context_func);
273 return restore_context_func;
277 mono_get_throw_corlib_exception (void)
279 gpointer code = NULL;
282 /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
283 if (throw_corlib_exception_func)
284 return throw_corlib_exception_func;
287 code = mono_aot_get_trampoline ("throw_corlib_exception");
289 code = mono_arch_get_throw_corlib_exception (&info, FALSE);
290 mono_tramp_info_register (info, NULL);
293 mono_memory_barrier ();
295 throw_corlib_exception_func = code;
297 return throw_corlib_exception_func;
301 * mono_get_throw_exception_addr:
303 * Return an address which stores the result of
304 * mono_get_throw_exception.
307 mono_get_throw_exception_addr (void)
309 return &throw_exception_func;
313 is_address_protected (MonoJitInfo *ji, MonoJitExceptionInfo *ei, gpointer ip)
315 MonoTryBlockHoleTableJitInfo *table;
320 if (ei->try_start > ip || ip >= ei->try_end)
323 if (!ji->has_try_block_holes)
326 table = mono_jit_info_get_try_block_hole_table_info (ji);
327 offset = (guint32)((char*)ip - (char*)ji->code_start);
328 clause = (guint16)(ei - ji->clauses);
329 g_assert (clause < ji->num_clauses);
331 for (i = 0; i < table->num_holes; ++i) {
332 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
333 if (hole->clause == clause && hole->offset <= offset && hole->offset + hole->length > offset)
339 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
342 static gboolean show_native_addresses = TRUE;
344 static gboolean show_native_addresses = FALSE;
347 static _Unwind_Reason_Code
348 build_stack_trace (struct _Unwind_Context *frame_ctx, void *state)
350 MonoDomain *domain = mono_domain_get ();
351 uintptr_t ip = _Unwind_GetIP (frame_ctx);
353 if (show_native_addresses || mono_jit_info_table_find (domain, (char*)ip)) {
354 GList **trace_ips = (GList **)state;
355 *trace_ips = g_list_prepend (*trace_ips, (gpointer)ip);
358 return _URC_NO_REASON;
362 get_unwind_backtrace (void)
366 _Unwind_Backtrace (build_stack_trace, &ips);
368 return g_slist_reverse (ips);
374 get_unwind_backtrace (void)
384 * Translate between the mono_arch_unwind_frame function and the old API.
387 find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
388 MonoContext *new_ctx, MonoLMF **lmf, gboolean *managed)
390 StackFrameInfo frame;
393 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
395 /* Avoid costly table lookup during stack overflow */
396 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
399 ji = mini_jit_info_table_find (domain, (char *)ip, NULL);
404 err = mono_arch_unwind_frame (domain, jit_tls, ji, ctx, new_ctx, lmf, NULL, &frame);
406 return (MonoJitInfo *)-1;
408 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
410 * Remove any unused lmf.
411 * Mask out the lower bits which might be used to hold additional information.
413 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
416 /* Convert between the new and the old APIs */
417 switch (frame.type) {
418 case FRAME_TYPE_MANAGED:
422 case FRAME_TYPE_TRAMPOLINE:
424 case FRAME_TYPE_MANAGED_TO_NATIVE:
428 memset (res, 0, sizeof (MonoJitInfo));
429 res->d.method = frame.method;
432 case FRAME_TYPE_DEBUGGER_INVOKE: {
436 * The normal exception handling code can't handle this frame, so just
439 ji = find_jit_info (domain, jit_tls, res, NULL, new_ctx, &tmp_ctx, lmf, managed);
440 memcpy (new_ctx, &tmp_ctx, sizeof (MonoContext));
444 g_assert_not_reached ();
449 /* mono_find_jit_info:
451 * This function is used to gather information from @ctx. It return the
452 * MonoJitInfo of the corresponding function, unwinds one stack frame and
453 * stores the resulting context into @new_ctx. It also stores a string
454 * describing the stack location into @trace (if not NULL), and modifies
455 * the @lmf if necessary. @native_offset return the IP offset from the
456 * start of the function or -1 if that info is not available.
459 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
460 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
464 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
466 MonoMethod *method = NULL;
477 ji = find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, lmf, &managed2);
479 if (ji == (gpointer)-1)
482 if (ji && !ji->is_trampoline)
483 method = jinfo_get_method (ji);
485 if (managed2 || (method && method->wrapper_type)) {
486 const char *real_ip, *start;
489 start = (const char *)ji->code_start;
491 /* ctx->ip points into native code */
492 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
494 real_ip = (const char*)ip;
496 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
497 offset = real_ip - start;
502 *native_offset = offset;
505 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
509 *trace = mono_debug_print_stack_frame (method, offset, domain);
512 char *fname = mono_method_full_name (jinfo_get_method (res), TRUE);
513 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
522 * mono_find_jit_info_ext:
524 * A version of mono_find_jit_info which returns all data in the StackFrameInfo
526 * A note about frames of type FRAME_TYPE_MANAGED_TO_NATIVE:
527 * - These frames are used to mark managed-to-native transitions, so CTX will refer to native
528 * code, and new_ctx will refer to the last managed frame. The caller should unwind once more
529 * to obtain the last managed frame.
530 * If SAVE_LOCATIONS is not NULL, it should point to an array of size MONO_MAX_IREGS.
531 * On return, it will be filled with the locations where callee saved registers are saved
532 * by the current frame. This is returned outside of StackFrameInfo because it can be
533 * quite large on some platforms.
534 * If ASYNC true, this function will be async safe, but some fields of frame and frame->ji will
538 mono_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls,
539 MonoJitInfo *prev_ji, MonoContext *ctx,
540 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
541 mgreg_t **save_locations,
542 StackFrameInfo *frame)
545 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
547 MonoDomain *target_domain = domain;
548 MonoMethod *method = NULL;
549 gboolean async = mono_thread_info_is_async_context ();
554 /* Avoid costly table lookup during stack overflow */
555 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
558 ji = mini_jit_info_table_find (domain, (char *)ip, &target_domain);
561 target_domain = domain;
564 memset (save_locations, 0, MONO_MAX_IREGS * sizeof (mgreg_t*));
566 err = mono_arch_unwind_frame (target_domain, jit_tls, ji, ctx, new_ctx, lmf, save_locations, frame);
570 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
572 * Remove any unused lmf.
573 * Mask out the lower bits which might be used to hold additional information.
575 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
578 if (frame->ji && !frame->ji->is_trampoline && !frame->ji->async)
579 method = jinfo_get_method (frame->ji);
581 if (frame->type == FRAME_TYPE_MANAGED && method) {
582 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
583 frame->managed = TRUE;
586 if (frame->type == FRAME_TYPE_MANAGED_TO_NATIVE) {
588 * This type of frame is just a marker, the caller should unwind once more to get the
589 * last managed frame.
592 frame->method = NULL;
595 frame->native_offset = -1;
596 frame->domain = target_domain;
597 frame->async_context = async;
601 if (frame->type == FRAME_TYPE_MANAGED)
602 frame->method = method;
604 if (ji && (frame->managed || (method && method->wrapper_type))) {
605 const char *real_ip, *start;
607 start = (const char *)ji->code_start;
608 if (frame->type == FRAME_TYPE_MANAGED)
609 real_ip = (const char*)ip;
611 /* ctx->ip points into native code */
612 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
614 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
615 frame->native_offset = real_ip - start;
617 frame->native_offset = -1;
621 *trace = mono_debug_print_stack_frame (method, frame->native_offset, domain);
623 if (trace && frame->method) {
624 char *fname = mono_method_full_name (frame->method, TRUE);
625 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
634 * This function is async-safe.
637 get_generic_info_from_stack_frame (MonoJitInfo *ji, MonoContext *ctx)
639 MonoGenericJitInfo *gi;
643 if (!ji->has_generic_jit_info)
645 gi = mono_jit_info_get_generic_jit_info (ji);
651 * Search location list if available, it contains the precise location of the
652 * argument for every pc offset, even if the method was interrupted while it was in
656 int offset = (mgreg_t)MONO_CONTEXT_GET_IP (ctx) - (mgreg_t)ji->code_start;
659 for (i = 0; i < gi->nlocs; ++i) {
660 MonoDwarfLocListEntry *entry = &gi->locations [i];
662 if (offset >= entry->from && (offset < entry->to || entry->to == 0)) {
664 info = (gpointer)mono_arch_context_get_int_reg (ctx, entry->reg);
666 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, entry->reg) + entry->offset);
670 g_assert (i < gi->nlocs);
673 info = (gpointer)mono_arch_context_get_int_reg (ctx, gi->this_reg);
675 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
679 method = jinfo_get_method (ji);
680 if (mono_method_get_context (method)->method_inst) {
681 /* A MonoMethodRuntimeGenericContext* */
683 } else if ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype) {
687 /* Avoid returning a managed object */
688 MonoObject *this_obj = (MonoObject *)info;
690 return this_obj->vtable;
695 * generic_info is either a MonoMethodRuntimeGenericContext or a MonoVTable.
697 static MonoGenericContext
698 get_generic_context_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
700 MonoGenericContext context = { NULL, NULL };
701 MonoClass *klass, *method_container_class;
704 g_assert (generic_info);
706 method = jinfo_get_method (ji);
707 g_assert (method->is_inflated);
708 if (mono_method_get_context (method)->method_inst) {
709 MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext *)generic_info;
711 klass = mrgctx->class_vtable->klass;
712 context.method_inst = mrgctx->method_inst;
713 g_assert (context.method_inst);
715 MonoVTable *vtable = (MonoVTable *)generic_info;
717 klass = vtable->klass;
720 //g_assert (!mono_class_is_gtd (method->klass));
721 if (mono_class_is_ginst (method->klass))
722 method_container_class = mono_class_get_generic_class (method->klass)->container_class;
724 method_container_class = method->klass;
726 /* class might refer to a subclass of method's class */
727 while (!(klass == method->klass || (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->container_class == method_container_class))) {
728 klass = klass->parent;
732 if (mono_class_is_ginst (klass) || mono_class_is_gtd (klass))
733 context.class_inst = mini_class_get_context (klass)->class_inst;
735 if (mono_class_is_ginst (klass))
736 g_assert (mono_class_has_parent_and_ignore_generics (mono_class_get_generic_class (klass)->container_class, method_container_class));
738 g_assert (mono_class_has_parent_and_ignore_generics (klass, method_container_class));
744 get_method_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
747 MonoGenericContext context;
750 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
751 return jinfo_get_method (ji);
752 context = get_generic_context_from_stack_frame (ji, generic_info);
754 method = jinfo_get_method (ji);
755 method = mono_method_get_declaring_generic_method (method);
756 method = mono_class_inflate_generic_method_checked (method, &context, &error);
757 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
763 * mono_exception_walk_native_trace:
764 * @ex: The exception object whose frames should be walked
765 * @func: callback to call for each stack frame
766 * @user_data: data passed to the callback
768 * This function walks the stacktrace of an exception. For
769 * each frame the callback function is called with the relevant info.
770 * The walk ends when no more stack frames are found or when the callback
771 * returns a TRUE value.
775 mono_exception_walk_trace (MonoException *ex, MonoExceptionFrameWalk func, gpointer user_data)
777 MONO_REQ_GC_UNSAFE_MODE;
779 MonoDomain *domain = mono_domain_get ();
780 MonoArray *ta = ex->trace_ips;
786 len = mono_array_length (ta) >> 1;
787 for (i = 0; i < len; i++) {
788 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
789 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
790 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)ip);
793 if (func (NULL, ip, 0, FALSE, user_data))
796 MonoMethod *method = get_method_from_stack_frame (ji, generic_info);
797 if (func (method, ji->code_start, (char *) ip - (char *) ji->code_start, TRUE, user_data))
806 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
809 MonoDomain *domain = mono_domain_get ();
811 MonoArray *ta = exc->trace_ips;
812 MonoDebugSourceLocation *location;
816 /* Exception is not thrown yet */
817 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, 0, &error);
818 mono_error_set_pending_exception (&error);
822 len = mono_array_length (ta) >> 1;
824 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0, &error);
825 if (mono_error_set_pending_exception (&error))
828 for (i = skip; i < len; i++) {
830 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, &error);
831 if (!mono_error_ok (&error)) {
832 mono_error_set_pending_exception (&error);
835 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
836 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
839 ji = mono_jit_info_table_find (domain, (char *)ip);
841 /* Unmanaged frame */
842 mono_array_setref (res, i, sf);
846 g_assert (ji != NULL);
849 /* Can't resolve actual method */
850 method = jinfo_get_method (ji);
852 method = get_method_from_stack_frame (ji, generic_info);
853 if (jinfo_get_method (ji)->wrapper_type) {
857 s = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION);
858 MONO_OBJECT_SETREF (sf, internal_method_name, mono_string_new (domain, s));
862 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, &error);
863 if (!mono_error_ok (&error)) {
864 mono_error_set_pending_exception (&error);
867 MONO_OBJECT_SETREF (sf, method, rm);
870 sf->method_index = ji->from_aot ? mono_aot_find_method_index (method) : 0xffffff;
871 sf->method_address = (gsize) ji->code_start;
872 sf->native_offset = (char *)ip - (char *)ji->code_start;
875 * mono_debug_lookup_source_location() returns both the file / line number information
876 * and the IL offset. Note that computing the IL offset is already an expensive
877 * operation, so we shouldn't call this method twice.
879 location = mono_debug_lookup_source_location (jinfo_get_method (ji), sf->native_offset, domain);
881 sf->il_offset = location->il_offset;
884 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (ji), sf->native_offset, NULL, &sp))
885 sf->il_offset = sp.il_offset;
890 if (need_file_info) {
891 if (location && location->source_file) {
892 MONO_OBJECT_SETREF (sf, filename, mono_string_new (domain, location->source_file));
893 sf->line = location->row;
894 sf->column = location->column;
896 sf->line = sf->column = 0;
901 mono_debug_free_source_location (location);
902 mono_array_setref (res, i, sf);
909 mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
912 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
913 if (jit_tls && jit_tls->orig_ex_ctx_set)
914 start_ctx = &jit_tls->orig_ex_ctx;
916 mono_walk_stack_with_ctx (func, start_ctx, unwind_options, user_data);
919 * mono_walk_stack_with_ctx:
921 * Unwind the current thread starting at @start_ctx.
923 * If @start_ctx is null, we capture the current context.
926 mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
928 MonoContext extra_ctx;
929 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
930 MONO_ARCH_CONTEXT_DEF
932 if (!thread || !thread->jit_data)
936 mono_arch_flush_register_windows ();
938 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
939 MONO_INIT_CONTEXT_FROM_CURRENT (&extra_ctx);
941 MONO_INIT_CONTEXT_FROM_FUNC (&extra_ctx, mono_walk_stack_with_ctx);
943 start_ctx = &extra_ctx;
946 mono_walk_stack_full (func, start_ctx, mono_domain_get (), (MonoJitTlsData *)thread->jit_data, mono_get_lmf (), unwind_options, user_data);
950 * mono_walk_stack_with_state:
952 * Unwind a thread described by @state.
954 * State must be valid (state->valid == TRUE).
956 * If you are using this function to unwind another thread, make sure it is suspended.
958 * If @state is null, we capture the current context.
961 mono_walk_stack_with_state (MonoJitStackWalk func, MonoThreadUnwindState *state, MonoUnwindOptions unwind_options, void *user_data)
963 MonoThreadUnwindState extra_state;
965 g_assert (!mono_thread_info_is_async_context ());
966 if (!mono_thread_state_init_from_current (&extra_state))
968 state = &extra_state;
971 g_assert (state->valid);
973 if (!state->unwind_data [MONO_UNWIND_DATA_DOMAIN])
977 mono_walk_stack_full (func,
979 (MonoDomain *)state->unwind_data [MONO_UNWIND_DATA_DOMAIN],
980 (MonoJitTlsData *)state->unwind_data [MONO_UNWIND_DATA_JIT_TLS],
981 (MonoLMF *)state->unwind_data [MONO_UNWIND_DATA_LMF],
982 unwind_options, user_data);
986 mono_walk_stack (MonoJitStackWalk func, MonoUnwindOptions options, void *user_data)
988 MonoThreadUnwindState state;
989 if (!mono_thread_state_init_from_current (&state))
991 mono_walk_stack_with_state (func, &state, options, user_data);
995 * mono_walk_stack_full:
996 * @func: callback to call for each stack frame
997 * @domain: starting appdomain, can be NULL to use the current domain
998 * @unwind_options: what extra information the unwinder should gather
999 * @start_ctx: starting state of the stack walk, can be NULL.
1000 * @thread: the thread whose stack to walk, can be NULL to use the current thread
1001 * @lmf: the LMF of @thread, can be NULL to use the LMF of the current thread
1002 * @user_data: data passed to the callback
1004 * This function walks the stack of a thread, starting from the state
1005 * represented by start_ctx. For each frame the callback
1006 * function is called with the relevant info. The walk ends when no more
1007 * managed stack frames are found or when the callback returns a TRUE value.
1010 mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data)
1013 MonoContext ctx, new_ctx;
1014 StackFrameInfo frame;
1016 mgreg_t *reg_locations [MONO_MAX_IREGS];
1017 mgreg_t *new_reg_locations [MONO_MAX_IREGS];
1018 gboolean get_reg_locations = unwind_options & MONO_UNWIND_REG_LOCATIONS;
1019 gboolean async = mono_thread_info_is_async_context ();
1021 if (mono_llvm_only) {
1027 ips = get_unwind_backtrace ();
1028 for (l = ips; l; l = l->next) {
1029 guint8 *ip = (guint8*)l->data;
1030 memset (&frame, 0, sizeof (StackFrameInfo));
1031 frame.ji = mini_jit_info_table_find (domain, (char*)ip, &frame.domain);
1032 if (!frame.ji || frame.ji->is_trampoline)
1034 frame.type = FRAME_TYPE_MANAGED;
1035 frame.method = jinfo_get_method (frame.ji);
1036 // FIXME: Cannot lookup the actual method
1037 frame.actual_method = frame.method;
1038 if (frame.type == FRAME_TYPE_MANAGED) {
1039 if (!frame.method->wrapper_type || frame.method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
1040 frame.managed = TRUE;
1042 frame.native_offset = ip - (guint8*)frame.ji->code_start;
1043 frame.il_offset = -1;
1045 if (func (&frame, NULL, user_data))
1052 g_assert (start_ctx);
1055 /*The LMF will be null if the target have no managed frames.*/
1056 /* g_assert (lmf); */
1059 g_assert (unwind_options == MONO_UNWIND_NONE);
1061 memcpy (&ctx, start_ctx, sizeof (MonoContext));
1062 memset (reg_locations, 0, sizeof (reg_locations));
1064 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
1066 res = mono_find_jit_info_ext (domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, get_reg_locations ? new_reg_locations : NULL, &frame);
1070 if ((unwind_options & MONO_UNWIND_LOOKUP_IL_OFFSET) && frame.ji && !frame.ji->is_trampoline) {
1071 MonoDebugSourceLocation *source;
1073 source = mono_debug_lookup_source_location (jinfo_get_method (frame.ji), frame.native_offset, domain);
1075 il_offset = source->il_offset;
1078 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (frame.ji), frame.native_offset, NULL, &sp))
1079 il_offset = sp.il_offset;
1083 mono_debug_free_source_location (source);
1087 frame.il_offset = il_offset;
1089 if ((unwind_options & MONO_UNWIND_LOOKUP_ACTUAL_METHOD) && frame.ji && !frame.ji->is_trampoline) {
1090 frame.actual_method = get_method_from_stack_frame (frame.ji, get_generic_info_from_stack_frame (frame.ji, &ctx));
1092 frame.actual_method = frame.method;
1095 if (get_reg_locations)
1096 frame.reg_locations = reg_locations;
1098 if (func (&frame, &ctx, user_data))
1101 if (get_reg_locations) {
1102 for (i = 0; i < MONO_MAX_IREGS; ++i)
1103 if (new_reg_locations [i])
1104 reg_locations [i] = new_reg_locations [i];
1112 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
1113 MonoReflectionMethod **method,
1114 gint32 *iloffset, gint32 *native_offset,
1115 MonoString **file, gint32 *line, gint32 *column)
1118 MonoDomain *domain = mono_domain_get ();
1119 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1120 MonoLMF *lmf = mono_get_lmf ();
1121 MonoJitInfo *ji = NULL;
1122 MonoContext ctx, new_ctx;
1123 MonoDebugSourceLocation *location;
1124 MonoMethod *jmethod = NULL, *actual_method;
1125 StackFrameInfo frame;
1128 MONO_ARCH_CONTEXT_DEF;
1130 if (mono_llvm_only) {
1132 MonoDomain *frame_domain;
1133 guint8 *frame_ip = NULL;
1135 /* FIXME: Generalize this code with an interface which returns an array of StackFrame structures */
1137 ips = get_unwind_backtrace ();
1138 for (l = ips; l && skip >= 0; l = l->next) {
1139 guint8 *ip = (guint8*)l->data;
1143 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &frame_domain);
1144 if (!ji || ji->is_trampoline)
1147 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1148 jmethod = jinfo_get_method (ji);
1149 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1156 /* No way to resolve generic instances */
1157 actual_method = jmethod;
1158 *native_offset = frame_ip - (guint8*)ji->code_start;
1160 mono_arch_flush_register_windows ();
1162 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1163 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
1165 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
1171 res = mono_find_jit_info_ext (domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1175 if (frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1176 frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1177 frame.type == FRAME_TYPE_TRAMPOLINE)
1181 *native_offset = frame.native_offset;
1183 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1184 jmethod = jinfo_get_method (ji);
1185 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1188 } while (skip >= 0);
1190 actual_method = get_method_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, &ctx));
1193 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, actual_method, NULL, &error);
1194 if (!mono_error_ok (&error)) {
1195 mono_error_set_pending_exception (&error);
1198 mono_gc_wbarrier_generic_store (method, (MonoObject*) rm);
1200 location = mono_debug_lookup_source_location (jmethod, *native_offset, domain);
1202 *iloffset = location->il_offset;
1206 if (need_file_info) {
1208 mono_gc_wbarrier_generic_store (file, (MonoObject*) mono_string_new (domain, location->source_file));
1209 *line = location->row;
1210 *column = location->column;
1213 *line = *column = 0;
1217 mono_debug_free_source_location (location);
1223 get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
1226 MonoClass *catch_class = ei->data.catch_class;
1227 MonoType *inflated_type;
1228 MonoGenericContext context;
1230 /*MonoJitExceptionInfo::data is an union used by filter and finally clauses too.*/
1231 if (!catch_class || ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
1234 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
1236 context = get_generic_context_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, ctx));
1238 /* FIXME: we shouldn't inflate but instead put the
1239 type in the rgctx and fetch it from there. It
1240 might be a good idea to do this lazily, i.e. only
1241 when the exception is actually thrown, so as not to
1242 waste space for exception clauses which might never
1244 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
1245 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
1247 catch_class = mono_class_from_mono_type (inflated_type);
1248 mono_metadata_free_type (inflated_type);
1254 * mini_jit_info_table_find_ext:
1256 * Same as mono_jit_info_table_find, but search all the domains of the current thread
1257 * if ADDR is not found in DOMAIN. The domain where the method was found is stored into
1258 * OUT_DOMAIN if it is not NULL.
1261 mini_jit_info_table_find_ext (MonoDomain *domain, char *addr, gboolean allow_trampolines, MonoDomain **out_domain)
1264 MonoInternalThread *t = mono_thread_internal_current ();
1270 ji = mono_jit_info_table_find_internal (domain, addr, TRUE, allow_trampolines);
1273 *out_domain = domain;
1277 /* maybe it is shared code, so we also search in the root domain */
1278 if (domain != mono_get_root_domain ()) {
1279 ji = mono_jit_info_table_find_internal (mono_get_root_domain (), addr, TRUE, allow_trampolines);
1282 *out_domain = mono_get_root_domain ();
1290 refs = (gpointer *)((t->appdomain_refs) ? *(gpointer *) t->appdomain_refs : NULL);
1291 for (; refs && *refs; refs++) {
1292 if (*refs != domain && *refs != mono_get_root_domain ()) {
1293 ji = mono_jit_info_table_find_internal ((MonoDomain*) *refs, addr, TRUE, allow_trampolines);
1296 *out_domain = (MonoDomain*) *refs;
1306 mini_jit_info_table_find (MonoDomain *domain, char *addr, MonoDomain **out_domain)
1308 return mini_jit_info_table_find_ext (domain, addr, FALSE, out_domain);
1311 /* Class lazy loading functions */
1312 static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute")
1315 * wrap_non_exception_throws:
1317 * Determine whenever M's assembly has a RuntimeCompatibilityAttribute with the
1318 * WrapNonExceptionThrows flag set.
1321 wrap_non_exception_throws (MonoMethod *m)
1324 MonoAssembly *ass = m->klass->image->assembly;
1325 MonoCustomAttrInfo* attrs;
1328 gboolean val = FALSE;
1331 if (ass->wrap_non_exception_throws_inited)
1332 return ass->wrap_non_exception_throws;
1334 klass = mono_class_get_runtime_compat_attr_class ();
1336 attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
1337 mono_error_cleanup (&error); /* FIXME don't swallow the error */
1339 for (i = 0; i < attrs->num_attrs; ++i) {
1340 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1342 int num_named, named_type, name_len;
1345 if (!attr->ctor || attr->ctor->klass != klass)
1347 /* Decode the RuntimeCompatibilityAttribute. See reflection.c */
1348 p = (const char*)attr->data;
1349 g_assert (read16 (p) == 0x0001);
1351 num_named = read16 (p);
1357 /* data_type = *p; */
1360 if (named_type != 0x54)
1362 name_len = mono_metadata_decode_blob_size (p, &p);
1363 name = (char *)g_malloc (name_len + 1);
1364 memcpy (name, p, name_len);
1365 name [name_len] = 0;
1367 g_assert (!strcmp (name, "WrapNonExceptionThrows"));
1369 /* The value is a BOOLEAN */
1372 mono_custom_attrs_free (attrs);
1375 ass->wrap_non_exception_throws = val;
1376 mono_memory_barrier ();
1377 ass->wrap_non_exception_throws_inited = TRUE;
1382 #define MAX_UNMANAGED_BACKTRACE 128
1384 build_native_trace (MonoError *error)
1387 /* This puppy only makes sense on mobile, IOW, ARM. */
1388 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
1390 void *native_trace [MAX_UNMANAGED_BACKTRACE];
1393 size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
1399 res = mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, size, error);
1400 return_val_if_nok (error, NULL);
1402 for (i = 0; i < size; i++)
1403 mono_array_set (res, gpointer, i, native_trace [i]);
1411 setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, GList **trace_ips)
1414 *trace_ips = g_list_reverse (*trace_ips);
1416 MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
1417 mono_error_assert_ok (&error);
1418 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
1419 MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace (&error));
1420 mono_error_assert_ok (&error);
1421 if (dynamic_methods) {
1422 /* These methods could go away anytime, so save a reference to them in the exception object */
1424 MonoMList *list = NULL;
1426 for (l = dynamic_methods; l; l = l->next) {
1428 MonoDomain *domain = mono_domain_get ();
1430 if (domain->method_to_dyn_method) {
1431 mono_domain_lock (domain);
1432 dis_link = (guint32)(size_t)g_hash_table_lookup (domain->method_to_dyn_method, l->data);
1433 mono_domain_unlock (domain);
1435 MonoObject *o = mono_gchandle_get_target (dis_link);
1437 list = mono_mlist_prepend_checked (list, o, &error);
1438 mono_error_assert_ok (&error);
1444 MONO_OBJECT_SETREF (mono_ex, dynamic_methods, list);
1447 g_list_free (*trace_ips);
1452 * mono_handle_exception_internal_first_pass:
1454 * The first pass of exception handling. Unwind the stack until a catch clause which can catch
1455 * OBJ is found. Run the index of the filter clause which caught the exception into
1456 * OUT_FILTER_IDX. Return TRUE if the exception is caught, FALSE otherwise.
1459 mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filter_idx, MonoJitInfo **out_ji, MonoJitInfo **out_prev_ji, MonoObject *non_exception)
1462 MonoDomain *domain = mono_domain_get ();
1463 MonoJitInfo *ji = NULL;
1464 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1465 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1466 MonoLMF *lmf = mono_get_lmf ();
1467 GList *trace_ips = NULL;
1468 GSList *dynamic_methods = NULL;
1469 MonoException *mono_ex;
1470 gboolean stack_overflow = FALSE;
1471 MonoContext initial_ctx;
1473 int frame_count = 0;
1478 g_assert (ctx != NULL);
1480 if (obj == (MonoObject *)domain->stack_overflow_ex)
1481 stack_overflow = TRUE;
1483 mono_ex = (MonoException*)obj;
1484 MonoArray *initial_trace_ips = mono_ex->trace_ips;
1485 if (initial_trace_ips) {
1486 int len = mono_array_length (initial_trace_ips) >> 1;
1488 for (i = 0; i < (len - 1); i++) {
1489 gpointer ip = mono_array_get (initial_trace_ips, gpointer, i * 2 + 0);
1490 gpointer generic_info = mono_array_get (initial_trace_ips, gpointer, i * 2 + 1);
1491 trace_ips = g_list_prepend (trace_ips, ip);
1492 trace_ips = g_list_prepend (trace_ips, generic_info);
1496 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1497 mono_error_assert_ok (&error);
1502 call_filter = (int (*) (MonoContext *, void *))mono_get_call_filter ();
1504 g_assert (jit_tls->end_of_stack);
1505 g_assert (jit_tls->abort_func);
1508 *out_filter_idx = -1;
1512 *out_prev_ji = NULL;
1517 MonoContext new_ctx;
1519 int clause_index_start = 0;
1520 gboolean unwind_res = TRUE;
1522 StackFrameInfo frame;
1527 unwind_res = mono_find_jit_info_ext (domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1529 if (frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1530 frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1531 frame.type == FRAME_TYPE_TRAMPOLINE) {
1535 g_assert (frame.type == FRAME_TYPE_MANAGED);
1540 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1541 g_slist_free (dynamic_methods);
1546 method = jinfo_get_method (ji);
1547 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1549 if (mini_get_debug_options ()->reverse_pinvoke_exceptions && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
1550 g_error ("A native frame was found while unwinding the stack after an exception.\n"
1551 "The native frame called the managed method:\n%s\n",
1552 mono_method_full_name (method, TRUE));
1555 if (method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
1556 // avoid giant stack traces during a stack overflow
1557 if (frame_count < 1000) {
1558 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1559 trace_ips = g_list_prepend (trace_ips, get_generic_info_from_stack_frame (ji, ctx));
1563 if (method->dynamic)
1564 dynamic_methods = g_slist_prepend (dynamic_methods, method);
1566 if (stack_overflow) {
1567 if (MONO_ARCH_STACK_GROWS_UP)
1568 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1570 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1572 free_stack = 0xffffff;
1575 for (i = clause_index_start; i < ji->num_clauses; i++) {
1576 MonoJitExceptionInfo *ei = &ji->clauses [i];
1577 gboolean filtered = FALSE;
1580 * During stack overflow, wait till the unwinding frees some stack
1581 * space before running handlers/finalizers.
1583 if (free_stack <= (64 * 1024))
1586 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
1588 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1591 * Have to unwrap RuntimeWrappedExceptions if the
1592 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1594 if (non_exception && !wrap_non_exception_throws (method))
1595 ex_obj = non_exception;
1599 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1600 #ifndef DISABLE_PERFCOUNTERS
1601 mono_perfcounters->exceptions_filters++;
1604 #ifndef MONO_CROSS_COMPILE
1605 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1607 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1609 /* Can't pass the ex object in a register yet to filter clauses, because call_filter () might not support it */
1610 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1612 g_assert (!ji->from_llvm);
1613 /* store the exception object in bp + ei->exvar_offset */
1614 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1618 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1620 * Pass the original il clause index to the landing pad so it can
1621 * branch to the landing pad associated with the il clause.
1622 * This is needed because llvm compiled code assumes that the EH
1623 * code always branches to the innermost landing pad.
1626 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1629 mono_debugger_agent_begin_exception_filter (mono_ex, ctx, &initial_ctx);
1630 filtered = call_filter (ctx, ei->data.filter);
1631 mono_debugger_agent_end_exception_filter (mono_ex, ctx, &initial_ctx);
1632 if (filtered && out_filter_idx)
1633 *out_filter_idx = filter_idx;
1639 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1640 g_slist_free (dynamic_methods);
1641 /* mono_debugger_agent_handle_exception () needs this */
1642 mini_set_abort_threshold (ctx);
1643 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1648 MonoError isinst_error;
1649 error_init (&isinst_error);
1650 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (ex_obj, catch_class, &error)) {
1651 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1652 g_slist_free (dynamic_methods);
1657 /* mono_debugger_agent_handle_exception () needs this */
1658 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1661 mono_error_cleanup (&isinst_error);
1668 g_assert_not_reached ();
1672 * mono_handle_exception_internal:
1673 * @ctx: saved processor state
1674 * @obj: the exception object
1675 * @resume: whenever to resume unwinding based on the state in MonoJitTlsData.
1678 mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resume, MonoJitInfo **out_ji)
1681 MonoDomain *domain = mono_domain_get ();
1682 MonoJitInfo *ji, *prev_ji;
1683 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1684 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1685 MonoLMF *lmf = mono_get_lmf ();
1686 MonoException *mono_ex;
1687 gboolean stack_overflow = FALSE;
1688 MonoContext initial_ctx;
1690 int frame_count = 0;
1691 gint32 filter_idx, first_filter_idx = 0;
1694 MonoObject *non_exception = NULL;
1696 g_assert (ctx != NULL);
1698 MonoException *ex = mono_get_exception_null_reference ();
1699 MONO_OBJECT_SETREF (ex, message, mono_string_new (domain, "Object reference not set to an instance of an object"));
1700 obj = (MonoObject *)ex;
1704 * Allocate a new exception object instead of the preconstructed ones.
1706 if (obj == (MonoObject *)domain->stack_overflow_ex) {
1708 * It is not a good idea to try and put even more pressure on the little stack available.
1709 * obj = mono_get_exception_stack_overflow ();
1711 stack_overflow = TRUE;
1713 else if (obj == (MonoObject *)domain->null_reference_ex) {
1714 obj = (MonoObject *)mono_get_exception_null_reference ();
1717 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1718 mono_error_assert_ok (&error);
1719 non_exception = obj;
1720 obj = (MonoObject *)mono_get_exception_runtime_wrapped_checked (obj, &error);
1721 mono_error_assert_ok (&error);
1724 mono_ex = (MonoException*)obj;
1726 if (mini_get_debug_options ()->suspend_on_exception) {
1727 mono_runtime_printf_err ("Exception thrown, suspending...");
1732 if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1733 mono_ex = (MonoException*)obj;
1735 mono_error_assert_ok (&error);
1739 if (mono_ex && jit_tls->class_cast_from) {
1740 if (!strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
1741 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1742 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1743 char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
1744 mono_ex->message = mono_string_new (domain, msg);
1749 if (!strcmp (mono_ex->object.vtable->klass->name, "ArrayTypeMismatchException")) {
1750 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1751 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1752 char *msg = g_strdup_printf ("Source array of type '%s' cannot be cast to destination array type '%s'.", from_name, to_name);
1753 mono_ex->message = mono_string_new (domain, msg);
1761 call_filter = (int (*)(MonoContext *, void*))mono_get_call_filter ();
1763 g_assert (jit_tls->end_of_stack);
1764 g_assert (jit_tls->abort_func);
1767 * We set orig_ex_ctx_set to TRUE/FALSE around profiler calls to make sure it doesn't
1768 * end up being TRUE on any code path.
1770 memcpy (&jit_tls->orig_ex_ctx, ctx, sizeof (MonoContext));
1775 MonoContext ctx_cp = *ctx;
1776 if (mono_trace_is_enabled ()) {
1777 MonoMethod *system_exception_get_message = mono_class_get_method_from_name (mono_defaults.exception_class, "get_Message", 0);
1778 MonoMethod *get_message = system_exception_get_message == NULL ? NULL : mono_object_get_virtual_method (obj, system_exception_get_message);
1779 MonoObject *message;
1780 const char *type_name = mono_class_get_name (mono_object_class (mono_ex));
1782 if (get_message == NULL) {
1784 } else if (!strcmp (type_name, "OutOfMemoryException") || !strcmp (type_name, "StackOverflowException")) {
1786 msg = g_strdup_printf ("(No exception message for: %s)\n", type_name);
1788 MonoObject *exc = NULL;
1789 message = mono_runtime_try_invoke (get_message, obj, NULL, &exc, &error);
1790 g_assert (exc == NULL);
1791 mono_error_assert_ok (&error);
1795 msg = mono_string_to_utf8_checked ((MonoString *) message, &error);
1796 if (!is_ok (&error)) {
1797 mono_error_cleanup (&error);
1798 msg = g_strdup ("(error while display System.Exception.Message property)");
1801 msg = g_strdup ("(System.Exception.Message property not available)");
1804 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);
1806 if (mono_ex && mono_trace_eval_exception (mono_object_class (mono_ex)))
1807 mono_print_thread_dump_from_ctx (ctx);
1809 jit_tls->orig_ex_ctx_set = TRUE;
1810 mono_profiler_exception_thrown (obj);
1811 jit_tls->orig_ex_ctx_set = FALSE;
1813 res = mono_handle_exception_internal_first_pass (&ctx_cp, obj, &first_filter_idx, &ji, &prev_ji, non_exception);
1816 if (mini_get_debug_options ()->break_on_exc)
1818 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1820 if (mini_get_debug_options ()->suspend_on_unhandled) {
1821 mono_runtime_printf_err ("Unhandled exception, suspending...");
1826 // FIXME: This runs managed code so it might cause another stack overflow when
1827 // we are handling a stack overflow
1828 mini_set_abort_threshold (ctx);
1829 mono_unhandled_exception (obj);
1831 gboolean unhandled = FALSE;
1834 * The exceptions caught by the mono_runtime_invoke_checked () calls
1835 * in the threadpool needs to be treated as unhandled (#669836).
1837 * FIXME: The check below is hackish, but its hard to distinguish
1838 * these runtime invoke calls from others in the runtime.
1840 if (ji && jinfo_get_method (ji)->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1841 if (prev_ji && jinfo_get_method (prev_ji) == mono_defaults.threadpool_perform_wait_callback_method)
1846 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1848 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, &ctx_cp);
1858 MonoContext new_ctx;
1860 int clause_index_start = 0;
1861 gboolean unwind_res = TRUE;
1865 ji = jit_tls->resume_state.ji;
1866 new_ctx = jit_tls->resume_state.new_ctx;
1867 clause_index_start = jit_tls->resume_state.clause_index;
1868 lmf = jit_tls->resume_state.lmf;
1869 first_filter_idx = jit_tls->resume_state.first_filter_idx;
1870 filter_idx = jit_tls->resume_state.filter_idx;
1872 StackFrameInfo frame;
1874 unwind_res = mono_find_jit_info_ext (domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1876 if (frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1877 frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1878 frame.type == FRAME_TYPE_TRAMPOLINE) {
1882 g_assert (frame.type == FRAME_TYPE_MANAGED);
1888 *(mono_get_lmf_addr ()) = lmf;
1890 jit_tls->abort_func (obj);
1891 g_assert_not_reached ();
1894 method = jinfo_get_method (ji);
1896 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1898 if (stack_overflow) {
1899 if (MONO_ARCH_STACK_GROWS_UP)
1900 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1902 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1904 free_stack = 0xffffff;
1907 for (i = clause_index_start; i < ji->num_clauses; i++) {
1908 MonoJitExceptionInfo *ei = &ji->clauses [i];
1909 gboolean filtered = FALSE;
1912 * During stack overflow, wait till the unwinding frees some stack
1913 * space before running handlers/finalizers.
1915 if (free_stack <= (64 * 1024))
1918 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
1920 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1923 * Have to unwrap RuntimeWrappedExceptions if the
1924 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1926 if (non_exception && !wrap_non_exception_throws (method))
1927 ex_obj = non_exception;
1931 if (((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER))) {
1932 #ifndef MONO_CROSS_COMPILE
1933 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1934 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1936 g_assert (!ji->from_llvm);
1937 /* store the exception object in bp + ei->exvar_offset */
1938 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1943 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1945 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1948 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1950 * Filter clauses should only be run in the
1951 * first pass of exception handling.
1953 filtered = (filter_idx == first_filter_idx);
1957 error_init (&error);
1958 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
1959 mono_object_isinst_checked (ex_obj, catch_class, &error)) || filtered) {
1961 * This guards against the situation that we abort a thread that is executing a finally clause
1962 * that was called by the EH machinery. It won't have a guard trampoline installed, so we must
1963 * check for this situation here and resume interruption if we are below the guarded block.
1965 if (G_UNLIKELY (jit_tls->handler_block_return_address)) {
1966 gboolean is_outside = FALSE;
1967 gpointer prot_bp = MONO_CONTEXT_GET_BP (&jit_tls->handler_block_context);
1968 gpointer catch_bp = MONO_CONTEXT_GET_BP (ctx);
1969 //FIXME make this stack direction aware
1970 if (catch_bp > prot_bp) {
1972 } else if (catch_bp == prot_bp) {
1973 /* Can be either try { try { } catch {} } finally {} or try { try { } finally {} } catch {}
1974 * So we check if the catch handler_start is protected by the guarded handler protected region
1977 * If there is an outstanding guarded_block return address, it means the current thread must be aborted.
1978 * This is the only way to reach out the guarded block as other cases are handled by the trampoline.
1979 * There aren't any further finally/fault handler blocks down the stack over this exception.
1980 * This must be ensured by the code that installs the guard trampoline.
1982 g_assert (ji == mini_jit_info_table_find (domain, (char *)MONO_CONTEXT_GET_IP (&jit_tls->handler_block_context), NULL));
1984 if (!is_address_protected (ji, jit_tls->handler_block, ei->handler_start)) {
1989 jit_tls->handler_block_return_address = NULL;
1990 jit_tls->handler_block = NULL;
1991 mono_thread_resume_interruption (TRUE); /*We ignore the exception here, it will be raised later*/
1995 if (mono_trace_is_enabled () && mono_trace_eval (method))
1996 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (method, TRUE));
1997 jit_tls->orig_ex_ctx_set = TRUE;
1998 mono_profiler_exception_clause_handler (method, ei->flags, i);
1999 jit_tls->orig_ex_ctx_set = FALSE;
2000 mini_set_abort_threshold (ctx);
2001 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2003 #ifndef DISABLE_PERFCOUNTERS
2004 mono_perfcounters->exceptions_depth += frame_count;
2006 if (obj == (MonoObject *)domain->stack_overflow_ex)
2007 jit_tls->handling_stack_ovf = FALSE;
2011 mono_error_cleanup (&error);
2012 if (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
2013 if (mono_trace_is_enabled () && mono_trace_eval (method))
2014 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2015 jit_tls->orig_ex_ctx_set = TRUE;
2016 mono_profiler_exception_clause_handler (method, ei->flags, i);
2017 jit_tls->orig_ex_ctx_set = FALSE;
2018 mini_set_abort_threshold (ctx);
2019 call_filter (ctx, ei->handler_start);
2021 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2022 if (mono_trace_is_enabled () && mono_trace_eval (method))
2023 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2024 jit_tls->orig_ex_ctx_set = TRUE;
2025 mono_profiler_exception_clause_handler (method, ei->flags, i);
2026 jit_tls->orig_ex_ctx_set = FALSE;
2027 #ifndef DISABLE_PERFCOUNTERS
2028 mono_perfcounters->exceptions_finallys++;
2031 if (ji->from_llvm) {
2033 * LLVM compiled finally handlers follow the design
2034 * of the c++ ehabi, i.e. they call a resume function
2035 * at the end instead of returning to the caller.
2036 * So save the exception handling state,
2037 * mono_resume_unwind () will call us again to continue
2040 jit_tls->resume_state.ex_obj = obj;
2041 jit_tls->resume_state.ji = ji;
2042 jit_tls->resume_state.clause_index = i + 1;
2043 jit_tls->resume_state.ctx = *ctx;
2044 jit_tls->resume_state.new_ctx = new_ctx;
2045 jit_tls->resume_state.lmf = lmf;
2046 jit_tls->resume_state.first_filter_idx = first_filter_idx;
2047 jit_tls->resume_state.filter_idx = filter_idx;
2048 mini_set_abort_threshold (ctx);
2049 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2052 mini_set_abort_threshold (ctx);
2053 call_filter (ctx, ei->handler_start);
2059 jit_tls->orig_ex_ctx_set = TRUE;
2060 mono_profiler_exception_method_leave (method);
2061 jit_tls->orig_ex_ctx_set = FALSE;
2066 g_assert_not_reached ();
2070 * mono_debugger_run_finally:
2071 * @start_ctx: saved processor state
2073 * This method is called by the Mono Debugger to call all `finally' clauses of the
2074 * current stack frame. It's used when the user issues a `return' command to make
2075 * the current stack frame return. After returning from this method, the debugger
2076 * unwinds the stack one frame and gives control back to the user.
2078 * NOTE: This method is only used when running inside the Mono Debugger.
2081 mono_debugger_run_finally (MonoContext *start_ctx)
2083 static int (*call_filter) (MonoContext *, gpointer) = NULL;
2084 MonoDomain *domain = mono_domain_get ();
2085 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2086 MonoLMF *lmf = mono_get_lmf ();
2087 MonoContext ctx, new_ctx;
2088 MonoJitInfo *ji, rji;
2093 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
2094 if (!ji || ji == (gpointer)-1)
2098 call_filter = (int (*)(MonoContext *, void *))mono_get_call_filter ();
2100 for (i = 0; i < ji->num_clauses; i++) {
2101 MonoJitExceptionInfo *ei = &ji->clauses [i];
2103 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (&ctx)) &&
2104 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
2105 call_filter (&ctx, ei->handler_start);
2111 * mono_handle_exception:
2112 * @ctx: saved processor state
2113 * @obj: the exception object
2116 mono_handle_exception (MonoContext *ctx, MonoObject *obj)
2118 MONO_REQ_GC_UNSAFE_MODE;
2120 #ifndef DISABLE_PERFCOUNTERS
2121 mono_perfcounters->exceptions_thrown++;
2124 return mono_handle_exception_internal (ctx, obj, FALSE, NULL);
2127 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2129 #ifndef MONO_ARCH_USE_SIGACTION
2130 #error "Can't use sigaltstack without sigaction"
2133 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
2136 mono_setup_altstack (MonoJitTlsData *tls)
2140 guint8 *staddr = NULL;
2142 if (mono_running_on_valgrind ())
2145 mono_thread_info_get_stack_bounds (&staddr, &stsize);
2149 tls->end_of_stack = staddr + stsize;
2150 tls->stack_size = stsize;
2152 /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
2154 tls->stack_ovf_guard_base = staddr + mono_pagesize ();
2155 tls->stack_ovf_guard_size = ALIGN_TO (8 * 4096, mono_pagesize ());
2157 g_assert ((guint8*)&sa >= (guint8*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size);
2159 if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
2160 /* mprotect can fail for the main thread stack */
2161 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);
2162 g_assert (gaddr == tls->stack_ovf_guard_base);
2163 tls->stack_ovf_valloced = TRUE;
2166 /* Setup an alternate signal stack */
2167 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);
2168 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2170 g_assert (tls->signal_stack);
2172 sa.ss_sp = tls->signal_stack;
2173 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2175 g_assert (sigaltstack (&sa, NULL) == 0);
2177 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);
2181 mono_free_altstack (MonoJitTlsData *tls)
2186 sa.ss_sp = tls->signal_stack;
2187 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2188 sa.ss_flags = SS_DISABLE;
2189 err = sigaltstack (&sa, NULL);
2190 g_assert (err == 0);
2192 if (tls->signal_stack)
2193 mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MEM_ACCOUNT_EXCEPTIONS);
2194 if (tls->stack_ovf_valloced)
2195 mono_vfree (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MEM_ACCOUNT_EXCEPTIONS);
2197 mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
2200 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2203 mono_setup_altstack (MonoJitTlsData *tls)
2208 mono_free_altstack (MonoJitTlsData *tls)
2212 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2215 try_restore_stack_protection (MonoJitTlsData *jit_tls, int extra_bytes)
2217 gint32 unprotect_size = jit_tls->stack_ovf_guard_size;
2218 /* we need to leave some room for throwing the exception */
2219 while (unprotect_size >= 0 && (char*)jit_tls->stack_ovf_guard_base + unprotect_size > ((char*)&unprotect_size - extra_bytes))
2220 unprotect_size -= mono_pagesize ();
2221 /* at this point we could try and build a new domain->stack_overflow_ex, but only if there
2222 * is sufficient stack
2224 //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);
2226 mono_mprotect (jit_tls->stack_ovf_guard_base, unprotect_size, MONO_MMAP_NONE);
2227 return unprotect_size == jit_tls->stack_ovf_guard_size;
2230 static G_GNUC_UNUSED void
2231 try_more_restore (void)
2233 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2234 if (try_restore_stack_protection (jit_tls, 500))
2235 jit_tls->restore_stack_prot = NULL;
2238 static G_GNUC_UNUSED void
2239 restore_stack_protection (void)
2241 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2242 MonoException *ex = mono_domain_get ()->stack_overflow_ex;
2243 /* if we can't restore the stack protection, keep a callback installed so
2244 * we'll try to restore as much stack as we can at each return from unmanaged
2247 if (try_restore_stack_protection (jit_tls, 4096))
2248 jit_tls->restore_stack_prot = NULL;
2250 jit_tls->restore_stack_prot = try_more_restore_tramp;
2251 /* here we also throw a stack overflow exception */
2252 ex->trace_ips = NULL;
2253 ex->stack_trace = NULL;
2254 mono_raise_exception (ex);
2258 mono_altstack_restore_prot (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
2260 MONO_REQ_GC_UNSAFE_MODE;
2262 void (*func)(void) = (void (*)(void))tramp_data;
2268 mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, guint8* fault_addr)
2273 /* we got a stack overflow in the soft-guard pages
2274 * There are two cases:
2275 * 1) managed code caused the overflow: we unprotect the soft-guard page
2276 * and let the arch-specific code trigger the exception handling mechanism
2277 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
2278 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
2279 * and hope we can continue with those enabled, at least until the hard-guard page
2280 * is hit. The alternative to continuing here is to just print a message and abort.
2281 * We may add in the future the code to protect the pages again in the codepath
2282 * when we return from unmanaged to managed code.
2284 if (jit_tls->stack_ovf_guard_size && fault_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
2285 fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
2286 /* we unprotect the minimum amount we can */
2288 gboolean handled = FALSE;
2290 guard_size = jit_tls->stack_ovf_guard_size - (mono_pagesize () * SIZEOF_VOID_P / 4);
2291 while (guard_size && fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + guard_size) {
2292 guard_size -= mono_pagesize ();
2294 guard_size = jit_tls->stack_ovf_guard_size - guard_size;
2295 /*fprintf (stderr, "unprotecting: %d\n", guard_size);*/
2296 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);
2297 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2299 mono_arch_handle_altstack_exception (ctx, siginfo, fault_addr, TRUE);
2304 /* We print a message: after this even managed stack overflows
2305 * may crash the runtime
2307 mono_runtime_printf_err ("Stack overflow in unmanaged: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2308 if (!jit_tls->handling_stack_ovf) {
2309 jit_tls->restore_stack_prot = restore_stack_protection_tramp;
2310 jit_tls->handling_stack_ovf = 1;
2312 /*fprintf (stderr, "Already handling stack overflow\n");*/
2321 MonoMethod *omethod;
2323 } PrintOverflowUserData;
2325 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2327 print_overflow_stack_frame (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2329 MonoMethod *method = NULL;
2330 PrintOverflowUserData *user_data = (PrintOverflowUserData *)data;
2333 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2334 method = jinfo_get_method (frame->ji);
2337 if (user_data->count == 0) {
2338 /* The first frame is in its prolog, so a line number cannot be computed */
2339 user_data->count ++;
2343 /* If this is a one method overflow, skip the other instances */
2344 if (method == user_data->omethod)
2347 location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2348 mono_runtime_printf_err (" %s", location);
2351 if (user_data->count == 1) {
2352 mono_runtime_printf_err (" <...>");
2353 user_data->omethod = method;
2355 user_data->omethod = NULL;
2358 user_data->count ++;
2360 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2367 mono_handle_hard_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
2369 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2370 PrintOverflowUserData ud;
2374 /* we don't do much now, but we can warn the user with a useful message */
2375 mono_runtime_printf_err ("Stack overflow: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2377 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2378 mono_sigctx_to_monoctx (ctx, &mctx);
2380 mono_runtime_printf_err ("Stacktrace:");
2382 memset (&ud, 0, sizeof (ud));
2384 mono_walk_stack_with_ctx (print_overflow_stack_frame, &mctx, MONO_UNWIND_LOOKUP_ACTUAL_METHOD, &ud);
2386 if (ji && !ji->is_trampoline && jinfo_get_method (ji))
2387 mono_runtime_printf_err ("At %s", mono_method_full_name (jinfo_get_method (ji), TRUE));
2389 mono_runtime_printf_err ("At <unmanaged>.");
2396 print_stack_frame_to_stderr (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2398 MonoMethod *method = NULL;
2400 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2401 method = jinfo_get_method (frame->ji);
2404 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2405 mono_runtime_printf_err (" %s", location);
2408 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2413 static G_GNUC_UNUSED gboolean
2414 print_stack_frame_to_string (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2416 GString *p = (GString*)data;
2417 MonoMethod *method = NULL;
2419 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2420 method = jinfo_get_method (frame->ji);
2422 if (method && frame->domain) {
2423 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
2424 g_string_append_printf (p, " %s\n", location);
2427 g_string_append_printf (p, " at <unknown> <0x%05x>\n", frame->native_offset);
2432 #ifndef MONO_CROSS_COMPILE
2434 static void print_process_map (void)
2437 FILE *fp = fopen ("/proc/self/maps", "r");
2441 mono_runtime_printf_err ("no /proc/self/maps, not on linux?\n");
2445 mono_runtime_printf_err ("/proc/self/maps:");
2447 while (fgets (line, sizeof (line), fp)) {
2449 size_t len = strlen (line) - 1;
2450 if (len >= 0 && line [len] == '\n')
2453 mono_runtime_printf_err ("%s", line);
2462 static gboolean handling_sigsegv = FALSE;
2465 * mono_handle_native_crash:
2467 * Handle a native crash (e.g. SIGSEGV) while in native code by
2468 * printing diagnostic information and aborting.
2471 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2473 #ifdef MONO_ARCH_USE_SIGACTION
2474 struct sigaction sa;
2476 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2478 gboolean is_sigsegv = !strcmp ("SIGSEGV", signal);
2480 if (handling_sigsegv && is_sigsegv)
2483 if (mini_get_debug_options ()->suspend_on_native_crash) {
2484 mono_runtime_printf_err ("Received %s, suspending...", signal);
2495 /* To prevent infinite loops when the stack walk causes a crash */
2497 handling_sigsegv = TRUE;
2499 /* !jit_tls means the thread was not registered with the runtime */
2500 if (jit_tls && mono_thread_internal_current ()) {
2501 mono_runtime_printf_err ("Stacktrace:\n");
2503 /* FIXME: Is MONO_UNWIND_LOOKUP_IL_OFFSET correct here? */
2504 mono_walk_stack (print_stack_frame_to_stderr, MONO_UNWIND_LOOKUP_IL_OFFSET, NULL);
2507 print_process_map ();
2509 #ifdef HAVE_BACKTRACE_SYMBOLS
2515 mono_runtime_printf_err ("\nNative stacktrace:\n");
2517 size = backtrace (array, 256);
2518 names = backtrace_symbols (array, size);
2519 for (i =0; i < size; ++i) {
2520 mono_runtime_printf_err ("\t%s", names [i]);
2524 /* Try to get more meaningful information using gdb */
2526 #if !defined(HOST_WIN32) && defined(HAVE_SYS_SYSCALL_H) && defined(SYS_fork)
2527 if (!mini_get_debug_options ()->no_gdb_backtrace) {
2528 /* From g_spawn_command_line_sync () in eglib */
2531 pid_t crashed_pid = getpid ();
2534 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
2535 * it will deadlock. Call the syscall directly instead.
2537 #if defined(PLATFORM_ANDROID)
2538 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
2539 g_assert_not_reached ();
2540 #elif !defined(PLATFORM_MACOSX) && defined(SYS_fork)
2541 pid = (pid_t) syscall (SYS_fork);
2542 #elif defined(PLATFORM_MACOSX) && HAVE_FORK
2543 pid = (pid_t) fork ();
2545 g_assert_not_reached ();
2548 #if defined (HAVE_PRCTL) && defined(PR_SET_PTRACER)
2550 // Allow gdb to attach to the process even if ptrace_scope sysctl variable is set to
2551 // a value other than 0 (the most permissive ptrace scope). Most modern Linux
2552 // distributions set the scope to 1 which allows attaching only to direct children of
2553 // the current process
2554 prctl (PR_SET_PTRACER, pid, 0, 0, 0);
2558 dup2 (STDERR_FILENO, STDOUT_FILENO);
2560 mono_gdb_render_native_backtraces (crashed_pid);
2564 mono_runtime_printf_err ("\nDebug info from gdb:\n");
2565 waitpid (pid, &status, 0);
2570 #ifdef PLATFORM_ANDROID
2571 /* set DUMPABLE for this process so debuggerd can attach with ptrace(2), see:
2572 * https://android.googlesource.com/platform/bionic/+/151da681000c07da3c24cd30a3279b1ca017f452/linker/debugger.cpp#206
2573 * this has changed on later versions of Android. Also, we don't want to
2574 * set this on start-up as DUMPABLE has security implications. */
2575 prctl (PR_SET_DUMPABLE, 1);
2577 mono_runtime_printf_err ("\nNo native Android stacktrace (see debuggerd output).\n");
2582 * A SIGSEGV indicates something went very wrong so we can no longer depend
2583 * on anything working. So try to print out lots of diagnostics, starting
2584 * with ones which have a greater chance of working.
2586 mono_runtime_printf_err (
2588 "=================================================================\n"
2589 "Got a %s while executing native code. This usually indicates\n"
2590 "a fatal error in the mono runtime or one of the native libraries \n"
2591 "used by your application.\n"
2592 "=================================================================\n",
2595 #ifdef MONO_ARCH_USE_SIGACTION
2596 sa.sa_handler = SIG_DFL;
2597 sigemptyset (&sa.sa_mask);
2600 /* Remove our SIGABRT handler */
2601 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
2603 /* On some systems we get a SIGILL when calling abort (), because it might
2604 * fail to raise SIGABRT */
2605 g_assert (sigaction (SIGILL, &sa, NULL) != -1);
2608 if (!mono_do_crash_chaining) {
2609 /*Android abort is a fluke, it doesn't abort, it triggers another segv. */
2610 #if defined (PLATFORM_ANDROID)
2621 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2623 g_assert_not_reached ();
2626 #endif /* !MONO_CROSS_COMPILE */
2629 mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
2631 MonoInternalThread *thread = mono_thread_internal_current ();
2632 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2637 GError *error = NULL;
2642 text = g_string_new (0);
2644 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
2646 g_string_append_printf (text, "\n\"%s\"", name);
2649 else if (thread->threadpool_thread)
2650 g_string_append (text, "\n\"<threadpool thread>\"");
2652 g_string_append (text, "\n\"<unnamed thread>\"");
2654 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
2655 mono_thread_internal_describe (thread, text);
2656 g_string_append (text, "\n");
2658 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2660 memcpy (&ctx, start_ctx, sizeof (MonoContext));
2662 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_print_thread_dump);
2664 mono_sigctx_to_monoctx (sigctx, &ctx);
2666 mono_walk_stack_with_ctx (print_stack_frame_to_string, &ctx, MONO_UNWIND_LOOKUP_ALL, text);
2668 mono_runtime_printf ("\t<Stack traces in thread dumps not supported on this platform>");
2671 mono_runtime_printf ("%s", text->str);
2673 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
2674 OutputDebugStringA(text->str);
2677 g_string_free (text, TRUE);
2678 mono_runtime_stdout_fflush ();
2682 * mono_print_thread_dump:
2684 * Print information about the current thread to stdout.
2685 * SIGCTX can be NULL, allowing this to be called from gdb.
2688 mono_print_thread_dump (void *sigctx)
2690 mono_print_thread_dump_internal (sigctx, NULL);
2694 mono_print_thread_dump_from_ctx (MonoContext *ctx)
2696 mono_print_thread_dump_internal (NULL, ctx);
2700 * mono_resume_unwind:
2702 * This is called by a trampoline from LLVM compiled finally clauses to continue
2706 mono_resume_unwind (MonoContext *ctx)
2708 MONO_REQ_GC_UNSAFE_MODE;
2710 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2711 MonoContext new_ctx;
2713 MONO_CONTEXT_SET_IP (ctx, MONO_CONTEXT_GET_IP (&jit_tls->resume_state.ctx));
2714 MONO_CONTEXT_SET_SP (ctx, MONO_CONTEXT_GET_SP (&jit_tls->resume_state.ctx));
2717 mono_handle_exception_internal (&new_ctx, (MonoObject *)jit_tls->resume_state.ex_obj, TRUE, NULL);
2719 mono_restore_context (&new_ctx);
2722 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
2727 MonoJitExceptionInfo *ei;
2728 } FindHandlerBlockData;
2731 find_last_handler_block (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2735 FindHandlerBlockData *pdata = (FindHandlerBlockData *)data;
2736 MonoJitInfo *ji = frame->ji;
2741 ip = MONO_CONTEXT_GET_IP (ctx);
2743 for (i = 0; i < ji->num_clauses; ++i) {
2744 MonoJitExceptionInfo *ei = ji->clauses + i;
2745 if (ei->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2747 /*If ip points to the first instruction it means the handler block didn't start
2748 so we can leave its execution to the EH machinery*/
2749 if (ei->handler_start < ip && ip < ei->data.handler_end) {
2761 install_handler_block_guard (MonoJitInfo *ji, MonoContext *ctx)
2764 MonoJitExceptionInfo *clause = NULL;
2767 ip = MONO_CONTEXT_GET_IP (ctx);
2769 for (i = 0; i < ji->num_clauses; ++i) {
2770 clause = &ji->clauses [i];
2771 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2773 if (clause->handler_start < ip && clause->data.handler_end > ip)
2777 /*no matching finally */
2778 if (i == ji->num_clauses)
2781 /*If we stopped on the instruction right before the try, we haven't actually started executing it*/
2782 if (ip == clause->handler_start)
2785 return mono_arch_install_handler_block_guard (ji, clause, ctx, mono_create_handler_block_trampoline ());
2789 * Finds the bottom handler block running and install a block guard if needed.
2792 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2794 FindHandlerBlockData data = { 0 };
2795 MonoJitTlsData *jit_tls = (MonoJitTlsData *)ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS];
2798 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
2803 /* Guard against a null MonoJitTlsData. This can happens if the thread receives the
2804 * interrupt signal before the JIT has time to initialize its TLS data for the given thread.
2806 if (!jit_tls || jit_tls->handler_block_return_address)
2809 /* Do an async safe stack walk */
2810 mono_thread_info_set_is_async_context (TRUE);
2811 mono_walk_stack_with_state (find_last_handler_block, ctx, MONO_UNWIND_NONE, &data);
2812 mono_thread_info_set_is_async_context (FALSE);
2817 memcpy (&jit_tls->handler_block_context, &data.ctx, sizeof (MonoContext));
2819 resume_ip = install_handler_block_guard (data.ji, &data.ctx);
2820 if (resume_ip == NULL)
2823 jit_tls->handler_block_return_address = resume_ip;
2824 jit_tls->handler_block = data.ei;
2830 mono_current_thread_has_handle_block_guard (void)
2832 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2833 return jit_tls && jit_tls->handler_block_return_address != NULL;
2838 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2844 mono_current_thread_has_handle_block_guard (void)
2852 mono_set_cast_details (MonoClass *from, MonoClass *to)
2854 MonoJitTlsData *jit_tls = NULL;
2856 if (mini_get_debug_options ()->better_cast_details) {
2857 jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2858 jit_tls->class_cast_from = from;
2859 jit_tls->class_cast_to = to;
2864 /*returns false if the thread is not attached*/
2866 mono_thread_state_init_from_sigctx (MonoThreadUnwindState *ctx, void *sigctx)
2868 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2869 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2876 mono_sigctx_to_monoctx (sigctx, &ctx->ctx);
2878 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2879 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2880 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2883 mono_thread_state_init (ctx);
2886 if (!ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] || !ctx->unwind_data [MONO_UNWIND_DATA_LMF])
2892 g_error ("Implement mono_arch_sigctx_to_monoctx for the current target");
2898 mono_thread_state_init (MonoThreadUnwindState *ctx)
2900 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2902 #if defined(MONO_CROSS_COMPILE)
2903 ctx->valid = FALSE; //A cross compiler doesn't need to suspend.
2904 #elif MONO_ARCH_HAS_MONO_CONTEXT
2905 MONO_CONTEXT_GET_CURRENT (ctx->ctx);
2907 g_error ("Use a null sigctx requires a working mono-context");
2910 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2911 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2912 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread ? thread->jit_data : NULL;
2918 mono_thread_state_init_from_monoctx (MonoThreadUnwindState *ctx, MonoContext *mctx)
2920 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2927 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2928 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2929 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2934 /*returns false if the thread is not attached*/
2936 mono_thread_state_init_from_current (MonoThreadUnwindState *ctx)
2938 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2939 MONO_ARCH_CONTEXT_DEF
2941 mono_arch_flush_register_windows ();
2943 if (!thread || !thread->jit_data) {
2947 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
2948 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx->ctx);
2950 MONO_INIT_CONTEXT_FROM_FUNC (&ctx->ctx, mono_thread_state_init_from_current);
2953 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2954 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2955 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2961 mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx)
2963 mono_handle_exception (ctx, (MonoObject *)exc);
2964 mono_restore_context (ctx);
2967 /*FIXME Move all monoctx -> sigctx conversion to signal handlers once all archs support utils/mono-context */
2969 mono_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
2971 #ifdef MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK
2972 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2973 jit_tls->ex_ctx = *ctx;
2975 mono_arch_setup_async_callback (ctx, async_cb, user_data);
2977 g_error ("This target doesn't support mono_arch_setup_async_callback");
2982 * mono_restore_context:
2984 * Call the architecture specific restore context function.
2987 mono_restore_context (MonoContext *ctx)
2989 static void (*restore_context) (MonoContext *);
2991 if (!restore_context)
2992 restore_context = (void (*)(MonoContext *))mono_get_restore_context ();
2993 restore_context (ctx);
2994 g_assert_not_reached ();
2998 * mono_jinfo_get_unwind_info:
3000 * Return the unwind info for JI.
3003 mono_jinfo_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3006 return mono_aot_get_unwind_info (ji, unwind_info_len);
3008 return mono_get_cached_unwind_info (ji->unwind_info, unwind_info_len);
3012 mono_jinfo_get_epilog_size (MonoJitInfo *ji)
3014 MonoArchEHJitInfo *info;
3016 info = mono_jit_info_get_arch_eh_info (ji);
3019 return info->epilog_size;
3023 * LLVM/Bitcode exception handling.
3027 throw_exception (MonoObject *ex, gboolean rethrow)
3029 MONO_REQ_GC_UNSAFE_MODE;
3032 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3033 MonoException *mono_ex;
3035 if (!mono_object_isinst_checked (ex, mono_defaults.exception_class, &error)) {
3036 mono_error_assert_ok (&error);
3037 mono_ex = mono_get_exception_runtime_wrapped_checked (ex, &error);
3038 mono_error_assert_ok (&error);
3039 jit_tls->thrown_non_exc = mono_gchandle_new (ex, FALSE);
3042 mono_ex = (MonoException*)ex;
3045 jit_tls->thrown_exc = mono_gchandle_new ((MonoObject*)mono_ex, FALSE);
3048 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
3049 GList *l, *ips = NULL;
3052 _Unwind_Backtrace (build_stack_trace, &ips);
3053 /* The list contains ip-gshared info pairs */
3055 ips = g_list_reverse (ips);
3056 for (l = ips; l; l = l->next) {
3057 trace = g_list_append (trace, l->data);
3058 trace = g_list_append (trace, NULL);
3060 MonoArray *ips_arr = mono_glist_to_array (trace, mono_defaults.int_class, &error);
3061 mono_error_assert_ok (&error);
3062 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3064 g_list_free (trace);
3068 mono_llvm_cpp_throw_exception ();
3072 mono_llvm_throw_exception (MonoObject *ex)
3074 throw_exception (ex, FALSE);
3078 mono_llvm_rethrow_exception (MonoObject *ex)
3080 throw_exception (ex, TRUE);
3084 mono_llvm_raise_exception (MonoException *e)
3086 mono_llvm_throw_exception ((MonoObject*)e);
3090 mono_llvm_throw_corlib_exception (guint32 ex_token_index)
3092 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
3095 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
3097 mono_llvm_throw_exception ((MonoObject*)ex);
3101 * mono_llvm_resume_exception:
3103 * Resume exception propagation.
3106 mono_llvm_resume_exception (void)
3108 mono_llvm_cpp_throw_exception ();
3112 * mono_llvm_load_exception:
3114 * Return the currently thrown exception.
3117 mono_llvm_load_exception (void)
3120 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3122 MonoException *mono_ex = (MonoException*)mono_gchandle_get_target (jit_tls->thrown_exc);
3124 if (mono_ex->trace_ips) {
3125 GList *trace_ips = NULL;
3126 gpointer ip = __builtin_return_address (0);
3128 size_t upper = mono_array_length (mono_ex->trace_ips);
3130 for (int i = 0; i < upper; i+= 2) {
3131 gpointer curr_ip = mono_array_get (mono_ex->trace_ips, gpointer, i);
3132 gpointer curr_info = mono_array_get (mono_ex->trace_ips, gpointer, i + 1);
3133 trace_ips = g_list_append (trace_ips, curr_ip);
3134 trace_ips = g_list_append (trace_ips, curr_info);
3140 // FIXME: Does this work correctly for rethrows?
3141 // We may be discarding useful information
3142 // when this gets GC'ed
3143 MonoArray *ips_arr = mono_glist_to_array (trace_ips, mono_defaults.int_class, &error);
3144 mono_error_assert_ok (&error);
3145 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3146 g_list_free (trace_ips);
3149 //MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
3151 MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, 0, &error));
3152 mono_error_assert_ok (&error);
3153 MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new_checked (mono_domain_get (), mono_defaults.stack_frame_class, 0, &error));
3154 mono_error_assert_ok (&error);
3157 return &mono_ex->object;
3161 * mono_llvm_clear_exception:
3163 * Mark the currently thrown exception as handled.
3166 mono_llvm_clear_exception (void)
3168 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3169 mono_gchandle_free (jit_tls->thrown_exc);
3170 jit_tls->thrown_exc = 0;
3171 if (jit_tls->thrown_non_exc)
3172 mono_gchandle_free (jit_tls->thrown_non_exc);
3173 jit_tls->thrown_non_exc = 0;
3175 mono_memory_barrier ();
3179 * mono_llvm_match_exception:
3181 * Return the innermost clause containing REGION_START-REGION_END which can handle
3182 * the current exception.
3185 mono_llvm_match_exception (MonoJitInfo *jinfo, guint32 region_start, guint32 region_end, gpointer rgctx, MonoObject *this_obj)
3188 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3192 g_assert (jit_tls->thrown_exc);
3193 exc = mono_gchandle_get_target (jit_tls->thrown_exc);
3194 if (jit_tls->thrown_non_exc) {
3196 * Have to unwrap RuntimeWrappedExceptions if the
3197 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
3199 if (!wrap_non_exception_throws (jinfo_get_method (jinfo)))
3200 exc = mono_gchandle_get_target (jit_tls->thrown_non_exc);
3203 for (int i = 0; i < jinfo->num_clauses; i++) {
3204 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3205 MonoClass *catch_class;
3207 if (! (ei->try_offset == region_start && ei->try_offset + ei->try_len == region_end) )
3210 catch_class = ei->data.catch_class;
3211 if (mono_class_is_open_constructed_type (&catch_class->byval_arg)) {
3212 MonoGenericContext context;
3213 MonoType *inflated_type;
3215 g_assert (rgctx || this_obj);
3216 context = get_generic_context_from_stack_frame (jinfo, rgctx ? rgctx : this_obj->vtable);
3217 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
3218 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3220 catch_class = mono_class_from_mono_type (inflated_type);
3221 mono_metadata_free_type (inflated_type);
3224 // FIXME: Handle edge cases handled in get_exception_catch_class
3225 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (exc, catch_class, &error)) {
3226 index = ei->clause_index;
3229 mono_error_assert_ok (&error);
3231 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3232 g_assert_not_reached ();
3241 mono_debug_personality (int a, _Unwind_Action b,
3242 uint64_t c, struct _Unwind_Exception *d, struct _Unwind_Context *e)
3244 g_assert_not_reached ();
3248 mono_debug_personality (void);
3251 mono_debug_personality (void)
3253 g_assert_not_reached ();