9a3d76d4476ea2ca501aad1014a8cb901500d3a5
[mono.git] / mono / mini / tramp-amd64.c
1 /*
2  * tramp-amd64.c: JIT trampoline code for amd64
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2001 Ximian, Inc.
9  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
10  */
11
12 #include <config.h>
13 #include <glib.h>
14
15 #include <mono/metadata/appdomain.h>
16 #include <mono/metadata/marshal.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/mono-debug-debugger.h>
19 #include <mono/metadata/monitor.h>
20 #include <mono/metadata/monitor.h>
21 #include <mono/metadata/gc-internal.h>
22 #include <mono/arch/amd64/amd64-codegen.h>
23
24 #include <mono/utils/memcheck.h>
25
26 #include "mini.h"
27 #include "mini-amd64.h"
28
29 #if defined(__native_client_codegen__) && defined(__native_client__)
30 #include <malloc.h>
31 #include <sys/nacl_syscalls.h>
32 #endif
33
34 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
35
36 static guint8* nullified_class_init_trampoline;
37
38 /*
39  * mono_arch_get_unbox_trampoline:
40  * @m: method pointer
41  * @addr: pointer to native code for @m
42  *
43  * when value type methods are called through the vtable we need to unbox the
44  * this argument. This method returns a pointer to a trampoline which does
45  * unboxing before calling the method
46  */
47 gpointer
48 mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
49 {
50         guint8 *code, *start;
51         int this_reg;
52
53         MonoDomain *domain = mono_domain_get ();
54
55         this_reg = mono_arch_get_this_arg_reg (NULL);
56
57         start = code = mono_domain_code_reserve (domain, 20);
58
59         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
60         /* FIXME: Optimize this */
61         amd64_mov_reg_imm (code, AMD64_RAX, addr);
62         amd64_jump_reg (code, AMD64_RAX);
63         g_assert ((code - start) < 20);
64
65         nacl_domain_code_validate (domain, &start, 20, &code);
66
67         mono_arch_flush_icache (start, code - start);
68
69         return start;
70 }
71
72 /*
73  * mono_arch_get_static_rgctx_trampoline:
74  *
75  *   Create a trampoline which sets RGCTX_REG to MRGCTX, then jumps to ADDR.
76  */
77 gpointer
78 mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
79 {
80         guint8 *code, *start;
81         int buf_len;
82
83         MonoDomain *domain = mono_domain_get ();
84
85 #ifdef MONO_ARCH_NOMAP32BIT
86         buf_len = 32;
87 #else
88         /* AOTed code could still have a non-32 bit address */
89         if ((((guint64)addr) >> 32) == 0)
90                 buf_len = 16;
91         else
92                 buf_len = 30;
93 #endif
94
95         start = code = mono_domain_code_reserve (domain, buf_len);
96
97         amd64_mov_reg_imm (code, MONO_ARCH_RGCTX_REG, mrgctx);
98         amd64_jump_code (code, addr);
99         g_assert ((code - start) < buf_len);
100
101         nacl_domain_code_validate (domain, &start, buf_len, &code);
102         mono_arch_flush_icache (start, code - start);
103
104         return start;
105 }
106
107 gpointer
108 mono_arch_get_llvm_imt_trampoline (MonoDomain *domain, MonoMethod *m, int vt_offset)
109 {
110         guint8 *code, *start;
111         int buf_len;
112         int this_reg;
113
114         buf_len = 32;
115
116         start = code = mono_domain_code_reserve (domain, buf_len);
117
118         this_reg = mono_arch_get_this_arg_reg (NULL);
119
120         /* Set imt arg */
121         amd64_mov_reg_imm (code, MONO_ARCH_IMT_REG, m);
122         /* Load vtable address */
123         amd64_mov_reg_membase (code, AMD64_RAX, this_reg, 0, 8);
124         amd64_jump_membase (code, AMD64_RAX, vt_offset);
125         amd64_ret (code);
126
127         g_assert ((code - start) < buf_len);
128
129         nacl_domain_code_validate (domain, &start, buf_len, &code);
130
131         mono_arch_flush_icache (start, code - start);
132
133         return start;
134 }
135
136 /*
137  * mono_arch_patch_callsite:
138  *
139  *   Patch the callsite whose address is given by ORIG_CODE so it calls ADDR. ORIG_CODE
140  * points to the pc right after the call.
141  */
142 void
143 mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
144 {
145 #if defined(__default_codegen__)
146         guint8 *code;
147         guint8 buf [16];
148         gboolean can_write = mono_breakpoint_clean_code (method_start, orig_code, 14, buf, sizeof (buf));
149
150         code = buf + 14;
151
152         /* mov 64-bit imm into r11 (followed by call reg?)  or direct call*/
153         if (((code [-13] == 0x49) && (code [-12] == 0xbb)) || (code [-5] == 0xe8)) {
154                 if (code [-5] != 0xe8) {
155                         if (can_write) {
156                                 InterlockedExchangePointer ((gpointer*)(orig_code - 11), addr);
157                                 VALGRIND_DISCARD_TRANSLATIONS (orig_code - 11, sizeof (gpointer));
158                         }
159                 } else {
160                         if ((((guint64)(addr)) >> 32) != 0) {
161 #ifdef MONO_ARCH_NOMAP32BIT
162                                 /* Print some diagnostics */
163                                 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char*)orig_code);
164                                 if (ji)
165                                         fprintf (stderr, "At %s, offset 0x%zx\n", mono_method_full_name (ji->method, TRUE), (guint8*)orig_code - (guint8*)ji->code_start);
166                                 fprintf (stderr, "Addr: %p\n", addr);
167                                 ji = mono_jit_info_table_find (mono_domain_get (), (char*)addr);
168                                 if (ji)
169                                         fprintf (stderr, "Callee: %s\n", mono_method_full_name (ji->method, TRUE));
170                                 g_assert_not_reached ();
171 #else
172                                 /* 
173                                  * This might happen when calling AOTed code. Create a thunk.
174                                  */
175                                 guint8 *thunk_start, *thunk_code;
176
177                                 thunk_start = thunk_code = mono_domain_code_reserve (mono_domain_get (), 32);
178                                 amd64_jump_membase (thunk_code, AMD64_RIP, 0);
179                                 *(guint64*)thunk_code = (guint64)addr;
180                                 addr = thunk_start;
181                                 g_assert ((((guint64)(addr)) >> 32) == 0);
182                                 mono_arch_flush_icache (thunk_start, thunk_code - thunk_start);
183 #endif
184                         }
185                         g_assert ((((guint64)(orig_code)) >> 32) == 0);
186                         if (can_write) {
187                                 InterlockedExchange ((gint32*)(orig_code - 4), ((gint64)addr - (gint64)orig_code));
188                                 VALGRIND_DISCARD_TRANSLATIONS (orig_code - 5, 4);
189                         }
190                 }
191         }
192         else if ((code [-7] == 0x41) && (code [-6] == 0xff) && (code [-5] == 0x15)) {
193                 /* call *<OFFSET>(%rip) */
194                 gpointer *got_entry = (gpointer*)((guint8*)orig_code + (*(guint32*)(orig_code - 4)));
195                 if (can_write) {
196                         InterlockedExchangePointer (got_entry, addr);
197                         VALGRIND_DISCARD_TRANSLATIONS (orig_code - 5, sizeof (gpointer));
198                 }
199         }
200 #elif defined(__native_client__)
201         /* These are essentially the same 2 cases as above, modified for NaCl*/
202
203         /* Target must be bundle-aligned */
204         g_assert (((guint32)addr & kNaClAlignmentMask) == 0);
205         /* Return target must be bundle-aligned */
206         g_assert (((guint32)orig_code & kNaClAlignmentMask) == 0);
207
208         if (orig_code[-5] == 0xe8) {
209                 /* Direct call */
210                 int ret;
211                 gint32 offset = (gint32)addr - (gint32)orig_code;
212                 guint8 buf[sizeof(gint32)];
213                 *((gint32*)(buf)) = offset;
214                 ret = nacl_dyncode_modify (orig_code - sizeof(gint32), buf, sizeof(gint32));
215                 g_assert (ret == 0);
216         }
217
218         else if (is_nacl_call_reg_sequence (orig_code - 10) && orig_code[-16] == 0x41 && orig_code[-15] == 0xbb) {
219                 int ret;
220                 guint8 buf[sizeof(gint32)];
221                 *((gint32 *)(buf)) = addr;
222                 /* orig_code[-14] is the start of the immediate. */
223                 ret = nacl_dyncode_modify (orig_code - 14, buf, sizeof(gint32));
224                 g_assert (ret == 0);
225         }
226         else {
227                 g_assert_not_reached ();
228         }
229
230         return;
231 #endif
232 }
233
234 void
235 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
236 {
237         gint32 disp;
238         gpointer *plt_jump_table_entry;
239
240 #if defined(__default_codegen__)
241         /* A PLT entry: jmp *<DISP>(%rip) */
242         g_assert (code [0] == 0xff);
243         g_assert (code [1] == 0x25);
244
245         disp = *(gint32*)(code + 2);
246
247         plt_jump_table_entry = (gpointer*)(code + 6 + disp);
248 #elif defined(__native_client_codegen__)
249         /* A PLT entry:            */
250         /* mov <DISP>(%rip), %r11d */
251         /* nacljmp *%r11           */
252
253         /* Verify the 'mov' */
254         g_assert (code [0] == 0x45);
255         g_assert (code [1] == 0x8b);
256         g_assert (code [2] == 0x1d);
257
258         disp = *(gint32*)(code + 3);
259
260         /* 7 = 3 (mov opcode) + 4 (disp) */
261         /* This needs to resolve to the target of the RIP-relative offset */
262         plt_jump_table_entry = (gpointer*)(code + 7 + disp);
263
264 #endif /* __native_client_codegen__ */
265
266
267         InterlockedExchangePointer (plt_jump_table_entry, addr);
268 }
269
270 static gpointer
271 get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
272 {
273         guint8 buf [10];
274         gint32 disp;
275         MonoJitInfo *ji = NULL;
276
277 #ifdef ENABLE_LLVM
278         /* code - 9 might be before the start of the method */
279         /* FIXME: Avoid this expensive call somehow */
280         ji = mono_jit_info_table_find (mono_domain_get (), (char*)code);
281 #endif
282
283         mono_breakpoint_clean_code (ji ? ji->code_start : NULL, code, 9, buf, sizeof (buf));
284         code = buf + 9;
285
286         *displacement = 0;
287
288         code -= 7;
289
290         if ((code [0] == 0x41) && (code [1] == 0xff) && (code [2] == 0x15)) {
291                 /* call OFFSET(%rip) */
292                 g_assert_not_reached ();
293                 *displacement = *(guint32*)(code + 3);
294                 return (gpointer*)(code + disp + 7);
295         } else {
296                 g_assert_not_reached ();
297                 return NULL;
298         }
299 }
300
301 static gpointer*
302 get_vcall_slot_addr (guint8* code, mgreg_t *regs)
303 {
304         gpointer vt;
305         int displacement;
306         vt = get_vcall_slot (code, regs, &displacement);
307         if (!vt)
308                 return NULL;
309         return (gpointer*)((char*)vt + displacement);
310 }
311
312 void
313 mono_arch_nullify_class_init_trampoline (guint8 *code, mgreg_t *regs)
314 {
315         guint8 buf [16];
316         MonoJitInfo *ji = NULL;
317         gboolean can_write;
318
319         if (mono_use_llvm) {
320                 /* code - 7 might be before the start of the method */
321                 /* FIXME: Avoid this expensive call somehow */
322                 ji = mono_jit_info_table_find (mono_domain_get (), (char*)code);
323         }
324
325         can_write = mono_breakpoint_clean_code (ji ? ji->code_start : NULL, code, 7, buf, sizeof (buf));
326
327         if (!can_write)
328                 return;
329
330         /* 
331          * A given byte sequence can match more than case here, so we have to be
332          * really careful about the ordering of the cases. Longer sequences
333          * come first.
334          */
335         if ((buf [0] == 0x41) && (buf [1] == 0xff) && (buf [2] == 0x15)) {
336                 gpointer *vtable_slot;
337
338                 /* call *<OFFSET>(%rip) */
339                 vtable_slot = get_vcall_slot_addr (code, regs);
340                 g_assert (vtable_slot);
341
342                 *vtable_slot = nullified_class_init_trampoline;
343         } else if (buf [2] == 0xe8) {
344                 /* call <TARGET> */
345                 //guint8 *buf = code - 2;
346
347                 /* 
348                  * It would be better to replace the call with nops, but that doesn't seem
349                  * to work on SMP machines even when the whole call is inside a cache line.
350                  * Patching the call address seems to work.
351                  */
352                 /*
353                 buf [0] = 0x66;
354                 buf [1] = 0x66;
355                 buf [2] = 0x90;
356                 buf [3] = 0x66;
357                 buf [4] = 0x90;
358                 */
359
360                 mono_arch_patch_callsite (code - 5, code, nullified_class_init_trampoline);
361         } else if ((buf [5] == 0xff) && x86_modrm_mod (buf [6]) == 3 && x86_modrm_reg (buf [6]) == 2) {
362                 /* call *<reg> */
363                 /* Generated by the LLVM JIT or on platforms without MAP_32BIT set */
364                 mono_arch_patch_callsite (code - 13, code, nullified_class_init_trampoline);
365         } else if (buf [4] == 0x90 || buf [5] == 0xeb || buf [6] == 0x66) {
366                 /* Already changed by another thread */
367                 ;
368         } else {
369                 printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", buf [0], buf [1], buf [2], buf [3],
370                         buf [4], buf [5], buf [6]);
371                 g_assert_not_reached ();
372         }
373 }
374
375 void
376 mono_arch_nullify_plt_entry (guint8 *code, mgreg_t *regs)
377 {
378         if (mono_aot_only && !nullified_class_init_trampoline)
379                 nullified_class_init_trampoline = mono_aot_get_trampoline ("nullified_class_init_trampoline");
380
381         mono_arch_patch_plt_entry (code, NULL, regs, nullified_class_init_trampoline);
382 }
383
384 guchar*
385 mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
386 {
387         guint8 *buf, *code, *tramp, *br [2], *r11_save_code, *after_r11_save_code;
388         int i, lmf_offset, offset, res_offset, arg_offset, rax_offset, tramp_offset, saved_regs_offset;
389         int saved_fpregs_offset, rbp_offset, framesize, orig_rsp_to_rbp_offset, cfa_offset;
390         gboolean has_caller;
391         GSList *unwind_ops = NULL;
392         MonoJumpInfo *ji = NULL;
393         const guint kMaxCodeSize = NACL_SIZE (548, 548*2);
394
395 #if defined(__native_client_codegen__)
396         const guint kNaClTrampOffset = 17;
397 #endif
398
399         if (tramp_type == MONO_TRAMPOLINE_JUMP)
400                 has_caller = FALSE;
401         else
402                 has_caller = TRUE;
403
404         code = buf = mono_global_codeman_reserve (kMaxCodeSize);
405
406         framesize = kMaxCodeSize + sizeof (MonoLMF);
407         framesize = (framesize + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
408
409         orig_rsp_to_rbp_offset = 0;
410         r11_save_code = code;
411         /* Reserve 5 bytes for the mov_membase_reg to save R11 */
412         code += 5;
413         after_r11_save_code = code;
414
415         // CFA = sp + 16 (the trampoline address is on the stack)
416         cfa_offset = 16;
417         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, AMD64_RSP, 16);
418         // IP saved at CFA - 8
419         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RIP, -8);
420
421         /* Pop the return address off the stack */
422         amd64_pop_reg (code, AMD64_R11);
423         orig_rsp_to_rbp_offset += sizeof(mgreg_t);
424
425         cfa_offset -= sizeof(mgreg_t);
426         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
427
428         /* 
429          * Allocate a new stack frame
430          */
431         amd64_push_reg (code, AMD64_RBP);
432         cfa_offset += sizeof(mgreg_t);
433         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
434         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RBP, - cfa_offset);
435
436         orig_rsp_to_rbp_offset -= sizeof(mgreg_t);
437         amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
438         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, AMD64_RBP);
439         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, framesize);
440
441         offset = 0;
442         rbp_offset = - offset;
443
444         offset += sizeof(mgreg_t);
445         rax_offset = - offset;
446
447         offset += sizeof(mgreg_t);
448         tramp_offset = - offset;
449
450         offset += sizeof(gpointer);
451         arg_offset = - offset;
452
453         /* Compute the trampoline address from the return address */
454         if (aot) {
455 #if defined(__default_codegen__)
456                 /* 7 = length of call *<offset>(rip) */
457                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 7);
458 #elif defined(__native_client_codegen__)
459                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, kNaClTrampOffset);
460 #endif
461         } else {
462                 /* 5 = length of amd64_call_membase () */
463                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 5);
464         }
465         amd64_mov_membase_reg (code, AMD64_RBP, tramp_offset, AMD64_R11, sizeof(gpointer));
466
467         offset += sizeof(mgreg_t);
468         res_offset = - offset;
469
470         /* Save all registers */
471
472         offset += AMD64_NREG * sizeof(mgreg_t);
473         saved_regs_offset = - offset;
474         for (i = 0; i < AMD64_NREG; ++i) {
475                 if (i == AMD64_RBP) {
476                         /* RAX is already saved */
477                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, rbp_offset, sizeof(mgreg_t));
478                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), AMD64_RAX, sizeof(mgreg_t));
479                 } else if (i != AMD64_R11) {
480                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
481                 } else {
482                         /* We have to save R11 right at the start of
483                            the trampoline code because it's used as a
484                            scratch register */
485                         amd64_mov_membase_reg (r11_save_code, AMD64_RSP, saved_regs_offset + orig_rsp_to_rbp_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
486                         g_assert (r11_save_code == after_r11_save_code);
487                 }
488         }
489         offset += 8 * sizeof(mgreg_t);
490         saved_fpregs_offset = - offset;
491         for (i = 0; i < 8; ++i)
492                 amd64_movsd_membase_reg (code, AMD64_RBP, saved_fpregs_offset + (i * sizeof(mgreg_t)), i);
493
494         if (tramp_type != MONO_TRAMPOLINE_GENERIC_CLASS_INIT &&
495                         tramp_type != MONO_TRAMPOLINE_MONITOR_ENTER &&
496                         tramp_type != MONO_TRAMPOLINE_MONITOR_EXIT) {
497                 /* Obtain the trampoline argument which is encoded in the instruction stream */
498                 if (aot) {
499                         /* Load the GOT offset */
500                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, sizeof(gpointer));
501 #if defined(__default_codegen__)
502                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 7, 4);
503 #elif defined(__native_client_codegen__)
504                         /* The arg is hidden in a "push imm32" instruction, */
505                         /* add one to skip the opcode.                      */
506                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, kNaClTrampOffset+1, 4);
507 #endif
508                         /* Compute the address of the GOT slot */
509                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_R11, AMD64_RAX, sizeof(gpointer));
510                         /* Load the value */
511                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, sizeof(gpointer));
512                 } else {                        
513                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, sizeof(gpointer));
514 #if defined(__default_codegen__)
515                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 5, 1);
516                         amd64_widen_reg (code, AMD64_RAX, AMD64_RAX, TRUE, FALSE);
517                         amd64_alu_reg_imm_size (code, X86_CMP, AMD64_RAX, 4, 1);
518                         br [0] = code;
519                         x86_branch8 (code, X86_CC_NE, 6, FALSE);
520                         /* 32 bit immediate */
521                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
522                         br [1] = code;
523                         x86_jump8 (code, 10);
524                         /* 64 bit immediate */
525                         mono_amd64_patch (br [0], code);
526                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 8);
527                         mono_amd64_patch (br [1], code);
528 #elif defined(__native_client_codegen__)
529                         /* All args are 32-bit pointers in NaCl */
530                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
531 #endif
532                 }
533                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, sizeof(gpointer));
534         } else {
535                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, saved_regs_offset + (MONO_AMD64_ARG_REG1 * sizeof(mgreg_t)), sizeof(mgreg_t));
536                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, sizeof(gpointer));
537         }
538
539         /* Save LMF begin */
540
541         offset += sizeof (MonoLMF);
542         lmf_offset = - offset;
543
544         /* Save ip */
545         if (has_caller)
546                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, 8, sizeof(gpointer));
547         else
548                 amd64_mov_reg_imm (code, AMD64_R11, 0);
549         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), AMD64_R11, sizeof(mgreg_t));
550         /* Save fp */
551         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, framesize, sizeof(mgreg_t));
552         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), AMD64_R11, sizeof(mgreg_t));
553         /* Save sp */
554         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RSP, sizeof(mgreg_t));
555         amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, framesize + 16);
556         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_R11, sizeof(mgreg_t));
557         /* Save method */
558         if (tramp_type == MONO_TRAMPOLINE_JIT || tramp_type == MONO_TRAMPOLINE_JUMP) {
559                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, arg_offset, sizeof(gpointer));
560                 amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), AMD64_R11, sizeof(gpointer));
561         } else {
562                 amd64_mov_membase_imm (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), 0, sizeof(gpointer));
563         }
564         /* Save callee saved regs */
565 #ifdef TARGET_WIN32
566         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), AMD64_RDI, sizeof(mgreg_t));
567         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), AMD64_RSI, sizeof(mgreg_t));
568 #endif
569         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), AMD64_RBX, sizeof(mgreg_t));
570         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), AMD64_R12, sizeof(mgreg_t));
571         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), AMD64_R13, sizeof(mgreg_t));
572         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), AMD64_R14, sizeof(mgreg_t));
573         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), AMD64_R15, sizeof(mgreg_t));
574
575         if (aot) {
576                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_get_lmf_addr");
577         } else {
578                 amd64_mov_reg_imm (code, AMD64_R11, mono_get_lmf_addr);
579         }
580         amd64_call_reg (code, AMD64_R11);
581
582         /* Save lmf_addr */
583         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, sizeof(gpointer));
584         /* Save previous_lmf */
585         /* Set the lowest bit to 1 to signal that this LMF has the ip field set */
586         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
587         amd64_alu_reg_imm_size (code, X86_ADD, AMD64_R11, 1, sizeof(gpointer));
588         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
589         /* Set new lmf */
590         amd64_lea_membase (code, AMD64_R11, AMD64_RBP, lmf_offset);
591         amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
592
593         /* Save LMF end */
594
595         /* Arg1 is the pointer to the saved registers */
596         amd64_lea_membase (code, AMD64_ARG_REG1, AMD64_RBP, saved_regs_offset);
597
598         /* Arg2 is the address of the calling code */
599         if (has_caller)
600                 amd64_mov_reg_membase (code, AMD64_ARG_REG2, AMD64_RBP, 8, sizeof(gpointer));
601         else
602                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
603
604         /* Arg3 is the method/vtable ptr */
605         amd64_mov_reg_membase (code, AMD64_ARG_REG3, AMD64_RBP, arg_offset, sizeof(gpointer));
606
607         /* Arg4 is the trampoline address */
608         amd64_mov_reg_membase (code, AMD64_ARG_REG4, AMD64_RBP, tramp_offset, sizeof(gpointer));
609
610         if (aot) {
611                 char *icall_name = g_strdup_printf ("trampoline_func_%d", tramp_type);
612                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
613         } else {
614                 tramp = (guint8*)mono_get_trampoline_func (tramp_type);
615                 amd64_mov_reg_imm (code, AMD64_R11, tramp);
616         }
617         amd64_call_reg (code, AMD64_R11);
618
619         /* Check for thread interruption */
620         /* This is not perf critical code so no need to check the interrupt flag */
621         /* 
622          * Have to call the _force_ variant, since there could be a protected wrapper on the top of the stack.
623          */
624         amd64_mov_membase_reg (code, AMD64_RBP, res_offset, AMD64_RAX, sizeof(mgreg_t));
625         if (aot) {
626                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_force_interruption_checkpoint");
627         } else {
628                 amd64_mov_reg_imm (code, AMD64_R11, (guint8*)mono_thread_force_interruption_checkpoint);
629         }
630         amd64_call_reg (code, AMD64_R11);
631
632         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, res_offset, sizeof(mgreg_t));        
633
634         /* Restore LMF */
635
636         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
637         amd64_alu_reg_imm_size (code, X86_SUB, AMD64_RCX, 1, sizeof(gpointer));
638         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof(gpointer));
639         amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, sizeof(gpointer));
640
641         /* 
642          * Save rax to the stack, after the leave instruction, this will become part of
643          * the red zone.
644          */
645         amd64_mov_membase_reg (code, AMD64_RBP, rax_offset, AMD64_RAX, sizeof(mgreg_t));
646
647         /* Restore argument registers, r10 (imt method/rgxtx)
648            and rax (needed for direct calls to C vararg functions). */
649         for (i = 0; i < AMD64_NREG; ++i)
650                 if (AMD64_IS_ARGUMENT_REG (i) || i == AMD64_R10 || i == AMD64_RAX)
651                         amd64_mov_reg_membase (code, i, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), sizeof(mgreg_t));
652
653         for (i = 0; i < 8; ++i)
654                 amd64_movsd_reg_membase (code, i, AMD64_RBP, saved_fpregs_offset + (i * sizeof(mgreg_t)));
655
656         /* Restore stack */
657         amd64_leave (code);
658
659         if (MONO_TRAMPOLINE_TYPE_MUST_RETURN (tramp_type)) {
660                 /* Load result */
661                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, rax_offset - sizeof(mgreg_t), sizeof(mgreg_t));
662                 amd64_ret (code);
663         } else {
664                 /* call the compiled method using the saved rax */
665                 amd64_jump_membase (code, AMD64_RSP, rax_offset - sizeof(mgreg_t));
666         }
667
668         g_assert ((code - buf) <= kMaxCodeSize);
669
670         nacl_global_codeman_validate (&buf, kMaxCodeSize, &code);
671
672         mono_arch_flush_icache (buf, code - buf);
673
674         if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT) {
675                 /* Initialize the nullified class init trampoline used in the AOT case */
676                 nullified_class_init_trampoline = mono_arch_get_nullified_class_init_trampoline (NULL);
677         }
678
679         if (info)
680                 *info = mono_tramp_info_create (mono_get_generic_trampoline_name (tramp_type), buf, code - buf, ji, unwind_ops);
681
682         return buf;
683 }
684
685 gpointer
686 mono_arch_get_nullified_class_init_trampoline (MonoTrampInfo **info)
687 {
688         guint8 *code, *buf;
689
690         code = buf = mono_global_codeman_reserve (16);
691         amd64_ret (code);
692
693         nacl_global_codeman_validate(&buf, 16, &code);
694
695         mono_arch_flush_icache (buf, code - buf);
696
697         if (info)
698                 *info = mono_tramp_info_create (g_strdup_printf ("nullified_class_init_trampoline"), buf, code - buf, NULL, NULL);
699
700         if (mono_jit_map_is_enabled ())
701                 mono_emit_jit_tramp (buf, code - buf, "nullified_class_init_trampoline");
702
703         return buf;
704 }
705
706 gpointer
707 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
708 {
709         guint8 *code, *buf, *tramp;
710         int size;
711         gboolean far_addr = FALSE;
712
713         tramp = mono_get_trampoline_code (tramp_type);
714
715 #if defined(__default_codegen__)
716         if ((((guint64)arg1) >> 32) == 0)
717                 size = 5 + 1 + 4;
718         else
719                 size = 5 + 1 + 8;
720
721         code = buf = mono_domain_code_reserve_align (domain, size, 1);
722
723         if (((gint64)tramp - (gint64)code) >> 31 != 0 && ((gint64)tramp - (gint64)code) >> 31 != -1) {
724 #ifndef MONO_ARCH_NOMAP32BIT
725                 g_assert_not_reached ();
726 #endif
727                 far_addr = TRUE;
728                 size += 16;
729                 code = buf = mono_domain_code_reserve_align (domain, size, 1);
730         }
731 #elif defined(__native_client_codegen__)
732         size = 5 + 1 + 4;
733         /* Aligning the call site below could */
734         /* add up to kNaClAlignment-1 bytes   */
735         size += (kNaClAlignment-1);
736         buf = mono_domain_code_reserve_align (domain, size, kNaClAlignment);
737         code = buf;
738 #endif
739
740         if (far_addr) {
741                 amd64_mov_reg_imm (code, AMD64_R11, tramp);
742                 amd64_call_reg (code, AMD64_R11);
743         } else {
744                 amd64_call_code (code, tramp);
745         }
746         /* The trampoline code will obtain the argument from the instruction stream */
747 #if defined(__default_codegen__)
748         if ((((guint64)arg1) >> 32) == 0) {
749                 *code = 0x4;
750                 *(guint32*)(code + 1) = (gint64)arg1;
751                 code += 5;
752         } else {
753                 *code = 0x8;
754                 *(guint64*)(code + 1) = (gint64)arg1;
755                 code += 9;
756         }
757 #elif defined(__native_client_codegen__)
758         /* For NaCl, all tramp args are 32-bit because they're pointers */
759         *code = 0x68; /* push imm32 */
760         *(guint32*)(code + 1) = (gint32)arg1;
761         code += 5;
762 #endif
763
764         g_assert ((code - buf) <= size);
765
766         if (code_len)
767                 *code_len = size;
768
769         nacl_domain_code_validate(domain, &buf, size, &code);
770
771         mono_arch_flush_icache (buf, size);
772
773         return buf;
774 }       
775
776 gpointer
777 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
778 {
779         guint8 *tramp;
780         guint8 *code, *buf;
781         guint8 **rgctx_null_jumps;
782         int tramp_size;
783         int depth, index;
784         int i;
785         gboolean mrgctx;
786         MonoJumpInfo *ji = NULL;
787         GSList *unwind_ops = NULL;
788
789         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
790         index = MONO_RGCTX_SLOT_INDEX (slot);
791         if (mrgctx)
792                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
793         for (depth = 0; ; ++depth) {
794                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
795
796                 if (index < size - 1)
797                         break;
798                 index -= size - 1;
799         }
800
801         tramp_size = NACL_SIZE (64 + 8 * depth, 128 + 8 * depth);
802
803         code = buf = mono_global_codeman_reserve (tramp_size);
804
805         unwind_ops = mono_arch_get_cie_program ();
806
807         rgctx_null_jumps = g_malloc (sizeof (guint8*) * (depth + 2));
808
809         if (mrgctx) {
810                 /* get mrgctx ptr */
811                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
812         } else {
813                 /* load rgctx ptr from vtable */
814                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context), sizeof(gpointer));
815                 /* is the rgctx ptr null? */
816                 amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
817                 /* if yes, jump to actual trampoline */
818                 rgctx_null_jumps [0] = code;
819                 amd64_branch8 (code, X86_CC_Z, -1, 1);
820         }
821
822         for (i = 0; i < depth; ++i) {
823                 /* load ptr to next array */
824                 if (mrgctx && i == 0)
825                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT, sizeof(gpointer));
826                 else
827                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, 0, sizeof(gpointer));
828                 /* is the ptr null? */
829                 amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
830                 /* if yes, jump to actual trampoline */
831                 rgctx_null_jumps [i + 1] = code;
832                 amd64_branch8 (code, X86_CC_Z, -1, 1);
833         }
834
835         /* fetch slot */
836         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, sizeof (gpointer) * (index + 1), sizeof(gpointer));
837         /* is the slot null? */
838         amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
839         /* if yes, jump to actual trampoline */
840         rgctx_null_jumps [depth + 1] = code;
841         amd64_branch8 (code, X86_CC_Z, -1, 1);
842         /* otherwise return */
843         amd64_ret (code);
844
845         for (i = mrgctx ? 1 : 0; i <= depth + 1; ++i)
846                 mono_amd64_patch (rgctx_null_jumps [i], code);
847
848         g_free (rgctx_null_jumps);
849
850         /* move the rgctx pointer to the VTABLE register */
851         amd64_mov_reg_reg (code, MONO_ARCH_VTABLE_REG, AMD64_ARG_REG1, sizeof(gpointer));
852
853         if (aot) {
854                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot));
855                 amd64_jump_reg (code, AMD64_R11);
856         } else {
857                 tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
858
859                 /* jump to the actual trampoline */
860                 amd64_jump_code (code, tramp);
861         }
862
863         nacl_global_codeman_validate (&buf, tramp_size, &code);
864         mono_arch_flush_icache (buf, code - buf);
865
866         g_assert (code - buf <= tramp_size);
867
868         if (info)
869                 *info = mono_tramp_info_create (mono_get_rgctx_fetch_trampoline_name (slot), buf, code - buf, ji, unwind_ops);
870
871         return buf;
872 }
873
874 gpointer
875 mono_arch_create_generic_class_init_trampoline (MonoTrampInfo **info, gboolean aot)
876 {
877         guint8 *tramp;
878         guint8 *code, *buf;
879         static int byte_offset = -1;
880         static guint8 bitmask;
881         guint8 *jump;
882         int tramp_size;
883         GSList *unwind_ops = NULL;
884         MonoJumpInfo *ji = NULL;
885
886         tramp_size = 64;
887
888         code = buf = mono_global_codeman_reserve (tramp_size);
889
890         if (byte_offset < 0)
891                 mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
892
893         amd64_test_membase_imm_size (code, MONO_AMD64_ARG_REG1, byte_offset, bitmask, 1);
894         jump = code;
895         amd64_branch8 (code, X86_CC_Z, -1, 1);
896
897         amd64_ret (code);
898
899         x86_patch (jump, code);
900
901         if (aot) {
902                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_generic_class_init");
903                 amd64_jump_reg (code, AMD64_R11);
904         } else {
905                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
906
907                 /* jump to the actual trampoline */
908                 amd64_jump_code (code, tramp);
909         }
910
911         nacl_global_codeman_validate (&buf, tramp_size, &code);
912
913         mono_arch_flush_icache (buf, code - buf);
914
915         g_assert (code - buf <= tramp_size);
916
917         if (info)
918                 *info = mono_tramp_info_create (g_strdup_printf ("generic_class_init_trampoline"), buf, code - buf, ji, unwind_ops);
919
920         return buf;
921 }
922
923 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
924
925 gpointer
926 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean aot)
927 {
928         guint8 *tramp;
929         guint8 *code, *buf;
930         guint8 *jump_obj_null, *jump_sync_null, *jump_cmpxchg_failed, *jump_other_owner, *jump_tid, *jump_sync_thin_hash = NULL;
931         int tramp_size;
932         int owner_offset, nest_offset, dummy;
933         MonoJumpInfo *ji = NULL;
934         GSList *unwind_ops = NULL;
935
936         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == AMD64_RDI);
937
938         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &dummy);
939         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
940         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
941         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
942         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
943
944         tramp_size = 96;
945
946         code = buf = mono_global_codeman_reserve (tramp_size);
947
948         unwind_ops = mono_arch_get_cie_program ();
949
950         if (mono_thread_get_tls_offset () != -1) {
951                 /* MonoObject* obj is in RDI */
952                 /* is obj null? */
953                 amd64_test_reg_reg (code, AMD64_RDI, AMD64_RDI);
954                 /* if yes, jump to actual trampoline */
955                 jump_obj_null = code;
956                 amd64_branch8 (code, X86_CC_Z, -1, 1);
957
958                 /* load obj->synchronization to RCX */
959                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RDI, G_STRUCT_OFFSET (MonoObject, synchronisation), 8);
960
961                 if (mono_gc_is_moving ()) {
962                         /*if bit zero is set it's a thin hash*/
963                         /*FIXME use testb encoding*/
964                         amd64_test_reg_imm (code, AMD64_RCX, 0x01);
965                         jump_sync_thin_hash = code;
966                         amd64_branch8 (code, X86_CC_NE, -1, 1);
967
968                         /*clear bits used by the gc*/
969                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, ~0x3);
970                 }
971
972                 /* is synchronization null? */
973                 amd64_test_reg_reg (code, AMD64_RCX, AMD64_RCX);
974                 /* if yes, jump to actual trampoline */
975                 jump_sync_null = code;
976                 amd64_branch8 (code, X86_CC_Z, -1, 1);
977
978                 /* load MonoInternalThread* into RDX */
979                 code = mono_amd64_emit_tls_get (code, AMD64_RDX, mono_thread_get_tls_offset ());
980                 /* load TID into RDX */
981                 amd64_mov_reg_membase (code, AMD64_RDX, AMD64_RDX, G_STRUCT_OFFSET (MonoInternalThread, tid), 8);
982
983                 /* is synchronization->owner null? */
984                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_RCX, owner_offset, 0, 8);
985                 /* if not, jump to next case */
986                 jump_tid = code;
987                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
988
989                 /* if yes, try a compare-exchange with the TID */
990                 /* zero RAX */
991                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
992                 /* compare and exchange */
993                 amd64_prefix (code, X86_LOCK_PREFIX);
994                 amd64_cmpxchg_membase_reg_size (code, AMD64_RCX, owner_offset, AMD64_RDX, 8);
995                 /* if not successful, jump to actual trampoline */
996                 jump_cmpxchg_failed = code;
997                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
998                 /* if successful, return */
999                 amd64_ret (code);
1000
1001                 /* next case: synchronization->owner is not null */
1002                 x86_patch (jump_tid, code);
1003                 /* is synchronization->owner == TID? */
1004                 amd64_alu_membase_reg_size (code, X86_CMP, AMD64_RCX, owner_offset, AMD64_RDX, 8);
1005                 /* if not, jump to actual trampoline */
1006                 jump_other_owner = code;
1007                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1008                 /* if yes, increment nest */
1009                 amd64_inc_membase_size (code, AMD64_RCX, nest_offset, 4);
1010                 /* return */
1011                 amd64_ret (code);
1012
1013                 x86_patch (jump_obj_null, code);
1014                 if (jump_sync_thin_hash)
1015                         x86_patch (jump_sync_thin_hash, code);
1016                 x86_patch (jump_sync_null, code);
1017                 x86_patch (jump_cmpxchg_failed, code);
1018                 x86_patch (jump_other_owner, code);
1019         }
1020
1021         /* jump to the actual trampoline */
1022 #if MONO_AMD64_ARG_REG1 != AMD64_RDI
1023         amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, AMD64_RDI);
1024 #endif
1025
1026         if (aot) {
1027                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_enter");
1028                 amd64_jump_reg (code, AMD64_R11);
1029         } else {
1030                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
1031
1032                 /* jump to the actual trampoline */
1033                 amd64_jump_code (code, tramp);
1034         }
1035
1036         nacl_global_codeman_validate (&buf, tramp_size, &code);
1037
1038         mono_arch_flush_icache (code, code - buf);
1039         g_assert (code - buf <= tramp_size);
1040
1041         if (info)
1042                 *info = mono_tramp_info_create (g_strdup_printf ("monitor_enter_trampoline"), buf, code - buf, ji, unwind_ops);
1043
1044         return buf;
1045 }
1046
1047 gpointer
1048 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
1049 {
1050         guint8 *tramp;
1051         guint8 *code, *buf;
1052         guint8 *jump_obj_null, *jump_have_waiters, *jump_sync_null, *jump_not_owned, *jump_sync_thin_hash = NULL;
1053         guint8 *jump_next;
1054         int tramp_size;
1055         int owner_offset, nest_offset, entry_count_offset;
1056         MonoJumpInfo *ji = NULL;
1057         GSList *unwind_ops = NULL;
1058
1059         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == AMD64_RDI);
1060
1061         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &entry_count_offset);
1062         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
1063         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
1064         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (entry_count_offset) == sizeof (gint32));
1065         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
1066         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
1067         entry_count_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (entry_count_offset);
1068
1069         tramp_size = 112;
1070
1071         code = buf = mono_global_codeman_reserve (tramp_size);
1072
1073         unwind_ops = mono_arch_get_cie_program ();
1074
1075         if (mono_thread_get_tls_offset () != -1) {
1076                 /* MonoObject* obj is in RDI */
1077                 /* is obj null? */
1078                 amd64_test_reg_reg (code, AMD64_RDI, AMD64_RDI);
1079                 /* if yes, jump to actual trampoline */
1080                 jump_obj_null = code;
1081                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1082
1083                 /* load obj->synchronization to RCX */
1084                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RDI, G_STRUCT_OFFSET (MonoObject, synchronisation), 8);
1085
1086                 if (mono_gc_is_moving ()) {
1087                         /*if bit zero is set it's a thin hash*/
1088                         /*FIXME use testb encoding*/
1089                         amd64_test_reg_imm (code, AMD64_RCX, 0x01);
1090                         jump_sync_thin_hash = code;
1091                         amd64_branch8 (code, X86_CC_NE, -1, 1);
1092
1093                         /*clear bits used by the gc*/
1094                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, ~0x3);
1095                 }
1096
1097                 /* is synchronization null? */
1098                 amd64_test_reg_reg (code, AMD64_RCX, AMD64_RCX);
1099                 /* if yes, jump to actual trampoline */
1100                 jump_sync_null = code;
1101                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1102
1103                 /* next case: synchronization is not null */
1104                 /* load MonoInternalThread* into RDX */
1105                 code = mono_amd64_emit_tls_get (code, AMD64_RDX, mono_thread_get_tls_offset ());
1106                 /* load TID into RDX */
1107                 amd64_mov_reg_membase (code, AMD64_RDX, AMD64_RDX, G_STRUCT_OFFSET (MonoInternalThread, tid), 8);
1108                 /* is synchronization->owner == TID */
1109                 amd64_alu_membase_reg_size (code, X86_CMP, AMD64_RCX, owner_offset, AMD64_RDX, 8);
1110                 /* if no, jump to actual trampoline */
1111                 jump_not_owned = code;
1112                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1113
1114                 /* next case: synchronization->owner == TID */
1115                 /* is synchronization->nest == 1 */
1116                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_RCX, nest_offset, 1, 4);
1117                 /* if not, jump to next case */
1118                 jump_next = code;
1119                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1120                 /* if yes, is synchronization->entry_count zero? */
1121                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_RCX, entry_count_offset, 0, 4);
1122                 /* if not, jump to actual trampoline */
1123                 jump_have_waiters = code;
1124                 amd64_branch8 (code, X86_CC_NZ, -1 , 1);
1125                 /* if yes, set synchronization->owner to null and return */
1126                 amd64_mov_membase_imm (code, AMD64_RCX, owner_offset, 0, 8);
1127                 amd64_ret (code);
1128
1129                 /* next case: synchronization->nest is not 1 */
1130                 x86_patch (jump_next, code);
1131                 /* decrease synchronization->nest and return */
1132                 amd64_dec_membase_size (code, AMD64_RCX, nest_offset, 4);
1133                 amd64_ret (code);
1134
1135                 x86_patch (jump_obj_null, code);
1136                 x86_patch (jump_have_waiters, code);
1137                 x86_patch (jump_not_owned, code);
1138                 x86_patch (jump_sync_null, code);
1139         }
1140
1141         /* jump to the actual trampoline */
1142 #if MONO_AMD64_ARG_REG1 != AMD64_RDI
1143         amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, AMD64_RDI);
1144 #endif
1145
1146         if (aot) {
1147                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_exit");
1148                 amd64_jump_reg (code, AMD64_R11);
1149         } else {
1150                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
1151                 amd64_jump_code (code, tramp);
1152         }
1153
1154         nacl_global_codeman_validate (&buf, tramp_size, &code);
1155
1156         mono_arch_flush_icache (code, code - buf);
1157         g_assert (code - buf <= tramp_size);
1158
1159         if (info)
1160                 *info = mono_tramp_info_create (g_strdup_printf ("monitor_exit_trampoline"), buf, code - buf, ji, unwind_ops);
1161
1162         return buf;
1163 }
1164 #endif
1165
1166 void
1167 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
1168 {
1169         /* FIXME: This is not thread safe */
1170         guint8 *code = ji->code_start;
1171
1172         amd64_mov_reg_imm (code, AMD64_ARG_REG1, func_arg);
1173         amd64_mov_reg_imm (code, AMD64_R11, func);
1174
1175         x86_push_imm (code, (guint64)func_arg);
1176         amd64_call_reg (code, AMD64_R11);
1177 }
1178
1179
1180 static void
1181 handler_block_trampoline_helper (gpointer *ptr)
1182 {
1183         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1184         *ptr = jit_tls->handler_block_return_address;
1185 }
1186
1187 gpointer
1188 mono_arch_create_handler_block_trampoline (void)
1189 {
1190         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1191         guint8 *code, *buf;
1192         int tramp_size = 64;
1193         code = buf = mono_global_codeman_reserve (tramp_size);
1194
1195         /*
1196         This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
1197         */
1198
1199         if (mono_get_jit_tls_offset () != -1) {
1200                 code = mono_amd64_emit_tls_get (code, AMD64_RDI, mono_get_jit_tls_offset ());
1201                 /*simulate a call*/
1202                 amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RDI, G_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 8);
1203                 amd64_jump_code (code, tramp);
1204         } else {
1205                 /*Slow path uses a c helper*/
1206                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RSP, 8);
1207                 amd64_mov_reg_imm (code, AMD64_RAX, tramp);
1208                 amd64_push_reg (code, AMD64_RAX);
1209                 amd64_jump_code (code, handler_block_trampoline_helper);
1210         }
1211
1212         mono_arch_flush_icache (buf, code - buf);
1213         g_assert (code - buf <= tramp_size);
1214
1215         if (mono_jit_map_is_enabled ())
1216                 mono_emit_jit_tramp (buf, code - buf, "handler_block_trampoline");
1217
1218         return buf;
1219 }
1220
1221 /*
1222  * mono_arch_get_call_target:
1223  *
1224  *   Return the address called by the code before CODE if exists.
1225  */
1226 guint8*
1227 mono_arch_get_call_target (guint8 *code)
1228 {
1229         if (code [-5] == 0xe8) {
1230                 guint32 disp = *(guint32*)(code - 4);
1231                 guint8 *target = code + disp;
1232
1233                 return target;
1234         } else {
1235                 return NULL;
1236         }
1237 }
1238
1239 /*
1240  * mono_arch_get_plt_info_offset:
1241  *
1242  *   Return the PLT info offset belonging to the plt entry PLT_ENTRY.
1243  */
1244 guint32
1245 mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
1246 {
1247 #if defined(__native_client__) || defined(__native_client_codegen__)
1248         /* 18 = 3 (mov opcode) + 4 (disp) + 10 (nacljmp) + 1 (push opcode) */
1249         /* See aot-compiler.c arch_emit_plt_entry for details.             */
1250         return *(guint32*)(plt_entry + 18);
1251 #else
1252         return *(guint32*)(plt_entry + 6);
1253 #endif
1254 }