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