ab704e4fe5cc6898142edd46a3b6f9f9faf69772
[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         if (mono_running_on_valgrind ()) {
229                 /* Prevent 'Address 0x... is just below the stack ptr.' errors */
230                 amd64_mov_reg_membase (code, AMD64_R8, AMD64_R11,  G_STRUCT_OFFSET (MonoContext, rsp), 8);
231                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11,  G_STRUCT_OFFSET (MonoContext, rip), 8);
232                 amd64_mov_reg_reg (code, AMD64_RSP, AMD64_R8, 8);
233         } else {
234                 amd64_mov_reg_membase (code, AMD64_RSP, AMD64_R11,  G_STRUCT_OFFSET (MonoContext, rsp), 8);
235                 /* get return address */
236                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11,  G_STRUCT_OFFSET (MonoContext, rip), 8);
237         }
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         static void (*restore_context) (MonoContext *);
350         MonoContext ctx;
351
352         if (!restore_context)
353                 restore_context = mono_get_restore_context ();
354
355         ctx.rsp = regs [AMD64_RSP];
356         ctx.rip = rip;
357         ctx.rbx = regs [AMD64_RBX];
358         ctx.rbp = regs [AMD64_RBP];
359         ctx.r12 = regs [AMD64_R12];
360         ctx.r13 = regs [AMD64_R13];
361         ctx.r14 = regs [AMD64_R14];
362         ctx.r15 = regs [AMD64_R15];
363         ctx.rdi = regs [AMD64_RDI];
364         ctx.rsi = regs [AMD64_RSI];
365         ctx.rax = regs [AMD64_RAX];
366         ctx.rcx = regs [AMD64_RCX];
367         ctx.rdx = regs [AMD64_RDX];
368
369         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
370                 MonoException *mono_ex = (MonoException*)exc;
371                 if (!rethrow)
372                         mono_ex->stack_trace = NULL;
373         }
374
375         if (mono_debug_using_mono_debugger ()) {
376                 guint8 buf [16];
377
378                 mono_breakpoint_clean_code (NULL, (gpointer)rip, 8, buf, sizeof (buf));
379
380                 if (buf [3] == 0xe8) {
381                         MonoContext ctx_cp = ctx;
382                         ctx_cp.rip = rip - 5;
383
384                         if (mono_debugger_handle_exception (&ctx_cp, exc)) {
385                                 restore_context (&ctx_cp);
386                                 g_assert_not_reached ();
387                         }
388                 }
389         }
390
391         /* adjust eip so that it point into the call instruction */
392         ctx.rip -= 1;
393
394         mono_handle_exception (&ctx, exc);
395         restore_context (&ctx);
396
397         g_assert_not_reached ();
398 }
399
400 void
401 mono_amd64_throw_corlib_exception (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
402                                                                    guint64 dummy5, guint64 dummy6,
403                                                                    mgreg_t *regs, mgreg_t rip,
404                                                                    guint32 ex_token_index, gint64 pc_offset)
405 {
406         guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
407         MonoException *ex;
408
409         ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
410
411         rip -= pc_offset;
412
413         /* Negate the ip adjustment done in mono_amd64_throw_exception () */
414         rip += 1;
415
416         mono_amd64_throw_exception (dummy1, dummy2, dummy3, dummy4, dummy5, dummy6, regs, rip, (MonoObject*)ex, FALSE);
417 }
418
419 static void
420 mono_amd64_resume_unwind (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint64 dummy4,
421                                                   guint64 dummy5, guint64 dummy6,
422                                                   mgreg_t *regs, mgreg_t rip,
423                                                   guint32 dummy7, gint64 dummy8)
424 {
425         /* Only the register parameters are valid */
426         MonoContext ctx;
427
428         ctx.rsp = regs [AMD64_RSP];
429         ctx.rip = rip;
430         ctx.rbx = regs [AMD64_RBX];
431         ctx.rbp = regs [AMD64_RBP];
432         ctx.r12 = regs [AMD64_R12];
433         ctx.r13 = regs [AMD64_R13];
434         ctx.r14 = regs [AMD64_R14];
435         ctx.r15 = regs [AMD64_R15];
436         ctx.rdi = regs [AMD64_RDI];
437         ctx.rsi = regs [AMD64_RSI];
438         ctx.rax = regs [AMD64_RAX];
439         ctx.rcx = regs [AMD64_RCX];
440         ctx.rdx = regs [AMD64_RDX];
441
442         mono_resume_unwind (&ctx);
443 }
444
445 /*
446  * get_throw_trampoline:
447  *
448  *  Generate a call to mono_amd64_throw_exception/
449  * mono_amd64_throw_corlib_exception.
450  */
451 static gpointer
452 get_throw_trampoline (MonoTrampInfo **info, gboolean rethrow, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, const char *tramp_name, gboolean aot)
453 {
454         guint8* start;
455         guint8 *code;
456         MonoJumpInfo *ji = NULL;
457         GSList *unwind_ops = NULL;
458         int i, stack_size, arg_offsets [16], regs_offset, dummy_stack_space;
459         const guint kMaxCodeSize = NACL_SIZE (256, 512);
460
461 #ifdef TARGET_WIN32
462         dummy_stack_space = 6 * sizeof(mgreg_t);        /* Windows expects stack space allocated for all 6 dummy args. */
463 #else
464         dummy_stack_space = 0;
465 #endif
466
467         start = code = mono_global_codeman_reserve (kMaxCodeSize);
468
469         /* The stack is unaligned on entry */
470         stack_size = 192 + 8 + dummy_stack_space;
471
472         code = start;
473
474         if (info)
475                 unwind_ops = mono_arch_get_cie_program ();
476
477         /* Alloc frame */
478         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_size);
479         if (info)
480                 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 8);
481
482         /*
483          * To hide linux/windows calling convention differences, we pass all arguments on
484          * the stack by passing 6 dummy values in registers.
485          */
486
487         arg_offsets [0] = dummy_stack_space + 0;
488         arg_offsets [1] = dummy_stack_space + sizeof(mgreg_t);
489         arg_offsets [2] = dummy_stack_space + sizeof(mgreg_t) * 2;
490         arg_offsets [3] = dummy_stack_space + sizeof(mgreg_t) * 3;
491         regs_offset = dummy_stack_space + sizeof(mgreg_t) * 4;
492
493         /* Save registers */
494         for (i = 0; i < AMD64_NREG; ++i)
495                 if (i != AMD64_RSP)
496                         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
497         /* Save RSP */
498         amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, stack_size + sizeof(mgreg_t));
499         amd64_mov_membase_reg (code, AMD64_RSP, regs_offset + (AMD64_RSP * sizeof(mgreg_t)), X86_EAX, sizeof(mgreg_t));
500         /* Set arg1 == regs */
501         amd64_lea_membase (code, AMD64_RAX, AMD64_RSP, regs_offset);
502         amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [0], AMD64_RAX, sizeof(mgreg_t));
503         /* Set arg2 == eip */
504         if (llvm_abs)
505                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
506         else
507                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, stack_size, sizeof(mgreg_t));
508         amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [1], AMD64_RAX, sizeof(mgreg_t));
509         /* Set arg3 == exc/ex_token_index */
510         if (resume_unwind)
511                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [2], 0, sizeof(mgreg_t));
512         else
513                 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [2], AMD64_ARG_REG1, sizeof(mgreg_t));
514         /* Set arg4 == rethrow/pc offset */
515         if (resume_unwind) {
516                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [3], 0, sizeof(mgreg_t));
517         } else if (corlib) {
518                 amd64_mov_membase_reg (code, AMD64_RSP, arg_offsets [3], AMD64_ARG_REG2, sizeof(mgreg_t));
519                 if (llvm_abs)
520                         /* 
521                          * The caller is LLVM code which passes the absolute address not a pc offset,
522                          * so compensate by passing 0 as 'rip' and passing the negated abs address as
523                          * the pc offset.
524                          */
525                         amd64_neg_membase (code, AMD64_RSP, arg_offsets [3]);
526         } else {
527                 amd64_mov_membase_imm (code, AMD64_RSP, arg_offsets [3], rethrow, sizeof(mgreg_t));
528         }
529
530         if (aot) {
531                 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");
532                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
533         } else {
534                 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));
535         }
536         amd64_call_reg (code, AMD64_R11);
537         amd64_breakpoint (code);
538
539         mono_arch_flush_icache (start, code - start);
540
541         g_assert ((code - start) < kMaxCodeSize);
542
543         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
544
545         if (info)
546                 *info = mono_tramp_info_create (tramp_name, start, code - start, ji, unwind_ops);
547
548         return start;
549 }
550
551 /**
552  * mono_arch_get_throw_exception:
553  *
554  * Returns a function pointer which can be used to raise 
555  * exceptions. The returned function has the following 
556  * signature: void (*func) (MonoException *exc); 
557  *
558  */
559 gpointer
560 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
561 {
562         return get_throw_trampoline (info, FALSE, FALSE, FALSE, FALSE, "throw_exception", aot);
563 }
564
565 gpointer 
566 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
567 {
568         return get_throw_trampoline (info, TRUE, FALSE, FALSE, FALSE, "rethrow_exception", aot);
569 }
570
571 /**
572  * mono_arch_get_throw_corlib_exception:
573  *
574  * Returns a function pointer which can be used to raise 
575  * corlib exceptions. The returned function has the following 
576  * signature: void (*func) (guint32 ex_token, guint32 offset); 
577  * Here, offset is the offset which needs to be substracted from the caller IP 
578  * to get the IP of the throw. Passing the offset has the advantage that it 
579  * needs no relocations in the caller.
580  */
581 gpointer 
582 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
583 {
584         return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
585 }
586
587 /*
588  * mono_arch_find_jit_info:
589  *
590  * This function is used to gather information from @ctx, and store it in @frame_info.
591  * It unwinds one stack frame, and stores the resulting context into @new_ctx. @lmf
592  * is modified if needed.
593  * Returns TRUE on success, FALSE otherwise.
594  */
595 gboolean
596 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, 
597                                                          MonoJitInfo *ji, MonoContext *ctx, 
598                                                          MonoContext *new_ctx, MonoLMF **lmf,
599                                                          mgreg_t **save_locations,
600                                                          StackFrameInfo *frame)
601 {
602         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
603
604         memset (frame, 0, sizeof (StackFrameInfo));
605         frame->ji = ji;
606
607         *new_ctx = *ctx;
608
609         if (ji != NULL) {
610                 mgreg_t regs [MONO_MAX_IREGS + 1];
611                 guint8 *cfa;
612                 guint32 unwind_info_len;
613                 guint8 *unwind_info;
614
615                 frame->type = FRAME_TYPE_MANAGED;
616
617                 if (ji->from_aot)
618                         unwind_info = mono_aot_get_unwind_info (ji, &unwind_info_len);
619                 else
620                         unwind_info = mono_get_cached_unwind_info (ji->used_regs, &unwind_info_len);
621
622                 frame->unwind_info = unwind_info;
623                 frame->unwind_info_len = unwind_info_len;
624  
625                 regs [AMD64_RAX] = new_ctx->rax;
626                 regs [AMD64_RBX] = new_ctx->rbx;
627                 regs [AMD64_RCX] = new_ctx->rcx;
628                 regs [AMD64_RDX] = new_ctx->rdx;
629                 regs [AMD64_RBP] = new_ctx->rbp;
630                 regs [AMD64_RSP] = new_ctx->rsp;
631                 regs [AMD64_RSI] = new_ctx->rsi;
632                 regs [AMD64_RDI] = new_ctx->rdi;
633                 regs [AMD64_RIP] = new_ctx->rip;
634                 regs [AMD64_R12] = new_ctx->r12;
635                 regs [AMD64_R13] = new_ctx->r13;
636                 regs [AMD64_R14] = new_ctx->r14;
637                 regs [AMD64_R15] = new_ctx->r15;
638
639                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
640                                                    (guint8*)ji->code_start + ji->code_size,
641                                                    ip, regs, MONO_MAX_IREGS + 1, 
642                                                    save_locations, MONO_MAX_IREGS, &cfa);
643
644                 new_ctx->rax = regs [AMD64_RAX];
645                 new_ctx->rbx = regs [AMD64_RBX];
646                 new_ctx->rcx = regs [AMD64_RCX];
647                 new_ctx->rdx = regs [AMD64_RDX];
648                 new_ctx->rbp = regs [AMD64_RBP];
649                 new_ctx->rsp = regs [AMD64_RSP];
650                 new_ctx->rsi = regs [AMD64_RSI];
651                 new_ctx->rdi = regs [AMD64_RDI];
652                 new_ctx->rip = regs [AMD64_RIP];
653                 new_ctx->r12 = regs [AMD64_R12];
654                 new_ctx->r13 = regs [AMD64_R13];
655                 new_ctx->r14 = regs [AMD64_R14];
656                 new_ctx->r15 = regs [AMD64_R15];
657  
658                 /* The CFA becomes the new SP value */
659                 new_ctx->rsp = (mgreg_t)cfa;
660
661                 /* Adjust IP */
662                 new_ctx->rip --;
663
664                 if (*lmf && ((*lmf) != jit_tls->first_lmf) && (MONO_CONTEXT_GET_SP (ctx) >= (gpointer)(*lmf)->rsp)) {
665                         /* remove any unused lmf */
666                         *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~3);
667                 }
668
669 #ifndef MONO_AMD64_NO_PUSHES
670                 /* Pop arguments off the stack */
671                 if (ji->has_arch_eh_info)
672                         new_ctx->rsp += mono_jit_info_get_arch_eh_info (ji)->stack_size;
673 #endif
674
675                 return TRUE;
676         } else if (*lmf) {
677                 guint64 rip;
678
679                 if (((guint64)(*lmf)->previous_lmf) & 2) {
680                         /* 
681                          * This LMF entry is created by the soft debug code to mark transitions to
682                          * managed code done during invokes.
683                          */
684                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
685
686                         g_assert (ext->debugger_invoke);
687
688                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
689
690                         *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~3);
691
692                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
693
694                         return TRUE;
695                 }
696
697                 if (((guint64)(*lmf)->previous_lmf) & 1) {
698                         /* This LMF has the rip field set */
699                         rip = (*lmf)->rip;
700                 } else if ((*lmf)->rsp == 0) {
701                         /* Top LMF entry */
702                         return FALSE;
703                 } else {
704                         /* 
705                          * The rsp field is set just before the call which transitioned to native 
706                          * code. Obtain the rip from the stack.
707                          */
708                         rip = *(guint64*)((*lmf)->rsp - sizeof(mgreg_t));
709                 }
710
711                 ji = mini_jit_info_table_find (domain, (gpointer)rip, NULL);
712                 /*
713                  * FIXME: ji == NULL can happen when a managed-to-native wrapper is interrupted
714                  * in the soft debugger suspend code, since (*lmf)->rsp no longer points to the
715                  * return address.
716                  */
717                 //g_assert (ji);
718                 if (!ji)
719                         return FALSE;
720
721                 /* Adjust IP */
722                 rip --;
723
724                 frame->ji = ji;
725                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
726
727                 new_ctx->rip = rip;
728                 new_ctx->rbp = (*lmf)->rbp;
729                 new_ctx->rsp = (*lmf)->rsp;
730
731                 new_ctx->rbx = (*lmf)->rbx;
732                 new_ctx->r12 = (*lmf)->r12;
733                 new_ctx->r13 = (*lmf)->r13;
734                 new_ctx->r14 = (*lmf)->r14;
735                 new_ctx->r15 = (*lmf)->r15;
736 #ifdef TARGET_WIN32
737                 new_ctx->rdi = (*lmf)->rdi;
738                 new_ctx->rsi = (*lmf)->rsi;
739 #endif
740
741                 *lmf = (gpointer)(((guint64)(*lmf)->previous_lmf) & ~3);
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         static void (*restore_context) (MonoContext *);
760
761         if (!restore_context)
762                 restore_context = mono_get_restore_context ();
763
764         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
765
766         if (mono_debugger_handle_exception (&ctx, (MonoObject *)obj))
767                 return;
768
769         mono_handle_exception (&ctx, obj);
770
771         restore_context (&ctx);
772 }
773
774 void
775 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
776 {
777         guint64 sp = ctx->rsp;
778
779         ctx->rdi = (guint64)user_data;
780
781         /* Allocate a stack frame below the red zone */
782         sp -= 128;
783         /* The stack should be unaligned */
784         if ((sp % 16) == 0)
785                 sp -= 8;
786         ctx->rsp = sp;
787         ctx->rip = (guint64)async_cb;
788 }
789
790 /**
791  * mono_arch_handle_exception:
792  *
793  * @ctx: saved processor state
794  * @obj: the exception object
795  */
796 gboolean
797 mono_arch_handle_exception (void *sigctx, gpointer obj)
798 {
799 #if defined(MONO_ARCH_USE_SIGACTION)
800         MonoContext mctx;
801
802         /*
803          * Handling the exception in the signal handler is problematic, since the original
804          * signal is disabled, and we could run arbitrary code though the debugger. So
805          * resume into the normal stack and do most work there if possible.
806          */
807         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
808
809         /* Pass the ctx parameter in TLS */
810         mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
811
812         mctx = jit_tls->ex_ctx;
813         mono_arch_setup_async_callback (&mctx, handle_signal_exception, obj);
814         mono_monoctx_to_sigctx (&mctx, sigctx);
815
816         return TRUE;
817 #else
818         MonoContext mctx;
819
820         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
821
822         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj))
823                 return TRUE;
824
825         mono_handle_exception (&mctx, obj);
826
827         mono_arch_monoctx_to_sigctx (&mctx, sigctx);
828
829         return TRUE;
830 #endif
831 }
832
833 void
834 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
835 {
836         mono_sigctx_to_monoctx (sigctx, mctx);
837 }
838
839 void
840 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
841 {
842         mono_monoctx_to_sigctx (mctx, sigctx);
843 }
844
845 gpointer
846 mono_arch_ip_from_context (void *sigctx)
847 {
848 #if defined(MONO_ARCH_USE_SIGACTION)
849         ucontext_t *ctx = (ucontext_t*)sigctx;
850
851         return (gpointer)UCONTEXT_REG_RIP (ctx);
852 #else
853         MonoContext *ctx = sigctx;
854         return (gpointer)ctx->rip;
855 #endif  
856 }
857
858 static void
859 restore_soft_guard_pages (void)
860 {
861         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
862         if (jit_tls->stack_ovf_guard_base)
863                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
864 }
865
866 /* 
867  * this function modifies mctx so that when it is restored, it
868  * won't execcute starting at mctx.eip, but in a function that
869  * will restore the protection on the soft-guard pages and return back to
870  * continue at mctx.eip.
871  */
872 static void
873 prepare_for_guard_pages (MonoContext *mctx)
874 {
875         gpointer *sp;
876         sp = (gpointer)(mctx->rsp);
877         sp -= 1;
878         /* the return addr */
879         sp [0] = (gpointer)(mctx->rip);
880         mctx->rip = (guint64)restore_soft_guard_pages;
881         mctx->rsp = (guint64)sp;
882 }
883
884 static void
885 altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean stack_ovf)
886 {
887         void (*restore_context) (MonoContext *);
888         MonoContext mctx;
889
890         restore_context = mono_get_restore_context ();
891         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
892
893         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj)) {
894                 if (stack_ovf)
895                         prepare_for_guard_pages (&mctx);
896                 restore_context (&mctx);
897         }
898
899         mono_handle_exception (&mctx, obj);
900         if (stack_ovf)
901                 prepare_for_guard_pages (&mctx);
902         restore_context (&mctx);
903 }
904
905 void
906 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
907 {
908 #if defined(MONO_ARCH_USE_SIGACTION)
909         MonoException *exc = NULL;
910         ucontext_t *ctx = (ucontext_t*)sigctx;
911         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_RIP (sigctx), NULL);
912         gpointer *sp;
913         int frame_size;
914         ucontext_t *copied_ctx;
915
916         if (stack_ovf)
917                 exc = mono_domain_get ()->stack_overflow_ex;
918         if (!ji)
919                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
920
921         /* setup a call frame on the real stack so that control is returned there
922          * and exception handling can continue.
923          * The frame looks like:
924          *   ucontext struct
925          *   ...
926          *   return ip
927          * 128 is the size of the red zone
928          */
929         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 4 + 128;
930 #ifdef __APPLE__
931         frame_size += sizeof (*ctx->uc_mcontext);
932 #endif
933         frame_size += 15;
934         frame_size &= ~15;
935         sp = (gpointer)(UCONTEXT_REG_RSP (sigctx) & ~15);
936         sp = (gpointer)((char*)sp - frame_size);
937         copied_ctx = (ucontext_t*)(sp + 4);
938         /* the arguments must be aligned */
939         sp [-1] = (gpointer)UCONTEXT_REG_RIP (sigctx);
940         /* may need to adjust pointers in the new struct copy, depending on the OS */
941         memcpy (copied_ctx, ctx, sizeof (ucontext_t));
942 #ifdef __APPLE__
943         {
944                 guint8 * copied_mcontext = (guint8*)copied_ctx + sizeof (ucontext_t);
945                 /* uc_mcontext is a pointer, so make a copy which is stored after the ctx */
946                 memcpy (copied_mcontext, ctx->uc_mcontext, sizeof (*ctx->uc_mcontext));
947                 copied_ctx->uc_mcontext = (void*)copied_mcontext;
948         }
949 #endif
950         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
951         UCONTEXT_REG_RIP (sigctx) = (unsigned long)altstack_handle_and_restore;
952         UCONTEXT_REG_RSP (sigctx) = (unsigned long)(sp - 1);
953         UCONTEXT_REG_RDI (sigctx) = (unsigned long)(copied_ctx);
954         UCONTEXT_REG_RSI (sigctx) = (guint64)exc;
955         UCONTEXT_REG_RDX (sigctx) = stack_ovf;
956 #endif
957 }
958
959 guint64
960 mono_amd64_get_original_ip (void)
961 {
962         MonoLMF *lmf = mono_get_lmf ();
963
964         g_assert (lmf);
965
966         /* Reset the change to previous_lmf */
967         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf & ~1);
968
969         return lmf->rip;
970 }
971
972 gpointer
973 mono_arch_get_throw_pending_exception (MonoTrampInfo **info, gboolean aot)
974 {
975         guint8 *code, *start;
976         guint8 *br[1];
977         gpointer throw_trampoline;
978         MonoJumpInfo *ji = NULL;
979         GSList *unwind_ops = NULL;
980         const guint kMaxCodeSize = NACL_SIZE (128, 256);
981
982         start = code = mono_global_codeman_reserve (kMaxCodeSize);
983
984         /* We are in the frame of a managed method after a call */
985         /* 
986          * We would like to throw the pending exception in such a way that it looks to
987          * be thrown from the managed method.
988          */
989
990         /* Save registers which might contain the return value of the call */
991         amd64_push_reg (code, AMD64_RAX);
992         amd64_push_reg (code, AMD64_RDX);
993
994         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
995         amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
996
997         /* Align stack */
998         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
999
1000         /* Obtain the pending exception */
1001         if (aot) {
1002                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_get_and_clear_pending_exception");
1003                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
1004         } else {
1005                 amd64_mov_reg_imm (code, AMD64_R11, mono_thread_get_and_clear_pending_exception);
1006         }
1007         amd64_call_reg (code, AMD64_R11);
1008
1009         /* Check if it is NULL, and branch */
1010         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
1011         br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
1012
1013         /* exc != NULL branch */
1014
1015         /* Save the exc on the stack */
1016         amd64_push_reg (code, AMD64_RAX);
1017         /* Align stack */
1018         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
1019
1020         /* Obtain the original ip and clear the flag in previous_lmf */
1021         if (aot) {
1022                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_get_original_ip");
1023                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
1024         } else {
1025                 amd64_mov_reg_imm (code, AMD64_R11, mono_amd64_get_original_ip);
1026         }
1027         amd64_call_reg (code, AMD64_R11);       
1028
1029         /* Load exc */
1030         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, 8, 8);
1031
1032         /* Pop saved stuff from the stack */
1033         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 6 * 8);
1034
1035         /* Setup arguments for the throw trampoline */
1036         /* Exception */
1037         amd64_mov_reg_reg (code, AMD64_ARG_REG1, AMD64_R11, 8);
1038         /* The trampoline expects the caller ip to be pushed on the stack */
1039         amd64_push_reg (code, AMD64_RAX);
1040
1041         /* Call the throw trampoline */
1042         if (aot) {
1043                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_throw_exception");
1044                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
1045         } else {
1046                 throw_trampoline = mono_get_throw_exception ();
1047                 amd64_mov_reg_imm (code, AMD64_R11, throw_trampoline);
1048         }
1049         /* We use a jump instead of a call so we can push the original ip on the stack */
1050         amd64_jump_reg (code, AMD64_R11);
1051
1052         /* ex == NULL branch */
1053         mono_amd64_patch (br [0], code);
1054
1055         /* Obtain the original ip and clear the flag in previous_lmf */
1056         if (aot) {
1057                 ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_amd64_get_original_ip");
1058                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
1059         } else {
1060                 amd64_mov_reg_imm (code, AMD64_R11, mono_amd64_get_original_ip);
1061         }
1062         amd64_call_reg (code, AMD64_R11);       
1063         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
1064
1065         /* Restore registers */
1066         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
1067         amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
1068         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
1069         amd64_pop_reg (code, AMD64_RDX);
1070         amd64_pop_reg (code, AMD64_RAX);
1071
1072         /* Return to original code */
1073         amd64_jump_reg (code, AMD64_R11);
1074
1075         g_assert ((code - start) < kMaxCodeSize);
1076
1077         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1078
1079         if (info)
1080                 *info = mono_tramp_info_create ("throw_pending_exception", start, code - start, ji, unwind_ops);
1081
1082         return start;
1083 }
1084
1085 static gpointer throw_pending_exception;
1086
1087 /*
1088  * Called when a thread receives an async exception while executing unmanaged code.
1089  * Instead of checking for this exception in the managed-to-native wrapper, we hijack 
1090  * the return address on the stack to point to a helper routine which throws the
1091  * exception.
1092  */
1093 void
1094 mono_arch_notify_pending_exc (void)
1095 {
1096         MonoLMF *lmf = mono_get_lmf ();
1097
1098         if (!lmf)
1099                 /* Not yet started */
1100                 return;
1101
1102         if (lmf->rsp == 0)
1103                 /* Initial LMF */
1104                 return;
1105
1106         if ((guint64)lmf->previous_lmf & 1)
1107                 /* Already hijacked or trampoline LMF entry */
1108                 return;
1109
1110         /* lmf->rsp is set just before making the call which transitions to unmanaged code */
1111         lmf->rip = *(guint64*)(lmf->rsp - 8);
1112         /* Signal that lmf->rip is set */
1113         lmf->previous_lmf = (gpointer)((guint64)lmf->previous_lmf | 1);
1114
1115         *(gpointer*)(lmf->rsp - 8) = throw_pending_exception;
1116 }
1117
1118 GSList*
1119 mono_amd64_get_exception_trampolines (gboolean aot)
1120 {
1121         MonoTrampInfo *info;
1122         GSList *tramps = NULL;
1123
1124         mono_arch_get_throw_pending_exception (&info, aot);
1125         tramps = g_slist_prepend (tramps, info);
1126
1127         /* LLVM needs different throw trampolines */
1128         get_throw_trampoline (&info, FALSE, TRUE, FALSE, FALSE, "llvm_throw_corlib_exception_trampoline", aot);
1129         tramps = g_slist_prepend (tramps, info);
1130
1131         get_throw_trampoline (&info, FALSE, TRUE, TRUE, FALSE, "llvm_throw_corlib_exception_abs_trampoline", aot);
1132         tramps = g_slist_prepend (tramps, info);
1133
1134         get_throw_trampoline (&info, FALSE, TRUE, TRUE, TRUE, "llvm_resume_unwind_trampoline", FALSE);
1135         tramps = g_slist_prepend (tramps, info);
1136
1137         return tramps;
1138 }
1139
1140 void
1141 mono_arch_exceptions_init (void)
1142 {
1143         GSList *tramps, *l;
1144         gpointer tramp;
1145
1146         if (mono_aot_only) {
1147                 throw_pending_exception = mono_aot_get_trampoline ("throw_pending_exception");
1148                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_trampoline");
1149                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
1150                 tramp = mono_aot_get_trampoline ("llvm_throw_corlib_exception_abs_trampoline");
1151                 mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
1152                 tramp = mono_aot_get_trampoline ("llvm_resume_unwind_trampoline");
1153                 mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
1154         } else {
1155                 /* Call this to avoid initialization races */
1156                 throw_pending_exception = mono_arch_get_throw_pending_exception (NULL, FALSE);
1157
1158                 tramps = mono_amd64_get_exception_trampolines (FALSE);
1159                 for (l = tramps; l; l = l->next) {
1160                         MonoTrampInfo *info = l->data;
1161
1162                         mono_register_jit_icall (info->code, g_strdup (info->name), NULL, TRUE);
1163                         mono_save_trampoline_xdebug_info (info);
1164                         mono_tramp_info_free (info);
1165                 }
1166                 g_slist_free (tramps);
1167         }
1168 }
1169
1170 #ifdef TARGET_WIN32
1171
1172 /*
1173  * The mono_arch_unwindinfo* methods are used to build and add
1174  * function table info for each emitted method from mono.  On Winx64
1175  * the seh handler will not be called if the mono methods are not
1176  * added to the function table.  
1177  *
1178  * We should not need to add non-volatile register info to the 
1179  * table since mono stores that info elsewhere. (Except for the register 
1180  * used for the fp.)
1181  */
1182
1183 #define MONO_MAX_UNWIND_CODES 22
1184
1185 typedef union _UNWIND_CODE {
1186     struct {
1187         guchar CodeOffset;
1188         guchar UnwindOp : 4;
1189         guchar OpInfo   : 4;
1190     };
1191     gushort FrameOffset;
1192 } UNWIND_CODE, *PUNWIND_CODE;
1193
1194 typedef struct _UNWIND_INFO {
1195         guchar Version       : 3;
1196         guchar Flags         : 5;
1197         guchar SizeOfProlog;
1198         guchar CountOfCodes;
1199         guchar FrameRegister : 4;
1200         guchar FrameOffset   : 4;
1201         /* custom size for mono allowing for mono allowing for*/
1202         /*UWOP_PUSH_NONVOL ebp offset = 21*/
1203         /*UWOP_ALLOC_LARGE : requires 2 or 3 offset = 20*/
1204         /*UWOP_SET_FPREG : requires 2 offset = 17*/
1205         /*UWOP_PUSH_NONVOL offset = 15-0*/
1206         UNWIND_CODE UnwindCode[MONO_MAX_UNWIND_CODES]; 
1207
1208 /*      UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1];
1209  *      union {
1210  *          OPTIONAL ULONG ExceptionHandler;
1211  *          OPTIONAL ULONG FunctionEntry;
1212  *      };
1213  *      OPTIONAL ULONG ExceptionData[]; */
1214 } UNWIND_INFO, *PUNWIND_INFO;
1215
1216 typedef struct
1217 {
1218         RUNTIME_FUNCTION runtimeFunction;
1219         UNWIND_INFO unwindInfo;
1220 } MonoUnwindInfo, *PMonoUnwindInfo;
1221
1222 static void
1223 mono_arch_unwindinfo_create (gpointer* monoui)
1224 {
1225         PMonoUnwindInfo newunwindinfo;
1226         *monoui = newunwindinfo = g_new0 (MonoUnwindInfo, 1);
1227         newunwindinfo->unwindInfo.Version = 1;
1228 }
1229
1230 void
1231 mono_arch_unwindinfo_add_push_nonvol (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
1232 {
1233         PMonoUnwindInfo unwindinfo;
1234         PUNWIND_CODE unwindcode;
1235         guchar codeindex;
1236         if (!*monoui)
1237                 mono_arch_unwindinfo_create (monoui);
1238         
1239         unwindinfo = (MonoUnwindInfo*)*monoui;
1240
1241         if (unwindinfo->unwindInfo.CountOfCodes >= MONO_MAX_UNWIND_CODES)
1242                 g_error ("Larger allocation needed for the unwind information.");
1243
1244         codeindex = MONO_MAX_UNWIND_CODES - (++unwindinfo->unwindInfo.CountOfCodes);
1245         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1246         unwindcode->UnwindOp = 0; /*UWOP_PUSH_NONVOL*/
1247         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1248         unwindcode->OpInfo = reg;
1249
1250         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1251                 g_error ("Adding unwind info in wrong order.");
1252         
1253         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1254 }
1255
1256 void
1257 mono_arch_unwindinfo_add_set_fpreg (gpointer* monoui, gpointer codebegin, gpointer nextip, guchar reg )
1258 {
1259         PMonoUnwindInfo unwindinfo;
1260         PUNWIND_CODE unwindcode;
1261         guchar codeindex;
1262         if (!*monoui)
1263                 mono_arch_unwindinfo_create (monoui);
1264         
1265         unwindinfo = (MonoUnwindInfo*)*monoui;
1266
1267         if (unwindinfo->unwindInfo.CountOfCodes + 1 >= MONO_MAX_UNWIND_CODES)
1268                 g_error ("Larger allocation needed for the unwind information.");
1269
1270         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += 2);
1271         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1272         unwindcode->FrameOffset = 0; /*Assuming no frame pointer offset for mono*/
1273         unwindcode++;
1274         unwindcode->UnwindOp = 3; /*UWOP_SET_FPREG*/
1275         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1276         unwindcode->OpInfo = reg;
1277         
1278         unwindinfo->unwindInfo.FrameRegister = reg;
1279
1280         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1281                 g_error ("Adding unwind info in wrong order.");
1282         
1283         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1284 }
1285
1286 void
1287 mono_arch_unwindinfo_add_alloc_stack (gpointer* monoui, gpointer codebegin, gpointer nextip, guint size )
1288 {
1289         PMonoUnwindInfo unwindinfo;
1290         PUNWIND_CODE unwindcode;
1291         guchar codeindex;
1292         guchar codesneeded;
1293         if (!*monoui)
1294                 mono_arch_unwindinfo_create (monoui);
1295         
1296         unwindinfo = (MonoUnwindInfo*)*monoui;
1297
1298         if (size < 0x8)
1299                 g_error ("Stack allocation must be equal to or greater than 0x8.");
1300         
1301         if (size <= 0x80)
1302                 codesneeded = 1;
1303         else if (size <= 0x7FFF8)
1304                 codesneeded = 2;
1305         else
1306                 codesneeded = 3;
1307         
1308         if (unwindinfo->unwindInfo.CountOfCodes + codesneeded > MONO_MAX_UNWIND_CODES)
1309                 g_error ("Larger allocation needed for the unwind information.");
1310
1311         codeindex = MONO_MAX_UNWIND_CODES - (unwindinfo->unwindInfo.CountOfCodes += codesneeded);
1312         unwindcode = &unwindinfo->unwindInfo.UnwindCode[codeindex];
1313
1314         if (codesneeded == 1) {
1315                 /*The size of the allocation is 
1316                   (the number in the OpInfo member) times 8 plus 8*/
1317                 unwindcode->OpInfo = (size - 8)/8;
1318                 unwindcode->UnwindOp = 2; /*UWOP_ALLOC_SMALL*/
1319         }
1320         else {
1321                 if (codesneeded == 3) {
1322                         /*the unscaled size of the allocation is recorded
1323                           in the next two slots in little-endian format*/
1324                         *((unsigned int*)(&unwindcode->FrameOffset)) = size;
1325                         unwindcode += 2;
1326                         unwindcode->OpInfo = 1;
1327                 }
1328                 else {
1329                         /*the size of the allocation divided by 8
1330                           is recorded in the next slot*/
1331                         unwindcode->FrameOffset = size/8; 
1332                         unwindcode++;   
1333                         unwindcode->OpInfo = 0;
1334                         
1335                 }
1336                 unwindcode->UnwindOp = 1; /*UWOP_ALLOC_LARGE*/
1337         }
1338
1339         unwindcode->CodeOffset = (((guchar*)nextip)-((guchar*)codebegin));
1340
1341         if (unwindinfo->unwindInfo.SizeOfProlog >= unwindcode->CodeOffset)
1342                 g_error ("Adding unwind info in wrong order.");
1343         
1344         unwindinfo->unwindInfo.SizeOfProlog = unwindcode->CodeOffset;
1345 }
1346
1347 guint
1348 mono_arch_unwindinfo_get_size (gpointer monoui)
1349 {
1350         PMonoUnwindInfo unwindinfo;
1351         if (!monoui)
1352                 return 0;
1353         
1354         unwindinfo = (MonoUnwindInfo*)monoui;
1355         return (8 + sizeof (MonoUnwindInfo)) - 
1356                 (sizeof (UNWIND_CODE) * (MONO_MAX_UNWIND_CODES - unwindinfo->unwindInfo.CountOfCodes));
1357 }
1358
1359 PRUNTIME_FUNCTION
1360 MONO_GET_RUNTIME_FUNCTION_CALLBACK ( DWORD64 ControlPc, IN PVOID Context )
1361 {
1362         MonoJitInfo *ji;
1363         guint64 pos;
1364         PMonoUnwindInfo targetinfo;
1365         MonoDomain *domain = mono_domain_get ();
1366
1367         ji = mini_jit_info_table_find (domain, (char*)ControlPc, NULL);
1368         if (!ji)
1369                 return 0;
1370
1371         pos = (guint64)(((char*)ji->code_start) + ji->code_size);
1372         
1373         targetinfo = (PMonoUnwindInfo)ALIGN_TO (pos, 8);
1374
1375         targetinfo->runtimeFunction.UnwindData = ((DWORD64)&targetinfo->unwindInfo) - ((DWORD64)Context);
1376
1377         return &targetinfo->runtimeFunction;
1378 }
1379
1380 void
1381 mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint code_size)
1382 {
1383         PMonoUnwindInfo unwindinfo, targetinfo;
1384         guchar codecount;
1385         guint64 targetlocation;
1386         if (!*monoui)
1387                 return;
1388
1389         unwindinfo = (MonoUnwindInfo*)*monoui;
1390         targetlocation = (guint64)&(((guchar*)code)[code_size]);
1391         targetinfo = (PMonoUnwindInfo) ALIGN_TO(targetlocation, 8);
1392
1393         unwindinfo->runtimeFunction.EndAddress = code_size;
1394         unwindinfo->runtimeFunction.UnwindData = ((guchar*)&targetinfo->unwindInfo) - ((guchar*)code);
1395         
1396         memcpy (targetinfo, unwindinfo, sizeof (MonoUnwindInfo) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
1397         
1398         codecount = unwindinfo->unwindInfo.CountOfCodes;
1399         if (codecount) {
1400                 memcpy (&targetinfo->unwindInfo.UnwindCode[0], &unwindinfo->unwindInfo.UnwindCode[MONO_MAX_UNWIND_CODES-codecount], 
1401                         sizeof (UNWIND_CODE) * unwindinfo->unwindInfo.CountOfCodes);
1402         }
1403
1404         g_free (unwindinfo);
1405         *monoui = 0;
1406
1407         RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
1408 }
1409
1410 #endif
1411
1412 #if MONO_SUPPORT_TASKLETS
1413 MonoContinuationRestore
1414 mono_tasklets_arch_restore (void)
1415 {
1416         static guint8* saved = NULL;
1417         guint8 *code, *start;
1418         int cont_reg = AMD64_R9; /* register usable on both call conventions */
1419         const guint kMaxCodeSize = NACL_SIZE (64, 128);
1420         
1421
1422         if (saved)
1423                 return (MonoContinuationRestore)saved;
1424         code = start = mono_global_codeman_reserve (kMaxCodeSize);
1425         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1426         /* cont is in AMD64_ARG_REG1 ($rcx or $rdi)
1427          * state is in AMD64_ARG_REG2 ($rdx or $rsi)
1428          * lmf_addr is in AMD64_ARG_REG3 ($r8 or $rdx)
1429          * We move cont to cont_reg since we need both rcx and rdi for the copy
1430          * state is moved to $rax so it's setup as the return value and we can overwrite $rsi
1431          */
1432         amd64_mov_reg_reg (code, cont_reg, MONO_AMD64_ARG_REG1, 8);
1433         amd64_mov_reg_reg (code, AMD64_RAX, MONO_AMD64_ARG_REG2, 8);
1434         /* setup the copy of the stack */
1435         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, G_STRUCT_OFFSET (MonoContinuation, stack_used_size), sizeof (int));
1436         amd64_shift_reg_imm (code, X86_SHR, AMD64_RCX, 3);
1437         x86_cld (code);
1438         amd64_mov_reg_membase (code, AMD64_RSI, cont_reg, G_STRUCT_OFFSET (MonoContinuation, saved_stack), sizeof (gpointer));
1439         amd64_mov_reg_membase (code, AMD64_RDI, cont_reg, G_STRUCT_OFFSET (MonoContinuation, return_sp), sizeof (gpointer));
1440         amd64_prefix (code, X86_REP_PREFIX);
1441         amd64_movsl (code);
1442
1443         /* now restore the registers from the LMF */
1444         amd64_mov_reg_membase (code, AMD64_RCX, cont_reg, G_STRUCT_OFFSET (MonoContinuation, lmf), 8);
1445         amd64_mov_reg_membase (code, AMD64_RBX, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, rbx), 8);
1446         amd64_mov_reg_membase (code, AMD64_RBP, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, rbp), 8);
1447         amd64_mov_reg_membase (code, AMD64_R12, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, r12), 8);
1448         amd64_mov_reg_membase (code, AMD64_R13, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, r13), 8);
1449         amd64_mov_reg_membase (code, AMD64_R14, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, r14), 8);
1450 #if !defined(__native_client_codegen__)
1451         amd64_mov_reg_membase (code, AMD64_R15, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, r15), 8);
1452 #endif
1453 #ifdef TARGET_WIN32
1454         amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, rdi), 8);
1455         amd64_mov_reg_membase (code, AMD64_RSI, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, rsi), 8);
1456 #endif
1457         amd64_mov_reg_membase (code, AMD64_RSP, AMD64_RCX, G_STRUCT_OFFSET (MonoLMF, rsp), 8);
1458
1459         /* restore the lmf chain */
1460         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1461         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1462
1463         /* state is already in rax */
1464         amd64_jump_membase (code, cont_reg, G_STRUCT_OFFSET (MonoContinuation, return_ip));
1465         g_assert ((code - start) <= kMaxCodeSize);
1466
1467         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
1468
1469         saved = start;
1470         return (MonoContinuationRestore)saved;
1471 }
1472 #endif
1473
1474 /*
1475  * mono_arch_setup_resume_sighandler_ctx:
1476  *
1477  *   Setup CTX so execution continues at FUNC.
1478  */
1479 void
1480 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1481 {
1482         /* 
1483          * When resuming from a signal handler, the stack should be misaligned, just like right after
1484          * a call.
1485          */
1486         if ((((guint64)MONO_CONTEXT_GET_SP (ctx)) % 16) == 0)
1487                 MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
1488         MONO_CONTEXT_SET_IP (ctx, func);
1489 }