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