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