Merge pull request #1349 from martinjt/MachineKeyProtect
[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_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_sigctx_to_monoctx (sigctx, &mctx);
773
774         mono_handle_exception (&mctx, obj);
775
776         mono_monoctx_to_sigctx (&mctx, sigctx);
777
778         return TRUE;
779 #endif
780 }
781
782 gpointer
783 mono_arch_ip_from_context (void *sigctx)
784 {
785 #if defined(MONO_ARCH_USE_SIGACTION)
786         ucontext_t *ctx = (ucontext_t*)sigctx;
787
788         return (gpointer)UCONTEXT_REG_RIP (ctx);
789 #elif defined(HOST_WIN32)
790         return ((CONTEXT*)sigctx)->Rip;
791 #else
792         MonoContext *ctx = sigctx;
793         return (gpointer)ctx->rip;
794 #endif  
795 }
796
797 static void
798 restore_soft_guard_pages (void)
799 {
800         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
801         if (jit_tls->stack_ovf_guard_base)
802                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
803 }
804
805 /* 
806  * this function modifies mctx so that when it is restored, it
807  * won't execcute starting at mctx.eip, but in a function that
808  * will restore the protection on the soft-guard pages and return back to
809  * continue at mctx.eip.
810  */
811 static void
812 prepare_for_guard_pages (MonoContext *mctx)
813 {
814         gpointer *sp;
815         sp = (gpointer)(mctx->rsp);
816         sp -= 1;
817         /* the return addr */
818         sp [0] = (gpointer)(mctx->rip);
819         mctx->rip = (guint64)restore_soft_guard_pages;
820         mctx->rsp = (guint64)sp;
821 }
822
823 static void
824 altstack_handle_and_restore (MonoContext *ctx, gpointer obj, gboolean stack_ovf)
825 {
826         MonoContext mctx;
827
828         mctx = *ctx;
829
830         mono_handle_exception (&mctx, obj);
831         if (stack_ovf)
832                 prepare_for_guard_pages (&mctx);
833         mono_restore_context (&mctx);
834 }
835
836 void
837 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
838 {
839 #if defined(MONO_ARCH_USE_SIGACTION)
840         MonoException *exc = NULL;
841         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_RIP (sigctx), NULL);
842         gpointer *sp;
843         int frame_size;
844         MonoContext *copied_ctx;
845
846         if (stack_ovf)
847                 exc = mono_domain_get ()->stack_overflow_ex;
848         if (!ji)
849                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
850
851         /* setup a call frame on the real stack so that control is returned there
852          * and exception handling can continue.
853          * The frame looks like:
854          *   ucontext struct
855          *   ...
856          *   return ip
857          * 128 is the size of the red zone
858          */
859         frame_size = sizeof (MonoContext) + sizeof (gpointer) * 4 + 128;
860         frame_size += 15;
861         frame_size &= ~15;
862         sp = (gpointer)(UCONTEXT_REG_RSP (sigctx) & ~15);
863         sp = (gpointer)((char*)sp - frame_size);
864         copied_ctx = (MonoContext*)(sp + 4);
865         /* the arguments must be aligned */
866         sp [-1] = (gpointer)UCONTEXT_REG_RIP (sigctx);
867         mono_sigctx_to_monoctx (sigctx, copied_ctx);
868         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
869         UCONTEXT_REG_RIP (sigctx) = (unsigned long)altstack_handle_and_restore;
870         UCONTEXT_REG_RSP (sigctx) = (unsigned long)(sp - 1);
871         UCONTEXT_REG_RDI (sigctx) = (unsigned long)(copied_ctx);
872         UCONTEXT_REG_RSI (sigctx) = (guint64)exc;
873         UCONTEXT_REG_RDX (sigctx) = stack_ovf;
874 #endif
875 }
876
877 guint64
878 mono_amd64_get_original_ip (void)
879 {
880         MonoLMF *lmf = mono_get_lmf ();
881
882         g_assert (lmf);
883
884         /* Reset the change to previous_lmf */
885         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf & ~1);
886
887         return lmf->rip;
888 }
889
890 gpointer
891 mono_arch_get_throw_pending_exception (MonoTrampInfo **info, gboolean aot)
892 {
893         guint8 *code, *start;
894         guint8 *br[1];
895         gpointer throw_trampoline;
896         MonoJumpInfo *ji = NULL;
897         GSList *unwind_ops = NULL;
898         const guint kMaxCodeSize = NACL_SIZE (128, 256);
899
900         start = code = mono_global_codeman_reserve (kMaxCodeSize);
901
902         /* We are in the frame of a managed method after a call */
903         /* 
904          * We would like to throw the pending exception in such a way that it looks to
905          * be thrown from the managed method.
906          */
907
908         /* Save registers which might contain the return value of the call */
909         amd64_push_reg (code, AMD64_RAX);
910         amd64_push_reg (code, AMD64_RDX);
911
912         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
913         amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
914
915         /* Align stack */
916         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
917
918         /* Obtain the pending exception */
919         if (aot) {
920                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_get_and_clear_pending_exception");
921                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
922         } else {
923                 amd64_mov_reg_imm (code, AMD64_R11, mono_thread_get_and_clear_pending_exception);
924         }
925         amd64_call_reg (code, AMD64_R11);
926
927         /* Check if it is NULL, and branch */
928         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
929         br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
930
931         /* exc != NULL branch */
932
933         /* Save the exc on the stack */
934         amd64_push_reg (code, AMD64_RAX);
935         /* Align stack */
936         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
937
938         /* Obtain the original ip and clear the flag in previous_lmf */
939         if (aot) {
940                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_get_original_ip");
941                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
942         } else {
943                 amd64_mov_reg_imm (code, AMD64_R11, mono_amd64_get_original_ip);
944         }
945         amd64_call_reg (code, AMD64_R11);       
946
947         /* Load exc */
948         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, 8, 8);
949
950         /* Pop saved stuff from the stack */
951         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 6 * 8);
952
953         /* Setup arguments for the throw trampoline */
954         /* Exception */
955         amd64_mov_reg_reg (code, AMD64_ARG_REG1, AMD64_R11, 8);
956         /* The trampoline expects the caller ip to be pushed on the stack */
957         amd64_push_reg (code, AMD64_RAX);
958
959         /* Call the throw trampoline */
960         if (aot) {
961                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_throw_exception");
962                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
963         } else {
964                 throw_trampoline = mono_get_throw_exception ();
965                 amd64_mov_reg_imm (code, AMD64_R11, throw_trampoline);
966         }
967         /* We use a jump instead of a call so we can push the original ip on the stack */
968         amd64_jump_reg (code, AMD64_R11);
969
970         /* ex == NULL branch */
971         mono_amd64_patch (br [0], code);
972
973         /* Obtain the original ip and clear the flag in previous_lmf */
974         if (aot) {
975                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_get_original_ip");
976                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
977         } else {
978                 amd64_mov_reg_imm (code, AMD64_R11, mono_amd64_get_original_ip);
979         }
980         amd64_call_reg (code, AMD64_R11);       
981         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
982
983         /* Restore registers */
984         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
985         amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
986         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
987         amd64_pop_reg (code, AMD64_RDX);
988         amd64_pop_reg (code, AMD64_RAX);
989
990         /* Return to original code */
991         amd64_jump_reg (code, AMD64_R11);
992
993         g_assert ((code - start) < kMaxCodeSize);
994
995         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
996
997         if (info)
998                 *info = mono_tramp_info_create ("throw_pending_exception", start, code - start, ji, unwind_ops);
999
1000         return start;
1001 }
1002
1003 static gpointer throw_pending_exception;
1004
1005 /*
1006  * Called when a thread receives an async exception while executing unmanaged code.
1007  * Instead of checking for this exception in the managed-to-native wrapper, we hijack 
1008  * the return address on the stack to point to a helper routine which throws the
1009  * exception.
1010  */
1011 void
1012 mono_arch_notify_pending_exc (MonoThreadInfo *info)
1013 {
1014         MonoLMF *lmf = mono_get_lmf ();
1015
1016         if (!info) {
1017                 lmf = mono_get_lmf ();
1018         } else {
1019                 g_assert (info->suspend_state.valid);
1020                 lmf = info->suspend_state.unwind_data [MONO_UNWIND_DATA_LMF];
1021         }
1022
1023         if (!lmf)
1024                 /* Not yet started */
1025                 return;
1026
1027         if (lmf->rsp == 0)
1028                 /* Initial LMF */
1029                 return;
1030
1031         if ((guint64)lmf->previous_lmf & 1)
1032                 /* Already hijacked or trampoline LMF entry */
1033                 return;
1034
1035         /* lmf->rsp is set just before making the call which transitions to unmanaged code */
1036         lmf->rip = *(guint64*)(lmf->rsp - 8);
1037         /* Signal that lmf->rip is set */
1038         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf | 1);
1039
1040         *(gpointer*)(lmf->rsp - 8) = throw_pending_exception;
1041 }
1042
1043 GSList*
1044 mono_amd64_get_exception_trampolines (gboolean aot)
1045 {
1046         MonoTrampInfo *info;
1047         GSList *tramps = NULL;
1048
1049         mono_arch_get_throw_pending_exception (&info, aot);
1050         tramps = g_slist_prepend (tramps, info);
1051
1052         /* LLVM needs different throw trampolines */
1053         get_throw_trampoline (&info, FALSE, TRUE, FALSE, FALSE, "llvm_throw_corlib_exception_trampoline", aot);
1054         tramps = g_slist_prepend (tramps, info);
1055
1056         get_throw_trampoline (&info, FALSE, TRUE, TRUE, FALSE, "llvm_throw_corlib_exception_abs_trampoline", aot);
1057         tramps = g_slist_prepend (tramps, info);
1058
1059         get_throw_trampoline (&info, FALSE, TRUE, TRUE, TRUE, "llvm_resume_unwind_trampoline", FALSE);
1060         tramps = g_slist_prepend (tramps, info);
1061
1062         return tramps;
1063 }
1064
1065 void
1066 mono_arch_exceptions_init (void)
1067 {
1068         GSList *tramps, *l;
1069         gpointer tramp;
1070
1071         if (mono_aot_only) {
1072                 throw_pending_exception = mono_aot_get_trampoline ("throw_pending_exception");
1073                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_trampoline");
1074                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
1075                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_abs_trampoline");
1076                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
1077                 tramp = mono_aot_get_trampoline ("llvm_resume_unwind_trampoline");
1078                 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
1079         } else {
1080                 /* Call this to avoid initialization races */
1081                 throw_pending_exception = mono_arch_get_throw_pending_exception (NULL, FALSE);
1082
1083                 tramps = mono_amd64_get_exception_trampolines (FALSE);
1084                 for (l = tramps; l; l = l->next) {
1085                         MonoTrampInfo *info = l->data;
1086
1087                         mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE);
1088                         mono_tramp_info_register (info);
1089                 }
1090                 g_slist_free (tramps);
1091         }
1092 }
1093
1094 #ifdef TARGET_WIN32
1095
1096 /*
1097  * The mono_arch_unwindinfo* methods are used to build and add
1098  * function table info for each emitted method from mono.  On Winx64
1099  * the seh handler will not be called if the mono methods are not
1100  * added to the function table.  
1101  *
1102  * We should not need to add non-volatile register info to the 
1103  * table since mono stores that info elsewhere. (Except for the register 
1104  * used for the fp.)
1105  */
1106
1107 #define MONO_MAX_UNWIND_CODES 22
1108
1109 typedef union _UNWIND_CODE {
1110     struct {
1111         guchar CodeOffset;
1112         guchar UnwindOp : 4;
1113         guchar OpInfo   : 4;
1114     };
1115     gushort FrameOffset;
1116 } UNWIND_CODE, *PUNWIND_CODE;
1117
1118 typedef struct _UNWIND_INFO {
1119         guchar Version       : 3;
1120         guchar Flags         : 5;
1121         guchar SizeOfProlog;
1122         guchar CountOfCodes;
1123         guchar FrameRegister : 4;
1124         guchar FrameOffset   : 4;
1125         /* custom size for mono allowing for mono allowing for*/
1126         /*UWOP_PUSH_NONVOL ebp offset = 21*/
1127         /*UWOP_ALLOC_LARGE : requires 2 or 3 offset = 20*/
1128         /*UWOP_SET_FPREG : requires 2 offset = 17*/
1129         /*UWOP_PUSH_NONVOL offset = 15-0*/
1130         UNWIND_CODE UnwindCode[MONO_MAX_UNWIND_CODES]; 
1131
1132 /*      UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
1133  *      union {
1134  *          OPTIONAL ULONG ExceptionHandler;
1135  *          OPTIONAL ULONG FunctionEntry;
1136  *      };
1137  *      OPTIONAL ULONG ExceptionData[]; */
1138 } UNWIND_INFO, *PUNWIND_INFO;
1139
1140 typedef struct
1141 {
1142         RUNTIME_FUNCTION runtimeFunction;
1143         UNWIND_INFO unwindInfo;
1144 } MonoUnwindInfo, *PMonoUnwindInfo;
1145
1146 static void
1147 mono_arch_unwindinfo_create (gpointer* monoui)
1148 {
1149         PMonoUnwindInfo newunwindinfo;
1150         *monoui = newunwindinfo = g_new0 (MonoUnwindInfo, 1);
1151         newunwindinfo->unwindInfo.Version = 1;
1152 }
1153
1154 void
1155 mono_arch_unwindinfo_add_push_nonvol (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
1156 {
1157         PMonoUnwindInfo unwindinfo;
1158         PUNWIND_CODE unwindcode;
1159         guchar codeindex;
1160         if (!*monoui)
1161                 mono_arch_unwindinfo_create (monoui);
1162         
1163         unwindinfo = (MonoUnwindInfo*)*monoui;
1164
1165         if (unwindinfo->unwindInfo.CountOfCodes >= MONO_MAX_UNWIND_CODES)
1166                 g_error ("Larger allocation needed for the unwind information.");
1167
1168         codeindex = MONO_MAX_UNWIND_CODES - (++unwindinfo->unwindInfo.CountOfCodes);
1169         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1170         unwindcode->UnwindOp = 0; /*UWOP_PUSH_NONVOL*/
1171         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1172         unwindcode->OpInfo = reg;
1173
1174         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1175                 g_error ("Adding unwind info in wrong order.");
1176         
1177         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1178 }
1179
1180 void
1181 mono_arch_unwindinfo_add_set_fpreg (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
1182 {
1183         PMonoUnwindInfo unwindinfo;
1184         PUNWIND_CODE unwindcode;
1185         guchar codeindex;
1186         if (!*monoui)
1187                 mono_arch_unwindinfo_create (monoui);
1188         
1189         unwindinfo = (MonoUnwindInfo*)*monoui;
1190
1191         if (unwindinfo->unwindInfo.CountOfCodes + 1 >= MONO_MAX_UNWIND_CODES)
1192                 g_error ("Larger allocation needed for the unwind information.");
1193
1194         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += 2);
1195         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1196         unwindcode->FrameOffset = 0; /*Assuming no frame pointer offset for mono*/
1197         unwindcode++;
1198         unwindcode->UnwindOp = 3; /*UWOP_SET_FPREG*/
1199         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1200         unwindcode->OpInfo = reg;
1201         
1202         unwindinfo->unwindInfo.FrameRegister = reg;
1203
1204         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1205                 g_error ("Adding unwind info in wrong order.");
1206         
1207         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1208 }
1209
1210 void
1211 mono_arch_unwindinfo_add_alloc_stack (gpointer* monoui, gpointer codebegin, gpointer nextip, guint size )
1212 {
1213         PMonoUnwindInfo unwindinfo;
1214         PUNWIND_CODE unwindcode;
1215         guchar codeindex;
1216         guchar codesneeded;
1217         if (!*monoui)
1218                 mono_arch_unwindinfo_create (monoui);
1219         
1220         unwindinfo = (MonoUnwindInfo*)*monoui;
1221
1222         if (size < 0x8)
1223                 g_error ("Stack allocation must be equal to or greater than 0x8.");
1224         
1225         if (size <= 0x80)
1226                 codesneeded = 1;
1227         else if (size <= 0x7FFF8)
1228                 codesneeded = 2;
1229         else
1230                 codesneeded = 3;
1231         
1232         if (unwindinfo->unwindInfo.CountOfCodes + codesneeded > MONO_MAX_UNWIND_CODES)
1233                 g_error ("Larger allocation needed for the unwind information.");
1234
1235         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += codesneeded);
1236         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1237
1238         if (codesneeded == 1) {
1239                 /*The size of the allocation is 
1240                   (the number in the OpInfo member) times 8 plus 8*/
1241                 unwindcode->OpInfo = (size - 8)/8;
1242                 unwindcode->UnwindOp = 2; /*UWOP_ALLOC_SMALL*/
1243         }
1244         else {
1245                 if (codesneeded == 3) {
1246                         /*the unscaled size of the allocation is recorded
1247                           in the next two slots in little-endian format*/
1248                         *((unsigned int*)(&unwindcode->FrameOffset)) = size;
1249                         unwindcode += 2;
1250                         unwindcode->OpInfo = 1;
1251                 }
1252                 else {
1253                         /*the size of the allocation divided by 8
1254                           is recorded in the next slot*/
1255                         unwindcode->FrameOffset = size/8; 
1256                         unwindcode++;   
1257                         unwindcode->OpInfo = 0;
1258                         
1259                 }
1260                 unwindcode->UnwindOp = 1; /*UWOP_ALLOC_LARGE*/
1261         }
1262
1263         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1264
1265         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1266                 g_error ("Adding unwind info in wrong order.");
1267         
1268         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1269 }
1270
1271 guint
1272 mono_arch_unwindinfo_get_size (gpointer monoui)
1273 {
1274         PMonoUnwindInfo unwindinfo;
1275         if (!monoui)
1276                 return 0;
1277         
1278         unwindinfo = (MonoUnwindInfo*)monoui;
1279         return (8 + sizeof (MonoUnwindInfo)) - 
1280                 (sizeof (UNWIND_CODE) * (MONO_MAX_UNWIND_CODES - unwindinfo->unwindInfo.CountOfCodes));
1281 }
1282
1283 static PRUNTIME_FUNCTION
1284 MONO_GET_RUNTIME_FUNCTION_CALLBACK ( DWORD64 ControlPc, IN PVOID Context )
1285 {
1286         MonoJitInfo *ji;
1287         guint64 pos;
1288         PMonoUnwindInfo targetinfo;
1289         MonoDomain *domain = mono_domain_get ();
1290
1291         ji = mini_jit_info_table_find (domain, (char*)ControlPc, NULL);
1292         if (!ji)
1293                 return 0;
1294
1295         pos = (guint64)(((char*)ji->code_start) + ji->code_size);
1296         
1297         targetinfo = (PMonoUnwindInfo)ALIGN_TO (pos, 8);
1298
1299         targetinfo->runtimeFunction.UnwindData = ((DWORD64)&targetinfo->unwindInfo) - ((DWORD64)Context);
1300
1301         return &targetinfo->runtimeFunction;
1302 }
1303
1304 void
1305 mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint code_size)
1306 {
1307         PMonoUnwindInfo unwindinfo, targetinfo;
1308         guchar codecount;
1309         guint64 targetlocation;
1310         if (!*monoui)
1311                 return;
1312
1313         unwindinfo = (MonoUnwindInfo*)*monoui;
1314         targetlocation = (guint64)&(((guchar*)code)[code_size]);
1315         targetinfo = (PMonoUnwindInfo) ALIGN_TO(targetlocation, 8);
1316
1317         unwindinfo->runtimeFunction.EndAddress = code_size;
1318         unwindinfo->runtimeFunction.UnwindData = ((guchar*)&targetinfo->unwindInfo) - ((guchar*)code);
1319         
1320         memcpy (targetinfo, unwindinfo, sizeof (MonoUnwindInfo) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
1321         
1322         codecount = unwindinfo->unwindInfo.CountOfCodes;
1323         if (codecount) {
1324                 memcpy (&targetinfo->unwindInfo.UnwindCode[0], &unwindinfo->unwindInfo.UnwindCode[MONO_MAX_UNWIND_CODES-codecount], 
1325                         sizeof (UNWIND_CODE) * unwindinfo->unwindInfo.CountOfCodes);
1326         }
1327
1328         g_free (unwindinfo);
1329         *monoui = 0;
1330
1331         RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
1332 }
1333
1334 #endif
1335
1336 #if MONO_SUPPORT_TASKLETS
1337 MonoContinuationRestore
1338 mono_tasklets_arch_restore (void)
1339 {
1340         static guint8* saved = NULL;
1341         guint8 *code, *start;
1342         int cont_reg = AMD64_R9; /* register usable on both call conventions */
1343         const guint kMaxCodeSize = NACL_SIZE (64, 128);
1344         
1345
1346         if (saved)
1347                 return (MonoContinuationRestore)saved;
1348         code = start = mono_global_codeman_reserve (kMaxCodeSize);
1349         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1350         /* cont is in AMD64_ARG_REG1 ($rcx or $rdi)
1351          * state is in AMD64_ARG_REG2 ($rdx or $rsi)
1352          * lmf_addr is in AMD64_ARG_REG3 ($r8 or $rdx)
1353          * We move cont to cont_reg since we need both rcx and rdi for the copy
1354          * state is moved to $rax so it's setup as the return value and we can overwrite $rsi
1355          */
1356         amd64_mov_reg_reg (code, cont_reg, MONO_AMD64_ARG_REG1, 8);
1357         amd64_mov_reg_reg (code, AMD64_RAX, MONO_AMD64_ARG_REG2, 8);
1358         /* setup the copy of the stack */
1359         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, stack_used_size), sizeof (int));
1360         amd64_shift_reg_imm (code, X86_SHR, AMD64_RCX, 3);
1361         x86_cld (code);
1362         amd64_mov_reg_membase (code, AMD64_RSI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, saved_stack), sizeof (gpointer));
1363         amd64_mov_reg_membase (code, AMD64_RDI, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_sp), sizeof (gpointer));
1364         amd64_prefix (code, X86_REP_PREFIX);
1365         amd64_movsl (code);
1366
1367         /* now restore the registers from the LMF */
1368         NOT_IMPLEMENTED;
1369         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, lmf), 8);
1370         amd64_mov_reg_membase (code, AMD64_RSP, AMD64_RCX, MONO_STRUCT_OFFSET (MonoLMF, rsp), 8);
1371
1372         /* restore the lmf chain */
1373         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1374         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1375
1376         /* state is already in rax */
1377         amd64_jump_membase (code, cont_reg, MONO_STRUCT_OFFSET (MonoContinuation, return_ip));
1378         g_assert ((code - start) <= kMaxCodeSize);
1379
1380         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1381
1382         saved = start;
1383         return (MonoContinuationRestore)saved;
1384 }
1385 #endif
1386
1387 /*
1388  * mono_arch_setup_resume_sighandler_ctx:
1389  *
1390  *   Setup CTX so execution continues at FUNC.
1391  */
1392 void
1393 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1394 {
1395         /* 
1396          * When resuming from a signal handler, the stack should be misaligned, just like right after
1397          * a call.
1398          */
1399         if ((((guint64)MONO_CONTEXT_GET_SP (ctx)) % 16) == 0)
1400                 MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
1401         MONO_CONTEXT_SET_IP (ctx, func);
1402 }