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