2004-10-20 Martin Baulig <martin@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 /* mono_find_jit_info:
28  *
29  * This function is used to gather information from @ctx. It return the 
30  * MonoJitInfo of the corresponding function, unwinds one stack frame and
31  * stores the resulting context into @new_ctx. It also stores a string 
32  * describing the stack location into @trace (if not NULL), and modifies
33  * the @lmf if necessary. @native_offset return the IP offset from the 
34  * start of the function or -1 if that info is not available.
35  */
36 static MonoJitInfo *
37 mono_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx, 
38                          MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
39                          gboolean *managed)
40 {
41         gboolean managed2;
42         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
43         MonoJitInfo *ji;
44
45         if (trace)
46                 *trace = NULL;
47
48         if (native_offset)
49                 *native_offset = -1;
50
51         if (managed)
52                 *managed = FALSE;
53
54         ji = mono_arch_find_jit_info (domain, jit_tls, res, prev_ji, ctx, new_ctx, NULL, lmf, NULL, &managed2);
55
56         if (ji == (gpointer)-1)
57                 return ji;
58
59         if (managed2 || ji->method->wrapper_type) {
60                 char *source_location, *tmpaddr, *fname;
61                 gint32 address, iloffset;
62
63                 address = (char *)ip - (char *)ji->code_start;
64
65                 if (native_offset)
66                         *native_offset = address;
67
68                 if (managed)
69                         if (!ji->method->wrapper_type)
70                                 *managed = TRUE;
71
72                 if (trace) {
73                         source_location = mono_debug_source_location_from_address (ji->method, address, NULL, domain);
74                         iloffset = mono_debug_il_offset_from_address (ji->method, address, domain);
75
76                         if (iloffset < 0)
77                                 tmpaddr = g_strdup_printf ("<0x%05x>", address);
78                         else
79                                 tmpaddr = g_strdup_printf ("[0x%05x]", iloffset);
80                 
81                         fname = mono_method_full_name (ji->method, TRUE);
82
83                         if (source_location)
84                                 *trace = g_strdup_printf ("in %s (at %s) %s", tmpaddr, source_location, fname);
85                         else
86                                 *trace = g_strdup_printf ("in %s %s", tmpaddr, fname);
87
88                         g_free (fname);
89                         g_free (source_location);
90                         g_free (tmpaddr);
91                 }
92         }
93         else {
94                 if (trace) {
95                         char *fname = mono_method_full_name (res->method, TRUE);
96                         *trace = g_strdup_printf ("in (unmanaged) %s", fname);
97                         g_free (fname);
98                 }
99         }
100
101         return ji;
102 }
103
104 MonoArray *
105 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
106 {
107         MonoDomain *domain = mono_domain_get ();
108         MonoArray *res;
109         MonoArray *ta = exc->trace_ips;
110         int i, len;
111
112         if (ta == NULL) {
113                 /* Exception is not thrown yet */
114                 return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
115         }
116         
117         len = mono_array_length (ta);
118
119         res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
120
121         for (i = skip; i < len; i++) {
122                 MonoJitInfo *ji;
123                 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
124                 gpointer ip = mono_array_get (ta, gpointer, i);
125
126                 ji = mono_jit_info_table_find (domain, ip);
127                 if (ji == NULL) {
128                         /* Unmanaged frame */
129                         mono_array_set (res, gpointer, i, sf);
130                         continue;
131                 }
132
133                 g_assert (ji != NULL);
134
135                 sf->method = mono_method_get_object (domain, ji->method, NULL);
136                 sf->native_offset = (char *)ip - (char *)ji->code_start;
137
138                 sf->il_offset = mono_debug_il_offset_from_address (ji->method, sf->native_offset, domain);
139
140                 if (need_file_info) {
141                         gchar *filename;
142                         
143                         filename = mono_debug_source_location_from_address (ji->method, sf->native_offset, &sf->line, domain);
144
145                         sf->filename = filename? mono_string_new (domain, filename): NULL;
146                         sf->column = 0;
147
148                         g_free (filename);
149                 }
150
151                 mono_array_set (res, gpointer, i, sf);
152         }
153
154         return res;
155 }
156
157 void
158 mono_jit_walk_stack (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
159         MonoDomain *domain = mono_domain_get ();
160         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
161         MonoLMF *lmf = jit_tls->lmf;
162         MonoJitInfo *ji, rji;
163         gint native_offset, il_offset;
164         gboolean managed;
165
166         MonoContext ctx, new_ctx;
167
168         mono_arch_flush_register_windows ();
169
170         MONO_CONTEXT_SET_IP (&ctx, __builtin_return_address (0));
171         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (1));
172
173         while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
174                 
175                 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
176                 g_assert (ji);
177
178                 if (ji == (gpointer)-1)
179                         return;
180
181                 il_offset = do_il_offset ? mono_debug_il_offset_from_address (ji->method, native_offset, domain): -1;
182
183                 if (func (ji->method, native_offset, il_offset, managed, user_data))
184                         return;
185                 
186                 ctx = new_ctx;
187         }
188 }
189
190 MonoBoolean
191 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info, 
192                           MonoReflectionMethod **method, 
193                           gint32 *iloffset, gint32 *native_offset,
194                           MonoString **file, gint32 *line, gint32 *column)
195 {
196         MonoDomain *domain = mono_domain_get ();
197         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
198         MonoLMF *lmf = jit_tls->lmf;
199         MonoJitInfo *ji, rji;
200         MonoContext ctx, new_ctx;
201
202         mono_arch_flush_register_windows ();
203
204         MONO_CONTEXT_SET_IP (&ctx, ves_icall_get_frame_info);
205         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (0));
206
207         skip++;
208
209         do {
210                 ji = mono_find_jit_info (domain, jit_tls, &rji, NULL, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
211
212                 ctx = new_ctx;
213                 
214                 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
215                         return FALSE;
216
217                 /* skip all wrappers ??*/
218                 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
219                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
220                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
221                         continue;
222
223                 skip--;
224
225         } while (skip >= 0);
226
227         *method = mono_method_get_object (domain, ji->method, NULL);
228         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
229
230         if (need_file_info) {
231                 gchar *filename;
232
233                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
234
235                 *file = filename? mono_string_new (domain, filename): NULL;
236                 *column = 0;
237
238                 g_free (filename);
239         }
240
241         return TRUE;
242 }
243
244 static MonoArray *
245 glist_to_array (GList *list) 
246 {
247         MonoDomain *domain = mono_domain_get ();
248         MonoArray *res;
249         int len, i;
250
251         if (!list)
252                 return NULL;
253
254         len = g_list_length (list);
255         res = mono_array_new (domain, mono_defaults.int_class, len);
256
257         for (i = 0; list; list = list->next, i++)
258                 mono_array_set (res, gpointer, i, list->data);
259
260         return res;
261 }
262
263 /**
264  * mono_handle_exception:
265  * @ctx: saved processor state
266  * @obj: the exception object
267  * @test_only: only test if the exception is caught, but dont call handlers
268  *
269  */
270 gboolean
271 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
272 {
273         MonoDomain *domain = mono_domain_get ();
274         MonoJitInfo *ji, rji;
275         static int (*call_filter) (MonoContext *, gpointer) = NULL;
276         static void (*restore_context) (void *);
277         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
278         MonoLMF *lmf = jit_tls->lmf;            
279         GList *trace_ips = NULL;
280         MonoException *mono_ex;
281         gboolean stack_overflow = FALSE;
282         MonoContext initial_ctx;
283         int frame_count = 0;
284         gboolean gc_disabled = FALSE;
285         MonoString *initial_stack_trace = NULL;
286         GString *trace_str = NULL;
287         
288         /*
289          * This function might execute on an alternate signal stack, and Boehm GC
290          * can't handle that.
291          * Also, since the altstack is small, stack space intensive operations like
292          * JIT compilation should be avoided.
293          */
294         if (IS_ON_SIGALTSTACK (jit_tls)) {
295                 /* 
296                  * FIXME: disabling/enabling GC while already on a signal stack might
297                  * not be safe either.
298                  */
299                 /* Have to reenable it later */
300                 gc_disabled = TRUE;
301                 mono_gc_disable ();
302         }
303
304         g_assert (ctx != NULL);
305         if (!obj) {
306                 MonoException *ex = mono_get_exception_null_reference ();
307                 ex->message = mono_string_new (domain, "Object reference not set to an instance of an object");
308                 obj = (MonoObject *)ex;
309         } 
310
311         /*
312          * Allocate a new exception object instead of the preconstructed ones.
313          * We can't do this in sigsegv_signal_handler, since GC is not yet
314          * disabled.
315          */
316         if (obj == domain->stack_overflow_ex) {
317                 obj = mono_get_exception_stack_overflow ();
318         }
319         else if (obj == domain->null_reference_ex) {
320                 obj = mono_get_exception_null_reference ();
321         }
322
323         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
324                 mono_ex = (MonoException*)obj;
325                 initial_stack_trace = mono_ex->stack_trace;
326         } else {
327                 mono_ex = NULL;
328         }
329
330         if (obj == domain->stack_overflow_ex)
331                 stack_overflow = TRUE;
332
333         if (!call_filter)
334                 call_filter = mono_arch_get_call_filter ();
335
336         if (!restore_context)
337                 restore_context = mono_arch_get_restore_context ();
338
339         g_assert (jit_tls->end_of_stack);
340         g_assert (jit_tls->abort_func);
341
342         if (!test_only) {
343                 MonoContext ctx_cp = *ctx;
344                 if (mono_jit_trace_calls != NULL)
345                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
346                 if (!mono_handle_exception (&ctx_cp, obj, original_ip, TRUE)) {
347                         if (mono_break_on_exc)
348                                 G_BREAKPOINT ();
349                         mono_unhandled_exception (obj);
350
351                         if (mono_debugger_unhandled_exception (original_ip, MONO_CONTEXT_GET_SP (ctx), obj)) {
352                                 /*
353                                  * If this returns true, then we're running inside the
354                                  * Mono Debugger and the debugger wants us to restore the
355                                  * context and continue (normally, the debugger inserts
356                                  * a breakpoint on the `original_ip', so it regains control
357                                  * immediately after restoring the context).
358                                  */
359                                 MONO_CONTEXT_SET_IP (ctx, original_ip);
360                                 restore_context (ctx);
361                                 g_assert_not_reached ();
362                         }
363                 }
364         }
365
366         initial_ctx = *ctx;
367         memset (&rji, 0, sizeof (rji));
368
369         while (1) {
370                 MonoContext new_ctx;
371                 char *trace = NULL;
372                 gboolean need_trace = FALSE;
373                 guint32 free_stack;
374
375                 if (test_only && (frame_count < 1000)) {
376                         need_trace = TRUE;
377                         if (!trace_str)
378                                 trace_str = g_string_new ("");
379                 }
380
381                 ji = mono_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx, 
382                                                                  need_trace ? &trace : NULL, &lmf, NULL, NULL);
383                 if (!ji) {
384                         g_warning ("Exception inside function without unwind info");
385                         g_assert_not_reached ();
386                 }
387
388                 if (ji != (gpointer)-1) {
389                         frame_count ++;
390                         //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
391
392                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
393                                 /* 
394                                  * Avoid overwriting the stack trace if the exception is
395                                  * rethrown. Also avoid giant stack traces during a stack
396                                  * overflow.
397                                  */
398                                 if (!initial_stack_trace && (frame_count < 1000)) {
399                                         trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
400
401                                         g_string_append (trace_str, trace);
402                                         g_string_append_c (trace_str, '\n');
403                                 }
404                         }
405
406                         if (stack_overflow)
407                                 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
408                         else
409                                 free_stack = 0xffffff;
410
411                         /* 
412                          * During stack overflow, wait till the unwinding frees some stack
413                          * space before running handlers/finalizers.
414                          */
415                         if ((free_stack > (64 * 1024)) && ji->num_clauses) {
416                                 int i;
417                                 
418                                 g_assert (ji->clauses);
419                         
420                                 for (i = 0; i < ji->num_clauses; i++) {
421                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
422                                         gboolean filtered = FALSE;
423
424                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
425                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
426                                                 /* catch block */
427
428                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
429                                                         /* store the exception object int cfg->excvar */
430                                                         g_assert (ji->exvar_offset);
431                                                         *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ji->exvar_offset)) = obj;
432                                                         if (!initial_stack_trace && trace_str) {
433                                                                 mono_ex->stack_trace = mono_string_new (domain, trace_str->str);
434                                                         }
435                                                 }
436
437                                                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
438                                                         mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
439                                                         filtered = call_filter (ctx, ei->data.filter);
440                                         }
441
442                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
443                                                      mono_object_isinst (obj, mono_class_get (ji->method->klass->image, ei->data.token))) || filtered) {
444                                                         if (test_only) {
445                                                                 if (mono_ex) {
446                                                                         trace_ips = g_list_reverse (trace_ips);
447                                                                         mono_ex->trace_ips = glist_to_array (trace_ips);
448                                                                 }
449                                                                 g_list_free (trace_ips);
450                                                                 g_free (trace);
451
452                                                                 if (gc_disabled)
453                                                                         mono_gc_enable ();
454                                                                 if (trace_str)
455                                                                         g_string_free (trace_str, TRUE);
456                                                                 return TRUE;
457                                                         }
458                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
459                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
460                                                         mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
461                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
462                                                         jit_tls->lmf = lmf;
463                                                         g_free (trace);
464
465                                                         if (gc_disabled)
466                                                                 mono_gc_enable ();
467                                                         if (trace_str)
468                                                                 g_string_free (trace_str, TRUE);
469                                                         return 0;
470                                                 }
471                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
472                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
473                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
474                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
475                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
476                                                         mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
477                                                         call_filter (ctx, ei->handler_start);
478                                                 }
479                                                 
480                                         }
481                                 }
482                         }
483                 }
484
485                 g_free (trace);
486                         
487                 *ctx = new_ctx;
488
489                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
490                         if (gc_disabled)
491                                 mono_gc_enable ();
492
493                         if (!test_only) {
494                                 jit_tls->lmf = lmf;
495
496                                 if (IS_ON_SIGALTSTACK (jit_tls)) {
497                                         /* Switch back to normal stack */
498                                         if (stack_overflow)
499                                                 /* Free up some stack space */
500                                                 MONO_CONTEXT_SET_SP (&initial_ctx, (guint32)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
501                                         MONO_CONTEXT_SET_IP (&initial_ctx, (unsigned int)jit_tls->abort_func);
502                                         restore_context (&initial_ctx);
503                                 }
504                                 else
505                                         jit_tls->abort_func (obj);
506                                 g_assert_not_reached ();
507                         } else {
508                                 if (mono_ex) {
509                                         trace_ips = g_list_reverse (trace_ips);
510                                         mono_ex->trace_ips = glist_to_array (trace_ips);
511                                 }
512                                 g_list_free (trace_ips);
513                                 if (trace_str)
514                                         g_string_free (trace_str, TRUE);
515                                 return FALSE;
516                         }
517                 }
518         }
519
520         g_assert_not_reached ();
521 }