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