2004-08-23 Zoltan Varga <vargaz@freemail.hu>
[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_arch_flush_register_windows ();
126
127         MONO_CONTEXT_SET_IP (&ctx, ves_icall_get_frame_info);
128         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (0));
129
130         skip++;
131
132         do {
133                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
134
135                 ctx = new_ctx;
136                 
137                 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
138                         return FALSE;
139
140                 /* skip all wrappers ??*/
141                 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
142                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
143                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
144                         continue;
145
146                 skip--;
147
148         } while (skip >= 0);
149
150         *method = mono_method_get_object (domain, ji->method, NULL);
151         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
152
153         if (need_file_info) {
154                 gchar *filename;
155
156                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
157
158                 *file = filename? mono_string_new (domain, filename): NULL;
159                 *column = 0;
160
161                 g_free (filename);
162         }
163
164         return TRUE;
165 }
166
167 static MonoArray *
168 glist_to_array (GList *list) 
169 {
170         MonoDomain *domain = mono_domain_get ();
171         MonoArray *res;
172         int len, i;
173
174         if (!list)
175                 return NULL;
176
177         len = g_list_length (list);
178         res = mono_array_new (domain, mono_defaults.int_class, len);
179
180         for (i = 0; list; list = list->next, i++)
181                 mono_array_set (res, gpointer, i, list->data);
182
183         return res;
184 }
185
186 /**
187  * mono_handle_exception:
188  * @ctx: saved processor state
189  * @obj: the exception object
190  * @test_only: only test if the exception is caught, but dont call handlers
191  *
192  */
193 gboolean
194 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
195 {
196         MonoDomain *domain = mono_domain_get ();
197         MonoJitInfo *ji, rji;
198         static int (*call_filter) (MonoContext *, gpointer) = NULL;
199         static void (*restore_context) (void *);
200         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
201         MonoLMF *lmf = jit_tls->lmf;            
202         GList *trace_ips = NULL;
203         MonoException *mono_ex;
204         gboolean stack_overflow = FALSE;
205         MonoContext initial_ctx;
206         int frame_count = 0;
207         gboolean gc_disabled = FALSE;
208         MonoString *initial_stack_trace = NULL;
209         GString *trace_str = NULL;
210         
211         /*
212          * This function might execute on an alternate signal stack, and Boehm GC
213          * can't handle that.
214          * Also, since the altstack is small, stack space intensive operations like
215          * JIT compilation should be avoided.
216          */
217         if (IS_ON_SIGALTSTACK (jit_tls)) {
218                 /* 
219                  * FIXME: disabling/enabling GC while already on a signal stack might
220                  * not be safe either.
221                  */
222                 /* Have to reenable it later */
223                 gc_disabled = TRUE;
224                 mono_gc_disable ();
225         }
226
227         g_assert (ctx != NULL);
228         if (!obj) {
229                 MonoException *ex = mono_get_exception_null_reference ();
230                 ex->message = mono_string_new (domain, "Object reference not set to an instance of an object");
231                 obj = (MonoObject *)ex;
232         } 
233
234         /*
235          * Allocate a new exception object instead of the preconstructed ones.
236          * We can't do this in sigsegv_signal_handler, since GC is not yet
237          * disabled.
238          */
239         if (obj == domain->stack_overflow_ex) {
240                 obj = mono_get_exception_stack_overflow ();
241         }
242         else if (obj == domain->null_reference_ex) {
243                 obj = mono_get_exception_null_reference ();
244         }
245
246         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
247                 mono_ex = (MonoException*)obj;
248                 initial_stack_trace = mono_ex->stack_trace;
249         } else {
250                 mono_ex = NULL;
251         }
252
253         if (obj == domain->stack_overflow_ex)
254                 stack_overflow = TRUE;
255
256         if (!call_filter)
257                 call_filter = mono_arch_get_call_filter ();
258
259         if (!restore_context)
260                 restore_context = mono_arch_get_restore_context ();
261
262         g_assert (jit_tls->end_of_stack);
263         g_assert (jit_tls->abort_func);
264
265         if (!test_only) {
266                 MonoContext ctx_cp = *ctx;
267                 if (mono_jit_trace_calls != NULL)
268                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
269                 if (!mono_handle_exception (&ctx_cp, obj, original_ip, TRUE)) {
270                         if (mono_break_on_exc)
271                                 G_BREAKPOINT ();
272                         mono_unhandled_exception (obj);
273
274                         if (mono_debugger_unhandled_exception (original_ip, obj)) {
275                                 /*
276                                  * If this returns true, then we're running inside the
277                                  * Mono Debugger and the debugger wants us to restore the
278                                  * context and continue (normally, the debugger inserts
279                                  * a breakpoint on the `original_ip', so it regains control
280                                  * immediately after restoring the context).
281                                  */
282                                 MONO_CONTEXT_SET_IP (ctx, original_ip);
283                                 restore_context (ctx);
284                                 g_assert_not_reached ();
285                         }
286                 }
287         }
288
289         initial_ctx = *ctx;
290         memset (&rji, 0, sizeof (rji));
291
292         while (1) {
293                 MonoContext new_ctx;
294                 char *trace = NULL;
295                 gboolean need_trace = FALSE;
296                 guint32 free_stack;
297
298                 if (test_only && (frame_count < 1000)) {
299                         need_trace = TRUE;
300                         if (!trace_str)
301                                 trace_str = g_string_new ("");
302                 }
303
304                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx, 
305                                               need_trace ? &trace : NULL, &lmf, NULL, NULL);
306                 if (!ji) {
307                         g_warning ("Exception inside function without unwind info");
308                         g_assert_not_reached ();
309                 }
310
311                 if (ji != (gpointer)-1) {
312                         frame_count ++;
313                         //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
314
315                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
316                                 /* 
317                                  * Avoid overwriting the stack trace if the exception is
318                                  * rethrown. Also avoid giant stack traces during a stack
319                                  * overflow.
320                                  */
321                                 if (!initial_stack_trace && (frame_count < 1000)) {
322                                         trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
323
324                                         g_string_append (trace_str, trace);
325                                         g_string_append_c (trace_str, '\n');
326                                 }
327                         }
328
329                         if (stack_overflow)
330                                 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
331                         else
332                                 free_stack = 0xffffff;
333
334                         /* 
335                          * During stack overflow, wait till the unwinding frees some stack
336                          * space before running handlers/finalizers.
337                          */
338                         if ((free_stack > (64 * 1024)) && ji->num_clauses) {
339                                 int i;
340                                 
341                                 g_assert (ji->clauses);
342                         
343                                 for (i = 0; i < ji->num_clauses; i++) {
344                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
345                                         gboolean filtered = FALSE;
346
347                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
348                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
349                                                 /* catch block */
350
351                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
352                                                         /* store the exception object int cfg->excvar */
353                                                         g_assert (ji->exvar_offset);
354                                                         *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ji->exvar_offset)) = obj;
355                                                         if (!initial_stack_trace && trace_str) {
356                                                                 mono_ex->stack_trace = mono_string_new (domain, trace_str->str);
357                                                         }
358                                                 }
359
360                                                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
361                                                         filtered = call_filter (ctx, ei->data.filter);
362
363                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
364                                                      mono_object_isinst (obj, mono_class_get (ji->method->klass->image, ei->data.token))) || filtered) {
365                                                         if (test_only) {
366                                                                 if (mono_ex) {
367                                                                         trace_ips = g_list_reverse (trace_ips);
368                                                                         mono_ex->trace_ips = glist_to_array (trace_ips);
369                                                                 }
370                                                                 g_list_free (trace_ips);
371                                                                 g_free (trace);
372
373                                                                 if (gc_disabled)
374                                                                         mono_gc_enable ();
375                                                                 if (trace_str)
376                                                                         g_string_free (trace_str, TRUE);
377                                                                 return TRUE;
378                                                         }
379                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
380                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
381                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
382                                                         jit_tls->lmf = lmf;
383                                                         g_free (trace);
384
385                                                         if (gc_disabled)
386                                                                 mono_gc_enable ();
387                                                         if (trace_str)
388                                                                 g_string_free (trace_str, TRUE);
389                                                         return 0;
390                                                 }
391                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
392                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
393                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
394                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
395                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
396                                                         call_filter (ctx, ei->handler_start);
397                                                 }
398                                                 
399                                         }
400                                 }
401                         }
402                 }
403
404                 g_free (trace);
405                         
406                 *ctx = new_ctx;
407
408                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
409                         if (gc_disabled)
410                                 mono_gc_enable ();
411
412                         if (!test_only) {
413                                 jit_tls->lmf = lmf;
414
415                                 if (IS_ON_SIGALTSTACK (jit_tls)) {
416                                         /* Switch back to normal stack */
417                                         if (stack_overflow)
418                                                 /* Free up some stack space */
419                                                 MONO_CONTEXT_SET_SP (&initial_ctx, (guint32)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
420                                         MONO_CONTEXT_SET_IP (&initial_ctx, (unsigned int)jit_tls->abort_func);
421                                         restore_context (&initial_ctx);
422                                 }
423                                 else
424                                         jit_tls->abort_func (obj);
425                                 g_assert_not_reached ();
426                         } else {
427                                 if (mono_ex) {
428                                         trace_ips = g_list_reverse (trace_ips);
429                                         mono_ex->trace_ips = glist_to_array (trace_ips);
430                                 }
431                                 g_list_free (trace_ips);
432                                 if (trace_str)
433                                         g_string_free (trace_str, TRUE);
434                                 return FALSE;
435                         }
436                 }
437         }
438
439         g_assert_not_reached ();
440 }