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