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