Merge pull request #1298 from esdrubal/uploadfileasync
[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, MONO_AMD64_ARG_REG1, 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 gpointer
950 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean aot)
951 {
952         guint8 *tramp;
953         guint8 *code, *buf;
954         guint8 *jump_obj_null, *jump_sync_null, *jump_cmpxchg_failed, *jump_other_owner, *jump_tid, *jump_sync_thin_hash = NULL;
955         int tramp_size;
956         int owner_offset, nest_offset, dummy;
957         MonoJumpInfo *ji = NULL;
958         GSList *unwind_ops = NULL;
959         int obj_reg = MONO_AMD64_ARG_REG1;
960         int sync_reg = MONO_AMD64_ARG_REG2;
961         int tid_reg = MONO_AMD64_ARG_REG3;
962
963         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == obj_reg);
964
965         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &dummy);
966         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
967         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
968         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
969         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
970
971         tramp_size = 96;
972
973         code = buf = mono_global_codeman_reserve (tramp_size);
974
975         unwind_ops = mono_arch_get_cie_program ();
976
977         if (!aot && mono_thread_get_tls_offset () != -1) {
978                 /* MonoObject* obj is in obj_reg */
979                 /* is obj null? */
980                 amd64_test_reg_reg (code, obj_reg, obj_reg);
981                 /* if yes, jump to actual trampoline */
982                 jump_obj_null = code;
983                 amd64_branch8 (code, X86_CC_Z, -1, 1);
984
985                 /* load obj->synchronization to sync_reg */
986                 amd64_mov_reg_membase (code, sync_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, synchronisation), 8);
987
988                 if (mono_gc_is_moving ()) {
989                         /*if bit zero is set it's a thin hash*/
990                         /*FIXME use testb encoding*/
991                         amd64_test_reg_imm (code, sync_reg, 0x01);
992                         jump_sync_thin_hash = code;
993                         amd64_branch8 (code, X86_CC_NE, -1, 1);
994
995                         /*clear bits used by the gc*/
996                         amd64_alu_reg_imm (code, X86_AND, sync_reg, ~0x3);
997                 }
998
999                 /* is synchronization null? */
1000                 amd64_test_reg_reg (code, sync_reg, sync_reg);
1001                 /* if yes, jump to actual trampoline */
1002                 jump_sync_null = code;
1003                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1004
1005                 /* load MonoInternalThread* into tid_reg */
1006                 code = mono_amd64_emit_tls_get (code, tid_reg, mono_thread_get_tls_offset ());
1007                 /* load TID into tid_reg */
1008                 amd64_mov_reg_membase (code, tid_reg, tid_reg, MONO_STRUCT_OFFSET (MonoInternalThread, tid), 8);
1009
1010                 /* is synchronization->owner null? */
1011                 amd64_alu_membase_imm_size (code, X86_CMP, sync_reg, owner_offset, 0, 8);
1012                 /* if not, jump to next case */
1013                 jump_tid = code;
1014                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1015
1016                 /* if yes, try a compare-exchange with the TID */
1017                 g_assert (tid_reg != X86_EAX);
1018                 /* zero RAX */
1019                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
1020                 /* compare and exchange */
1021                 amd64_prefix (code, X86_LOCK_PREFIX);
1022                 amd64_cmpxchg_membase_reg_size (code, sync_reg, owner_offset, tid_reg, 8);
1023                 /* if not successful, jump to actual trampoline */
1024                 jump_cmpxchg_failed = code;
1025                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1026                 /* if successful, return */
1027                 amd64_ret (code);
1028
1029                 /* next case: synchronization->owner is not null */
1030                 x86_patch (jump_tid, code);
1031                 /* is synchronization->owner == TID? */
1032                 amd64_alu_membase_reg_size (code, X86_CMP, sync_reg, owner_offset, tid_reg, 8);
1033                 /* if not, jump to actual trampoline */
1034                 jump_other_owner = code;
1035                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1036                 /* if yes, increment nest */
1037                 amd64_inc_membase_size (code, sync_reg, nest_offset, 4);
1038                 /* return */
1039                 amd64_ret (code);
1040
1041                 x86_patch (jump_obj_null, code);
1042                 if (jump_sync_thin_hash)
1043                         x86_patch (jump_sync_thin_hash, code);
1044                 x86_patch (jump_sync_null, code);
1045                 x86_patch (jump_cmpxchg_failed, code);
1046                 x86_patch (jump_other_owner, code);
1047         }
1048
1049         /* jump to the actual trampoline */
1050         if (MONO_AMD64_ARG_REG1 != obj_reg)
1051                 amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, obj_reg, sizeof (mgreg_t));
1052
1053         if (aot) {
1054                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_enter");
1055                 amd64_jump_reg (code, AMD64_R11);
1056         } else {
1057                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
1058
1059                 /* jump to the actual trampoline */
1060                 amd64_jump_code (code, tramp);
1061         }
1062
1063         nacl_global_codeman_validate (&buf, tramp_size, &code);
1064
1065         mono_arch_flush_icache (code, code - buf);
1066         g_assert (code - buf <= tramp_size);
1067
1068         if (info)
1069                 *info = mono_tramp_info_create ("monitor_enter_trampoline", buf, code - buf, ji, unwind_ops);
1070
1071         return buf;
1072 }
1073
1074 gpointer
1075 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
1076 {
1077         guint8 *tramp;
1078         guint8 *code, *buf;
1079         guint8 *jump_obj_null, *jump_have_waiters, *jump_sync_null, *jump_not_owned, *jump_sync_thin_hash = NULL;
1080         guint8 *jump_next;
1081         int tramp_size;
1082         int owner_offset, nest_offset, entry_count_offset;
1083         MonoJumpInfo *ji = NULL;
1084         GSList *unwind_ops = NULL;
1085         int obj_reg = MONO_AMD64_ARG_REG1;
1086         int sync_reg = MONO_AMD64_ARG_REG2;
1087
1088         g_assert (obj_reg == MONO_ARCH_MONITOR_OBJECT_REG);
1089
1090         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &entry_count_offset);
1091         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
1092         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
1093         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (entry_count_offset) == sizeof (gint32));
1094         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
1095         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
1096         entry_count_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (entry_count_offset);
1097
1098         tramp_size = 112;
1099
1100         code = buf = mono_global_codeman_reserve (tramp_size);
1101
1102         unwind_ops = mono_arch_get_cie_program ();
1103
1104         if (!aot && mono_thread_get_tls_offset () != -1) {
1105                 /* MonoObject* obj is in obj_reg */
1106                 /* is obj null? */
1107                 amd64_test_reg_reg (code, obj_reg, obj_reg);
1108                 /* if yes, jump to actual trampoline */
1109                 jump_obj_null = code;
1110                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1111
1112                 /* load obj->synchronization to RCX */
1113                 amd64_mov_reg_membase (code, sync_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, synchronisation), 8);
1114
1115                 if (mono_gc_is_moving ()) {
1116                         /*if bit zero is set it's a thin hash*/
1117                         /*FIXME use testb encoding*/
1118                         amd64_test_reg_imm (code, sync_reg, 0x01);
1119                         jump_sync_thin_hash = code;
1120                         amd64_branch8 (code, X86_CC_NE, -1, 1);
1121
1122                         /*clear bits used by the gc*/
1123                         amd64_alu_reg_imm (code, X86_AND, sync_reg, ~0x3);
1124                 }
1125
1126                 /* is synchronization null? */
1127                 amd64_test_reg_reg (code, sync_reg, sync_reg);
1128                 /* if yes, jump to actual trampoline */
1129                 jump_sync_null = code;
1130                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1131
1132                 /* next case: synchronization is not null */
1133                 /* load MonoInternalThread* into RAX */
1134                 code = mono_amd64_emit_tls_get (code, AMD64_RAX, mono_thread_get_tls_offset ());
1135                 /* load TID into RAX */
1136                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, MONO_STRUCT_OFFSET (MonoInternalThread, tid), 8);
1137                 /* is synchronization->owner == TID */
1138                 amd64_alu_membase_reg_size (code, X86_CMP, sync_reg, owner_offset, AMD64_RAX, 8);
1139                 /* if no, jump to actual trampoline */
1140                 jump_not_owned = code;
1141                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1142
1143                 /* next case: synchronization->owner == TID */
1144                 /* is synchronization->nest == 1 */
1145                 amd64_alu_membase_imm_size (code, X86_CMP, sync_reg, nest_offset, 1, 4);
1146                 /* if not, jump to next case */
1147                 jump_next = code;
1148                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1149                 /* if yes, is synchronization->entry_count zero? */
1150                 amd64_alu_membase_imm_size (code, X86_CMP, sync_reg, entry_count_offset, 0, 4);
1151                 /* if not, jump to actual trampoline */
1152                 jump_have_waiters = code;
1153                 amd64_branch8 (code, X86_CC_NZ, -1 , 1);
1154                 /* if yes, set synchronization->owner to null and return */
1155                 amd64_mov_membase_imm (code, sync_reg, owner_offset, 0, 8);
1156                 amd64_ret (code);
1157
1158                 /* next case: synchronization->nest is not 1 */
1159                 x86_patch (jump_next, code);
1160                 /* decrease synchronization->nest and return */
1161                 amd64_dec_membase_size (code, sync_reg, nest_offset, 4);
1162                 amd64_ret (code);
1163
1164                 x86_patch (jump_obj_null, code);
1165                 x86_patch (jump_have_waiters, code);
1166                 x86_patch (jump_not_owned, code);
1167                 x86_patch (jump_sync_null, code);
1168         }
1169
1170         /* jump to the actual trampoline */
1171         if (MONO_AMD64_ARG_REG1 != obj_reg)
1172                 amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, obj_reg, sizeof (mgreg_t));
1173
1174         if (aot) {
1175                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_exit");
1176                 amd64_jump_reg (code, AMD64_R11);
1177         } else {
1178                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
1179                 amd64_jump_code (code, tramp);
1180         }
1181
1182         nacl_global_codeman_validate (&buf, tramp_size, &code);
1183
1184         mono_arch_flush_icache (code, code - buf);
1185         g_assert (code - buf <= tramp_size);
1186
1187         if (info)
1188                 *info = mono_tramp_info_create ("monitor_exit_trampoline", buf, code - buf, ji, unwind_ops);
1189
1190         return buf;
1191 }
1192
1193 void
1194 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
1195 {
1196         /* FIXME: This is not thread safe */
1197         guint8 *code = ji->code_start;
1198
1199         amd64_mov_reg_imm (code, AMD64_ARG_REG1, func_arg);
1200         amd64_mov_reg_imm (code, AMD64_R11, func);
1201
1202         x86_push_imm (code, (guint64)func_arg);
1203         amd64_call_reg (code, AMD64_R11);
1204 }
1205
1206
1207 static void
1208 handler_block_trampoline_helper (gpointer *ptr)
1209 {
1210         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1211         *ptr = jit_tls->handler_block_return_address;
1212 }
1213
1214 gpointer
1215 mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
1216 {
1217         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1218         guint8 *code, *buf;
1219         int tramp_size = 64;
1220         MonoJumpInfo *ji = NULL;
1221         GSList *unwind_ops = NULL;
1222
1223         g_assert (!aot);
1224
1225         code = buf = mono_global_codeman_reserve (tramp_size);
1226
1227         /*
1228         This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
1229         */
1230         if (mono_get_jit_tls_offset () != -1) {
1231                 code = mono_amd64_emit_tls_get (code, MONO_AMD64_ARG_REG1, mono_get_jit_tls_offset ());
1232                 amd64_mov_reg_membase (code, MONO_AMD64_ARG_REG1, MONO_AMD64_ARG_REG1, 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, MONO_AMD64_ARG_REG1, AMD64_RSP, 8);
1239                 amd64_mov_reg_imm (code, AMD64_RAX, tramp);
1240                 amd64_push_reg (code, AMD64_RAX);
1241                 amd64_push_reg (code, AMD64_RAX);
1242                 amd64_jump_code (code, handler_block_trampoline_helper);
1243         }
1244
1245         mono_arch_flush_icache (buf, code - buf);
1246         g_assert (code - buf <= tramp_size);
1247
1248         if (info)
1249                 *info = mono_tramp_info_create ("handler_block_trampoline", buf, code - buf, ji, unwind_ops);
1250
1251         return buf;
1252 }
1253
1254 /*
1255  * mono_arch_get_call_target:
1256  *
1257  *   Return the address called by the code before CODE if exists.
1258  */
1259 guint8*
1260 mono_arch_get_call_target (guint8 *code)
1261 {
1262         if (code [-5] == 0xe8) {
1263                 gint32 disp = *(gint32*)(code - 4);
1264                 guint8 *target = code + disp;
1265
1266                 return target;
1267         } else {
1268                 return NULL;
1269         }
1270 }
1271
1272 /*
1273  * mono_arch_get_plt_info_offset:
1274  *
1275  *   Return the PLT info offset belonging to the plt entry PLT_ENTRY.
1276  */
1277 guint32
1278 mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
1279 {
1280 #if defined(__native_client__) || defined(__native_client_codegen__)
1281         /* 18 = 3 (mov opcode) + 4 (disp) + 10 (nacljmp) + 1 (push opcode) */
1282         /* See aot-compiler.c arch_emit_plt_entry for details.             */
1283         return *(guint32*)(plt_entry + 18);
1284 #else
1285         return *(guint32*)(plt_entry + 6);
1286 #endif
1287 }