Merge pull request #1685 from esdrubal/touint64
[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, 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         framesize = kMaxCodeSize + sizeof (MonoLMFTramp);
423         framesize = (framesize + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
424
425         orig_rsp_to_rbp_offset = 0;
426         r11_save_code = code;
427         /* Reserve 5 bytes for the mov_membase_reg to save R11 */
428         code += 5;
429         after_r11_save_code = code;
430
431         // CFA = sp + 16 (the trampoline address is on the stack)
432         cfa_offset = 16;
433         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, AMD64_RSP, 16);
434         // IP saved at CFA - 8
435         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RIP, -8);
436
437         /* Pop the return address off the stack */
438         amd64_pop_reg (code, AMD64_R11);
439         orig_rsp_to_rbp_offset += sizeof(mgreg_t);
440
441         cfa_offset -= sizeof(mgreg_t);
442         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
443
444         /* 
445          * Allocate a new stack frame
446          */
447         amd64_push_reg (code, AMD64_RBP);
448         cfa_offset += sizeof(mgreg_t);
449         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
450         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RBP, - cfa_offset);
451
452         orig_rsp_to_rbp_offset -= sizeof(mgreg_t);
453         amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
454         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, AMD64_RBP);
455         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, framesize);
456
457         offset = 0;
458         rbp_offset = - offset;
459
460         offset += sizeof(mgreg_t);
461         rax_offset = - offset;
462
463         offset += sizeof(mgreg_t);
464         tramp_offset = - offset;
465
466         offset += sizeof(gpointer);
467         arg_offset = - offset;
468
469         /* Compute the trampoline address from the return address */
470         if (aot) {
471 #if defined(__default_codegen__)
472                 /* 7 = length of call *<offset>(rip) */
473                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 7);
474 #elif defined(__native_client_codegen__)
475                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, kNaClTrampOffset);
476 #endif
477         } else {
478                 /* 5 = length of amd64_call_membase () */
479                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 5);
480         }
481         amd64_mov_membase_reg (code, AMD64_RBP, tramp_offset, AMD64_R11, sizeof(gpointer));
482
483         offset += sizeof(mgreg_t);
484         res_offset = - offset;
485
486         /* Save all registers */
487
488         offset += AMD64_NREG * sizeof(mgreg_t);
489         saved_regs_offset = - offset;
490         for (i = 0; i < AMD64_NREG; ++i) {
491                 if (i == AMD64_RBP) {
492                         /* RAX is already saved */
493                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, rbp_offset, sizeof(mgreg_t));
494                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), AMD64_RAX, sizeof(mgreg_t));
495                 } else if (i != AMD64_R11) {
496                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
497                 } else {
498                         /* We have to save R11 right at the start of
499                            the trampoline code because it's used as a
500                            scratch register */
501                         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));
502                         g_assert (r11_save_code == after_r11_save_code);
503                 }
504         }
505         offset += 8 * sizeof(mgreg_t);
506         saved_fpregs_offset = - offset;
507         for (i = 0; i < 8; ++i)
508                 amd64_movsd_membase_reg (code, AMD64_RBP, saved_fpregs_offset + (i * sizeof(mgreg_t)), i);
509
510         /* Check that the stack is aligned */
511 #if defined(__default_codegen__)
512         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RSP, sizeof (mgreg_t));
513         amd64_alu_reg_imm (code, X86_AND, AMD64_R11, 15);
514         amd64_alu_reg_imm (code, X86_CMP, AMD64_R11, 0);
515         br [0] = code;
516         amd64_branch_disp (code, X86_CC_Z, 0, FALSE);
517         if (aot) {
518                 amd64_mov_reg_imm (code, AMD64_R11, 0);
519                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
520         } else {
521                 amd64_mov_reg_imm (code, MONO_AMD64_ARG_REG1, tramp_type);
522                 amd64_mov_reg_imm (code, AMD64_R11, stack_unaligned);
523                 amd64_call_reg (code, AMD64_R11);
524         }
525         mono_amd64_patch (br [0], code);
526         //amd64_breakpoint (code);
527 #endif
528
529         if (tramp_type != MONO_TRAMPOLINE_GENERIC_CLASS_INIT &&
530                 tramp_type != MONO_TRAMPOLINE_MONITOR_ENTER &&
531                 tramp_type != MONO_TRAMPOLINE_MONITOR_ENTER_V4 &&
532                 tramp_type != MONO_TRAMPOLINE_MONITOR_EXIT &&
533                 tramp_type != MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD) {
534                 /* Obtain the trampoline argument which is encoded in the instruction stream */
535                 if (aot) {
536                         /* Load the GOT offset */
537                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, sizeof(gpointer));
538 #if defined(__default_codegen__)
539                         /*
540                          * r11 points to a call *<offset>(%rip) instruction, load the
541                          * pc-relative offset from the instruction itself.
542                          */
543                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 3, 4);
544                         /* 7 is the length of the call, 8 is the offset to the next got slot */
545                         amd64_alu_reg_imm_size (code, X86_ADD, AMD64_RAX, 7 + sizeof (gpointer), sizeof(gpointer));
546 #elif defined(__native_client_codegen__)
547                         /* The arg is hidden in a "push imm32" instruction, */
548                         /* add one to skip the opcode.                      */
549                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, kNaClTrampOffset+1, 4);
550 #endif
551                         /* Compute the address of the GOT slot */
552                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_R11, AMD64_RAX, sizeof(gpointer));
553                         /* Load the value */
554                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, sizeof(gpointer));
555                 } else {                        
556                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, sizeof(gpointer));
557 #if defined(__default_codegen__)
558                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 5, 1);
559                         amd64_widen_reg (code, AMD64_RAX, AMD64_RAX, TRUE, FALSE);
560                         amd64_alu_reg_imm_size (code, X86_CMP, AMD64_RAX, 4, 1);
561                         br [0] = code;
562                         x86_branch8 (code, X86_CC_NE, 6, FALSE);
563                         /* 32 bit immediate */
564                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
565                         br [1] = code;
566                         x86_jump8 (code, 10);
567                         /* 64 bit immediate */
568                         mono_amd64_patch (br [0], code);
569                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 8);
570                         mono_amd64_patch (br [1], code);
571 #elif defined(__native_client_codegen__)
572                         /* All args are 32-bit pointers in NaCl */
573                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
574 #endif
575                 }
576                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, sizeof(gpointer));
577         } else {
578                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, saved_regs_offset + (MONO_AMD64_ARG_REG1 * sizeof(mgreg_t)), sizeof(mgreg_t));
579                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, sizeof(gpointer));
580         }
581
582         /* Save LMF begin */
583
584         offset += sizeof (MonoLMFTramp);
585         lmf_offset = - offset;
586
587         /* Save ip */
588         if (has_caller)
589                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, 8, sizeof(gpointer));
590         else
591                 amd64_mov_reg_imm (code, AMD64_R11, 0);
592         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, rip), AMD64_R11, sizeof(mgreg_t));
593         /* Save fp */
594         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, framesize, sizeof(mgreg_t));
595         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, rbp), AMD64_R11, sizeof(mgreg_t));
596         /* Save sp */
597         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RSP, sizeof(mgreg_t));
598         amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, framesize + 16);
599         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, rsp), AMD64_R11, sizeof(mgreg_t));
600         /* Save pointer to registers */
601         amd64_lea_membase (code, AMD64_R11, AMD64_RBP, saved_regs_offset);
602         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMFTramp, regs), AMD64_R11, 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 + MONO_STRUCT_OFFSET (MonoLMFTramp, lmf_addr), AMD64_RAX, sizeof(gpointer));
613         /* Save previous_lmf */
614         /* Set the lowest bit to signal that this LMF has the ip field set */
615         /* Set the third lowest bit to signal that this is a MonoLMFTramp structure */
616         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
617         amd64_alu_reg_imm_size (code, X86_ADD, AMD64_R11, 0x5, sizeof(gpointer));
618         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
619         /* Set new lmf */
620         amd64_lea_membase (code, AMD64_R11, AMD64_RBP, lmf_offset);
621         amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
622
623         /* Save LMF end */
624
625         /* Arg1 is the pointer to the saved registers */
626         amd64_lea_membase (code, AMD64_ARG_REG1, AMD64_RBP, saved_regs_offset);
627
628         /* Arg2 is the address of the calling code */
629         if (has_caller)
630                 amd64_mov_reg_membase (code, AMD64_ARG_REG2, AMD64_RBP, 8, sizeof(gpointer));
631         else
632                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
633
634         /* Arg3 is the method/vtable ptr */
635         amd64_mov_reg_membase (code, AMD64_ARG_REG3, AMD64_RBP, arg_offset, sizeof(gpointer));
636
637         /* Arg4 is the trampoline address */
638         amd64_mov_reg_membase (code, AMD64_ARG_REG4, AMD64_RBP, tramp_offset, sizeof(gpointer));
639
640         if (aot) {
641                 char *icall_name = g_strdup_printf ("trampoline_func_%d", tramp_type);
642                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
643         } else {
644                 tramp = (guint8*)mono_get_trampoline_func (tramp_type);
645                 amd64_mov_reg_imm (code, AMD64_R11, tramp);
646         }
647         amd64_call_reg (code, AMD64_R11);
648
649         /* Check for thread interruption */
650         /* This is not perf critical code so no need to check the interrupt flag */
651         /* 
652          * Have to call the _force_ variant, since there could be a protected wrapper on the top of the stack.
653          */
654         amd64_mov_membase_reg (code, AMD64_RBP, res_offset, AMD64_RAX, sizeof(mgreg_t));
655         if (aot) {
656                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_force_interruption_checkpoint");
657         } else {
658                 amd64_mov_reg_imm (code, AMD64_R11, (guint8*)mono_thread_force_interruption_checkpoint);
659         }
660         amd64_call_reg (code, AMD64_R11);
661
662         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, res_offset, sizeof(mgreg_t));        
663
664         /* Restore LMF */
665         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
666         amd64_alu_reg_imm_size (code, X86_SUB, AMD64_RCX, 0x5, sizeof(gpointer));
667         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, lmf_offset + MONO_STRUCT_OFFSET (MonoLMFTramp, 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         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
703
704         if (info) {
705                 tramp_name = mono_get_generic_trampoline_name (tramp_type);
706                 *info = mono_tramp_info_create (tramp_name, buf, code - buf, ji, unwind_ops);
707                 g_free (tramp_name);
708         }
709
710         return buf;
711 }
712
713 gpointer
714 mono_arch_get_nullified_class_init_trampoline (MonoTrampInfo **info)
715 {
716         guint8 *code, *buf;
717         int size = NACL_SIZE (16, 32);
718
719         code = buf = mono_global_codeman_reserve (size);
720         amd64_ret (code);
721
722         nacl_global_codeman_validate(&buf, size, &code);
723
724         mono_arch_flush_icache (buf, code - buf);
725         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
726
727         if (info)
728                 *info = mono_tramp_info_create ("nullified_class_init_trampoline", buf, code - buf, NULL, NULL);
729
730         return buf;
731 }
732
733 gpointer
734 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
735 {
736         guint8 *code, *buf, *tramp;
737         int size;
738         gboolean far_addr = FALSE;
739
740         tramp = mono_get_trampoline_code (tramp_type);
741
742 #if defined(__default_codegen__)
743         if ((((guint64)arg1) >> 32) == 0)
744                 size = 5 + 1 + 4;
745         else
746                 size = 5 + 1 + 8;
747
748         code = buf = mono_domain_code_reserve_align (domain, size, 1);
749
750         if (((gint64)tramp - (gint64)code) >> 31 != 0 && ((gint64)tramp - (gint64)code) >> 31 != -1) {
751 #ifndef MONO_ARCH_NOMAP32BIT
752                 g_assert_not_reached ();
753 #endif
754                 far_addr = TRUE;
755                 size += 16;
756                 code = buf = mono_domain_code_reserve_align (domain, size, 1);
757         }
758 #elif defined(__native_client_codegen__)
759         size = 5 + 1 + 4;
760         /* Aligning the call site below could */
761         /* add up to kNaClAlignment-1 bytes   */
762         size += (kNaClAlignment-1);
763         size = NACL_BUNDLE_ALIGN_UP (size);
764         buf = mono_domain_code_reserve_align (domain, size, kNaClAlignment);
765         code = buf;
766 #endif
767
768         if (far_addr) {
769                 amd64_mov_reg_imm (code, AMD64_R11, tramp);
770                 amd64_call_reg (code, AMD64_R11);
771         } else {
772                 amd64_call_code (code, tramp);
773         }
774         /* The trampoline code will obtain the argument from the instruction stream */
775 #if defined(__default_codegen__)
776         if ((((guint64)arg1) >> 32) == 0) {
777                 *code = 0x4;
778                 *(guint32*)(code + 1) = (gint64)arg1;
779                 code += 5;
780         } else {
781                 *code = 0x8;
782                 *(guint64*)(code + 1) = (gint64)arg1;
783                 code += 9;
784         }
785 #elif defined(__native_client_codegen__)
786         /* For NaCl, all tramp args are 32-bit because they're pointers */
787         *code = 0x68; /* push imm32 */
788         *(guint32*)(code + 1) = (gint32)arg1;
789         code += 5;
790 #endif
791
792         g_assert ((code - buf) <= size);
793
794         if (code_len)
795                 *code_len = size;
796
797         nacl_domain_code_validate(domain, &buf, size, &code);
798
799         mono_arch_flush_icache (buf, size);
800         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE, mono_get_generic_trampoline_simple_name (tramp_type));
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, MONO_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         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE, NULL);
895
896         g_assert (code - buf <= tramp_size);
897
898         if (info) {
899                 char *name = mono_get_rgctx_fetch_trampoline_name (slot);
900                 *info = mono_tramp_info_create (name, buf, code - buf, ji, unwind_ops);
901                 g_free (name);
902         }
903
904         return buf;
905 }
906
907 gpointer
908 mono_arch_create_generic_class_init_trampoline (MonoTrampInfo **info, gboolean aot)
909 {
910         guint8 *tramp;
911         guint8 *code, *buf;
912         static int byte_offset = -1;
913         static guint8 bitmask;
914         guint8 *jump;
915         int tramp_size;
916         GSList *unwind_ops = NULL;
917         MonoJumpInfo *ji = NULL;
918
919         tramp_size = 64;
920
921         code = buf = mono_global_codeman_reserve (tramp_size);
922
923         if (byte_offset < 0)
924                 mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
925
926         amd64_test_membase_imm_size (code, MONO_AMD64_ARG_REG1, byte_offset, bitmask, 1);
927         jump = code;
928         amd64_branch8 (code, X86_CC_Z, -1, 1);
929
930         amd64_ret (code);
931
932         x86_patch (jump, code);
933
934         if (aot) {
935                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_generic_class_init");
936                 amd64_jump_reg (code, AMD64_R11);
937         } else {
938                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
939
940                 /* jump to the actual trampoline */
941                 amd64_jump_code (code, tramp);
942         }
943
944         nacl_global_codeman_validate (&buf, tramp_size, &code);
945
946         mono_arch_flush_icache (buf, code - buf);
947         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
948
949         g_assert (code - buf <= tramp_size);
950
951         if (info)
952                 *info = mono_tramp_info_create ("generic_class_init_trampoline", buf, code - buf, ji, unwind_ops);
953
954         return buf;
955 }
956
957 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
958
959 gpointer
960 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean is_v4, gboolean aot)
961 {
962         guint8 *tramp;
963         guint8 *code, *buf;
964         guint8 *jump_obj_null, *jump_sync_null, *jump_cmpxchg_failed, *jump_other_owner, *jump_tid, *jump_sync_thin_hash = NULL;
965         guint8 *jump_lock_taken_true = NULL;
966         int tramp_size;
967         int status_offset, nest_offset;
968         MonoJumpInfo *ji = NULL;
969         GSList *unwind_ops = NULL;
970         int obj_reg = MONO_AMD64_ARG_REG1;
971         int lock_taken_reg = MONO_AMD64_ARG_REG2;
972         int sync_reg = MONO_AMD64_ARG_REG3;
973         int tid_reg = MONO_AMD64_ARG_REG4;
974         int status_reg = AMD64_RAX;
975
976         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == obj_reg);
977 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
978         g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG == lock_taken_reg);
979 #else
980         g_assert (!is_v4);
981 #endif
982
983         mono_monitor_threads_sync_members_offset (&status_offset, &nest_offset);
984         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (status_offset) == sizeof (guint32));
985         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
986         status_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (status_offset);
987         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
988
989         tramp_size = 128;
990
991         code = buf = mono_global_codeman_reserve (tramp_size);
992
993         unwind_ops = mono_arch_get_cie_program ();
994
995         if (!aot && mono_thread_get_tls_offset () != -1) {
996                 /* MonoObject* obj is in obj_reg */
997                 /* is obj null? */
998                 amd64_test_reg_reg (code, obj_reg, obj_reg);
999                 /* if yes, jump to actual trampoline */
1000                 jump_obj_null = code;
1001                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1002
1003                 if (is_v4) {
1004                         amd64_test_membase_imm (code, lock_taken_reg, 0, 1);
1005                         /* if *lock_taken is 1, jump to actual trampoline */
1006                         jump_lock_taken_true = code;
1007                         x86_branch8 (code, X86_CC_NZ, -1, 1);
1008                 }
1009
1010                 /* load obj->synchronization to sync_reg */
1011                 amd64_mov_reg_membase (code, sync_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, synchronisation), 8);
1012
1013                 if (mono_gc_is_moving ()) {
1014                         /*if bit zero is set it's a thin hash*/
1015                         /*FIXME use testb encoding*/
1016                         amd64_test_reg_imm (code, sync_reg, 0x01);
1017                         jump_sync_thin_hash = code;
1018                         amd64_branch8 (code, X86_CC_NE, -1, 1);
1019
1020                         /*clear bits used by the gc*/
1021                         amd64_alu_reg_imm (code, X86_AND, sync_reg, ~0x3);
1022                 }
1023
1024                 /* is synchronization null? */
1025                 amd64_test_reg_reg (code, sync_reg, sync_reg);
1026                 /* if yes, jump to actual trampoline */
1027                 jump_sync_null = code;
1028                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1029
1030                 /* load MonoInternalThread* into tid_reg */
1031                 code = mono_amd64_emit_tls_get (code, tid_reg, mono_thread_get_tls_offset ());
1032                 /* load TID into tid_reg */
1033                 amd64_mov_reg_membase (code, tid_reg, tid_reg, MONO_STRUCT_OFFSET (MonoInternalThread, small_id), 4);
1034
1035                 /* is synchronization->owner free */
1036                 amd64_mov_reg_membase (code, status_reg, sync_reg, status_offset, 4);
1037                 amd64_test_reg_imm_size (code, status_reg, OWNER_MASK, 4);
1038                 /* if not, jump to next case */
1039                 jump_tid = code;
1040                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1041
1042                 /* if yes, try a compare-exchange with the TID */
1043                 g_assert (tid_reg != X86_EAX);
1044                 /* Form new status in tid_reg */
1045                 amd64_alu_reg_reg_size (code, X86_OR, tid_reg, status_reg, 4);
1046                 /* compare and exchange */
1047                 amd64_prefix (code, X86_LOCK_PREFIX);
1048                 amd64_cmpxchg_membase_reg_size (code, sync_reg, status_offset, tid_reg, 4);
1049                 /* if not successful, jump to actual trampoline */
1050                 jump_cmpxchg_failed = code;
1051                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1052                 /* if successful, return */
1053                 if (is_v4)
1054                         amd64_mov_membase_imm (code, lock_taken_reg, 0, 1, 1);
1055                 amd64_ret (code);
1056
1057                 /* next case: synchronization->owner is not null */
1058                 x86_patch (jump_tid, code);
1059                 /* is synchronization->owner == TID? */
1060                 amd64_alu_reg_imm_size (code, X86_AND, status_reg, OWNER_MASK, 4);
1061                 amd64_alu_reg_reg_size (code, X86_CMP, status_reg, tid_reg, 4);
1062                 /* if not, jump to actual trampoline */
1063                 jump_other_owner = code;
1064                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1065                 /* if yes, increment nest */
1066                 amd64_inc_membase_size (code, sync_reg, nest_offset, 4);
1067                 /* return */
1068                 if (is_v4)
1069                         amd64_mov_membase_imm (code, lock_taken_reg, 0, 1, 1);
1070                 amd64_ret (code);
1071
1072                 x86_patch (jump_obj_null, code);
1073                 if (jump_sync_thin_hash)
1074                         x86_patch (jump_sync_thin_hash, code);
1075                 x86_patch (jump_sync_null, code);
1076                 x86_patch (jump_cmpxchg_failed, code);
1077                 x86_patch (jump_other_owner, code);
1078                 if (is_v4)
1079                         x86_patch (jump_lock_taken_true, code);
1080         }
1081
1082         /* jump to the actual trampoline */
1083         if (MONO_AMD64_ARG_REG1 != obj_reg)
1084                 amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, obj_reg, sizeof (mgreg_t));
1085
1086         if (aot) {
1087                 if (is_v4)
1088                         code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_enter_v4");
1089                 else
1090                         code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_enter");
1091                 amd64_jump_reg (code, AMD64_R11);
1092         } else {
1093                 if (is_v4)
1094                         tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER_V4, mono_get_root_domain (), NULL);
1095                 else
1096                         tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
1097
1098                 /* jump to the actual trampoline */
1099                 amd64_jump_code (code, tramp);
1100         }
1101
1102         nacl_global_codeman_validate (&buf, tramp_size, &code);
1103
1104         mono_arch_flush_icache (code, code - buf);
1105         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_MONITOR, NULL);
1106         g_assert (code - buf <= tramp_size);
1107
1108         if (info) {
1109                 if (is_v4)
1110                         *info = mono_tramp_info_create ("monitor_enter_v4_trampoline", buf, code - buf, ji, unwind_ops);
1111                 else
1112                         *info = mono_tramp_info_create ("monitor_enter_trampoline", buf, code - buf, ji, unwind_ops);
1113         }
1114
1115         return buf;
1116 }
1117
1118 gpointer
1119 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
1120 {
1121         guint8 *tramp;
1122         guint8 *code, *buf;
1123         guint8 *jump_obj_null, *jump_have_waiters, *jump_sync_null, *jump_not_owned, *jump_cmpxchg_failed;
1124         guint8 *jump_next;
1125         int tramp_size;
1126         int status_offset, nest_offset;
1127         MonoJumpInfo *ji = NULL;
1128         GSList *unwind_ops = NULL;
1129         int obj_reg = MONO_AMD64_ARG_REG1;
1130         int sync_reg = MONO_AMD64_ARG_REG2;
1131         int status_reg = MONO_AMD64_ARG_REG3;
1132
1133         g_assert (obj_reg == MONO_ARCH_MONITOR_OBJECT_REG);
1134
1135         mono_monitor_threads_sync_members_offset (&status_offset, &nest_offset);
1136         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (status_offset) == sizeof (guint32));
1137         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
1138         status_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (status_offset);
1139         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
1140
1141         tramp_size = 112;
1142
1143         code = buf = mono_global_codeman_reserve (tramp_size);
1144
1145         unwind_ops = mono_arch_get_cie_program ();
1146
1147         if (!aot && mono_thread_get_tls_offset () != -1) {
1148                 /* MonoObject* obj is in obj_reg */
1149                 /* is obj null? */
1150                 amd64_test_reg_reg (code, obj_reg, obj_reg);
1151                 /* if yes, jump to actual trampoline */
1152                 jump_obj_null = code;
1153                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1154
1155                 /* load obj->synchronization to RCX */
1156                 amd64_mov_reg_membase (code, sync_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, synchronisation), 8);
1157
1158                 if (mono_gc_is_moving ()) {
1159                         /*if bit zero is set it's a thin hash*/
1160                         /*FIXME use testb encoding*/
1161                         amd64_test_reg_imm (code, sync_reg, 0x01);
1162                         amd64_branch8 (code, X86_CC_NE, -1, 1);
1163
1164                         /*clear bits used by the gc*/
1165                         amd64_alu_reg_imm (code, X86_AND, sync_reg, ~0x3);
1166                 }
1167
1168                 /* is synchronization null? */
1169                 amd64_test_reg_reg (code, sync_reg, sync_reg);
1170                 /* if yes, jump to actual trampoline */
1171                 jump_sync_null = code;
1172                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1173
1174                 /* next case: synchronization is not null */
1175                 /* load MonoInternalThread* into RAX */
1176                 code = mono_amd64_emit_tls_get (code, AMD64_RAX, mono_thread_get_tls_offset ());
1177                 /* load TID into RAX */
1178                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, MONO_STRUCT_OFFSET (MonoInternalThread, small_id), 4);
1179                 /* is synchronization->owner == TID */
1180                 amd64_mov_reg_membase (code, status_reg, sync_reg, status_offset, 4);
1181                 amd64_alu_reg_reg_size (code, X86_XOR, AMD64_RAX, status_reg, 4);
1182                 amd64_test_reg_imm_size (code, AMD64_RAX, OWNER_MASK, 4);
1183
1184                 /* if no, jump to actual trampoline */
1185                 jump_not_owned = code;
1186                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1187
1188                 /* next case: synchronization->owner == TID */
1189                 /* is synchronization->nest == 1 */
1190                 amd64_alu_membase_imm_size (code, X86_CMP, sync_reg, nest_offset, 1, 4);
1191                 /* if not, jump to next case */
1192                 jump_next = code;
1193                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1194                 /* if yes, is synchronization->entry_count greater than zero */
1195                 amd64_test_reg_imm_size (code, status_reg, ENTRY_COUNT_WAITERS, 4);
1196                 /* if not, jump to actual trampoline */
1197                 jump_have_waiters = code;
1198                 amd64_branch8 (code, X86_CC_NZ, -1 , 1);
1199                 /* if yes, try to set synchronization->owner to null and return */
1200                 g_assert (status_reg != AMD64_RAX);
1201                 /* old status in RAX */
1202                 amd64_mov_reg_reg (code, AMD64_RAX, status_reg, 4);
1203                 /* form new status */
1204                 amd64_alu_reg_imm_size (code, X86_AND, status_reg, ENTRY_COUNT_MASK, 4);
1205                 /* compare and exchange */
1206                 amd64_prefix (code, X86_LOCK_PREFIX);
1207                 amd64_cmpxchg_membase_reg_size (code, sync_reg, status_offset, status_reg, 4);
1208                 /* if not successful, jump to actual trampoline */
1209                 jump_cmpxchg_failed = code;
1210                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1211                 amd64_ret (code);
1212
1213                 /* next case: synchronization->nest is not 1 */
1214                 x86_patch (jump_next, code);
1215                 /* decrease synchronization->nest and return */
1216                 amd64_dec_membase_size (code, sync_reg, nest_offset, 4);
1217                 amd64_ret (code);
1218
1219                 x86_patch (jump_obj_null, code);
1220                 x86_patch (jump_have_waiters, code);
1221                 x86_patch (jump_not_owned, code);
1222                 x86_patch (jump_cmpxchg_failed, code);
1223                 x86_patch (jump_sync_null, code);
1224         }
1225
1226         /* jump to the actual trampoline */
1227         if (MONO_AMD64_ARG_REG1 != obj_reg)
1228                 amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, obj_reg, sizeof (mgreg_t));
1229
1230         if (aot) {
1231                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_exit");
1232                 amd64_jump_reg (code, AMD64_R11);
1233         } else {
1234                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
1235                 amd64_jump_code (code, tramp);
1236         }
1237
1238         nacl_global_codeman_validate (&buf, tramp_size, &code);
1239
1240         mono_arch_flush_icache (code, code - buf);
1241         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_MONITOR, NULL);
1242         g_assert (code - buf <= tramp_size);
1243
1244         if (info)
1245                 *info = mono_tramp_info_create ("monitor_exit_trampoline", buf, code - buf, ji, unwind_ops);
1246
1247         return buf;
1248 }
1249
1250 #else
1251
1252 gpointer
1253 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean is_v4, gboolean aot)
1254 {
1255         g_assert_not_reached ();
1256         return NULL;
1257 }
1258
1259 gpointer
1260 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
1261 {
1262         g_assert_not_reached ();
1263         return NULL;
1264 }
1265
1266 #endif
1267
1268 void
1269 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
1270 {
1271         /* FIXME: This is not thread safe */
1272         guint8 *code = ji->code_start;
1273
1274         amd64_mov_reg_imm (code, AMD64_ARG_REG1, func_arg);
1275         amd64_mov_reg_imm (code, AMD64_R11, func);
1276
1277         x86_push_imm (code, (guint64)func_arg);
1278         amd64_call_reg (code, AMD64_R11);
1279 }
1280
1281
1282 static void
1283 handler_block_trampoline_helper (gpointer *ptr)
1284 {
1285         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1286         *ptr = jit_tls->handler_block_return_address;
1287 }
1288
1289 gpointer
1290 mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
1291 {
1292         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1293         guint8 *code, *buf;
1294         int tramp_size = 64;
1295         MonoJumpInfo *ji = NULL;
1296         GSList *unwind_ops = NULL;
1297
1298         g_assert (!aot);
1299
1300         code = buf = mono_global_codeman_reserve (tramp_size);
1301
1302         /*
1303         This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
1304         */
1305         if (mono_get_jit_tls_offset () != -1) {
1306                 code = mono_amd64_emit_tls_get (code, MONO_AMD64_ARG_REG1, mono_get_jit_tls_offset ());
1307                 amd64_mov_reg_membase (code, MONO_AMD64_ARG_REG1, MONO_AMD64_ARG_REG1, MONO_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 8);
1308                 /* Simulate a call */
1309                 amd64_push_reg (code, AMD64_RAX);
1310                 amd64_jump_code (code, tramp);
1311         } else {
1312                 /*Slow path uses a c helper*/
1313                 amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, AMD64_RSP, 8);
1314                 amd64_mov_reg_imm (code, AMD64_RAX, tramp);
1315                 amd64_push_reg (code, AMD64_RAX);
1316                 amd64_push_reg (code, AMD64_RAX);
1317                 amd64_jump_code (code, handler_block_trampoline_helper);
1318         }
1319
1320         mono_arch_flush_icache (buf, code - buf);
1321         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
1322         g_assert (code - buf <= tramp_size);
1323
1324         if (info)
1325                 *info = mono_tramp_info_create ("handler_block_trampoline", buf, code - buf, ji, unwind_ops);
1326
1327         return buf;
1328 }
1329
1330 /*
1331  * mono_arch_get_call_target:
1332  *
1333  *   Return the address called by the code before CODE if exists.
1334  */
1335 guint8*
1336 mono_arch_get_call_target (guint8 *code)
1337 {
1338         if (code [-5] == 0xe8) {
1339                 gint32 disp = *(gint32*)(code - 4);
1340                 guint8 *target = code + disp;
1341
1342                 return target;
1343         } else {
1344                 return NULL;
1345         }
1346 }
1347
1348 /*
1349  * mono_arch_get_plt_info_offset:
1350  *
1351  *   Return the PLT info offset belonging to the plt entry PLT_ENTRY.
1352  */
1353 guint32
1354 mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
1355 {
1356 #if defined(__native_client__) || defined(__native_client_codegen__)
1357         /* 18 = 3 (mov opcode) + 4 (disp) + 10 (nacljmp) + 1 (push opcode) */
1358         /* See aot-compiler.c arch_emit_plt_entry for details.             */
1359         return *(guint32*)(plt_entry + 18);
1360 #else
1361         return *(guint32*)(plt_entry + 6);
1362 #endif
1363 }
1364
1365 /*
1366  * mono_arch_create_sdb_trampoline:
1367  *
1368  *   Return a trampoline which captures the current context, passes it to
1369  * debugger_agent_single_step_from_context ()/debugger_agent_breakpoint_from_context (),
1370  * then restores the (potentially changed) context.
1371  */
1372 guint8*
1373 mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gboolean aot)
1374 {
1375         int tramp_size = 256;
1376         int framesize, ctx_offset, cfa_offset;
1377         guint8 *code, *buf;
1378         GSList *unwind_ops = NULL;
1379         MonoJumpInfo *ji = NULL;
1380
1381         code = buf = mono_global_codeman_reserve (tramp_size);
1382
1383         framesize = sizeof (MonoContext);
1384         framesize = ALIGN_TO (framesize, MONO_ARCH_FRAME_ALIGNMENT);
1385
1386         // CFA = sp + 8
1387         cfa_offset = 8;
1388         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, AMD64_RSP, 8);
1389         // IP saved at CFA - 8
1390         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RIP, -cfa_offset);
1391
1392         amd64_push_reg (code, AMD64_RBP);
1393         cfa_offset += sizeof(mgreg_t);
1394         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
1395         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RBP, - cfa_offset);
1396
1397         amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
1398         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, AMD64_RBP);
1399         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, framesize);
1400
1401         ctx_offset = 0;
1402
1403         /* Initialize a MonoContext structure on the stack */
1404         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rax), AMD64_RAX, sizeof (mgreg_t));
1405         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rbx), AMD64_RBX, sizeof (mgreg_t));
1406         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rcx), AMD64_RCX, sizeof (mgreg_t));
1407         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rdx), AMD64_RDX, sizeof (mgreg_t));
1408         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rsi), AMD64_RSI, sizeof (mgreg_t));
1409         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rdi), AMD64_RDI, sizeof (mgreg_t));
1410         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r8), AMD64_R8, sizeof (mgreg_t));
1411         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r9), AMD64_R9, sizeof (mgreg_t));
1412         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r10), AMD64_R10, sizeof (mgreg_t));
1413         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r11), AMD64_R11, sizeof (mgreg_t));
1414         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r12), AMD64_R12, sizeof (mgreg_t));
1415         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r13), AMD64_R13, sizeof (mgreg_t));
1416         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r14), AMD64_R14, sizeof (mgreg_t));
1417         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r15), AMD64_R15, sizeof (mgreg_t));
1418
1419         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, 0, sizeof (mgreg_t));
1420         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rbp), AMD64_R11, sizeof (mgreg_t));
1421         amd64_lea_membase (code, AMD64_R11, AMD64_RBP, 2 * sizeof (mgreg_t));
1422         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rsp), AMD64_R11, sizeof (mgreg_t));
1423         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, sizeof (mgreg_t), sizeof (mgreg_t));
1424         amd64_mov_membase_reg (code, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rip), AMD64_R11, sizeof (mgreg_t));
1425
1426         /* Call the single step/breakpoint function in sdb */
1427         amd64_lea_membase (code, AMD64_ARG_REG1, AMD64_RSP, ctx_offset);
1428
1429         if (aot) {
1430                 if (single_step)
1431                         code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "debugger_agent_single_step_from_context");
1432                 else
1433                         code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "debugger_agent_breakpoint_from_context");
1434                 amd64_call_reg (code, AMD64_R11);
1435         } else {
1436                 if (single_step)
1437                         amd64_call_code (code, debugger_agent_single_step_from_context);
1438                 else
1439                         amd64_call_code (code, debugger_agent_breakpoint_from_context);
1440         }
1441
1442         /* Restore registers from ctx */
1443         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rax), sizeof (mgreg_t));
1444         amd64_mov_reg_membase (code, AMD64_RBX, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rbx), sizeof (mgreg_t));
1445         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rcx), sizeof (mgreg_t));
1446         amd64_mov_reg_membase (code, AMD64_RDX, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rdx), sizeof (mgreg_t));
1447         amd64_mov_reg_membase (code, AMD64_RSI, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rsi), sizeof (mgreg_t));
1448         amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rdi), sizeof (mgreg_t));
1449         amd64_mov_reg_membase (code, AMD64_R8, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r8), sizeof (mgreg_t));
1450         amd64_mov_reg_membase (code, AMD64_R9, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r9), sizeof (mgreg_t));
1451         amd64_mov_reg_membase (code, AMD64_R10, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r10), sizeof (mgreg_t));
1452         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r11), sizeof (mgreg_t));
1453         amd64_mov_reg_membase (code, AMD64_R12, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r12), sizeof (mgreg_t));
1454         amd64_mov_reg_membase (code, AMD64_R13, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r13), sizeof (mgreg_t));
1455         amd64_mov_reg_membase (code, AMD64_R14, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r14), sizeof (mgreg_t));
1456         amd64_mov_reg_membase (code, AMD64_R15, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, r15), sizeof (mgreg_t));
1457
1458         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rbp), sizeof (mgreg_t));
1459         amd64_mov_membase_reg (code, AMD64_RBP, 0, AMD64_R11, sizeof (mgreg_t));
1460         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, ctx_offset + MONO_STRUCT_OFFSET (MonoContext, rip), sizeof (mgreg_t));
1461         amd64_mov_membase_reg (code, AMD64_RBP, sizeof (mgreg_t), AMD64_R11, sizeof (mgreg_t));
1462
1463         amd64_leave (code);
1464         amd64_ret (code);
1465
1466         mono_arch_flush_icache (code, code - buf);
1467         g_assert (code - buf <= tramp_size);
1468
1469         if (info) {
1470                 const char *tramp_name = single_step ? "sdb_single_step_trampoline" : "sdb_breakpoint_trampoline";
1471                 *info = mono_tramp_info_create (tramp_name, buf, code - buf, ji, unwind_ops);
1472         }
1473
1474         return buf;
1475 }