Merge pull request #3692 from lateralusX/jlorenss/win-api-family-support-libmono
[mono.git] / mono / mini / exceptions-amd64.c
1 /*
2  * exceptions-amd64.c: exception support for AMD64
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
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.
10  */
11
12 #include <config.h>
13
14 #include <glib.h>
15 #include <string.h>
16
17 #ifdef HAVE_SIGNAL_H
18 #include <signal.h>
19 #endif
20 #ifdef HAVE_UCONTEXT_H
21 #include <ucontext.h>
22 #endif
23
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>
35
36 #include "mini.h"
37 #include "mini-amd64.h"
38 #include "tasklets.h"
39
40 #define ALIGN_TO(val,align) (((val) + ((align) - 1)) & ~((align) - 1))
41
42 #ifdef TARGET_WIN32
43 static MonoW32ExceptionHandler fpe_handler;
44 static MonoW32ExceptionHandler ill_handler;
45 static MonoW32ExceptionHandler segv_handler;
46
47 LPTOP_LEVEL_EXCEPTION_FILTER mono_old_win_toplevel_exception_filter;
48 void *mono_win_vectored_exception_handle;
49
50 #define W32_SEH_HANDLE_EX(_ex) \
51         if (_ex##_handler) _ex##_handler(0, ep, ctx)
52
53 static LONG CALLBACK seh_unhandled_exception_filter(EXCEPTION_POINTERS* ep)
54 {
55 #ifndef MONO_CROSS_COMPILE
56         if (mono_old_win_toplevel_exception_filter) {
57                 return (*mono_old_win_toplevel_exception_filter)(ep);
58         }
59 #endif
60
61         mono_handle_native_sigsegv (SIGSEGV, NULL, NULL);
62
63         return EXCEPTION_CONTINUE_SEARCH;
64 }
65
66 /*
67  * Unhandled Exception Filter
68  * Top-level per-process exception handler.
69  */
70 static LONG CALLBACK seh_vectored_exception_handler(EXCEPTION_POINTERS* ep)
71 {
72         EXCEPTION_RECORD* er;
73         CONTEXT* ctx;
74         LONG res;
75         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
76
77         /* If the thread is not managed by the runtime return early */
78         if (!jit_tls)
79                 return EXCEPTION_CONTINUE_SEARCH;
80
81         jit_tls->mono_win_chained_exception_needs_run = FALSE;
82         res = EXCEPTION_CONTINUE_EXECUTION;
83
84         er = ep->ExceptionRecord;
85         ctx = ep->ContextRecord;
86
87         switch (er->ExceptionCode) {
88         case EXCEPTION_ACCESS_VIOLATION:
89                 W32_SEH_HANDLE_EX(segv);
90                 break;
91         case EXCEPTION_ILLEGAL_INSTRUCTION:
92                 W32_SEH_HANDLE_EX(ill);
93                 break;
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);
101                 break;
102         default:
103                 jit_tls->mono_win_chained_exception_needs_run = TRUE;
104                 break;
105         }
106
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.
113                 */
114                 res = EXCEPTION_CONTINUE_SEARCH;
115         }
116
117         return res;
118 }
119
120 void win32_seh_init()
121 {
122         mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter);
123         mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler);
124 }
125
126 void win32_seh_cleanup()
127 {
128         guint32 ret = 0;
129
130         if (mono_old_win_toplevel_exception_filter) SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter);
131
132         ret = RemoveVectoredExceptionHandler (mono_win_vectored_exception_handle);
133         g_assert (ret);
134 }
135
136 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
137 {
138         switch (type) {
139         case SIGFPE:
140                 fpe_handler = handler;
141                 break;
142         case SIGILL:
143                 ill_handler = handler;
144                 break;
145         case SIGSEGV:
146                 segv_handler = handler;
147                 break;
148         default:
149                 break;
150         }
151 }
152
153 #endif /* TARGET_WIN32 */
154
155 #ifndef DISABLE_JIT
156 /*
157  * mono_arch_get_restore_context:
158  *
159  * Returns a pointer to a method which restores a previously saved sigcontext.
160  */
161 gpointer
162 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
163 {
164         guint8 *start = NULL;
165         guint8 *code;
166         MonoJumpInfo *ji = NULL;
167         GSList *unwind_ops = NULL;
168         int i, gregs_offset;
169
170         /* restore_contect (MonoContext *ctx) */
171
172         start = code = (guint8 *)mono_global_codeman_reserve (256);
173
174         amd64_mov_reg_reg (code, AMD64_R11, AMD64_ARG_REG1, 8);
175
176         /* Restore all registers except %rip and %r11 */
177         gregs_offset = MONO_STRUCT_OFFSET (MonoContext, gregs);
178         for (i = 0; i < AMD64_NREG; ++i) {
179                 if (i != AMD64_RIP && i != AMD64_RSP && i != AMD64_R8 && i != AMD64_R9 && i != AMD64_R10 && i != AMD64_R11)
180                         amd64_mov_reg_membase (code, i, AMD64_R11, gregs_offset + (i * 8), 8);
181         }
182
183         /*
184          * The context resides on the stack, in the stack frame of the
185          * caller of this function.  The stack pointer that we need to
186          * restore is potentially many stack frames higher up, so the
187          * distance between them can easily be more than the red zone
188          * size.  Hence the stack pointer can be restored only after
189          * we have finished loading everything from the context.
190          */
191         amd64_mov_reg_membase (code, AMD64_R8, AMD64_R11,  gregs_offset + (AMD64_RSP * 8), 8);
192         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11,  gregs_offset + (AMD64_RIP * 8), 8);
193         amd64_mov_reg_reg (code, AMD64_RSP, AMD64_R8, 8);
194
195         /* jump to the saved IP */
196         amd64_jump_reg (code, AMD64_R11);
197
198         mono_arch_flush_icache (start, code - start);
199         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
200
201         if (info)
202                 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
203
204         return start;
205 }
206
207 /*
208  * mono_arch_get_call_filter:
209  *
210  * Returns a pointer to a method which calls an exception filter. We
211  * also use this function to call finally handlers (we pass NULL as 
212  * @exc object in this case).
213  */
214 gpointer
215 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
216 {
217         guint8 *start;
218         int i, gregs_offset;
219         guint8 *code;
220         guint32 pos;
221         MonoJumpInfo *ji = NULL;
222         GSList *unwind_ops = NULL;
223         const guint kMaxCodeSize = 128;
224
225         start = code = (guint8 *)mono_global_codeman_reserve (kMaxCodeSize);
226
227         /* call_filter (MonoContext *ctx, unsigned long eip) */
228         code = start;
229
230         /* Alloc new frame */
231         amd64_push_reg (code, AMD64_RBP);
232         amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, 8);
233
234         /* Save callee saved regs */
235         pos = 0;
236         for (i = 0; i < AMD64_NREG; ++i)
237                 if (AMD64_IS_CALLEE_SAVED_REG (i)) {
238                         amd64_push_reg (code, i);
239                         pos += 8;
240                 }
241
242         /* Save EBP */
243         pos += 8;
244         amd64_push_reg (code, AMD64_RBP);
245
246         /* Make stack misaligned, the call will make it aligned again */
247         if (! (pos & 8))
248                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
249
250         gregs_offset = MONO_STRUCT_OFFSET (MonoContext, gregs);
251
252         /* set new EBP */
253         amd64_mov_reg_membase (code, AMD64_RBP, AMD64_ARG_REG1, gregs_offset + (AMD64_RBP * 8), 8);
254         /* load callee saved regs */
255         for (i = 0; i < AMD64_NREG; ++i) {
256                 if (AMD64_IS_CALLEE_SAVED_REG (i) && i != AMD64_RBP)
257                         amd64_mov_reg_membase (code, i, AMD64_ARG_REG1, gregs_offset + (i * 8), 8);
258         }
259         /* load exc register */
260         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_ARG_REG1,  gregs_offset + (AMD64_RAX * 8), 8);
261
262         /* call the handler */
263         amd64_call_reg (code, AMD64_ARG_REG2);
264
265         if (! (pos & 8))
266                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
267
268         /* restore RBP */
269         amd64_pop_reg (code, AMD64_RBP);
270
271         /* Restore callee saved regs */
272         for (i = AMD64_NREG; i >= 0; --i)
273                 if (AMD64_IS_CALLEE_SAVED_REG (i))
274                         amd64_pop_reg (code, i);
275
276         amd64_leave (code);
277         amd64_ret (code);
278
279         g_assert ((code - start) < kMaxCodeSize);
280
281         mono_arch_flush_icache (start, code - start);
282         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
283
284         if (info)
285                 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
286
287         return start;
288 }
289 #endif /* !DISABLE_JIT */
290
291 /* 
292  * The first few arguments are dummy, to force the other arguments to be passed on
293  * the stack, this avoids overwriting the argument registers in the throw trampoline.
294  */
295 void
296 mono_amd64_throw_exception (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
297                                                         guint64 dummy5, guint64 dummy6,
298                                                         MonoContext *mctx, MonoObject *exc, gboolean rethrow)
299 {
300         MonoError error;
301         MonoContext ctx;
302
303         /* mctx is on the caller's stack */
304         memcpy (&ctx, mctx, sizeof (MonoContext));
305
306         if (mono_object_isinst_checked (exc, mono_defaults.exception_class, &error)) {
307                 MonoException *mono_ex = (MonoException*)exc;
308                 if (!rethrow) {
309                         mono_ex->stack_trace = NULL;
310                         mono_ex->trace_ips = NULL;
311                 }
312         }
313         mono_error_assert_ok (&error);
314
315         /* adjust eip so that it point into the call instruction */
316         ctx.gregs [AMD64_RIP] --;
317
318         mono_handle_exception (&ctx, exc);
319         mono_restore_context (&ctx);
320         g_assert_not_reached ();
321 }
322
323 void
324 mono_amd64_throw_corlib_exception (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
325                                                                    guint64 dummy5, guint64 dummy6,
326                                                                    MonoContext *mctx, guint32 ex_token_index, gint64 pc_offset)
327 {
328         guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
329         MonoException *ex;
330
331         ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
332
333         mctx->gregs [AMD64_RIP] -= pc_offset;
334
335         /* Negate the ip adjustment done in mono_amd64_throw_exception () */
336         mctx->gregs [AMD64_RIP] += 1;
337
338         mono_amd64_throw_exception (dummy1, dummy2, dummy3, dummy4, dummy5, dummy6, mctx, (MonoObject*)ex, FALSE);
339 }
340
341 void
342 mono_amd64_resume_unwind (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
343                                                   guint64 dummy5, guint64 dummy6,
344                                                   MonoContext *mctx, guint32 dummy7, gint64 dummy8)
345 {
346         /* Only the register parameters are valid */
347         MonoContext ctx;
348
349         /* mctx is on the caller's stack */
350         memcpy (&ctx, mctx, sizeof (MonoContext));
351
352         mono_resume_unwind (&ctx);
353 }
354
355 #ifndef DISABLE_JIT
356 /*
357  * get_throw_trampoline:
358  *
359  *  Generate a call to mono_amd64_throw_exception/
360  * mono_amd64_throw_corlib_exception.
361  */
362 static gpointer
363 get_throw_trampoline (MonoTrampInfo **info, gboolean rethrow, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, const char *tramp_name, gboolean aot)
364 {
365         guint8* start;
366         guint8 *code;
367         MonoJumpInfo *ji = NULL;
368         GSList *unwind_ops = NULL;
369         int i, stack_size, arg_offsets [16], ctx_offset, regs_offset, dummy_stack_space;
370         const guint kMaxCodeSize = 256;
371
372 #ifdef TARGET_WIN32
373         dummy_stack_space = 6 * sizeof(mgreg_t);        /* Windows expects stack space allocated for all 6 dummy args. */
374 #else
375         dummy_stack_space = 0;
376 #endif
377
378         start = code = (guint8 *)mono_global_codeman_reserve (kMaxCodeSize);
379
380         /* The stack is unaligned on entry */
381         stack_size = ALIGN_TO (sizeof (MonoContext) + 64 + dummy_stack_space, MONO_ARCH_FRAME_ALIGNMENT) + 8;
382
383         code = start;
384
385         if (info)
386                 unwind_ops = mono_arch_get_cie_program ();
387
388         /* Alloc frame */
389         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_size);
390         if (info)
391                 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 8);
392
393         /*
394          * To hide linux/windows calling convention differences, we pass all arguments on
395          * the stack by passing 6 dummy values in registers.
396          */
397
398         arg_offsets [0] = dummy_stack_space + 0;
399         arg_offsets [1] = dummy_stack_space + sizeof(mgreg_t);
400         arg_offsets [2] = dummy_stack_space + sizeof(mgreg_t) * 2;
401         ctx_offset = dummy_stack_space + sizeof(mgreg_t) * 4;
402         regs_offset = ctx_offset + MONO_STRUCT_OFFSET (MonoContext, gregs);
403
404         /* Save registers */
405         for (i = 0; i < AMD64_NREG; ++i)
406                 if (i != AMD64_RSP)
407                         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
408         /* Save RSP */
409         amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, stack_size + sizeof(mgreg_t));
410         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RSP * sizeof(mgreg_t)), X86_EAX, sizeof(mgreg_t));
411         /* Save IP */
412         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, stack_size, sizeof(mgreg_t));
413         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RIP * sizeof(mgreg_t)), AMD64_RAX, sizeof(mgreg_t));
414         /* Set arg1 == ctx */
415         amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, ctx_offset);
416         amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [0], AMD64_RAX, sizeof(mgreg_t));
417         /* Set arg2 == exc/ex_token_index */
418         if (resume_unwind)
419                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [1], 0, sizeof(mgreg_t));
420         else
421                 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [1], AMD64_ARG_REG1, sizeof(mgreg_t));
422         /* Set arg3 == rethrow/pc offset */
423         if (resume_unwind) {
424                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], 0, sizeof(mgreg_t));
425         } else if (corlib) {
426                 if (llvm_abs)
427                         /*
428                          * The caller doesn't pass in a pc/pc offset, instead we simply use the
429                          * caller ip. Negate the pc adjustment done in mono_amd64_throw_corlib_exception ().
430                          */
431                         amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], 1, sizeof(mgreg_t));
432                 else
433                         amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [2], AMD64_ARG_REG2, sizeof(mgreg_t));
434         } else {
435                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], rethrow, sizeof(mgreg_t));
436         }
437
438         if (aot) {
439                 const char *icall_name;
440
441                 if (resume_unwind)
442                         icall_name = "mono_amd64_resume_unwind";
443                 else if (corlib)
444                         icall_name = "mono_amd64_throw_corlib_exception";
445                 else
446                         icall_name = "mono_amd64_throw_exception";
447                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
448                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
449         } else {
450                 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));
451         }
452         amd64_call_reg (code, AMD64_R11);
453         amd64_breakpoint (code);
454
455         mono_arch_flush_icache (start, code - start);
456
457         g_assert ((code - start) < kMaxCodeSize);
458
459         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
460
461         if (info)
462                 *info = mono_tramp_info_create (tramp_name, start, code - start, ji, unwind_ops);
463
464         return start;
465 }
466
467 /**
468  * mono_arch_get_throw_exception:
469  *
470  * Returns a function pointer which can be used to raise 
471  * exceptions. The returned function has the following 
472  * signature: void (*func) (MonoException *exc); 
473  *
474  */
475 gpointer
476 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
477 {
478         return get_throw_trampoline (info, FALSE, FALSE, FALSE, FALSE, "throw_exception", aot);
479 }
480
481 gpointer 
482 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
483 {
484         return get_throw_trampoline (info, TRUE, FALSE, FALSE, FALSE, "rethrow_exception", aot);
485 }
486
487 /**
488  * mono_arch_get_throw_corlib_exception:
489  *
490  * Returns a function pointer which can be used to raise 
491  * corlib exceptions. The returned function has the following 
492  * signature: void (*func) (guint32 ex_token, guint32 offset); 
493  * Here, offset is the offset which needs to be substracted from the caller IP 
494  * to get the IP of the throw. Passing the offset has the advantage that it 
495  * needs no relocations in the caller.
496  */
497 gpointer 
498 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
499 {
500         return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
501 }
502 #endif /* !DISABLE_JIT */
503
504 /*
505  * mono_arch_unwind_frame:
506  *
507  * This function is used to gather information from @ctx, and store it in @frame_info.
508  * It unwinds one stack frame, and stores the resulting context into @new_ctx. @lmf
509  * is modified if needed.
510  * Returns TRUE on success, FALSE otherwise.
511  */
512 gboolean
513 mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, 
514                                                          MonoJitInfo *ji, MonoContext *ctx, 
515                                                          MonoContext *new_ctx, MonoLMF **lmf,
516                                                          mgreg_t **save_locations,
517                                                          StackFrameInfo *frame)
518 {
519         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
520         int i;
521
522         memset (frame, 0, sizeof (StackFrameInfo));
523         frame->ji = ji;
524
525         *new_ctx = *ctx;
526
527         if (ji != NULL) {
528                 mgreg_t regs [MONO_MAX_IREGS + 1];
529                 guint8 *cfa;
530                 guint32 unwind_info_len;
531                 guint8 *unwind_info;
532                 guint8 *epilog = NULL;
533
534                 if (ji->is_trampoline)
535                         frame->type = FRAME_TYPE_TRAMPOLINE;
536                 else
537                         frame->type = FRAME_TYPE_MANAGED;
538
539                 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
540
541                 frame->unwind_info = unwind_info;
542                 frame->unwind_info_len = unwind_info_len;
543
544                 /*
545                 printf ("%s %p %p\n", ji->d.method->name, ji->code_start, ip);
546                 mono_print_unwind_info (unwind_info, unwind_info_len);
547                 */
548                 /* LLVM compiled code doesn't have this info */
549                 if (ji->has_arch_eh_info)
550                         epilog = (guint8*)ji->code_start + ji->code_size - mono_jinfo_get_epilog_size (ji);
551  
552                 for (i = 0; i < AMD64_NREG; ++i)
553                         regs [i] = new_ctx->gregs [i];
554
555                 mono_unwind_frame (unwind_info, unwind_info_len, (guint8 *)ji->code_start,
556                                                    (guint8*)ji->code_start + ji->code_size,
557                                                    (guint8 *)ip, epilog ? &epilog : NULL, regs, MONO_MAX_IREGS + 1,
558                                                    save_locations, MONO_MAX_IREGS, &cfa);
559
560                 for (i = 0; i < AMD64_NREG; ++i)
561                         new_ctx->gregs [i] = regs [i];
562  
563                 /* The CFA becomes the new SP value */
564                 new_ctx->gregs [AMD64_RSP] = (mgreg_t)cfa;
565
566                 /* Adjust IP */
567                 new_ctx->gregs [AMD64_RIP] --;
568
569                 return TRUE;
570         } else if (*lmf) {
571                 guint64 rip;
572
573                 if (((guint64)(*lmf)->previous_lmf) & 2) {
574                         /* 
575                          * This LMF entry is created by the soft debug code to mark transitions to
576                          * managed code done during invokes.
577                          */
578                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
579
580                         g_assert (ext->debugger_invoke);
581
582                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
583
584                         *lmf = (MonoLMF *)(((guint64)(*lmf)->previous_lmf) & ~7);
585
586                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
587
588                         return TRUE;
589                 }
590
591                 if (((guint64)(*lmf)->previous_lmf) & 4) {
592                         MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
593
594                         rip = (guint64)MONO_CONTEXT_GET_IP (ext->ctx);
595                 } else if (((guint64)(*lmf)->previous_lmf) & 1) {
596                         /* This LMF has the rip field set */
597                         rip = (*lmf)->rip;
598                 } else if ((*lmf)->rsp == 0) {
599                         /* Top LMF entry */
600                         return FALSE;
601                 } else {
602                         /* 
603                          * The rsp field is set just before the call which transitioned to native 
604                          * code. Obtain the rip from the stack.
605                          */
606                         rip = *(guint64*)((*lmf)->rsp - sizeof(mgreg_t));
607                 }
608
609                 ji = mini_jit_info_table_find (domain, (char *)rip, NULL);
610                 /*
611                  * FIXME: ji == NULL can happen when a managed-to-native wrapper is interrupted
612                  * in the soft debugger suspend code, since (*lmf)->rsp no longer points to the
613                  * return address.
614                  */
615                 //g_assert (ji);
616                 if (!ji)
617                         return FALSE;
618
619                 frame->ji = ji;
620                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
621
622                 if (((guint64)(*lmf)->previous_lmf) & 4) {
623                         MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
624
625                         /* Trampoline frame */
626                         for (i = 0; i < AMD64_NREG; ++i)
627                                 new_ctx->gregs [i] = ext->ctx->gregs [i];
628                         /* Adjust IP */
629                         new_ctx->gregs [AMD64_RIP] --;
630                 } else {
631                         /*
632                          * The registers saved in the LMF will be restored using the normal unwind info,
633                          * when the wrapper frame is processed.
634                          */
635                         /* Adjust IP */
636                         rip --;
637                         new_ctx->gregs [AMD64_RIP] = rip;
638                         new_ctx->gregs [AMD64_RSP] = (*lmf)->rsp;
639                         new_ctx->gregs [AMD64_RBP] = (*lmf)->rbp;
640                         for (i = 0; i < AMD64_NREG; ++i) {
641                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && i != AMD64_RBP)
642                                         new_ctx->gregs [i] = 0;
643                         }
644                 }
645
646                 *lmf = (MonoLMF *)(((guint64)(*lmf)->previous_lmf) & ~7);
647
648                 return TRUE;
649         }
650
651         return FALSE;
652 }
653
654 /*
655  * handle_exception:
656  *
657  *   Called by resuming from a signal handler.
658  */
659 static void
660 handle_signal_exception (gpointer obj)
661 {
662         MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
663         MonoContext ctx;
664
665         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
666
667         mono_handle_exception (&ctx, (MonoObject *)obj);
668
669         mono_restore_context (&ctx);
670 }
671
672 void
673 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
674 {
675         guint64 sp = ctx->gregs [AMD64_RSP];
676
677         ctx->gregs [AMD64_RDI] = (guint64)user_data;
678
679         /* Allocate a stack frame below the red zone */
680         sp -= 128;
681         /* The stack should be unaligned */
682         if ((sp % 16) == 0)
683                 sp -= 8;
684 #ifdef __linux__
685         /* Preserve the call chain to prevent crashes in the libgcc unwinder (#15969) */
686         *(guint64*)sp = ctx->gregs [AMD64_RIP];
687 #endif
688         ctx->gregs [AMD64_RSP] = sp;
689         ctx->gregs [AMD64_RIP] = (guint64)async_cb;
690 }
691
692 /**
693  * mono_arch_handle_exception:
694  *
695  * @ctx: saved processor state
696  * @obj: the exception object
697  */
698 gboolean
699 mono_arch_handle_exception (void *sigctx, gpointer obj)
700 {
701 #if defined(MONO_ARCH_USE_SIGACTION)
702         MonoContext mctx;
703
704         /*
705          * Handling the exception in the signal handler is problematic, since the original
706          * signal is disabled, and we could run arbitrary code though the debugger. So
707          * resume into the normal stack and do most work there if possible.
708          */
709         MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
710
711         /* Pass the ctx parameter in TLS */
712         mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
713
714         mctx = jit_tls->ex_ctx;
715         mono_arch_setup_async_callback (&mctx, handle_signal_exception, obj);
716         mono_monoctx_to_sigctx (&mctx, sigctx);
717
718         return TRUE;
719 #else
720         MonoContext mctx;
721
722         mono_sigctx_to_monoctx (sigctx, &mctx);
723
724         mono_handle_exception (&mctx, obj);
725
726         mono_monoctx_to_sigctx (&mctx, sigctx);
727
728         return TRUE;
729 #endif
730 }
731
732 gpointer
733 mono_arch_ip_from_context (void *sigctx)
734 {
735 #if defined(MONO_ARCH_USE_SIGACTION)
736         ucontext_t *ctx = (ucontext_t*)sigctx;
737
738         return (gpointer)UCONTEXT_REG_RIP (ctx);
739 #elif defined(HOST_WIN32)
740         return ((CONTEXT*)sigctx)->Rip;
741 #else
742         MonoContext *ctx = sigctx;
743         return (gpointer)ctx->gregs [AMD64_RIP];
744 #endif  
745 }
746
747 static void
748 restore_soft_guard_pages (void)
749 {
750         MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
751         if (jit_tls->stack_ovf_guard_base)
752                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
753 }
754
755 /* 
756  * this function modifies mctx so that when it is restored, it
757  * won't execcute starting at mctx.eip, but in a function that
758  * will restore the protection on the soft-guard pages and return back to
759  * continue at mctx.eip.
760  */
761 static void
762 prepare_for_guard_pages (MonoContext *mctx)
763 {
764         gpointer *sp;
765         sp = (gpointer *)(mctx->gregs [AMD64_RSP]);
766         sp -= 1;
767         /* the return addr */
768         sp [0] = (gpointer)(mctx->gregs [AMD64_RIP]);
769         mctx->gregs [AMD64_RIP] = (guint64)restore_soft_guard_pages;
770         mctx->gregs [AMD64_RSP] = (guint64)sp;
771 }
772
773 static void
774 altstack_handle_and_restore (MonoContext *ctx, MonoObject *obj, gboolean stack_ovf)
775 {
776         MonoContext mctx;
777
778         mctx = *ctx;
779
780         mono_handle_exception (&mctx, obj);
781         if (stack_ovf)
782                 prepare_for_guard_pages (&mctx);
783         mono_restore_context (&mctx);
784 }
785
786 void
787 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
788 {
789 #if defined(MONO_ARCH_USE_SIGACTION)
790         MonoException *exc = NULL;
791         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (char *)UCONTEXT_REG_RIP (sigctx), NULL);
792         gpointer *sp;
793         int frame_size;
794         MonoContext *copied_ctx;
795
796         if (stack_ovf)
797                 exc = mono_domain_get ()->stack_overflow_ex;
798         if (!ji)
799                 mono_handle_native_sigsegv (SIGSEGV, sigctx, siginfo);
800
801         /* setup a call frame on the real stack so that control is returned there
802          * and exception handling can continue.
803          * The frame looks like:
804          *   ucontext struct
805          *   ...
806          *   return ip
807          * 128 is the size of the red zone
808          */
809         frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4 + 128;
810         frame_size += 15;
811         frame_size &= ~15;
812         sp = (gpointer *)(UCONTEXT_REG_RSP (sigctx) & ~15);
813         sp = (gpointer *)((char*)sp - frame_size);
814         copied_ctx = (MonoContext*)(sp + 4);
815         /* the arguments must be aligned */
816         sp [-1] = (gpointer)UCONTEXT_REG_RIP (sigctx);
817         mono_sigctx_to_monoctx (sigctx, copied_ctx);
818         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
819         UCONTEXT_REG_RIP (sigctx) = (unsigned long)altstack_handle_and_restore;
820         UCONTEXT_REG_RSP (sigctx) = (unsigned long)(sp - 1);
821         UCONTEXT_REG_RDI (sigctx) = (unsigned long)(copied_ctx);
822         UCONTEXT_REG_RSI (sigctx) = (guint64)exc;
823         UCONTEXT_REG_RDX (sigctx) = stack_ovf;
824 #endif
825 }
826
827 guint64
828 mono_amd64_get_original_ip (void)
829 {
830         MonoLMF *lmf = mono_get_lmf ();
831
832         g_assert (lmf);
833
834         /* Reset the change to previous_lmf */
835         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf & ~1);
836
837         return lmf->rip;
838 }
839
840 #ifndef DISABLE_JIT
841 GSList*
842 mono_amd64_get_exception_trampolines (gboolean aot)
843 {
844         MonoTrampInfo *info;
845         GSList *tramps = NULL;
846
847         /* LLVM needs different throw trampolines */
848         get_throw_trampoline (&info, FALSE, TRUE, FALSE, FALSE, "llvm_throw_corlib_exception_trampoline", aot);
849         tramps = g_slist_prepend (tramps, info);
850
851         get_throw_trampoline (&info, FALSE, TRUE, TRUE, FALSE, "llvm_throw_corlib_exception_abs_trampoline", aot);
852         tramps = g_slist_prepend (tramps, info);
853
854         get_throw_trampoline (&info, FALSE, TRUE, TRUE, TRUE, "llvm_resume_unwind_trampoline", aot);
855         tramps = g_slist_prepend (tramps, info);
856
857         return tramps;
858 }
859 #endif /* !DISABLE_JIT */
860
861 void
862 mono_arch_exceptions_init (void)
863 {
864         GSList *tramps, *l;
865         gpointer tramp;
866
867         if (mono_aot_only) {
868                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_trampoline");
869                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
870                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_abs_trampoline");
871                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
872                 tramp = mono_aot_get_trampoline ("llvm_resume_unwind_trampoline");
873                 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
874         } else {
875                 /* Call this to avoid initialization races */
876                 tramps = mono_amd64_get_exception_trampolines (FALSE);
877                 for (l = tramps; l; l = l->next) {
878                         MonoTrampInfo *info = (MonoTrampInfo *)l->data;
879
880                         mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE);
881                         mono_tramp_info_register (info, NULL);
882                 }
883                 g_slist_free (tramps);
884         }
885 }
886
887 #if defined(TARGET_WIN32) && !defined(DISABLE_JIT)
888
889 /*
890  * The mono_arch_unwindinfo* methods are used to build and add
891  * function table info for each emitted method from mono.  On Winx64
892  * the seh handler will not be called if the mono methods are not
893  * added to the function table.  
894  *
895  * We should not need to add non-volatile register info to the 
896  * table since mono stores that info elsewhere. (Except for the register 
897  * used for the fp.)
898  */
899
900 #define MONO_MAX_UNWIND_CODES 22
901
902 typedef union _UNWIND_CODE {
903     struct {
904         guchar CodeOffset;
905         guchar UnwindOp : 4;
906         guchar OpInfo   : 4;
907     };
908     gushort FrameOffset;
909 } UNWIND_CODE, *PUNWIND_CODE;
910
911 typedef struct _UNWIND_INFO {
912         guchar Version       : 3;
913         guchar Flags         : 5;
914         guchar SizeOfProlog;
915         guchar CountOfCodes;
916         guchar FrameRegister : 4;
917         guchar FrameOffset   : 4;
918         /* custom size for mono allowing for mono allowing for*/
919         /*UWOP_PUSH_NONVOL ebp offset = 21*/
920         /*UWOP_ALLOC_LARGE : requires 2 or 3 offset = 20*/
921         /*UWOP_SET_FPREG : requires 2 offset = 17*/
922         /*UWOP_PUSH_NONVOL offset = 15-0*/
923         UNWIND_CODE UnwindCode[MONO_MAX_UNWIND_CODES]; 
924
925 /*      UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
926  *      union {
927  *          OPTIONAL ULONG ExceptionHandler;
928  *          OPTIONAL ULONG FunctionEntry;
929  *      };
930  *      OPTIONAL ULONG ExceptionData[]; */
931 } UNWIND_INFO, *PUNWIND_INFO;
932
933 typedef struct
934 {
935         RUNTIME_FUNCTION runtimeFunction;
936         UNWIND_INFO unwindInfo;
937 } MonoUnwindInfo, *PMonoUnwindInfo;
938
939 static void
940 mono_arch_unwindinfo_create (gpointer* monoui)
941 {
942         PMonoUnwindInfo newunwindinfo;
943         *monoui = newunwindinfo = g_new0 (MonoUnwindInfo, 1);
944         newunwindinfo->unwindInfo.Version = 1;
945 }
946
947 void
948 mono_arch_unwindinfo_add_push_nonvol (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
949 {
950         PMonoUnwindInfo unwindinfo;
951         PUNWIND_CODE unwindcode;
952         guchar codeindex;
953         if (!*monoui)
954                 mono_arch_unwindinfo_create (monoui);
955         
956         unwindinfo = (MonoUnwindInfo*)*monoui;
957
958         if (unwindinfo->unwindInfo.CountOfCodes >= MONO_MAX_UNWIND_CODES)
959                 g_error ("Larger allocation needed for the unwind information.");
960
961         codeindex = MONO_MAX_UNWIND_CODES - (++unwindinfo->unwindInfo.CountOfCodes);
962         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
963         unwindcode->UnwindOp = 0; /*UWOP_PUSH_NONVOL*/
964         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
965         unwindcode->OpInfo = reg;
966
967         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
968                 g_error ("Adding unwind info in wrong order.");
969         
970         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
971 }
972
973 void
974 mono_arch_unwindinfo_add_set_fpreg (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
975 {
976         PMonoUnwindInfo unwindinfo;
977         PUNWIND_CODE unwindcode;
978         guchar codeindex;
979         if (!*monoui)
980                 mono_arch_unwindinfo_create (monoui);
981         
982         unwindinfo = (MonoUnwindInfo*)*monoui;
983
984         if (unwindinfo->unwindInfo.CountOfCodes + 1 >= MONO_MAX_UNWIND_CODES)
985                 g_error ("Larger allocation needed for the unwind information.");
986
987         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += 2);
988         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
989         unwindcode->FrameOffset = 0; /*Assuming no frame pointer offset for mono*/
990         unwindcode++;
991         unwindcode->UnwindOp = 3; /*UWOP_SET_FPREG*/
992         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
993         unwindcode->OpInfo = reg;
994         
995         unwindinfo->unwindInfo.FrameRegister = reg;
996
997         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
998                 g_error ("Adding unwind info in wrong order.");
999         
1000         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1001 }
1002
1003 void
1004 mono_arch_unwindinfo_add_alloc_stack (gpointer* monoui, gpointer codebegin, gpointer nextip, guint size )
1005 {
1006         PMonoUnwindInfo unwindinfo;
1007         PUNWIND_CODE unwindcode;
1008         guchar codeindex;
1009         guchar codesneeded;
1010         if (!*monoui)
1011                 mono_arch_unwindinfo_create (monoui);
1012         
1013         unwindinfo = (MonoUnwindInfo*)*monoui;
1014
1015         if (size < 0x8)
1016                 g_error ("Stack allocation must be equal to or greater than 0x8.");
1017         
1018         if (size <= 0x80)
1019                 codesneeded = 1;
1020         else if (size <= 0x7FFF8)
1021                 codesneeded = 2;
1022         else
1023                 codesneeded = 3;
1024         
1025         if (unwindinfo->unwindInfo.CountOfCodes + codesneeded > MONO_MAX_UNWIND_CODES)
1026                 g_error ("Larger allocation needed for the unwind information.");
1027
1028         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += codesneeded);
1029         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1030
1031         if (codesneeded == 1) {
1032                 /*The size of the allocation is 
1033                   (the number in the OpInfo member) times 8 plus 8*/
1034                 unwindcode->OpInfo = (size - 8)/8;
1035                 unwindcode->UnwindOp = 2; /*UWOP_ALLOC_SMALL*/
1036         }
1037         else {
1038                 if (codesneeded == 3) {
1039                         /*the unscaled size of the allocation is recorded
1040                           in the next two slots in little-endian format*/
1041                         *((unsigned int*)(&unwindcode->FrameOffset)) = size;
1042                         unwindcode += 2;
1043                         unwindcode->OpInfo = 1;
1044                 }
1045                 else {
1046                         /*the size of the allocation divided by 8
1047                           is recorded in the next slot*/
1048                         unwindcode->FrameOffset = size/8; 
1049                         unwindcode++;   
1050                         unwindcode->OpInfo = 0;
1051                         
1052                 }
1053                 unwindcode->UnwindOp = 1; /*UWOP_ALLOC_LARGE*/
1054         }
1055
1056         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1057
1058         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1059                 g_error ("Adding unwind info in wrong order.");
1060         
1061         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1062 }
1063
1064 guint
1065 mono_arch_unwindinfo_get_size (gpointer monoui)
1066 {
1067         PMonoUnwindInfo unwindinfo;
1068         if (!monoui)
1069                 return 0;
1070         
1071         unwindinfo = (MonoUnwindInfo*)monoui;
1072         return (8 + sizeof (MonoUnwindInfo)) - 
1073                 (sizeof (UNWIND_CODE) * (MONO_MAX_UNWIND_CODES - unwindinfo->unwindInfo.CountOfCodes));
1074 }
1075
1076 static PRUNTIME_FUNCTION
1077 MONO_GET_RUNTIME_FUNCTION_CALLBACK ( DWORD64 ControlPc, IN PVOID Context )
1078 {
1079         MonoJitInfo *ji;
1080         guint64 pos;
1081         PMonoUnwindInfo targetinfo;
1082         MonoDomain *domain = mono_domain_get ();
1083
1084         ji = mini_jit_info_table_find (domain, (char*)ControlPc, NULL);
1085         if (!ji)
1086                 return 0;
1087
1088         pos = (guint64)(((char*)ji->code_start) + ji->code_size);
1089         
1090         targetinfo = (PMonoUnwindInfo)ALIGN_TO (pos, 8);
1091
1092         targetinfo->runtimeFunction.UnwindData = ((DWORD64)&targetinfo->unwindInfo) - ((DWORD64)Context);
1093
1094         return &targetinfo->runtimeFunction;
1095 }
1096
1097 void
1098 mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint code_size)
1099 {
1100         PMonoUnwindInfo unwindinfo, targetinfo;
1101         guchar codecount;
1102         guint64 targetlocation;
1103         if (!*monoui)
1104                 return;
1105
1106         unwindinfo = (MonoUnwindInfo*)*monoui;
1107         targetlocation = (guint64)&(((guchar*)code)[code_size]);
1108         targetinfo = (PMonoUnwindInfo) ALIGN_TO(targetlocation, 8);
1109
1110         unwindinfo->runtimeFunction.EndAddress = code_size;
1111         unwindinfo->runtimeFunction.UnwindData = ((guchar*)&targetinfo->unwindInfo) - ((guchar*)code);
1112         
1113         memcpy (targetinfo, unwindinfo, sizeof (MonoUnwindInfo) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
1114         
1115         codecount = unwindinfo->unwindInfo.CountOfCodes;
1116         if (codecount) {
1117                 memcpy (&targetinfo->unwindInfo.UnwindCode[0], &unwindinfo->unwindInfo.UnwindCode[MONO_MAX_UNWIND_CODES-codecount], 
1118                         sizeof (UNWIND_CODE) * unwindinfo->unwindInfo.CountOfCodes);
1119         }
1120
1121         g_free (unwindinfo);
1122         *monoui = 0;
1123
1124         RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
1125 }
1126
1127 #endif /* defined(TARGET_WIN32) !defined(DISABLE_JIT) */
1128
1129 #if MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT)
1130 MonoContinuationRestore
1131 mono_tasklets_arch_restore (void)
1132 {
1133         static guint8* saved = NULL;
1134         guint8 *code, *start;
1135         int cont_reg = AMD64_R9; /* register usable on both call conventions */
1136         const guint kMaxCodeSize = 64;
1137         
1138
1139         if (saved)
1140                 return (MonoContinuationRestore)saved;
1141         code = start = (guint8 *)mono_global_codeman_reserve (kMaxCodeSize);
1142         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1143         /* cont is in AMD64_ARG_REG1 ($rcx or $rdi)
1144          * state is in AMD64_ARG_REG2 ($rdx or $rsi)
1145          * lmf_addr is in AMD64_ARG_REG3 ($r8 or $rdx)
1146          * We move cont to cont_reg since we need both rcx and rdi for the copy
1147          * state is moved to $rax so it's setup as the return value and we can overwrite $rsi
1148          */
1149         amd64_mov_reg_reg (code, cont_reg, MONO_AMD64_ARG_REG1, 8);
1150         amd64_mov_reg_reg (code, AMD64_RAX, MONO_AMD64_ARG_REG2, 8);
1151         /* setup the copy of the stack */
1152         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), sizeof (int));
1153         amd64_shift_reg_imm (code, X86_SHR, AMD64_RCX, 3);
1154         x86_cld (code);
1155         amd64_mov_reg_membase (code, AMD64_RSI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), sizeof (gpointer));
1156         amd64_mov_reg_membase (code, AMD64_RDI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), sizeof (gpointer));
1157         amd64_prefix (code, X86_REP_PREFIX);
1158         amd64_movsl (code);
1159
1160         /* now restore the registers from the LMF */
1161         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 8);
1162         amd64_mov_reg_membase (code, AMD64_RBP, AMD64_RCX, MONO_STRUCT_OFFSET (MonoLMF, rbp), 8);
1163         amd64_mov_reg_membase (code, AMD64_RSP, AMD64_RCX, MONO_STRUCT_OFFSET (MonoLMF, rsp), 8);
1164
1165 #ifdef WIN32
1166         amd64_mov_reg_reg (code, AMD64_R14, AMD64_ARG_REG3, 8);
1167 #else
1168         amd64_mov_reg_reg (code, AMD64_R12, AMD64_ARG_REG3, 8);
1169 #endif
1170
1171         /* state is already in rax */
1172         amd64_jump_membase (code, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1173         g_assert ((code - start) <= kMaxCodeSize);
1174
1175         mono_arch_flush_icache (start, code - start);
1176         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
1177
1178         saved = start;
1179         return (MonoContinuationRestore)saved;
1180 }
1181 #endif /* MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT) */
1182
1183 /*
1184  * mono_arch_setup_resume_sighandler_ctx:
1185  *
1186  *   Setup CTX so execution continues at FUNC.
1187  */
1188 void
1189 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1190 {
1191         /* 
1192          * When resuming from a signal handler, the stack should be misaligned, just like right after
1193          * a call.
1194          */
1195         if ((((guint64)MONO_CONTEXT_GET_SP (ctx)) % 16) == 0)
1196                 MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
1197         MONO_CONTEXT_SET_IP (ctx, func);
1198 }
1199
1200 #ifdef DISABLE_JIT
1201 gpointer
1202 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
1203 {
1204         g_assert_not_reached ();
1205         return NULL;
1206 }
1207
1208 gpointer
1209 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
1210 {
1211         g_assert_not_reached ();
1212         return NULL;
1213 }
1214
1215 gpointer
1216 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
1217 {
1218         g_assert_not_reached ();
1219         return NULL;
1220 }
1221
1222 gpointer
1223 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
1224 {
1225         g_assert_not_reached ();
1226         return NULL;
1227 }
1228
1229 gpointer
1230 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
1231 {
1232         g_assert_not_reached ();
1233         return NULL;
1234 }
1235
1236 GSList*
1237 mono_amd64_get_exception_trampolines (gboolean aot)
1238 {
1239         g_assert_not_reached ();
1240         return NULL;
1241 }
1242 #endif /* DISABLE_JIT */
1243
1244 #if !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT)
1245 MonoContinuationRestore
1246 mono_tasklets_arch_restore (void)
1247 {
1248         g_assert_not_reached ();
1249         return NULL;
1250 }
1251 #endif /* !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT) */