[profiler] Remove support for the output=-FILENAME option.
[mono-project.git] / mono / mini / exceptions-x86.c
blob5042fa5efd1629755101e2f9c443cfc48877ef26
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 "tasklets.h"
35 static gpointer signal_exception_trampoline;
37 gpointer
38 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot);
40 #ifdef TARGET_WIN32
41 static void (*restore_stack) (void *);
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 gpointer mono_win_vectored_exception_handle;
49 extern int (*gUnhandledExceptionHandler)(EXCEPTION_POINTERS*);
51 #ifndef PROCESS_CALLBACK_FILTER_ENABLED
52 # define PROCESS_CALLBACK_FILTER_ENABLED 1
53 #endif
55 #define W32_SEH_HANDLE_EX(_ex) \
56 if (_ex##_handler) _ex##_handler(0, ep, ctx)
58 LONG CALLBACK seh_unhandled_exception_filter(EXCEPTION_POINTERS* ep)
60 #ifndef MONO_CROSS_COMPILE
61 if (mono_old_win_toplevel_exception_filter) {
62 return (*mono_old_win_toplevel_exception_filter)(ep);
64 #endif
66 mono_handle_native_crash ("SIGSEGV", NULL, NULL);
68 return EXCEPTION_CONTINUE_SEARCH;
72 * mono_win32_get_handle_stackoverflow (void):
74 * Returns a pointer to a method which restores the current context stack
75 * and calls handle_exceptions, when done restores the original stack.
77 static gpointer
78 mono_win32_get_handle_stackoverflow (void)
80 static guint8 *start = NULL;
81 guint8 *code;
83 if (start)
84 return start;
86 /* restore_contect (void *sigctx) */
87 start = code = mono_global_codeman_reserve (128);
89 /* load context into ebx */
90 x86_mov_reg_membase (code, X86_EBX, X86_ESP, 4, 4);
92 /* move current stack into edi for later restore */
93 x86_mov_reg_reg (code, X86_EDI, X86_ESP, 4);
95 /* use the new freed stack from sigcontext */
96 /* XXX replace usage of struct sigcontext with MonoContext so we can use MONO_STRUCT_OFFSET */
97 x86_mov_reg_membase (code, X86_ESP, X86_EBX, G_STRUCT_OFFSET (struct sigcontext, esp), 4);
99 /* get the current domain */
100 x86_call_code (code, mono_domain_get);
102 /* get stack overflow exception from domain object */
103 x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoDomain, stack_overflow_ex), 4);
105 /* call mono_arch_handle_exception (sctx, stack_overflow_exception_obj) */
106 x86_push_reg (code, X86_EAX);
107 x86_push_reg (code, X86_EBX);
108 x86_call_code (code, mono_arch_handle_exception);
110 /* restore the SEH handler stack */
111 x86_mov_reg_reg (code, X86_ESP, X86_EDI, 4);
113 /* return */
114 x86_ret (code);
116 mono_arch_flush_icache (start, code - start);
117 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
119 return start;
122 /* Special hack to workaround the fact that the
123 * when the SEH handler is called the stack is
124 * to small to recover.
126 * Stack walking part of this method is from mono_handle_exception
128 * The idea is simple;
129 * - walk the stack to free some space (64k)
130 * - set esp to new stack location
131 * - call mono_arch_handle_exception with stack overflow exception
132 * - set esp to SEH handlers stack
133 * - done
135 static void
136 win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, struct sigcontext *sctx)
138 SYSTEM_INFO si;
139 DWORD page_size;
140 MonoDomain *domain = mono_domain_get ();
141 MonoJitInfo rji;
142 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
143 MonoLMF *lmf = jit_tls->lmf;
144 MonoContext initial_ctx;
145 MonoContext ctx;
146 guint32 free_stack = 0;
147 StackFrameInfo frame;
149 mono_sigctx_to_monoctx (sctx, &ctx);
151 /* get our os page size */
152 GetSystemInfo(&si);
153 page_size = si.dwPageSize;
155 /* Let's walk the stack to recover
156 * the needed stack space (if possible)
158 memset (&rji, 0, sizeof (rji));
160 initial_ctx = ctx;
161 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
163 /* try to free 64kb from our stack */
164 do {
165 MonoContext new_ctx;
167 mono_arch_unwind_frame (domain, jit_tls, &rji, &ctx, &new_ctx, &lmf, NULL, &frame);
168 if (!frame.ji) {
169 g_warning ("Exception inside function without unwind info");
170 g_assert_not_reached ();
173 if (frame.ji != (gpointer)-1) {
174 free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
177 /* todo: we should call abort if ji is -1 */
178 ctx = new_ctx;
179 } while (free_stack < 64 * 1024 && frame.ji != (gpointer) -1);
181 mono_monoctx_to_sigctx (&ctx, sctx);
183 /* todo: install new stack-guard page */
185 /* use the new stack and call mono_arch_handle_exception () */
186 restore_stack (sctx);
190 * Unhandled Exception Filter
191 * Top-level per-process exception handler.
193 LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep)
195 EXCEPTION_RECORD* er;
196 CONTEXT* ctx;
197 LONG res;
198 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
200 /* If the thread is not managed by the runtime return early */
201 if (!jit_tls)
202 return EXCEPTION_CONTINUE_SEARCH;
204 jit_tls->mono_win_chained_exception_needs_run = FALSE;
205 res = EXCEPTION_CONTINUE_EXECUTION;
207 er = ep->ExceptionRecord;
208 ctx = ep->ContextRecord;
210 switch (er->ExceptionCode) {
211 case EXCEPTION_STACK_OVERFLOW:
212 win32_handle_stack_overflow (ep, ctx);
213 break;
214 case EXCEPTION_ACCESS_VIOLATION:
215 W32_SEH_HANDLE_EX(segv);
216 break;
217 case EXCEPTION_ILLEGAL_INSTRUCTION:
218 W32_SEH_HANDLE_EX(ill);
219 break;
220 case EXCEPTION_INT_DIVIDE_BY_ZERO:
221 case EXCEPTION_INT_OVERFLOW:
222 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
223 case EXCEPTION_FLT_OVERFLOW:
224 case EXCEPTION_FLT_UNDERFLOW:
225 case EXCEPTION_FLT_INEXACT_RESULT:
226 W32_SEH_HANDLE_EX(fpe);
227 break;
228 default:
229 jit_tls->mono_win_chained_exception_needs_run = TRUE;
230 break;
233 if (jit_tls->mono_win_chained_exception_needs_run) {
234 /* Don't copy context back if we chained exception
235 * as the handler may have modfied the EXCEPTION_POINTERS
236 * directly. We don't pass sigcontext to chained handlers.
237 * Return continue search so the UnhandledExceptionFilter
238 * can correctly chain the exception.
240 res = EXCEPTION_CONTINUE_SEARCH;
243 return res;
246 void win32_seh_init()
248 /* install restore stack helper */
249 if (!restore_stack)
250 restore_stack = mono_win32_get_handle_stackoverflow ();
252 mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter);
253 mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler);
256 void win32_seh_cleanup()
258 if (mono_old_win_toplevel_exception_filter)
259 SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter);
260 RemoveVectoredExceptionHandler (mono_win_vectored_exception_handle);
263 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
265 switch (type) {
266 case SIGFPE:
267 fpe_handler = handler;
268 break;
269 case SIGILL:
270 ill_handler = handler;
271 break;
272 case SIGSEGV:
273 segv_handler = handler;
274 break;
275 default:
276 break;
280 #endif /* TARGET_WIN32 */
283 * mono_arch_get_restore_context:
285 * Returns a pointer to a method which restores a previously saved sigcontext.
287 gpointer
288 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
290 guint8 *start = NULL;
291 guint8 *code;
292 MonoJumpInfo *ji = NULL;
293 GSList *unwind_ops = NULL;
295 /* restore_contect (MonoContext *ctx) */
297 start = code = mono_global_codeman_reserve (128);
299 /* load ctx */
300 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
302 /* restore EBX */
303 x86_mov_reg_membase (code, X86_EBX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebx), 4);
305 /* restore EDI */
306 x86_mov_reg_membase (code, X86_EDI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edi), 4);
308 /* restore ESI */
309 x86_mov_reg_membase (code, X86_ESI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esi), 4);
311 /* restore EDX */
312 x86_mov_reg_membase (code, X86_EDX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edx), 4);
315 * The context resides on the stack, in the stack frame of the
316 * caller of this function. The stack pointer that we need to
317 * restore is potentially many stack frames higher up, so the
318 * distance between them can easily be more than the red zone
319 * size. Hence the stack pointer can be restored only after
320 * we have finished loading everything from the context.
323 /* load ESP into EBP */
324 x86_mov_reg_membase (code, X86_EBP, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esp), 4);
325 /* load return address into ECX */
326 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, eip), 4);
327 /* save the return addr to the restored stack - 4 */
328 x86_mov_membase_reg (code, X86_EBP, -4, X86_ECX, 4);
330 /* load EBP into ECX */
331 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebp), 4);
332 /* save EBP to the restored stack - 8 */
333 x86_mov_membase_reg (code, X86_EBP, -8, X86_ECX, 4);
335 /* load EAX into ECX */
336 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, eax), 4);
337 /* save EAX to the restored stack - 12 */
338 x86_mov_membase_reg (code, X86_EBP, -12, X86_ECX, 4);
340 /* restore ECX */
341 x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ecx), 4);
343 /* restore ESP - 12 */
344 x86_lea_membase (code, X86_ESP, X86_EBP, -12);
345 /* restore EAX */
346 x86_pop_reg (code, X86_EAX);
347 /* restore EBP */
348 x86_pop_reg (code, X86_EBP);
349 /* jump to the saved IP */
350 x86_ret (code);
352 if (info)
353 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
354 else {
355 GSList *l;
357 for (l = unwind_ops; l; l = l->next)
358 g_free (l->data);
359 g_slist_free (unwind_ops);
362 mono_arch_flush_icache (start, code - start);
363 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
365 return start;
369 * mono_arch_get_call_filter:
371 * Returns a pointer to a method which calls an exception filter. We
372 * also use this function to call finally handlers (we pass NULL as
373 * @exc object in this case).
375 gpointer
376 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
378 guint8* start;
379 guint8 *code;
380 MonoJumpInfo *ji = NULL;
381 GSList *unwind_ops = NULL;
382 guint kMaxCodeSize = 64;
384 /* call_filter (MonoContext *ctx, unsigned long eip) */
385 start = code = mono_global_codeman_reserve (kMaxCodeSize);
387 x86_push_reg (code, X86_EBP);
388 x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
389 x86_push_reg (code, X86_EBX);
390 x86_push_reg (code, X86_EDI);
391 x86_push_reg (code, X86_ESI);
393 /* load ctx */
394 x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
395 /* load eip */
396 x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
397 /* save EBP */
398 x86_push_reg (code, X86_EBP);
400 /* set new EBP */
401 x86_mov_reg_membase (code, X86_EBP, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebp), 4);
402 /* restore registers used by global register allocation (EBX & ESI) */
403 x86_mov_reg_membase (code, X86_EBX, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, ebx), 4);
404 x86_mov_reg_membase (code, X86_ESI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, esi), 4);
405 x86_mov_reg_membase (code, X86_EDI, X86_EAX, MONO_STRUCT_OFFSET (MonoContext, edi), 4);
407 /* align stack and save ESP */
408 x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
409 x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
410 g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
411 x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
412 x86_push_reg (code, X86_EDX);
414 /* call the handler */
415 x86_call_reg (code, X86_ECX);
417 /* restore ESP */
418 x86_pop_reg (code, X86_ESP);
420 /* restore EBP */
421 x86_pop_reg (code, X86_EBP);
423 /* restore saved regs */
424 x86_pop_reg (code, X86_ESI);
425 x86_pop_reg (code, X86_EDI);
426 x86_pop_reg (code, X86_EBX);
427 x86_leave (code);
428 x86_ret (code);
430 if (info)
431 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
432 else {
433 GSList *l;
435 for (l = unwind_ops; l; l = l->next)
436 g_free (l->data);
437 g_slist_free (unwind_ops);
440 mono_arch_flush_icache (start, code - start);
441 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
443 g_assert ((code - start) < kMaxCodeSize);
444 return start;
448 * mono_x86_throw_exception:
450 * C function called from the throw trampolines.
452 void
453 mono_x86_throw_exception (mgreg_t *regs, MonoObject *exc,
454 mgreg_t eip, gboolean rethrow)
456 MonoError error;
457 MonoContext ctx;
459 ctx.esp = regs [X86_ESP];
460 ctx.eip = eip;
461 ctx.ebp = regs [X86_EBP];
462 ctx.edi = regs [X86_EDI];
463 ctx.esi = regs [X86_ESI];
464 ctx.ebx = regs [X86_EBX];
465 ctx.edx = regs [X86_EDX];
466 ctx.ecx = regs [X86_ECX];
467 ctx.eax = regs [X86_EAX];
469 #ifdef __APPLE__
470 /* The OSX ABI specifies 16 byte alignment at call sites */
471 g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
472 #endif
474 if (mono_object_isinst_checked (exc, mono_defaults.exception_class, &error)) {
475 MonoException *mono_ex = (MonoException*)exc;
476 if (!rethrow) {
477 mono_ex->stack_trace = NULL;
478 mono_ex->trace_ips = NULL;
481 mono_error_assert_ok (&error);
483 /* adjust eip so that it point into the call instruction */
484 ctx.eip -= 1;
486 mono_handle_exception (&ctx, exc);
488 mono_restore_context (&ctx);
490 g_assert_not_reached ();
493 void
494 mono_x86_throw_corlib_exception (mgreg_t *regs, guint32 ex_token_index,
495 mgreg_t eip, gint32 pc_offset)
497 guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
498 MonoException *ex;
500 ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
502 eip -= pc_offset;
504 /* Negate the ip adjustment done in mono_x86_throw_exception () */
505 eip += 1;
507 mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
510 static void
511 mono_x86_resume_unwind (mgreg_t *regs, MonoObject *exc,
512 mgreg_t eip, gboolean rethrow)
514 MonoContext ctx;
516 ctx.esp = regs [X86_ESP];
517 ctx.eip = eip;
518 ctx.ebp = regs [X86_EBP];
519 ctx.edi = regs [X86_EDI];
520 ctx.esi = regs [X86_ESI];
521 ctx.ebx = regs [X86_EBX];
522 ctx.edx = regs [X86_EDX];
523 ctx.ecx = regs [X86_ECX];
524 ctx.eax = regs [X86_EAX];
526 mono_resume_unwind (&ctx);
530 * get_throw_trampoline:
532 * Generate a call to mono_x86_throw_exception/
533 * mono_x86_throw_corlib_exception.
534 * If LLVM is true, generate code which assumes the caller is LLVM generated code,
535 * which doesn't push the arguments.
537 static guint8*
538 get_throw_trampoline (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, MonoTrampInfo **info, gboolean aot)
540 guint8 *start, *code, *labels [16];
541 int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
542 MonoJumpInfo *ji = NULL;
543 GSList *unwind_ops = NULL;
544 guint kMaxCodeSize = 192;
546 start = code = mono_global_codeman_reserve (kMaxCodeSize);
548 stack_size = 128;
551 * On apple, the stack is misaligned by the pushing of the return address.
553 if (!llvm && corlib)
554 /* On OSX, we don't generate alignment code to save space */
555 stack_size += 4;
556 else
557 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
560 * The stack looks like this:
561 * <pc offset> (only if corlib is TRUE)
562 * <exception object>/<type token>
563 * <return addr> <- esp (unaligned on apple)
566 unwind_ops = mono_arch_get_cie_program ();
568 /* Alloc frame */
569 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
570 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
572 arg_offsets [0] = 0;
573 arg_offsets [1] = 4;
574 arg_offsets [2] = 8;
575 arg_offsets [3] = 12;
576 regs_offset = 16;
578 /* Save registers */
579 for (i = 0; i < X86_NREG; ++i)
580 if (i != X86_ESP)
581 x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
582 /* Calculate the offset between the current sp and the sp of the caller */
583 if (llvm) {
584 /* LLVM doesn't push the arguments */
585 stack_offset = stack_size + 4;
586 } else {
587 if (corlib) {
588 /* Two arguments */
589 stack_offset = stack_size + 4 + 8;
590 #ifdef __APPLE__
591 /* We don't generate stack alignment code on osx to save space */
592 #endif
593 } else {
594 /* One argument + stack alignment */
595 stack_offset = stack_size + 4 + 4;
596 #ifdef __APPLE__
597 /* Pop the alignment added by OP_THROW too */
598 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
599 #else
600 if (mono_do_x86_stack_align)
601 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
602 #endif
605 /* Save ESP */
606 x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
607 x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
609 /* Clear fp stack */
610 labels [0] = code;
611 x86_fnstsw (code);
612 x86_shift_reg_imm (code, X86_SHR, X86_EAX, 11);
613 x86_alu_reg_imm (code, X86_AND, X86_EAX, 7);
614 x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0);
615 labels [1] = code;
616 x86_branch8 (code, X86_CC_EQ, 0, FALSE);
617 x86_fstp (code, 0);
618 x86_jump_code (code, labels [0]);
619 mono_x86_patch (labels [1], code);
621 /* Set arg1 == regs */
622 x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
623 x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
624 /* Set arg2 == exc/ex_token_index */
625 if (resume_unwind)
626 x86_mov_reg_imm (code, X86_EAX, 0);
627 else
628 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
629 x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
630 /* Set arg3 == eip */
631 if (llvm_abs)
632 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
633 else
634 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
635 x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
636 /* Set arg4 == rethrow/pc_offset */
637 if (resume_unwind) {
638 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], 0, 4);
639 } else if (corlib) {
640 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
641 if (llvm_abs) {
643 * The caller is LLVM code which passes the absolute address not a pc offset,
644 * so compensate by passing 0 as 'ip' and passing the negated abs address as
645 * the pc offset.
647 x86_neg_reg (code, X86_EAX);
649 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
650 } else {
651 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
653 /* Make the call */
654 if (aot) {
655 // This can be called from runtime code, which can't guarantee that
656 // ebx contains the got address.
657 // So emit the got address loading code too
658 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
659 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");
660 x86_call_reg (code, X86_EAX);
661 } else {
662 x86_call_code (code, resume_unwind ? (gpointer)(mono_x86_resume_unwind) : (corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception));
664 x86_breakpoint (code);
666 g_assert ((code - start) < kMaxCodeSize);
668 if (info)
669 *info = mono_tramp_info_create (name, start, code - start, ji, unwind_ops);
670 else {
671 GSList *l;
673 for (l = unwind_ops; l; l = l->next)
674 g_free (l->data);
675 g_slist_free (unwind_ops);
678 mono_arch_flush_icache (start, code - start);
679 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
681 return start;
685 * mono_arch_get_throw_exception:
686 * \returns a function pointer which can be used to raise
687 * exceptions. The returned function has the following
688 * signature: void (*func) (MonoException *exc);
689 * For example to raise an arithmetic exception you can use:
691 * x86_push_imm (code, mono_get_exception_arithmetic ());
692 * x86_call_code (code, arch_get_throw_exception ());
695 gpointer
696 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
698 return get_throw_trampoline ("throw_exception", FALSE, FALSE, FALSE, FALSE, FALSE, info, aot);
701 gpointer
702 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
704 return get_throw_trampoline ("rethrow_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot);
708 * mono_arch_get_throw_corlib_exception:
709 * \returns a function pointer which can be used to raise
710 * corlib exceptions. The returned function has the following
711 * signature: void (*func) (guint32 ex_token, guint32 offset);
712 * Here, offset is the offset which needs to be substracted from the caller IP
713 * to get the IP of the throw. Passing the offset has the advantage that it
714 * needs no relocations in the caller.
716 gpointer
717 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
719 return get_throw_trampoline ("throw_corlib_exception", FALSE, FALSE, TRUE, FALSE, FALSE, info, aot);
722 void
723 mono_arch_exceptions_init (void)
725 guint8 *tramp;
726 MonoTrampInfo *tinfo;
729 * If we're running WoW64, we need to set the usermode exception policy
730 * for SEHs to behave. This requires hotfix http://support.microsoft.com/kb/976038
731 * or (eventually) Windows 7 SP1.
733 #ifdef TARGET_WIN32
734 DWORD flags;
735 FARPROC getter;
736 FARPROC setter;
737 HMODULE kernel32 = LoadLibraryW (L"kernel32.dll");
739 if (kernel32) {
740 getter = GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy");
741 setter = GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy");
742 if (getter && setter) {
743 if (getter (&flags))
744 setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
747 #endif
749 if (mono_aot_only) {
750 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
751 return;
754 /* LLVM needs different throw trampolines */
755 tramp = get_throw_trampoline ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, &tinfo, FALSE);
756 mono_register_jit_icall (tramp, "llvm_throw_exception_trampoline", NULL, TRUE);
757 mono_tramp_info_register (tinfo, NULL);
759 tramp = get_throw_trampoline ("llvm_rethrow_exception_trampoline", TRUE, TRUE, FALSE, FALSE, FALSE, &tinfo, FALSE);
760 mono_register_jit_icall (tramp, "llvm_rethrow_exception_trampoline", NULL, TRUE);
761 mono_tramp_info_register (tinfo, NULL);
763 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, FALSE, &tinfo, FALSE);
764 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
765 mono_tramp_info_register (tinfo, NULL);
767 tramp = get_throw_trampoline ("llvm_throw_corlib_exception_abs_trampoline", FALSE, TRUE, TRUE, TRUE, FALSE, &tinfo, FALSE);
768 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
769 mono_tramp_info_register (tinfo, NULL);
771 tramp = get_throw_trampoline ("llvm_resume_unwind_trampoline", FALSE, FALSE, FALSE, FALSE, TRUE, &tinfo, FALSE);
772 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
773 mono_tramp_info_register (tinfo, NULL);
775 signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (&tinfo, FALSE);
776 mono_tramp_info_register (tinfo, NULL);
780 * mono_arch_unwind_frame:
782 * See exceptions-amd64.c for docs.
784 gboolean
785 mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls,
786 MonoJitInfo *ji, MonoContext *ctx,
787 MonoContext *new_ctx, MonoLMF **lmf,
788 mgreg_t **save_locations,
789 StackFrameInfo *frame)
791 gpointer ip = MONO_CONTEXT_GET_IP (ctx);
793 memset (frame, 0, sizeof (StackFrameInfo));
794 frame->ji = ji;
796 *new_ctx = *ctx;
798 if (ji != NULL) {
799 gssize regs [MONO_MAX_IREGS + 1];
800 guint8 *cfa;
801 guint32 unwind_info_len;
802 guint8 *unwind_info;
804 if (ji->is_trampoline)
805 frame->type = FRAME_TYPE_TRAMPOLINE;
806 else
807 frame->type = FRAME_TYPE_MANAGED;
809 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
811 regs [X86_EAX] = new_ctx->eax;
812 regs [X86_EBX] = new_ctx->ebx;
813 regs [X86_ECX] = new_ctx->ecx;
814 regs [X86_EDX] = new_ctx->edx;
815 regs [X86_ESP] = new_ctx->esp;
816 regs [X86_EBP] = new_ctx->ebp;
817 regs [X86_ESI] = new_ctx->esi;
818 regs [X86_EDI] = new_ctx->edi;
819 regs [X86_NREG] = new_ctx->eip;
821 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start,
822 (guint8*)ji->code_start + ji->code_size,
823 ip, NULL, regs, MONO_MAX_IREGS + 1,
824 save_locations, MONO_MAX_IREGS, &cfa);
826 new_ctx->eax = regs [X86_EAX];
827 new_ctx->ebx = regs [X86_EBX];
828 new_ctx->ecx = regs [X86_ECX];
829 new_ctx->edx = regs [X86_EDX];
830 new_ctx->esp = regs [X86_ESP];
831 new_ctx->ebp = regs [X86_EBP];
832 new_ctx->esi = regs [X86_ESI];
833 new_ctx->edi = regs [X86_EDI];
834 new_ctx->eip = regs [X86_NREG];
836 /* The CFA becomes the new SP value */
837 new_ctx->esp = (gssize)cfa;
839 /* Adjust IP */
840 new_ctx->eip --;
842 return TRUE;
843 } else if (*lmf) {
845 if (((guint64)(*lmf)->previous_lmf) & 2) {
847 * This LMF entry is created by the soft debug code to mark transitions to
848 * managed code done during invokes.
850 MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
852 g_assert (ext->debugger_invoke);
854 memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
856 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
858 frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
860 return TRUE;
863 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
864 frame->ji = ji;
865 } else {
866 if (!(*lmf)->method)
867 return FALSE;
868 frame->method = (*lmf)->method;
871 new_ctx->esi = (*lmf)->esi;
872 new_ctx->edi = (*lmf)->edi;
873 new_ctx->ebx = (*lmf)->ebx;
874 new_ctx->ebp = (*lmf)->ebp;
875 new_ctx->eip = (*lmf)->eip;
877 /* Adjust IP */
878 new_ctx->eip --;
880 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
882 /* Check if we are in a trampoline LMF frame */
883 if ((guint32)((*lmf)->previous_lmf) & 1) {
884 /* lmf->esp is set by the trampoline code */
885 new_ctx->esp = (*lmf)->esp;
887 else
888 /* the lmf is always stored on the stack, so the following
889 * expression points to a stack location which can be used as ESP */
890 new_ctx->esp = (unsigned long)&((*lmf)->eip);
892 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
894 return TRUE;
897 return FALSE;
900 gpointer
901 mono_arch_ip_from_context (void *sigctx)
903 #if defined(HOST_WATCHOS)
904 printf("WARNING: mono_arch_ip_from_context() called!\n");
905 return (NULL);
906 #elif defined(MONO_ARCH_USE_SIGACTION)
907 ucontext_t *ctx = (ucontext_t*)sigctx;
908 return (gpointer)UCONTEXT_REG_EIP (ctx);
909 #elif defined(HOST_WIN32)
910 return ((CONTEXT*)sigctx)->Eip;
911 #else
912 struct sigcontext *ctx = sigctx;
913 return (gpointer)ctx->SC_EIP;
914 #endif
918 * handle_exception:
920 * Called by resuming from a signal handler.
922 static void
923 handle_signal_exception (gpointer obj)
925 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
926 MonoContext ctx;
928 memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
930 mono_handle_exception (&ctx, obj);
932 mono_restore_context (&ctx);
936 * mono_x86_get_signal_exception_trampoline:
938 * This x86 specific trampoline is used to call handle_signal_exception.
940 gpointer
941 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
943 guint8 *start, *code;
944 MonoJumpInfo *ji = NULL;
945 GSList *unwind_ops = NULL;
946 int stack_size;
948 start = code = mono_global_codeman_reserve (128);
950 /* FIXME no unwind before we push ip */
951 /* Caller ip */
952 x86_push_reg (code, X86_ECX);
954 mono_add_unwind_op_def_cfa (unwind_ops, code, start, X86_ESP, 4);
955 mono_add_unwind_op_offset (unwind_ops, code, start, X86_NREG, -4);
957 /* Fix the alignment to be what apple expects */
958 stack_size = 12;
960 x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
961 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
963 /* Arg1 */
964 x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
965 /* Branch to target */
966 x86_call_reg (code, X86_EDX);
968 g_assert ((code - start) < 128);
970 if (info)
971 *info = mono_tramp_info_create ("x86_signal_exception_trampoline", start, code - start, ji, unwind_ops);
972 else {
973 GSList *l;
975 for (l = unwind_ops; l; l = l->next)
976 g_free (l->data);
977 g_slist_free (unwind_ops);
980 mono_arch_flush_icache (start, code - start);
981 MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
983 return start;
987 void
988 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
991 * Can't pass the obj on the stack, since we are executing on the
992 * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
993 * So put it into a register, and branch to a trampoline which
994 * pushes it.
996 ctx->eax = (mgreg_t)user_data;
997 ctx->ecx = ctx->eip;
998 ctx->edx = (mgreg_t)async_cb;
1000 /*align the stack*/
1001 ctx->esp = (ctx->esp - 16) & ~15;
1002 ctx->eip = (mgreg_t)signal_exception_trampoline;
1005 gboolean
1006 mono_arch_handle_exception (void *sigctx, gpointer obj)
1008 #if defined(MONO_ARCH_USE_SIGACTION)
1009 MonoContext mctx;
1010 ucontext_t *ctx = (ucontext_t*)sigctx;
1013 * Handling the exception in the signal handler is problematic, since the original
1014 * signal is disabled, and we could run arbitrary code though the debugger. So
1015 * resume into the normal stack and do most work there if possible.
1017 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1019 /* Pass the ctx parameter in TLS */
1020 mono_sigctx_to_monoctx (ctx, &jit_tls->ex_ctx);
1022 mctx = jit_tls->ex_ctx;
1023 mono_setup_async_callback (&mctx, handle_signal_exception, obj);
1024 mono_monoctx_to_sigctx (&mctx, sigctx);
1026 return TRUE;
1027 #elif defined (TARGET_WIN32)
1028 MonoContext mctx;
1029 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1030 struct sigcontext *ctx = (struct sigcontext *)sigctx;
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 void
1053 restore_soft_guard_pages (void)
1055 MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
1056 if (jit_tls->stack_ovf_guard_base)
1057 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1061 * this function modifies mctx so that when it is restored, it
1062 * won't execcute starting at mctx.eip, but in a function that
1063 * will restore the protection on the soft-guard pages and return back to
1064 * continue at mctx.eip.
1066 static void
1067 prepare_for_guard_pages (MonoContext *mctx)
1069 gpointer *sp;
1070 sp = (gpointer)(mctx->esp);
1071 sp -= 1;
1072 /* the resturn addr */
1073 sp [0] = (gpointer)(mctx->eip);
1074 mctx->eip = (unsigned long)restore_soft_guard_pages;
1075 mctx->esp = (unsigned long)sp;
1078 static void
1079 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
1081 MonoContext mctx;
1083 mctx = *ctx;
1085 mono_handle_exception (&mctx, obj);
1086 if (stack_ovf)
1087 prepare_for_guard_pages (&mctx);
1088 mono_restore_context (&mctx);
1091 void
1092 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
1094 #ifdef MONO_ARCH_USE_SIGACTION
1095 MonoException *exc = NULL;
1096 ucontext_t *ctx = (ucontext_t*)sigctx;
1097 MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1098 gpointer *sp;
1099 int frame_size;
1101 /* if we didn't find a managed method for the ip address and it matches the fault
1102 * address, we assume we followed a broken pointer during an indirect call, so
1103 * we try the lookup again with the return address pushed on the stack
1105 if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1106 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1107 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1108 if (ji)
1109 UCONTEXT_REG_EIP (ctx) = sp [0];
1111 if (stack_ovf)
1112 exc = mono_domain_get ()->stack_overflow_ex;
1113 if (!ji)
1114 mono_handle_native_crash ("SIGSEGV", sigctx, siginfo);
1115 /* setup a call frame on the real stack so that control is returned there
1116 * and exception handling can continue.
1117 * If this was a stack overflow the caller already ensured the stack pages
1118 * needed have been unprotected.
1119 * The frame looks like:
1120 * ucontext struct
1121 * test_only arg
1122 * exception arg
1123 * ctx arg
1124 * return ip
1126 // FIXME: test_only is no more.
1127 frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4;
1128 frame_size += 15;
1129 frame_size &= ~15;
1130 sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1131 sp = (gpointer)((char*)sp - frame_size);
1132 /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1133 * goes at sp [-1]
1135 sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1136 sp [0] = sp + 4;
1137 sp [1] = exc;
1138 sp [2] = (gpointer)stack_ovf;
1139 mono_sigctx_to_monoctx (sigctx, (MonoContext*)(sp + 4));
1140 /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1141 UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1142 UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1143 #endif
1146 #if MONO_SUPPORT_TASKLETS
1147 MonoContinuationRestore
1148 mono_tasklets_arch_restore (void)
1150 static guint8* saved = NULL;
1151 guint8 *code, *start;
1153 if (saved)
1154 return (MonoContinuationRestore)saved;
1155 code = start = mono_global_codeman_reserve (48);
1156 /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1157 /* put cont in edx */
1158 x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1159 /* state in eax, so it's setup as the return value */
1160 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1161 /* lmf_addr in ebx */
1162 x86_mov_reg_membase(code, X86_EBX, X86_ESP, 0x0C, 4);
1164 /* setup the copy of the stack */
1165 x86_mov_reg_membase (code, X86_ECX, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1166 x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1167 x86_cld (code);
1168 x86_mov_reg_membase (code, X86_ESI, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1169 x86_mov_reg_membase (code, X86_EDI, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1170 x86_prefix (code, X86_REP_PREFIX);
1171 x86_movsl (code);
1173 /* now restore the registers from the LMF */
1174 x86_mov_reg_membase (code, X86_ECX, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1175 x86_mov_reg_membase (code, X86_EBP, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, ebp), 4);
1176 x86_mov_reg_membase (code, X86_ESP, X86_ECX, MONO_STRUCT_OFFSET (MonoLMF, esp), 4);
1178 /* restore the lmf chain */
1179 /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1180 x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1182 x86_jump_membase (code, X86_EDX, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1183 g_assert ((code - start) <= 48);
1184 saved = start;
1185 return (MonoContinuationRestore)saved;
1187 #endif
1190 * mono_arch_setup_resume_sighandler_ctx:
1192 * Setup CTX so execution continues at FUNC.
1194 void
1195 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1197 int align = (((gint32)MONO_CONTEXT_GET_SP (ctx)) % MONO_ARCH_FRAME_ALIGNMENT + 4);
1199 if (align != 0)
1200 MONO_CONTEXT_SET_SP (ctx, (gsize)MONO_CONTEXT_GET_SP (ctx) - align);
1202 MONO_CONTEXT_SET_IP (ctx, func);