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