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