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