2010-06-17 Zoltan Varga <vargaz@gmail.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         /* Negate the ip adjustment done in mono_x86_throw_exception () */
456         eip += 1;
457
458         mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
459 }
460
461 /*
462  * get_throw_exception:
463  *
464  *  Generate a call to mono_x86_throw_exception/
465  * mono_x86_throw_corlib_exception.
466  * If LLVM is true, generate code which assumes the caller is LLVM generated code, 
467  * which doesn't push the arguments.
468  */
469 static guint8*
470 get_throw_exception (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, MonoTrampInfo **info, gboolean aot)
471 {
472         guint8 *start, *code;
473         int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
474         MonoJumpInfo *ji = NULL;
475         GSList *unwind_ops = NULL;
476
477         start = code = mono_global_codeman_reserve (128);
478
479         stack_size = 128;
480
481         /* 
482          * On apple, the stack is misaligned by the pushing of the return address.
483          */
484         if (!llvm && corlib)
485                 /* On OSX, we don't generate alignment code to save space */
486                 stack_size += 4;
487         else
488                 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
489
490         /*
491          * The stack looks like this:
492          * <pc offset> (only if corlib is TRUE)
493          * <exception object>/<type token>
494          * <return addr> <- esp (unaligned on apple)
495          */
496
497         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
498         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
499
500         /* Alloc frame */
501         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
502         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
503
504         arg_offsets [0] = 0;
505         arg_offsets [1] = 4;
506         arg_offsets [2] = 8;
507         arg_offsets [3] = 12;
508         regs_offset = 16;
509
510         /* Save registers */
511         for (i = 0; i < X86_NREG; ++i)
512                 if (i != X86_ESP)
513                         x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
514         /* Calculate the offset between the current sp and the sp of the caller */
515         if (llvm) {
516                 /* LLVM doesn't push the arguments */
517                 stack_offset = stack_size + 4;
518         } else {
519                 if (corlib) {
520                         /* Two arguments */
521                         stack_offset = stack_size + 4 + 8;
522 #ifdef __APPLE__
523                         /* We don't generate stack alignment code on osx to save space */
524 #endif
525                 } else {
526                         /* One argument */
527                         stack_offset = stack_size + 4 + 4;
528 #ifdef __APPLE__
529                         /* Pop the alignment added by OP_THROW too */
530                         stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
531 #endif
532                 }
533         }
534         /* Save ESP */
535         x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
536         x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
537
538         /* Set arg1 == regs */
539         x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
540         x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
541         /* Set arg2 == exc */
542         x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
543         x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
544         /* Set arg3 == eip */
545         if (llvm_abs)
546                 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
547         else
548                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
549         x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
550         if (corlib) {
551                 /* Set arg4 == offset */
552                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
553                 if (llvm_abs) {
554                         /* 
555                          * The caller is LLVM code which passes the absolute address not a pc offset,
556                          * so compensate by passing 0 as 'ip' and passing the negated abs address as
557                          * the pc offset.
558                          */
559                         x86_neg_reg (code, X86_EAX);
560                 }
561                 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
562         } else {
563                 /* Set arg4 == rethrow */
564                 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
565         }
566         /* Make the call */
567         if (aot) {
568                 // This can be called from runtime code, which can't guarantee that
569                 // ebx contains the got address.
570                 // So emit the got address loading code too
571                 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
572                 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");
573                 x86_call_reg (code, X86_EAX);
574         } else {
575                 x86_call_code (code, corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception);
576         }
577         x86_breakpoint (code);
578
579         g_assert ((code - start) < 128);
580
581         mono_save_trampoline_xdebug_info (corlib ? (llvm_abs ? "llvm_throw_corlib_exception_trampoline" : "llvm_throw_corlib_exception_trampoline") : "llvm_throw_exception_trampoline", start, code - start, unwind_ops);
582
583         if (info)
584                 *info = mono_tramp_info_create (g_strdup_printf (corlib ? "throw_corlib_exception" : (rethrow ? "rethrow_exception" : "throw_exception")), start, code - start, ji, unwind_ops);
585
586         return start;
587 }
588
589 /**
590  * mono_arch_get_throw_exception:
591  *
592  * Returns a function pointer which can be used to raise 
593  * exceptions. The returned function has the following 
594  * signature: void (*func) (MonoException *exc); 
595  * For example to raise an arithmetic exception you can use:
596  *
597  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
598  * x86_call_code (code, arch_get_throw_exception ()); 
599  *
600  */
601 gpointer 
602 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
603 {
604         return get_throw_exception ("throw_exception_trampoline", FALSE, FALSE, FALSE, FALSE, info, aot);
605 }
606
607 gpointer 
608 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
609 {
610         return get_throw_exception ("rethow_exception_trampoline", TRUE, FALSE, FALSE, FALSE, info, aot);
611 }
612
613 /**
614  * mono_arch_get_throw_corlib_exception:
615  *
616  * Returns a function pointer which can be used to raise 
617  * corlib exceptions. The returned function has the following 
618  * signature: void (*func) (guint32 ex_token, guint32 offset); 
619  * Here, offset is the offset which needs to be substracted from the caller IP 
620  * to get the IP of the throw. Passing the offset has the advantage that it 
621  * needs no relocations in the caller.
622  */
623 gpointer 
624 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
625 {
626         return get_throw_exception ("throw_corlib_exception_trampoline", FALSE, FALSE, TRUE, FALSE, info, aot);
627 }
628
629 void
630 mono_arch_exceptions_init (void)
631 {
632         guint8 *tramp;
633
634         if (mono_aot_only) {
635                 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
636                 return;
637         }
638
639         /* LLVM needs different throw trampolines */
640         tramp = get_throw_exception ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, NULL, FALSE);
641         mono_register_jit_icall (tramp, "mono_arch_llvm_throw_exception", NULL, TRUE);
642
643         tramp = get_throw_exception ("llvm_rethrow_exception_trampoline", FALSE, TRUE, FALSE, FALSE, NULL, FALSE);
644         mono_register_jit_icall (tramp, "mono_arch_llvm_rethrow_exception", NULL, TRUE);
645
646         tramp = get_throw_exception ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, NULL, FALSE);
647         mono_register_jit_icall (tramp, "mono_arch_llvm_throw_corlib_exception", NULL, TRUE);
648
649         tramp = get_throw_exception ("llvm_throw_corlib_exception_trampoline_abs", FALSE, TRUE, TRUE, TRUE, NULL, FALSE);
650         mono_register_jit_icall (tramp, "mono_arch_llvm_throw_corlib_exception_abs", NULL, TRUE);
651
652         signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (NULL, FALSE);
653 }
654
655 /*
656  * mono_arch_find_jit_info_ext:
657  *
658  * See exceptions-amd64.c for docs.
659  */
660 gboolean
661 mono_arch_find_jit_info_ext (MonoDomain *domain, MonoJitTlsData *jit_tls, 
662                                                          MonoJitInfo *ji, MonoContext *ctx, 
663                                                          MonoContext *new_ctx, MonoLMF **lmf, 
664                                                          StackFrameInfo *frame)
665 {
666         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
667
668         memset (frame, 0, sizeof (StackFrameInfo));
669         frame->ji = ji;
670         frame->managed = FALSE;
671
672         *new_ctx = *ctx;
673
674         if (ji != NULL) {
675                 gssize regs [MONO_MAX_IREGS + 1];
676                 guint8 *cfa;
677                 guint32 unwind_info_len;
678                 guint8 *unwind_info;
679
680                 frame->type = FRAME_TYPE_MANAGED;
681
682                 if (!ji->method->wrapper_type || ji->method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
683                         frame->managed = TRUE;
684
685                 if (ji->from_aot)
686                         unwind_info = mono_aot_get_unwind_info (ji, &unwind_info_len);
687                 else
688                         unwind_info = mono_get_cached_unwind_info (ji->used_regs, &unwind_info_len);
689
690                 regs [X86_EAX] = new_ctx->eax;
691                 regs [X86_EBX] = new_ctx->ebx;
692                 regs [X86_ECX] = new_ctx->ecx;
693                 regs [X86_EDX] = new_ctx->edx;
694                 regs [X86_ESP] = new_ctx->esp;
695                 regs [X86_EBP] = new_ctx->ebp;
696                 regs [X86_ESI] = new_ctx->esi;
697                 regs [X86_EDI] = new_ctx->edi;
698                 regs [X86_NREG] = new_ctx->eip;
699
700                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
701                                                    (guint8*)ji->code_start + ji->code_size,
702                                                    ip, regs, MONO_MAX_IREGS + 1, &cfa);
703
704                 new_ctx->eax = regs [X86_EAX];
705                 new_ctx->ebx = regs [X86_EBX];
706                 new_ctx->ecx = regs [X86_ECX];
707                 new_ctx->edx = regs [X86_EDX];
708                 new_ctx->esp = regs [X86_ESP];
709                 new_ctx->ebp = regs [X86_EBP];
710                 new_ctx->esi = regs [X86_ESI];
711                 new_ctx->edi = regs [X86_EDI];
712                 new_ctx->eip = regs [X86_NREG];
713
714                 /* The CFA becomes the new SP value */
715                 new_ctx->esp = (gssize)cfa;
716
717                 /* Adjust IP */
718                 new_ctx->eip --;
719
720                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
721                         /* remove any unused lmf */
722                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
723                 }
724
725                 /* Pop arguments off the stack */
726                 /* 
727                  * FIXME: LLVM doesn't push these, we can't use ji->from_llvm as it describes
728                  * the caller.
729                  */
730 #ifndef ENABLE_LLVM
731                 {
732                         MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (ji->method)->param_count + 1);
733
734                         guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (ji->method), mono_method_signature (ji->method)->param_count, arg_info);
735                         new_ctx->esp += stack_to_pop;
736                 }
737 #endif
738
739                 return TRUE;
740         } else if (*lmf) {
741
742                 if (((guint64)(*lmf)->previous_lmf) & 2) {
743                         /* 
744                          * This LMF entry is created by the soft debug code to mark transitions to
745                          * managed code done during invokes.
746                          */
747                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
748
749                         g_assert (ext->debugger_invoke);
750
751                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
752
753                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
754
755                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
756
757                         return TRUE;
758                 }
759                 
760                 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
761                 } else {
762                         if (!((guint32)((*lmf)->previous_lmf) & 1))
763                                 /* Top LMF entry */
764                                 return FALSE;
765                         /* Trampoline lmf frame */
766                         frame->method = (*lmf)->method;
767                 }
768
769                 new_ctx->esi = (*lmf)->esi;
770                 new_ctx->edi = (*lmf)->edi;
771                 new_ctx->ebx = (*lmf)->ebx;
772                 new_ctx->ebp = (*lmf)->ebp;
773                 new_ctx->eip = (*lmf)->eip;
774
775                 frame->ji = ji;
776                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
777
778                 /* Check if we are in a trampoline LMF frame */
779                 if ((guint32)((*lmf)->previous_lmf) & 1) {
780                         /* lmf->esp is set by the trampoline code */
781                         new_ctx->esp = (*lmf)->esp;
782
783                         /* Pop arguments off the stack */
784                         /* FIXME: Handle the delegate case too ((*lmf)->method == NULL) */
785                         /* FIXME: Handle the IMT/vtable case too */
786 #ifndef ENABLE_LLVM
787                         if ((*lmf)->method && (*lmf)->method != MONO_FAKE_IMT_METHOD && (*lmf)->method != MONO_FAKE_VTABLE_METHOD) {
788                                 MonoMethod *method = (*lmf)->method;
789                                 MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (method)->param_count + 1);
790
791                                 guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (method), mono_method_signature (method)->param_count, arg_info);
792                                 new_ctx->esp += stack_to_pop;
793                         }
794 #endif
795                 }
796                 else
797                         /* the lmf is always stored on the stack, so the following
798                          * expression points to a stack location which can be used as ESP */
799                         new_ctx->esp = (unsigned long)&((*lmf)->eip);
800
801                 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
802
803                 return TRUE;
804         }
805
806         return FALSE;
807 }
808
809 #ifdef __sun
810 #define REG_EAX EAX
811 #define REG_EBX EBX
812 #define REG_ECX ECX
813 #define REG_EDX EDX
814 #define REG_EBP EBP
815 #define REG_ESP ESP
816 #define REG_ESI ESI
817 #define REG_EDI EDI
818 #define REG_EIP EIP
819 #endif
820
821 void
822 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
823 {
824 #ifdef MONO_ARCH_USE_SIGACTION
825         ucontext_t *ctx = (ucontext_t*)sigctx;
826         
827         mctx->eax = UCONTEXT_REG_EAX (ctx);
828         mctx->ebx = UCONTEXT_REG_EBX (ctx);
829         mctx->ecx = UCONTEXT_REG_ECX (ctx);
830         mctx->edx = UCONTEXT_REG_EDX (ctx);
831         mctx->ebp = UCONTEXT_REG_EBP (ctx);
832         mctx->esp = UCONTEXT_REG_ESP (ctx);
833         mctx->esi = UCONTEXT_REG_ESI (ctx);
834         mctx->edi = UCONTEXT_REG_EDI (ctx);
835         mctx->eip = UCONTEXT_REG_EIP (ctx);
836 #else   
837         struct sigcontext *ctx = (struct sigcontext *)sigctx;
838
839         mctx->eax = ctx->SC_EAX;
840         mctx->ebx = ctx->SC_EBX;
841         mctx->ecx = ctx->SC_ECX;
842         mctx->edx = ctx->SC_EDX;
843         mctx->ebp = ctx->SC_EBP;
844         mctx->esp = ctx->SC_ESP;
845         mctx->esi = ctx->SC_ESI;
846         mctx->edi = ctx->SC_EDI;
847         mctx->eip = ctx->SC_EIP;
848 #endif
849 }
850
851 void
852 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
853 {
854 #ifdef MONO_ARCH_USE_SIGACTION
855         ucontext_t *ctx = (ucontext_t*)sigctx;
856
857         UCONTEXT_REG_EAX (ctx) = mctx->eax;
858         UCONTEXT_REG_EBX (ctx) = mctx->ebx;
859         UCONTEXT_REG_ECX (ctx) = mctx->ecx;
860         UCONTEXT_REG_EDX (ctx) = mctx->edx;
861         UCONTEXT_REG_EBP (ctx) = mctx->ebp;
862         UCONTEXT_REG_ESP (ctx) = mctx->esp;
863         UCONTEXT_REG_ESI (ctx) = mctx->esi;
864         UCONTEXT_REG_EDI (ctx) = mctx->edi;
865         UCONTEXT_REG_EIP (ctx) = mctx->eip;
866 #else
867         struct sigcontext *ctx = (struct sigcontext *)sigctx;
868
869         ctx->SC_EAX = mctx->eax;
870         ctx->SC_EBX = mctx->ebx;
871         ctx->SC_ECX = mctx->ecx;
872         ctx->SC_EDX = mctx->edx;
873         ctx->SC_EBP = mctx->ebp;
874         ctx->SC_ESP = mctx->esp;
875         ctx->SC_ESI = mctx->esi;
876         ctx->SC_EDI = mctx->edi;
877         ctx->SC_EIP = mctx->eip;
878 #endif
879 }       
880
881 gpointer
882 mono_arch_ip_from_context (void *sigctx)
883 {
884 #ifdef MONO_ARCH_USE_SIGACTION
885         ucontext_t *ctx = (ucontext_t*)sigctx;
886         return (gpointer)UCONTEXT_REG_EIP (ctx);
887 #else
888         struct sigcontext *ctx = sigctx;
889         return (gpointer)ctx->SC_EIP;
890 #endif  
891 }
892
893 /*
894  * handle_exception:
895  *
896  *   Called by resuming from a signal handler.
897  */
898 static void
899 handle_signal_exception (gpointer obj)
900 {
901         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
902         MonoContext ctx;
903         static void (*restore_context) (MonoContext *);
904
905         if (!restore_context)
906                 restore_context = mono_get_restore_context ();
907
908         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
909
910         if (mono_debugger_handle_exception (&ctx, (MonoObject *)obj))
911                 return;
912
913         mono_handle_exception (&ctx, obj, MONO_CONTEXT_GET_IP (&ctx), FALSE);
914
915         restore_context (&ctx);
916 }
917
918 /*
919  * mono_x86_get_signal_exception_trampoline:
920  *
921  *   This x86 specific trampoline is used to call handle_signal_exception.
922  */
923 gpointer
924 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
925 {
926         guint8 *start, *code;
927         MonoJumpInfo *ji = NULL;
928         GSList *unwind_ops = NULL;
929         int stack_size;
930
931         start = code = mono_global_codeman_reserve (128);
932
933         /* Caller ip */
934         x86_push_reg (code, X86_ECX);
935
936         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
937         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
938
939         /* Fix the alignment to be what apple expects */
940         stack_size = 12;
941
942         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
943         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
944
945         /* Arg1 */
946         x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
947         /* Branch to target */
948         x86_call_reg (code, X86_EDX);
949
950         g_assert ((code - start) < 128);
951
952         mono_save_trampoline_xdebug_info ("x86_signal_exception_trampoline", start, code - start, unwind_ops);
953
954         if (info)
955                 *info = mono_tramp_info_create (g_strdup ("x86_signal_exception_trampoline"), start, code - start, ji, unwind_ops);
956
957         return start;
958 }
959
960 gboolean
961 mono_arch_handle_exception (void *sigctx, gpointer obj, gboolean test_only)
962 {
963 #if defined(MONO_ARCH_USE_SIGACTION)
964         /*
965          * Handling the exception in the signal handler is problematic, since the original
966          * signal is disabled, and we could run arbitrary code though the debugger. So
967          * resume into the normal stack and do most work there if possible.
968          */
969         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
970         guint64 sp = UCONTEXT_REG_ESP (sigctx);
971
972         /* Pass the ctx parameter in TLS */
973         mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
974         /*
975          * Can't pass the obj on the stack, since we are executing on the
976          * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
977          * So put it into a register, and branch to a trampoline which
978          * pushes it.
979          */
980         g_assert (!test_only);
981         UCONTEXT_REG_EAX (sigctx) = (gsize)obj;
982         UCONTEXT_REG_ECX (sigctx) = UCONTEXT_REG_EIP (sigctx);
983         UCONTEXT_REG_EDX (sigctx) = (gsize)handle_signal_exception;
984
985         /* Allocate a stack frame, align it to 16 bytes which is needed on apple */
986         sp -= 16;
987         sp &= ~15;
988         UCONTEXT_REG_ESP (sigctx) = sp;
989
990         UCONTEXT_REG_EIP (sigctx) = (gsize)signal_exception_trampoline;
991
992         return TRUE;
993 #else
994         MonoContext mctx;
995
996         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
997
998         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj))
999                 return TRUE;
1000
1001         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, test_only);
1002
1003         mono_arch_monoctx_to_sigctx (&mctx, sigctx);
1004
1005         return TRUE;
1006 #endif
1007 }
1008
1009 static void
1010 restore_soft_guard_pages (void)
1011 {
1012         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1013         if (jit_tls->stack_ovf_guard_base)
1014                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1015 }
1016
1017 /* 
1018  * this function modifies mctx so that when it is restored, it
1019  * won't execcute starting at mctx.eip, but in a function that
1020  * will restore the protection on the soft-guard pages and return back to
1021  * continue at mctx.eip.
1022  */
1023 static void
1024 prepare_for_guard_pages (MonoContext *mctx)
1025 {
1026         gpointer *sp;
1027         sp = (gpointer)(mctx->esp);
1028         sp -= 1;
1029         /* the resturn addr */
1030         sp [0] = (gpointer)(mctx->eip);
1031         mctx->eip = (unsigned long)restore_soft_guard_pages;
1032         mctx->esp = (unsigned long)sp;
1033 }
1034
1035 static void
1036 altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean stack_ovf)
1037 {
1038         void (*restore_context) (MonoContext *);
1039         MonoContext mctx;
1040
1041         restore_context = mono_get_restore_context ();
1042         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1043
1044         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj)) {
1045                 if (stack_ovf)
1046                         prepare_for_guard_pages (&mctx);
1047                 restore_context (&mctx);
1048         }
1049
1050         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, FALSE);
1051         if (stack_ovf)
1052                 prepare_for_guard_pages (&mctx);
1053         restore_context (&mctx);
1054 }
1055
1056 void
1057 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
1058 {
1059 #ifdef MONO_ARCH_USE_SIGACTION
1060         MonoException *exc = NULL;
1061         ucontext_t *ctx = (ucontext_t*)sigctx;
1062         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1063         gpointer *sp;
1064         int frame_size;
1065
1066         /* if we didn't find a managed method for the ip address and it matches the fault
1067          * address, we assume we followed a broken pointer during an indirect call, so
1068          * we try the lookup again with the return address pushed on the stack
1069          */
1070         if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1071                 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1072                 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1073                 if (ji)
1074                         UCONTEXT_REG_EIP (ctx) = sp [0];
1075         }
1076         if (stack_ovf)
1077                 exc = mono_domain_get ()->stack_overflow_ex;
1078         if (!ji)
1079                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
1080         /* setup a call frame on the real stack so that control is returned there
1081          * and exception handling can continue.
1082          * If this was a stack overflow the caller already ensured the stack pages
1083          * needed have been unprotected.
1084          * The frame looks like:
1085          *   ucontext struct
1086          *   test_only arg
1087          *   exception arg
1088          *   ctx arg
1089          *   return ip
1090          */
1091         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 4;
1092         frame_size += 15;
1093         frame_size &= ~15;
1094         sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1095         sp = (gpointer)((char*)sp - frame_size);
1096         /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1097          * goes at sp [-1]
1098          */
1099         sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1100         sp [0] = sp + 4;
1101         sp [1] = exc;
1102         sp [2] = (gpointer)stack_ovf;
1103         /* may need to adjust pointers in the new struct copy, depending on the OS */
1104         memcpy (sp + 4, ctx, sizeof (ucontext_t));
1105         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1106         UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1107         UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1108 #endif
1109 }
1110
1111 #if MONO_SUPPORT_TASKLETS
1112 MonoContinuationRestore
1113 mono_tasklets_arch_restore (void)
1114 {
1115         static guint8* saved = NULL;
1116         guint8 *code, *start;
1117
1118         if (saved)
1119                 return (MonoContinuationRestore)saved;
1120         code = start = mono_global_codeman_reserve (48);
1121         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1122         /* put cont in edx */
1123         x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1124         /* setup the copy of the stack */
1125         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1126         x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1127         x86_cld (code);
1128         x86_mov_reg_membase (code, X86_ESI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1129         x86_mov_reg_membase (code, X86_EDI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1130         x86_prefix (code, X86_REP_PREFIX);
1131         x86_movsl (code);
1132
1133         /* now restore the registers from the LMF */
1134         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1135         x86_mov_reg_membase (code, X86_EBX, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebx), 4);
1136         x86_mov_reg_membase (code, X86_EBP, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebp), 4);
1137         x86_mov_reg_membase (code, X86_ESI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, esi), 4);
1138         x86_mov_reg_membase (code, X86_EDI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, edi), 4);
1139
1140         /* restore the lmf chain */
1141         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1142         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1143
1144         /* state in eax, so it's setup as the return value */
1145         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1146         x86_jump_membase (code, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_ip));
1147         g_assert ((code - start) <= 48);
1148         saved = start;
1149         return (MonoContinuationRestore)saved;
1150 }
1151 #endif
1152