2 * exceptions-x86.c: exception support for x86
5 * Dietmar Maurer (dietmar@ximian.com)
7 * (C) 2001 Ximian, Inc.
12 #if _WIN32_WINNT < 0x0501
13 /* Required for Vectored Exception Handling. */
15 #define _WIN32_WINNT 0x0501
16 #endif /* _WIN32_WINNT < 0x0501 */
22 #include <mono/arch/x86/x86-codegen.h>
23 #include <mono/metadata/appdomain.h>
24 #include <mono/metadata/tabledefs.h>
25 #include <mono/metadata/threads.h>
26 #include <mono/metadata/debug-helpers.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/metadata/mono-debug.h>
30 #include <mono/utils/mono-mmap.h>
35 #include "debug-mini.h"
37 static gpointer signal_exception_trampoline;
40 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot) MONO_INTERNAL;
43 static void (*restore_stack) (void *);
45 static MonoW32ExceptionHandler fpe_handler;
46 static MonoW32ExceptionHandler ill_handler;
47 static MonoW32ExceptionHandler segv_handler;
49 LPTOP_LEVEL_EXCEPTION_FILTER mono_old_win_toplevel_exception_filter;
50 gpointer mono_win_vectored_exception_handle;
51 extern gboolean mono_win_chained_exception_needs_run;
52 extern int (*gUnhandledExceptionHandler)(EXCEPTION_POINTERS*);
54 #ifndef PROCESS_CALLBACK_FILTER_ENABLED
55 # define PROCESS_CALLBACK_FILTER_ENABLED 1
58 #define W32_SEH_HANDLE_EX(_ex) \
59 if (_ex##_handler) _ex##_handler(0, ep, sctx)
61 LONG CALLBACK seh_unhandled_exception_filter(EXCEPTION_POINTERS* ep)
63 #ifndef MONO_CROSS_COMPILE
64 if (mono_old_win_toplevel_exception_filter) {
65 return (*mono_old_win_toplevel_exception_filter)(ep);
69 mono_handle_native_sigsegv (SIGSEGV, NULL);
71 return EXCEPTION_CONTINUE_SEARCH;
75 * mono_win32_get_handle_stackoverflow (void):
77 * Returns a pointer to a method which restores the current context stack
78 * and calls handle_exceptions, when done restores the original stack.
81 mono_win32_get_handle_stackoverflow (void)
83 static guint8 *start = NULL;
89 /* restore_contect (void *sigctx) */
90 start = code = mono_global_codeman_reserve (128);
92 /* load context into ebx */
93 x86_mov_reg_membase (code, X86_EBX, X86_ESP, 4, 4);
95 /* move current stack into edi for later restore */
96 x86_mov_reg_reg (code, X86_EDI, X86_ESP, 4);
98 /* use the new freed stack from sigcontext */
99 x86_mov_reg_membase (code, X86_ESP, X86_EBX, G_STRUCT_OFFSET (struct sigcontext, esp), 4);
101 /* get the current domain */
102 x86_call_code (code, mono_domain_get);
104 /* get stack overflow exception from domain object */
105 x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoDomain, stack_overflow_ex), 4);
107 /* call mono_arch_handle_exception (sctx, stack_overflow_exception_obj) */
108 x86_push_reg (code, X86_EAX);
109 x86_push_reg (code, X86_EBX);
110 x86_call_code (code, mono_arch_handle_exception);
112 /* restore the SEH handler stack */
113 x86_mov_reg_reg (code, X86_ESP, X86_EDI, 4);
121 /* Special hack to workaround the fact that the
122 * when the SEH handler is called the stack is
123 * to small to recover.
125 * Stack walking part of this method is from mono_handle_exception
127 * The idea is simple;
128 * - walk the stack to free some space (64k)
129 * - set esp to new stack location
130 * - call mono_arch_handle_exception with stack overflow exception
131 * - set esp to SEH handlers stack
135 win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, struct sigcontext *sctx)
139 MonoDomain *domain = mono_domain_get ();
141 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
142 MonoLMF *lmf = jit_tls->lmf;
143 MonoContext initial_ctx;
145 guint32 free_stack = 0;
146 StackFrameInfo frame;
148 /* convert sigcontext to MonoContext (due to reuse of stack walking helpers */
149 mono_arch_sigctx_to_monoctx (sctx, &ctx);
151 /* get our os page size */
153 page_size = si.dwPageSize;
155 /* Let's walk the stack to recover
156 * the needed stack space (if possible)
158 memset (&rji, 0, sizeof (rji));
161 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
163 /* try to free 64kb from our stack */
167 mono_arch_find_jit_info (domain, jit_tls, &rji, &ctx, &new_ctx, &lmf, NULL, &frame);
169 g_warning ("Exception inside function without unwind info");
170 g_assert_not_reached ();
173 if (frame.ji != (gpointer)-1) {
174 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
177 /* todo: we should call abort if ji is -1 */
179 } while (free_stack < 64 * 1024 && frame.ji != (gpointer) -1);
181 /* convert into sigcontext to be used in mono_arch_handle_exception */
182 mono_arch_monoctx_to_sigctx (&ctx, sctx);
184 /* todo: install new stack-guard page */
186 /* use the new stack and call mono_arch_handle_exception () */
187 restore_stack (sctx);
191 * Unhandled Exception Filter
192 * Top-level per-process exception handler.
194 LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep)
196 EXCEPTION_RECORD* er;
198 struct sigcontext* sctx;
201 mono_win_chained_exception_needs_run = FALSE;
202 res = EXCEPTION_CONTINUE_EXECUTION;
204 er = ep->ExceptionRecord;
205 ctx = ep->ContextRecord;
206 sctx = g_malloc(sizeof(struct sigcontext));
208 /* Copy Win32 context to UNIX style context */
209 sctx->eax = ctx->Eax;
210 sctx->ebx = ctx->Ebx;
211 sctx->ecx = ctx->Ecx;
212 sctx->edx = ctx->Edx;
213 sctx->ebp = ctx->Ebp;
214 sctx->esp = ctx->Esp;
215 sctx->esi = ctx->Esi;
216 sctx->edi = ctx->Edi;
217 sctx->eip = ctx->Eip;
219 switch (er->ExceptionCode) {
220 case EXCEPTION_STACK_OVERFLOW:
221 win32_handle_stack_overflow (ep, sctx);
223 case EXCEPTION_ACCESS_VIOLATION:
224 W32_SEH_HANDLE_EX(segv);
226 case EXCEPTION_ILLEGAL_INSTRUCTION:
227 W32_SEH_HANDLE_EX(ill);
229 case EXCEPTION_INT_DIVIDE_BY_ZERO:
230 case EXCEPTION_INT_OVERFLOW:
231 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
232 case EXCEPTION_FLT_OVERFLOW:
233 case EXCEPTION_FLT_UNDERFLOW:
234 case EXCEPTION_FLT_INEXACT_RESULT:
235 W32_SEH_HANDLE_EX(fpe);
241 if (mono_win_chained_exception_needs_run) {
242 /* Don't copy context back if we chained exception
243 * as the handler may have modfied the EXCEPTION_POINTERS
244 * directly. We don't pass sigcontext to chained handlers.
245 * Return continue search so the UnhandledExceptionFilter
246 * can correctly chain the exception.
248 res = EXCEPTION_CONTINUE_SEARCH;
250 /* Copy context back */
251 ctx->Eax = sctx->eax;
252 ctx->Ebx = sctx->ebx;
253 ctx->Ecx = sctx->ecx;
254 ctx->Edx = sctx->edx;
255 ctx->Ebp = sctx->ebp;
256 ctx->Esp = sctx->esp;
257 ctx->Esi = sctx->esi;
258 ctx->Edi = sctx->edi;
259 ctx->Eip = sctx->eip;
262 /* TODO: Find right place to free this in stack overflow case */
263 if (er->ExceptionCode != EXCEPTION_STACK_OVERFLOW)
269 void win32_seh_init()
271 /* install restore stack helper */
273 restore_stack = mono_win32_get_handle_stackoverflow ();
275 mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter);
276 mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler);
279 void win32_seh_cleanup()
281 if (mono_old_win_toplevel_exception_filter) SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter);
282 RemoveVectoredExceptionHandler (seh_unhandled_exception_filter);
285 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
289 fpe_handler = handler;
292 ill_handler = handler;
295 segv_handler = handler;
302 #endif /* TARGET_WIN32 */
305 * mono_arch_get_restore_context:
307 * Returns a pointer to a method which restores a previously saved sigcontext.
310 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
312 guint8 *start = NULL;
314 MonoJumpInfo *ji = NULL;
315 GSList *unwind_ops = NULL;
317 /* restore_contect (MonoContext *ctx) */
319 start = code = mono_global_codeman_reserve (128);
322 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
325 x86_mov_reg_membase (code, X86_EBX, X86_EAX, G_STRUCT_OFFSET (MonoContext, ebx), 4);
328 x86_mov_reg_membase (code, X86_EDI, X86_EAX, G_STRUCT_OFFSET (MonoContext, edi), 4);
331 x86_mov_reg_membase (code, X86_ESI, X86_EAX, G_STRUCT_OFFSET (MonoContext, esi), 4);
334 x86_mov_reg_membase (code, X86_EDX, X86_EAX, G_STRUCT_OFFSET (MonoContext, edx), 4);
337 * The context resides on the stack, in the stack frame of the
338 * caller of this function. The stack pointer that we need to
339 * restore is potentially many stack frames higher up, so the
340 * distance between them can easily be more than the red zone
341 * size. Hence the stack pointer can be restored only after
342 * we have finished loading everything from the context.
345 /* load ESP into EBP */
346 x86_mov_reg_membase (code, X86_EBP, X86_EAX, G_STRUCT_OFFSET (MonoContext, esp), 4);
347 /* load return address into ECX */
348 x86_mov_reg_membase (code, X86_ECX, X86_EAX, G_STRUCT_OFFSET (MonoContext, eip), 4);
349 /* save the return addr to the restored stack - 4 */
350 x86_mov_membase_reg (code, X86_EBP, -4, X86_ECX, 4);
352 /* load EBP into ECX */
353 x86_mov_reg_membase (code, X86_ECX, X86_EAX, G_STRUCT_OFFSET (MonoContext, ebp), 4);
354 /* save EBP to the restored stack - 8 */
355 x86_mov_membase_reg (code, X86_EBP, -8, X86_ECX, 4);
357 /* load EAX into ECX */
358 x86_mov_reg_membase (code, X86_ECX, X86_EAX, G_STRUCT_OFFSET (MonoContext, eax), 4);
359 /* save EAX to the restored stack - 12 */
360 x86_mov_membase_reg (code, X86_EBP, -12, X86_ECX, 4);
363 x86_mov_reg_membase (code, X86_ECX, X86_EAX, G_STRUCT_OFFSET (MonoContext, ecx), 4);
365 /* restore ESP - 12 */
366 x86_lea_membase (code, X86_ESP, X86_EBP, -12);
368 x86_pop_reg (code, X86_EAX);
370 x86_pop_reg (code, X86_EBP);
371 /* jump to the saved IP */
374 nacl_global_codeman_validate(&start, 128, &code);
377 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
381 for (l = unwind_ops; l; l = l->next)
383 g_slist_free (unwind_ops);
390 * mono_arch_get_call_filter:
392 * Returns a pointer to a method which calls an exception filter. We
393 * also use this function to call finally handlers (we pass NULL as
394 * @exc object in this case).
397 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
401 MonoJumpInfo *ji = NULL;
402 GSList *unwind_ops = NULL;
403 guint kMaxCodeSize = NACL_SIZE (64, 128);
405 /* call_filter (MonoContext *ctx, unsigned long eip) */
406 start = code = mono_global_codeman_reserve (kMaxCodeSize);
408 x86_push_reg (code, X86_EBP);
409 x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
410 x86_push_reg (code, X86_EBX);
411 x86_push_reg (code, X86_EDI);
412 x86_push_reg (code, X86_ESI);
415 x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
417 x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
419 x86_push_reg (code, X86_EBP);
422 x86_mov_reg_membase (code, X86_EBP, X86_EAX, G_STRUCT_OFFSET (MonoContext, ebp), 4);
423 /* restore registers used by global register allocation (EBX & ESI) */
424 x86_mov_reg_membase (code, X86_EBX, X86_EAX, G_STRUCT_OFFSET (MonoContext, ebx), 4);
425 x86_mov_reg_membase (code, X86_ESI, X86_EAX, G_STRUCT_OFFSET (MonoContext, esi), 4);
426 x86_mov_reg_membase (code, X86_EDI, X86_EAX, G_STRUCT_OFFSET (MonoContext, edi), 4);
428 /* align stack and save ESP */
429 x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
430 x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
431 g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
432 x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
433 x86_push_reg (code, X86_EDX);
435 /* call the handler */
436 x86_call_reg (code, X86_ECX);
439 x86_pop_reg (code, X86_ESP);
442 x86_pop_reg (code, X86_EBP);
444 /* restore saved regs */
445 x86_pop_reg (code, X86_ESI);
446 x86_pop_reg (code, X86_EDI);
447 x86_pop_reg (code, X86_EBX);
451 nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
454 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
458 for (l = unwind_ops; l; l = l->next)
460 g_slist_free (unwind_ops);
463 g_assert ((code - start) < kMaxCodeSize);
468 * mono_x86_throw_exception:
470 * C function called from the throw trampolines.
473 mono_x86_throw_exception (mgreg_t *regs, MonoObject *exc,
474 mgreg_t eip, gboolean rethrow)
478 ctx.esp = regs [X86_ESP];
480 ctx.ebp = regs [X86_EBP];
481 ctx.edi = regs [X86_EDI];
482 ctx.esi = regs [X86_ESI];
483 ctx.ebx = regs [X86_EBX];
484 ctx.edx = regs [X86_EDX];
485 ctx.ecx = regs [X86_ECX];
486 ctx.eax = regs [X86_EAX];
489 /* The OSX ABI specifies 16 byte alignment at call sites */
490 g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
493 if (mono_object_isinst (exc, mono_defaults.exception_class)) {
494 MonoException *mono_ex = (MonoException*)exc;
496 mono_ex->stack_trace = NULL;
499 if (mono_debug_using_mono_debugger ()) {
500 guint8 buf [16], *code;
502 mono_breakpoint_clean_code (NULL, (gpointer)eip, 8, buf, sizeof (buf));
505 if (buf [3] == 0xe8) {
506 MonoContext ctx_cp = ctx;
507 ctx_cp.eip = eip - 5;
509 if (mono_debugger_handle_exception (&ctx_cp, exc)) {
510 mono_restore_context (&ctx_cp);
511 g_assert_not_reached ();
516 /* adjust eip so that it point into the call instruction */
519 mono_handle_exception (&ctx, exc);
521 mono_restore_context (&ctx);
523 g_assert_not_reached ();
527 mono_x86_throw_corlib_exception (mgreg_t *regs, guint32 ex_token_index,
528 mgreg_t eip, gint32 pc_offset)
530 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
533 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
537 /* Negate the ip adjustment done in mono_x86_throw_exception () */
540 mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
544 mono_x86_resume_unwind (mgreg_t *regs, MonoObject *exc,
545 mgreg_t eip, gboolean rethrow)
549 ctx.esp = regs [X86_ESP];
551 ctx.ebp = regs [X86_EBP];
552 ctx.edi = regs [X86_EDI];
553 ctx.esi = regs [X86_ESI];
554 ctx.ebx = regs [X86_EBX];
555 ctx.edx = regs [X86_EDX];
556 ctx.ecx = regs [X86_ECX];
557 ctx.eax = regs [X86_EAX];
559 mono_resume_unwind (&ctx);
563 * get_throw_trampoline:
565 * Generate a call to mono_x86_throw_exception/
566 * mono_x86_throw_corlib_exception.
567 * If LLVM is true, generate code which assumes the caller is LLVM generated code,
568 * which doesn't push the arguments.
571 get_throw_trampoline (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, MonoTrampInfo **info, gboolean aot)
573 guint8 *start, *code;
574 int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
575 MonoJumpInfo *ji = NULL;
576 GSList *unwind_ops = NULL;
577 guint kMaxCodeSize = NACL_SIZE (128, 256);
579 start = code = mono_global_codeman_reserve (kMaxCodeSize);
584 * On apple, the stack is misaligned by the pushing of the return address.
587 /* On OSX, we don't generate alignment code to save space */
590 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
593 * The stack looks like this:
594 * <pc offset> (only if corlib is TRUE)
595 * <exception object>/<type token>
596 * <return addr> <- esp (unaligned on apple)
599 mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
600 mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
603 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
604 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
609 arg_offsets [3] = 12;
613 for (i = 0; i < X86_NREG; ++i)
615 x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
616 /* Calculate the offset between the current sp and the sp of the caller */
618 /* LLVM doesn't push the arguments */
619 stack_offset = stack_size + 4;
623 stack_offset = stack_size + 4 + 8;
625 /* We don't generate stack alignment code on osx to save space */
628 /* One argument + stack alignment */
629 stack_offset = stack_size + 4 + 4;
631 /* Pop the alignment added by OP_THROW too */
632 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
634 if (mono_do_x86_stack_align)
635 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
640 x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
641 x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
643 /* Set arg1 == regs */
644 x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
645 x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
646 /* Set arg2 == exc/ex_token_index */
648 x86_mov_reg_imm (code, X86_EAX, 0);
650 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
651 x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
652 /* Set arg3 == eip */
654 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
656 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
657 x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
658 /* Set arg4 == rethrow/pc_offset */
660 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], 0, 4);
662 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
665 * The caller is LLVM code which passes the absolute address not a pc offset,
666 * so compensate by passing 0 as 'ip' and passing the negated abs address as
669 x86_neg_reg (code, X86_EAX);
671 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
673 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
677 // This can be called from runtime code, which can't guarantee that
678 // ebx contains the got address.
679 // So emit the got address loading code too
680 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
681 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");
682 x86_call_reg (code, X86_EAX);
684 x86_call_code (code, resume_unwind ? (gpointer)(mono_x86_resume_unwind) : (corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception));
686 x86_breakpoint (code);
688 nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
690 g_assert ((code - start) < kMaxCodeSize);
693 *info = mono_tramp_info_create (name, start, code - start, ji, unwind_ops);
697 for (l = unwind_ops; l; l = l->next)
699 g_slist_free (unwind_ops);
706 * mono_arch_get_throw_exception:
708 * Returns a function pointer which can be used to raise
709 * exceptions. The returned function has the following
710 * signature: void (*func) (MonoException *exc);
711 * For example to raise an arithmetic exception you can use:
713 * x86_push_imm (code, mono_get_exception_arithmetic ());
714 * x86_call_code (code, arch_get_throw_exception ());
718 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
720 return get_throw_trampoline ("throw_exception", FALSE, FALSE, FALSE, FALSE, FALSE, info, aot);
724 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
726 return get_throw_trampoline ("rethrow_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot);
730 * mono_arch_get_throw_corlib_exception:
732 * Returns a function pointer which can be used to raise
733 * corlib exceptions. The returned function has the following
734 * signature: void (*func) (guint32 ex_token, guint32 offset);
735 * Here, offset is the offset which needs to be substracted from the caller IP
736 * to get the IP of the throw. Passing the offset has the advantage that it
737 * needs no relocations in the caller.
740 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
742 return get_throw_trampoline ("throw_corlib_exception", FALSE, FALSE, TRUE, FALSE, FALSE, info, aot);
746 mono_arch_exceptions_init (void)
751 * If we're running WoW64, we need to set the usermode exception policy
752 * for SEHs to behave. This requires hotfix http://support.microsoft.com/kb/976038
753 * or (eventually) Windows 7 SP1.
759 HMODULE kernel32 = LoadLibraryW (L"kernel32.dll");
762 getter = GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy");
763 setter = GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy");
764 if (getter && setter) {
766 setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
772 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
776 /* LLVM needs different throw trampolines */
777 tramp = get_throw_trampoline ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, NULL, FALSE);
778 mono_register_jit_icall (tramp, "llvm_throw_exception_trampoline", NULL, TRUE);
780 tramp = get_throw_trampoline ("llvm_rethrow_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, NULL, FALSE);
781 mono_register_jit_icall (tramp, "llvm_rethrow_exception_trampoline", NULL, TRUE);
783 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, FALSE, NULL, FALSE);
784 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
786 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_abs_trampoline", FALSE, TRUE, TRUE, TRUE, FALSE, NULL, FALSE);
787 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
789 tramp = get_throw_trampoline ("llvm_resume_unwind_trampoline", FALSE, FALSE, FALSE, FALSE, TRUE, NULL, FALSE);
790 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
792 signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (NULL, FALSE);
796 * mono_arch_find_jit_info:
798 * See exceptions-amd64.c for docs.
801 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls,
802 MonoJitInfo *ji, MonoContext *ctx,
803 MonoContext *new_ctx, MonoLMF **lmf,
804 mgreg_t **save_locations,
805 StackFrameInfo *frame)
807 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
809 memset (frame, 0, sizeof (StackFrameInfo));
815 gssize regs [MONO_MAX_IREGS + 1];
817 guint32 unwind_info_len;
820 frame->type = FRAME_TYPE_MANAGED;
823 unwind_info = mono_aot_get_unwind_info (ji, &unwind_info_len);
825 unwind_info = mono_get_cached_unwind_info (ji->used_regs, &unwind_info_len);
827 regs [X86_EAX] = new_ctx->eax;
828 regs [X86_EBX] = new_ctx->ebx;
829 regs [X86_ECX] = new_ctx->ecx;
830 regs [X86_EDX] = new_ctx->edx;
831 regs [X86_ESP] = new_ctx->esp;
832 regs [X86_EBP] = new_ctx->ebp;
833 regs [X86_ESI] = new_ctx->esi;
834 regs [X86_EDI] = new_ctx->edi;
835 regs [X86_NREG] = new_ctx->eip;
837 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start,
838 (guint8*)ji->code_start + ji->code_size,
839 ip, regs, MONO_MAX_IREGS + 1,
840 save_locations, MONO_MAX_IREGS, &cfa);
842 new_ctx->eax = regs [X86_EAX];
843 new_ctx->ebx = regs [X86_EBX];
844 new_ctx->ecx = regs [X86_ECX];
845 new_ctx->edx = regs [X86_EDX];
846 new_ctx->esp = regs [X86_ESP];
847 new_ctx->ebp = regs [X86_EBP];
848 new_ctx->esi = regs [X86_ESI];
849 new_ctx->edi = regs [X86_EDI];
850 new_ctx->eip = regs [X86_NREG];
852 /* The CFA becomes the new SP value */
853 new_ctx->esp = (gssize)cfa;
858 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
859 /* remove any unused lmf */
860 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
863 /* Pop arguments off the stack */
865 * FIXME: LLVM doesn't push these, we can't use ji->from_llvm as it describes
869 if (ji->has_arch_eh_info)
870 new_ctx->esp += mono_jit_info_get_arch_eh_info (ji)->stack_size;
876 if (((guint64)(*lmf)->previous_lmf) & 2) {
878 * This LMF entry is created by the soft debug code to mark transitions to
879 * managed code done during invokes.
881 MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
883 g_assert (ext->debugger_invoke);
885 memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
887 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
889 frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
894 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
896 if (!((guint32)((*lmf)->previous_lmf) & 1))
899 g_assert_not_reached ();
900 /* Trampoline lmf frame */
901 frame->method = (*lmf)->method;
904 new_ctx->esi = (*lmf)->esi;
905 new_ctx->edi = (*lmf)->edi;
906 new_ctx->ebx = (*lmf)->ebx;
907 new_ctx->ebp = (*lmf)->ebp;
908 new_ctx->eip = (*lmf)->eip;
914 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
916 /* Check if we are in a trampoline LMF frame */
917 if ((guint32)((*lmf)->previous_lmf) & 1) {
918 /* lmf->esp is set by the trampoline code */
919 new_ctx->esp = (*lmf)->esp;
921 /* Pop arguments off the stack */
922 /* FIXME: Handle the delegate case too ((*lmf)->method == NULL) */
923 /* FIXME: Handle the IMT/vtable case too */
926 if ((*lmf)->method) {
927 MonoMethod *method = (*lmf)->method;
928 MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (method)->param_count + 1);
930 guint32 stack_to_pop = mono_arch_get_argument_info (NULL, mono_method_signature (method), mono_method_signature (method)->param_count, arg_info);
931 new_ctx->esp += stack_to_pop;
937 /* the lmf is always stored on the stack, so the following
938 * expression points to a stack location which can be used as ESP */
939 new_ctx->esp = (unsigned long)&((*lmf)->eip);
941 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
950 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
952 mono_sigctx_to_monoctx (sigctx, mctx);
956 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
958 mono_monoctx_to_sigctx (mctx, sigctx);
962 mono_arch_ip_from_context (void *sigctx)
964 #if defined(__native_client__)
965 printf("WARNING: mono_arch_ip_from_context() called!\n");
968 #ifdef MONO_ARCH_USE_SIGACTION
969 ucontext_t *ctx = (ucontext_t*)sigctx;
970 return (gpointer)UCONTEXT_REG_EIP (ctx);
972 struct sigcontext *ctx = sigctx;
973 return (gpointer)ctx->SC_EIP;
975 #endif /* __native_client__ */
981 * Called by resuming from a signal handler.
984 handle_signal_exception (gpointer obj)
986 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
989 memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
991 if (mono_debugger_handle_exception (&ctx, (MonoObject *)obj))
994 mono_handle_exception (&ctx, obj);
996 mono_restore_context (&ctx);
1000 * mono_x86_get_signal_exception_trampoline:
1002 * This x86 specific trampoline is used to call handle_signal_exception.
1005 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
1007 guint8 *start, *code;
1008 MonoJumpInfo *ji = NULL;
1009 GSList *unwind_ops = NULL;
1012 start = code = mono_global_codeman_reserve (128);
1015 x86_push_reg (code, X86_ECX);
1017 mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
1018 mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
1020 /* Fix the alignment to be what apple expects */
1023 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
1024 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
1027 x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
1028 /* Branch to target */
1029 x86_call_reg (code, X86_EDX);
1031 g_assert ((code - start) < 128);
1034 *info = mono_tramp_info_create ("x86_signal_exception_trampoline", start, code - start, ji, unwind_ops);
1038 for (l = unwind_ops; l; l = l->next)
1040 g_slist_free (unwind_ops);
1048 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
1051 * Can't pass the obj on the stack, since we are executing on the
1052 * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
1053 * So put it into a register, and branch to a trampoline which
1056 ctx->eax = (mgreg_t)user_data;
1057 ctx->ecx = ctx->eip;
1058 ctx->edx = (mgreg_t)async_cb;
1061 ctx->esp = (ctx->esp - 16) & ~15;
1062 ctx->eip = (mgreg_t)signal_exception_trampoline;
1066 mono_arch_handle_exception (void *sigctx, gpointer obj)
1068 #if defined(MONO_ARCH_USE_SIGACTION)
1070 ucontext_t *ctx = (ucontext_t*)sigctx;
1073 * Handling the exception in the signal handler is problematic, since the original
1074 * signal is disabled, and we could run arbitrary code though the debugger. So
1075 * resume into the normal stack and do most work there if possible.
1077 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1079 /* Pass the ctx parameter in TLS */
1080 mono_arch_sigctx_to_monoctx (ctx, &jit_tls->ex_ctx);
1082 mctx = jit_tls->ex_ctx;
1083 mono_setup_async_callback (&mctx, handle_signal_exception, obj);
1084 mono_monoctx_to_sigctx (&mctx, sigctx);
1087 #elif defined (TARGET_WIN32)
1089 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1090 struct sigcontext *ctx = (struct sigcontext *)sigctx;
1092 mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
1094 mctx = jit_tls->ex_ctx;
1095 mono_setup_async_callback (&mctx, handle_signal_exception, obj);
1096 mono_monoctx_to_sigctx (&mctx, sigctx);
1102 mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1104 if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj))
1107 mono_handle_exception (&mctx, obj);
1109 mono_arch_monoctx_to_sigctx (&mctx, sigctx);
1116 restore_soft_guard_pages (void)
1118 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1119 if (jit_tls->stack_ovf_guard_base)
1120 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1124 * this function modifies mctx so that when it is restored, it
1125 * won't execcute starting at mctx.eip, but in a function that
1126 * will restore the protection on the soft-guard pages and return back to
1127 * continue at mctx.eip.
1130 prepare_for_guard_pages (MonoContext *mctx)
1133 sp = (gpointer)(mctx->esp);
1135 /* the resturn addr */
1136 sp [0] = (gpointer)(mctx->eip);
1137 mctx->eip = (unsigned long)restore_soft_guard_pages;
1138 mctx->esp = (unsigned long)sp;
1142 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
1148 if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj)) {
1150 prepare_for_guard_pages (&mctx);
1151 mono_restore_context (&mctx);
1154 mono_handle_exception (&mctx, obj);
1156 prepare_for_guard_pages (&mctx);
1157 mono_restore_context (&mctx);
1161 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
1163 #ifdef MONO_ARCH_USE_SIGACTION
1164 MonoException *exc = NULL;
1165 ucontext_t *ctx = (ucontext_t*)sigctx;
1166 MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1170 /* if we didn't find a managed method for the ip address and it matches the fault
1171 * address, we assume we followed a broken pointer during an indirect call, so
1172 * we try the lookup again with the return address pushed on the stack
1174 if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1175 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1176 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1178 UCONTEXT_REG_EIP (ctx) = sp [0];
1181 exc = mono_domain_get ()->stack_overflow_ex;
1183 mono_handle_native_sigsegv (SIGSEGV, sigctx);
1184 /* setup a call frame on the real stack so that control is returned there
1185 * and exception handling can continue.
1186 * If this was a stack overflow the caller already ensured the stack pages
1187 * needed have been unprotected.
1188 * The frame looks like:
1195 // FIXME: test_only is no more.
1196 frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4;
1199 sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1200 sp = (gpointer)((char*)sp - frame_size);
1201 /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1204 sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1207 sp [2] = (gpointer)stack_ovf;
1208 mono_sigctx_to_monoctx (sigctx, (MonoContext*)(sp + 4));
1209 /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1210 UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1211 UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1215 #if MONO_SUPPORT_TASKLETS
1216 MonoContinuationRestore
1217 mono_tasklets_arch_restore (void)
1219 static guint8* saved = NULL;
1220 guint8 *code, *start;
1222 #ifdef __native_client_codegen__
1223 g_print("mono_tasklets_arch_restore needs to be aligned for Native Client\n");
1226 return (MonoContinuationRestore)saved;
1227 code = start = mono_global_codeman_reserve (48);
1228 /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1229 /* put cont in edx */
1230 x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1231 /* state in eax, so it's setup as the return value */
1232 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1234 /* setup the copy of the stack */
1235 x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1236 x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1238 x86_mov_reg_membase (code, X86_ESI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1239 x86_mov_reg_membase (code, X86_EDI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1240 x86_prefix (code, X86_REP_PREFIX);
1243 /* now restore the registers from the LMF */
1244 x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1245 x86_mov_reg_membase (code, X86_EBX, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebx), 4);
1246 x86_mov_reg_membase (code, X86_EBP, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebp), 4);
1247 x86_mov_reg_membase (code, X86_ESI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, esi), 4);
1248 x86_mov_reg_membase (code, X86_EDI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, edi), 4);
1250 /* restore the lmf chain */
1251 /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1252 x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1254 x86_jump_membase (code, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_ip));
1255 g_assert ((code - start) <= 48);
1257 return (MonoContinuationRestore)saved;
1262 * mono_arch_setup_resume_sighandler_ctx:
1264 * Setup CTX so execution continues at FUNC.
1267 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1269 int align = (((gint32)MONO_CONTEXT_GET_SP (ctx)) % MONO_ARCH_FRAME_ALIGNMENT + 4);
1272 MONO_CONTEXT_SET_SP (ctx, (gsize)MONO_CONTEXT_GET_SP (ctx) - align);
1274 MONO_CONTEXT_SET_IP (ctx, func);