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