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