2 * exceptions-amd64.c: exception support for AMD64
5 * Dietmar Maurer (dietmar@ximian.com)
7 * (C) 2001 Ximian, Inc.
8 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
20 #ifdef HAVE_UCONTEXT_H
24 #include <mono/arch/amd64/amd64-codegen.h>
25 #include <mono/metadata/abi-details.h>
26 #include <mono/metadata/appdomain.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/threads.h>
29 #include <mono/metadata/threads-types.h>
30 #include <mono/metadata/debug-helpers.h>
31 #include <mono/metadata/exception.h>
32 #include <mono/metadata/gc-internals.h>
33 #include <mono/metadata/mono-debug.h>
34 #include <mono/utils/mono-mmap.h>
37 #include "mini-amd64.h"
40 #define ALIGN_TO(val,align) (((val) + ((align) - 1)) & ~((align) - 1))
43 static MonoW32ExceptionHandler fpe_handler;
44 static MonoW32ExceptionHandler ill_handler;
45 static MonoW32ExceptionHandler segv_handler;
47 LPTOP_LEVEL_EXCEPTION_FILTER mono_old_win_toplevel_exception_filter;
48 void *mono_win_vectored_exception_handle;
50 #define W32_SEH_HANDLE_EX(_ex) \
51 if (_ex##_handler) _ex##_handler(0, ep, ctx)
53 static LONG CALLBACK seh_unhandled_exception_filter(EXCEPTION_POINTERS* ep)
55 #ifndef MONO_CROSS_COMPILE
56 if (mono_old_win_toplevel_exception_filter) {
57 return (*mono_old_win_toplevel_exception_filter)(ep);
61 mono_handle_native_sigsegv (SIGSEGV, NULL, NULL);
63 return EXCEPTION_CONTINUE_SEARCH;
67 * Unhandled Exception Filter
68 * Top-level per-process exception handler.
70 static LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep)
75 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
77 /* If the thread is not managed by the runtime return early */
79 return EXCEPTION_CONTINUE_SEARCH;
81 jit_tls->mono_win_chained_exception_needs_run = FALSE;
82 res = EXCEPTION_CONTINUE_EXECUTION;
84 er = ep->ExceptionRecord;
85 ctx = ep->ContextRecord;
87 switch (er->ExceptionCode) {
88 case EXCEPTION_ACCESS_VIOLATION:
89 W32_SEH_HANDLE_EX(segv);
91 case EXCEPTION_ILLEGAL_INSTRUCTION:
92 W32_SEH_HANDLE_EX(ill);
94 case EXCEPTION_INT_DIVIDE_BY_ZERO:
95 case EXCEPTION_INT_OVERFLOW:
96 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
97 case EXCEPTION_FLT_OVERFLOW:
98 case EXCEPTION_FLT_UNDERFLOW:
99 case EXCEPTION_FLT_INEXACT_RESULT:
100 W32_SEH_HANDLE_EX(fpe);
103 jit_tls->mono_win_chained_exception_needs_run = TRUE;
107 if (jit_tls->mono_win_chained_exception_needs_run) {
108 /* Don't copy context back if we chained exception
109 * as the handler may have modfied the EXCEPTION_POINTERS
110 * directly. We don't pass sigcontext to chained handlers.
111 * Return continue search so the UnhandledExceptionFilter
112 * can correctly chain the exception.
114 res = EXCEPTION_CONTINUE_SEARCH;
120 void win32_seh_init()
122 mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter);
123 mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler);
126 void win32_seh_cleanup()
130 if (mono_old_win_toplevel_exception_filter) SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter);
132 ret = RemoveVectoredExceptionHandler (mono_win_vectored_exception_handle);
136 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
140 fpe_handler = handler;
143 ill_handler = handler;
146 segv_handler = handler;
153 #endif /* TARGET_WIN32 */
156 * mono_arch_get_restore_context:
158 * Returns a pointer to a method which restores a previously saved sigcontext.
161 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
163 guint8 *start = NULL;
165 MonoJumpInfo *ji = NULL;
166 GSList *unwind_ops = NULL;
169 /* restore_contect (MonoContext *ctx) */
171 start = code = (guint8 *)mono_global_codeman_reserve (256);
173 amd64_mov_reg_reg (code, AMD64_R11, AMD64_ARG_REG1, 8);
175 /* Restore all registers except %rip and %r11 */
176 gregs_offset = MONO_STRUCT_OFFSET (MonoContext, gregs);
177 for (i = 0; i < AMD64_NREG; ++i) {
178 #if defined(__native_client_codegen__)
182 if (i != AMD64_RIP && i != AMD64_RSP && i != AMD64_R8 && i != AMD64_R9 && i != AMD64_R10 && i != AMD64_R11)
183 amd64_mov_reg_membase (code, i, AMD64_R11, gregs_offset + (i * 8), 8);
187 * The context resides on the stack, in the stack frame of the
188 * caller of this function. The stack pointer that we need to
189 * restore is potentially many stack frames higher up, so the
190 * distance between them can easily be more than the red zone
191 * size. Hence the stack pointer can be restored only after
192 * we have finished loading everything from the context.
194 amd64_mov_reg_membase (code, AMD64_R8, AMD64_R11, gregs_offset + (AMD64_RSP * 8), 8);
195 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, gregs_offset + (AMD64_RIP * 8), 8);
196 amd64_mov_reg_reg (code, AMD64_RSP, AMD64_R8, 8);
198 /* jump to the saved IP */
199 amd64_jump_reg (code, AMD64_R11);
201 nacl_global_codeman_validate (&start, 256, &code);
203 mono_arch_flush_icache (start, code - start);
204 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
207 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
213 * mono_arch_get_call_filter:
215 * Returns a pointer to a method which calls an exception filter. We
216 * also use this function to call finally handlers (we pass NULL as
217 * @exc object in this case).
220 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
226 MonoJumpInfo *ji = NULL;
227 GSList *unwind_ops = NULL;
228 const guint kMaxCodeSize = NACL_SIZE (128, 256);
230 start = code = (guint8 *)mono_global_codeman_reserve (kMaxCodeSize);
232 /* call_filter (MonoContext *ctx, unsigned long eip) */
235 /* Alloc new frame */
236 amd64_push_reg (code, AMD64_RBP);
237 amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, 8);
239 /* Save callee saved regs */
241 for (i = 0; i < AMD64_NREG; ++i)
242 if (AMD64_IS_CALLEE_SAVED_REG (i)) {
243 amd64_push_reg (code, i);
249 amd64_push_reg (code, AMD64_RBP);
251 /* Make stack misaligned, the call will make it aligned again */
253 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
255 gregs_offset = MONO_STRUCT_OFFSET (MonoContext, gregs);
258 amd64_mov_reg_membase (code, AMD64_RBP, AMD64_ARG_REG1, gregs_offset + (AMD64_RBP * 8), 8);
259 /* load callee saved regs */
260 for (i = 0; i < AMD64_NREG; ++i) {
261 #if defined(__native_client_codegen__)
265 if (AMD64_IS_CALLEE_SAVED_REG (i) && i != AMD64_RBP)
266 amd64_mov_reg_membase (code, i, AMD64_ARG_REG1, gregs_offset + (i * 8), 8);
268 /* load exc register */
269 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_ARG_REG1, gregs_offset + (AMD64_RAX * 8), 8);
271 /* call the handler */
272 amd64_call_reg (code, AMD64_ARG_REG2);
275 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
278 amd64_pop_reg (code, AMD64_RBP);
280 /* Restore callee saved regs */
281 for (i = AMD64_NREG; i >= 0; --i)
282 if (AMD64_IS_CALLEE_SAVED_REG (i))
283 amd64_pop_reg (code, i);
288 g_assert ((code - start) < kMaxCodeSize);
290 nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
292 mono_arch_flush_icache (start, code - start);
293 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
296 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
302 * The first few arguments are dummy, to force the other arguments to be passed on
303 * the stack, this avoids overwriting the argument registers in the throw trampoline.
306 mono_amd64_throw_exception (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
307 guint64 dummy5, guint64 dummy6,
308 MonoContext *mctx, MonoObject *exc, gboolean rethrow)
313 /* mctx is on the caller's stack */
314 memcpy (&ctx, mctx, sizeof (MonoContext));
316 if (mono_object_isinst_checked (exc, mono_defaults.exception_class, &error)) {
317 MonoException *mono_ex = (MonoException*)exc;
319 mono_ex->stack_trace = NULL;
320 mono_ex->trace_ips = NULL;
323 mono_error_assert_ok (&error);
325 /* adjust eip so that it point into the call instruction */
326 ctx.gregs [AMD64_RIP] --;
328 mono_handle_exception (&ctx, exc);
329 mono_restore_context (&ctx);
330 g_assert_not_reached ();
334 mono_amd64_throw_corlib_exception (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
335 guint64 dummy5, guint64 dummy6,
336 MonoContext *mctx, guint32 ex_token_index, gint64 pc_offset)
338 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
341 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
343 mctx->gregs [AMD64_RIP] -= pc_offset;
345 /* Negate the ip adjustment done in mono_amd64_throw_exception () */
346 mctx->gregs [AMD64_RIP] += 1;
348 mono_amd64_throw_exception (dummy1, dummy2, dummy3, dummy4, dummy5, dummy6, mctx, (MonoObject*)ex, FALSE);
352 mono_amd64_resume_unwind (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
353 guint64 dummy5, guint64 dummy6,
354 MonoContext *mctx, guint32 dummy7, gint64 dummy8)
356 /* Only the register parameters are valid */
359 /* mctx is on the caller's stack */
360 memcpy (&ctx, mctx, sizeof (MonoContext));
362 mono_resume_unwind (&ctx);
366 * get_throw_trampoline:
368 * Generate a call to mono_amd64_throw_exception/
369 * mono_amd64_throw_corlib_exception.
372 get_throw_trampoline (MonoTrampInfo **info, gboolean rethrow, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, const char *tramp_name, gboolean aot)
376 MonoJumpInfo *ji = NULL;
377 GSList *unwind_ops = NULL;
378 int i, stack_size, arg_offsets [16], ctx_offset, regs_offset, dummy_stack_space;
379 const guint kMaxCodeSize = NACL_SIZE (256, 512);
382 dummy_stack_space = 6 * sizeof(mgreg_t); /* Windows expects stack space allocated for all 6 dummy args. */
384 dummy_stack_space = 0;
387 start = code = (guint8 *)mono_global_codeman_reserve (kMaxCodeSize);
389 /* The stack is unaligned on entry */
390 stack_size = ALIGN_TO (sizeof (MonoContext) + 64 + dummy_stack_space, MONO_ARCH_FRAME_ALIGNMENT) + 8;
395 unwind_ops = mono_arch_get_cie_program ();
398 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_size);
400 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 8);
403 * To hide linux/windows calling convention differences, we pass all arguments on
404 * the stack by passing 6 dummy values in registers.
407 arg_offsets [0] = dummy_stack_space + 0;
408 arg_offsets [1] = dummy_stack_space + sizeof(mgreg_t);
409 arg_offsets [2] = dummy_stack_space + sizeof(mgreg_t) * 2;
410 ctx_offset = dummy_stack_space + sizeof(mgreg_t) * 4;
411 regs_offset = ctx_offset + MONO_STRUCT_OFFSET (MonoContext, gregs);
414 for (i = 0; i < AMD64_NREG; ++i)
416 amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
418 amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, stack_size + sizeof(mgreg_t));
419 amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RSP * sizeof(mgreg_t)), X86_EAX, sizeof(mgreg_t));
421 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, stack_size, sizeof(mgreg_t));
422 amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RIP * sizeof(mgreg_t)), AMD64_RAX, sizeof(mgreg_t));
423 /* Set arg1 == ctx */
424 amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, ctx_offset);
425 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [0], AMD64_RAX, sizeof(mgreg_t));
426 /* Set arg2 == exc/ex_token_index */
428 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [1], 0, sizeof(mgreg_t));
430 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [1], AMD64_ARG_REG1, sizeof(mgreg_t));
431 /* Set arg3 == rethrow/pc offset */
433 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], 0, sizeof(mgreg_t));
437 * The caller doesn't pass in a pc/pc offset, instead we simply use the
438 * caller ip. Negate the pc adjustment done in mono_amd64_throw_corlib_exception ().
440 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], 1, sizeof(mgreg_t));
442 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [2], AMD64_ARG_REG2, sizeof(mgreg_t));
444 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], rethrow, sizeof(mgreg_t));
448 const char *icall_name;
451 icall_name = "mono_amd64_resume_unwind";
453 icall_name = "mono_amd64_throw_corlib_exception";
455 icall_name = "mono_amd64_throw_exception";
456 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
457 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
459 amd64_mov_reg_imm (code, AMD64_R11, resume_unwind ? ((gpointer)mono_amd64_resume_unwind) : (corlib ? (gpointer)mono_amd64_throw_corlib_exception : (gpointer)mono_amd64_throw_exception));
461 amd64_call_reg (code, AMD64_R11);
462 amd64_breakpoint (code);
464 mono_arch_flush_icache (start, code - start);
466 g_assert ((code - start) < kMaxCodeSize);
468 nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
469 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
472 *info = mono_tramp_info_create (tramp_name, start, code - start, ji, unwind_ops);
478 * mono_arch_get_throw_exception:
480 * Returns a function pointer which can be used to raise
481 * exceptions. The returned function has the following
482 * signature: void (*func) (MonoException *exc);
486 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
488 return get_throw_trampoline (info, FALSE, FALSE, FALSE, FALSE, "throw_exception", aot);
492 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
494 return get_throw_trampoline (info, TRUE, FALSE, FALSE, FALSE, "rethrow_exception", aot);
498 * mono_arch_get_throw_corlib_exception:
500 * Returns a function pointer which can be used to raise
501 * corlib exceptions. The returned function has the following
502 * signature: void (*func) (guint32 ex_token, guint32 offset);
503 * Here, offset is the offset which needs to be substracted from the caller IP
504 * to get the IP of the throw. Passing the offset has the advantage that it
505 * needs no relocations in the caller.
508 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
510 return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
514 * mono_arch_unwind_frame:
516 * This function is used to gather information from @ctx, and store it in @frame_info.
517 * It unwinds one stack frame, and stores the resulting context into @new_ctx. @lmf
518 * is modified if needed.
519 * Returns TRUE on success, FALSE otherwise.
522 mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls,
523 MonoJitInfo *ji, MonoContext *ctx,
524 MonoContext *new_ctx, MonoLMF **lmf,
525 mgreg_t **save_locations,
526 StackFrameInfo *frame)
528 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
531 memset (frame, 0, sizeof (StackFrameInfo));
537 mgreg_t regs [MONO_MAX_IREGS + 1];
539 guint32 unwind_info_len;
541 guint8 *epilog = NULL;
543 if (ji->is_trampoline)
544 frame->type = FRAME_TYPE_TRAMPOLINE;
546 frame->type = FRAME_TYPE_MANAGED;
548 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
550 frame->unwind_info = unwind_info;
551 frame->unwind_info_len = unwind_info_len;
554 printf ("%s %p %p\n", ji->d.method->name, ji->code_start, ip);
555 mono_print_unwind_info (unwind_info, unwind_info_len);
557 /* LLVM compiled code doesn't have this info */
558 if (ji->has_arch_eh_info)
559 epilog = (guint8*)ji->code_start + ji->code_size - mono_jinfo_get_epilog_size (ji);
561 for (i = 0; i < AMD64_NREG; ++i)
562 regs [i] = new_ctx->gregs [i];
564 mono_unwind_frame (unwind_info, unwind_info_len, (guint8 *)ji->code_start,
565 (guint8*)ji->code_start + ji->code_size,
566 (guint8 *)ip, epilog ? &epilog : NULL, regs, MONO_MAX_IREGS + 1,
567 save_locations, MONO_MAX_IREGS, &cfa);
569 for (i = 0; i < AMD64_NREG; ++i)
570 new_ctx->gregs [i] = regs [i];
572 /* The CFA becomes the new SP value */
573 new_ctx->gregs [AMD64_RSP] = (mgreg_t)cfa;
576 new_ctx->gregs [AMD64_RIP] --;
582 if (((guint64)(*lmf)->previous_lmf) & 2) {
584 * This LMF entry is created by the soft debug code to mark transitions to
585 * managed code done during invokes.
587 MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
589 g_assert (ext->debugger_invoke);
591 memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
593 *lmf = (MonoLMF *)(((guint64)(*lmf)->previous_lmf) & ~7);
595 frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
600 if (((guint64)(*lmf)->previous_lmf) & 4) {
601 MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
603 rip = (guint64)MONO_CONTEXT_GET_IP (ext->ctx);
604 } else if (((guint64)(*lmf)->previous_lmf) & 1) {
605 /* This LMF has the rip field set */
607 } else if ((*lmf)->rsp == 0) {
612 * The rsp field is set just before the call which transitioned to native
613 * code. Obtain the rip from the stack.
615 rip = *(guint64*)((*lmf)->rsp - sizeof(mgreg_t));
618 ji = mini_jit_info_table_find (domain, (char *)rip, NULL);
620 * FIXME: ji == NULL can happen when a managed-to-native wrapper is interrupted
621 * in the soft debugger suspend code, since (*lmf)->rsp no longer points to the
629 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
631 if (((guint64)(*lmf)->previous_lmf) & 4) {
632 MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
634 /* Trampoline frame */
635 for (i = 0; i < AMD64_NREG; ++i)
636 new_ctx->gregs [i] = ext->ctx->gregs [i];
638 new_ctx->gregs [AMD64_RIP] --;
641 * The registers saved in the LMF will be restored using the normal unwind info,
642 * when the wrapper frame is processed.
646 new_ctx->gregs [AMD64_RIP] = rip;
647 new_ctx->gregs [AMD64_RSP] = (*lmf)->rsp;
648 new_ctx->gregs [AMD64_RBP] = (*lmf)->rbp;
649 for (i = 0; i < AMD64_NREG; ++i) {
650 if (AMD64_IS_CALLEE_SAVED_REG (i) && i != AMD64_RBP)
651 new_ctx->gregs [i] = 0;
655 *lmf = (MonoLMF *)(((guint64)(*lmf)->previous_lmf) & ~7);
666 * Called by resuming from a signal handler.
669 handle_signal_exception (gpointer obj)
671 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
674 memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
676 mono_handle_exception (&ctx, (MonoObject *)obj);
678 mono_restore_context (&ctx);
682 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
684 guint64 sp = ctx->gregs [AMD64_RSP];
686 ctx->gregs [AMD64_RDI] = (guint64)user_data;
688 /* Allocate a stack frame below the red zone */
690 /* The stack should be unaligned */
694 /* Preserve the call chain to prevent crashes in the libgcc unwinder (#15969) */
695 *(guint64*)sp = ctx->gregs [AMD64_RIP];
697 ctx->gregs [AMD64_RSP] = sp;
698 ctx->gregs [AMD64_RIP] = (guint64)async_cb;
702 * mono_arch_handle_exception:
704 * @ctx: saved processor state
705 * @obj: the exception object
708 mono_arch_handle_exception (void *sigctx, gpointer obj)
710 #if defined(MONO_ARCH_USE_SIGACTION)
714 * Handling the exception in the signal handler is problematic, since the original
715 * signal is disabled, and we could run arbitrary code though the debugger. So
716 * resume into the normal stack and do most work there if possible.
718 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
720 /* Pass the ctx parameter in TLS */
721 mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
723 mctx = jit_tls->ex_ctx;
724 mono_arch_setup_async_callback (&mctx, handle_signal_exception, obj);
725 mono_monoctx_to_sigctx (&mctx, sigctx);
731 mono_sigctx_to_monoctx (sigctx, &mctx);
733 mono_handle_exception (&mctx, obj);
735 mono_monoctx_to_sigctx (&mctx, sigctx);
742 mono_arch_ip_from_context (void *sigctx)
744 #if defined(MONO_ARCH_USE_SIGACTION)
745 ucontext_t *ctx = (ucontext_t*)sigctx;
747 return (gpointer)UCONTEXT_REG_RIP (ctx);
748 #elif defined(HOST_WIN32)
749 return ((CONTEXT*)sigctx)->Rip;
751 MonoContext *ctx = sigctx;
752 return (gpointer)ctx->gregs [AMD64_RIP];
757 restore_soft_guard_pages (void)
759 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
760 if (jit_tls->stack_ovf_guard_base)
761 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
765 * this function modifies mctx so that when it is restored, it
766 * won't execcute starting at mctx.eip, but in a function that
767 * will restore the protection on the soft-guard pages and return back to
768 * continue at mctx.eip.
771 prepare_for_guard_pages (MonoContext *mctx)
774 sp = (gpointer *)(mctx->gregs [AMD64_RSP]);
776 /* the return addr */
777 sp [0] = (gpointer)(mctx->gregs [AMD64_RIP]);
778 mctx->gregs [AMD64_RIP] = (guint64)restore_soft_guard_pages;
779 mctx->gregs [AMD64_RSP] = (guint64)sp;
783 altstack_handle_and_restore (MonoContext *ctx, MonoObject *obj, gboolean stack_ovf)
789 mono_handle_exception (&mctx, obj);
791 prepare_for_guard_pages (&mctx);
792 mono_restore_context (&mctx);
796 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
798 #if defined(MONO_ARCH_USE_SIGACTION)
799 MonoException *exc = NULL;
800 MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (char *)UCONTEXT_REG_RIP (sigctx), NULL);
803 MonoContext *copied_ctx;
806 exc = mono_domain_get ()->stack_overflow_ex;
808 mono_handle_native_sigsegv (SIGSEGV, sigctx, siginfo);
810 /* setup a call frame on the real stack so that control is returned there
811 * and exception handling can continue.
812 * The frame looks like:
816 * 128 is the size of the red zone
818 frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4 + 128;
821 sp = (gpointer *)(UCONTEXT_REG_RSP (sigctx) & ~15);
822 sp = (gpointer *)((char*)sp - frame_size);
823 copied_ctx = (MonoContext*)(sp + 4);
824 /* the arguments must be aligned */
825 sp [-1] = (gpointer)UCONTEXT_REG_RIP (sigctx);
826 mono_sigctx_to_monoctx (sigctx, copied_ctx);
827 /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
828 UCONTEXT_REG_RIP (sigctx) = (unsigned long)altstack_handle_and_restore;
829 UCONTEXT_REG_RSP (sigctx) = (unsigned long)(sp - 1);
830 UCONTEXT_REG_RDI (sigctx) = (unsigned long)(copied_ctx);
831 UCONTEXT_REG_RSI (sigctx) = (guint64)exc;
832 UCONTEXT_REG_RDX (sigctx) = stack_ovf;
837 mono_amd64_get_original_ip (void)
839 MonoLMF *lmf = mono_get_lmf ();
843 /* Reset the change to previous_lmf */
844 lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf & ~1);
850 mono_amd64_get_exception_trampolines (gboolean aot)
853 GSList *tramps = NULL;
855 /* LLVM needs different throw trampolines */
856 get_throw_trampoline (&info, FALSE, TRUE, FALSE, FALSE, "llvm_throw_corlib_exception_trampoline", aot);
857 tramps = g_slist_prepend (tramps, info);
859 get_throw_trampoline (&info, FALSE, TRUE, TRUE, FALSE, "llvm_throw_corlib_exception_abs_trampoline", aot);
860 tramps = g_slist_prepend (tramps, info);
862 get_throw_trampoline (&info, FALSE, TRUE, TRUE, TRUE, "llvm_resume_unwind_trampoline", aot);
863 tramps = g_slist_prepend (tramps, info);
869 mono_arch_exceptions_init (void)
875 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_trampoline");
876 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
877 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_abs_trampoline");
878 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
879 tramp = mono_aot_get_trampoline ("llvm_resume_unwind_trampoline");
880 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
882 /* Call this to avoid initialization races */
883 tramps = mono_amd64_get_exception_trampolines (FALSE);
884 for (l = tramps; l; l = l->next) {
885 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
887 mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE);
888 mono_tramp_info_register (info, NULL);
890 g_slist_free (tramps);
897 * The mono_arch_unwindinfo* methods are used to build and add
898 * function table info for each emitted method from mono. On Winx64
899 * the seh handler will not be called if the mono methods are not
900 * added to the function table.
902 * We should not need to add non-volatile register info to the
903 * table since mono stores that info elsewhere. (Except for the register
907 #define MONO_MAX_UNWIND_CODES 22
909 typedef union _UNWIND_CODE {
916 } UNWIND_CODE, *PUNWIND_CODE;
918 typedef struct _UNWIND_INFO {
923 guchar FrameRegister : 4;
924 guchar FrameOffset : 4;
925 /* custom size for mono allowing for mono allowing for*/
926 /*UWOP_PUSH_NONVOL ebp offset = 21*/
927 /*UWOP_ALLOC_LARGE : requires 2 or 3 offset = 20*/
928 /*UWOP_SET_FPREG : requires 2 offset = 17*/
929 /*UWOP_PUSH_NONVOL offset = 15-0*/
930 UNWIND_CODE UnwindCode[MONO_MAX_UNWIND_CODES];
932 /* UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
934 * OPTIONAL ULONG ExceptionHandler;
935 * OPTIONAL ULONG FunctionEntry;
937 * OPTIONAL ULONG ExceptionData[]; */
938 } UNWIND_INFO, *PUNWIND_INFO;
942 RUNTIME_FUNCTION runtimeFunction;
943 UNWIND_INFO unwindInfo;
944 } MonoUnwindInfo, *PMonoUnwindInfo;
947 mono_arch_unwindinfo_create (gpointer* monoui)
949 PMonoUnwindInfo newunwindinfo;
950 *monoui = newunwindinfo = g_new0 (MonoUnwindInfo, 1);
951 newunwindinfo->unwindInfo.Version = 1;
955 mono_arch_unwindinfo_add_push_nonvol (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
957 PMonoUnwindInfo unwindinfo;
958 PUNWIND_CODE unwindcode;
961 mono_arch_unwindinfo_create (monoui);
963 unwindinfo = (MonoUnwindInfo*)*monoui;
965 if (unwindinfo->unwindInfo.CountOfCodes >= MONO_MAX_UNWIND_CODES)
966 g_error ("Larger allocation needed for the unwind information.");
968 codeindex = MONO_MAX_UNWIND_CODES - (++unwindinfo->unwindInfo.CountOfCodes);
969 unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
970 unwindcode->UnwindOp = 0; /*UWOP_PUSH_NONVOL*/
971 unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
972 unwindcode->OpInfo = reg;
974 if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
975 g_error ("Adding unwind info in wrong order.");
977 unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
981 mono_arch_unwindinfo_add_set_fpreg (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
983 PMonoUnwindInfo unwindinfo;
984 PUNWIND_CODE unwindcode;
987 mono_arch_unwindinfo_create (monoui);
989 unwindinfo = (MonoUnwindInfo*)*monoui;
991 if (unwindinfo->unwindInfo.CountOfCodes + 1 >= MONO_MAX_UNWIND_CODES)
992 g_error ("Larger allocation needed for the unwind information.");
994 codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += 2);
995 unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
996 unwindcode->FrameOffset = 0; /*Assuming no frame pointer offset for mono*/
998 unwindcode->UnwindOp = 3; /*UWOP_SET_FPREG*/
999 unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1000 unwindcode->OpInfo = reg;
1002 unwindinfo->unwindInfo.FrameRegister = reg;
1004 if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1005 g_error ("Adding unwind info in wrong order.");
1007 unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1011 mono_arch_unwindinfo_add_alloc_stack (gpointer* monoui, gpointer codebegin, gpointer nextip, guint size )
1013 PMonoUnwindInfo unwindinfo;
1014 PUNWIND_CODE unwindcode;
1018 mono_arch_unwindinfo_create (monoui);
1020 unwindinfo = (MonoUnwindInfo*)*monoui;
1023 g_error ("Stack allocation must be equal to or greater than 0x8.");
1027 else if (size <= 0x7FFF8)
1032 if (unwindinfo->unwindInfo.CountOfCodes + codesneeded > MONO_MAX_UNWIND_CODES)
1033 g_error ("Larger allocation needed for the unwind information.");
1035 codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += codesneeded);
1036 unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1038 if (codesneeded == 1) {
1039 /*The size of the allocation is
1040 (the number in the OpInfo member) times 8 plus 8*/
1041 unwindcode->OpInfo = (size - 8)/8;
1042 unwindcode->UnwindOp = 2; /*UWOP_ALLOC_SMALL*/
1045 if (codesneeded == 3) {
1046 /*the unscaled size of the allocation is recorded
1047 in the next two slots in little-endian format*/
1048 *((unsigned int*)(&unwindcode->FrameOffset)) = size;
1050 unwindcode->OpInfo = 1;
1053 /*the size of the allocation divided by 8
1054 is recorded in the next slot*/
1055 unwindcode->FrameOffset = size/8;
1057 unwindcode->OpInfo = 0;
1060 unwindcode->UnwindOp = 1; /*UWOP_ALLOC_LARGE*/
1063 unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1065 if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1066 g_error ("Adding unwind info in wrong order.");
1068 unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1072 mono_arch_unwindinfo_get_size (gpointer monoui)
1074 PMonoUnwindInfo unwindinfo;
1078 unwindinfo = (MonoUnwindInfo*)monoui;
1079 return (8 + sizeof (MonoUnwindInfo)) -
1080 (sizeof (UNWIND_CODE) * (MONO_MAX_UNWIND_CODES - unwindinfo->unwindInfo.CountOfCodes));
1083 static PRUNTIME_FUNCTION
1084 MONO_GET_RUNTIME_FUNCTION_CALLBACK ( DWORD64 ControlPc, IN PVOID Context )
1088 PMonoUnwindInfo targetinfo;
1089 MonoDomain *domain = mono_domain_get ();
1091 ji = mini_jit_info_table_find (domain, (char*)ControlPc, NULL);
1095 pos = (guint64)(((char*)ji->code_start) + ji->code_size);
1097 targetinfo = (PMonoUnwindInfo)ALIGN_TO (pos, 8);
1099 targetinfo->runtimeFunction.UnwindData = ((DWORD64)&targetinfo->unwindInfo) - ((DWORD64)Context);
1101 return &targetinfo->runtimeFunction;
1105 mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint code_size)
1107 PMonoUnwindInfo unwindinfo, targetinfo;
1109 guint64 targetlocation;
1113 unwindinfo = (MonoUnwindInfo*)*monoui;
1114 targetlocation = (guint64)&(((guchar*)code)[code_size]);
1115 targetinfo = (PMonoUnwindInfo) ALIGN_TO(targetlocation, 8);
1117 unwindinfo->runtimeFunction.EndAddress = code_size;
1118 unwindinfo->runtimeFunction.UnwindData = ((guchar*)&targetinfo->unwindInfo) - ((guchar*)code);
1120 memcpy (targetinfo, unwindinfo, sizeof (MonoUnwindInfo) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
1122 codecount = unwindinfo->unwindInfo.CountOfCodes;
1124 memcpy (&targetinfo->unwindInfo.UnwindCode[0], &unwindinfo->unwindInfo.UnwindCode[MONO_MAX_UNWIND_CODES-codecount],
1125 sizeof (UNWIND_CODE) * unwindinfo->unwindInfo.CountOfCodes);
1128 g_free (unwindinfo);
1131 RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
1136 #if MONO_SUPPORT_TASKLETS
1137 MonoContinuationRestore
1138 mono_tasklets_arch_restore (void)
1140 static guint8* saved = NULL;
1141 guint8 *code, *start;
1142 int cont_reg = AMD64_R9; /* register usable on both call conventions */
1143 const guint kMaxCodeSize = NACL_SIZE (64, 128);
1147 return (MonoContinuationRestore)saved;
1148 code = start = (guint8 *)mono_global_codeman_reserve (kMaxCodeSize);
1149 /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1150 /* cont is in AMD64_ARG_REG1 ($rcx or $rdi)
1151 * state is in AMD64_ARG_REG2 ($rdx or $rsi)
1152 * lmf_addr is in AMD64_ARG_REG3 ($r8 or $rdx)
1153 * We move cont to cont_reg since we need both rcx and rdi for the copy
1154 * state is moved to $rax so it's setup as the return value and we can overwrite $rsi
1156 amd64_mov_reg_reg (code, cont_reg, MONO_AMD64_ARG_REG1, 8);
1157 amd64_mov_reg_reg (code, AMD64_RAX, MONO_AMD64_ARG_REG2, 8);
1158 /* setup the copy of the stack */
1159 amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), sizeof (int));
1160 amd64_shift_reg_imm (code, X86_SHR, AMD64_RCX, 3);
1162 amd64_mov_reg_membase (code, AMD64_RSI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), sizeof (gpointer));
1163 amd64_mov_reg_membase (code, AMD64_RDI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), sizeof (gpointer));
1164 amd64_prefix (code, X86_REP_PREFIX);
1167 /* now restore the registers from the LMF */
1169 amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 8);
1170 amd64_mov_reg_membase (code, AMD64_RSP, AMD64_RCX, MONO_STRUCT_OFFSET (MonoLMF, rsp), 8);
1172 /* restore the lmf chain */
1173 /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1174 x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1176 /* state is already in rax */
1177 amd64_jump_membase (code, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1178 g_assert ((code - start) <= kMaxCodeSize);
1180 nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1181 mono_arch_flush_icache (start, code - start);
1182 mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
1185 return (MonoContinuationRestore)saved;
1190 * mono_arch_setup_resume_sighandler_ctx:
1192 * Setup CTX so execution continues at FUNC.
1195 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1198 * When resuming from a signal handler, the stack should be misaligned, just like right after
1201 if ((((guint64)MONO_CONTEXT_GET_SP (ctx)) % 16) == 0)
1202 MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
1203 MONO_CONTEXT_SET_IP (ctx, func);