2 * mini-exceptions.c: generic exception support
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Mono Team (mono-list@lists.ximian.com)
8 * Copyright 2001-2003 Ximian, Inc.
9 * Copyright 2003-2008 Novell, Inc.
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
22 #ifdef HAVE_EXECINFO_H
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
30 #ifdef HAVE_SYS_WAIT_H
38 #ifdef HAVE_SYS_SYSCALL_H
39 #include <sys/syscall.h>
42 #ifdef HAVE_SYS_PRCTL_H
43 #include <sys/prctl.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/tabledefs.h>
52 #include <mono/metadata/threads.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/metadata/debug-helpers.h>
55 #include <mono/metadata/exception.h>
56 #include <mono/metadata/exception-internals.h>
57 #include <mono/metadata/object-internals.h>
58 #include <mono/metadata/reflection-internals.h>
59 #include <mono/metadata/gc-internals.h>
60 #include <mono/metadata/mono-debug.h>
61 #include <mono/metadata/profiler.h>
62 #include <mono/metadata/mono-endian.h>
63 #include <mono/metadata/environment.h>
64 #include <mono/metadata/mono-mlist.h>
65 #include <mono/utils/mono-mmap.h>
66 #include <mono/utils/mono-logger-internals.h>
67 #include <mono/utils/mono-error.h>
68 #include <mono/utils/mono-error-internals.h>
72 #include "debugger-agent.h"
73 #include "seq-points.h"
74 #include "llvm-runtime.h"
75 #include "mini-llvm.h"
78 #include "mini-llvm-cpp.h"
81 #ifndef MONO_ARCH_CONTEXT_DEF
82 #define MONO_ARCH_CONTEXT_DEF
85 #ifndef MONO_ARCH_STACK_GROWS_UP
86 #define MONO_ARCH_STACK_GROWS_UP 0
89 static gpointer restore_context_func, call_filter_func;
90 static gpointer throw_exception_func, rethrow_exception_func;
91 static gpointer throw_corlib_exception_func;
93 static gpointer try_more_restore_tramp = NULL;
94 static gpointer restore_stack_protection_tramp = NULL;
96 static void try_more_restore (void);
97 static void restore_stack_protection (void);
98 static void mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data);
99 static void mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx);
100 static void mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data);
101 static gboolean mono_current_thread_has_handle_block_guard (void);
104 first_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer addr)
106 gpointer **data = (gpointer **)addr;
112 // FIXME: Happens with llvm_only
117 *data = MONO_CONTEXT_GET_SP (ctx);
123 mono_thread_get_managed_sp (void)
125 gpointer addr = NULL;
126 mono_walk_stack (first_managed, MONO_UNWIND_SIGNAL_SAFE, &addr);
131 mini_abort_threshold_offset (gpointer threshold, gpointer sp)
133 intptr_t stack_threshold = (intptr_t) threshold;
134 intptr_t stack_pointer = (intptr_t) sp;
136 const int direction = MONO_ARCH_STACK_GROWS_UP ? -1 : 1;
137 intptr_t magnitude = stack_pointer - stack_threshold;
139 return direction * magnitude;
143 mini_clear_abort_threshold (void)
145 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
146 jit_tls->abort_exc_stack_threshold = NULL;
150 mini_set_abort_threshold (MonoContext *ctx)
152 gpointer sp = MONO_CONTEXT_GET_SP (ctx);
153 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
154 // Only move it up, to avoid thrown/caught
155 // exceptions lower in the stack from triggering
157 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
158 if (!jit_tls->abort_exc_stack_threshold || above_threshold) {
159 jit_tls->abort_exc_stack_threshold = sp;
163 // Note: In the case that the frame is above where the thread abort
164 // was set we bump the threshold so that functions called from the new,
165 // higher threshold don't trigger the thread abort exception
166 static inline gboolean
167 mini_above_abort_threshold (void)
169 gpointer sp = mono_thread_get_managed_sp ();
170 MonoJitTlsData *jit_tls = (MonoJitTlsData*) mono_tls_get_jit_tls ();
175 gboolean above_threshold = mini_abort_threshold_offset (jit_tls->abort_exc_stack_threshold, sp) >= 0;
178 jit_tls->abort_exc_stack_threshold = sp;
180 return above_threshold;
184 mono_get_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
187 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
193 mono_exceptions_init (void)
195 MonoRuntimeExceptionHandlingCallbacks cbs;
197 restore_context_func = mono_aot_get_trampoline ("restore_context");
198 call_filter_func = mono_aot_get_trampoline ("call_filter");
199 throw_exception_func = mono_aot_get_trampoline ("throw_exception");
200 rethrow_exception_func = mono_aot_get_trampoline ("rethrow_exception");
204 restore_context_func = mono_arch_get_restore_context (&info, FALSE);
205 mono_tramp_info_register (info, NULL);
206 call_filter_func = mono_arch_get_call_filter (&info, FALSE);
207 mono_tramp_info_register (info, NULL);
208 throw_exception_func = mono_arch_get_throw_exception (&info, FALSE);
209 mono_tramp_info_register (info, NULL);
210 rethrow_exception_func = mono_arch_get_rethrow_exception (&info, FALSE);
211 mono_tramp_info_register (info, NULL);
213 #ifdef MONO_ARCH_HAVE_RESTORE_STACK_SUPPORT
214 if (!mono_llvm_only) {
215 try_more_restore_tramp = mono_create_specific_trampoline (try_more_restore, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
216 restore_stack_protection_tramp = mono_create_specific_trampoline (restore_stack_protection, MONO_TRAMPOLINE_RESTORE_STACK_PROT, mono_domain_get (), NULL);
220 #ifdef MONO_ARCH_HAVE_EXCEPTIONS_INIT
221 mono_arch_exceptions_init ();
223 cbs.mono_walk_stack_with_ctx = mono_runtime_walk_stack_with_ctx;
224 cbs.mono_walk_stack_with_state = mono_walk_stack_with_state;
227 cbs.mono_raise_exception = mono_llvm_raise_exception;
229 cbs.mono_raise_exception = (void (*)(MonoException *))mono_get_throw_exception ();
230 cbs.mono_raise_exception_with_ctx = mono_raise_exception_with_ctx;
231 cbs.mono_exception_walk_trace = mono_exception_walk_trace;
232 cbs.mono_install_handler_block_guard = mono_install_handler_block_guard;
233 cbs.mono_current_thread_has_handle_block_guard = mono_current_thread_has_handle_block_guard;
234 cbs.mono_clear_abort_threshold = mini_clear_abort_threshold;
235 cbs.mono_above_abort_threshold = mini_above_abort_threshold;
236 mono_install_eh_callbacks (&cbs);
237 mono_install_get_seq_point (mono_get_seq_point_for_native_offset);
241 mono_get_throw_exception (void)
243 g_assert (throw_exception_func);
244 return throw_exception_func;
248 mono_get_rethrow_exception (void)
250 g_assert (rethrow_exception_func);
251 return rethrow_exception_func;
255 mono_get_call_filter (void)
257 g_assert (call_filter_func);
258 return call_filter_func;
262 mono_get_restore_context (void)
264 g_assert (restore_context_func);
265 return restore_context_func;
269 mono_get_throw_corlib_exception (void)
271 gpointer code = NULL;
274 /* This depends on corlib classes so cannot be inited in mono_exceptions_init () */
275 if (throw_corlib_exception_func)
276 return throw_corlib_exception_func;
279 code = mono_aot_get_trampoline ("throw_corlib_exception");
281 code = mono_arch_get_throw_corlib_exception (&info, FALSE);
282 mono_tramp_info_register (info, NULL);
285 mono_memory_barrier ();
287 throw_corlib_exception_func = code;
289 return throw_corlib_exception_func;
293 * mono_get_throw_exception_addr:
295 * Return an address which stores the result of
296 * mono_get_throw_exception.
299 mono_get_throw_exception_addr (void)
301 return &throw_exception_func;
305 is_address_protected (MonoJitInfo *ji, MonoJitExceptionInfo *ei, gpointer ip)
307 MonoTryBlockHoleTableJitInfo *table;
312 if (ei->try_start > ip || ip >= ei->try_end)
315 if (!ji->has_try_block_holes)
318 table = mono_jit_info_get_try_block_hole_table_info (ji);
319 offset = (guint32)((char*)ip - (char*)ji->code_start);
320 clause = (guint16)(ei - ji->clauses);
321 g_assert (clause < ji->num_clauses);
323 for (i = 0; i < table->num_holes; ++i) {
324 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
325 if (hole->clause == clause && hole->offset <= offset && hole->offset + hole->length > offset)
331 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
334 static gboolean show_native_addresses = TRUE;
336 static gboolean show_native_addresses = FALSE;
339 static _Unwind_Reason_Code
340 build_stack_trace (struct _Unwind_Context *frame_ctx, void *state)
342 MonoDomain *domain = mono_domain_get ();
343 uintptr_t ip = _Unwind_GetIP (frame_ctx);
345 if (show_native_addresses || mono_jit_info_table_find (domain, (char*)ip)) {
346 GList **trace_ips = (GList **)state;
347 *trace_ips = g_list_prepend (*trace_ips, (gpointer)ip);
350 return _URC_NO_REASON;
354 get_unwind_backtrace (void)
358 _Unwind_Backtrace (build_stack_trace, &ips);
360 return g_slist_reverse (ips);
366 get_unwind_backtrace (void)
376 * Translate between the mono_arch_unwind_frame function and the old API.
379 find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
380 MonoContext *new_ctx, MonoLMF **lmf, gboolean *managed)
382 StackFrameInfo frame;
385 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
387 /* Avoid costly table lookup during stack overflow */
388 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
391 ji = mini_jit_info_table_find (domain, (char *)ip, NULL);
396 err = mono_arch_unwind_frame (domain, jit_tls, ji, ctx, new_ctx, lmf, NULL, &frame);
398 return (MonoJitInfo *)-1;
400 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
402 * Remove any unused lmf.
403 * Mask out the lower bits which might be used to hold additional information.
405 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
408 /* Convert between the new and the old APIs */
409 switch (frame.type) {
410 case FRAME_TYPE_MANAGED:
414 case FRAME_TYPE_TRAMPOLINE:
416 case FRAME_TYPE_MANAGED_TO_NATIVE:
420 memset (res, 0, sizeof (MonoJitInfo));
421 res->d.method = frame.method;
424 case FRAME_TYPE_DEBUGGER_INVOKE: {
428 * The normal exception handling code can't handle this frame, so just
431 ji = find_jit_info (domain, jit_tls, res, NULL, new_ctx, &tmp_ctx, lmf, managed);
432 memcpy (new_ctx, &tmp_ctx, sizeof (MonoContext));
436 g_assert_not_reached ();
441 /* mono_find_jit_info:
443 * This function is used to gather information from @ctx. It return the
444 * MonoJitInfo of the corresponding function, unwinds one stack frame and
445 * stores the resulting context into @new_ctx. It also stores a string
446 * describing the stack location into @trace (if not NULL), and modifies
447 * the @lmf if necessary. @native_offset return the IP offset from the
448 * start of the function or -1 if that info is not available.
451 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
452 MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
456 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
458 MonoMethod *method = NULL;
469 ji = find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, lmf, &managed2);
471 if (ji == (gpointer)-1)
474 if (ji && !ji->is_trampoline)
475 method = jinfo_get_method (ji);
477 if (managed2 || (method && method->wrapper_type)) {
478 const char *real_ip, *start;
481 start = (const char *)ji->code_start;
483 /* ctx->ip points into native code */
484 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
486 real_ip = (const char*)ip;
488 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
489 offset = real_ip - start;
494 *native_offset = offset;
497 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
501 *trace = mono_debug_print_stack_frame (method, offset, domain);
504 char *fname = mono_method_full_name (jinfo_get_method (res), TRUE);
505 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
514 * mono_find_jit_info_ext:
516 * A version of mono_find_jit_info which returns all data in the StackFrameInfo
518 * A note about frames of type FRAME_TYPE_MANAGED_TO_NATIVE:
519 * - These frames are used to mark managed-to-native transitions, so CTX will refer to native
520 * code, and new_ctx will refer to the last managed frame. The caller should unwind once more
521 * to obtain the last managed frame.
522 * If SAVE_LOCATIONS is not NULL, it should point to an array of size MONO_MAX_IREGS.
523 * On return, it will be filled with the locations where callee saved registers are saved
524 * by the current frame. This is returned outside of StackFrameInfo because it can be
525 * quite large on some platforms.
526 * If ASYNC true, this function will be async safe, but some fields of frame and frame->ji will
530 mono_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls,
531 MonoJitInfo *prev_ji, MonoContext *ctx,
532 MonoContext *new_ctx, char **trace, MonoLMF **lmf,
533 mgreg_t **save_locations,
534 StackFrameInfo *frame)
537 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
539 MonoDomain *target_domain = domain;
540 MonoMethod *method = NULL;
541 gboolean async = mono_thread_info_is_async_context ();
546 /* Avoid costly table lookup during stack overflow */
547 if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
550 ji = mini_jit_info_table_find (domain, (char *)ip, &target_domain);
553 target_domain = domain;
556 memset (save_locations, 0, MONO_MAX_IREGS * sizeof (mgreg_t*));
558 err = mono_arch_unwind_frame (target_domain, jit_tls, ji, ctx, new_ctx, lmf, save_locations, frame);
562 if (*lmf && ((*lmf) != jit_tls->first_lmf) && ((gpointer)MONO_CONTEXT_GET_SP (new_ctx) >= (gpointer)(*lmf))) {
564 * Remove any unused lmf.
565 * Mask out the lower bits which might be used to hold additional information.
567 *lmf = (MonoLMF *)(((gsize)(*lmf)->previous_lmf) & ~(SIZEOF_VOID_P -1));
570 if (frame->ji && !frame->ji->is_trampoline && !frame->ji->async)
571 method = jinfo_get_method (frame->ji);
573 if (frame->type == FRAME_TYPE_MANAGED && method) {
574 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
575 frame->managed = TRUE;
578 if (frame->type == FRAME_TYPE_MANAGED_TO_NATIVE) {
580 * This type of frame is just a marker, the caller should unwind once more to get the
581 * last managed frame.
584 frame->method = NULL;
587 frame->native_offset = -1;
588 frame->domain = target_domain;
589 frame->async_context = async;
593 if (frame->type == FRAME_TYPE_MANAGED)
594 frame->method = method;
596 if (ji && (frame->managed || (method && method->wrapper_type))) {
597 const char *real_ip, *start;
599 start = (const char *)ji->code_start;
600 if (frame->type == FRAME_TYPE_MANAGED)
601 real_ip = (const char*)ip;
603 /* ctx->ip points into native code */
604 real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx);
606 if ((real_ip >= start) && (real_ip <= start + ji->code_size))
607 frame->native_offset = real_ip - start;
609 frame->native_offset = -1;
613 *trace = mono_debug_print_stack_frame (method, frame->native_offset, domain);
615 if (trace && frame->method) {
616 char *fname = mono_method_full_name (frame->method, TRUE);
617 *trace = g_strdup_printf ("in (unmanaged) %s", fname);
626 * This function is async-safe.
629 get_generic_info_from_stack_frame (MonoJitInfo *ji, MonoContext *ctx)
631 MonoGenericJitInfo *gi;
635 if (!ji->has_generic_jit_info)
637 gi = mono_jit_info_get_generic_jit_info (ji);
643 * Search location list if available, it contains the precise location of the
644 * argument for every pc offset, even if the method was interrupted while it was in
648 int offset = (mgreg_t)MONO_CONTEXT_GET_IP (ctx) - (mgreg_t)ji->code_start;
651 for (i = 0; i < gi->nlocs; ++i) {
652 MonoDwarfLocListEntry *entry = &gi->locations [i];
654 if (offset >= entry->from && (offset < entry->to || entry->to == 0)) {
656 info = (gpointer)mono_arch_context_get_int_reg (ctx, entry->reg);
658 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, entry->reg) + entry->offset);
662 g_assert (i < gi->nlocs);
665 info = (gpointer)mono_arch_context_get_int_reg (ctx, gi->this_reg);
667 info = *(gpointer*)(gpointer)((char*)mono_arch_context_get_int_reg (ctx, gi->this_reg) +
671 method = jinfo_get_method (ji);
672 if (mono_method_get_context (method)->method_inst) {
673 /* A MonoMethodRuntimeGenericContext* */
675 } else if ((method->flags & METHOD_ATTRIBUTE_STATIC) || method->klass->valuetype) {
679 /* Avoid returning a managed object */
680 MonoObject *this_obj = (MonoObject *)info;
682 return this_obj->vtable;
687 * generic_info is either a MonoMethodRuntimeGenericContext or a MonoVTable.
689 static MonoGenericContext
690 get_generic_context_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
692 MonoGenericContext context = { NULL, NULL };
693 MonoClass *klass, *method_container_class;
696 g_assert (generic_info);
698 method = jinfo_get_method (ji);
699 g_assert (method->is_inflated);
700 if (mono_method_get_context (method)->method_inst) {
701 MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext *)generic_info;
703 klass = mrgctx->class_vtable->klass;
704 context.method_inst = mrgctx->method_inst;
705 g_assert (context.method_inst);
707 MonoVTable *vtable = (MonoVTable *)generic_info;
709 klass = vtable->klass;
712 //g_assert (!mono_class_is_gtd (method->klass));
713 if (mono_class_is_ginst (method->klass))
714 method_container_class = mono_class_get_generic_class (method->klass)->container_class;
716 method_container_class = method->klass;
718 /* class might refer to a subclass of method's class */
719 while (!(klass == method->klass || (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->container_class == method_container_class))) {
720 klass = klass->parent;
724 if (mono_class_is_ginst (klass) || mono_class_is_gtd (klass))
725 context.class_inst = mini_class_get_context (klass)->class_inst;
727 if (mono_class_is_ginst (klass))
728 g_assert (mono_class_has_parent_and_ignore_generics (mono_class_get_generic_class (klass)->container_class, method_container_class));
730 g_assert (mono_class_has_parent_and_ignore_generics (klass, method_container_class));
736 get_method_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
739 MonoGenericContext context;
742 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
743 return jinfo_get_method (ji);
744 context = get_generic_context_from_stack_frame (ji, generic_info);
746 method = jinfo_get_method (ji);
747 method = mono_method_get_declaring_generic_method (method);
748 method = mono_class_inflate_generic_method_checked (method, &context, &error);
749 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
755 * mono_exception_walk_native_trace:
756 * @ex: The exception object whose frames should be walked
757 * @func: callback to call for each stack frame
758 * @user_data: data passed to the callback
760 * This function walks the stacktrace of an exception. For
761 * each frame the callback function is called with the relevant info.
762 * The walk ends when no more stack frames are found or when the callback
763 * returns a TRUE value.
767 mono_exception_walk_trace (MonoException *ex, MonoExceptionFrameWalk func, gpointer user_data)
769 MONO_REQ_GC_UNSAFE_MODE;
771 MonoDomain *domain = mono_domain_get ();
772 MonoArray *ta = ex->trace_ips;
778 len = mono_array_length (ta) >> 1;
779 for (i = 0; i < len; i++) {
780 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
781 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
782 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)ip);
785 if (func (NULL, ip, 0, FALSE, user_data))
788 MonoMethod *method = get_method_from_stack_frame (ji, generic_info);
789 if (func (method, ji->code_start, (char *) ip - (char *) ji->code_start, TRUE, user_data))
798 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
801 MonoDomain *domain = mono_domain_get ();
803 MonoArray *ta = exc->trace_ips;
804 MonoDebugSourceLocation *location;
808 /* Exception is not thrown yet */
809 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, 0, &error);
810 mono_error_set_pending_exception (&error);
814 len = mono_array_length (ta) >> 1;
816 res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0, &error);
817 if (mono_error_set_pending_exception (&error))
820 for (i = skip; i < len; i++) {
822 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, &error);
823 if (!mono_error_ok (&error)) {
824 mono_error_set_pending_exception (&error);
827 gpointer ip = mono_array_get (ta, gpointer, i * 2 + 0);
828 gpointer generic_info = mono_array_get (ta, gpointer, i * 2 + 1);
831 ji = mono_jit_info_table_find (domain, (char *)ip);
833 /* Unmanaged frame */
834 mono_array_setref (res, i, sf);
838 g_assert (ji != NULL);
841 /* Can't resolve actual method */
842 method = jinfo_get_method (ji);
844 method = get_method_from_stack_frame (ji, generic_info);
845 if (jinfo_get_method (ji)->wrapper_type) {
849 s = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_REFLECTION);
850 MONO_OBJECT_SETREF (sf, internal_method_name, mono_string_new (domain, s));
854 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, &error);
855 if (!mono_error_ok (&error)) {
856 mono_error_set_pending_exception (&error);
859 MONO_OBJECT_SETREF (sf, method, rm);
862 sf->method_index = ji->from_aot ? mono_aot_find_method_index (method) : 0xffffff;
863 sf->method_address = (gsize) ji->code_start;
864 sf->native_offset = (char *)ip - (char *)ji->code_start;
867 * mono_debug_lookup_source_location() returns both the file / line number information
868 * and the IL offset. Note that computing the IL offset is already an expensive
869 * operation, so we shouldn't call this method twice.
871 location = mono_debug_lookup_source_location (jinfo_get_method (ji), sf->native_offset, domain);
873 sf->il_offset = location->il_offset;
876 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (ji), sf->native_offset, NULL, &sp))
877 sf->il_offset = sp.il_offset;
882 if (need_file_info) {
883 if (location && location->source_file) {
884 MONO_OBJECT_SETREF (sf, filename, mono_string_new (domain, location->source_file));
885 sf->line = location->row;
886 sf->column = location->column;
888 sf->line = sf->column = 0;
893 mono_debug_free_source_location (location);
894 mono_array_setref (res, i, sf);
901 mono_runtime_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
904 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
905 if (jit_tls && jit_tls->orig_ex_ctx_set)
906 start_ctx = &jit_tls->orig_ex_ctx;
908 mono_walk_stack_with_ctx (func, start_ctx, unwind_options, user_data);
911 * mono_walk_stack_with_ctx:
913 * Unwind the current thread starting at @start_ctx.
915 * If @start_ctx is null, we capture the current context.
918 mono_walk_stack_with_ctx (MonoJitStackWalk func, MonoContext *start_ctx, MonoUnwindOptions unwind_options, void *user_data)
920 MonoContext extra_ctx;
921 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
922 MONO_ARCH_CONTEXT_DEF
924 if (!thread || !thread->jit_data)
928 mono_arch_flush_register_windows ();
930 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
931 MONO_INIT_CONTEXT_FROM_CURRENT (&extra_ctx);
933 MONO_INIT_CONTEXT_FROM_FUNC (&extra_ctx, mono_walk_stack_with_ctx);
935 start_ctx = &extra_ctx;
938 mono_walk_stack_full (func, start_ctx, mono_domain_get (), (MonoJitTlsData *)thread->jit_data, mono_get_lmf (), unwind_options, user_data);
942 * mono_walk_stack_with_state:
944 * Unwind a thread described by @state.
946 * State must be valid (state->valid == TRUE).
948 * If you are using this function to unwind another thread, make sure it is suspended.
950 * If @state is null, we capture the current context.
953 mono_walk_stack_with_state (MonoJitStackWalk func, MonoThreadUnwindState *state, MonoUnwindOptions unwind_options, void *user_data)
955 MonoThreadUnwindState extra_state;
957 g_assert (!mono_thread_info_is_async_context ());
958 if (!mono_thread_state_init_from_current (&extra_state))
960 state = &extra_state;
963 g_assert (state->valid);
965 if (!state->unwind_data [MONO_UNWIND_DATA_DOMAIN])
969 mono_walk_stack_full (func,
971 (MonoDomain *)state->unwind_data [MONO_UNWIND_DATA_DOMAIN],
972 (MonoJitTlsData *)state->unwind_data [MONO_UNWIND_DATA_JIT_TLS],
973 (MonoLMF *)state->unwind_data [MONO_UNWIND_DATA_LMF],
974 unwind_options, user_data);
978 mono_walk_stack (MonoJitStackWalk func, MonoUnwindOptions options, void *user_data)
980 MonoThreadUnwindState state;
981 if (!mono_thread_state_init_from_current (&state))
983 mono_walk_stack_with_state (func, &state, options, user_data);
987 * mono_walk_stack_full:
988 * @func: callback to call for each stack frame
989 * @domain: starting appdomain, can be NULL to use the current domain
990 * @unwind_options: what extra information the unwinder should gather
991 * @start_ctx: starting state of the stack walk, can be NULL.
992 * @thread: the thread whose stack to walk, can be NULL to use the current thread
993 * @lmf: the LMF of @thread, can be NULL to use the LMF of the current thread
994 * @user_data: data passed to the callback
996 * This function walks the stack of a thread, starting from the state
997 * represented by start_ctx. For each frame the callback
998 * function is called with the relevant info. The walk ends when no more
999 * managed stack frames are found or when the callback returns a TRUE value.
1002 mono_walk_stack_full (MonoJitStackWalk func, MonoContext *start_ctx, MonoDomain *domain, MonoJitTlsData *jit_tls, MonoLMF *lmf, MonoUnwindOptions unwind_options, gpointer user_data)
1005 MonoContext ctx, new_ctx;
1006 StackFrameInfo frame;
1008 mgreg_t *reg_locations [MONO_MAX_IREGS];
1009 mgreg_t *new_reg_locations [MONO_MAX_IREGS];
1010 gboolean get_reg_locations = unwind_options & MONO_UNWIND_REG_LOCATIONS;
1011 gboolean async = mono_thread_info_is_async_context ();
1013 if (mono_llvm_only) {
1019 ips = get_unwind_backtrace ();
1020 for (l = ips; l; l = l->next) {
1021 guint8 *ip = (guint8*)l->data;
1022 memset (&frame, 0, sizeof (StackFrameInfo));
1023 frame.ji = mini_jit_info_table_find (domain, (char*)ip, &frame.domain);
1024 if (!frame.ji || frame.ji->is_trampoline)
1026 frame.type = FRAME_TYPE_MANAGED;
1027 frame.method = jinfo_get_method (frame.ji);
1028 // FIXME: Cannot lookup the actual method
1029 frame.actual_method = frame.method;
1030 if (frame.type == FRAME_TYPE_MANAGED) {
1031 if (!frame.method->wrapper_type || frame.method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
1032 frame.managed = TRUE;
1034 frame.native_offset = ip - (guint8*)frame.ji->code_start;
1035 frame.il_offset = -1;
1037 if (func (&frame, NULL, user_data))
1044 g_assert (start_ctx);
1047 /*The LMF will be null if the target have no managed frames.*/
1048 /* g_assert (lmf); */
1051 g_assert (unwind_options == MONO_UNWIND_NONE);
1053 memcpy (&ctx, start_ctx, sizeof (MonoContext));
1054 memset (reg_locations, 0, sizeof (reg_locations));
1056 while (MONO_CONTEXT_GET_SP (&ctx) < jit_tls->end_of_stack) {
1058 res = mono_find_jit_info_ext (domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, get_reg_locations ? new_reg_locations : NULL, &frame);
1062 if ((unwind_options & MONO_UNWIND_LOOKUP_IL_OFFSET) && frame.ji && !frame.ji->is_trampoline) {
1063 MonoDebugSourceLocation *source;
1065 source = mono_debug_lookup_source_location (jinfo_get_method (frame.ji), frame.native_offset, domain);
1067 il_offset = source->il_offset;
1070 if (mono_find_prev_seq_point_for_native_offset (domain, jinfo_get_method (frame.ji), frame.native_offset, NULL, &sp))
1071 il_offset = sp.il_offset;
1075 mono_debug_free_source_location (source);
1079 frame.il_offset = il_offset;
1081 if ((unwind_options & MONO_UNWIND_LOOKUP_ACTUAL_METHOD) && frame.ji && !frame.ji->is_trampoline) {
1082 frame.actual_method = get_method_from_stack_frame (frame.ji, get_generic_info_from_stack_frame (frame.ji, &ctx));
1084 frame.actual_method = frame.method;
1087 if (get_reg_locations)
1088 frame.reg_locations = reg_locations;
1090 if (func (&frame, &ctx, user_data))
1093 if (get_reg_locations) {
1094 for (i = 0; i < MONO_MAX_IREGS; ++i)
1095 if (new_reg_locations [i])
1096 reg_locations [i] = new_reg_locations [i];
1104 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info,
1105 MonoReflectionMethod **method,
1106 gint32 *iloffset, gint32 *native_offset,
1107 MonoString **file, gint32 *line, gint32 *column)
1110 MonoDomain *domain = mono_domain_get ();
1111 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1112 MonoLMF *lmf = mono_get_lmf ();
1113 MonoJitInfo *ji = NULL;
1114 MonoContext ctx, new_ctx;
1115 MonoDebugSourceLocation *location;
1116 MonoMethod *jmethod = NULL, *actual_method;
1117 StackFrameInfo frame;
1120 MONO_ARCH_CONTEXT_DEF;
1122 if (mono_llvm_only) {
1124 MonoDomain *frame_domain;
1125 guint8 *frame_ip = NULL;
1127 /* FIXME: Generalize this code with an interface which returns an array of StackFrame structures */
1129 ips = get_unwind_backtrace ();
1130 for (l = ips; l && skip >= 0; l = l->next) {
1131 guint8 *ip = (guint8*)l->data;
1135 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &frame_domain);
1136 if (!ji || ji->is_trampoline)
1139 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1140 jmethod = jinfo_get_method (ji);
1141 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1148 /* No way to resolve generic instances */
1149 actual_method = jmethod;
1150 *native_offset = frame_ip - (guint8*)ji->code_start;
1152 mono_arch_flush_register_windows ();
1154 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1155 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
1157 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
1163 res = mono_find_jit_info_ext (domain, jit_tls, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1167 if (frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1168 frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1169 frame.type == FRAME_TYPE_TRAMPOLINE)
1173 *native_offset = frame.native_offset;
1175 /* The skip count passed by the caller depends on us not filtering out MANAGED_TO_NATIVE */
1176 jmethod = jinfo_get_method (ji);
1177 if (jmethod->wrapper_type != MONO_WRAPPER_NONE && jmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && jmethod->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
1180 } while (skip >= 0);
1182 actual_method = get_method_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, &ctx));
1185 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, actual_method, NULL, &error);
1186 if (!mono_error_ok (&error)) {
1187 mono_error_set_pending_exception (&error);
1190 mono_gc_wbarrier_generic_store (method, (MonoObject*) rm);
1192 location = mono_debug_lookup_source_location (jmethod, *native_offset, domain);
1194 *iloffset = location->il_offset;
1198 if (need_file_info) {
1200 mono_gc_wbarrier_generic_store (file, (MonoObject*) mono_string_new (domain, location->source_file));
1201 *line = location->row;
1202 *column = location->column;
1205 *line = *column = 0;
1209 mono_debug_free_source_location (location);
1215 get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContext *ctx)
1218 MonoClass *catch_class = ei->data.catch_class;
1219 MonoType *inflated_type;
1220 MonoGenericContext context;
1222 /*MonoJitExceptionInfo::data is an union used by filter and finally clauses too.*/
1223 if (!catch_class || ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
1226 if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
1228 context = get_generic_context_from_stack_frame (ji, get_generic_info_from_stack_frame (ji, ctx));
1230 /* FIXME: we shouldn't inflate but instead put the
1231 type in the rgctx and fetch it from there. It
1232 might be a good idea to do this lazily, i.e. only
1233 when the exception is actually thrown, so as not to
1234 waste space for exception clauses which might never
1236 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
1237 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
1239 catch_class = mono_class_from_mono_type (inflated_type);
1240 mono_metadata_free_type (inflated_type);
1246 * mini_jit_info_table_find_ext:
1248 * Same as mono_jit_info_table_find, but search all the domains of the current thread
1249 * if ADDR is not found in DOMAIN. The domain where the method was found is stored into
1250 * OUT_DOMAIN if it is not NULL.
1253 mini_jit_info_table_find_ext (MonoDomain *domain, char *addr, gboolean allow_trampolines, MonoDomain **out_domain)
1256 MonoInternalThread *t = mono_thread_internal_current ();
1262 ji = mono_jit_info_table_find_internal (domain, addr, TRUE, allow_trampolines);
1265 *out_domain = domain;
1269 /* maybe it is shared code, so we also search in the root domain */
1270 if (domain != mono_get_root_domain ()) {
1271 ji = mono_jit_info_table_find_internal (mono_get_root_domain (), addr, TRUE, allow_trampolines);
1274 *out_domain = mono_get_root_domain ();
1282 refs = (gpointer *)((t->appdomain_refs) ? *(gpointer *) t->appdomain_refs : NULL);
1283 for (; refs && *refs; refs++) {
1284 if (*refs != domain && *refs != mono_get_root_domain ()) {
1285 ji = mono_jit_info_table_find_internal ((MonoDomain*) *refs, addr, TRUE, allow_trampolines);
1288 *out_domain = (MonoDomain*) *refs;
1298 mini_jit_info_table_find (MonoDomain *domain, char *addr, MonoDomain **out_domain)
1300 return mini_jit_info_table_find_ext (domain, addr, FALSE, out_domain);
1303 /* Class lazy loading functions */
1304 static GENERATE_GET_CLASS_WITH_CACHE (runtime_compat_attr, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute")
1307 * wrap_non_exception_throws:
1309 * Determine whenever M's assembly has a RuntimeCompatibilityAttribute with the
1310 * WrapNonExceptionThrows flag set.
1313 wrap_non_exception_throws (MonoMethod *m)
1316 MonoAssembly *ass = m->klass->image->assembly;
1317 MonoCustomAttrInfo* attrs;
1320 gboolean val = FALSE;
1323 if (ass->wrap_non_exception_throws_inited)
1324 return ass->wrap_non_exception_throws;
1326 klass = mono_class_get_runtime_compat_attr_class ();
1328 attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
1329 mono_error_cleanup (&error); /* FIXME don't swallow the error */
1331 for (i = 0; i < attrs->num_attrs; ++i) {
1332 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1334 int num_named, named_type, name_len;
1337 if (!attr->ctor || attr->ctor->klass != klass)
1339 /* Decode the RuntimeCompatibilityAttribute. See reflection.c */
1340 p = (const char*)attr->data;
1341 g_assert (read16 (p) == 0x0001);
1343 num_named = read16 (p);
1349 /* data_type = *p; */
1352 if (named_type != 0x54)
1354 name_len = mono_metadata_decode_blob_size (p, &p);
1355 name = (char *)g_malloc (name_len + 1);
1356 memcpy (name, p, name_len);
1357 name [name_len] = 0;
1359 g_assert (!strcmp (name, "WrapNonExceptionThrows"));
1361 /* The value is a BOOLEAN */
1364 mono_custom_attrs_free (attrs);
1367 ass->wrap_non_exception_throws = val;
1368 mono_memory_barrier ();
1369 ass->wrap_non_exception_throws_inited = TRUE;
1374 #define MAX_UNMANAGED_BACKTRACE 128
1376 build_native_trace (MonoError *error)
1378 mono_error_init (error);
1379 /* This puppy only makes sense on mobile, IOW, ARM. */
1380 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
1382 void *native_trace [MAX_UNMANAGED_BACKTRACE];
1385 size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
1391 res = mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, size, error);
1392 return_val_if_nok (error, NULL);
1394 for (i = 0; i < size; i++)
1395 mono_array_set (res, gpointer, i, native_trace [i]);
1403 setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, GList **trace_ips)
1406 *trace_ips = g_list_reverse (*trace_ips);
1408 MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
1409 mono_error_assert_ok (&error);
1410 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
1411 MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace (&error));
1412 mono_error_assert_ok (&error);
1413 if (dynamic_methods) {
1414 /* These methods could go away anytime, so save a reference to them in the exception object */
1416 MonoMList *list = NULL;
1418 for (l = dynamic_methods; l; l = l->next) {
1420 MonoDomain *domain = mono_domain_get ();
1422 if (domain->method_to_dyn_method) {
1423 mono_domain_lock (domain);
1424 dis_link = (guint32)(size_t)g_hash_table_lookup (domain->method_to_dyn_method, l->data);
1425 mono_domain_unlock (domain);
1427 MonoObject *o = mono_gchandle_get_target (dis_link);
1429 list = mono_mlist_prepend_checked (list, o, &error);
1430 mono_error_assert_ok (&error);
1436 MONO_OBJECT_SETREF (mono_ex, dynamic_methods, list);
1439 g_list_free (*trace_ips);
1444 * mono_handle_exception_internal_first_pass:
1446 * The first pass of exception handling. Unwind the stack until a catch clause which can catch
1447 * OBJ is found. Run the index of the filter clause which caught the exception into
1448 * OUT_FILTER_IDX. Return TRUE if the exception is caught, FALSE otherwise.
1451 mono_handle_exception_internal_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filter_idx, MonoJitInfo **out_ji, MonoJitInfo **out_prev_ji, MonoObject *non_exception)
1454 MonoDomain *domain = mono_domain_get ();
1455 MonoJitInfo *ji = NULL;
1456 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1457 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1458 MonoLMF *lmf = mono_get_lmf ();
1459 GList *trace_ips = NULL;
1460 GSList *dynamic_methods = NULL;
1461 MonoException *mono_ex;
1462 gboolean stack_overflow = FALSE;
1463 MonoContext initial_ctx;
1465 int frame_count = 0;
1470 g_assert (ctx != NULL);
1472 if (obj == (MonoObject *)domain->stack_overflow_ex)
1473 stack_overflow = TRUE;
1475 mono_ex = (MonoException*)obj;
1476 MonoArray *initial_trace_ips = mono_ex->trace_ips;
1477 if (initial_trace_ips) {
1478 int len = mono_array_length (initial_trace_ips) >> 1;
1480 for (i = 0; i < (len - 1); i++) {
1481 gpointer ip = mono_array_get (initial_trace_ips, gpointer, i * 2 + 0);
1482 gpointer generic_info = mono_array_get (initial_trace_ips, gpointer, i * 2 + 1);
1483 trace_ips = g_list_prepend (trace_ips, ip);
1484 trace_ips = g_list_prepend (trace_ips, generic_info);
1488 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1489 mono_error_assert_ok (&error);
1494 call_filter = (int (*) (MonoContext *, void *))mono_get_call_filter ();
1496 g_assert (jit_tls->end_of_stack);
1497 g_assert (jit_tls->abort_func);
1500 *out_filter_idx = -1;
1504 *out_prev_ji = NULL;
1509 MonoContext new_ctx;
1511 int clause_index_start = 0;
1512 gboolean unwind_res = TRUE;
1514 StackFrameInfo frame;
1519 unwind_res = mono_find_jit_info_ext (domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1521 if (frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1522 frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1523 frame.type == FRAME_TYPE_TRAMPOLINE) {
1527 g_assert (frame.type == FRAME_TYPE_MANAGED);
1532 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1533 g_slist_free (dynamic_methods);
1538 method = jinfo_get_method (ji);
1539 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1541 if (mini_get_debug_options ()->reverse_pinvoke_exceptions && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
1542 g_error ("A native frame was found while unwinding the stack after an exception.\n"
1543 "The native frame called the managed method:\n%s\n",
1544 mono_method_full_name (method, TRUE));
1547 if (method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
1548 // avoid giant stack traces during a stack overflow
1549 if (frame_count < 1000) {
1550 trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1551 trace_ips = g_list_prepend (trace_ips, get_generic_info_from_stack_frame (ji, ctx));
1555 if (method->dynamic)
1556 dynamic_methods = g_slist_prepend (dynamic_methods, method);
1558 if (stack_overflow) {
1559 if (MONO_ARCH_STACK_GROWS_UP)
1560 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1562 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1564 free_stack = 0xffffff;
1567 for (i = clause_index_start; i < ji->num_clauses; i++) {
1568 MonoJitExceptionInfo *ei = &ji->clauses [i];
1569 gboolean filtered = FALSE;
1572 * During stack overflow, wait till the unwinding frees some stack
1573 * space before running handlers/finalizers.
1575 if (free_stack <= (64 * 1024))
1578 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
1580 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1583 * Have to unwrap RuntimeWrappedExceptions if the
1584 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1586 if (non_exception && !wrap_non_exception_throws (method))
1587 ex_obj = non_exception;
1591 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1592 gboolean is_user_frame = method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD;
1593 #ifndef DISABLE_PERFCOUNTERS
1594 mono_perfcounters->exceptions_filters++;
1597 Here's the thing, if this is a filter clause done by a wrapper like runtime invoke, we don't want to
1598 trim the stackframe since if it returns FALSE we lose information.
1600 FIXME Not 100% sure if it's a good idea even with user clauses.
1603 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1605 #ifndef MONO_CROSS_COMPILE
1606 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1608 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1610 /* Can't pass the ex object in a register yet to filter clauses, because call_filter () might not support it */
1611 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1613 g_assert (!ji->from_llvm);
1614 /* store the exception object in bp + ei->exvar_offset */
1615 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1619 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1621 * Pass the original il clause index to the landing pad so it can
1622 * branch to the landing pad associated with the il clause.
1623 * This is needed because llvm compiled code assumes that the EH
1624 * code always branches to the innermost landing pad.
1627 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1630 mono_debugger_agent_begin_exception_filter (mono_ex, ctx, &initial_ctx);
1631 filtered = call_filter (ctx, ei->data.filter);
1632 mono_debugger_agent_end_exception_filter (mono_ex, ctx, &initial_ctx);
1633 if (filtered && out_filter_idx)
1634 *out_filter_idx = filter_idx;
1641 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1642 g_slist_free (dynamic_methods);
1643 /* mono_debugger_agent_handle_exception () needs this */
1644 mini_set_abort_threshold (ctx);
1645 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1650 MonoError isinst_error;
1651 mono_error_init (&isinst_error);
1652 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (ex_obj, catch_class, &error)) {
1653 setup_stack_trace (mono_ex, dynamic_methods, &trace_ips);
1654 g_slist_free (dynamic_methods);
1659 /* mono_debugger_agent_handle_exception () needs this */
1660 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1663 mono_error_cleanup (&isinst_error);
1670 g_assert_not_reached ();
1674 * mono_handle_exception_internal:
1675 * @ctx: saved processor state
1676 * @obj: the exception object
1677 * @resume: whenever to resume unwinding based on the state in MonoJitTlsData.
1680 mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resume, MonoJitInfo **out_ji)
1683 MonoDomain *domain = mono_domain_get ();
1684 MonoJitInfo *ji, *prev_ji;
1685 static int (*call_filter) (MonoContext *, gpointer) = NULL;
1686 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
1687 MonoLMF *lmf = mono_get_lmf ();
1688 MonoException *mono_ex;
1689 gboolean stack_overflow = FALSE;
1690 MonoContext initial_ctx;
1692 int frame_count = 0;
1693 gint32 filter_idx, first_filter_idx = 0;
1696 MonoObject *non_exception = NULL;
1698 g_assert (ctx != NULL);
1700 MonoException *ex = mono_get_exception_null_reference ();
1701 MONO_OBJECT_SETREF (ex, message, mono_string_new (domain, "Object reference not set to an instance of an object"));
1702 obj = (MonoObject *)ex;
1706 * Allocate a new exception object instead of the preconstructed ones.
1708 if (obj == (MonoObject *)domain->stack_overflow_ex) {
1710 * It is not a good idea to try and put even more pressure on the little stack available.
1711 * obj = mono_get_exception_stack_overflow ();
1713 stack_overflow = TRUE;
1715 else if (obj == (MonoObject *)domain->null_reference_ex) {
1716 obj = (MonoObject *)mono_get_exception_null_reference ();
1719 if (!mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1720 mono_error_assert_ok (&error);
1721 non_exception = obj;
1722 obj = (MonoObject *)mono_get_exception_runtime_wrapped_checked (obj, &error);
1723 mono_error_assert_ok (&error);
1726 mono_ex = (MonoException*)obj;
1728 if (mini_get_debug_options ()->suspend_on_exception) {
1729 mono_runtime_printf_err ("Exception thrown, suspending...");
1734 if (mono_object_isinst_checked (obj, mono_defaults.exception_class, &error)) {
1735 mono_ex = (MonoException*)obj;
1737 mono_error_assert_ok (&error);
1741 if (mono_ex && jit_tls->class_cast_from) {
1742 if (!strcmp (mono_ex->object.vtable->klass->name, "InvalidCastException")) {
1743 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1744 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1745 char *msg = g_strdup_printf ("Unable to cast object of type '%s' to type '%s'.", from_name, to_name);
1746 mono_ex->message = mono_string_new (domain, msg);
1751 if (!strcmp (mono_ex->object.vtable->klass->name, "ArrayTypeMismatchException")) {
1752 char *from_name = mono_type_get_full_name (jit_tls->class_cast_from);
1753 char *to_name = mono_type_get_full_name (jit_tls->class_cast_to);
1754 char *msg = g_strdup_printf ("Source array of type '%s' cannot be cast to destination array type '%s'.", from_name, to_name);
1755 mono_ex->message = mono_string_new (domain, msg);
1763 call_filter = (int (*)(MonoContext *, void*))mono_get_call_filter ();
1765 g_assert (jit_tls->end_of_stack);
1766 g_assert (jit_tls->abort_func);
1769 * We set orig_ex_ctx_set to TRUE/FALSE around profiler calls to make sure it doesn't
1770 * end up being TRUE on any code path.
1772 memcpy (&jit_tls->orig_ex_ctx, ctx, sizeof (MonoContext));
1777 MonoContext ctx_cp = *ctx;
1778 if (mono_trace_is_enabled ()) {
1779 MonoMethod *system_exception_get_message = mono_class_get_method_from_name (mono_defaults.exception_class, "get_Message", 0);
1780 MonoMethod *get_message = system_exception_get_message == NULL ? NULL : mono_object_get_virtual_method (obj, system_exception_get_message);
1781 MonoObject *message;
1782 const char *type_name = mono_class_get_name (mono_object_class (mono_ex));
1784 if (get_message == NULL) {
1786 } else if (!strcmp (type_name, "OutOfMemoryException") || !strcmp (type_name, "StackOverflowException")) {
1788 msg = g_strdup_printf ("(No exception message for: %s)\n", type_name);
1790 MonoObject *exc = NULL;
1791 message = mono_runtime_try_invoke (get_message, obj, NULL, &exc, &error);
1792 g_assert (exc == NULL);
1793 mono_error_assert_ok (&error);
1797 msg = mono_string_to_utf8_checked ((MonoString *) message, &error);
1798 if (!is_ok (&error)) {
1799 mono_error_cleanup (&error);
1800 msg = g_strdup ("(error while display System.Exception.Message property)");
1803 msg = g_strdup ("(System.Exception.Message property not available)");
1806 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);
1808 if (mono_ex && mono_trace_eval_exception (mono_object_class (mono_ex)))
1809 mono_print_thread_dump_from_ctx (ctx);
1811 jit_tls->orig_ex_ctx_set = TRUE;
1812 mono_profiler_exception_thrown (obj);
1813 jit_tls->orig_ex_ctx_set = FALSE;
1815 res = mono_handle_exception_internal_first_pass (&ctx_cp, obj, &first_filter_idx, &ji, &prev_ji, non_exception);
1818 if (mini_get_debug_options ()->break_on_exc)
1820 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1822 if (mini_get_debug_options ()->suspend_on_unhandled) {
1823 mono_runtime_printf_err ("Unhandled exception, suspending...");
1828 // FIXME: This runs managed code so it might cause another stack overflow when
1829 // we are handling a stack overflow
1830 mini_set_abort_threshold (ctx);
1831 mono_unhandled_exception (obj);
1833 gboolean unhandled = FALSE;
1836 * The exceptions caught by the mono_runtime_invoke_checked () calls
1837 * in the threadpool needs to be treated as unhandled (#669836).
1839 * FIXME: The check below is hackish, but its hard to distinguish
1840 * these runtime invoke calls from others in the runtime.
1842 if (ji && jinfo_get_method (ji)->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1843 if (prev_ji && jinfo_get_method (prev_ji) == mono_defaults.threadpool_perform_wait_callback_method)
1848 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, NULL);
1850 mono_debugger_agent_handle_exception ((MonoException *)obj, ctx, &ctx_cp);
1860 MonoContext new_ctx;
1862 int clause_index_start = 0;
1863 gboolean unwind_res = TRUE;
1867 ji = jit_tls->resume_state.ji;
1868 new_ctx = jit_tls->resume_state.new_ctx;
1869 clause_index_start = jit_tls->resume_state.clause_index;
1870 lmf = jit_tls->resume_state.lmf;
1871 first_filter_idx = jit_tls->resume_state.first_filter_idx;
1872 filter_idx = jit_tls->resume_state.filter_idx;
1874 StackFrameInfo frame;
1876 unwind_res = mono_find_jit_info_ext (domain, jit_tls, NULL, ctx, &new_ctx, NULL, &lmf, NULL, &frame);
1878 if (frame.type == FRAME_TYPE_DEBUGGER_INVOKE ||
1879 frame.type == FRAME_TYPE_MANAGED_TO_NATIVE ||
1880 frame.type == FRAME_TYPE_TRAMPOLINE) {
1884 g_assert (frame.type == FRAME_TYPE_MANAGED);
1890 *(mono_get_lmf_addr ()) = lmf;
1892 jit_tls->abort_func (obj);
1893 g_assert_not_reached ();
1896 method = jinfo_get_method (ji);
1898 //printf ("M: %s %d.\n", mono_method_full_name (method, TRUE), frame_count);
1900 if (stack_overflow) {
1901 if (MONO_ARCH_STACK_GROWS_UP)
1902 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (ctx));
1904 free_stack = (guint8*)(MONO_CONTEXT_GET_SP (ctx)) - (guint8*)(MONO_CONTEXT_GET_SP (&initial_ctx));
1906 free_stack = 0xffffff;
1909 for (i = clause_index_start; i < ji->num_clauses; i++) {
1910 MonoJitExceptionInfo *ei = &ji->clauses [i];
1911 gboolean filtered = FALSE;
1914 * During stack overflow, wait till the unwinding frees some stack
1915 * space before running handlers/finalizers.
1917 if (free_stack <= (64 * 1024))
1920 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
1922 MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
1925 * Have to unwrap RuntimeWrappedExceptions if the
1926 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
1928 if (non_exception && !wrap_non_exception_throws (method))
1929 ex_obj = non_exception;
1933 if (((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER))) {
1934 #ifndef MONO_CROSS_COMPILE
1935 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
1936 MONO_CONTEXT_SET_LLVM_EXC_REG (ctx, ex_obj);
1938 g_assert (!ji->from_llvm);
1939 /* store the exception object in bp + ei->exvar_offset */
1940 *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = ex_obj;
1945 #ifdef MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG
1947 MONO_CONTEXT_SET_LLVM_EH_SELECTOR_REG (ctx, ei->clause_index);
1950 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1952 * Filter clauses should only be run in the
1953 * first pass of exception handling.
1955 filtered = (filter_idx == first_filter_idx);
1959 mono_error_init (&error);
1960 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE &&
1961 mono_object_isinst_checked (ex_obj, catch_class, &error)) || filtered) {
1963 * This guards against the situation that we abort a thread that is executing a finally clause
1964 * that was called by the EH machinery. It won't have a guard trampoline installed, so we must
1965 * check for this situation here and resume interruption if we are below the guarded block.
1967 if (G_UNLIKELY (jit_tls->handler_block_return_address)) {
1968 gboolean is_outside = FALSE;
1969 gpointer prot_bp = MONO_CONTEXT_GET_BP (&jit_tls->handler_block_context);
1970 gpointer catch_bp = MONO_CONTEXT_GET_BP (ctx);
1971 //FIXME make this stack direction aware
1972 if (catch_bp > prot_bp) {
1974 } else if (catch_bp == prot_bp) {
1975 /* Can be either try { try { } catch {} } finally {} or try { try { } finally {} } catch {}
1976 * So we check if the catch handler_start is protected by the guarded handler protected region
1979 * If there is an outstanding guarded_block return address, it means the current thread must be aborted.
1980 * This is the only way to reach out the guarded block as other cases are handled by the trampoline.
1981 * There aren't any further finally/fault handler blocks down the stack over this exception.
1982 * This must be ensured by the code that installs the guard trampoline.
1984 g_assert (ji == mini_jit_info_table_find (domain, (char *)MONO_CONTEXT_GET_IP (&jit_tls->handler_block_context), NULL));
1986 if (!is_address_protected (ji, jit_tls->handler_block, ei->handler_start)) {
1991 jit_tls->handler_block_return_address = NULL;
1992 jit_tls->handler_block = NULL;
1993 mono_thread_resume_interruption (); /*We ignore the exception here, it will be raised later*/
1997 if (mono_trace_is_enabled () && mono_trace_eval (method))
1998 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (method, TRUE));
1999 jit_tls->orig_ex_ctx_set = TRUE;
2000 mono_profiler_exception_clause_handler (method, ei->flags, i);
2001 jit_tls->orig_ex_ctx_set = FALSE;
2002 mini_set_abort_threshold (ctx);
2003 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2005 #ifndef DISABLE_PERFCOUNTERS
2006 mono_perfcounters->exceptions_depth += frame_count;
2008 if (obj == (MonoObject *)domain->stack_overflow_ex)
2009 jit_tls->handling_stack_ovf = FALSE;
2013 mono_error_cleanup (&error);
2014 if (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
2015 if (mono_trace_is_enabled () && mono_trace_eval (method))
2016 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2017 jit_tls->orig_ex_ctx_set = TRUE;
2018 mono_profiler_exception_clause_handler (method, ei->flags, i);
2019 jit_tls->orig_ex_ctx_set = FALSE;
2020 mini_set_abort_threshold (ctx);
2021 call_filter (ctx, ei->handler_start);
2023 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2024 if (mono_trace_is_enabled () && mono_trace_eval (method))
2025 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (method, TRUE));
2026 jit_tls->orig_ex_ctx_set = TRUE;
2027 mono_profiler_exception_clause_handler (method, ei->flags, i);
2028 jit_tls->orig_ex_ctx_set = FALSE;
2029 #ifndef DISABLE_PERFCOUNTERS
2030 mono_perfcounters->exceptions_finallys++;
2033 if (ji->from_llvm) {
2035 * LLVM compiled finally handlers follow the design
2036 * of the c++ ehabi, i.e. they call a resume function
2037 * at the end instead of returning to the caller.
2038 * So save the exception handling state,
2039 * mono_resume_unwind () will call us again to continue
2042 jit_tls->resume_state.ex_obj = obj;
2043 jit_tls->resume_state.ji = ji;
2044 jit_tls->resume_state.clause_index = i + 1;
2045 jit_tls->resume_state.ctx = *ctx;
2046 jit_tls->resume_state.new_ctx = new_ctx;
2047 jit_tls->resume_state.lmf = lmf;
2048 jit_tls->resume_state.first_filter_idx = first_filter_idx;
2049 jit_tls->resume_state.filter_idx = filter_idx;
2050 mini_set_abort_threshold (ctx);
2051 MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
2054 mini_set_abort_threshold (ctx);
2055 call_filter (ctx, ei->handler_start);
2061 jit_tls->orig_ex_ctx_set = TRUE;
2062 mono_profiler_exception_method_leave (method);
2063 jit_tls->orig_ex_ctx_set = FALSE;
2068 g_assert_not_reached ();
2072 * mono_debugger_run_finally:
2073 * @start_ctx: saved processor state
2075 * This method is called by the Mono Debugger to call all `finally' clauses of the
2076 * current stack frame. It's used when the user issues a `return' command to make
2077 * the current stack frame return. After returning from this method, the debugger
2078 * unwinds the stack one frame and gives control back to the user.
2080 * NOTE: This method is only used when running inside the Mono Debugger.
2083 mono_debugger_run_finally (MonoContext *start_ctx)
2085 static int (*call_filter) (MonoContext *, gpointer) = NULL;
2086 MonoDomain *domain = mono_domain_get ();
2087 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2088 MonoLMF *lmf = mono_get_lmf ();
2089 MonoContext ctx, new_ctx;
2090 MonoJitInfo *ji, rji;
2095 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
2096 if (!ji || ji == (gpointer)-1)
2100 call_filter = (int (*)(MonoContext *, void *))mono_get_call_filter ();
2102 for (i = 0; i < ji->num_clauses; i++) {
2103 MonoJitExceptionInfo *ei = &ji->clauses [i];
2105 if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (&ctx)) &&
2106 (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
2107 call_filter (&ctx, ei->handler_start);
2113 * mono_handle_exception:
2114 * @ctx: saved processor state
2115 * @obj: the exception object
2118 mono_handle_exception (MonoContext *ctx, MonoObject *obj)
2120 MONO_REQ_GC_UNSAFE_MODE;
2122 #ifndef DISABLE_PERFCOUNTERS
2123 mono_perfcounters->exceptions_thrown++;
2126 return mono_handle_exception_internal (ctx, obj, FALSE, NULL);
2129 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2131 #ifndef MONO_ARCH_USE_SIGACTION
2132 #error "Can't use sigaltstack without sigaction"
2135 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
2138 mono_setup_altstack (MonoJitTlsData *tls)
2142 guint8 *staddr = NULL;
2144 if (mono_running_on_valgrind ())
2147 mono_thread_info_get_stack_bounds (&staddr, &stsize);
2151 tls->end_of_stack = staddr + stsize;
2152 tls->stack_size = stsize;
2154 /*g_print ("thread %p, stack_base: %p, stack_size: %d\n", (gpointer)pthread_self (), staddr, stsize);*/
2156 tls->stack_ovf_guard_base = staddr + mono_pagesize ();
2157 tls->stack_ovf_guard_size = ALIGN_TO (8 * 4096, mono_pagesize ());
2159 g_assert ((guint8*)&sa >= (guint8*)tls->stack_ovf_guard_base + tls->stack_ovf_guard_size);
2161 if (mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE)) {
2162 /* mprotect can fail for the main thread stack */
2163 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);
2164 g_assert (gaddr == tls->stack_ovf_guard_base);
2165 tls->stack_ovf_valloced = TRUE;
2168 /* Setup an alternate signal stack */
2169 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);
2170 tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2172 g_assert (tls->signal_stack);
2174 sa.ss_sp = tls->signal_stack;
2175 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2177 g_assert (sigaltstack (&sa, NULL) == 0);
2179 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);
2183 mono_free_altstack (MonoJitTlsData *tls)
2188 sa.ss_sp = tls->signal_stack;
2189 sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
2190 sa.ss_flags = SS_DISABLE;
2191 err = sigaltstack (&sa, NULL);
2192 g_assert (err == 0);
2194 if (tls->signal_stack)
2195 mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE, MONO_MEM_ACCOUNT_EXCEPTIONS);
2196 if (tls->stack_ovf_valloced)
2197 mono_vfree (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MEM_ACCOUNT_EXCEPTIONS);
2199 mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
2202 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2205 mono_setup_altstack (MonoJitTlsData *tls)
2210 mono_free_altstack (MonoJitTlsData *tls)
2214 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
2217 try_restore_stack_protection (MonoJitTlsData *jit_tls, int extra_bytes)
2219 gint32 unprotect_size = jit_tls->stack_ovf_guard_size;
2220 /* we need to leave some room for throwing the exception */
2221 while (unprotect_size >= 0 && (char*)jit_tls->stack_ovf_guard_base + unprotect_size > ((char*)&unprotect_size - extra_bytes))
2222 unprotect_size -= mono_pagesize ();
2223 /* at this point we could try and build a new domain->stack_overflow_ex, but only if there
2224 * is sufficient stack
2226 //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);
2228 mono_mprotect (jit_tls->stack_ovf_guard_base, unprotect_size, MONO_MMAP_NONE);
2229 return unprotect_size == jit_tls->stack_ovf_guard_size;
2232 static G_GNUC_UNUSED void
2233 try_more_restore (void)
2235 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2236 if (try_restore_stack_protection (jit_tls, 500))
2237 jit_tls->restore_stack_prot = NULL;
2240 static G_GNUC_UNUSED void
2241 restore_stack_protection (void)
2243 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2244 MonoException *ex = mono_domain_get ()->stack_overflow_ex;
2245 /* if we can't restore the stack protection, keep a callback installed so
2246 * we'll try to restore as much stack as we can at each return from unmanaged
2249 if (try_restore_stack_protection (jit_tls, 4096))
2250 jit_tls->restore_stack_prot = NULL;
2252 jit_tls->restore_stack_prot = try_more_restore_tramp;
2253 /* here we also throw a stack overflow exception */
2254 ex->trace_ips = NULL;
2255 ex->stack_trace = NULL;
2256 mono_raise_exception (ex);
2260 mono_altstack_restore_prot (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
2262 MONO_REQ_GC_UNSAFE_MODE;
2264 void (*func)(void) = (void (*)(void))tramp_data;
2270 mono_handle_soft_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, guint8* fault_addr)
2275 /* we got a stack overflow in the soft-guard pages
2276 * There are two cases:
2277 * 1) managed code caused the overflow: we unprotect the soft-guard page
2278 * and let the arch-specific code trigger the exception handling mechanism
2279 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
2280 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
2281 * and hope we can continue with those enabled, at least until the hard-guard page
2282 * is hit. The alternative to continuing here is to just print a message and abort.
2283 * We may add in the future the code to protect the pages again in the codepath
2284 * when we return from unmanaged to managed code.
2286 if (jit_tls->stack_ovf_guard_size && fault_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
2287 fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
2288 /* we unprotect the minimum amount we can */
2290 gboolean handled = FALSE;
2292 guard_size = jit_tls->stack_ovf_guard_size - (mono_pagesize () * SIZEOF_VOID_P / 4);
2293 while (guard_size && fault_addr < (guint8*)jit_tls->stack_ovf_guard_base + guard_size) {
2294 guard_size -= mono_pagesize ();
2296 guard_size = jit_tls->stack_ovf_guard_size - guard_size;
2297 /*fprintf (stderr, "unprotecting: %d\n", guard_size);*/
2298 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);
2299 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2301 mono_arch_handle_altstack_exception (ctx, siginfo, fault_addr, TRUE);
2306 /* We print a message: after this even managed stack overflows
2307 * may crash the runtime
2309 mono_runtime_printf_err ("Stack overflow in unmanaged: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2310 if (!jit_tls->handling_stack_ovf) {
2311 jit_tls->restore_stack_prot = restore_stack_protection_tramp;
2312 jit_tls->handling_stack_ovf = 1;
2314 /*fprintf (stderr, "Already handling stack overflow\n");*/
2323 MonoMethod *omethod;
2325 } PrintOverflowUserData;
2327 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2329 print_overflow_stack_frame (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2331 MonoMethod *method = NULL;
2332 PrintOverflowUserData *user_data = (PrintOverflowUserData *)data;
2335 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2336 method = jinfo_get_method (frame->ji);
2339 if (user_data->count == 0) {
2340 /* The first frame is in its prolog, so a line number cannot be computed */
2341 user_data->count ++;
2345 /* If this is a one method overflow, skip the other instances */
2346 if (method == user_data->omethod)
2349 location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2350 mono_runtime_printf_err (" %s", location);
2353 if (user_data->count == 1) {
2354 mono_runtime_printf_err (" <...>");
2355 user_data->omethod = method;
2357 user_data->omethod = NULL;
2360 user_data->count ++;
2362 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2369 mono_handle_hard_stack_ovf (MonoJitTlsData *jit_tls, MonoJitInfo *ji, void *ctx, guint8* fault_addr)
2371 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2372 PrintOverflowUserData ud;
2376 /* we don't do much now, but we can warn the user with a useful message */
2377 mono_runtime_printf_err ("Stack overflow: IP: %p, fault addr: %p", mono_arch_ip_from_context (ctx), fault_addr);
2379 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2380 mono_sigctx_to_monoctx (ctx, &mctx);
2382 mono_runtime_printf_err ("Stacktrace:");
2384 memset (&ud, 0, sizeof (ud));
2386 mono_walk_stack_with_ctx (print_overflow_stack_frame, &mctx, MONO_UNWIND_LOOKUP_ACTUAL_METHOD, &ud);
2388 if (ji && !ji->is_trampoline && jinfo_get_method (ji))
2389 mono_runtime_printf_err ("At %s", mono_method_full_name (jinfo_get_method (ji), TRUE));
2391 mono_runtime_printf_err ("At <unmanaged>.");
2398 print_stack_frame_to_stderr (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2400 MonoMethod *method = NULL;
2402 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2403 method = jinfo_get_method (frame->ji);
2406 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, mono_domain_get ());
2407 mono_runtime_printf_err (" %s", location);
2410 mono_runtime_printf_err (" at <unknown> <0x%05x>", frame->native_offset);
2415 static G_GNUC_UNUSED gboolean
2416 print_stack_frame_to_string (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2418 GString *p = (GString*)data;
2419 MonoMethod *method = NULL;
2421 if (frame->ji && frame->type != FRAME_TYPE_TRAMPOLINE)
2422 method = jinfo_get_method (frame->ji);
2424 if (method && frame->domain) {
2425 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
2426 g_string_append_printf (p, " %s\n", location);
2429 g_string_append_printf (p, " at <unknown> <0x%05x>\n", frame->native_offset);
2434 #ifndef MONO_CROSS_COMPILE
2436 static void print_process_map (void)
2439 FILE *fp = fopen ("/proc/self/maps", "r");
2443 mono_runtime_printf_err ("no /proc/self/maps, not on linux?\n");
2447 mono_runtime_printf_err ("/proc/self/maps:");
2449 while (fgets (line, sizeof (line), fp)) {
2451 size_t len = strlen (line) - 1;
2452 if (len >= 0 && line [len] == '\n')
2455 mono_runtime_printf_err ("%s", line);
2464 static gboolean handling_sigsegv = FALSE;
2467 * mono_handle_native_crash:
2469 * Handle a native crash (e.g. SIGSEGV) while in native code by
2470 * printing diagnostic information and aborting.
2473 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2475 #ifdef MONO_ARCH_USE_SIGACTION
2476 struct sigaction sa;
2478 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2480 gboolean is_sigsegv = !strcmp ("SIGSEGV", signal);
2482 if (handling_sigsegv && is_sigsegv)
2485 if (mini_get_debug_options ()->suspend_on_sigsegv && is_sigsegv) {
2486 mono_runtime_printf_err ("Received %s, suspending...", signal);
2497 /* To prevent infinite loops when the stack walk causes a crash */
2499 handling_sigsegv = TRUE;
2501 /* !jit_tls means the thread was not registered with the runtime */
2502 if (jit_tls && mono_thread_internal_current ()) {
2503 mono_runtime_printf_err ("Stacktrace:\n");
2505 /* FIXME: Is MONO_UNWIND_LOOKUP_IL_OFFSET correct here? */
2506 mono_walk_stack (print_stack_frame_to_stderr, MONO_UNWIND_LOOKUP_IL_OFFSET, NULL);
2509 print_process_map ();
2511 #ifdef HAVE_BACKTRACE_SYMBOLS
2517 mono_runtime_printf_err ("\nNative stacktrace:\n");
2519 size = backtrace (array, 256);
2520 names = backtrace_symbols (array, size);
2521 for (i =0; i < size; ++i) {
2522 mono_runtime_printf_err ("\t%s", names [i]);
2526 /* Try to get more meaningful information using gdb */
2528 #if !defined(HOST_WIN32) && defined(HAVE_SYS_SYSCALL_H) && defined(SYS_fork)
2529 if (!mini_get_debug_options ()->no_gdb_backtrace) {
2530 /* From g_spawn_command_line_sync () in eglib */
2533 pid_t crashed_pid = getpid ();
2536 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
2537 * it will deadlock. Call the syscall directly instead.
2539 #if defined(PLATFORM_ANDROID)
2540 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
2541 g_assert_not_reached ();
2542 #elif !defined(PLATFORM_MACOSX) && defined(SYS_fork)
2543 pid = (pid_t) syscall (SYS_fork);
2544 #elif defined(PLATFORM_MACOSX) && HAVE_FORK
2545 pid = (pid_t) fork ();
2547 g_assert_not_reached ();
2550 #if defined (HAVE_PRCTL) && defined(PR_SET_PTRACER)
2552 // Allow gdb to attach to the process even if ptrace_scope sysctl variable is set to
2553 // a value other than 0 (the most permissive ptrace scope). Most modern Linux
2554 // distributions set the scope to 1 which allows attaching only to direct children of
2555 // the current process
2556 prctl (PR_SET_PTRACER, pid, 0, 0, 0);
2560 dup2 (STDERR_FILENO, STDOUT_FILENO);
2562 mono_gdb_render_native_backtraces (crashed_pid);
2566 mono_runtime_printf_err ("\nDebug info from gdb:\n");
2567 waitpid (pid, &status, 0);
2572 #ifdef PLATFORM_ANDROID
2573 /* set DUMPABLE for this process so debuggerd can attach with ptrace(2), see:
2574 * https://android.googlesource.com/platform/bionic/+/151da681000c07da3c24cd30a3279b1ca017f452/linker/debugger.cpp#206
2575 * this has changed on later versions of Android. Also, we don't want to
2576 * set this on start-up as DUMPABLE has security implications. */
2577 prctl (PR_SET_DUMPABLE, 1);
2579 mono_runtime_printf_err ("\nNo native Android stacktrace (see debuggerd output).\n");
2584 * A SIGSEGV indicates something went very wrong so we can no longer depend
2585 * on anything working. So try to print out lots of diagnostics, starting
2586 * with ones which have a greater chance of working.
2588 mono_runtime_printf_err (
2590 "=================================================================\n"
2591 "Got a %s while executing native code. This usually indicates\n"
2592 "a fatal error in the mono runtime or one of the native libraries \n"
2593 "used by your application.\n"
2594 "=================================================================\n",
2597 #ifdef MONO_ARCH_USE_SIGACTION
2598 sa.sa_handler = SIG_DFL;
2599 sigemptyset (&sa.sa_mask);
2602 /* Remove our SIGABRT handler */
2603 g_assert (sigaction (SIGABRT, &sa, NULL) != -1);
2605 /* On some systems we get a SIGILL when calling abort (), because it might
2606 * fail to raise SIGABRT */
2607 g_assert (sigaction (SIGILL, &sa, NULL) != -1);
2610 if (!mono_do_crash_chaining) {
2611 /*Android abort is a fluke, it doesn't abort, it triggers another segv. */
2612 #if defined (PLATFORM_ANDROID)
2623 mono_handle_native_crash (const char *signal, void *ctx, MONO_SIG_HANDLER_INFO_TYPE *info)
2625 g_assert_not_reached ();
2628 #endif /* !MONO_CROSS_COMPILE */
2631 mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
2633 MonoInternalThread *thread = mono_thread_internal_current ();
2634 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2639 GError *error = NULL;
2644 text = g_string_new (0);
2646 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
2648 g_string_append_printf (text, "\n\"%s\"", name);
2651 else if (thread->threadpool_thread)
2652 g_string_append (text, "\n\"<threadpool thread>\"");
2654 g_string_append (text, "\n\"<unnamed thread>\"");
2656 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
2657 mono_thread_internal_describe (thread, text);
2658 g_string_append (text, "\n");
2660 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2662 memcpy (&ctx, start_ctx, sizeof (MonoContext));
2664 MONO_INIT_CONTEXT_FROM_FUNC (&ctx, mono_print_thread_dump);
2666 mono_sigctx_to_monoctx (sigctx, &ctx);
2668 mono_walk_stack_with_ctx (print_stack_frame_to_string, &ctx, MONO_UNWIND_LOOKUP_ALL, text);
2670 mono_runtime_printf ("\t<Stack traces in thread dumps not supported on this platform>");
2673 mono_runtime_printf ("%s", text->str);
2675 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
2676 OutputDebugStringA(text->str);
2679 g_string_free (text, TRUE);
2680 mono_runtime_stdout_fflush ();
2684 * mono_print_thread_dump:
2686 * Print information about the current thread to stdout.
2687 * SIGCTX can be NULL, allowing this to be called from gdb.
2690 mono_print_thread_dump (void *sigctx)
2692 mono_print_thread_dump_internal (sigctx, NULL);
2696 mono_print_thread_dump_from_ctx (MonoContext *ctx)
2698 mono_print_thread_dump_internal (NULL, ctx);
2702 * mono_resume_unwind:
2704 * This is called by a trampoline from LLVM compiled finally clauses to continue
2708 mono_resume_unwind (MonoContext *ctx)
2710 MONO_REQ_GC_UNSAFE_MODE;
2712 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2713 MonoContext new_ctx;
2715 MONO_CONTEXT_SET_IP (ctx, MONO_CONTEXT_GET_IP (&jit_tls->resume_state.ctx));
2716 MONO_CONTEXT_SET_SP (ctx, MONO_CONTEXT_GET_SP (&jit_tls->resume_state.ctx));
2719 mono_handle_exception_internal (&new_ctx, (MonoObject *)jit_tls->resume_state.ex_obj, TRUE, NULL);
2721 mono_restore_context (&new_ctx);
2724 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
2729 MonoJitExceptionInfo *ei;
2730 } FindHandlerBlockData;
2733 find_last_handler_block (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
2737 FindHandlerBlockData *pdata = (FindHandlerBlockData *)data;
2738 MonoJitInfo *ji = frame->ji;
2743 ip = MONO_CONTEXT_GET_IP (ctx);
2745 for (i = 0; i < ji->num_clauses; ++i) {
2746 MonoJitExceptionInfo *ei = ji->clauses + i;
2747 if (ei->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2749 /*If ip points to the first instruction it means the handler block didn't start
2750 so we can leave its execution to the EH machinery*/
2751 if (ei->handler_start < ip && ip < ei->data.handler_end) {
2763 install_handler_block_guard (MonoJitInfo *ji, MonoContext *ctx)
2766 MonoJitExceptionInfo *clause = NULL;
2769 ip = MONO_CONTEXT_GET_IP (ctx);
2771 for (i = 0; i < ji->num_clauses; ++i) {
2772 clause = &ji->clauses [i];
2773 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
2775 if (clause->handler_start < ip && clause->data.handler_end > ip)
2779 /*no matching finally */
2780 if (i == ji->num_clauses)
2783 /*If we stopped on the instruction right before the try, we haven't actually started executing it*/
2784 if (ip == clause->handler_start)
2787 return mono_arch_install_handler_block_guard (ji, clause, ctx, mono_create_handler_block_trampoline ());
2791 * Finds the bottom handler block running and install a block guard if needed.
2794 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2796 FindHandlerBlockData data = { 0 };
2797 MonoJitTlsData *jit_tls = (MonoJitTlsData *)ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS];
2800 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
2805 /* Guard against a null MonoJitTlsData. This can happens if the thread receives the
2806 * interrupt signal before the JIT has time to initialize its TLS data for the given thread.
2808 if (!jit_tls || jit_tls->handler_block_return_address)
2811 /* Do an async safe stack walk */
2812 mono_thread_info_set_is_async_context (TRUE);
2813 mono_walk_stack_with_state (find_last_handler_block, ctx, MONO_UNWIND_NONE, &data);
2814 mono_thread_info_set_is_async_context (FALSE);
2819 memcpy (&jit_tls->handler_block_context, &data.ctx, sizeof (MonoContext));
2821 resume_ip = install_handler_block_guard (data.ji, &data.ctx);
2822 if (resume_ip == NULL)
2825 jit_tls->handler_block_return_address = resume_ip;
2826 jit_tls->handler_block = data.ei;
2832 mono_current_thread_has_handle_block_guard (void)
2834 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2835 return jit_tls && jit_tls->handler_block_return_address != NULL;
2840 mono_install_handler_block_guard (MonoThreadUnwindState *ctx)
2846 mono_current_thread_has_handle_block_guard (void)
2854 mono_set_cast_details (MonoClass *from, MonoClass *to)
2856 MonoJitTlsData *jit_tls = NULL;
2858 if (mini_get_debug_options ()->better_cast_details) {
2859 jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2860 jit_tls->class_cast_from = from;
2861 jit_tls->class_cast_to = to;
2866 /*returns false if the thread is not attached*/
2868 mono_thread_state_init_from_sigctx (MonoThreadUnwindState *ctx, void *sigctx)
2870 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2871 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2878 mono_sigctx_to_monoctx (sigctx, &ctx->ctx);
2880 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2881 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2882 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2885 mono_thread_state_init (ctx);
2888 if (!ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] || !ctx->unwind_data [MONO_UNWIND_DATA_LMF])
2894 g_error ("Implement mono_arch_sigctx_to_monoctx for the current target");
2900 mono_thread_state_init (MonoThreadUnwindState *ctx)
2902 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2904 #if defined(MONO_CROSS_COMPILE)
2905 ctx->valid = FALSE; //A cross compiler doesn't need to suspend.
2906 #elif MONO_ARCH_HAS_MONO_CONTEXT
2907 MONO_CONTEXT_GET_CURRENT (ctx->ctx);
2909 g_error ("Use a null sigctx requires a working mono-context");
2912 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2913 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2914 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread ? thread->jit_data : NULL;
2920 mono_thread_state_init_from_monoctx (MonoThreadUnwindState *ctx, MonoContext *mctx)
2922 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2929 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2930 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2931 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2936 /*returns false if the thread is not attached*/
2938 mono_thread_state_init_from_current (MonoThreadUnwindState *ctx)
2940 MonoThreadInfo *thread = mono_thread_info_current_unchecked ();
2941 MONO_ARCH_CONTEXT_DEF
2943 mono_arch_flush_register_windows ();
2945 if (!thread || !thread->jit_data) {
2949 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
2950 MONO_INIT_CONTEXT_FROM_CURRENT (&ctx->ctx);
2952 MONO_INIT_CONTEXT_FROM_FUNC (&ctx->ctx, mono_thread_state_init_from_current);
2955 ctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
2956 ctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
2957 ctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = thread->jit_data;
2963 mono_raise_exception_with_ctx (MonoException *exc, MonoContext *ctx)
2965 mono_handle_exception (ctx, (MonoObject *)exc);
2966 mono_restore_context (ctx);
2969 /*FIXME Move all monoctx -> sigctx conversion to signal handlers once all archs support utils/mono-context */
2971 mono_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
2973 #ifdef MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK
2974 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_tls_get_jit_tls ();
2975 jit_tls->ex_ctx = *ctx;
2977 mono_arch_setup_async_callback (ctx, async_cb, user_data);
2979 g_error ("This target doesn't support mono_arch_setup_async_callback");
2984 * mono_restore_context:
2986 * Call the architecture specific restore context function.
2989 mono_restore_context (MonoContext *ctx)
2991 static void (*restore_context) (MonoContext *);
2993 if (!restore_context)
2994 restore_context = (void (*)(MonoContext *))mono_get_restore_context ();
2995 restore_context (ctx);
2996 g_assert_not_reached ();
3000 * mono_jinfo_get_unwind_info:
3002 * Return the unwind info for JI.
3005 mono_jinfo_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3008 return mono_aot_get_unwind_info (ji, unwind_info_len);
3010 return mono_get_cached_unwind_info (ji->unwind_info, unwind_info_len);
3014 mono_jinfo_get_epilog_size (MonoJitInfo *ji)
3016 MonoArchEHJitInfo *info;
3018 info = mono_jit_info_get_arch_eh_info (ji);
3021 return info->epilog_size;
3025 * LLVM/Bitcode exception handling.
3029 throw_exception (MonoObject *ex, gboolean rethrow)
3031 MONO_REQ_GC_UNSAFE_MODE;
3034 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3035 MonoException *mono_ex;
3037 if (!mono_object_isinst_checked (ex, mono_defaults.exception_class, &error)) {
3038 mono_error_assert_ok (&error);
3039 mono_ex = mono_get_exception_runtime_wrapped_checked (ex, &error);
3040 mono_error_assert_ok (&error);
3041 jit_tls->thrown_non_exc = mono_gchandle_new (ex, FALSE);
3044 mono_ex = (MonoException*)ex;
3047 jit_tls->thrown_exc = mono_gchandle_new ((MonoObject*)mono_ex, FALSE);
3050 #ifdef MONO_ARCH_HAVE_UNWIND_BACKTRACE
3051 GList *l, *ips = NULL;
3054 _Unwind_Backtrace (build_stack_trace, &ips);
3055 /* The list contains ip-gshared info pairs */
3057 ips = g_list_reverse (ips);
3058 for (l = ips; l; l = l->next) {
3059 trace = g_list_append (trace, l->data);
3060 trace = g_list_append (trace, NULL);
3062 MonoArray *ips_arr = mono_glist_to_array (trace, mono_defaults.int_class, &error);
3063 mono_error_assert_ok (&error);
3064 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3066 g_list_free (trace);
3070 mono_llvm_cpp_throw_exception ();
3074 mono_llvm_throw_exception (MonoObject *ex)
3076 throw_exception (ex, FALSE);
3080 mono_llvm_rethrow_exception (MonoObject *ex)
3082 throw_exception (ex, TRUE);
3086 mono_llvm_raise_exception (MonoException *e)
3088 mono_llvm_throw_exception ((MonoObject*)e);
3092 mono_llvm_throw_corlib_exception (guint32 ex_token_index)
3094 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
3097 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
3099 mono_llvm_throw_exception ((MonoObject*)ex);
3103 * mono_llvm_resume_exception:
3105 * Resume exception propagation.
3108 mono_llvm_resume_exception (void)
3110 mono_llvm_cpp_throw_exception ();
3114 * mono_llvm_load_exception:
3116 * Return the currently thrown exception.
3119 mono_llvm_load_exception (void)
3122 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3124 MonoException *mono_ex = (MonoException*)mono_gchandle_get_target (jit_tls->thrown_exc);
3126 if (mono_ex->trace_ips) {
3127 GList *trace_ips = NULL;
3128 gpointer ip = __builtin_return_address (0);
3130 size_t upper = mono_array_length (mono_ex->trace_ips);
3132 for (int i = 0; i < upper; i+= 2) {
3133 gpointer curr_ip = mono_array_get (mono_ex->trace_ips, gpointer, i);
3134 gpointer curr_info = mono_array_get (mono_ex->trace_ips, gpointer, i + 1);
3135 trace_ips = g_list_append (trace_ips, curr_ip);
3136 trace_ips = g_list_append (trace_ips, curr_info);
3142 // FIXME: Does this work correctly for rethrows?
3143 // We may be discarding useful information
3144 // when this gets GC'ed
3145 MonoArray *ips_arr = mono_glist_to_array (trace_ips, mono_defaults.int_class, &error);
3146 mono_error_assert_ok (&error);
3147 MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
3148 g_list_free (trace_ips);
3151 //MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
3153 MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, 0, &error));
3154 mono_error_assert_ok (&error);
3155 MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new_checked (mono_domain_get (), mono_defaults.stack_frame_class, 0, &error));
3156 mono_error_assert_ok (&error);
3159 return &mono_ex->object;
3163 * mono_llvm_clear_exception:
3165 * Mark the currently thrown exception as handled.
3168 mono_llvm_clear_exception (void)
3170 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3171 mono_gchandle_free (jit_tls->thrown_exc);
3172 jit_tls->thrown_exc = 0;
3173 if (jit_tls->thrown_non_exc)
3174 mono_gchandle_free (jit_tls->thrown_non_exc);
3175 jit_tls->thrown_non_exc = 0;
3177 mono_memory_barrier ();
3181 * mono_llvm_match_exception:
3183 * Return the innermost clause containing REGION_START-REGION_END which can handle
3184 * the current exception.
3187 mono_llvm_match_exception (MonoJitInfo *jinfo, guint32 region_start, guint32 region_end, gpointer rgctx, MonoObject *this_obj)
3190 MonoJitTlsData *jit_tls = mono_get_jit_tls ();
3194 g_assert (jit_tls->thrown_exc);
3195 exc = mono_gchandle_get_target (jit_tls->thrown_exc);
3196 if (jit_tls->thrown_non_exc) {
3198 * Have to unwrap RuntimeWrappedExceptions if the
3199 * method's assembly doesn't have a RuntimeCompatibilityAttribute.
3201 if (!wrap_non_exception_throws (jinfo_get_method (jinfo)))
3202 exc = mono_gchandle_get_target (jit_tls->thrown_non_exc);
3205 for (int i = 0; i < jinfo->num_clauses; i++) {
3206 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3207 MonoClass *catch_class;
3209 if (! (ei->try_offset == region_start && ei->try_offset + ei->try_len == region_end) )
3212 catch_class = ei->data.catch_class;
3213 if (mono_class_is_open_constructed_type (&catch_class->byval_arg)) {
3214 MonoGenericContext context;
3215 MonoType *inflated_type;
3217 g_assert (rgctx || this_obj);
3218 context = get_generic_context_from_stack_frame (jinfo, rgctx ? rgctx : this_obj->vtable);
3219 inflated_type = mono_class_inflate_generic_type_checked (&catch_class->byval_arg, &context, &error);
3220 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3222 catch_class = mono_class_from_mono_type (inflated_type);
3223 mono_metadata_free_type (inflated_type);
3226 // FIXME: Handle edge cases handled in get_exception_catch_class
3227 if (ei->flags == MONO_EXCEPTION_CLAUSE_NONE && mono_object_isinst_checked (exc, catch_class, &error)) {
3228 index = ei->clause_index;
3231 mono_error_assert_ok (&error);
3233 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3234 g_assert_not_reached ();
3243 mono_debug_personality (int a, _Unwind_Action b,
3244 uint64_t c, struct _Unwind_Exception *d, struct _Unwind_Context *e)
3246 g_assert_not_reached ();
3250 mono_debug_personality (void);
3253 mono_debug_personality (void)
3255 g_assert_not_reached ();