[jit] Remove the support for MONO_ARCH_NOTIFY_PENDING_EXC, it only works on amd64...
[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-internal.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 = 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 = 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, AMD64_RBX, 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         MonoContext ctx;
310
311         /* mctx is on the caller's stack */
312         memcpy (&ctx, mctx, sizeof (MonoContext));
313
314         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
315                 MonoException *mono_ex = (MonoException*)exc;
316                 if (!rethrow) {
317                         mono_ex->stack_trace = NULL;
318                         mono_ex->trace_ips = NULL;
319                 }
320         }
321
322         /* adjust eip so that it point into the call instruction */
323         ctx.gregs [AMD64_RIP] --;
324
325         mono_handle_exception (&ctx, exc);
326         mono_restore_context (&ctx);
327         g_assert_not_reached ();
328 }
329
330 void
331 mono_amd64_throw_corlib_exception (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
332                                                                    guint64 dummy5, guint64 dummy6,
333                                                                    MonoContext *mctx, guint32 ex_token_index, gint64 pc_offset)
334 {
335         guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
336         MonoException *ex;
337
338         ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
339
340         mctx->gregs [AMD64_RIP] -= pc_offset;
341
342         /* Negate the ip adjustment done in mono_amd64_throw_exception () */
343         mctx->gregs [AMD64_RIP] += 1;
344
345         mono_amd64_throw_exception (dummy1, dummy2, dummy3, dummy4, dummy5, dummy6, mctx, (MonoObject*)ex, FALSE);
346 }
347
348 void
349 mono_amd64_resume_unwind (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
350                                                   guint64 dummy5, guint64 dummy6,
351                                                   MonoContext *mctx, guint32 dummy7, gint64 dummy8)
352 {
353         /* Only the register parameters are valid */
354         MonoContext ctx;
355
356         /* mctx is on the caller's stack */
357         memcpy (&ctx, mctx, sizeof (MonoContext));
358
359         mono_resume_unwind (&ctx);
360 }
361
362 /*
363  * get_throw_trampoline:
364  *
365  *  Generate a call to mono_amd64_throw_exception/
366  * mono_amd64_throw_corlib_exception.
367  */
368 static gpointer
369 get_throw_trampoline (MonoTrampInfo **info, gboolean rethrow, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, const char *tramp_name, gboolean aot)
370 {
371         guint8* start;
372         guint8 *code;
373         MonoJumpInfo *ji = NULL;
374         GSList *unwind_ops = NULL;
375         int i, stack_size, arg_offsets [16], ctx_offset, regs_offset, dummy_stack_space;
376         const guint kMaxCodeSize = NACL_SIZE (256, 512);
377
378 #ifdef TARGET_WIN32
379         dummy_stack_space = 6 * sizeof(mgreg_t);        /* Windows expects stack space allocated for all 6 dummy args. */
380 #else
381         dummy_stack_space = 0;
382 #endif
383
384         start = code = mono_global_codeman_reserve (kMaxCodeSize);
385
386         /* The stack is unaligned on entry */
387         stack_size = ALIGN_TO (sizeof (MonoContext) + 64 + dummy_stack_space, MONO_ARCH_FRAME_ALIGNMENT) + 8;
388
389         code = start;
390
391         if (info)
392                 unwind_ops = mono_arch_get_cie_program ();
393
394         /* Alloc frame */
395         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_size);
396         if (info)
397                 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 8);
398
399         /*
400          * To hide linux/windows calling convention differences, we pass all arguments on
401          * the stack by passing 6 dummy values in registers.
402          */
403
404         arg_offsets [0] = dummy_stack_space + 0;
405         arg_offsets [1] = dummy_stack_space + sizeof(mgreg_t);
406         arg_offsets [2] = dummy_stack_space + sizeof(mgreg_t) * 2;
407         ctx_offset = dummy_stack_space + sizeof(mgreg_t) * 4;
408         regs_offset = ctx_offset + MONO_STRUCT_OFFSET (MonoContext, gregs);
409
410         /* Save registers */
411         for (i = 0; i < AMD64_NREG; ++i)
412                 if (i != AMD64_RSP)
413                         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
414         /* Save RSP */
415         amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, stack_size + sizeof(mgreg_t));
416         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RSP * sizeof(mgreg_t)), X86_EAX, sizeof(mgreg_t));
417         /* Save IP */
418         if (llvm_abs)
419                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
420         else
421                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, stack_size, sizeof(mgreg_t));
422         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RIP * sizeof(mgreg_t)), AMD64_RAX, sizeof(mgreg_t));
423         /* Set arg1 == ctx */
424         amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, ctx_offset);
425         amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [0], AMD64_RAX, sizeof(mgreg_t));
426         /* Set arg2 == exc/ex_token_index */
427         if (resume_unwind)
428                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [1], 0, sizeof(mgreg_t));
429         else
430                 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [1], AMD64_ARG_REG1, sizeof(mgreg_t));
431         /* Set arg3 == rethrow/pc offset */
432         if (resume_unwind) {
433                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], 0, sizeof(mgreg_t));
434         } else if (corlib) {
435                 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [2], AMD64_ARG_REG2, sizeof(mgreg_t));
436                 if (llvm_abs)
437                         /* 
438                          * The caller is LLVM code which passes the absolute address not a pc offset,
439                          * so compensate by passing 0 as 'rip' and passing the negated abs address as
440                          * the pc offset.
441                          */
442                         amd64_neg_membase (code, AMD64_RSP, arg_offsets [2]);
443         } else {
444                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], rethrow, sizeof(mgreg_t));
445         }
446
447         if (aot) {
448                 const char *icall_name;
449
450                 if (resume_unwind)
451                         icall_name = "mono_amd64_resume_unwind";
452                 else if (corlib)
453                         icall_name = "mono_amd64_throw_corlib_exception";
454                 else
455                         icall_name = "mono_amd64_throw_exception";
456                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
457                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
458         } else {
459                 amd64_mov_reg_imm (code, AMD64_R11, resume_unwind ? ((gpointer)mono_amd64_resume_unwind) : (corlib ? (gpointer)mono_amd64_throw_corlib_exception : (gpointer)mono_amd64_throw_exception));
460         }
461         amd64_call_reg (code, AMD64_R11);
462         amd64_breakpoint (code);
463
464         mono_arch_flush_icache (start, code - start);
465
466         g_assert ((code - start) < kMaxCodeSize);
467
468         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
469         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
470
471         if (info)
472                 *info = mono_tramp_info_create (tramp_name, start, code - start, ji, unwind_ops);
473
474         return start;
475 }
476
477 /**
478  * mono_arch_get_throw_exception:
479  *
480  * Returns a function pointer which can be used to raise 
481  * exceptions. The returned function has the following 
482  * signature: void (*func) (MonoException *exc); 
483  *
484  */
485 gpointer
486 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
487 {
488         return get_throw_trampoline (info, FALSE, FALSE, FALSE, FALSE, "throw_exception", aot);
489 }
490
491 gpointer 
492 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
493 {
494         return get_throw_trampoline (info, TRUE, FALSE, FALSE, FALSE, "rethrow_exception", aot);
495 }
496
497 /**
498  * mono_arch_get_throw_corlib_exception:
499  *
500  * Returns a function pointer which can be used to raise 
501  * corlib exceptions. The returned function has the following 
502  * signature: void (*func) (guint32 ex_token, guint32 offset); 
503  * Here, offset is the offset which needs to be substracted from the caller IP 
504  * to get the IP of the throw. Passing the offset has the advantage that it 
505  * needs no relocations in the caller.
506  */
507 gpointer 
508 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
509 {
510         return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
511 }
512
513 /*
514  * mono_arch_find_jit_info:
515  *
516  * This function is used to gather information from @ctx, and store it in @frame_info.
517  * It unwinds one stack frame, and stores the resulting context into @new_ctx. @lmf
518  * is modified if needed.
519  * Returns TRUE on success, FALSE otherwise.
520  */
521 gboolean
522 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, 
523                                                          MonoJitInfo *ji, MonoContext *ctx, 
524                                                          MonoContext *new_ctx, MonoLMF **lmf,
525                                                          mgreg_t **save_locations,
526                                                          StackFrameInfo *frame)
527 {
528         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
529         int i;
530
531         memset (frame, 0, sizeof (StackFrameInfo));
532         frame->ji = ji;
533
534         *new_ctx = *ctx;
535
536         if (ji != NULL) {
537                 mgreg_t regs [MONO_MAX_IREGS + 1];
538                 guint8 *cfa;
539                 guint32 unwind_info_len;
540                 guint8 *unwind_info;
541                 guint8 *epilog = NULL;
542
543                 frame->type = FRAME_TYPE_MANAGED;
544
545                 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
546
547                 frame->unwind_info = unwind_info;
548                 frame->unwind_info_len = unwind_info_len;
549
550                 /*
551                 printf ("%s %p %p\n", ji->d.method->name, ji->code_start, ip);
552                 mono_print_unwind_info (unwind_info, unwind_info_len);
553                 */
554                 /* LLVM compiled code doesn't have this info */
555                 if (ji->has_arch_eh_info)
556                         epilog = (guint8*)ji->code_start + ji->code_size - mono_jinfo_get_epilog_size (ji);
557  
558                 for (i = 0; i < AMD64_NREG; ++i)
559                         regs [i] = new_ctx->gregs [i];
560
561                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
562                                                    (guint8*)ji->code_start + ji->code_size,
563                                                    ip, epilog ? &epilog : NULL, regs, MONO_MAX_IREGS + 1,
564                                                    save_locations, MONO_MAX_IREGS, &cfa);
565
566                 for (i = 0; i < AMD64_NREG; ++i)
567                         new_ctx->gregs [i] = regs [i];
568  
569                 /* The CFA becomes the new SP value */
570                 new_ctx->gregs [AMD64_RSP] = (mgreg_t)cfa;
571
572                 /* Adjust IP */
573                 new_ctx->gregs [AMD64_RIP] --;
574
575                 return TRUE;
576         } else if (*lmf) {
577                 guint64 rip;
578
579                 if (((guint64)(*lmf)->previous_lmf) & 2) {
580                         /* 
581                          * This LMF entry is created by the soft debug code to mark transitions to
582                          * managed code done during invokes.
583                          */
584                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
585
586                         g_assert (ext->debugger_invoke);
587
588                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
589
590                         *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~7);
591
592                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
593
594                         return TRUE;
595                 }
596
597                 if (((guint64)(*lmf)->previous_lmf) & 4) {
598                         MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
599
600                         rip = (guint64)MONO_CONTEXT_GET_IP (ext->ctx);
601                 } else if (((guint64)(*lmf)->previous_lmf) & 1) {
602                         /* This LMF has the rip field set */
603                         rip = (*lmf)->rip;
604                 } else if ((*lmf)->rsp == 0) {
605                         /* Top LMF entry */
606                         return FALSE;
607                 } else {
608                         /* 
609                          * The rsp field is set just before the call which transitioned to native 
610                          * code. Obtain the rip from the stack.
611                          */
612                         rip = *(guint64*)((*lmf)->rsp - sizeof(mgreg_t));
613                 }
614
615                 ji = mini_jit_info_table_find (domain, (gpointer)rip, NULL);
616                 /*
617                  * FIXME: ji == NULL can happen when a managed-to-native wrapper is interrupted
618                  * in the soft debugger suspend code, since (*lmf)->rsp no longer points to the
619                  * return address.
620                  */
621                 //g_assert (ji);
622                 if (!ji)
623                         return FALSE;
624
625                 frame->ji = ji;
626                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
627
628                 if (((guint64)(*lmf)->previous_lmf) & 4) {
629                         MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
630
631                         /* Trampoline frame */
632                         for (i = 0; i < AMD64_NREG; ++i)
633                                 new_ctx->gregs [i] = ext->ctx->gregs [i];
634                         /* Adjust IP */
635                         new_ctx->gregs [AMD64_RIP] --;
636                 } else {
637                         /*
638                          * The registers saved in the LMF will be restored using the normal unwind info,
639                          * when the wrapper frame is processed.
640                          */
641                         /* Adjust IP */
642                         rip --;
643                         new_ctx->gregs [AMD64_RIP] = rip;
644                         new_ctx->gregs [AMD64_RSP] = (*lmf)->rsp;
645                         new_ctx->gregs [AMD64_RBP] = (*lmf)->rbp;
646                         for (i = 0; i < AMD64_NREG; ++i) {
647                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && i != AMD64_RBP)
648                                         new_ctx->gregs [i] = 0;
649                         }
650                 }
651
652                 *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~7);
653
654                 return TRUE;
655         }
656
657         return FALSE;
658 }
659
660 /*
661  * handle_exception:
662  *
663  *   Called by resuming from a signal handler.
664  */
665 static void
666 handle_signal_exception (gpointer obj)
667 {
668         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
669         MonoContext ctx;
670
671         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
672
673         mono_handle_exception (&ctx, obj);
674
675         mono_restore_context (&ctx);
676 }
677
678 void
679 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
680 {
681         guint64 sp = ctx->gregs [AMD64_RSP];
682
683         ctx->gregs [AMD64_RDI] = (guint64)user_data;
684
685         /* Allocate a stack frame below the red zone */
686         sp -= 128;
687         /* The stack should be unaligned */
688         if ((sp % 16) == 0)
689                 sp -= 8;
690 #ifdef __linux__
691         /* Preserve the call chain to prevent crashes in the libgcc unwinder (#15969) */
692         *(guint64*)sp = ctx->gregs [AMD64_RIP];
693 #endif
694         ctx->gregs [AMD64_RSP] = sp;
695         ctx->gregs [AMD64_RIP] = (guint64)async_cb;
696 }
697
698 /**
699  * mono_arch_handle_exception:
700  *
701  * @ctx: saved processor state
702  * @obj: the exception object
703  */
704 gboolean
705 mono_arch_handle_exception (void *sigctx, gpointer obj)
706 {
707 #if defined(MONO_ARCH_USE_SIGACTION)
708         MonoContext mctx;
709
710         /*
711          * Handling the exception in the signal handler is problematic, since the original
712          * signal is disabled, and we could run arbitrary code though the debugger. So
713          * resume into the normal stack and do most work there if possible.
714          */
715         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
716
717         /* Pass the ctx parameter in TLS */
718         mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
719
720         mctx = jit_tls->ex_ctx;
721         mono_arch_setup_async_callback (&mctx, handle_signal_exception, obj);
722         mono_monoctx_to_sigctx (&mctx, sigctx);
723
724         return TRUE;
725 #else
726         MonoContext mctx;
727
728         mono_sigctx_to_monoctx (sigctx, &mctx);
729
730         mono_handle_exception (&mctx, obj);
731
732         mono_monoctx_to_sigctx (&mctx, sigctx);
733
734         return TRUE;
735 #endif
736 }
737
738 gpointer
739 mono_arch_ip_from_context (void *sigctx)
740 {
741 #if defined(MONO_ARCH_USE_SIGACTION)
742         ucontext_t *ctx = (ucontext_t*)sigctx;
743
744         return (gpointer)UCONTEXT_REG_RIP (ctx);
745 #elif defined(HOST_WIN32)
746         return ((CONTEXT*)sigctx)->Rip;
747 #else
748         MonoContext *ctx = sigctx;
749         return (gpointer)ctx->gregs [AMD64_RIP];
750 #endif  
751 }
752
753 static void
754 restore_soft_guard_pages (void)
755 {
756         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
757         if (jit_tls->stack_ovf_guard_base)
758                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
759 }
760
761 /* 
762  * this function modifies mctx so that when it is restored, it
763  * won't execcute starting at mctx.eip, but in a function that
764  * will restore the protection on the soft-guard pages and return back to
765  * continue at mctx.eip.
766  */
767 static void
768 prepare_for_guard_pages (MonoContext *mctx)
769 {
770         gpointer *sp;
771         sp = (gpointer)(mctx->gregs [AMD64_RSP]);
772         sp -= 1;
773         /* the return addr */
774         sp [0] = (gpointer)(mctx->gregs [AMD64_RIP]);
775         mctx->gregs [AMD64_RIP] = (guint64)restore_soft_guard_pages;
776         mctx->gregs [AMD64_RSP] = (guint64)sp;
777 }
778
779 static void
780 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
781 {
782         MonoContext mctx;
783
784         mctx = *ctx;
785
786         mono_handle_exception (&mctx, obj);
787         if (stack_ovf)
788                 prepare_for_guard_pages (&mctx);
789         mono_restore_context (&mctx);
790 }
791
792 void
793 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
794 {
795 #if defined(MONO_ARCH_USE_SIGACTION)
796         MonoException *exc = NULL;
797         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_RIP (sigctx), NULL);
798         gpointer *sp;
799         int frame_size;
800         MonoContext *copied_ctx;
801
802         if (stack_ovf)
803                 exc = mono_domain_get ()->stack_overflow_ex;
804         if (!ji)
805                 mono_handle_native_sigsegv (SIGSEGV, sigctx, siginfo);
806
807         /* setup a call frame on the real stack so that control is returned there
808          * and exception handling can continue.
809          * The frame looks like:
810          *   ucontext struct
811          *   ...
812          *   return ip
813          * 128 is the size of the red zone
814          */
815         frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4 + 128;
816         frame_size += 15;
817         frame_size &= ~15;
818         sp = (gpointer)(UCONTEXT_REG_RSP (sigctx) & ~15);
819         sp = (gpointer)((char*)sp - frame_size);
820         copied_ctx = (MonoContext*)(sp + 4);
821         /* the arguments must be aligned */
822         sp [-1] = (gpointer)UCONTEXT_REG_RIP (sigctx);
823         mono_sigctx_to_monoctx (sigctx, copied_ctx);
824         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
825         UCONTEXT_REG_RIP (sigctx) = (unsigned long)altstack_handle_and_restore;
826         UCONTEXT_REG_RSP (sigctx) = (unsigned long)(sp - 1);
827         UCONTEXT_REG_RDI (sigctx) = (unsigned long)(copied_ctx);
828         UCONTEXT_REG_RSI (sigctx) = (guint64)exc;
829         UCONTEXT_REG_RDX (sigctx) = stack_ovf;
830 #endif
831 }
832
833 guint64
834 mono_amd64_get_original_ip (void)
835 {
836         MonoLMF *lmf = mono_get_lmf ();
837
838         g_assert (lmf);
839
840         /* Reset the change to previous_lmf */
841         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf & ~1);
842
843         return lmf->rip;
844 }
845
846 GSList*
847 mono_amd64_get_exception_trampolines (gboolean aot)
848 {
849         MonoTrampInfo *info;
850         GSList *tramps = NULL;
851
852         /* LLVM needs different throw trampolines */
853         get_throw_trampoline (&info, FALSE, TRUE, FALSE, FALSE, "llvm_throw_corlib_exception_trampoline", aot);
854         tramps = g_slist_prepend (tramps, info);
855
856         get_throw_trampoline (&info, FALSE, TRUE, TRUE, FALSE, "llvm_throw_corlib_exception_abs_trampoline", aot);
857         tramps = g_slist_prepend (tramps, info);
858
859         get_throw_trampoline (&info, FALSE, TRUE, TRUE, TRUE, "llvm_resume_unwind_trampoline", aot);
860         tramps = g_slist_prepend (tramps, info);
861
862         return tramps;
863 }
864
865 void
866 mono_arch_exceptions_init (void)
867 {
868         GSList *tramps, *l;
869         gpointer tramp;
870
871         if (mono_aot_only) {
872                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_trampoline");
873                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
874                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_abs_trampoline");
875                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
876                 tramp = mono_aot_get_trampoline ("llvm_resume_unwind_trampoline");
877                 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
878         } else {
879                 /* Call this to avoid initialization races */
880                 tramps = mono_amd64_get_exception_trampolines (FALSE);
881                 for (l = tramps; l; l = l->next) {
882                         MonoTrampInfo *info = l->data;
883
884                         mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE);
885                         mono_tramp_info_register (info);
886                 }
887                 g_slist_free (tramps);
888         }
889 }
890
891 #ifdef TARGET_WIN32
892
893 /*
894  * The mono_arch_unwindinfo* methods are used to build and add
895  * function table info for each emitted method from mono.  On Winx64
896  * the seh handler will not be called if the mono methods are not
897  * added to the function table.  
898  *
899  * We should not need to add non-volatile register info to the 
900  * table since mono stores that info elsewhere. (Except for the register 
901  * used for the fp.)
902  */
903
904 #define MONO_MAX_UNWIND_CODES 22
905
906 typedef union _UNWIND_CODE {
907     struct {
908         guchar CodeOffset;
909         guchar UnwindOp : 4;
910         guchar OpInfo   : 4;
911     };
912     gushort FrameOffset;
913 } UNWIND_CODE, *PUNWIND_CODE;
914
915 typedef struct _UNWIND_INFO {
916         guchar Version       : 3;
917         guchar Flags         : 5;
918         guchar SizeOfProlog;
919         guchar CountOfCodes;
920         guchar FrameRegister : 4;
921         guchar FrameOffset   : 4;
922         /* custom size for mono allowing for mono allowing for*/
923         /*UWOP_PUSH_NONVOL ebp offset = 21*/
924         /*UWOP_ALLOC_LARGE : requires 2 or 3 offset = 20*/
925         /*UWOP_SET_FPREG : requires 2 offset = 17*/
926         /*UWOP_PUSH_NONVOL offset = 15-0*/
927         UNWIND_CODE UnwindCode[MONO_MAX_UNWIND_CODES]; 
928
929 /*      UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
930  *      union {
931  *          OPTIONAL ULONG ExceptionHandler;
932  *          OPTIONAL ULONG FunctionEntry;
933  *      };
934  *      OPTIONAL ULONG ExceptionData[]; */
935 } UNWIND_INFO, *PUNWIND_INFO;
936
937 typedef struct
938 {
939         RUNTIME_FUNCTION runtimeFunction;
940         UNWIND_INFO unwindInfo;
941 } MonoUnwindInfo, *PMonoUnwindInfo;
942
943 static void
944 mono_arch_unwindinfo_create (gpointer* monoui)
945 {
946         PMonoUnwindInfo newunwindinfo;
947         *monoui = newunwindinfo = g_new0 (MonoUnwindInfo, 1);
948         newunwindinfo->unwindInfo.Version = 1;
949 }
950
951 void
952 mono_arch_unwindinfo_add_push_nonvol (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
953 {
954         PMonoUnwindInfo unwindinfo;
955         PUNWIND_CODE unwindcode;
956         guchar codeindex;
957         if (!*monoui)
958                 mono_arch_unwindinfo_create (monoui);
959         
960         unwindinfo = (MonoUnwindInfo*)*monoui;
961
962         if (unwindinfo->unwindInfo.CountOfCodes >= MONO_MAX_UNWIND_CODES)
963                 g_error ("Larger allocation needed for the unwind information.");
964
965         codeindex = MONO_MAX_UNWIND_CODES - (++unwindinfo->unwindInfo.CountOfCodes);
966         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
967         unwindcode->UnwindOp = 0; /*UWOP_PUSH_NONVOL*/
968         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
969         unwindcode->OpInfo = reg;
970
971         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
972                 g_error ("Adding unwind info in wrong order.");
973         
974         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
975 }
976
977 void
978 mono_arch_unwindinfo_add_set_fpreg (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
979 {
980         PMonoUnwindInfo unwindinfo;
981         PUNWIND_CODE unwindcode;
982         guchar codeindex;
983         if (!*monoui)
984                 mono_arch_unwindinfo_create (monoui);
985         
986         unwindinfo = (MonoUnwindInfo*)*monoui;
987
988         if (unwindinfo->unwindInfo.CountOfCodes + 1 >= MONO_MAX_UNWIND_CODES)
989                 g_error ("Larger allocation needed for the unwind information.");
990
991         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += 2);
992         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
993         unwindcode->FrameOffset = 0; /*Assuming no frame pointer offset for mono*/
994         unwindcode++;
995         unwindcode->UnwindOp = 3; /*UWOP_SET_FPREG*/
996         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
997         unwindcode->OpInfo = reg;
998         
999         unwindinfo->unwindInfo.FrameRegister = reg;
1000
1001         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1002                 g_error ("Adding unwind info in wrong order.");
1003         
1004         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1005 }
1006
1007 void
1008 mono_arch_unwindinfo_add_alloc_stack (gpointer* monoui, gpointer codebegin, gpointer nextip, guint size )
1009 {
1010         PMonoUnwindInfo unwindinfo;
1011         PUNWIND_CODE unwindcode;
1012         guchar codeindex;
1013         guchar codesneeded;
1014         if (!*monoui)
1015                 mono_arch_unwindinfo_create (monoui);
1016         
1017         unwindinfo = (MonoUnwindInfo*)*monoui;
1018
1019         if (size < 0x8)
1020                 g_error ("Stack allocation must be equal to or greater than 0x8.");
1021         
1022         if (size <= 0x80)
1023                 codesneeded = 1;
1024         else if (size <= 0x7FFF8)
1025                 codesneeded = 2;
1026         else
1027                 codesneeded = 3;
1028         
1029         if (unwindinfo->unwindInfo.CountOfCodes + codesneeded > MONO_MAX_UNWIND_CODES)
1030                 g_error ("Larger allocation needed for the unwind information.");
1031
1032         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += codesneeded);
1033         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1034
1035         if (codesneeded == 1) {
1036                 /*The size of the allocation is 
1037                   (the number in the OpInfo member) times 8 plus 8*/
1038                 unwindcode->OpInfo = (size - 8)/8;
1039                 unwindcode->UnwindOp = 2; /*UWOP_ALLOC_SMALL*/
1040         }
1041         else {
1042                 if (codesneeded == 3) {
1043                         /*the unscaled size of the allocation is recorded
1044                           in the next two slots in little-endian format*/
1045                         *((unsigned int*)(&unwindcode->FrameOffset)) = size;
1046                         unwindcode += 2;
1047                         unwindcode->OpInfo = 1;
1048                 }
1049                 else {
1050                         /*the size of the allocation divided by 8
1051                           is recorded in the next slot*/
1052                         unwindcode->FrameOffset = size/8; 
1053                         unwindcode++;   
1054                         unwindcode->OpInfo = 0;
1055                         
1056                 }
1057                 unwindcode->UnwindOp = 1; /*UWOP_ALLOC_LARGE*/
1058         }
1059
1060         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1061
1062         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1063                 g_error ("Adding unwind info in wrong order.");
1064         
1065         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1066 }
1067
1068 guint
1069 mono_arch_unwindinfo_get_size (gpointer monoui)
1070 {
1071         PMonoUnwindInfo unwindinfo;
1072         if (!monoui)
1073                 return 0;
1074         
1075         unwindinfo = (MonoUnwindInfo*)monoui;
1076         return (8 + sizeof (MonoUnwindInfo)) - 
1077                 (sizeof (UNWIND_CODE) * (MONO_MAX_UNWIND_CODES - unwindinfo->unwindInfo.CountOfCodes));
1078 }
1079
1080 static PRUNTIME_FUNCTION
1081 MONO_GET_RUNTIME_FUNCTION_CALLBACK ( DWORD64 ControlPc, IN PVOID Context )
1082 {
1083         MonoJitInfo *ji;
1084         guint64 pos;
1085         PMonoUnwindInfo targetinfo;
1086         MonoDomain *domain = mono_domain_get ();
1087
1088         ji = mini_jit_info_table_find (domain, (char*)ControlPc, NULL);
1089         if (!ji)
1090                 return 0;
1091
1092         pos = (guint64)(((char*)ji->code_start) + ji->code_size);
1093         
1094         targetinfo = (PMonoUnwindInfo)ALIGN_TO (pos, 8);
1095
1096         targetinfo->runtimeFunction.UnwindData = ((DWORD64)&targetinfo->unwindInfo) - ((DWORD64)Context);
1097
1098         return &targetinfo->runtimeFunction;
1099 }
1100
1101 void
1102 mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint code_size)
1103 {
1104         PMonoUnwindInfo unwindinfo, targetinfo;
1105         guchar codecount;
1106         guint64 targetlocation;
1107         if (!*monoui)
1108                 return;
1109
1110         unwindinfo = (MonoUnwindInfo*)*monoui;
1111         targetlocation = (guint64)&(((guchar*)code)[code_size]);
1112         targetinfo = (PMonoUnwindInfo) ALIGN_TO(targetlocation, 8);
1113
1114         unwindinfo->runtimeFunction.EndAddress = code_size;
1115         unwindinfo->runtimeFunction.UnwindData = ((guchar*)&targetinfo->unwindInfo) - ((guchar*)code);
1116         
1117         memcpy (targetinfo, unwindinfo, sizeof (MonoUnwindInfo) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
1118         
1119         codecount = unwindinfo->unwindInfo.CountOfCodes;
1120         if (codecount) {
1121                 memcpy (&targetinfo->unwindInfo.UnwindCode[0], &unwindinfo->unwindInfo.UnwindCode[MONO_MAX_UNWIND_CODES-codecount], 
1122                         sizeof (UNWIND_CODE) * unwindinfo->unwindInfo.CountOfCodes);
1123         }
1124
1125         g_free (unwindinfo);
1126         *monoui = 0;
1127
1128         RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
1129 }
1130
1131 #endif
1132
1133 #if MONO_SUPPORT_TASKLETS
1134 MonoContinuationRestore
1135 mono_tasklets_arch_restore (void)
1136 {
1137         static guint8* saved = NULL;
1138         guint8 *code, *start;
1139         int cont_reg = AMD64_R9; /* register usable on both call conventions */
1140         const guint kMaxCodeSize = NACL_SIZE (64, 128);
1141         
1142
1143         if (saved)
1144                 return (MonoContinuationRestore)saved;
1145         code = start = mono_global_codeman_reserve (kMaxCodeSize);
1146         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1147         /* cont is in AMD64_ARG_REG1 ($rcx or $rdi)
1148          * state is in AMD64_ARG_REG2 ($rdx or $rsi)
1149          * lmf_addr is in AMD64_ARG_REG3 ($r8 or $rdx)
1150          * We move cont to cont_reg since we need both rcx and rdi for the copy
1151          * state is moved to $rax so it's setup as the return value and we can overwrite $rsi
1152          */
1153         amd64_mov_reg_reg (code, cont_reg, MONO_AMD64_ARG_REG1, 8);
1154         amd64_mov_reg_reg (code, AMD64_RAX, MONO_AMD64_ARG_REG2, 8);
1155         /* setup the copy of the stack */
1156         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), sizeof (int));
1157         amd64_shift_reg_imm (code, X86_SHR, AMD64_RCX, 3);
1158         x86_cld (code);
1159         amd64_mov_reg_membase (code, AMD64_RSI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), sizeof (gpointer));
1160         amd64_mov_reg_membase (code, AMD64_RDI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), sizeof (gpointer));
1161         amd64_prefix (code, X86_REP_PREFIX);
1162         amd64_movsl (code);
1163
1164         /* now restore the registers from the LMF */
1165         NOT_IMPLEMENTED;
1166         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 8);
1167         amd64_mov_reg_membase (code, AMD64_RSP, AMD64_RCX, MONO_STRUCT_OFFSET (MonoLMF, rsp), 8);
1168
1169         /* restore the lmf chain */
1170         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1171         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1172
1173         /* state is already in rax */
1174         amd64_jump_membase (code, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1175         g_assert ((code - start) <= kMaxCodeSize);
1176
1177         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1178         mono_arch_flush_icache (start, code - start);
1179         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL);
1180
1181         saved = start;
1182         return (MonoContinuationRestore)saved;
1183 }
1184 #endif
1185
1186 /*
1187  * mono_arch_setup_resume_sighandler_ctx:
1188  *
1189  *   Setup CTX so execution continues at FUNC.
1190  */
1191 void
1192 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1193 {
1194         /* 
1195          * When resuming from a signal handler, the stack should be misaligned, just like right after
1196          * a call.
1197          */
1198         if ((((guint64)MONO_CONTEXT_GET_SP (ctx)) % 16) == 0)
1199                 MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
1200         MONO_CONTEXT_SET_IP (ctx, func);
1201 }