f0eb6e6025c22704f8f1c39d15ec3dbb3ead936a
[mono.git] / mono / mini / mini-exceptions.c
1 /*
2  * mini-exceptions.c: generic exception support
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <signal.h>
13 #include <string.h>
14
15 #ifdef HAVE_EXECINFO_H
16 #include <execinfo.h>
17 #endif
18
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/debug-helpers.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/gc-internal.h>
25 #include <mono/metadata/mono-debug.h>
26 #include <mono/metadata/mono-debug-debugger.h>
27
28 #include "mini.h"
29
30 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
31 #include <unistd.h>
32 #include <sys/mman.h>
33 #endif
34
35 #define IS_ON_SIGALTSTACK(jit_tls) ((jit_tls) && ((guint8*)&(jit_tls) > (guint8*)(jit_tls)->signal_stack) && ((guint8*)&(jit_tls) < ((guint8*)(jit_tls)->signal_stack + (jit_tls)->signal_stack_size)))
36
37 #ifndef MONO_ARCH_CONTEXT_DEF
38 #define MONO_ARCH_CONTEXT_DEF
39 #endif
40
41 #ifndef MONO_INIT_CONTEXT_FROM_CALLER
42 #define MONO_INIT_CONTEXT_FROM_CALLER(ctx) do { \
43         MONO_CONTEXT_SET_IP ((ctx), __builtin_return_address (0)); \
44         MONO_CONTEXT_SET_BP ((ctx), __builtin_frame_address (1)); \
45 } while (0)
46 #endif
47
48 #ifndef mono_find_jit_info
49
50 /* mono_find_jit_info:
51  *
52  * This function is used to gather information from @ctx. It return the 
53  * MonoJitInfo of the corresponding function, unwinds one stack frame and
54  * stores the resulting context into @new_ctx. It also stores a string 
55  * describing the stack location into @trace (if not NULL), and modifies
56  * the @lmf if necessary. @native_offset return the IP offset from the 
57  * start of the function or -1 if that info is not available.
58  */
59 static MonoJitInfo *
60 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx, 
61                          MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
62                          gboolean *managed)
63 {
64         gboolean managed2;
65         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
66         MonoJitInfo *ji;
67
68         if (trace)
69                 *trace = NULL;
70
71         if (native_offset)
72                 *native_offset = -1;
73
74         if (managed)
75                 *managed = FALSE;
76
77         ji = mono_arch_find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, NULL, lmf, NULL, &managed2);
78
79         if (ji == (gpointer)-1)
80                 return ji;
81
82         if (managed2 || ji->method->wrapper_type) {
83                 char *source_location, *tmpaddr, *fname;
84                 gint32 offset, iloffset;
85
86                 if (!managed2)
87                         /* ctx->ip points into native code */
88                         offset = (char*)MONO_CONTEXT_GET_IP (new_ctx) - (char*)ji->code_start;
89                 else
90                         offset = (char *)ip - (char *)ji->code_start;
91
92                 if (native_offset)
93                         *native_offset = offset;
94
95                 if (managed)
96                         if (!ji->method->wrapper_type)
97                                 *managed = TRUE;
98
99                 if (trace) {
100                         source_location = mono_debug_source_location_from_address (ji->method, offset, NULL, domain);
101                         iloffset = mono_debug_il_offset_from_address (ji->method, offset, domain);
102
103                         if (iloffset < 0)
104                                 tmpaddr = g_strdup_printf ("<0x%05x>", offset);
105                         else
106                                 tmpaddr = g_strdup_printf ("[0x%05x]", iloffset);
107                 
108                         fname = mono_method_full_name (ji->method, TRUE);
109
110                         if (source_location)
111                                 *trace = g_strdup_printf ("in %s (at %s) %s", tmpaddr, source_location, fname);
112                         else
113                                 *trace = g_strdup_printf ("in %s %s", tmpaddr, fname);
114
115                         g_free (fname);
116                         g_free (source_location);
117                         g_free (tmpaddr);
118                 }
119         }
120         else {
121                 if (trace) {
122                         char *fname = mono_method_full_name (res->method, TRUE);
123                         *trace = g_strdup_printf ("in (unmanaged) %s", fname);
124                         g_free (fname);
125                 }
126         }
127
128         return ji;
129 }
130
131 #endif /* mono_find_jit_info */
132
133 MonoString *
134 ves_icall_System_Exception_get_trace (MonoException *ex)
135 {
136         MonoDomain *domain = mono_domain_get ();
137         MonoString *res;
138         MonoArray *ta = ex->trace_ips;
139         int i, len;
140         GString *trace_str;
141         char tmpaddr [256];
142
143         if (ta == NULL)
144                 /* Exception is not thrown yet */
145                 return NULL;
146
147         len = mono_array_length (ta);
148         trace_str = g_string_new ("");
149         for (i = 0; i < len; i++) {
150                 MonoJitInfo *ji;
151                 gpointer ip = mono_array_get (ta, gpointer, i);
152
153                 ji = mono_jit_info_table_find (domain, ip);
154                 if (ji == NULL) {
155                         /* Unmanaged frame */
156                         g_string_append_printf (trace_str, "in (unmanaged) %p\n", ip);
157                 } else {
158                         char *source_location, *fname;
159                         gint32 address, iloffset;
160
161                         address = (char *)ip - (char *)ji->code_start;
162
163                         source_location = mono_debug_source_location_from_address (ji->method, address, NULL, ex->object.vtable->domain);
164                         iloffset = mono_debug_il_offset_from_address (ji->method, address, ex->object.vtable->domain);
165
166                         if (iloffset < 0)
167                                 sprintf (tmpaddr, "<0x%05x>", address);
168                         else
169                                 sprintf (tmpaddr, "[0x%05x]", iloffset);
170                 
171                         fname = mono_method_full_name (ji->method, TRUE);
172
173                         if (source_location)
174                                 g_string_append_printf (trace_str, "in %s (at %s) %s\n", tmpaddr, source_location, fname);
175                         else
176                                 g_string_append_printf (trace_str, "in %s %s\n", tmpaddr, fname);
177
178                         g_free (fname);
179                         g_free (source_location);
180                 }
181         }
182
183         res = mono_string_new (ex->object.vtable->domain, trace_str->str);
184         g_string_free (trace_str, TRUE);
185
186         return res;
187 }
188
189 MonoArray *
190 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
191 {
192         MonoDomain *domain = mono_domain_get ();
193         MonoArray *res;
194         MonoArray *ta = exc->trace_ips;
195         int i, len;
196
197         if (ta == NULL) {
198                 /* Exception is not thrown yet */
199                 return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
200         }
201         
202         len = mono_array_length (ta);
203
204         res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
205
206         for (i = skip; i < len; i++) {
207                 MonoJitInfo *ji;
208                 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
209                 gpointer ip = mono_array_get (ta, gpointer, i);
210
211                 ji = mono_jit_info_table_find (domain, ip);
212                 if (ji == NULL) {
213                         /* Unmanaged frame */
214                         mono_array_set (res, gpointer, i, sf);
215                         continue;
216                 }
217
218                 g_assert (ji != NULL);
219
220                 if (ji->method->wrapper_type) {
221                         char *s;
222
223                         sf->method = NULL;
224                         s = mono_method_full_name (ji->method, TRUE);
225                         sf->internal_method_name = mono_string_new (domain, s);
226                         g_free (s);
227                 }
228                 else
229                         sf->method = mono_method_get_object (domain, ji->method, NULL);
230                 sf->native_offset = (char *)ip - (char *)ji->code_start;
231
232                 sf->il_offset = mono_debug_il_offset_from_address (ji->method, sf->native_offset, domain);
233
234                 if (need_file_info) {
235                         gchar *filename;
236                         
237                         filename = mono_debug_source_location_from_address (ji->method, sf->native_offset, &sf->line, domain);
238
239                         sf->filename = filename? mono_string_new (domain, filename): NULL;
240                         sf->column = 0;
241
242                         g_free (filename);
243                 }
244
245                 mono_array_set (res, gpointer, i, sf);
246         }
247
248         return res;
249 }
250
251 /**
252  * mono_walk_stack:
253  * @domain: starting appdomain
254  * @jit_tls: JIT data for the thread
255  * @start_ctx: starting state of the stack frame
256  * @func: callback to call for each stack frame
257  * @user_data: data passed to the callback
258  *
259  * This function walks the stack of a thread, starting from the state
260  * represented by jit_tls and start_ctx. For each frame the callback
261  * function is called with the relevant info. The walk ends when no more
262  * managed stack frames are found or when the callback returns a TRUE value.
263  * Note that the function can be used to walk the stack of a thread 
264  * different from the current.
265  */
266 void
267 mono_walk_stack (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start_ctx, MonoStackFrameWalk func, gpointer user_data)
268 {
269         MonoLMF *lmf = jit_tls->lmf;
270         MonoJitInfo *ji, rji;
271         gint native_offset;
272         gboolean managed;
273         MonoContext ctx, new_ctx;
274
275         ctx = *start_ctx;
276
277         while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
278                 /* 
279                  * FIXME: mono_find_jit_info () will need to be able to return a different
280                  * MonoDomain when apddomain transitions are found on the stack.
281                  */
282                 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
283                 if (!ji || ji == (gpointer)-1)
284                         return;
285
286                 if (func (domain, &new_ctx, ji, user_data))
287                         return;
288
289                 ctx = new_ctx;
290         }
291 }
292
293 #ifndef CUSTOM_STACK_WALK
294
295 void
296 mono_jit_walk_stack (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
297         MonoDomain *domain = mono_domain_get ();
298         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
299         MonoLMF *lmf = jit_tls->lmf;
300         MonoJitInfo *ji, rji;
301         gint native_offset, il_offset;
302         gboolean managed;
303         MonoContext ctx, new_ctx;
304
305         MONO_ARCH_CONTEXT_DEF
306
307         mono_arch_flush_register_windows ();
308
309 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
310         MONO_INIT_CONTEXT_FROM_CURRENT (&ctx);
311 #else
312     MONO_INIT_CONTEXT_FROM_CALLER (&ctx);
313 #endif
314
315         while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
316                 
317                 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
318                 g_assert (ji);
319
320                 if (ji == (gpointer)-1)
321                         return;
322
323                 il_offset = do_il_offset ? mono_debug_il_offset_from_address (ji->method, native_offset, domain): -1;
324
325                 if (func (ji->method, native_offset, il_offset, managed, user_data))
326                         return;
327                 
328                 ctx = new_ctx;
329         }
330 }
331
332 MonoBoolean
333 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info, 
334                           MonoReflectionMethod **method, 
335                           gint32 *iloffset, gint32 *native_offset,
336                           MonoString **file, gint32 *line, gint32 *column)
337 {
338         MonoDomain *domain = mono_domain_get ();
339         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
340         MonoLMF *lmf = jit_tls->lmf;
341         MonoJitInfo *ji, rji;
342         MonoContext ctx, new_ctx;
343
344         MONO_ARCH_CONTEXT_DEF;
345
346         mono_arch_flush_register_windows ();
347
348         MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_get_frame_info);
349
350         skip++;
351
352         do {
353                 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
354
355                 ctx = new_ctx;
356                 
357                 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
358                         return FALSE;
359
360                 /* skip all wrappers ??*/
361                 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
362                     ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
363                     ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
364                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
365                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
366                         continue;
367
368                 skip--;
369
370         } while (skip >= 0);
371
372         *method = mono_method_get_object (domain, ji->method, NULL);
373         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
374
375         if (need_file_info) {
376                 gchar *filename;
377
378                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
379
380                 *file = filename? mono_string_new (domain, filename): NULL;
381                 *column = 0;
382
383                 g_free (filename);
384         }
385
386         return TRUE;
387 }
388
389 #endif /* CUSTOM_STACK_WALK */
390
391 typedef struct {
392         guint32 skips;
393         MonoSecurityFrame *frame;
394 } MonoFrameSecurityInfo;
395
396 static gboolean
397 callback_get_first_frame_security_info (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
398 {
399         MonoFrameSecurityInfo *si = (MonoFrameSecurityInfo*) data;
400
401         /* FIXME: skip all wrappers ?? probably not - case by case testing is required */
402         if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
403             ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
404             ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
405             ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
406             ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE) {
407                 return FALSE;
408         }
409
410         if (si->skips > 0) {
411                 si->skips--;
412                 return FALSE;
413         }
414
415         si->frame = mono_declsec_create_frame (domain, ji);
416
417         /* Stop - we only want the first frame (e.g. LinkDemand and InheritanceDemand) */
418         return TRUE;
419 }
420
421 /**
422  * ves_icall_System_Security_SecurityFrame_GetSecurityFrame:
423  * @skip: the number of stack frames to skip
424  *
425  * This function returns a the security informations of a single stack frame 
426  * (after the skipped ones). This is required for [NonCas]LinkDemand[Choice]
427  * and [NonCas]InheritanceDemand[Choice] as only the caller security is 
428  * evaluated.
429  */
430 MonoSecurityFrame*
431 ves_icall_System_Security_SecurityFrame_GetSecurityFrame (gint32 skip)
432 {
433         MonoDomain *domain = mono_domain_get ();
434         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
435         MonoFrameSecurityInfo si;
436         MonoContext ctx;
437
438         MONO_ARCH_CONTEXT_DEF
439
440         MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
441
442         si.skips = skip;
443         si.frame = NULL;
444         mono_walk_stack (domain, jit_tls, &ctx, callback_get_first_frame_security_info, (gpointer)&si);
445
446         return (si.skips == 0) ? si.frame : NULL;
447 }
448
449
450 typedef struct {
451         guint32 skips;
452         MonoArray *stack;
453         guint32 count;
454         guint32 maximum;
455 } MonoSecurityStack;
456
457 static void
458 grow_array (MonoSecurityStack *stack)
459 {
460         MonoDomain *domain = mono_domain_get ();
461         guint32 newsize = (stack->maximum << 1);
462         MonoArray *newstack = mono_array_new (domain, mono_defaults.runtimesecurityframe_class, newsize);
463         int i;
464         for (i=0; i < stack->maximum; i++) {
465                 gpointer frame = mono_array_get (stack->stack, gpointer, i);
466                 mono_array_set (newstack, gpointer, i, frame);
467         }
468         stack->maximum = newsize;
469         stack->stack = newstack;
470 }
471
472 static gboolean
473 callback_get_stack_frames_security_info (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
474 {
475         MonoSecurityStack *ss = (MonoSecurityStack*) data;
476
477         /* FIXME: skip all wrappers ?? probably not - case by case testing is required */
478         if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
479             ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
480             ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
481             ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
482             ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE) {
483                 return FALSE;
484         }
485
486         if (ss->skips > 0) {
487                 ss->skips--;
488                 return FALSE;
489         }
490
491         if (ss->count == ss->maximum)
492                 grow_array (ss);
493         
494         mono_array_set (ss->stack, gpointer, ss->count++, mono_declsec_create_frame (domain, ji));
495
496         /* continue down the stack */
497         return FALSE;
498 }
499
500 static MonoArray *
501 glist_to_array (GList *list, MonoClass *eclass) 
502 {
503         MonoDomain *domain = mono_domain_get ();
504         MonoArray *res;
505         int len, i;
506
507         if (!list)
508                 return NULL;
509
510         len = g_list_length (list);
511         res = mono_array_new (domain, eclass, len);
512
513         for (i = 0; list; list = list->next, i++)
514                 mono_array_set (res, gpointer, i, list->data);
515
516         return res;
517 }
518
519 /**
520  * ves_icall_System_Security_SecurityFrame_GetSecurityStack:
521  * @skip: the number of stack frames to skip
522  *
523  * This function returns an managed array of containing the security
524  * informations for each frame (after the skipped ones). This is used for
525  * [NonCas]Demand[Choice] where the complete evaluation of the stack is 
526  * required.
527  */
528 MonoArray*
529 ves_icall_System_Security_SecurityFrame_GetSecurityStack (gint32 skip)
530 {
531         MonoDomain *domain = mono_domain_get ();
532         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
533         MonoSecurityStack ss;
534         MonoContext ctx;
535
536         MONO_ARCH_CONTEXT_DEF
537
538         MONO_INIT_CONTEXT_FROM_FUNC (&ctx, ves_icall_System_Security_SecurityFrame_GetSecurityStack);
539
540         ss.skips = skip;
541         ss.count = 0;
542         ss.maximum = MONO_CAS_INITIAL_STACK_SIZE;
543         ss.stack = mono_array_new (domain, mono_defaults.runtimesecurityframe_class, ss.maximum);
544         mono_walk_stack (domain, jit_tls, &ctx, callback_get_stack_frames_security_info, (gpointer)&ss);
545         /* g_warning ("STACK RESULT: %d out of %d", ss.count, ss.maximum); */
546         return ss.stack;
547 }
548
549 #ifndef CUSTOM_EXCEPTION_HANDLING
550
551 /**
552  * mono_handle_exception_internal:
553  * @ctx: saved processor state
554  * @obj: the exception object
555  * @test_only: only test if the exception is caught, but dont call handlers
556  * @out_filter_idx: out parameter. if test_only is true, set to the index of 
557  * the first filter clause which caught the exception.
558  */
559 static gboolean
560 mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only, gint32 *out_filter_idx)
561 {
562         MonoDomain *domain = mono_domain_get ();
563         MonoJitInfo *ji, rji;
564         static int (*call_filter) (MonoContext *, gpointer) = NULL;
565         static void (*restore_context) (void *);
566         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
567         MonoLMF *lmf = jit_tls->lmf;            
568         MonoArray *initial_trace_ips = NULL;
569         GList *trace_ips = NULL;
570         MonoException *mono_ex;
571         gboolean stack_overflow = FALSE;
572         MonoContext initial_ctx;
573         int frame_count = 0;
574         gboolean gc_disabled = FALSE;
575         gboolean has_dynamic_methods = FALSE;
576         gint32 filter_idx, first_filter_idx;
577         
578         /*
579          * This function might execute on an alternate signal stack, and Boehm GC
580          * can't handle that.
581          * Also, since the altstack is small, stack space intensive operations like
582          * JIT compilation should be avoided.
583          */
584         if (IS_ON_SIGALTSTACK (jit_tls)) {
585                 /* 
586                  * FIXME: disabling/enabling GC while already on a signal stack might
587                  * not be safe either.
588                  */
589                 /* Have to reenable it later */
590                 gc_disabled = TRUE;
591                 mono_gc_disable ();
592         }
593
594         g_assert (ctx != NULL);
595         if (!obj) {
596                 MonoException *ex = mono_get_exception_null_reference ();
597                 ex->message = mono_string_new (domain, "Object reference not set to an instance of an object");
598                 obj = (MonoObject *)ex;
599         } 
600
601         /*
602          * Allocate a new exception object instead of the preconstructed ones.
603          * We can't do this in sigsegv_signal_handler, since GC is not yet
604          * disabled.
605          */
606         if (obj == domain->stack_overflow_ex) {
607                 obj = mono_get_exception_stack_overflow ();
608                 stack_overflow = TRUE;
609         }
610         else if (obj == domain->null_reference_ex) {
611                 obj = mono_get_exception_null_reference ();
612         }
613
614         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
615                 mono_ex = (MonoException*)obj;
616                 initial_trace_ips = mono_ex->trace_ips;
617         } else {
618                 mono_ex = NULL;
619         }
620
621         if (!call_filter)
622                 call_filter = mono_arch_get_call_filter ();
623
624         if (!restore_context)
625                 restore_context = mono_arch_get_restore_context ();
626
627         g_assert (jit_tls->end_of_stack);
628         g_assert (jit_tls->abort_func);
629
630         if (!test_only) {
631                 MonoContext ctx_cp = *ctx;
632                 if (mono_jit_trace_calls != NULL)
633                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
634                 if (!mono_handle_exception_internal (&ctx_cp, obj, original_ip, TRUE, &first_filter_idx)) {
635                         if (mono_break_on_exc)
636                                 G_BREAKPOINT ();
637                         mono_unhandled_exception (obj);
638
639                         if (mono_debugger_unhandled_exception (original_ip, MONO_CONTEXT_GET_SP (ctx), obj)) {
640                                 /*
641                                  * If this returns true, then we're running inside the
642                                  * Mono Debugger and the debugger wants us to restore the
643                                  * context and continue (normally, the debugger inserts
644                                  * a breakpoint on the `original_ip', so it regains control
645                                  * immediately after restoring the context).
646                                  */
647                                 MONO_CONTEXT_SET_IP (ctx, original_ip);
648                                 restore_context (ctx);
649                                 g_assert_not_reached ();
650                         }
651                 }
652         }
653
654         if (out_filter_idx)
655                 *out_filter_idx = -1;
656         filter_idx = 0;
657         initial_ctx = *ctx;
658         memset (&rji, 0, sizeof (rji));
659
660         while (1) {
661                 MonoContext new_ctx;
662                 guint32 free_stack;
663
664                 ji = mono_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx, 
665                                                                  NULL, &lmf, NULL, NULL);
666                 if (!ji) {
667                         g_warning ("Exception inside function without unwind info");
668                         g_assert_not_reached ();
669                 }
670
671                 if (ji != (gpointer)-1) {
672                         frame_count ++;
673                         //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
674
675                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
676                                 /* 
677                                  * Avoid overwriting the stack trace if the exception is
678                                  * rethrown. Also avoid giant stack traces during a stack
679                                  * overflow.
680                                  */
681                                 if (!initial_trace_ips && (frame_count < 1000)) {
682                                         trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
683                                 }
684                         }
685
686                         if (ji->method->dynamic)
687                                 has_dynamic_methods = TRUE;
688
689                         if (stack_overflow)
690                                 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
691                         else
692                                 free_stack = 0xffffff;
693
694                         /* 
695                          * During stack overflow, wait till the unwinding frees some stack
696                          * space before running handlers/finalizers.
697                          */
698                         if ((free_stack > (64 * 1024)) && ji->num_clauses) {
699                                 int i;
700                                 
701                                 for (i = 0; i < ji->num_clauses; i++) {
702                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
703                                         gboolean filtered = FALSE;
704
705 #ifdef __s390__
706                                         if (ei->try_start < MONO_CONTEXT_GET_IP (ctx) && 
707 #else
708                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
709 #endif
710                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
711                                                 /* catch block */
712
713                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
714                                                         /* store the exception object in cfg->excvar */
715                                                         g_assert (ei->exvar_offset);
716                                                         *((gpointer *)(gpointer)((char *)MONO_CONTEXT_GET_BP (ctx) + ei->exvar_offset)) = obj;
717                                                 }
718
719                                                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
720                                                         // mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
721                                                         if (test_only) {
722                                                                 filtered = call_filter (ctx, ei->data.filter);
723                                                                 if (filtered && out_filter_idx)
724                                                                         *out_filter_idx = filter_idx;
725                                                         }
726                                                         else {
727                                                                 /* 
728                                                                  * Filter clauses should only be run in the 
729                                                                  * first pass of exception handling.
730                                                                  */
731                                                                 filtered = (filter_idx == first_filter_idx);
732                                                         }
733                                                         filter_idx ++;
734                                                 }
735
736                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
737                                                      mono_object_isinst (obj, ei->data.catch_class)) || filtered) {
738                                                         if (test_only) {
739                                                                 if (mono_ex && !initial_trace_ips) {
740                                                                         trace_ips = g_list_reverse (trace_ips);
741                                                                         mono_ex->trace_ips = glist_to_array (trace_ips, mono_defaults.int_class);
742                                                                         if (has_dynamic_methods)
743                                                                                 /* These methods could go away anytime, so compute the stack trace now */
744                                                                                 mono_ex->stack_trace = ves_icall_System_Exception_get_trace (mono_ex);
745                                                                 }
746                                                                 g_list_free (trace_ips);
747
748                                                                 if (gc_disabled)
749                                                                         mono_gc_enable ();
750                                                                 return TRUE;
751                                                         }
752                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
753                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
754                                                         mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
755                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
756                                                         jit_tls->lmf = lmf;
757
758                                                         if (gc_disabled)
759                                                                 mono_gc_enable ();
760                                                         return 0;
761                                                 }
762                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
763                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
764                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
765                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
766                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
767                                                         mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
768                                                         call_filter (ctx, ei->handler_start);
769                                                 }
770                                                 
771                                         }
772                                 }
773                         }
774                 }
775
776                 *ctx = new_ctx;
777
778                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
779                         if (gc_disabled)
780                                 mono_gc_enable ();
781
782                         if (!test_only) {
783                                 jit_tls->lmf = lmf;
784
785                                 if (IS_ON_SIGALTSTACK (jit_tls)) {
786                                         /* Switch back to normal stack */
787                                         if (stack_overflow) {
788                                                 /* Free up some stack space */
789                                                 MONO_CONTEXT_SET_SP (&initial_ctx, (gssize)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
790                                                 g_assert ((gssize)MONO_CONTEXT_GET_SP (&initial_ctx) < (gssize)jit_tls->end_of_stack);
791                                         }
792                                         MONO_CONTEXT_SET_IP (&initial_ctx, (gssize)jit_tls->abort_func);
793                                         restore_context (&initial_ctx);
794                                 }
795                                 else
796                                         jit_tls->abort_func (obj);
797                                 g_assert_not_reached ();
798                         } else {
799                                 if (mono_ex && !initial_trace_ips) {
800                                         trace_ips = g_list_reverse (trace_ips);
801                                         mono_ex->trace_ips = glist_to_array (trace_ips, mono_defaults.int_class);
802                                         if (has_dynamic_methods)
803                                                 /* These methods could go away anytime, so compute the stack trace now */
804                                                 mono_ex->stack_trace = ves_icall_System_Exception_get_trace (mono_ex);
805                                 }
806                                 g_list_free (trace_ips);
807                                 return FALSE;
808                         }
809                 }
810         }
811
812         g_assert_not_reached ();
813 }
814
815 /**
816  * mono_debugger_run_finally:
817  * @start_ctx: saved processor state
818  *
819  * This method is called by the Mono Debugger to call all `finally' clauses of the
820  * current stack frame.  It's used when the user issues a `return' command to make
821  * the current stack frame return.  After returning from this method, the debugger
822  * unwinds the stack one frame and gives control back to the user.
823  *
824  * NOTE: This method is only used when running inside the Mono Debugger.
825  */
826 void
827 mono_debugger_run_finally (MonoContext *start_ctx)
828 {
829         static int (*call_filter) (MonoContext *, gpointer) = NULL;
830         MonoDomain *domain = mono_domain_get ();
831         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
832         MonoLMF *lmf = jit_tls->lmf;
833         MonoContext ctx, new_ctx;
834         MonoJitInfo *ji, rji;
835         int i;
836
837         ctx = *start_ctx;
838
839         ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, NULL, NULL);
840         if (!ji || ji == (gpointer)-1)
841                 return;
842
843         if (!call_filter)
844                 call_filter = mono_arch_get_call_filter ();
845
846         for (i = 0; i < ji->num_clauses; i++) {
847                 MonoJitExceptionInfo *ei = &ji->clauses [i];
848
849                 if ((ei->try_start <= MONO_CONTEXT_GET_IP (&ctx)) && 
850                     (MONO_CONTEXT_GET_IP (&ctx) < ei->try_end) &&
851                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
852                         call_filter (&ctx, ei->handler_start);
853                 }
854         }
855 }
856
857 /**
858  * mono_handle_exception:
859  * @ctx: saved processor state
860  * @obj: the exception object
861  * @test_only: only test if the exception is caught, but dont call handlers
862  */
863 gboolean
864 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
865 {
866         return mono_handle_exception_internal (ctx, obj, original_ip, test_only, NULL);
867 }
868
869 #endif /* CUSTOM_EXCEPTION_HANDLING */
870
871 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
872
873 void
874 mono_setup_altstack (MonoJitTlsData *tls)
875 {
876         pthread_t self = pthread_self();
877         pthread_attr_t attr;
878         size_t stsize = 0;
879         struct sigaltstack sa;
880         guint8 *staddr = NULL;
881         guint8 *current = (guint8*)&staddr;
882
883         if (mono_running_on_valgrind ())
884                 return;
885
886         /* Determine stack boundaries */
887         pthread_attr_init( &attr );
888 #ifdef HAVE_PTHREAD_GETATTR_NP
889         pthread_getattr_np( self, &attr );
890 #else
891 #ifdef HAVE_PTHREAD_ATTR_GET_NP
892         pthread_attr_get_np( self, &attr );
893 #elif defined(sun)
894         pthread_attr_getstacksize( &attr, &stsize );
895 #else
896 #error "Not implemented"
897 #endif
898 #endif
899 #ifndef sun
900         pthread_attr_getstack( &attr, (void**)&staddr, &stsize );
901 #endif
902
903         g_assert (staddr);
904
905         g_assert ((current > staddr) && (current < staddr + stsize));
906
907         tls->end_of_stack = staddr + stsize;
908
909         /*
910          * threads created by nptl does not seem to have a guard page, and
911          * since the main thread is not created by us, we can't even set one.
912          * Increasing stsize fools the SIGSEGV signal handler into thinking this
913          * is a stack overflow exception.
914          */
915         tls->stack_size = stsize + getpagesize ();
916
917         /* Setup an alternate signal stack */
918         tls->signal_stack = mmap (0, MONO_ARCH_SIGNAL_STACK_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
919         tls->signal_stack_size = MONO_ARCH_SIGNAL_STACK_SIZE;
920
921         g_assert (tls->signal_stack);
922
923         sa.ss_sp = tls->signal_stack;
924         sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
925         sa.ss_flags = SS_ONSTACK;
926         sigaltstack (&sa, NULL);
927 }
928
929 void
930 mono_free_altstack (MonoJitTlsData *tls)
931 {
932         struct sigaltstack sa;
933         int err;
934
935         sa.ss_sp = tls->signal_stack;
936         sa.ss_size = MONO_ARCH_SIGNAL_STACK_SIZE;
937         sa.ss_flags = SS_DISABLE;
938         err = sigaltstack  (&sa, NULL);
939         g_assert (err == 0);
940
941         if (tls->signal_stack)
942                 munmap (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
943 }
944
945 #endif /* MONO_ARCH_SIGSEGV_ON_ALTSTACK */
946
947 static gboolean
948 print_stack_frame (MonoMethod *method, gint32 native_offset, gint32 il_offset, gboolean managed, gpointer data)
949 {
950         if (method) {
951                 if (il_offset != -1)
952                         printf ("in [0x%lx] %s\n", (long)il_offset, mono_method_full_name (method, TRUE));
953                 else
954                         printf ("in <0x%lx> %s\n", (long)native_offset, mono_method_full_name (method, TRUE));
955         } else
956                 printf ("in <%lx> <unknown>\n", (long)native_offset);
957
958         return FALSE;
959 }
960
961 /*
962  * mono_handle_native_sigsegv:
963  *
964  *   Handle a SIGSEGV received while in native code by printing diagnostic 
965  * information and aborting.
966  */
967 void
968 mono_handle_native_sigsegv (void *ctx)
969 {
970         /*
971          * A SIGSEGV indicates something went very wrong so we can no longer depend
972          * on anything working. So try to print out lots of diagnostics, starting 
973          * with ones which have a greater change of working.
974          */
975         fprintf (stderr,
976                          "\n"
977                          "=================================================================\n"
978                          "Got a SIGSEGV while executing native code. This usually indicates\n"
979                          "a fatal error in the mono runtime or one of the native libraries \n"
980                          "used by your application.\n"
981                          "=================================================================\n"
982                          "\n");
983
984         fprintf (stderr, "Stacktrace:\n\n");
985
986         mono_jit_walk_stack (print_stack_frame, TRUE, NULL);
987
988 #ifdef HAVE_BACKTRACE_SYMBOLS
989  {
990         void *array [256];
991         char **names;
992         int i, size;
993
994         fprintf (stderr, "\nNative stacktrace:\n\n");
995
996         size = backtrace (array, 256);
997         names = backtrace_symbols (array, size);
998         for (i =0; i < size; ++i) {
999                 g_print ("\t%s\n", names [i]);
1000         }
1001         free (names);
1002  }
1003 #endif
1004
1005         abort ();
1006 }