Merge pull request #944 from ermshiperete/bug-novell-496138
[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 = NULL;
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                 /* LLVM compiled code doesn't have this info */
569                 if (ji->has_arch_eh_info)
570                         epilog = (guint8*)ji->code_start + ji->code_size - mono_jinfo_get_epilog_size (ji);
571  
572                 regs [AMD64_RAX] = new_ctx->rax;
573                 regs [AMD64_RBX] = new_ctx->rbx;
574                 regs [AMD64_RCX] = new_ctx->rcx;
575                 regs [AMD64_RDX] = new_ctx->rdx;
576                 regs [AMD64_RBP] = new_ctx->rbp;
577                 regs [AMD64_RSP] = new_ctx->rsp;
578                 regs [AMD64_RSI] = new_ctx->rsi;
579                 regs [AMD64_RDI] = new_ctx->rdi;
580                 regs [AMD64_RIP] = new_ctx->rip;
581                 regs [AMD64_R12] = new_ctx->r12;
582                 regs [AMD64_R13] = new_ctx->r13;
583                 regs [AMD64_R14] = new_ctx->r14;
584                 regs [AMD64_R15] = new_ctx->r15;
585
586                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
587                                                    (guint8*)ji->code_start + ji->code_size,
588                                                    ip, epilog ? &epilog : NULL, regs, MONO_MAX_IREGS + 1,
589                                                    save_locations, MONO_MAX_IREGS, &cfa);
590
591                 new_ctx->rax = regs [AMD64_RAX];
592                 new_ctx->rbx = regs [AMD64_RBX];
593                 new_ctx->rcx = regs [AMD64_RCX];
594                 new_ctx->rdx = regs [AMD64_RDX];
595                 new_ctx->rbp = regs [AMD64_RBP];
596                 new_ctx->rsp = regs [AMD64_RSP];
597                 new_ctx->rsi = regs [AMD64_RSI];
598                 new_ctx->rdi = regs [AMD64_RDI];
599                 new_ctx->rip = regs [AMD64_RIP];
600                 new_ctx->r12 = regs [AMD64_R12];
601                 new_ctx->r13 = regs [AMD64_R13];
602                 new_ctx->r14 = regs [AMD64_R14];
603                 new_ctx->r15 = regs [AMD64_R15];
604  
605                 /* The CFA becomes the new SP value */
606                 new_ctx->rsp = (mgreg_t)cfa;
607
608                 /* Adjust IP */
609                 new_ctx->rip --;
610
611                 return TRUE;
612         } else if (*lmf) {
613                 guint64 rip;
614
615                 if (((guint64)(*lmf)->previous_lmf) & 2) {
616                         /* 
617                          * This LMF entry is created by the soft debug code to mark transitions to
618                          * managed code done during invokes.
619                          */
620                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
621
622                         g_assert (ext->debugger_invoke);
623
624                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
625
626                         *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~7);
627
628                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
629
630                         return TRUE;
631                 }
632
633                 if (((guint64)(*lmf)->previous_lmf) & 1) {
634                         /* This LMF has the rip field set */
635                         rip = (*lmf)->rip;
636                 } else if ((*lmf)->rsp == 0) {
637                         /* Top LMF entry */
638                         return FALSE;
639                 } else {
640                         /* 
641                          * The rsp field is set just before the call which transitioned to native 
642                          * code. Obtain the rip from the stack.
643                          */
644                         rip = *(guint64*)((*lmf)->rsp - sizeof(mgreg_t));
645                 }
646
647                 ji = mini_jit_info_table_find (domain, (gpointer)rip, NULL);
648                 /*
649                  * FIXME: ji == NULL can happen when a managed-to-native wrapper is interrupted
650                  * in the soft debugger suspend code, since (*lmf)->rsp no longer points to the
651                  * return address.
652                  */
653                 //g_assert (ji);
654                 if (!ji)
655                         return FALSE;
656
657                 /* Adjust IP */
658                 rip --;
659
660                 frame->ji = ji;
661                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
662
663                 new_ctx->rip = rip;
664                 new_ctx->rbp = (*lmf)->rbp;
665                 new_ctx->rsp = (*lmf)->rsp;
666
667                 if (((guint64)(*lmf)->previous_lmf) & 4) {
668                         MonoLMFTramp *ext = (MonoLMFTramp*)(*lmf);
669
670                         /* Trampoline frame */
671                         new_ctx->rbx = ext->regs [AMD64_RBX];
672                         new_ctx->r12 = ext->regs [AMD64_R12];
673                         new_ctx->r13 = ext->regs [AMD64_R13];
674                         new_ctx->r14 = ext->regs [AMD64_R14];
675                         new_ctx->r15 = ext->regs [AMD64_R15];
676 #ifdef TARGET_WIN32
677                         new_ctx->rdi = ext->regs [AMD64_RDI];
678                         new_ctx->rsi = ext->regs [AMD64_RSI];
679 #endif
680                 } else {
681                         /*
682                          * The registers saved in the LMF will be restored using the normal unwind info,
683                          * when the wrapper frame is processed.
684                          */
685                         new_ctx->rbx = 0;
686                         new_ctx->r12 = 0;
687                         new_ctx->r13 = 0;
688                         new_ctx->r14 = 0;
689                         new_ctx->r15 = 0;
690 #ifdef TARGET_WIN32
691                         new_ctx->rdi = 0;
692                         new_ctx->rsi = 0;
693 #endif
694                 }
695
696                 *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~7);
697
698                 return TRUE;
699         }
700
701         return FALSE;
702 }
703
704 /*
705  * handle_exception:
706  *
707  *   Called by resuming from a signal handler.
708  */
709 static void
710 handle_signal_exception (gpointer obj)
711 {
712         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
713         MonoContext ctx;
714
715         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
716
717         mono_handle_exception (&ctx, obj);
718
719         mono_restore_context (&ctx);
720 }
721
722 void
723 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
724 {
725         guint64 sp = ctx->rsp;
726
727         ctx->rdi = (guint64)user_data;
728
729         /* Allocate a stack frame below the red zone */
730         sp -= 128;
731         /* The stack should be unaligned */
732         if ((sp % 16) == 0)
733                 sp -= 8;
734 #ifdef __linux__
735         /* Preserve the call chain to prevent crashes in the libgcc unwinder (#15969) */
736         *(guint64*)sp = ctx->rip;
737 #endif
738         ctx->rsp = sp;
739         ctx->rip = (guint64)async_cb;
740 }
741
742 /**
743  * mono_arch_handle_exception:
744  *
745  * @ctx: saved processor state
746  * @obj: the exception object
747  */
748 gboolean
749 mono_arch_handle_exception (void *sigctx, gpointer obj)
750 {
751 #if defined(MONO_ARCH_USE_SIGACTION)
752         MonoContext mctx;
753
754         /*
755          * Handling the exception in the signal handler is problematic, since the original
756          * signal is disabled, and we could run arbitrary code though the debugger. So
757          * resume into the normal stack and do most work there if possible.
758          */
759         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
760
761         /* Pass the ctx parameter in TLS */
762         mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
763
764         mctx = jit_tls->ex_ctx;
765         mono_arch_setup_async_callback (&mctx, handle_signal_exception, obj);
766         mono_monoctx_to_sigctx (&mctx, sigctx);
767
768         return TRUE;
769 #else
770         MonoContext mctx;
771
772         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
773
774         mono_handle_exception (&mctx, obj);
775
776         mono_arch_monoctx_to_sigctx (&mctx, sigctx);
777
778         return TRUE;
779 #endif
780 }
781
782 void
783 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
784 {
785         mono_sigctx_to_monoctx (sigctx, mctx);
786 }
787
788 void
789 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
790 {
791         mono_monoctx_to_sigctx (mctx, sigctx);
792 }
793
794 gpointer
795 mono_arch_ip_from_context (void *sigctx)
796 {
797 #if defined(MONO_ARCH_USE_SIGACTION)
798         ucontext_t *ctx = (ucontext_t*)sigctx;
799
800         return (gpointer)UCONTEXT_REG_RIP (ctx);
801 #elif defined(HOST_WIN32)
802         return ((CONTEXT*)sigctx)->Rip;
803 #else
804         MonoContext *ctx = sigctx;
805         return (gpointer)ctx->rip;
806 #endif  
807 }
808
809 static void
810 restore_soft_guard_pages (void)
811 {
812         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
813         if (jit_tls->stack_ovf_guard_base)
814                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
815 }
816
817 /* 
818  * this function modifies mctx so that when it is restored, it
819  * won't execcute starting at mctx.eip, but in a function that
820  * will restore the protection on the soft-guard pages and return back to
821  * continue at mctx.eip.
822  */
823 static void
824 prepare_for_guard_pages (MonoContext *mctx)
825 {
826         gpointer *sp;
827         sp = (gpointer)(mctx->rsp);
828         sp -= 1;
829         /* the return addr */
830         sp [0] = (gpointer)(mctx->rip);
831         mctx->rip = (guint64)restore_soft_guard_pages;
832         mctx->rsp = (guint64)sp;
833 }
834
835 static void
836 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
837 {
838         MonoContext mctx;
839
840         mctx = *ctx;
841
842         mono_handle_exception (&mctx, obj);
843         if (stack_ovf)
844                 prepare_for_guard_pages (&mctx);
845         mono_restore_context (&mctx);
846 }
847
848 void
849 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
850 {
851 #if defined(MONO_ARCH_USE_SIGACTION)
852         MonoException *exc = NULL;
853         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_RIP (sigctx), NULL);
854         gpointer *sp;
855         int frame_size;
856         MonoContext *copied_ctx;
857
858         if (stack_ovf)
859                 exc = mono_domain_get ()->stack_overflow_ex;
860         if (!ji)
861                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
862
863         /* setup a call frame on the real stack so that control is returned there
864          * and exception handling can continue.
865          * The frame looks like:
866          *   ucontext struct
867          *   ...
868          *   return ip
869          * 128 is the size of the red zone
870          */
871         frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4 + 128;
872         frame_size += 15;
873         frame_size &= ~15;
874         sp = (gpointer)(UCONTEXT_REG_RSP (sigctx) & ~15);
875         sp = (gpointer)((char*)sp - frame_size);
876         copied_ctx = (MonoContext*)(sp + 4);
877         /* the arguments must be aligned */
878         sp [-1] = (gpointer)UCONTEXT_REG_RIP (sigctx);
879         mono_sigctx_to_monoctx (sigctx, copied_ctx);
880         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
881         UCONTEXT_REG_RIP (sigctx) = (unsigned long)altstack_handle_and_restore;
882         UCONTEXT_REG_RSP (sigctx) = (unsigned long)(sp - 1);
883         UCONTEXT_REG_RDI (sigctx) = (unsigned long)(copied_ctx);
884         UCONTEXT_REG_RSI (sigctx) = (guint64)exc;
885         UCONTEXT_REG_RDX (sigctx) = stack_ovf;
886 #endif
887 }
888
889 guint64
890 mono_amd64_get_original_ip (void)
891 {
892         MonoLMF *lmf = mono_get_lmf ();
893
894         g_assert (lmf);
895
896         /* Reset the change to previous_lmf */
897         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf & ~1);
898
899         return lmf->rip;
900 }
901
902 gpointer
903 mono_arch_get_throw_pending_exception (MonoTrampInfo **info, gboolean aot)
904 {
905         guint8 *code, *start;
906         guint8 *br[1];
907         gpointer throw_trampoline;
908         MonoJumpInfo *ji = NULL;
909         GSList *unwind_ops = NULL;
910         const guint kMaxCodeSize = NACL_SIZE (128, 256);
911
912         start = code = mono_global_codeman_reserve (kMaxCodeSize);
913
914         /* We are in the frame of a managed method after a call */
915         /* 
916          * We would like to throw the pending exception in such a way that it looks to
917          * be thrown from the managed method.
918          */
919
920         /* Save registers which might contain the return value of the call */
921         amd64_push_reg (code, AMD64_RAX);
922         amd64_push_reg (code, AMD64_RDX);
923
924         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
925         amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
926
927         /* Align stack */
928         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
929
930         /* Obtain the pending exception */
931         if (aot) {
932                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_get_and_clear_pending_exception");
933                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
934         } else {
935                 amd64_mov_reg_imm (code, AMD64_R11, mono_thread_get_and_clear_pending_exception);
936         }
937         amd64_call_reg (code, AMD64_R11);
938
939         /* Check if it is NULL, and branch */
940         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
941         br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
942
943         /* exc != NULL branch */
944
945         /* Save the exc on the stack */
946         amd64_push_reg (code, AMD64_RAX);
947         /* Align stack */
948         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
949
950         /* Obtain the original ip and clear the flag in previous_lmf */
951         if (aot) {
952                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_get_original_ip");
953                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
954         } else {
955                 amd64_mov_reg_imm (code, AMD64_R11, mono_amd64_get_original_ip);
956         }
957         amd64_call_reg (code, AMD64_R11);       
958
959         /* Load exc */
960         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, 8, 8);
961
962         /* Pop saved stuff from the stack */
963         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 6 * 8);
964
965         /* Setup arguments for the throw trampoline */
966         /* Exception */
967         amd64_mov_reg_reg (code, AMD64_ARG_REG1, AMD64_R11, 8);
968         /* The trampoline expects the caller ip to be pushed on the stack */
969         amd64_push_reg (code, AMD64_RAX);
970
971         /* Call the throw trampoline */
972         if (aot) {
973                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_throw_exception");
974                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
975         } else {
976                 throw_trampoline = mono_get_throw_exception ();
977                 amd64_mov_reg_imm (code, AMD64_R11, throw_trampoline);
978         }
979         /* We use a jump instead of a call so we can push the original ip on the stack */
980         amd64_jump_reg (code, AMD64_R11);
981
982         /* ex == NULL branch */
983         mono_amd64_patch (br [0], code);
984
985         /* Obtain the original ip and clear the flag in previous_lmf */
986         if (aot) {
987                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_get_original_ip");
988                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
989         } else {
990                 amd64_mov_reg_imm (code, AMD64_R11, mono_amd64_get_original_ip);
991         }
992         amd64_call_reg (code, AMD64_R11);       
993         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
994
995         /* Restore registers */
996         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
997         amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
998         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
999         amd64_pop_reg (code, AMD64_RDX);
1000         amd64_pop_reg (code, AMD64_RAX);
1001
1002         /* Return to original code */
1003         amd64_jump_reg (code, AMD64_R11);
1004
1005         g_assert ((code - start) < kMaxCodeSize);
1006
1007         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1008
1009         if (info)
1010                 *info = mono_tramp_info_create ("throw_pending_exception", start, code - start, ji, unwind_ops);
1011
1012         return start;
1013 }
1014
1015 static gpointer throw_pending_exception;
1016
1017 /*
1018  * Called when a thread receives an async exception while executing unmanaged code.
1019  * Instead of checking for this exception in the managed-to-native wrapper, we hijack 
1020  * the return address on the stack to point to a helper routine which throws the
1021  * exception.
1022  */
1023 void
1024 mono_arch_notify_pending_exc (MonoThreadInfo *info)
1025 {
1026         MonoLMF *lmf = mono_get_lmf ();
1027
1028         if (!info) {
1029                 lmf = mono_get_lmf ();
1030         } else {
1031                 g_assert (info->suspend_state.valid);
1032                 lmf = info->suspend_state.unwind_data [MONO_UNWIND_DATA_LMF];
1033         }
1034
1035         if (!lmf)
1036                 /* Not yet started */
1037                 return;
1038
1039         if (lmf->rsp == 0)
1040                 /* Initial LMF */
1041                 return;
1042
1043         if ((guint64)lmf->previous_lmf & 1)
1044                 /* Already hijacked or trampoline LMF entry */
1045                 return;
1046
1047         /* lmf->rsp is set just before making the call which transitions to unmanaged code */
1048         lmf->rip = *(guint64*)(lmf->rsp - 8);
1049         /* Signal that lmf->rip is set */
1050         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf | 1);
1051
1052         *(gpointer*)(lmf->rsp - 8) = throw_pending_exception;
1053 }
1054
1055 GSList*
1056 mono_amd64_get_exception_trampolines (gboolean aot)
1057 {
1058         MonoTrampInfo *info;
1059         GSList *tramps = NULL;
1060
1061         mono_arch_get_throw_pending_exception (&info, aot);
1062         tramps = g_slist_prepend (tramps, info);
1063
1064         /* LLVM needs different throw trampolines */
1065         get_throw_trampoline (&info, FALSE, TRUE, FALSE, FALSE, "llvm_throw_corlib_exception_trampoline", aot);
1066         tramps = g_slist_prepend (tramps, info);
1067
1068         get_throw_trampoline (&info, FALSE, TRUE, TRUE, FALSE, "llvm_throw_corlib_exception_abs_trampoline", aot);
1069         tramps = g_slist_prepend (tramps, info);
1070
1071         get_throw_trampoline (&info, FALSE, TRUE, TRUE, TRUE, "llvm_resume_unwind_trampoline", FALSE);
1072         tramps = g_slist_prepend (tramps, info);
1073
1074         return tramps;
1075 }
1076
1077 void
1078 mono_arch_exceptions_init (void)
1079 {
1080         GSList *tramps, *l;
1081         gpointer tramp;
1082
1083         if (mono_aot_only) {
1084                 throw_pending_exception = mono_aot_get_trampoline ("throw_pending_exception");
1085                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_trampoline");
1086                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
1087                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_abs_trampoline");
1088                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
1089                 tramp = mono_aot_get_trampoline ("llvm_resume_unwind_trampoline");
1090                 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
1091         } else {
1092                 /* Call this to avoid initialization races */
1093                 throw_pending_exception = mono_arch_get_throw_pending_exception (NULL, FALSE);
1094
1095                 tramps = mono_amd64_get_exception_trampolines (FALSE);
1096                 for (l = tramps; l; l = l->next) {
1097                         MonoTrampInfo *info = l->data;
1098
1099                         mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE);
1100                         mono_tramp_info_register (info);
1101                 }
1102                 g_slist_free (tramps);
1103         }
1104 }
1105
1106 #ifdef TARGET_WIN32
1107
1108 /*
1109  * The mono_arch_unwindinfo* methods are used to build and add
1110  * function table info for each emitted method from mono.  On Winx64
1111  * the seh handler will not be called if the mono methods are not
1112  * added to the function table.  
1113  *
1114  * We should not need to add non-volatile register info to the 
1115  * table since mono stores that info elsewhere. (Except for the register 
1116  * used for the fp.)
1117  */
1118
1119 #define MONO_MAX_UNWIND_CODES 22
1120
1121 typedef union _UNWIND_CODE {
1122     struct {
1123         guchar CodeOffset;
1124         guchar UnwindOp : 4;
1125         guchar OpInfo   : 4;
1126     };
1127     gushort FrameOffset;
1128 } UNWIND_CODE, *PUNWIND_CODE;
1129
1130 typedef struct _UNWIND_INFO {
1131         guchar Version       : 3;
1132         guchar Flags         : 5;
1133         guchar SizeOfProlog;
1134         guchar CountOfCodes;
1135         guchar FrameRegister : 4;
1136         guchar FrameOffset   : 4;
1137         /* custom size for mono allowing for mono allowing for*/
1138         /*UWOP_PUSH_NONVOL ebp offset = 21*/
1139         /*UWOP_ALLOC_LARGE : requires 2 or 3 offset = 20*/
1140         /*UWOP_SET_FPREG : requires 2 offset = 17*/
1141         /*UWOP_PUSH_NONVOL offset = 15-0*/
1142         UNWIND_CODE UnwindCode[MONO_MAX_UNWIND_CODES]; 
1143
1144 /*      UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
1145  *      union {
1146  *          OPTIONAL ULONG ExceptionHandler;
1147  *          OPTIONAL ULONG FunctionEntry;
1148  *      };
1149  *      OPTIONAL ULONG ExceptionData[]; */
1150 } UNWIND_INFO, *PUNWIND_INFO;
1151
1152 typedef struct
1153 {
1154         RUNTIME_FUNCTION runtimeFunction;
1155         UNWIND_INFO unwindInfo;
1156 } MonoUnwindInfo, *PMonoUnwindInfo;
1157
1158 static void
1159 mono_arch_unwindinfo_create (gpointer* monoui)
1160 {
1161         PMonoUnwindInfo newunwindinfo;
1162         *monoui = newunwindinfo = g_new0 (MonoUnwindInfo, 1);
1163         newunwindinfo->unwindInfo.Version = 1;
1164 }
1165
1166 void
1167 mono_arch_unwindinfo_add_push_nonvol (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
1168 {
1169         PMonoUnwindInfo unwindinfo;
1170         PUNWIND_CODE unwindcode;
1171         guchar codeindex;
1172         if (!*monoui)
1173                 mono_arch_unwindinfo_create (monoui);
1174         
1175         unwindinfo = (MonoUnwindInfo*)*monoui;
1176
1177         if (unwindinfo->unwindInfo.CountOfCodes >= MONO_MAX_UNWIND_CODES)
1178                 g_error ("Larger allocation needed for the unwind information.");
1179
1180         codeindex = MONO_MAX_UNWIND_CODES - (++unwindinfo->unwindInfo.CountOfCodes);
1181         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1182         unwindcode->UnwindOp = 0; /*UWOP_PUSH_NONVOL*/
1183         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1184         unwindcode->OpInfo = reg;
1185
1186         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1187                 g_error ("Adding unwind info in wrong order.");
1188         
1189         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1190 }
1191
1192 void
1193 mono_arch_unwindinfo_add_set_fpreg (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
1194 {
1195         PMonoUnwindInfo unwindinfo;
1196         PUNWIND_CODE unwindcode;
1197         guchar codeindex;
1198         if (!*monoui)
1199                 mono_arch_unwindinfo_create (monoui);
1200         
1201         unwindinfo = (MonoUnwindInfo*)*monoui;
1202
1203         if (unwindinfo->unwindInfo.CountOfCodes + 1 >= MONO_MAX_UNWIND_CODES)
1204                 g_error ("Larger allocation needed for the unwind information.");
1205
1206         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += 2);
1207         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1208         unwindcode->FrameOffset = 0; /*Assuming no frame pointer offset for mono*/
1209         unwindcode++;
1210         unwindcode->UnwindOp = 3; /*UWOP_SET_FPREG*/
1211         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1212         unwindcode->OpInfo = reg;
1213         
1214         unwindinfo->unwindInfo.FrameRegister = reg;
1215
1216         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1217                 g_error ("Adding unwind info in wrong order.");
1218         
1219         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1220 }
1221
1222 void
1223 mono_arch_unwindinfo_add_alloc_stack (gpointer* monoui, gpointer codebegin, gpointer nextip, guint size )
1224 {
1225         PMonoUnwindInfo unwindinfo;
1226         PUNWIND_CODE unwindcode;
1227         guchar codeindex;
1228         guchar codesneeded;
1229         if (!*monoui)
1230                 mono_arch_unwindinfo_create (monoui);
1231         
1232         unwindinfo = (MonoUnwindInfo*)*monoui;
1233
1234         if (size < 0x8)
1235                 g_error ("Stack allocation must be equal to or greater than 0x8.");
1236         
1237         if (size <= 0x80)
1238                 codesneeded = 1;
1239         else if (size <= 0x7FFF8)
1240                 codesneeded = 2;
1241         else
1242                 codesneeded = 3;
1243         
1244         if (unwindinfo->unwindInfo.CountOfCodes + codesneeded > MONO_MAX_UNWIND_CODES)
1245                 g_error ("Larger allocation needed for the unwind information.");
1246
1247         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += codesneeded);
1248         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1249
1250         if (codesneeded == 1) {
1251                 /*The size of the allocation is 
1252                   (the number in the OpInfo member) times 8 plus 8*/
1253                 unwindcode->OpInfo = (size - 8)/8;
1254                 unwindcode->UnwindOp = 2; /*UWOP_ALLOC_SMALL*/
1255         }
1256         else {
1257                 if (codesneeded == 3) {
1258                         /*the unscaled size of the allocation is recorded
1259                           in the next two slots in little-endian format*/
1260                         *((unsigned int*)(&unwindcode->FrameOffset)) = size;
1261                         unwindcode += 2;
1262                         unwindcode->OpInfo = 1;
1263                 }
1264                 else {
1265                         /*the size of the allocation divided by 8
1266                           is recorded in the next slot*/
1267                         unwindcode->FrameOffset = size/8; 
1268                         unwindcode++;   
1269                         unwindcode->OpInfo = 0;
1270                         
1271                 }
1272                 unwindcode->UnwindOp = 1; /*UWOP_ALLOC_LARGE*/
1273         }
1274
1275         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1276
1277         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1278                 g_error ("Adding unwind info in wrong order.");
1279         
1280         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1281 }
1282
1283 guint
1284 mono_arch_unwindinfo_get_size (gpointer monoui)
1285 {
1286         PMonoUnwindInfo unwindinfo;
1287         if (!monoui)
1288                 return 0;
1289         
1290         unwindinfo = (MonoUnwindInfo*)monoui;
1291         return (8 + sizeof (MonoUnwindInfo)) - 
1292                 (sizeof (UNWIND_CODE) * (MONO_MAX_UNWIND_CODES - unwindinfo->unwindInfo.CountOfCodes));
1293 }
1294
1295 static PRUNTIME_FUNCTION
1296 MONO_GET_RUNTIME_FUNCTION_CALLBACK ( DWORD64 ControlPc, IN PVOID Context )
1297 {
1298         MonoJitInfo *ji;
1299         guint64 pos;
1300         PMonoUnwindInfo targetinfo;
1301         MonoDomain *domain = mono_domain_get ();
1302
1303         ji = mini_jit_info_table_find (domain, (char*)ControlPc, NULL);
1304         if (!ji)
1305                 return 0;
1306
1307         pos = (guint64)(((char*)ji->code_start) + ji->code_size);
1308         
1309         targetinfo = (PMonoUnwindInfo)ALIGN_TO (pos, 8);
1310
1311         targetinfo->runtimeFunction.UnwindData = ((DWORD64)&targetinfo->unwindInfo) - ((DWORD64)Context);
1312
1313         return &targetinfo->runtimeFunction;
1314 }
1315
1316 void
1317 mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint code_size)
1318 {
1319         PMonoUnwindInfo unwindinfo, targetinfo;
1320         guchar codecount;
1321         guint64 targetlocation;
1322         if (!*monoui)
1323                 return;
1324
1325         unwindinfo = (MonoUnwindInfo*)*monoui;
1326         targetlocation = (guint64)&(((guchar*)code)[code_size]);
1327         targetinfo = (PMonoUnwindInfo) ALIGN_TO(targetlocation, 8);
1328
1329         unwindinfo->runtimeFunction.EndAddress = code_size;
1330         unwindinfo->runtimeFunction.UnwindData = ((guchar*)&targetinfo->unwindInfo) - ((guchar*)code);
1331         
1332         memcpy (targetinfo, unwindinfo, sizeof (MonoUnwindInfo) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
1333         
1334         codecount = unwindinfo->unwindInfo.CountOfCodes;
1335         if (codecount) {
1336                 memcpy (&targetinfo->unwindInfo.UnwindCode[0], &unwindinfo->unwindInfo.UnwindCode[MONO_MAX_UNWIND_CODES-codecount], 
1337                         sizeof (UNWIND_CODE) * unwindinfo->unwindInfo.CountOfCodes);
1338         }
1339
1340         g_free (unwindinfo);
1341         *monoui = 0;
1342
1343         RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
1344 }
1345
1346 #endif
1347
1348 #if MONO_SUPPORT_TASKLETS
1349 MonoContinuationRestore
1350 mono_tasklets_arch_restore (void)
1351 {
1352         static guint8* saved = NULL;
1353         guint8 *code, *start;
1354         int cont_reg = AMD64_R9; /* register usable on both call conventions */
1355         const guint kMaxCodeSize = NACL_SIZE (64, 128);
1356         
1357
1358         if (saved)
1359                 return (MonoContinuationRestore)saved;
1360         code = start = mono_global_codeman_reserve (kMaxCodeSize);
1361         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1362         /* cont is in AMD64_ARG_REG1 ($rcx or $rdi)
1363          * state is in AMD64_ARG_REG2 ($rdx or $rsi)
1364          * lmf_addr is in AMD64_ARG_REG3 ($r8 or $rdx)
1365          * We move cont to cont_reg since we need both rcx and rdi for the copy
1366          * state is moved to $rax so it's setup as the return value and we can overwrite $rsi
1367          */
1368         amd64_mov_reg_reg (code, cont_reg, MONO_AMD64_ARG_REG1, 8);
1369         amd64_mov_reg_reg (code, AMD64_RAX, MONO_AMD64_ARG_REG2, 8);
1370         /* setup the copy of the stack */
1371         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), sizeof (int));
1372         amd64_shift_reg_imm (code, X86_SHR, AMD64_RCX, 3);
1373         x86_cld (code);
1374         amd64_mov_reg_membase (code, AMD64_RSI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), sizeof (gpointer));
1375         amd64_mov_reg_membase (code, AMD64_RDI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), sizeof (gpointer));
1376         amd64_prefix (code, X86_REP_PREFIX);
1377         amd64_movsl (code);
1378
1379         /* now restore the registers from the LMF */
1380         NOT_IMPLEMENTED;
1381         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 8);
1382         amd64_mov_reg_membase (code, AMD64_RSP, AMD64_RCX, MONO_STRUCT_OFFSET (MonoLMF, rsp), 8);
1383
1384         /* restore the lmf chain */
1385         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1386         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1387
1388         /* state is already in rax */
1389         amd64_jump_membase (code, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1390         g_assert ((code - start) <= kMaxCodeSize);
1391
1392         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1393
1394         saved = start;
1395         return (MonoContinuationRestore)saved;
1396 }
1397 #endif
1398
1399 /*
1400  * mono_arch_setup_resume_sighandler_ctx:
1401  *
1402  *   Setup CTX so execution continues at FUNC.
1403  */
1404 void
1405 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1406 {
1407         /* 
1408          * When resuming from a signal handler, the stack should be misaligned, just like right after
1409          * a call.
1410          */
1411         if ((((guint64)MONO_CONTEXT_GET_SP (ctx)) % 16) == 0)
1412                 MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
1413         MONO_CONTEXT_SET_IP (ctx, func);
1414 }