2010-05-14 Geoff Norton <gnorton@novell.com>
[mono.git] / mono / mini / exceptions-x86.c
1 /*
2  * exceptions-x86.c: exception support for x86
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/gc-internal.h>
22 #include <mono/metadata/mono-debug.h>
23 #include <mono/utils/mono-mmap.h>
24
25 #include "mini.h"
26 #include "mini-x86.h"
27 #include "tasklets.h"
28 #include "debug-mini.h"
29
30 static gpointer signal_exception_trampoline;
31
32 gpointer
33 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot) MONO_INTERNAL;
34
35 #ifdef TARGET_WIN32
36 static void (*restore_stack) (void *);
37
38 static MonoW32ExceptionHandler fpe_handler;
39 static MonoW32ExceptionHandler ill_handler;
40 static MonoW32ExceptionHandler segv_handler;
41
42 static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
43
44 #define W32_SEH_HANDLE_EX(_ex) \
45         if (_ex##_handler) _ex##_handler(0, er, sctx)
46
47 /*
48  * mono_win32_get_handle_stackoverflow (void):
49  *
50  * Returns a pointer to a method which restores the current context stack
51  * and calls handle_exceptions, when done restores the original stack.
52  */
53 static gpointer
54 mono_win32_get_handle_stackoverflow (void)
55 {
56         static guint8 *start = NULL;
57         guint8 *code;
58
59         if (start)
60                 return start;
61
62         /* restore_contect (void *sigctx) */
63         start = code = mono_global_codeman_reserve (128);
64
65         /* load context into ebx */
66         x86_mov_reg_membase (code, X86_EBX, X86_ESP, 4, 4);
67
68         /* move current stack into edi for later restore */
69         x86_mov_reg_reg (code, X86_EDI, X86_ESP, 4);
70
71         /* use the new freed stack from sigcontext */
72         x86_mov_reg_membase (code, X86_ESP, X86_EBX,  G_STRUCT_OFFSET (struct sigcontext, esp), 4);
73
74         /* get the current domain */
75         x86_call_code (code, mono_domain_get);
76
77         /* get stack overflow exception from domain object */
78         x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoDomain, stack_overflow_ex), 4);
79
80         /* call mono_arch_handle_exception (sctx, stack_overflow_exception_obj, FALSE) */
81         x86_push_imm (code, 0);
82         x86_push_reg (code, X86_EAX);
83         x86_push_reg (code, X86_EBX);
84         x86_call_code (code, mono_arch_handle_exception);
85
86         /* restore the SEH handler stack */
87         x86_mov_reg_reg (code, X86_ESP, X86_EDI, 4);
88
89         /* return */
90         x86_ret (code);
91
92         return start;
93 }
94
95 /* Special hack to workaround the fact that the
96  * when the SEH handler is called the stack is
97  * to small to recover.
98  *
99  * Stack walking part of this method is from mono_handle_exception
100  *
101  * The idea is simple; 
102  *  - walk the stack to free some space (64k)
103  *  - set esp to new stack location
104  *  - call mono_arch_handle_exception with stack overflow exception
105  *  - set esp to SEH handlers stack
106  *  - done
107  */
108 static void 
109 win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, struct sigcontext *sctx) 
110 {
111         SYSTEM_INFO si;
112         DWORD page_size;
113         MonoDomain *domain = mono_domain_get ();
114         MonoJitInfo rji;
115         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
116         MonoLMF *lmf = jit_tls->lmf;            
117         MonoContext initial_ctx;
118         MonoContext ctx;
119         guint32 free_stack = 0;
120         StackFrameInfo frame;
121
122         /* convert sigcontext to MonoContext (due to reuse of stack walking helpers */
123         mono_arch_sigctx_to_monoctx (sctx, &ctx);
124         
125         /* get our os page size */
126         GetSystemInfo(&si);
127         page_size = si.dwPageSize;
128
129         /* Let's walk the stack to recover
130          * the needed stack space (if possible)
131          */
132         memset (&rji, 0, sizeof (rji));
133
134         initial_ctx = ctx;
135         free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
136
137         /* try to free 64kb from our stack */
138         do {
139                 MonoContext new_ctx;
140
141                 mono_arch_find_jit_info_ext (domain, jit_tls, &rji, &ctx, &new_ctx, &lmf, &frame);
142                 if (!frame.ji) {
143                         g_warning ("Exception inside function without unwind info");
144                         g_assert_not_reached ();
145                 }
146
147                 if (frame.ji != (gpointer)-1) {
148                         free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
149                 }
150
151                 /* todo: we should call abort if ji is -1 */
152                 ctx = new_ctx;
153         } while (free_stack < 64 * 1024 && frame.ji != (gpointer) -1);
154
155         /* convert into sigcontext to be used in mono_arch_handle_exception */
156         mono_arch_monoctx_to_sigctx (&ctx, sctx);
157
158         /* todo: install new stack-guard page */
159
160         /* use the new stack and call mono_arch_handle_exception () */
161         restore_stack (sctx);
162 }
163
164 /*
165  * Unhandled Exception Filter
166  * Top-level per-process exception handler.
167  */
168 LONG CALLBACK seh_handler(EXCEPTION_POINTERS* ep)
169 {
170         EXCEPTION_RECORD* er;
171         CONTEXT* ctx;
172         struct sigcontext* sctx;
173         LONG res;
174
175         res = EXCEPTION_CONTINUE_EXECUTION;
176
177         er = ep->ExceptionRecord;
178         ctx = ep->ContextRecord;
179         sctx = g_malloc(sizeof(struct sigcontext));
180
181         /* Copy Win32 context to UNIX style context */
182         sctx->eax = ctx->Eax;
183         sctx->ebx = ctx->Ebx;
184         sctx->ecx = ctx->Ecx;
185         sctx->edx = ctx->Edx;
186         sctx->ebp = ctx->Ebp;
187         sctx->esp = ctx->Esp;
188         sctx->esi = ctx->Esi;
189         sctx->edi = ctx->Edi;
190         sctx->eip = ctx->Eip;
191
192         switch (er->ExceptionCode) {
193         case EXCEPTION_STACK_OVERFLOW:
194                 win32_handle_stack_overflow (ep, sctx);
195                 break;
196         case EXCEPTION_ACCESS_VIOLATION:
197                 W32_SEH_HANDLE_EX(segv);
198                 break;
199         case EXCEPTION_ILLEGAL_INSTRUCTION:
200                 W32_SEH_HANDLE_EX(ill);
201                 break;
202         case EXCEPTION_INT_DIVIDE_BY_ZERO:
203         case EXCEPTION_INT_OVERFLOW:
204         case EXCEPTION_FLT_DIVIDE_BY_ZERO:
205         case EXCEPTION_FLT_OVERFLOW:
206         case EXCEPTION_FLT_UNDERFLOW:
207         case EXCEPTION_FLT_INEXACT_RESULT:
208                 W32_SEH_HANDLE_EX(fpe);
209                 break;
210         default:
211                 break;
212         }
213
214         /* Copy context back */
215         ctx->Eax = sctx->eax;
216         ctx->Ebx = sctx->ebx;
217         ctx->Ecx = sctx->ecx;
218         ctx->Edx = sctx->edx;
219         ctx->Ebp = sctx->ebp;
220         ctx->Esp = sctx->esp;
221         ctx->Esi = sctx->esi;
222         ctx->Edi = sctx->edi;
223         ctx->Eip = sctx->eip;
224
225         g_free (sctx);
226
227         return res;
228 }
229
230 void win32_seh_init()
231 {
232         /* install restore stack helper */
233         if (!restore_stack)
234                 restore_stack = mono_win32_get_handle_stackoverflow ();
235
236         old_handler = SetUnhandledExceptionFilter(seh_handler);
237 }
238
239 void win32_seh_cleanup()
240 {
241         if (old_handler) SetUnhandledExceptionFilter(old_handler);
242 }
243
244 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
245 {
246         switch (type) {
247         case SIGFPE:
248                 fpe_handler = handler;
249                 break;
250         case SIGILL:
251                 ill_handler = handler;
252                 break;
253         case SIGSEGV:
254                 segv_handler = handler;
255                 break;
256         default:
257                 break;
258         }
259 }
260
261 #endif /* TARGET_WIN32 */
262
263 /*
264  * mono_arch_get_restore_context:
265  *
266  * Returns a pointer to a method which restores a previously saved sigcontext.
267  */
268 gpointer
269 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
270 {
271         guint8 *start = NULL;
272         guint8 *code;
273         MonoJumpInfo *ji = NULL;
274         GSList *unwind_ops = NULL;
275
276         /* restore_contect (MonoContext *ctx) */
277
278         start = code = mono_global_codeman_reserve (128);
279         
280         /* load ctx */
281         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
282
283         /* get return address, stored in ECX */
284         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, eip), 4);
285         /* restore EBX */
286         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebx), 4);
287         /* restore EDI */
288         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edi), 4);
289         /* restore ESI */
290         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esi), 4);
291         /* restore ESP */
292         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esp), 4);
293         /* save the return addr to the restored stack */
294         x86_push_reg (code, X86_ECX);
295         /* restore EBP */
296         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebp), 4);
297         /* restore ECX */
298         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ecx), 4);
299         /* restore EDX */
300         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edx), 4);
301         /* restore EAX */
302         x86_mov_reg_membase (code, X86_EAX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, eax), 4);
303
304         /* jump to the saved IP */
305         x86_ret (code);
306
307         if (info)
308                 *info = mono_tramp_info_create (g_strdup_printf ("restore_context"), start, code - start, ji, unwind_ops);
309
310         return start;
311 }
312
313 /*
314  * mono_arch_get_call_filter:
315  *
316  * Returns a pointer to a method which calls an exception filter. We
317  * also use this function to call finally handlers (we pass NULL as 
318  * @exc object in this case).
319  */
320 gpointer
321 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
322 {
323         guint8* start;
324         guint8 *code;
325         MonoJumpInfo *ji = NULL;
326         GSList *unwind_ops = NULL;
327
328         /* call_filter (MonoContext *ctx, unsigned long eip) */
329         start = code = mono_global_codeman_reserve (64);
330
331         x86_push_reg (code, X86_EBP);
332         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
333         x86_push_reg (code, X86_EBX);
334         x86_push_reg (code, X86_EDI);
335         x86_push_reg (code, X86_ESI);
336
337         /* load ctx */
338         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
339         /* load eip */
340         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
341         /* save EBP */
342         x86_push_reg (code, X86_EBP);
343
344         /* set new EBP */
345         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebp), 4);
346         /* restore registers used by global register allocation (EBX & ESI) */
347         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebx), 4);
348         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esi), 4);
349         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edi), 4);
350
351         /* align stack and save ESP */
352         x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
353         x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
354         g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
355         x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
356         x86_push_reg (code, X86_EDX);
357
358         /* call the handler */
359         x86_call_reg (code, X86_ECX);
360
361         /* restore ESP */
362         x86_pop_reg (code, X86_ESP);
363
364         /* restore EBP */
365         x86_pop_reg (code, X86_EBP);
366
367         /* restore saved regs */
368         x86_pop_reg (code, X86_ESI);
369         x86_pop_reg (code, X86_EDI);
370         x86_pop_reg (code, X86_EBX);
371         x86_leave (code);
372         x86_ret (code);
373
374         if (info)
375                 *info = mono_tramp_info_create (g_strdup_printf ("call_filter"), start, code - start, ji, unwind_ops);
376
377         g_assert ((code - start) < 64);
378         return start;
379 }
380
381 /*
382  * mono_x86_throw_exception:
383  *
384  *   C function called from the throw trampolines.
385  */
386 void
387 mono_x86_throw_exception (mgreg_t *regs, MonoObject *exc, 
388                                                   mgreg_t eip, gboolean rethrow)
389 {
390         static void (*restore_context) (MonoContext *);
391         MonoContext ctx;
392
393         if (!restore_context)
394                 restore_context = mono_get_restore_context ();
395
396         ctx.esp = regs [X86_ESP];
397         ctx.eip = eip;
398         ctx.ebp = regs [X86_EBP];
399         ctx.edi = regs [X86_EDI];
400         ctx.esi = regs [X86_ESI];
401         ctx.ebx = regs [X86_EBX];
402         ctx.edx = regs [X86_EDX];
403         ctx.ecx = regs [X86_ECX];
404         ctx.eax = regs [X86_EAX];
405
406 #ifdef __APPLE__
407         /* The OSX ABI specifies 16 byte alignment at call sites */
408         g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
409 #endif
410
411         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
412                 MonoException *mono_ex = (MonoException*)exc;
413                 if (!rethrow)
414                         mono_ex->stack_trace = NULL;
415         }
416
417         if (mono_debug_using_mono_debugger ()) {
418                 guint8 buf [16], *code;
419
420                 mono_breakpoint_clean_code (NULL, (gpointer)eip, 8, buf, sizeof (buf));
421                 code = buf + 8;
422
423                 if (buf [3] == 0xe8) {
424                         MonoContext ctx_cp = ctx;
425                         ctx_cp.eip = eip - 5;
426
427                         if (mono_debugger_handle_exception (&ctx_cp, exc)) {
428                                 restore_context (&ctx_cp);
429                                 g_assert_not_reached ();
430                         }
431                 }
432         }
433
434         /* adjust eip so that it point into the call instruction */
435         ctx.eip -= 1;
436
437         mono_handle_exception (&ctx, exc, (gpointer)eip, FALSE);
438
439         restore_context (&ctx);
440
441         g_assert_not_reached ();
442 }
443
444 void
445 mono_x86_throw_corlib_exception (mgreg_t *regs, guint32 ex_token_index, 
446                                                                  mgreg_t eip, gint32 pc_offset)
447 {
448         guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
449         MonoException *ex;
450
451         ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
452
453         eip -= pc_offset;
454
455         mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
456 }
457
458 /*
459  * get_throw_exception:
460  *
461  *  Generate a call to mono_x86_throw_exception/
462  * mono_x86_throw_corlib_exception.
463  * If LLVM is true, generate code which assumes the caller is LLVM generated code, 
464  * which doesn't push the arguments.
465  */
466 static guint8*
467 get_throw_exception (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, MonoTrampInfo **info, gboolean aot)
468 {
469         guint8 *start, *code;
470         int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
471         MonoJumpInfo *ji = NULL;
472         GSList *unwind_ops = NULL;
473
474         start = code = mono_global_codeman_reserve (128);
475
476         stack_size = 128;
477
478         /* 
479          * On apple, the stack is misaligned by the pushing of the return address.
480          */
481         if (!llvm && corlib)
482                 /* On OSX, we don't generate alignment code to save space */
483                 stack_size += 4;
484         else
485                 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
486
487         /*
488          * The stack looks like this:
489          * <pc offset> (only if corlib is TRUE)
490          * <exception object>/<type token>
491          * <return addr> <- esp (unaligned on apple)
492          */
493
494         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
495         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
496
497         /* Alloc frame */
498         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
499         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
500
501         arg_offsets [0] = 0;
502         arg_offsets [1] = 4;
503         arg_offsets [2] = 8;
504         arg_offsets [3] = 12;
505         regs_offset = 16;
506
507         /* Save registers */
508         for (i = 0; i < X86_NREG; ++i)
509                 if (i != X86_ESP)
510                         x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
511         /* Calculate the offset between the current sp and the sp of the caller */
512         if (llvm) {
513                 /* LLVM doesn't push the arguments */
514                 stack_offset = stack_size + 4;
515         } else {
516                 if (corlib) {
517                         /* Two arguments */
518                         stack_offset = stack_size + 4 + 8;
519 #ifdef __APPLE__
520                         /* We don't generate stack alignment code on osx to save space */
521 #endif
522                 } else {
523                         /* One argument */
524                         stack_offset = stack_size + 4 + 4;
525 #ifdef __APPLE__
526                         /* Pop the alignment added by OP_THROW too */
527                         stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
528 #endif
529                 }
530         }
531         /* Save ESP */
532         x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
533         x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
534
535         /* Set arg1 == regs */
536         x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
537         x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
538         /* Set arg2 == exc */
539         x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
540         x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
541         /* Set arg3 == eip */
542         x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
543         x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
544         if (corlib) {
545                 /* Set arg4 == offset */
546                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
547                 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
548         } else {
549                 /* Set arg4 == rethrow */
550                 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
551         }
552         /* Make the call */
553         if (aot) {
554                 // This can be called from runtime code, which can't guarantee that
555                 // ebx contains the got address.
556                 // So emit the got address loading code too
557                 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
558                 code = mono_arch_emit_load_aotconst (start, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, corlib ? "mono_x86_throw_corlib_exception" : "mono_x86_throw_exception");
559                 x86_call_reg (code, X86_EAX);
560         } else {
561                 x86_call_code (code, corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception);
562         }
563         x86_breakpoint (code);
564
565         g_assert ((code - start) < 128);
566
567         mono_save_trampoline_xdebug_info (corlib ? "llvm_throw_corlib_exception_trampoline" : "llvm_throw_exception_trampoline", start, code - start, unwind_ops);
568
569         if (info)
570                 *info = mono_tramp_info_create (g_strdup_printf (corlib ? "throw_corlib_exception" : (rethrow ? "rethrow_exception" : "throw_exception")), start, code - start, ji, unwind_ops);
571
572         return start;
573 }
574
575 /**
576  * mono_arch_get_throw_exception:
577  *
578  * Returns a function pointer which can be used to raise 
579  * exceptions. The returned function has the following 
580  * signature: void (*func) (MonoException *exc); 
581  * For example to raise an arithmetic exception you can use:
582  *
583  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
584  * x86_call_code (code, arch_get_throw_exception ()); 
585  *
586  */
587 gpointer 
588 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
589 {
590         return get_throw_exception ("throw_exception_trampoline", FALSE, FALSE, FALSE, info, aot);
591 }
592
593 gpointer 
594 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
595 {
596         return get_throw_exception ("rethow_exception_trampoline", TRUE, FALSE, FALSE, info, aot);
597 }
598
599 /**
600  * mono_arch_get_throw_corlib_exception:
601  *
602  * Returns a function pointer which can be used to raise 
603  * corlib exceptions. The returned function has the following 
604  * signature: void (*func) (guint32 ex_token, guint32 offset); 
605  * Here, offset is the offset which needs to be substracted from the caller IP 
606  * to get the IP of the throw. Passing the offset has the advantage that it 
607  * needs no relocations in the caller.
608  */
609 gpointer 
610 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
611 {
612         return get_throw_exception ("throw_corlib_exception_trampoline", FALSE, FALSE, TRUE, info, aot);
613 }
614
615 void
616 mono_arch_exceptions_init (void)
617 {
618         guint8 *tramp;
619
620         if (mono_aot_only) {
621                 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
622                 return;
623         }
624
625         /* LLVM needs different throw trampolines */
626         tramp = get_throw_exception ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, NULL, FALSE);
627
628         mono_register_jit_icall (tramp, "mono_arch_llvm_throw_exception", NULL, TRUE);
629
630         tramp = get_throw_exception ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, NULL, FALSE);
631
632         mono_register_jit_icall (tramp, "mono_arch_llvm_throw_corlib_exception", NULL, TRUE);
633
634         signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (NULL, FALSE);
635 }
636
637 /*
638  * mono_arch_find_jit_info_ext:
639  *
640  * See exceptions-amd64.c for docs.
641  */
642 gboolean
643 mono_arch_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls, 
644                                                          MonoJitInfo *ji, MonoContext *ctx, 
645                                                          MonoContext *new_ctx, MonoLMF **lmf, 
646                                                          StackFrameInfo *frame)
647 {
648         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
649
650         memset (frame, 0, sizeof (StackFrameInfo));
651         frame->ji = ji;
652         frame->managed = FALSE;
653
654         *new_ctx = *ctx;
655
656         if (ji != NULL) {
657                 gssize regs [MONO_MAX_IREGS + 1];
658                 guint8 *cfa;
659                 guint32 unwind_info_len;
660                 guint8 *unwind_info;
661
662                 frame->type = FRAME_TYPE_MANAGED;
663
664                 if (!ji->method->wrapper_type || ji->method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
665                         frame->managed = TRUE;
666
667                 if (ji->from_aot)
668                         unwind_info = mono_aot_get_unwind_info (ji, &unwind_info_len);
669                 else
670                         unwind_info = mono_get_cached_unwind_info (ji->used_regs, &unwind_info_len);
671
672                 regs [X86_EAX] = new_ctx->eax;
673                 regs [X86_EBX] = new_ctx->ebx;
674                 regs [X86_ECX] = new_ctx->ecx;
675                 regs [X86_EDX] = new_ctx->edx;
676                 regs [X86_ESP] = new_ctx->esp;
677                 regs [X86_EBP] = new_ctx->ebp;
678                 regs [X86_ESI] = new_ctx->esi;
679                 regs [X86_EDI] = new_ctx->edi;
680                 regs [X86_NREG] = new_ctx->eip;
681
682                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
683                                                    (guint8*)ji->code_start + ji->code_size,
684                                                    ip, regs, MONO_MAX_IREGS + 1, &cfa);
685
686                 new_ctx->eax = regs [X86_EAX];
687                 new_ctx->ebx = regs [X86_EBX];
688                 new_ctx->ecx = regs [X86_ECX];
689                 new_ctx->edx = regs [X86_EDX];
690                 new_ctx->esp = regs [X86_ESP];
691                 new_ctx->ebp = regs [X86_EBP];
692                 new_ctx->esi = regs [X86_ESI];
693                 new_ctx->edi = regs [X86_EDI];
694                 new_ctx->eip = regs [X86_NREG];
695
696                 /* The CFA becomes the new SP value */
697                 new_ctx->esp = (gssize)cfa;
698
699                 /* Adjust IP */
700                 new_ctx->eip --;
701
702                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
703                         /* remove any unused lmf */
704                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
705                 }
706
707                 /* Pop arguments off the stack */
708                 /* 
709                  * FIXME: LLVM doesn't push these, we can't use ji->from_llvm as it describes
710                  * the caller.
711                  */
712 #ifndef ENABLE_LLVM
713                 {
714                         MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (ji->method)->param_count + 1);
715
716                         guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (ji->method), mono_method_signature (ji->method)->param_count, arg_info);
717                         new_ctx->esp += stack_to_pop;
718                 }
719 #endif
720
721                 return TRUE;
722         } else if (*lmf) {
723
724                 if (((guint64)(*lmf)->previous_lmf) & 2) {
725                         /* 
726                          * This LMF entry is created by the soft debug code to mark transitions to
727                          * managed code done during invokes.
728                          */
729                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
730
731                         g_assert (ext->debugger_invoke);
732
733                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
734
735                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
736
737                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
738
739                         return TRUE;
740                 }
741                 
742                 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
743                 } else {
744                         if (!((guint32)((*lmf)->previous_lmf) & 1))
745                                 /* Top LMF entry */
746                                 return FALSE;
747                         /* Trampoline lmf frame */
748                         frame->method = (*lmf)->method;
749                 }
750
751                 new_ctx->esi = (*lmf)->esi;
752                 new_ctx->edi = (*lmf)->edi;
753                 new_ctx->ebx = (*lmf)->ebx;
754                 new_ctx->ebp = (*lmf)->ebp;
755                 new_ctx->eip = (*lmf)->eip;
756
757                 frame->ji = ji;
758                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
759
760                 /* Check if we are in a trampoline LMF frame */
761                 if ((guint32)((*lmf)->previous_lmf) & 1) {
762                         /* lmf->esp is set by the trampoline code */
763                         new_ctx->esp = (*lmf)->esp;
764
765                         /* Pop arguments off the stack */
766                         /* FIXME: Handle the delegate case too ((*lmf)->method == NULL) */
767                         /* FIXME: Handle the IMT/vtable case too */
768 #ifndef ENABLE_LLVM
769                         if ((*lmf)->method && (*lmf)->method != MONO_FAKE_IMT_METHOD && (*lmf)->method != MONO_FAKE_VTABLE_METHOD) {
770                                 MonoMethod *method = (*lmf)->method;
771                                 MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (method)->param_count + 1);
772
773                                 guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (method), mono_method_signature (method)->param_count, arg_info);
774                                 new_ctx->esp += stack_to_pop;
775                         }
776 #endif
777                 }
778                 else
779                         /* the lmf is always stored on the stack, so the following
780                          * expression points to a stack location which can be used as ESP */
781                         new_ctx->esp = (unsigned long)&((*lmf)->eip);
782
783                 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
784
785                 return TRUE;
786         }
787
788         return FALSE;
789 }
790
791 #ifdef __sun
792 #define REG_EAX EAX
793 #define REG_EBX EBX
794 #define REG_ECX ECX
795 #define REG_EDX EDX
796 #define REG_EBP EBP
797 #define REG_ESP ESP
798 #define REG_ESI ESI
799 #define REG_EDI EDI
800 #define REG_EIP EIP
801 #endif
802
803 void
804 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
805 {
806 #ifdef MONO_ARCH_USE_SIGACTION
807         ucontext_t *ctx = (ucontext_t*)sigctx;
808         
809         mctx->eax = UCONTEXT_REG_EAX (ctx);
810         mctx->ebx = UCONTEXT_REG_EBX (ctx);
811         mctx->ecx = UCONTEXT_REG_ECX (ctx);
812         mctx->edx = UCONTEXT_REG_EDX (ctx);
813         mctx->ebp = UCONTEXT_REG_EBP (ctx);
814         mctx->esp = UCONTEXT_REG_ESP (ctx);
815         mctx->esi = UCONTEXT_REG_ESI (ctx);
816         mctx->edi = UCONTEXT_REG_EDI (ctx);
817         mctx->eip = UCONTEXT_REG_EIP (ctx);
818 #else   
819         struct sigcontext *ctx = (struct sigcontext *)sigctx;
820
821         mctx->eax = ctx->SC_EAX;
822         mctx->ebx = ctx->SC_EBX;
823         mctx->ecx = ctx->SC_ECX;
824         mctx->edx = ctx->SC_EDX;
825         mctx->ebp = ctx->SC_EBP;
826         mctx->esp = ctx->SC_ESP;
827         mctx->esi = ctx->SC_ESI;
828         mctx->edi = ctx->SC_EDI;
829         mctx->eip = ctx->SC_EIP;
830 #endif
831 }
832
833 void
834 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
835 {
836 #ifdef MONO_ARCH_USE_SIGACTION
837         ucontext_t *ctx = (ucontext_t*)sigctx;
838
839         UCONTEXT_REG_EAX (ctx) = mctx->eax;
840         UCONTEXT_REG_EBX (ctx) = mctx->ebx;
841         UCONTEXT_REG_ECX (ctx) = mctx->ecx;
842         UCONTEXT_REG_EDX (ctx) = mctx->edx;
843         UCONTEXT_REG_EBP (ctx) = mctx->ebp;
844         UCONTEXT_REG_ESP (ctx) = mctx->esp;
845         UCONTEXT_REG_ESI (ctx) = mctx->esi;
846         UCONTEXT_REG_EDI (ctx) = mctx->edi;
847         UCONTEXT_REG_EIP (ctx) = mctx->eip;
848 #else
849         struct sigcontext *ctx = (struct sigcontext *)sigctx;
850
851         ctx->SC_EAX = mctx->eax;
852         ctx->SC_EBX = mctx->ebx;
853         ctx->SC_ECX = mctx->ecx;
854         ctx->SC_EDX = mctx->edx;
855         ctx->SC_EBP = mctx->ebp;
856         ctx->SC_ESP = mctx->esp;
857         ctx->SC_ESI = mctx->esi;
858         ctx->SC_EDI = mctx->edi;
859         ctx->SC_EIP = mctx->eip;
860 #endif
861 }       
862
863 gpointer
864 mono_arch_ip_from_context (void *sigctx)
865 {
866 #ifdef MONO_ARCH_USE_SIGACTION
867         ucontext_t *ctx = (ucontext_t*)sigctx;
868         return (gpointer)UCONTEXT_REG_EIP (ctx);
869 #else
870         struct sigcontext *ctx = sigctx;
871         return (gpointer)ctx->SC_EIP;
872 #endif  
873 }
874
875 /*
876  * handle_exception:
877  *
878  *   Called by resuming from a signal handler.
879  */
880 static void
881 handle_signal_exception (gpointer obj)
882 {
883         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
884         MonoContext ctx;
885         static void (*restore_context) (MonoContext *);
886
887         if (!restore_context)
888                 restore_context = mono_get_restore_context ();
889
890         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
891
892         if (mono_debugger_handle_exception (&ctx, (MonoObject *)obj))
893                 return;
894
895         mono_handle_exception (&ctx, obj, MONO_CONTEXT_GET_IP (&ctx), FALSE);
896
897         restore_context (&ctx);
898 }
899
900 /*
901  * mono_x86_get_signal_exception_trampoline:
902  *
903  *   This x86 specific trampoline is used to call handle_signal_exception.
904  */
905 gpointer
906 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
907 {
908         guint8 *start, *code;
909         MonoJumpInfo *ji = NULL;
910         GSList *unwind_ops = NULL;
911         int stack_size;
912
913         start = code = mono_global_codeman_reserve (128);
914
915         /* Caller ip */
916         x86_push_reg (code, X86_ECX);
917
918         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
919         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
920
921         /* Fix the alignment to be what apple expects */
922         stack_size = 12;
923
924         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
925         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
926
927         /* Arg1 */
928         x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
929         /* Branch to target */
930         x86_call_reg (code, X86_EDX);
931
932         g_assert ((code - start) < 128);
933
934         mono_save_trampoline_xdebug_info ("x86_signal_exception_trampoline", start, code - start, unwind_ops);
935
936         if (info)
937                 *info = mono_tramp_info_create (g_strdup ("x86_signal_exception_trampoline"), start, code - start, ji, unwind_ops);
938
939         return start;
940 }
941
942 gboolean
943 mono_arch_handle_exception (void *sigctx, gpointer obj, gboolean test_only)
944 {
945 #if defined(MONO_ARCH_USE_SIGACTION)
946         /*
947          * Handling the exception in the signal handler is problematic, since the original
948          * signal is disabled, and we could run arbitrary code though the debugger. So
949          * resume into the normal stack and do most work there if possible.
950          */
951         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
952         guint64 sp = UCONTEXT_REG_ESP (sigctx);
953
954         /* Pass the ctx parameter in TLS */
955         mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
956         /*
957          * Can't pass the obj on the stack, since we are executing on the
958          * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
959          * So put it into a register, and branch to a trampoline which
960          * pushes it.
961          */
962         g_assert (!test_only);
963         UCONTEXT_REG_EAX (sigctx) = (gsize)obj;
964         UCONTEXT_REG_ECX (sigctx) = UCONTEXT_REG_EIP (sigctx);
965         UCONTEXT_REG_EDX (sigctx) = (gsize)handle_signal_exception;
966
967         /* Allocate a stack frame, align it to 16 bytes which is needed on apple */
968         sp -= 16;
969         sp &= ~15;
970         UCONTEXT_REG_ESP (sigctx) = sp;
971
972         UCONTEXT_REG_EIP (sigctx) = (gsize)signal_exception_trampoline;
973
974         return TRUE;
975 #else
976         MonoContext mctx;
977
978         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
979
980         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj))
981                 return TRUE;
982
983         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, test_only);
984
985         mono_arch_monoctx_to_sigctx (&mctx, sigctx);
986
987         return TRUE;
988 #endif
989 }
990
991 static void
992 restore_soft_guard_pages (void)
993 {
994         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
995         if (jit_tls->stack_ovf_guard_base)
996                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
997 }
998
999 /* 
1000  * this function modifies mctx so that when it is restored, it
1001  * won't execcute starting at mctx.eip, but in a function that
1002  * will restore the protection on the soft-guard pages and return back to
1003  * continue at mctx.eip.
1004  */
1005 static void
1006 prepare_for_guard_pages (MonoContext *mctx)
1007 {
1008         gpointer *sp;
1009         sp = (gpointer)(mctx->esp);
1010         sp -= 1;
1011         /* the resturn addr */
1012         sp [0] = (gpointer)(mctx->eip);
1013         mctx->eip = (unsigned long)restore_soft_guard_pages;
1014         mctx->esp = (unsigned long)sp;
1015 }
1016
1017 static void
1018 altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean stack_ovf)
1019 {
1020         void (*restore_context) (MonoContext *);
1021         MonoContext mctx;
1022
1023         restore_context = mono_get_restore_context ();
1024         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1025
1026         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj)) {
1027                 if (stack_ovf)
1028                         prepare_for_guard_pages (&mctx);
1029                 restore_context (&mctx);
1030         }
1031
1032         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, FALSE);
1033         if (stack_ovf)
1034                 prepare_for_guard_pages (&mctx);
1035         restore_context (&mctx);
1036 }
1037
1038 void
1039 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
1040 {
1041 #ifdef MONO_ARCH_USE_SIGACTION
1042         MonoException *exc = NULL;
1043         ucontext_t *ctx = (ucontext_t*)sigctx;
1044         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1045         gpointer *sp;
1046         int frame_size;
1047
1048         /* if we didn't find a managed method for the ip address and it matches the fault
1049          * address, we assume we followed a broken pointer during an indirect call, so
1050          * we try the lookup again with the return address pushed on the stack
1051          */
1052         if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1053                 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1054                 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1055                 if (ji)
1056                         UCONTEXT_REG_EIP (ctx) = sp [0];
1057         }
1058         if (stack_ovf)
1059                 exc = mono_domain_get ()->stack_overflow_ex;
1060         if (!ji)
1061                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
1062         /* setup a call frame on the real stack so that control is returned there
1063          * and exception handling can continue.
1064          * If this was a stack overflow the caller already ensured the stack pages
1065          * needed have been unprotected.
1066          * The frame looks like:
1067          *   ucontext struct
1068          *   test_only arg
1069          *   exception arg
1070          *   ctx arg
1071          *   return ip
1072          */
1073         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 4;
1074         frame_size += 15;
1075         frame_size &= ~15;
1076         sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1077         sp = (gpointer)((char*)sp - frame_size);
1078         /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1079          * goes at sp [-1]
1080          */
1081         sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1082         sp [0] = sp + 4;
1083         sp [1] = exc;
1084         sp [2] = (gpointer)stack_ovf;
1085         /* may need to adjust pointers in the new struct copy, depending on the OS */
1086         memcpy (sp + 4, ctx, sizeof (ucontext_t));
1087         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1088         UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1089         UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1090 #endif
1091 }
1092
1093 #if MONO_SUPPORT_TASKLETS
1094 MonoContinuationRestore
1095 mono_tasklets_arch_restore (void)
1096 {
1097         static guint8* saved = NULL;
1098         guint8 *code, *start;
1099
1100         if (saved)
1101                 return (MonoContinuationRestore)saved;
1102         code = start = mono_global_codeman_reserve (48);
1103         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1104         /* put cont in edx */
1105         x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1106         /* setup the copy of the stack */
1107         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1108         x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1109         x86_cld (code);
1110         x86_mov_reg_membase (code, X86_ESI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1111         x86_mov_reg_membase (code, X86_EDI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1112         x86_prefix (code, X86_REP_PREFIX);
1113         x86_movsl (code);
1114
1115         /* now restore the registers from the LMF */
1116         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1117         x86_mov_reg_membase (code, X86_EBX, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebx), 4);
1118         x86_mov_reg_membase (code, X86_EBP, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebp), 4);
1119         x86_mov_reg_membase (code, X86_ESI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, esi), 4);
1120         x86_mov_reg_membase (code, X86_EDI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, edi), 4);
1121
1122         /* restore the lmf chain */
1123         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1124         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1125
1126         /* state in eax, so it's setup as the return value */
1127         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1128         x86_jump_membase (code, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_ip));
1129         g_assert ((code - start) <= 48);
1130         saved = start;
1131         return (MonoContinuationRestore)saved;
1132 }
1133 #endif
1134