2004-04-29 Gonzalo Paniagua Javier <gonzalo@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 #include <mono/metadata/appdomain.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/debug-helpers.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/gc-internal.h>
21 #include <mono/metadata/mono-debug.h>
22
23 #include "mini.h"
24
25 #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)))
26
27 MonoArray *
28 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
29 {
30         MonoDomain *domain = mono_domain_get ();
31         MonoArray *res;
32         MonoArray *ta = exc->trace_ips;
33         int i, len;
34
35         if (ta == NULL) {
36                 /* Exception is not thrown yet */
37                 return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
38         }
39         
40         len = mono_array_length (ta);
41
42         res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
43
44         for (i = skip; i < len; i++) {
45                 MonoJitInfo *ji;
46                 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
47                 gpointer ip = mono_array_get (ta, gpointer, i);
48
49                 ji = mono_jit_info_table_find (domain, ip);
50                 if (ji == NULL) {
51                         /* Unmanaged frame */
52                         mono_array_set (res, gpointer, i, sf);
53                         continue;
54                 }
55
56                 g_assert (ji != NULL);
57
58                 sf->method = mono_method_get_object (domain, ji->method, NULL);
59                 sf->native_offset = (char *)ip - (char *)ji->code_start;
60
61                 sf->il_offset = mono_debug_il_offset_from_address (ji->method, sf->native_offset, domain);
62
63                 if (need_file_info) {
64                         gchar *filename;
65                         
66                         filename = mono_debug_source_location_from_address (ji->method, sf->native_offset, &sf->line, domain);
67
68                         sf->filename = filename? mono_string_new (domain, filename): NULL;
69                         sf->column = 0;
70
71                         g_free (filename);
72                 }
73
74                 mono_array_set (res, gpointer, i, sf);
75         }
76
77         return res;
78 }
79
80 void
81 mono_jit_walk_stack (MonoStackWalk func, gpointer user_data) {
82         MonoDomain *domain = mono_domain_get ();
83         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
84         MonoLMF *lmf = jit_tls->lmf;
85         MonoJitInfo *ji, rji;
86         gint native_offset, il_offset;
87         gboolean managed;
88
89         MonoContext ctx, new_ctx;
90
91         mono_arch_flush_register_windows ();
92
93         MONO_CONTEXT_SET_IP (&ctx, __builtin_return_address (0));
94         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (1));
95
96         while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
97                 
98                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
99                 g_assert (ji);
100
101                 if (ji == (gpointer)-1)
102                         return;
103
104                 il_offset = mono_debug_il_offset_from_address (ji->method, native_offset, domain);
105
106                 if (func (ji->method, native_offset, il_offset, managed, user_data))
107                         return;
108                 
109                 ctx = new_ctx;
110         }
111 }
112
113 MonoBoolean
114 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info, 
115                           MonoReflectionMethod **method, 
116                           gint32 *iloffset, gint32 *native_offset,
117                           MonoString **file, gint32 *line, gint32 *column)
118 {
119         MonoDomain *domain = mono_domain_get ();
120         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
121         MonoLMF *lmf = jit_tls->lmf;
122         MonoJitInfo *ji, rji;
123         MonoContext ctx, new_ctx;
124
125         MONO_CONTEXT_SET_IP (&ctx, ves_icall_get_frame_info);
126         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (0));
127
128         skip++;
129
130         do {
131                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
132
133                 ctx = new_ctx;
134                 
135                 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
136                         return FALSE;
137
138                 /* skip all wrappers ??*/
139                 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
140                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
141                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
142                         continue;
143
144                 skip--;
145
146         } while (skip >= 0);
147
148         *method = mono_method_get_object (domain, ji->method, NULL);
149         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
150
151         if (need_file_info) {
152                 gchar *filename;
153
154                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
155
156                 *file = filename? mono_string_new (domain, filename): NULL;
157                 *column = 0;
158
159                 g_free (filename);
160         }
161
162         return TRUE;
163 }
164
165 static MonoArray *
166 glist_to_array (GList *list) 
167 {
168         MonoDomain *domain = mono_domain_get ();
169         MonoArray *res;
170         int len, i;
171
172         if (!list)
173                 return NULL;
174
175         len = g_list_length (list);
176         res = mono_array_new (domain, mono_defaults.int_class, len);
177
178         for (i = 0; list; list = list->next, i++)
179                 mono_array_set (res, gpointer, i, list->data);
180
181         return res;
182 }
183
184 /**
185  * mono_handle_exception:
186  * @ctx: saved processor state
187  * @obj: the exception object
188  * @test_only: only test if the exception is caught, but dont call handlers
189  *
190  */
191 gboolean
192 mono_handle_exception (MonoContext *ctx, gpointer obj, gboolean test_only)
193 {
194         MonoDomain *domain = mono_domain_get ();
195         MonoJitInfo *ji, rji;
196         static int (*call_filter) (MonoContext *, gpointer) = NULL;
197         static void (*restore_context) (struct sigcontext *);
198         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
199         MonoLMF *lmf = jit_tls->lmf;            
200         GList *trace_ips = NULL;
201         MonoException *mono_ex;
202         gboolean stack_overflow = FALSE;
203         MonoContext initial_ctx;
204         int frame_count = 0;
205         gboolean gc_disabled = FALSE;
206         MonoString *initial_stack_trace;
207         
208         /*
209          * This function might execute on an alternate signal stack, and Boehm GC
210          * can't handle that.
211          * Also, since the altstack is small, stack space intensive operations like
212          * JIT compilation should be avoided.
213          */
214         if (IS_ON_SIGALTSTACK (jit_tls)) {
215                 /* 
216                  * FIXME: disabling/enabling GC while already on a signal stack might
217                  * not be safe either.
218                  */
219                 /* Have to reenable it later */
220                 gc_disabled = TRUE;
221                 mono_gc_disable ();
222         }
223
224         g_assert (ctx != NULL);
225         if (!obj) {
226                 MonoException *ex = mono_get_exception_null_reference ();
227                 ex->message = mono_string_new (domain, "Object reference not set to an instance of an object");
228                 obj = (MonoObject *)ex;
229         } 
230
231         /*
232          * Allocate a new exception object instead of the preconstructed ones.
233          * We can't do this in sigsegv_signal_handler, since GC is not yet
234          * disabled.
235          */
236         if (obj == domain->stack_overflow_ex) {
237                 obj = mono_get_exception_stack_overflow ();
238         }
239         else if (obj == domain->null_reference_ex) {
240                 obj = mono_get_exception_null_reference ();
241         }
242
243         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
244                 mono_ex = (MonoException*)obj;
245                 initial_stack_trace = mono_ex->stack_trace;
246         } else {
247                 mono_ex = NULL;
248         }
249
250         if (obj == domain->stack_overflow_ex)
251                 stack_overflow = TRUE;
252
253         if (!call_filter)
254                 call_filter = mono_arch_get_call_filter ();
255
256         if (!restore_context)
257                 restore_context = mono_arch_get_restore_context ();
258
259         g_assert (jit_tls->end_of_stack);
260         g_assert (jit_tls->abort_func);
261
262         if (!test_only) {
263                 MonoContext ctx_cp = *ctx;
264                 if (mono_jit_trace_calls != NULL)
265                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
266                 if (!mono_handle_exception (&ctx_cp, obj, TRUE)) {
267                         if (mono_break_on_exc)
268                                 G_BREAKPOINT ();
269                         mono_unhandled_exception (obj);
270                 }
271         }
272
273         initial_ctx = *ctx;
274         memset (&rji, 0, sizeof (rji));
275
276         while (1) {
277                 MonoContext new_ctx;
278                 char *trace = NULL;
279                 gboolean need_trace = FALSE;
280                 guint32 free_stack;
281
282                 if (test_only && (frame_count < 1000))
283                         need_trace = TRUE;
284
285                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx, 
286                                               need_trace ? &trace : NULL, &lmf, NULL, NULL);
287                 if (!ji) {
288                         g_warning ("Exception inside function without unwind info");
289                         g_assert_not_reached ();
290                 }
291
292                 if (ji != (gpointer)-1) {
293                         frame_count ++;
294                         //printf ("M: %s %p %p %d.\n", mono_method_full_name (ji->method, TRUE), jit_tls->end_of_stack, ctx->ebp, count);
295
296                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
297                                 char *tmp, *strace;
298
299                                 /* 
300                                  * Avoid overwriting the stack trace if the exception is
301                                  * rethrown. Also avoid giant stack traces during a stack
302                                  * overflow.
303                                  */
304                                 if (!initial_stack_trace && (frame_count < 1000)) {
305                                         trace_ips = g_list_append (trace_ips, MONO_CONTEXT_GET_IP (ctx));
306
307                                         if (!mono_ex->stack_trace)
308                                                 strace = g_strdup ("");
309                                         else
310                                                 strace = mono_string_to_utf8 (mono_ex->stack_trace);
311
312                                         tmp = g_strdup_printf ("%s%s\n", strace, trace);
313                                         g_free (strace);
314
315                                         mono_ex->stack_trace = mono_string_new (domain, tmp);
316
317                                         g_free (tmp);
318                                 }
319                         }
320
321                         if (stack_overflow)
322                                 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
323                         else
324                                 free_stack = 0xffffff;
325
326                         /* 
327                          * During stack overflow, wait till the unwinding frees some stack
328                          * space before running handlers/finalizers.
329                          */
330                         if ((free_stack > (64 * 1024)) && ji->num_clauses) {
331                                 int i;
332                                 
333                                 g_assert (ji->clauses);
334                         
335                                 for (i = 0; i < ji->num_clauses; i++) {
336                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
337
338                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
339                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
340                                                 /* catch block */
341
342                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
343                                                         /* store the exception object int cfg->excvar */
344                                                         g_assert (ji->exvar_offset);
345                                                         *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ji->exvar_offset)) = obj;
346                                                 }
347
348                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
349                                                      mono_object_isinst (obj, mono_class_get (ji->method->klass->image, ei->data.token))) ||
350                                                     ((ei->flags == MONO_EXCEPTION_CLAUSE_FILTER &&
351                                                       call_filter (ctx, ei->data.filter)))) {
352                                                         if (test_only) {
353                                                                 if (mono_ex)
354                                                                         mono_ex->trace_ips = glist_to_array (trace_ips);
355                                                                 g_list_free (trace_ips);
356                                                                 g_free (trace);
357
358                                                                 if (gc_disabled)
359                                                                         mono_gc_enable ();
360                                                                 return TRUE;
361                                                         }
362                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
363                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
364                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
365                                                         jit_tls->lmf = lmf;
366                                                         g_free (trace);
367
368                                                         if (gc_disabled)
369                                                                 mono_gc_enable ();
370                                                         return 0;
371                                                 }
372                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
373                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
374                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
375                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
376                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
377                                                         call_filter (ctx, ei->handler_start);
378                                                 }
379                                                 
380                                         }
381                                 }
382                         }
383                 }
384
385                 g_free (trace);
386                         
387                 *ctx = new_ctx;
388
389                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
390                         if (gc_disabled)
391                                 mono_gc_enable ();
392
393                         if (!test_only) {
394                                 jit_tls->lmf = lmf;
395
396                                 if (IS_ON_SIGALTSTACK (jit_tls)) {
397                                         /* Switch back to normal stack */
398                                         if (stack_overflow)
399                                                 /* Free up some stack space */
400                                                 MONO_CONTEXT_SET_SP (&initial_ctx, (guint32)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
401                                         MONO_CONTEXT_SET_IP (&initial_ctx, (unsigned int)jit_tls->abort_func);
402                                         restore_context (&initial_ctx);
403                                 }
404                                 else
405                                         jit_tls->abort_func (obj);
406                                 g_assert_not_reached ();
407                         } else {
408                                 if (mono_ex)
409                                         mono_ex->trace_ips = glist_to_array (trace_ips);
410                                 g_list_free (trace_ips);
411                                 return FALSE;
412                         }
413                 }
414         }
415
416         g_assert_not_reached ();
417 }