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