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