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