Merge pull request #3169 from lambdageek/fix-regression-70561
[mono-project.git] / mono / mini / exceptions-x86.c
blob5811210cabeb51ef59b2ab5c8c7de078de06e1ac
1 /*
2 * exceptions-x86.c: exception support for x86
4 * Authors:
5 * Dietmar Maurer (dietmar@ximian.com)
7 * (C) 2001 Ximian, Inc.
8 */
10 #include <config.h>
12 #include <glib.h>
13 #include <signal.h>
14 #include <string.h>
15 #ifdef HAVE_UCONTEXT_H
16 #include <ucontext.h>
17 #endif
19 #include <mono/metadata/abi-details.h>
20 #include <mono/arch/x86/x86-codegen.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/metadata/threads.h>
24 #include <mono/metadata/debug-helpers.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/gc-internals.h>
27 #include <mono/metadata/mono-debug.h>
28 #include <mono/utils/mono-mmap.h>
30 #include "mini.h"
31 #include "mini-x86.h"
32 #include "tasklets.h"
34 static gpointer signal_exception_trampoline;
36 gpointer
37 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot);
39 #ifdef TARGET_WIN32
40 static void (*restore_stack) (void *);
42 static MonoW32ExceptionHandler fpe_handler;
43 static MonoW32ExceptionHandler ill_handler;
44 static MonoW32ExceptionHandler segv_handler;
46 LPTOP_LEVEL_EXCEPTION_FILTER mono_old_win_toplevel_exception_filter;
47 gpointer mono_win_vectored_exception_handle;
48 extern int (*gUnhandledExceptionHandler)(EXCEPTION_POINTERS*);
50 #ifndef PROCESS_CALLBACK_FILTER_ENABLED
51 # define PROCESS_CALLBACK_FILTER_ENABLED 1
52 #endif
54 #define W32_SEH_HANDLE_EX(_ex) \
55 if (_ex##_handler) _ex##_handler(0, ep, ctx)
57 LONG CALLBACK seh_unhandled_exception_filter(EXCEPTION_POINTERS* ep)
59 #ifndef MONO_CROSS_COMPILE
60 if (mono_old_win_toplevel_exception_filter) {
61 return (*mono_old_win_toplevel_exception_filter)(ep);
63 #endif
65 mono_handle_native_sigsegv (SIGSEGV, NULL, NULL);
67 return EXCEPTION_CONTINUE_SEARCH;
71 * mono_win32_get_handle_stackoverflow (void):
73 * Returns a pointer to a method which restores the current context stack
74 * and calls handle_exceptions, when done restores the original stack.
76 static gpointer
77 mono_win32_get_handle_stackoverflow (void)
79 static guint8 *start = NULL;
80 guint8 *code;
82 if (start)
83 return start;
85 /* restore_contect (void *sigctx) */
86 start = code = mono_global_codeman_reserve (128);
88 /* load context into ebx */
89 x86_mov_reg_membase (code, X86_EBX, X86_ESP, 4, 4);
91 /* move current stack into edi for later restore */
92 x86_mov_reg_reg (code, X86_EDI, X86_ESP, 4);
94 /* use the new freed stack from sigcontext */
95 /* XXX replace usage of struct sigcontext with MonoContext so we can use MONO_STRUCT_OFFSET */
96 x86_mov_reg_membase (code, X86_ESP, X86_EBX, G_STRUCT_OFFSET (struct sigcontext, esp), 4);
98 /* get the current domain */
99 x86_call_code (code, mono_domain_get);
101 /* get stack overflow exception from domain object */
102 x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoDomain, stack_overflow_ex), 4);
104 /* call mono_arch_handle_exception (sctx, stack_overflow_exception_obj) */
105 x86_push_reg (code, X86_EAX);
106 x86_push_reg (code, X86_EBX);
107 x86_call_code (code, mono_arch_handle_exception);
109 /* restore the SEH handler stack */
110 x86_mov_reg_reg (code, X86_ESP, X86_EDI, 4);
112 /* return */
113 x86_ret (code);
115 mono_arch_flush_icache (start, code - start);
116 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
118 return start;
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
132 * - done
134 static void
135 win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, struct sigcontext *sctx)
137 SYSTEM_INFO si;
138 DWORD page_size;
139 MonoDomain *domain = mono_domain_get ();
140 MonoJitInfo rji;
141 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
142 MonoLMF *lmf = jit_tls->lmf;
143 MonoContext initial_ctx;
144 MonoContext ctx;
145 guint32 free_stack = 0;
146 StackFrameInfo frame;
148 mono_sigctx_to_monoctx (sctx, &ctx);
150 /* get our os page size */
151 GetSystemInfo(&si);
152 page_size = si.dwPageSize;
154 /* Let's walk the stack to recover
155 * the needed stack space (if possible)
157 memset (&rji, 0, sizeof (rji));
159 initial_ctx = ctx;
160 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
162 /* try to free 64kb from our stack */
163 do {
164 MonoContext new_ctx;
166 mono_arch_unwind_frame (domain, jit_tls, &rji, &ctx, &new_ctx, &lmf, NULL, &frame);
167 if (!frame.ji) {
168 g_warning ("Exception inside function without unwind info");
169 g_assert_not_reached ();
172 if (frame.ji != (gpointer)-1) {
173 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
176 /* todo: we should call abort if ji is -1 */
177 ctx = new_ctx;
178 } while (free_stack < 64 * 1024 && frame.ji != (gpointer) -1);
180 mono_monoctx_to_sigctx (&ctx, sctx);
182 /* todo: install new stack-guard page */
184 /* use the new stack and call mono_arch_handle_exception () */
185 restore_stack (sctx);
189 * Unhandled Exception Filter
190 * Top-level per-process exception handler.
192 LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep)
194 EXCEPTION_RECORD* er;
195 CONTEXT* ctx;
196 LONG res;
197 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
199 /* If the thread is not managed by the runtime return early */
200 if (!jit_tls)
201 return EXCEPTION_CONTINUE_SEARCH;
203 jit_tls->mono_win_chained_exception_needs_run = FALSE;
204 res = EXCEPTION_CONTINUE_EXECUTION;
206 er = ep->ExceptionRecord;
207 ctx = ep->ContextRecord;
209 switch (er->ExceptionCode) {
210 case EXCEPTION_STACK_OVERFLOW:
211 win32_handle_stack_overflow (ep, ctx);
212 break;
213 case EXCEPTION_ACCESS_VIOLATION:
214 W32_SEH_HANDLE_EX(segv);
215 break;
216 case EXCEPTION_ILLEGAL_INSTRUCTION:
217 W32_SEH_HANDLE_EX(ill);
218 break;
219 case EXCEPTION_INT_DIVIDE_BY_ZERO:
220 case EXCEPTION_INT_OVERFLOW:
221 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
222 case EXCEPTION_FLT_OVERFLOW:
223 case EXCEPTION_FLT_UNDERFLOW:
224 case EXCEPTION_FLT_INEXACT_RESULT:
225 W32_SEH_HANDLE_EX(fpe);
226 break;
227 default:
228 jit_tls->mono_win_chained_exception_needs_run = TRUE;
229 break;
232 if (jit_tls->mono_win_chained_exception_needs_run) {
233 /* Don't copy context back if we chained exception
234 * as the handler may have modfied the EXCEPTION_POINTERS
235 * directly. We don't pass sigcontext to chained handlers.
236 * Return continue search so the UnhandledExceptionFilter
237 * can correctly chain the exception.
239 res = EXCEPTION_CONTINUE_SEARCH;
242 return res;
245 void win32_seh_init()
247 /* install restore stack helper */
248 if (!restore_stack)
249 restore_stack = mono_win32_get_handle_stackoverflow ();
251 mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter);
252 mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler);
255 void win32_seh_cleanup()
257 if (mono_old_win_toplevel_exception_filter)
258 SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter);
259 RemoveVectoredExceptionHandler (mono_win_vectored_exception_handle);
262 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
264 switch (type) {
265 case SIGFPE:
266 fpe_handler = handler;
267 break;
268 case SIGILL:
269 ill_handler = handler;
270 break;
271 case SIGSEGV:
272 segv_handler = handler;
273 break;
274 default:
275 break;
279 #endif /* TARGET_WIN32 */
282 * mono_arch_get_restore_context:
284 * Returns a pointer to a method which restores a previously saved sigcontext.
286 gpointer
287 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
289 guint8 *start = NULL;
290 guint8 *code;
291 MonoJumpInfo *ji = NULL;
292 GSList *unwind_ops = NULL;
294 /* restore_contect (MonoContext *ctx) */
296 start = code = mono_global_codeman_reserve (128);
298 /* load ctx */
299 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
301 /* restore EBX */
302 x86_mov_reg_membase (code, X86_EBX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebx), 4);
304 /* restore EDI */
305 x86_mov_reg_membase (code, X86_EDI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edi), 4);
307 /* restore ESI */
308 x86_mov_reg_membase (code, X86_ESI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esi), 4);
310 /* restore EDX */
311 x86_mov_reg_membase (code, X86_EDX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edx), 4);
314 * The context resides on the stack, in the stack frame of the
315 * caller of this function. The stack pointer that we need to
316 * restore is potentially many stack frames higher up, so the
317 * distance between them can easily be more than the red zone
318 * size. Hence the stack pointer can be restored only after
319 * we have finished loading everything from the context.
322 /* load ESP into EBP */
323 x86_mov_reg_membase (code, X86_EBP, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esp), 4);
324 /* load return address into ECX */
325 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, eip), 4);
326 /* save the return addr to the restored stack - 4 */
327 x86_mov_membase_reg (code, X86_EBP, -4, X86_ECX, 4);
329 /* load EBP into ECX */
330 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebp), 4);
331 /* save EBP to the restored stack - 8 */
332 x86_mov_membase_reg (code, X86_EBP, -8, X86_ECX, 4);
334 /* load EAX into ECX */
335 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, eax), 4);
336 /* save EAX to the restored stack - 12 */
337 x86_mov_membase_reg (code, X86_EBP, -12, X86_ECX, 4);
339 /* restore ECX */
340 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ecx), 4);
342 /* restore ESP - 12 */
343 x86_lea_membase (code, X86_ESP, X86_EBP, -12);
344 /* restore EAX */
345 x86_pop_reg (code, X86_EAX);
346 /* restore EBP */
347 x86_pop_reg (code, X86_EBP);
348 /* jump to the saved IP */
349 x86_ret (code);
351 if (info)
352 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
353 else {
354 GSList *l;
356 for (l = unwind_ops; l; l = l->next)
357 g_free (l->data);
358 g_slist_free (unwind_ops);
361 mono_arch_flush_icache (start, code - start);
362 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
364 return start;
368 * mono_arch_get_call_filter:
370 * Returns a pointer to a method which calls an exception filter. We
371 * also use this function to call finally handlers (we pass NULL as
372 * @exc object in this case).
374 gpointer
375 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
377 guint8* start;
378 guint8 *code;
379 MonoJumpInfo *ji = NULL;
380 GSList *unwind_ops = NULL;
381 guint kMaxCodeSize = 64;
383 /* call_filter (MonoContext *ctx, unsigned long eip) */
384 start = code = mono_global_codeman_reserve (kMaxCodeSize);
386 x86_push_reg (code, X86_EBP);
387 x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
388 x86_push_reg (code, X86_EBX);
389 x86_push_reg (code, X86_EDI);
390 x86_push_reg (code, X86_ESI);
392 /* load ctx */
393 x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
394 /* load eip */
395 x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
396 /* save EBP */
397 x86_push_reg (code, X86_EBP);
399 /* set new EBP */
400 x86_mov_reg_membase (code, X86_EBP, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebp), 4);
401 /* restore registers used by global register allocation (EBX & ESI) */
402 x86_mov_reg_membase (code, X86_EBX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebx), 4);
403 x86_mov_reg_membase (code, X86_ESI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esi), 4);
404 x86_mov_reg_membase (code, X86_EDI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edi), 4);
406 /* align stack and save ESP */
407 x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
408 x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
409 g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
410 x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
411 x86_push_reg (code, X86_EDX);
413 /* call the handler */
414 x86_call_reg (code, X86_ECX);
416 /* restore ESP */
417 x86_pop_reg (code, X86_ESP);
419 /* restore EBP */
420 x86_pop_reg (code, X86_EBP);
422 /* restore saved regs */
423 x86_pop_reg (code, X86_ESI);
424 x86_pop_reg (code, X86_EDI);
425 x86_pop_reg (code, X86_EBX);
426 x86_leave (code);
427 x86_ret (code);
429 if (info)
430 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
431 else {
432 GSList *l;
434 for (l = unwind_ops; l; l = l->next)
435 g_free (l->data);
436 g_slist_free (unwind_ops);
439 mono_arch_flush_icache (start, code - start);
440 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
442 g_assert ((code - start) < kMaxCodeSize);
443 return start;
447 * mono_x86_throw_exception:
449 * C function called from the throw trampolines.
451 void
452 mono_x86_throw_exception (mgreg_t *regs, MonoObject *exc,
453 mgreg_t eip, gboolean rethrow)
455 MonoError error;
456 MonoContext ctx;
458 ctx.esp = regs [X86_ESP];
459 ctx.eip = eip;
460 ctx.ebp = regs [X86_EBP];
461 ctx.edi = regs [X86_EDI];
462 ctx.esi = regs [X86_ESI];
463 ctx.ebx = regs [X86_EBX];
464 ctx.edx = regs [X86_EDX];
465 ctx.ecx = regs [X86_ECX];
466 ctx.eax = regs [X86_EAX];
468 #ifdef __APPLE__
469 /* The OSX ABI specifies 16 byte alignment at call sites */
470 g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
471 #endif
473 if (mono_object_isinst_checked (exc, mono_defaults.exception_class, &error)) {
474 MonoException *mono_ex = (MonoException*)exc;
475 if (!rethrow) {
476 mono_ex->stack_trace = NULL;
477 mono_ex->trace_ips = NULL;
480 mono_error_assert_ok (&error);
482 /* adjust eip so that it point into the call instruction */
483 ctx.eip -= 1;
485 mono_handle_exception (&ctx, exc);
487 mono_restore_context (&ctx);
489 g_assert_not_reached ();
492 void
493 mono_x86_throw_corlib_exception (mgreg_t *regs, guint32 ex_token_index,
494 mgreg_t eip, gint32 pc_offset)
496 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
497 MonoException *ex;
499 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
501 eip -= pc_offset;
503 /* Negate the ip adjustment done in mono_x86_throw_exception () */
504 eip += 1;
506 mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
509 static void
510 mono_x86_resume_unwind (mgreg_t *regs, MonoObject *exc,
511 mgreg_t eip, gboolean rethrow)
513 MonoContext ctx;
515 ctx.esp = regs [X86_ESP];
516 ctx.eip = eip;
517 ctx.ebp = regs [X86_EBP];
518 ctx.edi = regs [X86_EDI];
519 ctx.esi = regs [X86_ESI];
520 ctx.ebx = regs [X86_EBX];
521 ctx.edx = regs [X86_EDX];
522 ctx.ecx = regs [X86_ECX];
523 ctx.eax = regs [X86_EAX];
525 mono_resume_unwind (&ctx);
529 * get_throw_trampoline:
531 * Generate a call to mono_x86_throw_exception/
532 * mono_x86_throw_corlib_exception.
533 * If LLVM is true, generate code which assumes the caller is LLVM generated code,
534 * which doesn't push the arguments.
536 static guint8*
537 get_throw_trampoline (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, MonoTrampInfo **info, gboolean aot)
539 guint8 *start, *code;
540 int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
541 MonoJumpInfo *ji = NULL;
542 GSList *unwind_ops = NULL;
543 guint kMaxCodeSize = 128;
545 start = code = mono_global_codeman_reserve (kMaxCodeSize);
547 stack_size = 128;
550 * On apple, the stack is misaligned by the pushing of the return address.
552 if (!llvm && corlib)
553 /* On OSX, we don't generate alignment code to save space */
554 stack_size += 4;
555 else
556 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
559 * The stack looks like this:
560 * <pc offset> (only if corlib is TRUE)
561 * <exception object>/<type token>
562 * <return addr> <- esp (unaligned on apple)
565 unwind_ops = mono_arch_get_cie_program ();
567 /* Alloc frame */
568 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
569 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
571 arg_offsets [0] = 0;
572 arg_offsets [1] = 4;
573 arg_offsets [2] = 8;
574 arg_offsets [3] = 12;
575 regs_offset = 16;
577 /* Save registers */
578 for (i = 0; i < X86_NREG; ++i)
579 if (i != X86_ESP)
580 x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
581 /* Calculate the offset between the current sp and the sp of the caller */
582 if (llvm) {
583 /* LLVM doesn't push the arguments */
584 stack_offset = stack_size + 4;
585 } else {
586 if (corlib) {
587 /* Two arguments */
588 stack_offset = stack_size + 4 + 8;
589 #ifdef __APPLE__
590 /* We don't generate stack alignment code on osx to save space */
591 #endif
592 } else {
593 /* One argument + stack alignment */
594 stack_offset = stack_size + 4 + 4;
595 #ifdef __APPLE__
596 /* Pop the alignment added by OP_THROW too */
597 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
598 #else
599 if (mono_do_x86_stack_align)
600 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
601 #endif
604 /* Save ESP */
605 x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
606 x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
608 /* Set arg1 == regs */
609 x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
610 x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
611 /* Set arg2 == exc/ex_token_index */
612 if (resume_unwind)
613 x86_mov_reg_imm (code, X86_EAX, 0);
614 else
615 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
616 x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
617 /* Set arg3 == eip */
618 if (llvm_abs)
619 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
620 else
621 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
622 x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
623 /* Set arg4 == rethrow/pc_offset */
624 if (resume_unwind) {
625 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], 0, 4);
626 } else if (corlib) {
627 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
628 if (llvm_abs) {
630 * The caller is LLVM code which passes the absolute address not a pc offset,
631 * so compensate by passing 0 as 'ip' and passing the negated abs address as
632 * the pc offset.
634 x86_neg_reg (code, X86_EAX);
636 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
637 } else {
638 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
640 /* Make the call */
641 if (aot) {
642 // This can be called from runtime code, which can't guarantee that
643 // ebx contains the got address.
644 // So emit the got address loading code too
645 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
646 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");
647 x86_call_reg (code, X86_EAX);
648 } else {
649 x86_call_code (code, resume_unwind ? (gpointer)(mono_x86_resume_unwind) : (corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception));
651 x86_breakpoint (code);
653 g_assert ((code - start) < kMaxCodeSize);
655 if (info)
656 *info = mono_tramp_info_create (name, start, code - start, ji, unwind_ops);
657 else {
658 GSList *l;
660 for (l = unwind_ops; l; l = l->next)
661 g_free (l->data);
662 g_slist_free (unwind_ops);
665 mono_arch_flush_icache (start, code - start);
666 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
668 return start;
672 * mono_arch_get_throw_exception:
674 * Returns a function pointer which can be used to raise
675 * exceptions. The returned function has the following
676 * signature: void (*func) (MonoException *exc);
677 * For example to raise an arithmetic exception you can use:
679 * x86_push_imm (code, mono_get_exception_arithmetic ());
680 * x86_call_code (code, arch_get_throw_exception ());
683 gpointer
684 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
686 return get_throw_trampoline ("throw_exception", FALSE, FALSE, FALSE, FALSE, FALSE, info, aot);
689 gpointer
690 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
692 return get_throw_trampoline ("rethrow_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot);
696 * mono_arch_get_throw_corlib_exception:
698 * Returns a function pointer which can be used to raise
699 * corlib exceptions. The returned function has the following
700 * signature: void (*func) (guint32 ex_token, guint32 offset);
701 * Here, offset is the offset which needs to be substracted from the caller IP
702 * to get the IP of the throw. Passing the offset has the advantage that it
703 * needs no relocations in the caller.
705 gpointer
706 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
708 return get_throw_trampoline ("throw_corlib_exception", FALSE, FALSE, TRUE, FALSE, FALSE, info, aot);
711 void
712 mono_arch_exceptions_init (void)
714 guint8 *tramp;
715 MonoTrampInfo *tinfo;
718 * If we're running WoW64, we need to set the usermode exception policy
719 * for SEHs to behave. This requires hotfix http://support.microsoft.com/kb/976038
720 * or (eventually) Windows 7 SP1.
722 #ifdef TARGET_WIN32
723 DWORD flags;
724 FARPROC getter;
725 FARPROC setter;
726 HMODULE kernel32 = LoadLibraryW (L"kernel32.dll");
728 if (kernel32) {
729 getter = GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy");
730 setter = GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy");
731 if (getter && setter) {
732 if (getter (&flags))
733 setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
736 #endif
738 if (mono_aot_only) {
739 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
740 return;
743 /* LLVM needs different throw trampolines */
744 tramp = get_throw_trampoline ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, &tinfo, FALSE);
745 mono_register_jit_icall (tramp, "llvm_throw_exception_trampoline", NULL, TRUE);
746 mono_tramp_info_register (tinfo, NULL);
748 tramp = get_throw_trampoline ("llvm_rethrow_exception_trampoline", TRUE, TRUE, FALSE, FALSE, FALSE, &tinfo, FALSE);
749 mono_register_jit_icall (tramp, "llvm_rethrow_exception_trampoline", NULL, TRUE);
750 mono_tramp_info_register (tinfo, NULL);
752 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, FALSE, &tinfo, FALSE);
753 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
754 mono_tramp_info_register (tinfo, NULL);
756 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_abs_trampoline", FALSE, TRUE, TRUE, TRUE, FALSE, &tinfo, FALSE);
757 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
758 mono_tramp_info_register (tinfo, NULL);
760 tramp = get_throw_trampoline ("llvm_resume_unwind_trampoline", FALSE, FALSE, FALSE, FALSE, TRUE, &tinfo, FALSE);
761 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
762 mono_tramp_info_register (tinfo, NULL);
764 signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (&tinfo, FALSE);
765 mono_tramp_info_register (tinfo, NULL);
769 * mono_arch_unwind_frame:
771 * See exceptions-amd64.c for docs.
773 gboolean
774 mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls,
775 MonoJitInfo *ji, MonoContext *ctx,
776 MonoContext *new_ctx, MonoLMF **lmf,
777 mgreg_t **save_locations,
778 StackFrameInfo *frame)
780 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
782 memset (frame, 0, sizeof (StackFrameInfo));
783 frame->ji = ji;
785 *new_ctx = *ctx;
787 if (ji != NULL) {
788 gssize regs [MONO_MAX_IREGS + 1];
789 guint8 *cfa;
790 guint32 unwind_info_len;
791 guint8 *unwind_info;
793 if (ji->is_trampoline)
794 frame->type = FRAME_TYPE_TRAMPOLINE;
795 else
796 frame->type = FRAME_TYPE_MANAGED;
798 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
800 regs [X86_EAX] = new_ctx->eax;
801 regs [X86_EBX] = new_ctx->ebx;
802 regs [X86_ECX] = new_ctx->ecx;
803 regs [X86_EDX] = new_ctx->edx;
804 regs [X86_ESP] = new_ctx->esp;
805 regs [X86_EBP] = new_ctx->ebp;
806 regs [X86_ESI] = new_ctx->esi;
807 regs [X86_EDI] = new_ctx->edi;
808 regs [X86_NREG] = new_ctx->eip;
810 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start,
811 (guint8*)ji->code_start + ji->code_size,
812 ip, NULL, regs, MONO_MAX_IREGS + 1,
813 save_locations, MONO_MAX_IREGS, &cfa);
815 new_ctx->eax = regs [X86_EAX];
816 new_ctx->ebx = regs [X86_EBX];
817 new_ctx->ecx = regs [X86_ECX];
818 new_ctx->edx = regs [X86_EDX];
819 new_ctx->esp = regs [X86_ESP];
820 new_ctx->ebp = regs [X86_EBP];
821 new_ctx->esi = regs [X86_ESI];
822 new_ctx->edi = regs [X86_EDI];
823 new_ctx->eip = regs [X86_NREG];
825 /* The CFA becomes the new SP value */
826 new_ctx->esp = (gssize)cfa;
828 /* Adjust IP */
829 new_ctx->eip --;
831 return TRUE;
832 } else if (*lmf) {
834 if (((guint64)(*lmf)->previous_lmf) & 2) {
836 * This LMF entry is created by the soft debug code to mark transitions to
837 * managed code done during invokes.
839 MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
841 g_assert (ext->debugger_invoke);
843 memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
845 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
847 frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
849 return TRUE;
852 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
853 frame->ji = ji;
854 } else {
855 if (!(*lmf)->method)
856 return FALSE;
857 frame->method = (*lmf)->method;
860 new_ctx->esi = (*lmf)->esi;
861 new_ctx->edi = (*lmf)->edi;
862 new_ctx->ebx = (*lmf)->ebx;
863 new_ctx->ebp = (*lmf)->ebp;
864 new_ctx->eip = (*lmf)->eip;
866 /* Adjust IP */
867 new_ctx->eip --;
869 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
871 /* Check if we are in a trampoline LMF frame */
872 if ((guint32)((*lmf)->previous_lmf) & 1) {
873 /* lmf->esp is set by the trampoline code */
874 new_ctx->esp = (*lmf)->esp;
876 else
877 /* the lmf is always stored on the stack, so the following
878 * expression points to a stack location which can be used as ESP */
879 new_ctx->esp = (unsigned long)&((*lmf)->eip);
881 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
883 return TRUE;
886 return FALSE;
889 gpointer
890 mono_arch_ip_from_context (void *sigctx)
892 #if defined(HOST_WATCHOS)
893 printf("WARNING: mono_arch_ip_from_context() called!\n");
894 return (NULL);
895 #elif defined(MONO_ARCH_USE_SIGACTION)
896 ucontext_t *ctx = (ucontext_t*)sigctx;
897 return (gpointer)UCONTEXT_REG_EIP (ctx);
898 #elif defined(HOST_WIN32)
899 return ((CONTEXT*)sigctx)->Eip;
900 #else
901 struct sigcontext *ctx = sigctx;
902 return (gpointer)ctx->SC_EIP;
903 #endif
907 * handle_exception:
909 * Called by resuming from a signal handler.
911 static void
912 handle_signal_exception (gpointer obj)
914 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
915 MonoContext ctx;
917 memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
919 mono_handle_exception (&ctx, obj);
921 mono_restore_context (&ctx);
925 * mono_x86_get_signal_exception_trampoline:
927 * This x86 specific trampoline is used to call handle_signal_exception.
929 gpointer
930 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
932 guint8 *start, *code;
933 MonoJumpInfo *ji = NULL;
934 GSList *unwind_ops = NULL;
935 int stack_size;
937 start = code = mono_global_codeman_reserve (128);
939 /* FIXME no unwind before we push ip */
940 /* Caller ip */
941 x86_push_reg (code, X86_ECX);
943 mono_add_unwind_op_def_cfa (unwind_ops, code, start, X86_ESP, 4);
944 mono_add_unwind_op_offset (unwind_ops, code, start, X86_NREG, -4);
946 /* Fix the alignment to be what apple expects */
947 stack_size = 12;
949 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
950 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
952 /* Arg1 */
953 x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
954 /* Branch to target */
955 x86_call_reg (code, X86_EDX);
957 g_assert ((code - start) < 128);
959 if (info)
960 *info = mono_tramp_info_create ("x86_signal_exception_trampoline", start, code - start, ji, unwind_ops);
961 else {
962 GSList *l;
964 for (l = unwind_ops; l; l = l->next)
965 g_free (l->data);
966 g_slist_free (unwind_ops);
969 mono_arch_flush_icache (start, code - start);
970 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
972 return start;
976 void
977 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
980 * Can't pass the obj on the stack, since we are executing on the
981 * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
982 * So put it into a register, and branch to a trampoline which
983 * pushes it.
985 ctx->eax = (mgreg_t)user_data;
986 ctx->ecx = ctx->eip;
987 ctx->edx = (mgreg_t)async_cb;
989 /*align the stack*/
990 ctx->esp = (ctx->esp - 16) & ~15;
991 ctx->eip = (mgreg_t)signal_exception_trampoline;
994 gboolean
995 mono_arch_handle_exception (void *sigctx, gpointer obj)
997 #if defined(MONO_ARCH_USE_SIGACTION)
998 MonoContext mctx;
999 ucontext_t *ctx = (ucontext_t*)sigctx;
1002 * Handling the exception in the signal handler is problematic, since the original
1003 * signal is disabled, and we could run arbitrary code though the debugger. So
1004 * resume into the normal stack and do most work there if possible.
1006 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1008 /* Pass the ctx parameter in TLS */
1009 mono_sigctx_to_monoctx (ctx, &jit_tls->ex_ctx);
1011 mctx = jit_tls->ex_ctx;
1012 mono_setup_async_callback (&mctx, handle_signal_exception, obj);
1013 mono_monoctx_to_sigctx (&mctx, sigctx);
1015 return TRUE;
1016 #elif defined (TARGET_WIN32)
1017 MonoContext mctx;
1018 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1019 struct sigcontext *ctx = (struct sigcontext *)sigctx;
1021 mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
1023 mctx = jit_tls->ex_ctx;
1024 mono_setup_async_callback (&mctx, handle_signal_exception, obj);
1025 mono_monoctx_to_sigctx (&mctx, sigctx);
1027 return TRUE;
1028 #else
1029 MonoContext mctx;
1031 mono_sigctx_to_monoctx (sigctx, &mctx);
1033 mono_handle_exception (&mctx, obj);
1035 mono_monoctx_to_sigctx (&mctx, sigctx);
1037 return TRUE;
1038 #endif
1041 static void
1042 restore_soft_guard_pages (void)
1044 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1045 if (jit_tls->stack_ovf_guard_base)
1046 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1050 * this function modifies mctx so that when it is restored, it
1051 * won't execcute starting at mctx.eip, but in a function that
1052 * will restore the protection on the soft-guard pages and return back to
1053 * continue at mctx.eip.
1055 static void
1056 prepare_for_guard_pages (MonoContext *mctx)
1058 gpointer *sp;
1059 sp = (gpointer)(mctx->esp);
1060 sp -= 1;
1061 /* the resturn addr */
1062 sp [0] = (gpointer)(mctx->eip);
1063 mctx->eip = (unsigned long)restore_soft_guard_pages;
1064 mctx->esp = (unsigned long)sp;
1067 static void
1068 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
1070 MonoContext mctx;
1072 mctx = *ctx;
1074 mono_handle_exception (&mctx, obj);
1075 if (stack_ovf)
1076 prepare_for_guard_pages (&mctx);
1077 mono_restore_context (&mctx);
1080 void
1081 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
1083 #ifdef MONO_ARCH_USE_SIGACTION
1084 MonoException *exc = NULL;
1085 ucontext_t *ctx = (ucontext_t*)sigctx;
1086 MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1087 gpointer *sp;
1088 int frame_size;
1090 /* if we didn't find a managed method for the ip address and it matches the fault
1091 * address, we assume we followed a broken pointer during an indirect call, so
1092 * we try the lookup again with the return address pushed on the stack
1094 if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1095 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1096 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1097 if (ji)
1098 UCONTEXT_REG_EIP (ctx) = sp [0];
1100 if (stack_ovf)
1101 exc = mono_domain_get ()->stack_overflow_ex;
1102 if (!ji)
1103 mono_handle_native_sigsegv (SIGSEGV, sigctx, siginfo);
1104 /* setup a call frame on the real stack so that control is returned there
1105 * and exception handling can continue.
1106 * If this was a stack overflow the caller already ensured the stack pages
1107 * needed have been unprotected.
1108 * The frame looks like:
1109 * ucontext struct
1110 * test_only arg
1111 * exception arg
1112 * ctx arg
1113 * return ip
1115 // FIXME: test_only is no more.
1116 frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4;
1117 frame_size += 15;
1118 frame_size &= ~15;
1119 sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1120 sp = (gpointer)((char*)sp - frame_size);
1121 /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1122 * goes at sp [-1]
1124 sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1125 sp [0] = sp + 4;
1126 sp [1] = exc;
1127 sp [2] = (gpointer)stack_ovf;
1128 mono_sigctx_to_monoctx (sigctx, (MonoContext*)(sp + 4));
1129 /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1130 UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1131 UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1132 #endif
1135 #if MONO_SUPPORT_TASKLETS
1136 MonoContinuationRestore
1137 mono_tasklets_arch_restore (void)
1139 static guint8* saved = NULL;
1140 guint8 *code, *start;
1142 if (saved)
1143 return (MonoContinuationRestore)saved;
1144 code = start = mono_global_codeman_reserve (48);
1145 /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1146 /* put cont in edx */
1147 x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1148 /* state in eax, so it's setup as the return value */
1149 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1151 /* setup the copy of the stack */
1152 x86_mov_reg_membase (code, X86_ECX, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1153 x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1154 x86_cld (code);
1155 x86_mov_reg_membase (code, X86_ESI, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1156 x86_mov_reg_membase (code, X86_EDI, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1157 x86_prefix (code, X86_REP_PREFIX);
1158 x86_movsl (code);
1160 /* now restore the registers from the LMF */
1161 x86_mov_reg_membase (code, X86_ECX, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1162 x86_mov_reg_membase (code, X86_EBX, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, ebx), 4);
1163 x86_mov_reg_membase (code, X86_EBP, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, ebp), 4);
1164 x86_mov_reg_membase (code, X86_ESI, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, esi), 4);
1165 x86_mov_reg_membase (code, X86_EDI, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, edi), 4);
1167 /* restore the lmf chain */
1168 /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1169 x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1171 x86_jump_membase (code, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1172 g_assert ((code - start) <= 48);
1173 saved = start;
1174 return (MonoContinuationRestore)saved;
1176 #endif
1179 * mono_arch_setup_resume_sighandler_ctx:
1181 * Setup CTX so execution continues at FUNC.
1183 void
1184 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1186 int align = (((gint32)MONO_CONTEXT_GET_SP (ctx)) % MONO_ARCH_FRAME_ALIGNMENT + 4);
1188 if (align != 0)
1189 MONO_CONTEXT_SET_SP (ctx, (gsize)MONO_CONTEXT_GET_SP (ctx) - align);
1191 MONO_CONTEXT_SET_IP (ctx, func);