Significant disambiguation between host and target. (#10969)
[mono-project.git] / mono / mini / exceptions-x86.c
blob415b9ba20cfded3ef91a281b585d31f0e51dcc36
1 /**
2 * \file
3 * exception support for x86
5 * Authors:
6 * Dietmar Maurer (dietmar@ximian.com)
8 * (C) 2001 Ximian, Inc.
9 */
11 #include <config.h>
13 #include <glib.h>
14 #include <signal.h>
15 #include <string.h>
16 #ifdef HAVE_UCONTEXT_H
17 #include <ucontext.h>
18 #endif
20 #include <mono/metadata/abi-details.h>
21 #include <mono/arch/x86/x86-codegen.h>
22 #include <mono/metadata/appdomain.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/debug-helpers.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/gc-internals.h>
28 #include <mono/metadata/mono-debug.h>
29 #include <mono/utils/mono-mmap.h>
31 #include "mini.h"
32 #include "mini-x86.h"
33 #include "mini-runtime.h"
34 #include "tasklets.h"
35 #include "aot-runtime.h"
37 static gpointer signal_exception_trampoline;
39 gpointer
40 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot);
42 #ifdef TARGET_WIN32
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 int (*gUnhandledExceptionHandler)(EXCEPTION_POINTERS*);
53 #ifndef PROCESS_CALLBACK_FILTER_ENABLED
54 # define PROCESS_CALLBACK_FILTER_ENABLED 1
55 #endif
57 #define W32_SEH_HANDLE_EX(_ex) \
58 if (_ex##_handler) _ex##_handler(0, ep, ctx)
60 LONG CALLBACK seh_unhandled_exception_filter(EXCEPTION_POINTERS* ep)
62 #ifndef MONO_CROSS_COMPILE
63 if (mono_old_win_toplevel_exception_filter) {
64 return (*mono_old_win_toplevel_exception_filter)(ep);
66 #endif
68 mono_handle_native_crash ("SIGSEGV", NULL, NULL);
70 return EXCEPTION_CONTINUE_SEARCH;
74 * mono_win32_get_handle_stackoverflow (void):
76 * Returns a pointer to a method which restores the current context stack
77 * and calls handle_exceptions, when done restores the original stack.
79 static gpointer
80 mono_win32_get_handle_stackoverflow (void)
82 static guint8 *start = NULL;
83 guint8 *code;
85 if (start)
86 return start;
88 /* restore_contect (void *sigctx) */
89 start = code = mono_global_codeman_reserve (128);
91 /* load context into ebx */
92 x86_mov_reg_membase (code, X86_EBX, X86_ESP, 4, 4);
94 /* move current stack into edi for later restore */
95 x86_mov_reg_reg (code, X86_EDI, X86_ESP);
97 /* use the new freed stack from sigcontext */
98 /* XXX replace usage of struct sigcontext with MonoContext so we can use MONO_STRUCT_OFFSET */
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);
115 /* return */
116 x86_ret (code);
118 mono_arch_flush_icache (start, code - start);
119 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
121 return start;
124 /* Special hack to workaround the fact that the
125 * when the SEH handler is called the stack is
126 * to small to recover.
128 * Stack walking part of this method is from mono_handle_exception
130 * The idea is simple;
131 * - walk the stack to free some space (64k)
132 * - set esp to new stack location
133 * - call mono_arch_handle_exception with stack overflow exception
134 * - set esp to SEH handlers stack
135 * - done
137 static void
138 win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, CONTEXT *sctx)
140 SYSTEM_INFO si;
141 DWORD page_size;
142 MonoDomain *domain = mono_domain_get ();
143 MonoJitInfo rji;
144 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
145 MonoLMF *lmf = jit_tls->lmf;
146 MonoContext initial_ctx;
147 MonoContext ctx;
148 guint32 free_stack = 0;
149 StackFrameInfo frame;
151 mono_sigctx_to_monoctx (sctx, &ctx);
153 /* get our os page size */
154 GetSystemInfo(&si);
155 page_size = si.dwPageSize;
157 /* Let's walk the stack to recover
158 * the needed stack space (if possible)
160 memset (&rji, 0, sizeof (rji));
162 initial_ctx = ctx;
163 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
165 /* try to free 64kb from our stack */
166 do {
167 MonoContext new_ctx;
169 mono_arch_unwind_frame (domain, jit_tls, &rji, &ctx, &new_ctx, &lmf, NULL, &frame);
170 if (!frame.ji) {
171 g_warning ("Exception inside function without unwind info");
172 g_assert_not_reached ();
175 if (frame.ji != (gpointer)-1) {
176 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
179 /* todo: we should call abort if ji is -1 */
180 ctx = new_ctx;
181 } while (free_stack < 64 * 1024 && frame.ji != (gpointer) -1);
183 mono_monoctx_to_sigctx (&ctx, sctx);
185 /* todo: install new stack-guard page */
187 /* use the new stack and call mono_arch_handle_exception () */
188 restore_stack (sctx);
192 * Unhandled Exception Filter
193 * Top-level per-process exception handler.
195 LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep)
197 EXCEPTION_RECORD* er;
198 CONTEXT* ctx;
199 LONG res;
200 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
202 /* If the thread is not managed by the runtime return early */
203 if (!jit_tls)
204 return EXCEPTION_CONTINUE_SEARCH;
206 jit_tls->mono_win_chained_exception_needs_run = FALSE;
207 res = EXCEPTION_CONTINUE_EXECUTION;
209 er = ep->ExceptionRecord;
210 ctx = ep->ContextRecord;
212 switch (er->ExceptionCode) {
213 case EXCEPTION_STACK_OVERFLOW:
214 win32_handle_stack_overflow (ep, ctx);
215 break;
216 case EXCEPTION_ACCESS_VIOLATION:
217 W32_SEH_HANDLE_EX(segv);
218 break;
219 case EXCEPTION_ILLEGAL_INSTRUCTION:
220 W32_SEH_HANDLE_EX(ill);
221 break;
222 case EXCEPTION_INT_DIVIDE_BY_ZERO:
223 case EXCEPTION_INT_OVERFLOW:
224 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
225 case EXCEPTION_FLT_OVERFLOW:
226 case EXCEPTION_FLT_UNDERFLOW:
227 case EXCEPTION_FLT_INEXACT_RESULT:
228 W32_SEH_HANDLE_EX(fpe);
229 break;
230 default:
231 jit_tls->mono_win_chained_exception_needs_run = TRUE;
232 break;
235 if (jit_tls->mono_win_chained_exception_needs_run) {
236 /* Don't copy context back if we chained exception
237 * as the handler may have modfied the EXCEPTION_POINTERS
238 * directly. We don't pass sigcontext to chained handlers.
239 * Return continue search so the UnhandledExceptionFilter
240 * can correctly chain the exception.
242 res = EXCEPTION_CONTINUE_SEARCH;
245 return res;
248 void win32_seh_init()
250 /* install restore stack helper */
251 if (!restore_stack)
252 restore_stack = (void (*) (void*))mono_win32_get_handle_stackoverflow ();
254 mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter);
255 mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler);
258 void win32_seh_cleanup()
260 if (mono_old_win_toplevel_exception_filter)
261 SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter);
262 RemoveVectoredExceptionHandler (mono_win_vectored_exception_handle);
265 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
267 switch (type) {
268 case SIGFPE:
269 fpe_handler = handler;
270 break;
271 case SIGILL:
272 ill_handler = handler;
273 break;
274 case SIGSEGV:
275 segv_handler = handler;
276 break;
277 default:
278 break;
282 #endif /* TARGET_WIN32 */
285 * mono_arch_get_restore_context:
287 * Returns a pointer to a method which restores a previously saved sigcontext.
289 gpointer
290 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
292 guint8 *start = NULL;
293 guint8 *code;
294 MonoJumpInfo *ji = NULL;
295 GSList *unwind_ops = NULL;
297 /* restore_contect (MonoContext *ctx) */
299 start = code = mono_global_codeman_reserve (128);
301 /* load ctx */
302 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
304 /* restore EBX */
305 x86_mov_reg_membase (code, X86_EBX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebx), 4);
307 /* restore EDI */
308 x86_mov_reg_membase (code, X86_EDI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edi), 4);
310 /* restore ESI */
311 x86_mov_reg_membase (code, X86_ESI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esi), 4);
313 /* restore EDX */
314 x86_mov_reg_membase (code, X86_EDX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edx), 4);
317 * The context resides on the stack, in the stack frame of the
318 * caller of this function. The stack pointer that we need to
319 * restore is potentially many stack frames higher up, so the
320 * distance between them can easily be more than the red zone
321 * size. Hence the stack pointer can be restored only after
322 * we have finished loading everything from the context.
325 /* load ESP into EBP */
326 x86_mov_reg_membase (code, X86_EBP, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esp), 4);
327 /* load return address into ECX */
328 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, eip), 4);
329 /* save the return addr to the restored stack - 4 */
330 x86_mov_membase_reg (code, X86_EBP, -4, X86_ECX, 4);
332 /* load EBP into ECX */
333 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebp), 4);
334 /* save EBP to the restored stack - 8 */
335 x86_mov_membase_reg (code, X86_EBP, -8, X86_ECX, 4);
337 /* load EAX into ECX */
338 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, eax), 4);
339 /* save EAX to the restored stack - 12 */
340 x86_mov_membase_reg (code, X86_EBP, -12, X86_ECX, 4);
342 /* restore ECX */
343 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ecx), 4);
345 /* restore ESP - 12 */
346 x86_lea_membase (code, X86_ESP, X86_EBP, -12);
347 /* restore EAX */
348 x86_pop_reg (code, X86_EAX);
349 /* restore EBP */
350 x86_pop_reg (code, X86_EBP);
351 /* jump to the saved IP */
352 x86_ret (code);
354 if (info)
355 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
356 else {
357 GSList *l;
359 for (l = unwind_ops; l; l = l->next)
360 g_free (l->data);
361 g_slist_free (unwind_ops);
364 mono_arch_flush_icache (start, code - start);
365 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
367 return start;
371 * mono_arch_get_call_filter:
373 * Returns a pointer to a method which calls an exception filter. We
374 * also use this function to call finally handlers (we pass NULL as
375 * @exc object in this case).
377 gpointer
378 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
380 guint8* start;
381 guint8 *code;
382 MonoJumpInfo *ji = NULL;
383 GSList *unwind_ops = NULL;
384 guint kMaxCodeSize = 64;
386 /* call_filter (MonoContext *ctx, unsigned long eip) */
387 start = code = mono_global_codeman_reserve (kMaxCodeSize);
389 x86_push_reg (code, X86_EBP);
390 x86_mov_reg_reg (code, X86_EBP, X86_ESP);
391 x86_push_reg (code, X86_EBX);
392 x86_push_reg (code, X86_EDI);
393 x86_push_reg (code, X86_ESI);
395 /* load ctx */
396 x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
397 /* load eip */
398 x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
399 /* save EBP */
400 x86_push_reg (code, X86_EBP);
402 /* set new EBP */
403 x86_mov_reg_membase (code, X86_EBP, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebp), 4);
404 /* restore registers used by global register allocation (EBX & ESI) */
405 x86_mov_reg_membase (code, X86_EBX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebx), 4);
406 x86_mov_reg_membase (code, X86_ESI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esi), 4);
407 x86_mov_reg_membase (code, X86_EDI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edi), 4);
409 /* align stack and save ESP */
410 x86_mov_reg_reg (code, X86_EDX, X86_ESP);
411 x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
412 g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
413 x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
414 x86_push_reg (code, X86_EDX);
416 /* call the handler */
417 x86_call_reg (code, X86_ECX);
419 /* restore ESP */
420 x86_pop_reg (code, X86_ESP);
422 /* restore EBP */
423 x86_pop_reg (code, X86_EBP);
425 /* restore saved regs */
426 x86_pop_reg (code, X86_ESI);
427 x86_pop_reg (code, X86_EDI);
428 x86_pop_reg (code, X86_EBX);
429 x86_leave (code);
430 x86_ret (code);
432 if (info)
433 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
434 else {
435 GSList *l;
437 for (l = unwind_ops; l; l = l->next)
438 g_free (l->data);
439 g_slist_free (unwind_ops);
442 mono_arch_flush_icache (start, code - start);
443 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
445 g_assert ((code - start) < kMaxCodeSize);
446 return start;
450 * mono_x86_throw_exception:
452 * C function called from the throw trampolines.
454 void
455 mono_x86_throw_exception (host_mgreg_t *regs, MonoObject *exc,
456 host_mgreg_t eip, gboolean rethrow, gboolean preserve_ips)
458 ERROR_DECL (error);
459 MonoContext ctx;
461 ctx.esp = regs [X86_ESP];
462 ctx.eip = eip;
463 ctx.ebp = regs [X86_EBP];
464 ctx.edi = regs [X86_EDI];
465 ctx.esi = regs [X86_ESI];
466 ctx.ebx = regs [X86_EBX];
467 ctx.edx = regs [X86_EDX];
468 ctx.ecx = regs [X86_ECX];
469 ctx.eax = regs [X86_EAX];
471 #ifdef __APPLE__
472 /* The OSX ABI specifies 16 byte alignment at call sites */
473 g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
474 #endif
476 if (mono_object_isinst_checked (exc, mono_defaults.exception_class, error)) {
477 MonoException *mono_ex = (MonoException*)exc;
478 if (!rethrow) {
479 mono_ex->stack_trace = NULL;
480 mono_ex->trace_ips = NULL;
481 } else if (preserve_ips) {
482 mono_ex->caught_in_unmanaged = TRUE;
485 mono_error_assert_ok (error);
487 /* adjust eip so that it point into the call instruction */
488 ctx.eip -= 1;
490 mono_handle_exception (&ctx, exc);
492 mono_restore_context (&ctx);
494 g_assert_not_reached ();
497 void
498 mono_x86_throw_corlib_exception (host_mgreg_t *regs, guint32 ex_token_index,
499 host_mgreg_t eip, gint32 pc_offset)
501 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
502 MonoException *ex;
504 ex = mono_exception_from_token (m_class_get_image (mono_defaults.exception_class), ex_token);
506 eip -= pc_offset;
508 /* Negate the ip adjustment done in mono_x86_throw_exception () */
509 eip += 1;
511 mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE, FALSE);
514 static void
515 mono_x86_resume_unwind (host_mgreg_t *regs, MonoObject *exc,
516 host_mgreg_t eip, gboolean rethrow)
518 MonoContext ctx;
520 ctx.esp = regs [X86_ESP];
521 ctx.eip = eip;
522 ctx.ebp = regs [X86_EBP];
523 ctx.edi = regs [X86_EDI];
524 ctx.esi = regs [X86_ESI];
525 ctx.ebx = regs [X86_EBX];
526 ctx.edx = regs [X86_EDX];
527 ctx.ecx = regs [X86_ECX];
528 ctx.eax = regs [X86_EAX];
530 mono_resume_unwind (&ctx);
534 * get_throw_trampoline:
536 * Generate a call to mono_x86_throw_exception/
537 * mono_x86_throw_corlib_exception.
538 * If LLVM is true, generate code which assumes the caller is LLVM generated code,
539 * which doesn't push the arguments.
541 static guint8*
542 get_throw_trampoline (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, MonoTrampInfo **info, gboolean aot, gboolean preserve_ips)
544 guint8 *start, *code, *labels [16];
545 int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
546 MonoJumpInfo *ji = NULL;
547 GSList *unwind_ops = NULL;
548 guint kMaxCodeSize = 192;
550 start = code = mono_global_codeman_reserve (kMaxCodeSize);
552 stack_size = 128;
555 * On apple, the stack is misaligned by the pushing of the return address.
557 if (!llvm && corlib)
558 /* On OSX, we don't generate alignment code to save space */
559 stack_size += 4;
560 else
561 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
564 * The stack looks like this:
565 * <pc offset> (only if corlib is TRUE)
566 * <exception object>/<type token>
567 * <return addr> <- esp (unaligned on apple)
570 unwind_ops = mono_arch_get_cie_program ();
572 /* Alloc frame */
573 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
574 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
576 arg_offsets [0] = 0;
577 arg_offsets [1] = 4;
578 arg_offsets [2] = 8;
579 arg_offsets [3] = 12;
580 arg_offsets [4] = 16;
581 regs_offset = 20;
583 /* Save registers */
584 for (i = 0; i < X86_NREG; ++i)
585 if (i != X86_ESP)
586 x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
587 /* Calculate the offset between the current sp and the sp of the caller */
588 if (llvm) {
589 /* LLVM doesn't push the arguments */
590 stack_offset = stack_size + 4;
591 } else {
592 if (corlib) {
593 /* Two arguments */
594 stack_offset = stack_size + 4 + 8;
595 #ifdef __APPLE__
596 /* We don't generate stack alignment code on osx to save space */
597 #endif
598 } else {
599 /* One argument + stack alignment */
600 stack_offset = stack_size + 4 + 4;
601 #ifdef __APPLE__
602 /* Pop the alignment added by OP_THROW too */
603 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
604 #else
605 if (mono_do_x86_stack_align)
606 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
607 #endif
610 /* Save ESP */
611 x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
612 x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
614 /* Clear fp stack */
615 labels [0] = code;
616 x86_fnstsw (code);
617 x86_shift_reg_imm (code, X86_SHR, X86_EAX, 11);
618 x86_alu_reg_imm (code, X86_AND, X86_EAX, 7);
619 x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0);
620 labels [1] = code;
621 x86_branch8 (code, X86_CC_EQ, 0, FALSE);
622 x86_fstp (code, 0);
623 x86_jump_code (code, labels [0]);
624 mono_x86_patch (labels [1], code);
626 /* Set arg1 == regs */
627 x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
628 x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
629 /* Set arg2 == exc/ex_token_index */
630 if (resume_unwind)
631 x86_mov_reg_imm (code, X86_EAX, 0);
632 else
633 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
634 x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
635 /* Set arg3 == eip */
636 if (llvm_abs)
637 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
638 else
639 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
640 x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
641 /* Set arg4 == rethrow/pc_offset */
642 if (resume_unwind) {
643 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], 0, 4);
644 } else if (corlib) {
645 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
646 if (llvm_abs) {
648 * The caller is LLVM code which passes the absolute address not a pc offset,
649 * so compensate by passing 0 as 'ip' and passing the negated abs address as
650 * the pc offset.
652 x86_neg_reg (code, X86_EAX);
654 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
655 } else {
656 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
658 /* Set arg4 == preserve_ips */
659 x86_mov_membase_imm (code, X86_ESP, arg_offsets [4], preserve_ips, 4);
661 /* Make the call */
662 if (aot) {
663 // This can be called from runtime code, which can't guarantee that
664 // ebx contains the got address.
665 // So emit the got address loading code too
666 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
667 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");
668 x86_call_reg (code, X86_EAX);
669 } else {
670 x86_call_code (code, resume_unwind ? (gpointer)(mono_x86_resume_unwind) : (corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception));
672 x86_breakpoint (code);
674 g_assert ((code - start) < kMaxCodeSize);
676 if (info)
677 *info = mono_tramp_info_create (name, start, code - start, ji, unwind_ops);
678 else {
679 GSList *l;
681 for (l = unwind_ops; l; l = l->next)
682 g_free (l->data);
683 g_slist_free (unwind_ops);
686 mono_arch_flush_icache (start, code - start);
687 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
689 return start;
693 * mono_arch_get_throw_exception:
694 * \returns a function pointer which can be used to raise
695 * exceptions. The returned function has the following
696 * signature: void (*func) (MonoException *exc);
697 * For example to raise an arithmetic exception you can use:
699 * x86_push_imm (code, mono_get_exception_arithmetic ());
700 * x86_call_code (code, arch_get_throw_exception ());
703 gpointer
704 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
706 return get_throw_trampoline ("throw_exception", FALSE, FALSE, FALSE, FALSE, FALSE, info, aot, FALSE);
709 gpointer
710 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
712 return get_throw_trampoline ("rethrow_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot, FALSE);
715 gpointer
716 mono_arch_get_rethrow_preserve_exception (MonoTrampInfo **info, gboolean aot)
718 return get_throw_trampoline ("rethrow_preserve_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot, TRUE);
722 * mono_arch_get_throw_corlib_exception:
723 * \returns a function pointer which can be used to raise
724 * corlib exceptions. The returned function has the following
725 * signature: void (*func) (guint32 ex_token, guint32 offset);
726 * Here, offset is the offset which needs to be substracted from the caller IP
727 * to get the IP of the throw. Passing the offset has the advantage that it
728 * needs no relocations in the caller.
730 gpointer
731 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
733 return get_throw_trampoline ("throw_corlib_exception", FALSE, FALSE, TRUE, FALSE, FALSE, info, aot, FALSE);
736 void
737 mono_arch_exceptions_init (void)
739 guint8 *tramp;
740 MonoTrampInfo *tinfo;
743 * If we're running WoW64, we need to set the usermode exception policy
744 * for SEHs to behave. This requires hotfix http://support.microsoft.com/kb/976038
745 * or (eventually) Windows 7 SP1.
747 #ifdef TARGET_WIN32
748 HMODULE kernel32 = LoadLibraryW (L"kernel32.dll");
749 if (kernel32) {
750 typedef BOOL (WINAPI * SetProcessUserModeExceptionPolicy_t) (DWORD dwFlags);
751 typedef BOOL (WINAPI * GetProcessUserModeExceptionPolicy_t) (PDWORD dwFlags);
752 GetProcessUserModeExceptionPolicy_t const getter = (GetProcessUserModeExceptionPolicy_t)GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy");
753 if (getter) {
754 SetProcessUserModeExceptionPolicy_t const setter = (SetProcessUserModeExceptionPolicy_t)GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy");
755 if (setter) {
756 DWORD flags = 0;
757 if (getter (&flags))
758 setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
762 #endif
764 if (mono_aot_only) {
765 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
766 return;
769 /* LLVM needs different throw trampolines */
770 tramp = get_throw_trampoline ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, &tinfo, FALSE, FALSE);
771 mono_register_jit_icall (tramp, "llvm_throw_exception_trampoline", NULL, TRUE);
772 mono_tramp_info_register (tinfo, NULL);
774 tramp = get_throw_trampoline ("llvm_rethrow_exception_trampoline", TRUE, TRUE, FALSE, FALSE, FALSE, &tinfo, FALSE, FALSE);
775 mono_register_jit_icall (tramp, "llvm_rethrow_exception_trampoline", NULL, TRUE);
776 mono_tramp_info_register (tinfo, NULL);
778 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, FALSE, &tinfo, FALSE, FALSE);
779 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
780 mono_tramp_info_register (tinfo, NULL);
782 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_abs_trampoline", FALSE, TRUE, TRUE, TRUE, FALSE, &tinfo, FALSE, FALSE);
783 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
784 mono_tramp_info_register (tinfo, NULL);
786 tramp = get_throw_trampoline ("llvm_resume_unwind_trampoline", FALSE, FALSE, FALSE, FALSE, TRUE, &tinfo, FALSE, FALSE);
787 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
788 mono_tramp_info_register (tinfo, NULL);
790 signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (&tinfo, FALSE);
791 mono_tramp_info_register (tinfo, NULL);
795 * mono_arch_unwind_frame:
797 * See exceptions-amd64.c for docs.
799 gboolean
800 mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls,
801 MonoJitInfo *ji, MonoContext *ctx,
802 MonoContext *new_ctx, MonoLMF **lmf,
803 host_mgreg_t **save_locations,
804 StackFrameInfo *frame)
806 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
808 memset (frame, 0, sizeof (StackFrameInfo));
809 frame->ji = ji;
811 *new_ctx = *ctx;
813 if (ji != NULL) {
814 host_mgreg_t regs [MONO_MAX_IREGS + 1];
815 guint8 *cfa;
816 guint32 unwind_info_len;
817 guint8 *unwind_info;
819 if (ji->is_trampoline)
820 frame->type = FRAME_TYPE_TRAMPOLINE;
821 else
822 frame->type = FRAME_TYPE_MANAGED;
824 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
826 regs [X86_EAX] = new_ctx->eax;
827 regs [X86_EBX] = new_ctx->ebx;
828 regs [X86_ECX] = new_ctx->ecx;
829 regs [X86_EDX] = new_ctx->edx;
830 regs [X86_ESP] = new_ctx->esp;
831 regs [X86_EBP] = new_ctx->ebp;
832 regs [X86_ESI] = new_ctx->esi;
833 regs [X86_EDI] = new_ctx->edi;
834 regs [X86_NREG] = new_ctx->eip;
836 mono_unwind_frame ((guint8*)unwind_info, unwind_info_len, (guint8*)ji->code_start,
837 (guint8*)ji->code_start + ji->code_size,
838 (guint8*)ip, NULL, regs, MONO_MAX_IREGS + 1,
839 save_locations, MONO_MAX_IREGS, &cfa);
841 new_ctx->eax = regs [X86_EAX];
842 new_ctx->ebx = regs [X86_EBX];
843 new_ctx->ecx = regs [X86_ECX];
844 new_ctx->edx = regs [X86_EDX];
845 new_ctx->esp = regs [X86_ESP];
846 new_ctx->ebp = regs [X86_EBP];
847 new_ctx->esi = regs [X86_ESI];
848 new_ctx->edi = regs [X86_EDI];
849 new_ctx->eip = regs [X86_NREG];
851 /* The CFA becomes the new SP value */
852 new_ctx->esp = (gssize)cfa;
854 /* Adjust IP */
855 new_ctx->eip --;
857 return TRUE;
858 } else if (*lmf) {
859 g_assert ((((gsize)(*lmf)->previous_lmf) & 2) == 0);
861 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
862 frame->ji = ji;
863 } else {
864 if (!(*lmf)->method)
865 return FALSE;
866 frame->method = (*lmf)->method;
869 new_ctx->esi = (*lmf)->esi;
870 new_ctx->edi = (*lmf)->edi;
871 new_ctx->ebx = (*lmf)->ebx;
872 new_ctx->ebp = (*lmf)->ebp;
873 new_ctx->eip = (*lmf)->eip;
875 /* Adjust IP */
876 new_ctx->eip --;
878 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
880 /* Check if we are in a trampoline LMF frame */
881 if ((gsize)((*lmf)->previous_lmf) & 1) {
882 /* lmf->esp is set by the trampoline code */
883 new_ctx->esp = (*lmf)->esp;
885 else
886 /* the lmf is always stored on the stack, so the following
887 * expression points to a stack location which can be used as ESP */
888 new_ctx->esp = (unsigned long)&((*lmf)->eip);
890 *lmf = (MonoLMF*)(((gsize)(*lmf)->previous_lmf) & ~3);
892 return TRUE;
895 return FALSE;
898 gpointer
899 mono_arch_ip_from_context (void *sigctx)
901 #if defined(HOST_WATCHOS)
902 printf("WARNING: mono_arch_ip_from_context() called!\n");
903 return (NULL);
904 #elif defined(MONO_CROSS_COMPILE)
905 g_assert_not_reached ();
906 return NULL;
907 #elif defined(MONO_ARCH_USE_SIGACTION)
908 ucontext_t *ctx = (ucontext_t*)sigctx;
909 return (gpointer)UCONTEXT_REG_EIP (ctx);
910 #elif defined(HOST_WIN32)
911 return (gpointer)((CONTEXT*)sigctx)->Eip;
912 #else
913 struct sigcontext *ctx = sigctx;
914 return (gpointer)ctx->SC_EIP;
915 #endif
919 * handle_exception:
921 * Called by resuming from a signal handler.
923 static void
924 handle_signal_exception (gpointer obj)
926 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
927 MonoContext ctx;
929 memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
931 mono_handle_exception (&ctx, (MonoObject*)obj);
933 mono_restore_context (&ctx);
937 * mono_x86_get_signal_exception_trampoline:
939 * This x86 specific trampoline is used to call handle_signal_exception.
941 gpointer
942 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
944 guint8 *start, *code;
945 MonoJumpInfo *ji = NULL;
946 GSList *unwind_ops = NULL;
947 int stack_size;
949 start = code = mono_global_codeman_reserve (128);
951 /* FIXME no unwind before we push ip */
952 /* Caller ip */
953 x86_push_reg (code, X86_ECX);
955 mono_add_unwind_op_def_cfa (unwind_ops, code, start, X86_ESP, 4);
956 mono_add_unwind_op_offset (unwind_ops, code, start, X86_NREG, -4);
958 /* Fix the alignment to be what apple expects */
959 stack_size = 12;
961 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
962 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
964 /* Arg1 */
965 x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
966 /* Branch to target */
967 x86_call_reg (code, X86_EDX);
969 g_assert ((code - start) < 128);
971 if (info)
972 *info = mono_tramp_info_create ("x86_signal_exception_trampoline", start, code - start, ji, unwind_ops);
973 else {
974 GSList *l;
976 for (l = unwind_ops; l; l = l->next)
977 g_free (l->data);
978 g_slist_free (unwind_ops);
981 mono_arch_flush_icache (start, code - start);
982 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
984 return start;
988 void
989 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
992 * Can't pass the obj on the stack, since we are executing on the
993 * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
994 * So put it into a register, and branch to a trampoline which
995 * pushes it.
997 ctx->eax = (host_mgreg_t)(gsize)user_data;
998 ctx->ecx = ctx->eip;
999 ctx->edx = (host_mgreg_t)(gsize)async_cb;
1001 /*align the stack*/
1002 ctx->esp = (ctx->esp - 16) & ~15;
1003 ctx->eip = (host_mgreg_t)(gsize)signal_exception_trampoline;
1006 gboolean
1007 mono_arch_handle_exception (void *sigctx, gpointer obj)
1009 #if defined(MONO_ARCH_USE_SIGACTION)
1010 MonoContext mctx;
1011 ucontext_t *ctx = (ucontext_t*)sigctx;
1014 * Handling the exception in the signal handler is problematic, since the original
1015 * signal is disabled, and we could run arbitrary code though the debugger. So
1016 * resume into the normal stack and do most work there if possible.
1018 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1020 /* Pass the ctx parameter in TLS */
1021 mono_sigctx_to_monoctx (ctx, &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 #elif defined (TARGET_WIN32)
1029 MonoContext mctx;
1030 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1032 mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
1034 mctx = jit_tls->ex_ctx;
1035 mono_setup_async_callback (&mctx, handle_signal_exception, obj);
1036 mono_monoctx_to_sigctx (&mctx, sigctx);
1038 return TRUE;
1039 #else
1040 MonoContext mctx;
1042 mono_sigctx_to_monoctx (sigctx, &mctx);
1044 mono_handle_exception (&mctx, obj);
1046 mono_monoctx_to_sigctx (&mctx, sigctx);
1048 return TRUE;
1049 #endif
1052 static MonoObject*
1053 restore_soft_guard_pages (void)
1055 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1057 if (jit_tls->stack_ovf_guard_base)
1058 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1060 if (jit_tls->stack_ovf_pending) {
1061 MonoDomain *domain = mono_domain_get ();
1062 jit_tls->stack_ovf_pending = 0;
1063 return (MonoObject *) domain->stack_overflow_ex;
1065 return NULL;
1069 * this function modifies mctx so that when it is restored, it
1070 * won't execcute starting at mctx.eip, but in a function that
1071 * will restore the protection on the soft-guard pages and return back to
1072 * continue at mctx.eip.
1074 static void
1075 prepare_for_guard_pages (MonoContext *mctx)
1077 gpointer *sp;
1078 sp = (gpointer*)(mctx->esp);
1079 sp -= 1;
1080 /* the return addr */
1081 sp [0] = (gpointer)(mctx->eip);
1082 mctx->eip = (unsigned long)restore_soft_guard_pages;
1083 mctx->esp = (unsigned long)sp;
1087 static void
1088 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
1090 MonoContext mctx;
1092 mctx = *ctx;
1094 mono_handle_exception (&mctx, (MonoObject*)obj);
1095 if (stack_ovf) {
1096 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1097 jit_tls->stack_ovf_pending = 1;
1098 prepare_for_guard_pages (&mctx);
1100 mono_restore_context (&mctx);
1103 void
1104 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
1106 #if defined(MONO_ARCH_USE_SIGACTION) && !defined(MONO_CROSS_COMPILE)
1107 MonoException *exc = NULL;
1108 ucontext_t *ctx = (ucontext_t*)sigctx;
1109 MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1110 gpointer *sp;
1111 int frame_size;
1113 /* if we didn't find a managed method for the ip address and it matches the fault
1114 * address, we assume we followed a broken pointer during an indirect call, so
1115 * we try the lookup again with the return address pushed on the stack
1117 if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1118 glong *sp = (glong*)UCONTEXT_REG_ESP (ctx);
1119 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1120 if (ji)
1121 UCONTEXT_REG_EIP (ctx) = sp [0];
1123 if (stack_ovf)
1124 exc = mono_domain_get ()->stack_overflow_ex;
1125 if (!ji)
1126 mono_handle_native_crash ("SIGSEGV", sigctx, siginfo);
1127 /* setup a call frame on the real stack so that control is returned there
1128 * and exception handling can continue.
1129 * If this was a stack overflow the caller already ensured the stack pages
1130 * needed have been unprotected.
1131 * The frame looks like:
1132 * ucontext struct
1133 * test_only arg
1134 * exception arg
1135 * ctx arg
1136 * return ip
1138 // FIXME: test_only is no more.
1139 frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4;
1140 frame_size += 15;
1141 frame_size &= ~15;
1142 sp = (gpointer*)(UCONTEXT_REG_ESP (ctx) & ~15);
1143 sp = (gpointer*)((char*)sp - frame_size);
1144 /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1145 * goes at sp [-1]
1147 sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1148 sp [0] = sp + 4;
1149 sp [1] = exc;
1150 sp [2] = (gpointer)stack_ovf;
1151 mono_sigctx_to_monoctx (sigctx, (MonoContext*)(sp + 4));
1152 /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1153 UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1154 UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1155 #endif
1158 #if MONO_SUPPORT_TASKLETS
1159 MonoContinuationRestore
1160 mono_tasklets_arch_restore (void)
1162 static guint8* saved = NULL;
1163 guint8 *code, *start;
1165 if (saved)
1166 return (MonoContinuationRestore)saved;
1167 code = start = mono_global_codeman_reserve (48);
1168 /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1169 /* put cont in edx */
1170 x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1171 /* state in eax, so it's setup as the return value */
1172 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1173 /* lmf_addr in ebx */
1174 x86_mov_reg_membase(code, X86_EBX, X86_ESP, 0x0C, 4);
1176 /* setup the copy of the stack */
1177 x86_mov_reg_membase (code, X86_ECX, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1178 x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1179 x86_cld (code);
1180 x86_mov_reg_membase (code, X86_ESI, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1181 x86_mov_reg_membase (code, X86_EDI, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1182 x86_prefix (code, X86_REP_PREFIX);
1183 x86_movsl (code);
1185 /* now restore the registers from the LMF */
1186 x86_mov_reg_membase (code, X86_ECX, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1187 x86_mov_reg_membase (code, X86_EBP, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, ebp), 4);
1188 x86_mov_reg_membase (code, X86_ESP, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, esp), 4);
1190 /* restore the lmf chain */
1191 /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1192 x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1194 x86_jump_membase (code, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1196 mono_arch_flush_icache (start, code - start);
1197 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
1198 g_assert ((code - start) <= 48);
1200 saved = start;
1201 return (MonoContinuationRestore)saved;
1203 #endif
1206 * mono_arch_setup_resume_sighandler_ctx:
1208 * Setup CTX so execution continues at FUNC.
1210 void
1211 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1213 int align = (((gint32)MONO_CONTEXT_GET_SP (ctx)) % MONO_ARCH_FRAME_ALIGNMENT + 4);
1215 if (align != 0)
1216 MONO_CONTEXT_SET_SP (ctx, (gsize)MONO_CONTEXT_GET_SP (ctx) - align);
1218 MONO_CONTEXT_SET_IP (ctx, func);