Minor correction.
[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_XDOMAIN_INVOKE ||
220                     ji->method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH ||
221                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
222                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
223                         continue;
224
225                 skip--;
226
227         } while (skip >= 0);
228
229         *method = mono_method_get_object (domain, ji->method, NULL);
230         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
231
232         if (need_file_info) {
233                 gchar *filename;
234
235                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
236
237                 *file = filename? mono_string_new (domain, filename): NULL;
238                 *column = 0;
239
240                 g_free (filename);
241         }
242
243         return TRUE;
244 }
245
246 static MonoArray *
247 glist_to_array (GList *list) 
248 {
249         MonoDomain *domain = mono_domain_get ();
250         MonoArray *res;
251         int len, i;
252
253         if (!list)
254                 return NULL;
255
256         len = g_list_length (list);
257         res = mono_array_new (domain, mono_defaults.int_class, len);
258
259         for (i = 0; list; list = list->next, i++)
260                 mono_array_set (res, gpointer, i, list->data);
261
262         return res;
263 }
264
265 /**
266  * mono_handle_exception:
267  * @ctx: saved processor state
268  * @obj: the exception object
269  * @test_only: only test if the exception is caught, but dont call handlers
270  *
271  */
272 gboolean
273 mono_handle_exception (MonoContext *ctx, gpointer obj, gpointer original_ip, gboolean test_only)
274 {
275         MonoDomain *domain = mono_domain_get ();
276         MonoJitInfo *ji, rji;
277         static int (*call_filter) (MonoContext *, gpointer) = NULL;
278         static void (*restore_context) (void *);
279         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
280         MonoLMF *lmf = jit_tls->lmf;            
281         GList *trace_ips = NULL;
282         MonoException *mono_ex;
283         gboolean stack_overflow = FALSE;
284         MonoContext initial_ctx;
285         int frame_count = 0;
286         gboolean gc_disabled = FALSE;
287         MonoString *initial_stack_trace = NULL;
288         GString *trace_str = NULL;
289         
290         /*
291          * This function might execute on an alternate signal stack, and Boehm GC
292          * can't handle that.
293          * Also, since the altstack is small, stack space intensive operations like
294          * JIT compilation should be avoided.
295          */
296         if (IS_ON_SIGALTSTACK (jit_tls)) {
297                 /* 
298                  * FIXME: disabling/enabling GC while already on a signal stack might
299                  * not be safe either.
300                  */
301                 /* Have to reenable it later */
302                 gc_disabled = TRUE;
303                 mono_gc_disable ();
304         }
305
306         g_assert (ctx != NULL);
307         if (!obj) {
308                 MonoException *ex = mono_get_exception_null_reference ();
309                 ex->message = mono_string_new (domain, "Object reference not set to an instance of an object");
310                 obj = (MonoObject *)ex;
311         } 
312
313         /*
314          * Allocate a new exception object instead of the preconstructed ones.
315          * We can't do this in sigsegv_signal_handler, since GC is not yet
316          * disabled.
317          */
318         if (obj == domain->stack_overflow_ex) {
319                 obj = mono_get_exception_stack_overflow ();
320         }
321         else if (obj == domain->null_reference_ex) {
322                 obj = mono_get_exception_null_reference ();
323         }
324
325         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
326                 mono_ex = (MonoException*)obj;
327                 initial_stack_trace = mono_ex->stack_trace;
328         } else {
329                 mono_ex = NULL;
330         }
331
332         if (obj == domain->stack_overflow_ex)
333                 stack_overflow = TRUE;
334
335         if (!call_filter)
336                 call_filter = mono_arch_get_call_filter ();
337
338         if (!restore_context)
339                 restore_context = mono_arch_get_restore_context ();
340
341         g_assert (jit_tls->end_of_stack);
342         g_assert (jit_tls->abort_func);
343
344         if (!test_only) {
345                 MonoContext ctx_cp = *ctx;
346                 if (mono_jit_trace_calls != NULL)
347                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
348                 if (!mono_handle_exception (&ctx_cp, obj, original_ip, TRUE)) {
349                         if (mono_break_on_exc)
350                                 G_BREAKPOINT ();
351                         mono_unhandled_exception (obj);
352
353                         if (mono_debugger_unhandled_exception (original_ip, MONO_CONTEXT_GET_SP (ctx), obj)) {
354                                 /*
355                                  * If this returns true, then we're running inside the
356                                  * Mono Debugger and the debugger wants us to restore the
357                                  * context and continue (normally, the debugger inserts
358                                  * a breakpoint on the `original_ip', so it regains control
359                                  * immediately after restoring the context).
360                                  */
361                                 MONO_CONTEXT_SET_IP (ctx, original_ip);
362                                 restore_context (ctx);
363                                 g_assert_not_reached ();
364                         }
365                 }
366         }
367
368         initial_ctx = *ctx;
369         memset (&rji, 0, sizeof (rji));
370
371         while (1) {
372                 MonoContext new_ctx;
373                 char *trace = NULL;
374                 gboolean need_trace = FALSE;
375                 guint32 free_stack;
376
377                 if (test_only && (frame_count < 1000)) {
378                         need_trace = TRUE;
379                         if (!trace_str)
380                                 trace_str = g_string_new ("");
381                 }
382
383                 ji = mono_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx, 
384                                                                  need_trace ? &trace : NULL, &lmf, NULL, NULL);
385                 if (!ji) {
386                         g_warning ("Exception inside function without unwind info");
387                         g_assert_not_reached ();
388                 }
389
390                 if (ji != (gpointer)-1) {
391                         frame_count ++;
392                         //printf ("M: %s %d %d.\n", mono_method_full_name (ji->method, TRUE), frame_count, test_only);
393
394                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
395                                 /* 
396                                  * Avoid overwriting the stack trace if the exception is
397                                  * rethrown. Also avoid giant stack traces during a stack
398                                  * overflow.
399                                  */
400                                 if (!initial_stack_trace && (frame_count < 1000)) {
401                                         trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
402
403                                         g_string_append (trace_str, trace);
404                                         g_string_append_c (trace_str, '\n');
405                                 }
406                         }
407
408                         if (stack_overflow)
409                                 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
410                         else
411                                 free_stack = 0xffffff;
412
413                         /* 
414                          * During stack overflow, wait till the unwinding frees some stack
415                          * space before running handlers/finalizers.
416                          */
417                         if ((free_stack > (64 * 1024)) && ji->num_clauses) {
418                                 int i;
419                                 
420                                 g_assert (ji->clauses);
421                         
422                                 for (i = 0; i < ji->num_clauses; i++) {
423                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
424                                         gboolean filtered = FALSE;
425
426                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
427                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
428                                                 /* catch block */
429
430                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
431                                                         /* store the exception object int cfg->excvar */
432                                                         g_assert (ji->exvar_offset);
433                                                         *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ji->exvar_offset)) = obj;
434                                                         if (!initial_stack_trace && trace_str) {
435                                                                 mono_ex->stack_trace = mono_string_new (domain, trace_str->str);
436                                                         }
437                                                 }
438
439                                                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
440                                                         mono_debugger_handle_exception (ei->data.filter, MONO_CONTEXT_GET_SP (ctx), obj);
441                                                         filtered = call_filter (ctx, ei->data.filter);
442                                                 }
443
444                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
445                                                      mono_object_isinst (obj, ei->data.catch_class)) || filtered) {
446                                                         if (test_only) {
447                                                                 if (mono_ex) {
448                                                                         trace_ips = g_list_reverse (trace_ips);
449                                                                         mono_ex->trace_ips = glist_to_array (trace_ips);
450                                                                 }
451                                                                 g_list_free (trace_ips);
452                                                                 g_free (trace);
453
454                                                                 if (gc_disabled)
455                                                                         mono_gc_enable ();
456                                                                 if (trace_str)
457                                                                         g_string_free (trace_str, TRUE);
458                                                                 return TRUE;
459                                                         }
460                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
461                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
462                                                         mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
463                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
464                                                         jit_tls->lmf = lmf;
465                                                         g_free (trace);
466
467                                                         if (gc_disabled)
468                                                                 mono_gc_enable ();
469                                                         if (trace_str)
470                                                                 g_string_free (trace_str, TRUE);
471                                                         return 0;
472                                                 }
473                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
474                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
475                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
476                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
477                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
478                                                         mono_debugger_handle_exception (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
479                                                         call_filter (ctx, ei->handler_start);
480                                                 }
481                                                 
482                                         }
483                                 }
484                         }
485                 }
486
487                 g_free (trace);
488                         
489                 *ctx = new_ctx;
490
491                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
492                         if (gc_disabled)
493                                 mono_gc_enable ();
494
495                         if (!test_only) {
496                                 jit_tls->lmf = lmf;
497
498                                 if (IS_ON_SIGALTSTACK (jit_tls)) {
499                                         /* Switch back to normal stack */
500                                         if (stack_overflow)
501                                                 /* Free up some stack space */
502                                                 MONO_CONTEXT_SET_SP (&initial_ctx, (guint32)(MONO_CONTEXT_GET_SP (&initial_ctx)) + (64 * 1024));
503                                         MONO_CONTEXT_SET_IP (&initial_ctx, (unsigned int)jit_tls->abort_func);
504                                         restore_context (&initial_ctx);
505                                 }
506                                 else
507                                         jit_tls->abort_func (obj);
508                                 g_assert_not_reached ();
509                         } else {
510                                 if (mono_ex) {
511                                         trace_ips = g_list_reverse (trace_ips);
512                                         mono_ex->trace_ips = glist_to_array (trace_ips);
513                                 }
514                                 g_list_free (trace_ips);
515                                 if (trace_str)
516                                         g_string_free (trace_str, TRUE);
517                                 return FALSE;
518                         }
519                 }
520         }
521
522         g_assert_not_reached ();
523 }