Ooops, forgot a NULL check in my last commit.
[mono.git] / mono / jit / exception.c
1 /*
2  * exception.c: 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
13 #include <mono/arch/x86/x86-codegen.h>
14 #include <mono/metadata/appdomain.h>
15 #include <mono/metadata/tabledefs.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/debug-helpers.h>
18
19 #include "jit.h"
20 #include "codegen.h"
21 #include "debug.h"
22
23 #ifdef __FreeBSD__
24 # define SC_EAX sc_eax
25 # define SC_EBX sc_ebx
26 # define SC_ECX sc_ecx
27 # define SC_EDX sc_edx
28 # define SC_EBP sc_ebp
29 # define SC_EIP sc_eip
30 # define SC_ESP sc_esp
31 # define SC_EDI sc_edi
32 # define SC_ESI sc_esi
33 #else
34 # define SC_EAX eax
35 # define SC_EBX ebx
36 # define SC_ECX ecx
37 # define SC_EDX edx
38 # define SC_EBP ebp
39 # define SC_EIP eip
40 # define SC_ESP esp
41 # define SC_EDI edi
42 # define SC_ESI esi
43 #endif
44
45 /*
46  * arch_get_restore_context:
47  *
48  * Returns a pointer to a method which restores a previously saved sigcontext.
49  */
50 static gpointer
51 arch_get_restore_context (void)
52 {
53         static guint8 *start = NULL;
54         guint8 *code;
55
56         if (start)
57                 return start;
58
59         /* restore_contect (struct sigcontext *ctx) */
60         /* we do not restore X86_EAX, X86_EDX */
61
62         start = code = g_malloc (1024);
63         
64         /* load ctx */
65         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
66
67         /* get return address, stored in EDX */
68         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EIP), 4);
69         /* restore EBX */
70         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBX), 4);
71         /* restore EDI */
72         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EDI), 4);
73         /* restore ESI */
74         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESI), 4);
75         /* restore ESP */
76         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESP), 4);
77         /* restore EBP */
78         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBP), 4);
79         /* restore ECX. the exception object is passed here to the catch handler */
80         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ECX), 4);
81
82         /* jump to the saved IP */
83         x86_jump_reg (code, X86_EDX);
84
85         return start;
86 }
87
88 /*
89  * arch_get_call_finally:
90  *
91  * Returns a pointer to a method which calls a finally handler.
92  */
93 static gpointer
94 arch_get_call_finally (void)
95 {
96         static guint8 start [28];
97         static int inited = 0;
98         guint8 *code;
99
100         if (inited)
101                 return start;
102
103         inited = 1;
104         /* call_finally (struct sigcontext *ctx, unsigned long eip) */
105         code = start;
106
107         x86_push_reg (code, X86_EBP);
108         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
109         x86_push_reg (code, X86_EBX);
110         x86_push_reg (code, X86_EDI);
111         x86_push_reg (code, X86_ESI);
112
113         /* load ctx */
114         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
115         /* load eip */
116         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
117         /* save EBP */
118         x86_push_reg (code, X86_EBP);
119         /* set new EBP */
120         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBP), 4);
121         /* save the ESP - this is used by endfinally */
122         x86_mov_membase_reg (code, X86_EBP, -16, X86_ESP, 4);
123         /* call the handler */
124         x86_call_reg (code, X86_ECX);
125         /* restore EBP */
126         x86_pop_reg (code, X86_EBP);
127         /* restore saved regs */
128         x86_pop_reg (code, X86_ESI);
129         x86_pop_reg (code, X86_EDI);
130         x86_pop_reg (code, X86_EBX);
131         x86_leave (code);
132         x86_ret (code);
133
134         g_assert ((code - start) < 28);
135         return start;
136 }
137
138 static MonoArray *
139 glist_to_array (GList *list) 
140 {
141         MonoDomain *domain = mono_domain_get ();
142         MonoArray *res;
143         int len, i;
144
145         if (!list)
146                 return NULL;
147
148         len = g_list_length (list);
149         res = mono_array_new (domain, mono_defaults.int_class, len);
150
151         for (i = 0; list; list = list->next, i++)
152                 mono_array_set (res, gpointer, i, list->data);
153
154         return res;
155 }
156
157 /*
158  * return TRUE if the exception is catched. It also sets the 
159  * stack_trace String. 
160  */
161 static gboolean
162 arch_exc_is_caught (MonoDomain *domain, MonoJitTlsData *jit_tls, gpointer ip, 
163                     gpointer *bp, gpointer obj)
164 {
165         MonoJitInfo *ji;
166         gpointer *end_of_stack;
167         MonoLMF *lmf = jit_tls->lmf;
168         MonoMethod *m;
169         GList *trace_ips = NULL;
170         int i;
171
172         end_of_stack = jit_tls->end_of_stack;
173         g_assert (end_of_stack);
174
175         while (1) {
176
177                 ji = mono_jit_info_table_find (domain, ip);
178
179                 if (ji) { /* we are inside managed code */
180                         m = ji->method;
181                         
182                         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
183                                 char    *strace;
184                                 char    *tmp, *tmpsig, *source_location, *tmpaddr;
185                                 gint32   address, iloffset;
186
187                                 trace_ips = g_list_append (trace_ips, ip);
188
189                                 if (!((MonoException*)obj)->stack_trace)
190                                         strace = g_strdup ("");
191                                 else
192                                         strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
193
194                                 address = (char *)ip - (char *)ji->code_start;
195
196                                 source_location = mono_debug_source_location_from_address (m, address, NULL);
197                                 iloffset = mono_debug_il_offset_from_address (m, address);
198
199                                 if (iloffset < 0)
200                                         tmpaddr = g_strdup_printf ("<0x%05x>", address);
201                                 else
202                                         tmpaddr = g_strdup_printf ("[0x%05x]", iloffset);
203
204                                 tmpsig = mono_signature_get_desc(m->signature, TRUE);
205                                 if (source_location)
206                                         tmp = g_strdup_printf ("%sin %s (at %s) %s.%s:%s (%s)\n", strace, tmpaddr,
207                                                                source_location, m->klass->name_space, m->klass->name,
208                                                                m->name, tmpsig);
209                                 else
210                                         tmp = g_strdup_printf ("%sin %s %s.%s:%s (%s)\n", strace, tmpaddr,
211                                                                m->klass->name_space, m->klass->name, m->name, tmpsig);
212                                 g_free (source_location);
213                                 g_free (tmpsig);
214                                 g_free (strace);
215
216                                 ((MonoException*)obj)->stack_trace = mono_string_new (domain, tmp);
217                                 g_free (tmp);
218                         }
219
220                         if (ji->num_clauses) {
221
222                                 g_assert (ji->clauses);
223
224                                 for (i = 0; i < ji->num_clauses; i++) {
225                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
226                                 
227                                         if (ei->try_start <= ip && ip <= (ei->try_end)) { 
228                                                 /* catch block */
229                                                 if (ei->flags == 0 && mono_object_isinst (obj, 
230                                                         mono_class_get (m->klass->image, ei->token_or_filter))) {
231                                                         ((MonoException*)obj)->trace_ips = glist_to_array (trace_ips);
232                                                         g_list_free (trace_ips);
233                                                         return TRUE;
234                                                 }
235                                         }
236                                 }
237                         }
238
239                         /* continue unwinding */
240
241                         ip = (gpointer)(*((int *)bp + 1) - 5);
242                         bp = (gpointer)(*((int *)bp));
243
244                         if (bp >= end_of_stack) {
245                                 ((MonoException*)obj)->trace_ips = glist_to_array (trace_ips);
246                                 g_list_free (trace_ips);
247                                 if (!jit_tls->env)
248                                         return FALSE;
249                                 return TRUE;
250                         }
251         
252                 } else {
253                         if (!lmf) {
254                                 ((MonoException*)obj)->trace_ips = glist_to_array (trace_ips);
255                                 g_list_free (trace_ips);
256                                 return FALSE;
257                         }
258
259                         bp = (gpointer)lmf->ebp;
260                         ip = (gpointer)lmf->eip;
261
262                         m = lmf->method;
263
264                         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
265                                 char  *strace; 
266                                 char  *tmp;
267
268                                 trace_ips = g_list_append (trace_ips, lmf->method->info);
269
270                                 if (!((MonoException*)obj)->stack_trace)
271                                         strace = g_strdup ("");
272                                 else
273                                         strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
274
275                                 tmp = g_strdup_printf ("%sin (unmanaged) %s.%s:%s ()\n", strace, m->klass->name_space,  
276                                                        m->klass->name, m->name);
277
278                                 g_free (strace);
279
280                                 ((MonoException*)obj)->stack_trace = mono_string_new (domain, tmp);
281                                 g_free (tmp);
282                         }
283
284                         lmf = lmf->previous_lmf;
285
286                         if (bp >= end_of_stack) {
287                                 ((MonoException*)obj)->trace_ips = glist_to_array (trace_ips);
288                                 g_list_free (trace_ips);
289                                 if (!jit_tls->env)
290                                         return FALSE;
291                                 return TRUE;
292                         }
293                 }
294         }
295         
296         return FALSE;
297 }
298
299 MonoArray *
300 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
301 {
302         MonoDomain *domain = mono_domain_get ();
303         MonoArray *res;
304         MonoArray *ta = exc->trace_ips;
305         int i, len;
306         
307         len = mono_array_length (ta);
308
309         res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
310
311         for (i = skip; i < len; i++) {
312                 MonoJitInfo *ji;
313                 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
314                 gpointer ip = mono_array_get (ta, gpointer, i);
315
316                 ji = mono_jit_info_table_find (domain, ip);
317                 g_assert (ji != NULL);
318
319                 sf->method = mono_method_get_object (domain, ji->method);
320                 sf->native_offset = (char *)ip - (char *)ji->code_start;
321                 sf->il_offset = mono_debug_il_offset_from_address (ji->method, sf->native_offset);
322
323                 if (need_file_info) {
324                         gchar *filename;
325
326                         filename = mono_debug_source_location_from_address (ji->method, sf->native_offset, &sf->line);
327
328                         sf->filename = mono_string_new (domain, filename ? filename : "<unknown>");
329                         sf->column = 0;
330
331                         g_free (filename);
332                 }
333
334                 mono_array_set (res, gpointer, i, sf);
335         }
336
337         return res;
338 }
339
340 MonoBoolean
341 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info, 
342                           MonoReflectionMethod **method, 
343                           gint32 *iloffset, gint32 *native_offset,
344                           MonoString **file, gint32 *line, gint32 *column)
345 {
346         MonoDomain *domain = mono_domain_get ();
347         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
348         MonoLMF *lmf = jit_tls->lmf;
349         gpointer *sf = (gpointer *)&skip;
350         gpointer ip = sf [-1];
351         int addr;
352         gpointer *bp = sf [-2];
353         MonoMethod *m = NULL;
354
355         do {
356                 MonoJitInfo *ji;
357                 addr = -1; /* unknown */
358
359                 if ((ji = mono_jit_info_table_find (domain, ip))) {
360                         m = ji->method;
361                         addr = (char *)ip - (char *)ji->code_start;
362                         ip = (gpointer)((char *)bp [1] - 5);
363                         bp = bp [0];
364                 } else {
365                         if (!lmf)
366                                 return FALSE;
367                         
368                         m = lmf->method;
369
370                         bp = (gpointer)lmf->ebp;
371                         ip = (gpointer)lmf->eip;
372
373                         lmf = lmf->previous_lmf;
374                 }
375
376                 if ((unsigned)bp >= (unsigned)jit_tls->end_of_stack)
377                         return FALSE;
378
379         } while (skip-- > 0);
380
381         g_assert (m);
382
383         *method = mono_method_get_object (domain, m);
384         *iloffset = mono_debug_il_offset_from_address (m, addr);
385         *native_offset = addr;
386
387         if (need_file_info) {
388                 gchar *filename;
389
390                 filename = mono_debug_source_location_from_address (m, addr, line);
391
392                 *file = mono_string_new (domain, filename ? filename : "<unknown>");
393                 *column = 0;
394
395                 g_free (filename);
396         }
397
398         return TRUE;
399 }
400
401 /**
402  * arch_handle_exception:
403  * @ctx: saved processor state
404  * @obj:
405  */
406 void
407 arch_handle_exception (struct sigcontext *ctx, gpointer obj)
408 {
409         MonoDomain *domain = mono_domain_get ();
410         MonoJitInfo *ji;
411         gpointer ip = (gpointer)ctx->SC_EIP;
412         static void (*restore_context) (struct sigcontext *);
413         static void (*call_finally) (struct sigcontext *, unsigned long);
414         void (*cleanup) (MonoObject *exc);
415         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
416         gpointer end_of_stack;
417
418         g_assert (ctx != NULL);
419
420         if (!obj) {
421                 MonoException *ex = mono_get_exception_null_reference ();
422                 ex->message = mono_string_new (domain, 
423                         "Object reference not set to an instance of an object");
424                 obj = (MonoObject *)ex;
425         } 
426
427         ((MonoException *)obj)->stack_trace = NULL;
428
429         if (!restore_context)
430                 restore_context = arch_get_restore_context ();
431         
432         if (!call_finally)
433                 call_finally = arch_get_call_finally ();
434
435         end_of_stack = jit_tls->end_of_stack;
436         g_assert (end_of_stack);
437
438         cleanup = jit_tls->abort_func;
439
440         if (!arch_exc_is_caught (domain, jit_tls, ip, (gpointer *)ctx->SC_EBP, obj)) {
441                 if (mono_break_on_exc) {
442                         if (mono_debug_format != MONO_DEBUG_FORMAT_NONE)
443                                 mono_debug_make_symbols ();
444                         G_BREAKPOINT ();
445                 }
446                 mono_unhandled_exception (obj);
447         }
448
449         while (1) {
450
451                 ji = mono_jit_info_table_find (domain, ip);
452         
453                 if (ji) { /* we are inside managed code */
454                         MonoMethod *m = ji->method;
455                         int offset;
456
457                         if (ji->num_clauses) {
458                                 int i;
459                                 
460                                 g_assert (ji->clauses);
461                         
462                                 for (i = 0; i < ji->num_clauses; i++) {
463                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
464
465                                         if (ei->try_start <= ip && ip <= (ei->try_end)) { 
466                                                 /* catch block */
467                                                 if (ei->flags == 0 && mono_object_isinst (obj, 
468                                                         mono_class_get (m->klass->image, ei->token_or_filter))) {
469                                         
470                                                         ctx->SC_EIP = (unsigned long)ei->handler_start;
471                                                         ctx->SC_ECX = (unsigned long)obj;
472                                                         restore_context (ctx);
473                                                         g_assert_not_reached ();
474                                                 }
475                                         }
476                                 }
477
478                                 /* no handler found - we need to call all finally handlers */
479                                 for (i = 0; i < ji->num_clauses; i++) {
480                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
481
482                                         if (ei->try_start <= ip && ip < (ei->try_end) &&
483                                             (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
484                                                 call_finally (ctx, (unsigned long)ei->handler_start);
485                                         }
486                                 }
487                         }
488
489                         /* continue unwinding */
490
491                         offset = -1;
492                         /* restore caller saved registers */
493                         if (ji->used_regs & X86_EBX_MASK) {
494                                 ctx->SC_EBX = *((int *)ctx->SC_EBP + offset);
495                                 offset--;
496                         }
497                         if (ji->used_regs & X86_EDI_MASK) {
498                                 ctx->SC_EDI = *((int *)ctx->SC_EBP + offset);
499                                 offset--;
500                         }
501                         if (ji->used_regs & X86_ESI_MASK) {
502                                 ctx->SC_ESI = *((int *)ctx->SC_EBP + offset);
503                         }
504
505                         ctx->SC_ESP = ctx->SC_EBP;
506                         ctx->SC_EIP = *((int *)ctx->SC_EBP + 1) - 5;
507                         ctx->SC_EBP = *((int *)ctx->SC_EBP);
508
509                         ip = (gpointer)ctx->SC_EIP;
510
511                         if (ctx->SC_EBP > (unsigned)end_of_stack) {
512                                 g_assert (cleanup);
513                                 cleanup (obj);
514                                 g_assert_not_reached ();
515                         }
516         
517                 } else {
518                         MonoLMF *lmf = jit_tls->lmf;
519
520                         if (!lmf) {
521                                 g_assert (cleanup);
522                                 cleanup (obj);
523                                 g_assert_not_reached ();
524                         }
525
526                         jit_tls->lmf = lmf->previous_lmf;
527
528                         ctx->SC_ESI = lmf->esi;
529                         ctx->SC_EDI = lmf->edi;
530                         ctx->SC_EBX = lmf->ebx;
531                         ctx->SC_EBP = lmf->ebp;
532                         ctx->SC_EIP = lmf->eip;
533                         ctx->SC_ESP = (unsigned long)&lmf->eip;
534
535                         ip = (gpointer)ctx->SC_EIP;
536
537                         if (ctx->SC_EBP >= (unsigned)end_of_stack) {
538                                 g_assert (cleanup);
539                                 cleanup (obj);
540                                 g_assert_not_reached ();
541                         }
542                 }
543         }
544
545         g_assert_not_reached ();
546 }
547
548 static void
549 throw_exception (unsigned long eax, unsigned long ecx, unsigned long edx, unsigned long ebx,
550                  unsigned long esi, unsigned long edi, unsigned long ebp, MonoObject *exc,
551                  unsigned long eip,  unsigned long esp)
552 {
553         struct sigcontext ctx;
554
555         /* adjust eip so that it point to the call instruction */
556         eip -= 5;
557
558         ctx.SC_ESP = esp;
559         ctx.SC_EIP = eip;
560         ctx.SC_EBP = ebp;
561         ctx.SC_EDI = edi;
562         ctx.SC_ESI = esi;
563         ctx.SC_EBX = ebx;
564         ctx.SC_EDX = edx;
565         ctx.SC_ECX = ecx;
566         ctx.SC_EAX = eax;
567         
568         arch_handle_exception (&ctx, exc);
569
570         g_assert_not_reached ();
571 }
572
573 /**
574  * arch_get_throw_exception:
575  *
576  * Returns a function pointer which can be used to raise 
577  * exceptions. The returned function has the following 
578  * signature: void (*func) (MonoException *exc); 
579  * For example to raise an arithmetic exception you can use:
580  *
581  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
582  * x86_call_code (code, arch_get_throw_exception ()); 
583  *
584  */
585 gpointer 
586 arch_get_throw_exception (void)
587 {
588         static guint8 start [24];
589         static int inited = 0;
590         guint8 *code;
591
592         if (inited)
593                 return start;
594
595         inited = 1;
596         code = start;
597
598         x86_push_reg (code, X86_ESP);
599         x86_push_membase (code, X86_ESP, 4); /* IP */
600         x86_push_membase (code, X86_ESP, 12); /* exception */
601         x86_push_reg (code, X86_EBP);
602         x86_push_reg (code, X86_EDI);
603         x86_push_reg (code, X86_ESI);
604         x86_push_reg (code, X86_EBX);
605         x86_push_reg (code, X86_EDX);
606         x86_push_reg (code, X86_ECX);
607         x86_push_reg (code, X86_EAX);
608         x86_call_code (code, throw_exception);
609         /* we should never reach this breakpoint */
610         x86_breakpoint (code);
611
612         g_assert ((code - start) < 24);
613         return start;
614 }
615
616 /**
617  * arch_get_throw_exception_by_name:
618  *
619  * Returns a function pointer which can be used to raise 
620  * corlib exceptions. The returned function has the following 
621  * signature: void (*func) (char *exc_name); 
622  * For example to raise an arithmetic exception you can use:
623  *
624  * x86_push_imm (code, "ArithmeticException"); 
625  * x86_call_code (code, arch_get_throw_exception ()); 
626  *
627  */
628 gpointer 
629 arch_get_throw_exception_by_name ()
630 {
631         static guint8 start [32];
632         static int inited = 0;
633         guint8 *code;
634
635         if (inited)
636                 return start;
637
638         inited = 1;
639         code = start;
640
641         /* fixme: we do not save EAX, EDX, ECD - unsure if we need that */
642
643         x86_push_membase (code, X86_ESP, 4); /* exception name */
644         x86_push_imm (code, "System");
645         x86_push_imm (code, mono_defaults.exception_class->image);
646         x86_call_code (code, mono_exception_from_name);
647         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 12);
648         /* save the newly create object (overwrite exception name)*/
649         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
650         x86_jump_code (code, arch_get_throw_exception ());
651
652         g_assert ((code - start) < 32);
653
654         return start;
655 }