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