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