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