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