Update
[mono.git] / mono / mini / exceptions-x86.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 #include <signal.h>
13 #include <string.h>
14
15 #include <mono/arch/x86/x86-codegen.h>
16 #include <mono/metadata/appdomain.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/threads.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/exception.h>
21 #include <mono/metadata/mono-debug.h>
22
23 #include "mini.h"
24 #include "mini-x86.h"
25
26 #ifdef PLATFORM_WIN32
27
28 #include <windows.h>
29
30 /* use SIG* defines if possible */
31 #ifdef HAVE_SIGNAL_H
32 #include <signal.h>
33 #endif
34
35 /* sigcontext surrogate */
36 struct sigcontext {
37         unsigned int eax;
38         unsigned int ebx;
39         unsigned int ecx;
40         unsigned int edx;
41         unsigned int ebp;
42         unsigned int esp;
43         unsigned int esi;
44         unsigned int edi;
45         unsigned int eip;
46 };
47
48
49 typedef void (* MonoW32ExceptionHandler) (int);
50 void win32_seh_init(void);
51 void win32_seh_cleanup(void);
52 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler);
53
54 #ifndef SIGFPE
55 #define SIGFPE 4
56 #endif
57
58 #ifndef SIGILL
59 #define SIGILL 8
60 #endif
61
62 #ifndef SIGSEGV
63 #define SIGSEGV 11
64 #endif
65
66 LONG CALLBACK seh_handler(EXCEPTION_POINTERS* ep);
67
68 static MonoW32ExceptionHandler fpe_handler;
69 static MonoW32ExceptionHandler ill_handler;
70 static MonoW32ExceptionHandler segv_handler;
71
72 static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
73
74 #define W32_SEH_HANDLE_EX(_ex) \
75         if (_ex##_handler) _ex##_handler((int)sctx)
76
77 /*
78  * Unhandled Exception Filter
79  * Top-level per-process exception handler.
80  */
81 LONG CALLBACK seh_handler(EXCEPTION_POINTERS* ep)
82 {
83         EXCEPTION_RECORD* er;
84         CONTEXT* ctx;
85         struct sigcontext* sctx;
86         LONG res;
87
88         res = EXCEPTION_CONTINUE_EXECUTION;
89
90         er = ep->ExceptionRecord;
91         ctx = ep->ContextRecord;
92         sctx = g_malloc(sizeof(struct sigcontext));
93
94         /* Copy Win32 context to UNIX style context */
95         sctx->eax = ctx->Eax;
96         sctx->ebx = ctx->Ebx;
97         sctx->ecx = ctx->Ecx;
98         sctx->edx = ctx->Edx;
99         sctx->ebp = ctx->Ebp;
100         sctx->esp = ctx->Esp;
101         sctx->esi = ctx->Esi;
102         sctx->edi = ctx->Edi;
103         sctx->eip = ctx->Eip;
104
105         switch (er->ExceptionCode) {
106         case EXCEPTION_ACCESS_VIOLATION:
107                 W32_SEH_HANDLE_EX(segv);
108                 break;
109         case EXCEPTION_ILLEGAL_INSTRUCTION:
110                 W32_SEH_HANDLE_EX(ill);
111                 break;
112         case EXCEPTION_INT_DIVIDE_BY_ZERO:
113         case EXCEPTION_INT_OVERFLOW:
114         case EXCEPTION_FLT_DIVIDE_BY_ZERO:
115         case EXCEPTION_FLT_OVERFLOW:
116         case EXCEPTION_FLT_UNDERFLOW:
117         case EXCEPTION_FLT_INEXACT_RESULT:
118                 W32_SEH_HANDLE_EX(fpe);
119                 break;
120         default:
121                 break;
122         }
123
124         /* Copy context back */
125         ctx->Eax = sctx->eax;
126         ctx->Ebx = sctx->ebx;
127         ctx->Ecx = sctx->ecx;
128         ctx->Edx = sctx->edx;
129         ctx->Ebp = sctx->ebp;
130         ctx->Esp = sctx->esp;
131         ctx->Esi = sctx->esi;
132         ctx->Edi = sctx->edi;
133         ctx->Eip = sctx->eip;
134
135         return res;
136 }
137
138 void win32_seh_init()
139 {
140         old_handler = SetUnhandledExceptionFilter(seh_handler);
141 }
142
143 void win32_seh_cleanup()
144 {
145         if (old_handler) SetUnhandledExceptionFilter(old_handler);
146 }
147
148 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
149 {
150         switch (type) {
151         case SIGFPE:
152                 fpe_handler = handler;
153                 break;
154         case SIGILL:
155                 ill_handler = handler;
156                 break;
157         case SIGSEGV:
158                 segv_handler = handler;
159                 break;
160         default:
161                 break;
162         }
163 }
164
165 #endif /* PLATFORM_WIN32 */
166
167 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
168 # define SC_EAX sc_eax
169 # define SC_EBX sc_ebx
170 # define SC_ECX sc_ecx
171 # define SC_EDX sc_edx
172 # define SC_EBP sc_ebp
173 # define SC_EIP sc_eip
174 # define SC_ESP sc_esp
175 # define SC_EDI sc_edi
176 # define SC_ESI sc_esi
177 #else
178 # define SC_EAX eax
179 # define SC_EBX ebx
180 # define SC_ECX ecx
181 # define SC_EDX edx
182 # define SC_EBP ebp
183 # define SC_EIP eip
184 # define SC_ESP esp
185 # define SC_EDI edi
186 # define SC_ESI esi
187 #endif
188
189 gboolean  mono_arch_handle_exception (struct sigcontext *ctx, gpointer obj, gboolean test_only);
190
191 typedef struct sigcontext MonoContext;
192
193 #define MONO_CONTEXT_SET_IP(ctx,ip) do { (ctx)->SC_EIP = (long)ip; } while (0); 
194 #define MONO_CONTEXT_SET_BP(ctx,bp) do { (ctx)->SC_EBP = (long)bp; } while (0); 
195
196 #define MONO_CONTEXT_GET_IP(ctx) ((gpointer)((ctx)->SC_EIP))
197 #define MONO_CONTEXT_GET_BP(ctx) ((gpointer)((ctx)->SC_EBP))
198
199 #ifdef MONO_USE_EXC_TABLES
200
201 /*************************************/
202 /*    STACK UNWINDING STUFF          */
203 /*************************************/
204
205 /* These definitions are from unwind-dw2.c in glibc 2.2.5 */
206
207 /* For x86 */
208 #define DWARF_FRAME_REGISTERS 17
209
210 typedef struct frame_state
211 {
212   void *cfa;
213   void *eh_ptr;
214   long cfa_offset;
215   long args_size;
216   long reg_or_offset[DWARF_FRAME_REGISTERS+1];
217   unsigned short cfa_reg;
218   unsigned short retaddr_column;
219   char saved[DWARF_FRAME_REGISTERS+1];
220 } frame_state;
221
222 static long
223 get_sigcontext_reg (struct sigcontext *ctx, int dwarf_regnum)
224 {
225         switch (dwarf_regnum) {
226         case X86_EAX:
227                 return ctx->SC_EAX;
228         case X86_EBX:
229                 return ctx->SC_EBX;
230         case X86_ECX:
231                 return ctx->SC_ECX;
232         case X86_EDX:
233                 return ctx->SC_EDX;
234         case X86_ESI:
235                 return ctx->SC_ESI;
236         case X86_EDI:
237                 return ctx->SC_EDI;
238         case X86_EBP:
239                 return ctx->SC_EBP;
240         case X86_ESP:
241                 return ctx->SC_ESP;
242         default:
243                 g_assert_not_reached ();
244         }
245
246         return 0;
247 }
248
249 static void
250 set_sigcontext_reg (struct sigcontext *ctx, int dwarf_regnum, long value)
251 {
252         switch (dwarf_regnum) {
253         case X86_EAX:
254                 ctx->SC_EAX = value;
255                 break;
256         case X86_EBX:
257                 ctx->SC_EBX = value;
258                 break;
259         case X86_ECX:
260                 ctx->SC_ECX = value;
261                 break;
262         case X86_EDX:
263                 ctx->SC_EDX = value;
264                 break;
265         case X86_ESI:
266                 ctx->SC_ESI = value;
267                 break;
268         case X86_EDI:
269                 ctx->SC_EDI = value;
270                 break;
271         case X86_EBP:
272                 ctx->SC_EBP = value;
273                 break;
274         case X86_ESP:
275                 ctx->SC_ESP = value;
276                 break;
277         case 8:
278                 ctx->SC_EIP = value;
279                 break;
280         default:
281                 g_assert_not_reached ();
282         }
283 }
284
285 typedef struct frame_state * (*framesf) (void *, struct frame_state *);
286
287 static framesf frame_state_for = NULL;
288
289 static gboolean inited = FALSE;
290
291 typedef char ** (*get_backtrace_symbols_type) (void *__const *__array, int __size);
292
293 static get_backtrace_symbols_type get_backtrace_symbols = NULL;
294
295 static void
296 init_frame_state_for (void)
297 {
298         GModule *module;
299
300         /*
301          * There are two versions of __frame_state_for: one in libgcc.a and the
302          * other in glibc.so. We need the version from glibc.
303          * For more info, see this:
304          * http://gcc.gnu.org/ml/gcc/2002-08/msg00192.html
305          */
306         if ((module = g_module_open ("libc.so.6", G_MODULE_BIND_LAZY))) {
307         
308                 if (!g_module_symbol (module, "__frame_state_for", (gpointer*)&frame_state_for))
309                         frame_state_for = NULL;
310
311                 if (!g_module_symbol (module, "backtrace_symbols", (gpointer*)&get_backtrace_symbols)) {
312                         get_backtrace_symbols = NULL;
313                         frame_state_for = NULL;
314                 }
315
316                 g_module_close (module);
317         }
318
319         inited = TRUE;
320 }
321
322 /* mono_arch_has_unwind_info:
323  *
324  * Tests if a function has an DWARF exception table able to restore
325  * all caller saved registers. 
326  */
327 gboolean
328 mono_arch_has_unwind_info (gconstpointer addr)
329 {
330         struct frame_state state_in;
331         struct frame_state *res;
332
333         if (!inited) 
334                 init_frame_state_for ();
335         
336         if (!frame_state_for)
337                 return FALSE;
338
339         g_assert (addr);
340
341         memset (&state_in, 0, sizeof (state_in));
342
343         /* offset 10 is just a guess, but it works for all methods tested */
344         if ((res = frame_state_for ((char *)addr + 10, &state_in))) {
345
346                 if (res->saved [X86_EBX] == 1 &&
347                     res->saved [X86_EDI] == 1 &&
348                     res->saved [X86_EBP] == 1 &&
349                     res->saved [X86_ESI] == 1)
350                         return TRUE;
351         }
352
353         return FALSE;
354 }
355
356 struct stack_frame
357 {
358   void *next;
359   void *return_address;
360 };
361
362 static MonoJitInfo *
363 x86_unwind_native_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, struct sigcontext *ctx, 
364                          struct sigcontext *new_ctx, MonoLMF *lmf, char **trace)
365 {
366         struct stack_frame *frame;
367         gpointer max_stack;
368         MonoJitInfo *ji;
369         struct frame_state state_in;
370         struct frame_state *res;
371
372         if (trace)
373                 *trace = NULL;
374
375         if (!inited) 
376                 init_frame_state_for ();
377
378         if (!frame_state_for)
379                 return FALSE;
380
381         frame = MONO_CONTEXT_GET_BP (ctx);
382
383         max_stack = lmf && lmf->method ? lmf : jit_tls->end_of_stack;
384
385         *new_ctx = *ctx;
386
387         memset (&state_in, 0, sizeof (state_in));
388
389         while ((gpointer)frame->next < (gpointer)max_stack) {
390                 gpointer ip, addr = frame->return_address;
391                 void *cfa;
392                 char *tmp, **symbols;
393
394                 if (trace) {
395                         ip = MONO_CONTEXT_GET_IP (new_ctx);
396                         symbols = get_backtrace_symbols (&ip, 1);
397                         if (*trace)
398                                 tmp = g_strdup_printf ("%s\nin (unmanaged) %s", *trace, symbols [0]);
399                         else
400                                 tmp = g_strdup_printf ("in (unmanaged) %s", symbols [0]);
401
402                         free (symbols);
403                         g_free (*trace);
404                         *trace = tmp;
405                 }
406
407                 if ((res = frame_state_for (addr, &state_in))) {        
408                         int i;
409
410                         cfa = (gint8*) (get_sigcontext_reg (new_ctx, res->cfa_reg) + res->cfa_offset);
411                         frame = (struct stack_frame *)((gint8*)cfa - 8);
412                         for (i = 0; i < DWARF_FRAME_REGISTERS + 1; i++) {
413                                 int how = res->saved[i];
414                                 long val;
415                                 g_assert ((how == 0) || (how == 1));
416                         
417                                 if (how == 1) {
418                                         val = * (long*) ((gint8*)cfa + res->reg_or_offset[i]);
419                                         set_sigcontext_reg (new_ctx, i, val);
420                                 }
421                         }
422                         new_ctx->SC_ESP = (long)cfa;
423
424                         if (res->saved [X86_EBX] == 1 &&
425                             res->saved [X86_EDI] == 1 &&
426                             res->saved [X86_EBP] == 1 &&
427                             res->saved [X86_ESI] == 1 &&
428                             (ji = mono_jit_info_table_find (domain, frame->return_address))) {
429                                 //printf ("FRAME CFA %s\n", mono_method_full_name (ji->method, TRUE));
430                                 return ji;
431                         }
432
433                 } else {
434                         //printf ("FRAME %p %p %p\n", frame, MONO_CONTEXT_GET_IP (new_ctx), mono_jit_info_table_find (domain, MONO_CONTEXT_GET_IP (new_ctx)));
435
436                         MONO_CONTEXT_SET_IP (new_ctx, frame->return_address);
437                         frame = frame->next;
438                         MONO_CONTEXT_SET_BP (new_ctx, frame);
439
440                         /* stop if !frame or when we detect an unexpected managed frame */
441                         if (!frame || mono_jit_info_table_find (domain, frame->return_address)) {
442                                 if (trace) {
443                                         g_free (*trace);
444                                         *trace = NULL;
445                                 }
446                                 return NULL;
447                         }
448                 }
449         }
450
451         //if (!lmf)
452         //g_assert_not_reached ();
453
454         if (trace) {
455                 g_free (*trace);
456                 *trace = NULL;
457         }
458         return NULL;
459 }
460
461 #endif
462
463 /*
464  * arch_get_restore_context:
465  *
466  * Returns a pointer to a method which restores a previously saved sigcontext.
467  */
468 static gpointer
469 arch_get_restore_context (void)
470 {
471         static guint8 *start = NULL;
472         guint8 *code;
473
474         if (start)
475                 return start;
476
477         /* restore_contect (struct sigcontext *ctx) */
478         /* we do not restore X86_EAX, X86_EDX */
479
480         start = code = g_malloc (1024);
481         
482         /* load ctx */
483         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
484
485         /* get return address, stored in EDX */
486         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EIP), 4);
487         /* restore EBX */
488         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBX), 4);
489         /* restore EDI */
490         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EDI), 4);
491         /* restore ESI */
492         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESI), 4);
493         /* restore ESP */
494         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESP), 4);
495         /* restore EBP */
496         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBP), 4);
497
498         /* jump to the saved IP */
499         x86_jump_reg (code, X86_EDX);
500
501         return start;
502 }
503
504 /*
505  * arch_get_call_filter:
506  *
507  * Returns a pointer to a method which calls an exception filter. We
508  * also use this function to call finally handlers (we pass NULL as 
509  * @exc object in this case).
510  */
511 static gpointer
512 arch_get_call_filter (void)
513 {
514         static guint8 start [64];
515         static int inited = 0;
516         guint8 *code;
517
518         if (inited)
519                 return start;
520
521         inited = 1;
522         /* call_filter (struct sigcontext *ctx, unsigned long eip) */
523         code = start;
524
525         x86_push_reg (code, X86_EBP);
526         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
527         x86_push_reg (code, X86_EBX);
528         x86_push_reg (code, X86_EDI);
529         x86_push_reg (code, X86_ESI);
530
531         /* load ctx */
532         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
533         /* load eip */
534         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
535         /* save EBP */
536         x86_push_reg (code, X86_EBP);
537
538         /* set new EBP */
539         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBP), 4);
540         /* restore registers used by global register allocation (EBX & ESI) */
541         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBX), 4);
542         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESI), 4);
543         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EDI), 4);
544
545         /* call the handler */
546         x86_call_reg (code, X86_ECX);
547
548         /* restore EBP */
549         x86_pop_reg (code, X86_EBP);
550
551         /* restore saved regs */
552         x86_pop_reg (code, X86_ESI);
553         x86_pop_reg (code, X86_EDI);
554         x86_pop_reg (code, X86_EBX);
555         x86_leave (code);
556         x86_ret (code);
557
558         g_assert ((code - start) < 64);
559         return start;
560 }
561
562 static void
563 throw_exception (unsigned long eax, unsigned long ecx, unsigned long edx, unsigned long ebx,
564                  unsigned long esi, unsigned long edi, unsigned long ebp, MonoObject *exc,
565                  unsigned long eip,  unsigned long esp)
566 {
567         static void (*restore_context) (struct sigcontext *);
568         struct sigcontext ctx;
569
570         if (!restore_context)
571                 restore_context = arch_get_restore_context ();
572
573         /* adjust eip so that it point into the call instruction */
574         eip -= 1;
575
576         ctx.SC_ESP = esp;
577         ctx.SC_EIP = eip;
578         ctx.SC_EBP = ebp;
579         ctx.SC_EDI = edi;
580         ctx.SC_ESI = esi;
581         ctx.SC_EBX = ebx;
582         ctx.SC_EDX = edx;
583         ctx.SC_ECX = ecx;
584         ctx.SC_EAX = eax;
585         
586         mono_arch_handle_exception (&ctx, exc, FALSE);
587         restore_context (&ctx);
588
589         g_assert_not_reached ();
590 }
591
592 /**
593  * arch_get_throw_exception:
594  *
595  * Returns a function pointer which can be used to raise 
596  * exceptions. The returned function has the following 
597  * signature: void (*func) (MonoException *exc); 
598  * For example to raise an arithmetic exception you can use:
599  *
600  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
601  * x86_call_code (code, arch_get_throw_exception ()); 
602  *
603  */
604 gpointer 
605 mono_arch_get_throw_exception (void)
606 {
607         static guint8 start [24];
608         static int inited = 0;
609         guint8 *code;
610
611         if (inited)
612                 return start;
613
614         inited = 1;
615         code = start;
616
617         x86_push_reg (code, X86_ESP);
618         x86_push_membase (code, X86_ESP, 4); /* IP */
619         x86_push_membase (code, X86_ESP, 12); /* exception */
620         x86_push_reg (code, X86_EBP);
621         x86_push_reg (code, X86_EDI);
622         x86_push_reg (code, X86_ESI);
623         x86_push_reg (code, X86_EBX);
624         x86_push_reg (code, X86_EDX);
625         x86_push_reg (code, X86_ECX);
626         x86_push_reg (code, X86_EAX);
627         x86_call_code (code, throw_exception);
628         /* we should never reach this breakpoint */
629         x86_breakpoint (code);
630
631         g_assert ((code - start) < 24);
632         return start;
633 }
634
635 /**
636  * arch_get_throw_exception_by_name:
637  *
638  * Returns a function pointer which can be used to raise 
639  * corlib exceptions. The returned function has the following 
640  * signature: void (*func) (char *exc_name); 
641  * For example to raise an arithmetic exception you can use:
642  *
643  * x86_push_imm (code, "ArithmeticException"); 
644  * x86_call_code (code, arch_get_throw_exception_by_name ()); 
645  *
646  */
647 gpointer 
648 mono_arch_get_throw_exception_by_name (void)
649 {
650         static guint8 start [32];
651         static int inited = 0;
652         guint8 *code;
653
654         if (inited)
655                 return start;
656
657         inited = 1;
658         code = start;
659
660         x86_push_membase (code, X86_ESP, 4); /* exception name */
661         x86_push_imm (code, "System");
662         x86_push_imm (code, mono_defaults.exception_class->image);
663         x86_call_code (code, mono_exception_from_name);
664         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 12);
665         /* save the newly create object (overwrite exception name)*/
666         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
667         x86_jump_code (code, mono_arch_get_throw_exception ());
668
669         g_assert ((code - start) < 32);
670
671         return start;
672 }       
673
674 static MonoArray *
675 glist_to_array (GList *list) 
676 {
677         MonoDomain *domain = mono_domain_get ();
678         MonoArray *res;
679         int len, i;
680
681         if (!list)
682                 return NULL;
683
684         len = g_list_length (list);
685         res = mono_array_new (domain, mono_defaults.int_class, len);
686
687         for (i = 0; list; list = list->next, i++)
688                 mono_array_set (res, gpointer, i, list->data);
689
690         return res;
691 }
692
693 /* mono_arch_find_jit_info:
694  *
695  * This function is used to gather information from @ctx. It return the 
696  * MonoJitInfo of the corresponding function, unwinds one stack frame and
697  * stores the resulting context into @new_ctx. It also stores a string 
698  * describing the stack location into @trace (if not NULL), and modifies
699  * the @lmf if necessary. @native_offset return the IP offset from the 
700  * start of the function or -1 if that info is not available.
701  */
702 static MonoJitInfo *
703 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoContext *ctx, 
704                          MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
705                          gboolean *managed)
706 {
707         MonoJitInfo *ji;
708         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
709
710         ji = mono_jit_info_table_find (domain, ip);
711
712         if (trace)
713                 *trace = NULL;
714
715         if (native_offset)
716                 *native_offset = -1;
717
718         if (managed)
719                 *managed = FALSE;
720
721         if (ji != NULL) {
722                 char *source_location, *tmpaddr, *fname;
723                 gint32 address, iloffset;
724                 int offset;
725
726                 *new_ctx = *ctx;
727
728                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
729                         /* remove any unused lmf */
730                         *lmf = (*lmf)->previous_lmf;
731                 }
732
733                 address = (char *)ip - (char *)ji->code_start;
734
735                 if (native_offset)
736                         *native_offset = address;
737
738                 if (managed)
739                         if (!ji->method->wrapper_type)
740                                 *managed = TRUE;
741
742                 if (trace) {
743                         source_location = mono_debug_source_location_from_address (ji->method, address, NULL, domain);
744                         iloffset = mono_debug_il_offset_from_address (ji->method, address, domain);
745
746                         if (iloffset < 0)
747                                 tmpaddr = g_strdup_printf ("<0x%05x>", address);
748                         else
749                                 tmpaddr = g_strdup_printf ("[0x%05x]", iloffset);
750                 
751                         fname = mono_method_full_name (ji->method, TRUE);
752
753                         if (source_location)
754                                 *trace = g_strdup_printf ("in %s (at %s) %s", tmpaddr, source_location, fname);
755                         else
756                                 *trace = g_strdup_printf ("in %s %s", tmpaddr, fname);
757
758                         g_free (fname);
759                         g_free (source_location);
760                         g_free (tmpaddr);
761                 }
762                                 
763                 offset = -1;
764                 /* restore caller saved registers */
765                 if (ji->used_regs & X86_EBX_MASK) {
766                         new_ctx->SC_EBX = *((int *)ctx->SC_EBP + offset);
767                         offset--;
768                 }
769                 if (ji->used_regs & X86_EDI_MASK) {
770                         new_ctx->SC_EDI = *((int *)ctx->SC_EBP + offset);
771                         offset--;
772                 }
773                 if (ji->used_regs & X86_ESI_MASK) {
774                         new_ctx->SC_ESI = *((int *)ctx->SC_EBP + offset);
775                 }
776
777                 new_ctx->SC_ESP = ctx->SC_EBP;
778                 /* we substract 1, so that the IP points into the call instruction */
779                 new_ctx->SC_EIP = *((int *)ctx->SC_EBP + 1) - 1;
780                 new_ctx->SC_EBP = *((int *)ctx->SC_EBP);
781
782                 *res = *ji;
783                 return res;
784 #ifdef MONO_USE_EXC_TABLES
785         } else if ((ji = x86_unwind_native_frame (domain, jit_tls, ctx, new_ctx, *lmf, trace))) {
786                 *res = *ji;             
787                 return res;
788 #endif
789         } else if (*lmf) {
790                 
791                 *new_ctx = *ctx;
792
793                 if (!(*lmf)->method)
794                         return (gpointer)-1;
795
796                 if (trace)
797                         *trace = g_strdup_printf ("in (unmanaged) %s", mono_method_full_name ((*lmf)->method, TRUE));
798                 
799                 if ((ji = mono_jit_info_table_find (domain, (gpointer)(*lmf)->eip))) {
800                         *res = *ji;
801                 } else {
802                         memset (res, 0, sizeof (MonoJitInfo));
803                         res->method = (*lmf)->method;
804                 }
805
806                 new_ctx->SC_ESI = (*lmf)->esi;
807                 new_ctx->SC_EDI = (*lmf)->edi;
808                 new_ctx->SC_EBX = (*lmf)->ebx;
809                 new_ctx->SC_EBP = (*lmf)->ebp;
810                 new_ctx->SC_EIP = (*lmf)->eip;
811                 /* the lmf is always stored on the stack, so the following
812                  * expression points to a stack location which can be used as ESP */
813                 new_ctx->SC_ESP = (unsigned long)&((*lmf)->eip);
814
815                 *lmf = (*lmf)->previous_lmf;
816
817                 return res;
818                 
819         }
820
821         return NULL;
822 }
823
824 MonoArray *
825 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
826 {
827         MonoDomain *domain = mono_domain_get ();
828         MonoArray *res;
829         MonoArray *ta = exc->trace_ips;
830         int i, len;
831
832         if (ta == NULL) {
833                 /* Exception is not thrown yet */
834                 return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
835         }
836         
837         len = mono_array_length (ta);
838
839         res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
840
841         for (i = skip; i < len; i++) {
842                 MonoJitInfo *ji;
843                 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
844                 gpointer ip = mono_array_get (ta, gpointer, i);
845
846                 ji = mono_jit_info_table_find (domain, ip);
847                 if (ji == NULL) {
848                         /* Unmanaged frame */
849                         mono_array_set (res, gpointer, i, sf);
850                         continue;
851                 }
852
853                 g_assert (ji != NULL);
854
855                 sf->method = mono_method_get_object (domain, ji->method, NULL);
856                 sf->native_offset = (char *)ip - (char *)ji->code_start;
857
858                 sf->il_offset = mono_debug_il_offset_from_address (ji->method, sf->native_offset, domain);
859
860                 if (need_file_info) {
861                         gchar *filename;
862                         
863                         filename = mono_debug_source_location_from_address (ji->method, sf->native_offset, &sf->line, domain);
864
865                         sf->filename = filename? mono_string_new (domain, filename): NULL;
866                         sf->column = 0;
867
868                         g_free (filename);
869                 }
870
871                 mono_array_set (res, gpointer, i, sf);
872         }
873
874         return res;
875 }
876
877 void
878 mono_jit_walk_stack (MonoStackWalk func, gpointer user_data) {
879         MonoDomain *domain = mono_domain_get ();
880         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
881         MonoLMF *lmf = jit_tls->lmf;
882         MonoJitInfo *ji, rji;
883         gint native_offset, il_offset;
884         gboolean managed;
885
886         MonoContext ctx, new_ctx;
887
888         MONO_CONTEXT_SET_IP (&ctx, __builtin_return_address (0));
889         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (1));
890
891         while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
892                 
893                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
894                 g_assert (ji);
895
896                 if (ji == (gpointer)-1)
897                         return;
898
899                 il_offset = mono_debug_il_offset_from_address (ji->method, native_offset, domain);
900
901                 if (func (ji->method, native_offset, il_offset, managed, user_data))
902                         return;
903                 
904                 ctx = new_ctx;
905         }
906 }
907
908 MonoBoolean
909 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info, 
910                           MonoReflectionMethod **method, 
911                           gint32 *iloffset, gint32 *native_offset,
912                           MonoString **file, gint32 *line, gint32 *column)
913 {
914         MonoDomain *domain = mono_domain_get ();
915         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
916         MonoLMF *lmf = jit_tls->lmf;
917         MonoJitInfo *ji, rji;
918         MonoContext ctx, new_ctx;
919
920         MONO_CONTEXT_SET_IP (&ctx, ves_icall_get_frame_info);
921         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (0));
922
923         skip++;
924
925         do {
926                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
927
928                 ctx = new_ctx;
929                 
930                 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
931                         return FALSE;
932
933                 /* skip all wrappers ??*/
934                 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
935                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
936                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
937                         continue;
938
939                 skip--;
940
941         } while (skip >= 0);
942
943         *method = mono_method_get_object (domain, ji->method, NULL);
944         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
945
946         if (need_file_info) {
947                 gchar *filename;
948
949                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
950
951                 *file = filename? mono_string_new (domain, filename): NULL;
952                 *column = 0;
953
954                 g_free (filename);
955         }
956
957         return TRUE;
958 }
959
960 /**
961  * arch_handle_exception:
962  * @ctx: saved processor state
963  * @obj: the exception object
964  * @test_only: only test if the exception is caught, but dont call handlers
965  *
966  *
967  */
968 gboolean
969 mono_arch_handle_exception (MonoContext *ctx, gpointer obj, gboolean test_only)
970 {
971         MonoDomain *domain = mono_domain_get ();
972         MonoJitInfo *ji, rji;
973         static int (*call_filter) (MonoContext *, gpointer) = NULL;
974         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
975         MonoLMF *lmf = jit_tls->lmf;            
976         GList *trace_ips = NULL;
977
978         g_assert (ctx != NULL);
979         if (!obj) {
980                 MonoException *ex = mono_get_exception_null_reference ();
981                 ex->message = mono_string_new (domain, 
982                         "Object reference not set to an instance of an object");
983                 obj = (MonoObject *)ex;
984         } 
985
986         g_assert (mono_object_isinst (obj, mono_defaults.exception_class));
987
988         if (!call_filter)
989                 call_filter = arch_get_call_filter ();
990
991         g_assert (jit_tls->end_of_stack);
992         g_assert (jit_tls->abort_func);
993
994         if (!test_only) {
995                 MonoContext ctx_cp = *ctx;
996                 if (mono_jit_trace_calls != NULL)
997                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
998                 if (!mono_arch_handle_exception (&ctx_cp, obj, TRUE)) {
999                         if (mono_break_on_exc)
1000                                 G_BREAKPOINT ();
1001                         mono_unhandled_exception (obj);
1002                 }
1003         }
1004
1005         while (1) {
1006                 MonoContext new_ctx;
1007                 char *trace = NULL;
1008                 
1009                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, ctx, &new_ctx, 
1010                                               test_only ? &trace : NULL, &lmf, NULL, NULL);
1011                 if (!ji) {
1012                         g_warning ("Exception inside function without unwind info");
1013                         g_assert_not_reached ();
1014                 }
1015
1016                 if (ji != (gpointer)-1) {
1017                         
1018                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
1019                                 char *tmp, *strace;
1020
1021                                 trace_ips = g_list_append (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1022
1023                                 if (!((MonoException*)obj)->stack_trace)
1024                                         strace = g_strdup ("");
1025                                 else
1026                                         strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1027                         
1028                                 tmp = g_strdup_printf ("%s%s\n", strace, trace);
1029                                 g_free (strace);
1030
1031                                 ((MonoException*)obj)->stack_trace = mono_string_new (domain, tmp);
1032
1033                                 g_free (tmp);
1034                         }
1035
1036                         if (ji->num_clauses) {
1037                                 int i;
1038                                 
1039                                 g_assert (ji->clauses);
1040                         
1041                                 for (i = 0; i < ji->num_clauses; i++) {
1042                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
1043
1044                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
1045                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
1046                                                 /* catch block */
1047
1048                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
1049                                                         /* store the exception object int cfg->excvar */
1050                                                         g_assert (ji->exvar_offset);
1051                                                         *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ji->exvar_offset)) = obj;
1052                                                 }
1053
1054                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
1055                                                      mono_object_isinst (obj, mono_class_get (ji->method->klass->image, ei->data.token))) ||
1056                                                     ((ei->flags == MONO_EXCEPTION_CLAUSE_FILTER &&
1057                                                       call_filter (ctx, ei->data.filter)))) {
1058                                                         if (test_only) {
1059                                                                 ((MonoException*)obj)->trace_ips = glist_to_array (trace_ips);
1060                                                                 g_list_free (trace_ips);
1061                                                                 g_free (trace);
1062                                                                 return TRUE;
1063                                                         }
1064                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
1065                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
1066                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1067                                                         jit_tls->lmf = lmf;
1068                                                         g_free (trace);
1069                                                         return 0;
1070                                                 }
1071                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
1072                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
1073                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
1074                                                         if (mono_jit_trace_calls != NULL && mono_trace_eval (ji->method))
1075                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
1076                                                         call_filter (ctx, ei->handler_start);
1077                                                 }
1078                                                 
1079                                         }
1080                                 }
1081                         }
1082                 }
1083
1084                 g_free (trace);
1085                         
1086                 *ctx = new_ctx;
1087
1088                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
1089                         if (!test_only) {
1090                                 jit_tls->lmf = lmf;
1091                                 jit_tls->abort_func (obj);
1092                                 g_assert_not_reached ();
1093                         } else {
1094                                 ((MonoException*)obj)->trace_ips = glist_to_array (trace_ips);
1095                                 g_list_free (trace_ips);
1096                                 return FALSE;
1097                         }
1098                 }
1099         }
1100
1101         g_assert_not_reached ();
1102 }
1103
1104