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