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