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