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