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