2009-01-11 Zoltan Varga <vargaz@gmail.com>
[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  */
10
11 #include <config.h>
12 #include <glib.h>
13
14 #include <mono/metadata/appdomain.h>
15 #include <mono/metadata/marshal.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/mono-debug-debugger.h>
18 #include <mono/metadata/monitor.h>
19 #include <mono/arch/amd64/amd64-codegen.h>
20
21 #ifdef HAVE_VALGRIND_MEMCHECK_H
22 #include <valgrind/memcheck.h>
23 #endif
24
25 #include "mini.h"
26 #include "mini-amd64.h"
27
28 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
29
30 static guint8* nullified_class_init_trampoline;
31
32 /*
33  * mono_arch_get_unbox_trampoline:
34  * @gsctx: the generic sharing context
35  * @m: method pointer
36  * @addr: pointer to native code for @m
37  *
38  * when value type methods are called through the vtable we need to unbox the
39  * this argument. This method returns a pointer to a trampoline which does
40  * unboxing before calling the method
41  */
42 gpointer
43 mono_arch_get_unbox_trampoline (MonoGenericSharingContext *gsctx, MonoMethod *m, gpointer addr)
44 {
45         guint8 *code, *start;
46         int this_reg;
47
48         MonoDomain *domain = mono_domain_get ();
49
50         this_reg = mono_arch_get_this_arg_reg (mono_method_signature (m), gsctx, NULL);
51
52         mono_domain_lock (domain);
53         start = code = mono_code_manager_reserve (domain->code_mp, 20);
54         mono_domain_unlock (domain);
55
56         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
57         /* FIXME: Optimize this */
58         amd64_mov_reg_imm (code, AMD64_RAX, addr);
59         amd64_jump_reg (code, AMD64_RAX);
60         g_assert ((code - start) < 20);
61
62         mono_arch_flush_icache (start, code - start);
63
64         return start;
65 }
66
67 /*
68  * mono_arch_patch_callsite:
69  *
70  *   Patch the callsite whose address is given by ORIG_CODE so it calls ADDR. ORIG_CODE
71  * points to the pc right after the call.
72  */
73 void
74 mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
75 {
76         guint8 *code;
77         guint8 buf [16];
78         gboolean can_write = mono_breakpoint_clean_code (method_start, orig_code, 14, buf, sizeof (buf));
79
80         code = buf + 14;
81
82         if (((code [-13] == 0x49) && (code [-12] == 0xbb)) || (code [-5] == 0xe8)) {
83                 if (code [-5] != 0xe8) {
84                         if (can_write) {
85                                 InterlockedExchangePointer ((gpointer*)(orig_code - 11), addr);
86 #ifdef HAVE_VALGRIND_MEMCHECK_H
87                                 VALGRIND_DISCARD_TRANSLATIONS (orig_code - 11, sizeof (gpointer));
88 #endif
89                         }
90                 } else {
91                         if ((((guint64)(addr)) >> 32) != 0) {
92                                 /* Print some diagnostics */
93                                 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char*)orig_code);
94                                 if (ji)
95                                         fprintf (stderr, "At %s, offset 0x%zx\n", mono_method_full_name (ji->method, TRUE), (guint8*)orig_code - (guint8*)ji->code_start);
96                                 fprintf (stderr, "Addr: %p\n", addr);
97                                 ji = mono_jit_info_table_find (mono_domain_get (), (char*)addr);
98                                 if (ji)
99                                         fprintf (stderr, "Callee: %s\n", mono_method_full_name (ji->method, TRUE));
100                                 g_assert_not_reached ();
101                         }
102                         g_assert ((((guint64)(orig_code)) >> 32) == 0);
103                         if (can_write) {
104                                 InterlockedExchange ((gint32*)(orig_code - 4), ((gint64)addr - (gint64)orig_code));
105 #ifdef HAVE_VALGRIND_MEMCHECK_H
106                                 VALGRIND_DISCARD_TRANSLATIONS (orig_code - 5, 4);
107 #endif
108                         }
109                 }
110         }
111         else if ((code [-7] == 0x41) && (code [-6] == 0xff) && (code [-5] == 0x15)) {
112                 /* call *<OFFSET>(%rip) */
113                 gpointer *got_entry = (gpointer*)((guint8*)orig_code + (*(guint32*)(orig_code - 4)));
114                 if (can_write) {
115                         InterlockedExchangePointer (got_entry, addr);
116 #ifdef HAVE_VALGRIND_MEMCHECK_H
117                         VALGRIND_DISCARD_TRANSLATIONS (orig_code - 5, sizeof (gpointer));
118 #endif
119                 }
120         }
121 }
122
123 void
124 mono_arch_patch_plt_entry (guint8 *code, guint8 *addr)
125 {
126         gint32 disp;
127         gpointer *plt_jump_table_entry;
128
129         /* A PLT entry: jmp *<DISP>(%rip) */
130         g_assert (code [0] == 0xff);
131         g_assert (code [1] == 0x25);
132
133         disp = *(gint32*)(code + 2);
134
135         plt_jump_table_entry = (gpointer*)(code + 6 + disp);
136
137         InterlockedExchangePointer (plt_jump_table_entry, addr);
138 }
139
140 void
141 mono_arch_nullify_class_init_trampoline (guint8 *code, gssize *regs)
142 {
143         guint8 buf [16];
144         gboolean can_write = mono_breakpoint_clean_code (NULL, code, 7, buf, sizeof (buf));
145
146         if (!can_write)
147                 return;
148
149         code -= 3;
150
151         /* 
152          * A given byte sequence can match more than case here, so we have to be
153          * really careful about the ordering of the cases. Longer sequences
154          * come first.
155          */
156         if ((code [-4] == 0x41) && (code [-3] == 0xff) && (code [-2] == 0x15)) {
157                 gpointer *vtable_slot;
158
159                 /* call *<OFFSET>(%rip) */
160                 vtable_slot = mono_arch_get_vcall_slot_addr (code + 3, (gpointer*)regs);
161                 g_assert (vtable_slot);
162
163                 *vtable_slot = nullified_class_init_trampoline;
164         } else if (code [-2] == 0xe8) {
165                 /* call <TARGET> */
166                 guint8 *buf = code - 2;
167
168                 buf [0] = 0x66;
169                 buf [1] = 0x66;
170                 buf [2] = 0x90;
171                 buf [3] = 0x66;
172                 buf [4] = 0x90;
173         } else if ((code [0] == 0x41) && (code [1] == 0xff)) {
174                 /* call <REG> */
175                 /* happens on machines without MAP_32BIT like freebsd */
176                 /* amd64_set_reg_template is 10 bytes long */
177                 guint8* buf = code - 10;
178
179                 /* FIXME: Make this thread safe */
180                 /* Padding code suggested by the AMD64 Opt Manual */
181                 buf [0] = 0x66;
182                 buf [1] = 0x66;
183                 buf [2] = 0x66;
184                 buf [3] = 0x90;
185                 buf [4] = 0x66;
186                 buf [5] = 0x66;
187                 buf [6] = 0x66;
188                 buf [7] = 0x90;
189                 buf [8] = 0x66;
190                 buf [9] = 0x66;
191                 buf [10] = 0x90;
192                 buf [11] = 0x66;
193                 buf [12] = 0x90;
194         } else if (code [0] == 0x90 || code [0] == 0xeb || code [0] == 0x66) {
195                 /* Already changed by another thread */
196                 ;
197         } else {
198                 printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", code [0], code [1], code [2], code [3],
199                         code [4], code [5], code [6]);
200                 g_assert_not_reached ();
201         }
202 }
203
204 void
205 mono_arch_nullify_plt_entry (guint8 *code)
206 {
207         if (mono_aot_only && !nullified_class_init_trampoline)
208                 nullified_class_init_trampoline = mono_aot_get_named_code ("nullified_class_init_trampoline");
209
210         mono_arch_patch_plt_entry (code, nullified_class_init_trampoline);
211 }
212
213 guchar*
214 mono_arch_create_trampoline_code (MonoTrampolineType tramp_type)
215 {
216         MonoJumpInfo *ji;
217         guint32 code_size;
218
219         return mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, FALSE);
220 }
221
222 guchar*
223 mono_arch_create_trampoline_code_full (MonoTrampolineType tramp_type, guint32 *code_size, MonoJumpInfo **ji, gboolean aot)
224 {
225         guint8 *buf, *code, *tramp, *br [2], *r11_save_code, *after_r11_save_code;
226         int i, lmf_offset, offset, res_offset, arg_offset, rax_offset, tramp_offset, saved_regs_offset;
227         int saved_fpregs_offset, rbp_offset, framesize, orig_rsp_to_rbp_offset, cfa_offset;
228         gboolean has_caller;
229         GSList *unwind_ops = NULL;
230         GSList *l;
231
232         if (tramp_type == MONO_TRAMPOLINE_JUMP)
233                 has_caller = FALSE;
234         else
235                 has_caller = TRUE;
236
237         code = buf = mono_global_codeman_reserve (538);
238
239         *ji = NULL;
240
241         framesize = 538 + sizeof (MonoLMF);
242         framesize = (framesize + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
243
244         orig_rsp_to_rbp_offset = 0;
245         r11_save_code = code;
246         /* Reserve 5 bytes for the mov_membase_reg to save R11 */
247         code += 5;
248         after_r11_save_code = code;
249
250         // CFA = sp + 16 (the trampoline address is on the stack)
251         cfa_offset = 16;
252         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, AMD64_RSP, 16);
253         // IP saved at CFA - 8
254         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RIP, -8);
255
256         /* Pop the return address off the stack */
257         amd64_pop_reg (code, AMD64_R11);
258         orig_rsp_to_rbp_offset += 8;
259
260         cfa_offset -= 8;
261         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
262
263         /* 
264          * Allocate a new stack frame
265          */
266         amd64_push_reg (code, AMD64_RBP);
267         cfa_offset += 8;
268         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
269         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RBP, - cfa_offset);
270
271         orig_rsp_to_rbp_offset -= 8;
272         amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, 8);
273         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, AMD64_RBP);
274         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, framesize);
275
276         offset = 0;
277         rbp_offset = - offset;
278
279         offset += 8;
280         rax_offset = - offset;
281
282         offset += 8;
283         tramp_offset = - offset;
284
285         offset += 8;
286         arg_offset = - offset;
287
288         /* Compute the trampoline address from the return address */
289         if (aot) {
290                 /* 7 = length of call *<offset>(rip) */
291                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 7);
292         } else {
293                 /* 5 = length of amd64_call_membase () */
294                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 5);
295         }
296         amd64_mov_membase_reg (code, AMD64_RBP, tramp_offset, AMD64_R11, 8);
297
298         offset += 8;
299         res_offset = - offset;
300
301         /* Save all registers */
302
303         offset += AMD64_NREG * 8;
304         saved_regs_offset = - offset;
305         for (i = 0; i < AMD64_NREG; ++i) {
306                 if (i == AMD64_RBP) {
307                         /* RAX is already saved */
308                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, rbp_offset, 8);
309                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * 8), AMD64_RAX, 8);
310                 } else if (i != AMD64_R11) {
311                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * 8), i, 8);
312                 } else {
313                         /* We have to save R11 right at the start of
314                            the trampoline code because it's used as a
315                            scratch register */
316                         amd64_mov_membase_reg (r11_save_code, AMD64_RSP, saved_regs_offset + orig_rsp_to_rbp_offset + (i * 8), i, 8);
317                         g_assert (r11_save_code == after_r11_save_code);
318                 }
319         }
320         offset += 8 * 8;
321         saved_fpregs_offset = - offset;
322         for (i = 0; i < 8; ++i)
323                 amd64_movsd_membase_reg (code, AMD64_RBP, saved_fpregs_offset + (i * 8), i);
324
325         if (tramp_type != MONO_TRAMPOLINE_GENERIC_CLASS_INIT &&
326                         tramp_type != MONO_TRAMPOLINE_MONITOR_ENTER &&
327                         tramp_type != MONO_TRAMPOLINE_MONITOR_EXIT) {
328                 /* Obtain the trampoline argument which is encoded in the instruction stream */
329                 if (aot) {
330                         /* Load the GOT offset */
331                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, 8);
332                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 7, 4);
333                         /* Compute the address of the GOT slot */
334                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_R11, AMD64_RAX, 8);
335                         /* Load the value */
336                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
337                 } else {                        
338                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, 8);
339                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 5, 1);
340                         amd64_widen_reg (code, AMD64_RAX, AMD64_RAX, TRUE, FALSE);
341                         amd64_alu_reg_imm_size (code, X86_CMP, AMD64_RAX, 4, 1);
342                         br [0] = code;
343                         x86_branch8 (code, X86_CC_NE, 6, FALSE);
344                         /* 32 bit immediate */
345                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
346                         br [1] = code;
347                         x86_jump8 (code, 10);
348                         /* 64 bit immediate */
349                         mono_amd64_patch (br [0], code);
350                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 8);
351                         mono_amd64_patch (br [1], code);
352                 }
353                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, 8);
354         } else {
355                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, saved_regs_offset + (MONO_AMD64_ARG_REG1 * 8), 8);
356                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, 8);
357         }
358
359         /* Save LMF begin */
360
361         offset += sizeof (MonoLMF);
362         lmf_offset = - offset;
363
364         /* Save ip */
365         if (has_caller)
366                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, 8, 8);
367         else
368                 amd64_mov_reg_imm (code, AMD64_R11, 0);
369         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), AMD64_R11, 8);
370         /* Save fp */
371         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, framesize, 8);
372         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), AMD64_R11, 8);
373         /* Save sp */
374         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RSP, 8);
375         amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, framesize + 16);
376         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_R11, 8);
377         /* Save method */
378         if (tramp_type == MONO_TRAMPOLINE_JIT || tramp_type == MONO_TRAMPOLINE_JUMP) {
379                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, arg_offset, 8);
380                 amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), AMD64_R11, 8);
381         } else {
382                 amd64_mov_membase_imm (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), 0, 8);
383         }
384         /* Save callee saved regs */
385 #ifdef PLATFORM_WIN32
386         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), AMD64_RDI, 8);
387         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), AMD64_RSI, 8);
388 #endif
389         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), AMD64_RBX, 8);
390         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), AMD64_R12, 8);
391         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), AMD64_R13, 8);
392         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), AMD64_R14, 8);
393         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), AMD64_R15, 8);
394
395         if (aot) {
396                 *ji = mono_patch_info_list_prepend (*ji, code - buf, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_get_lmf_addr");
397                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
398         } else {
399                 amd64_mov_reg_imm (code, AMD64_R11, mono_get_lmf_addr);
400         }
401         amd64_call_reg (code, AMD64_R11);
402
403         /* Save lmf_addr */
404         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, 8);
405         /* Save previous_lmf */
406         /* Set the lowest bit to 1 to signal that this LMF has the ip field set */
407         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, 8);
408         amd64_alu_reg_imm_size (code, X86_ADD, AMD64_R11, 1, 8);
409         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, 8);
410         /* Set new lmf */
411         amd64_lea_membase (code, AMD64_R11, AMD64_RBP, lmf_offset);
412         amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, 8);
413
414         /* Save LMF end */
415
416         /* Arg1 is the pointer to the saved registers */
417         amd64_lea_membase (code, AMD64_ARG_REG1, AMD64_RBP, saved_regs_offset);
418
419         /* Arg2 is the address of the calling code */
420         if (has_caller)
421                 amd64_mov_reg_membase (code, AMD64_ARG_REG2, AMD64_RBP, 8, 8);
422         else
423                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
424
425         /* Arg3 is the method/vtable ptr */
426         amd64_mov_reg_membase (code, AMD64_ARG_REG3, AMD64_RBP, arg_offset, 8);
427
428         /* Arg4 is the trampoline address */
429         amd64_mov_reg_membase (code, AMD64_ARG_REG4, AMD64_RBP, tramp_offset, 8);
430
431         if (aot) {
432                 char *icall_name = g_strdup_printf ("trampoline_func_%d", tramp_type);
433                 *ji = mono_patch_info_list_prepend (*ji, code - buf, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
434                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RIP, 0, 8);
435         } else {
436                 tramp = (guint8*)mono_get_trampoline_func (tramp_type);
437                 amd64_mov_reg_imm (code, AMD64_RAX, tramp);
438         }
439         amd64_call_reg (code, AMD64_RAX);
440
441         /* Check for thread interruption */
442         /* This is not perf critical code so no need to check the interrupt flag */
443         /* 
444          * Have to call the _force_ variant, since there could be a protected wrapper on the top of the stack.
445          */
446         amd64_mov_membase_reg (code, AMD64_RBP, res_offset, AMD64_RAX, 8);
447         if (aot) {
448                 *ji = mono_patch_info_list_prepend (*ji, code - buf, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_force_interruption_checkpoint");
449                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RIP, 0, 8);
450         } else {
451                 amd64_mov_reg_imm (code, AMD64_RAX, (guint8*)mono_thread_force_interruption_checkpoint);
452         }
453         amd64_call_reg (code, AMD64_RAX);
454         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, res_offset, 8);      
455
456         /* Restore LMF */
457
458         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), 8);
459         amd64_alu_reg_imm_size (code, X86_SUB, AMD64_RCX, 1, 8);
460         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), 8);
461         amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, 8);
462
463         /* 
464          * Save rax to the stack, after the leave instruction, this will become part of
465          * the red zone.
466          */
467         amd64_mov_membase_reg (code, AMD64_RBP, rax_offset, AMD64_RAX, 8);
468
469         /* Restore argument registers, r10 (needed to pass rgctx to
470            static shared generic methods), r11 (imt register for
471            interface calls), and rax (needed for direct calls to C vararg functions). */
472         for (i = 0; i < AMD64_NREG; ++i)
473                 if (AMD64_IS_ARGUMENT_REG (i) || i == AMD64_R10 || i == AMD64_R11 || i == AMD64_RAX)
474                         amd64_mov_reg_membase (code, i, AMD64_RBP, saved_regs_offset + (i * 8), 8);
475
476         for (i = 0; i < 8; ++i)
477                 amd64_movsd_reg_membase (code, i, AMD64_RBP, saved_fpregs_offset + (i * 8));
478
479         /* Restore stack */
480         amd64_leave (code);
481
482         if (MONO_TRAMPOLINE_TYPE_MUST_RETURN (tramp_type)) {
483                 /* Load result */
484                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, rax_offset - 0x8, 8);
485                 amd64_ret (code);
486         } else {
487                 /* call the compiled method using the saved rax */
488                 amd64_jump_membase (code, AMD64_RSP, rax_offset - 0x8);
489         }
490
491         g_assert ((code - buf) <= 538);
492
493         mono_arch_flush_icache (buf, code - buf);
494
495         *code_size = code - buf;
496
497         if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT) {
498                 guint32 code_len;
499
500                 /* Initialize the nullified class init trampoline used in the AOT case */
501                 nullified_class_init_trampoline = mono_arch_get_nullified_class_init_trampoline (&code_len);
502         }
503
504         mono_save_trampoline_xdebug_info ("<generic_trampoline>", buf, *code_size, unwind_ops);
505
506         for (l = unwind_ops; l; l = l->next)
507                 g_free (l->data);
508         g_slist_free (unwind_ops);
509         
510         return buf;
511 }
512
513 gpointer
514 mono_arch_get_nullified_class_init_trampoline (guint32 *code_len)
515 {
516         guint8 *code, *buf;
517
518         code = buf = mono_global_codeman_reserve (16);
519         amd64_ret (code);
520
521         mono_arch_flush_icache (buf, code - buf);
522
523         *code_len = code - buf;
524
525         return buf;
526 }
527
528 gpointer
529 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
530 {
531         guint8 *code, *buf, *tramp;
532         int size;
533
534         tramp = mono_get_trampoline_code (tramp_type);
535
536         if ((((guint64)arg1) >> 32) == 0)
537                 size = 5 + 1 + 4;
538         else
539                 size = 5 + 1 + 8;
540
541         mono_domain_lock (domain);
542         code = buf = mono_code_manager_reserve_align (domain->code_mp, size, 1);
543         mono_domain_unlock (domain);
544
545         amd64_call_code (code, tramp);
546         /* The trampoline code will obtain the argument from the instruction stream */
547         if ((((guint64)arg1) >> 32) == 0) {
548                 *code = 0x4;
549                 *(guint32*)(code + 1) = (gint64)arg1;
550                 code += 5;
551         } else {
552                 *code = 0x8;
553                 *(guint64*)(code + 1) = (gint64)arg1;
554                 code += 9;
555         }
556
557         g_assert ((code - buf) <= size);
558
559         if (code_len)
560                 *code_len = size;
561
562         mono_arch_flush_icache (buf, size);
563
564         return buf;
565 }       
566
567 gpointer
568 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot)
569 {
570         guint32 code_size;
571         MonoJumpInfo *ji;
572
573         return mono_arch_create_rgctx_lazy_fetch_trampoline_full (slot, &code_size, &ji, FALSE);
574 }
575
576 gpointer
577 mono_arch_create_rgctx_lazy_fetch_trampoline_full (guint32 slot, guint32 *code_size, MonoJumpInfo **ji, gboolean aot)
578 {
579         guint8 *tramp;
580         guint8 *code, *buf;
581         guint8 **rgctx_null_jumps;
582         int tramp_size;
583         int depth, index;
584         int i;
585         gboolean mrgctx;
586
587         *ji = NULL;
588
589         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
590         index = MONO_RGCTX_SLOT_INDEX (slot);
591         if (mrgctx)
592                 index += sizeof (MonoMethodRuntimeGenericContext) / sizeof (gpointer);
593         for (depth = 0; ; ++depth) {
594                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
595
596                 if (index < size - 1)
597                         break;
598                 index -= size - 1;
599         }
600
601         tramp_size = 64 + 8 * depth;
602
603         code = buf = mono_global_codeman_reserve (tramp_size);
604
605         rgctx_null_jumps = g_malloc (sizeof (guint8*) * (depth + 2));
606
607         if (mrgctx) {
608                 /* get mrgctx ptr */
609                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
610         } else {
611                 /* load rgctx ptr from vtable */
612                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context), 8);
613                 /* is the rgctx ptr null? */
614                 amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
615                 /* if yes, jump to actual trampoline */
616                 rgctx_null_jumps [0] = code;
617                 amd64_branch8 (code, X86_CC_Z, -1, 1);
618         }
619
620         for (i = 0; i < depth; ++i) {
621                 /* load ptr to next array */
622                 if (mrgctx && i == 0)
623                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, sizeof (MonoMethodRuntimeGenericContext), 8);
624                 else
625                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, 0, 8);
626                 /* is the ptr null? */
627                 amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
628                 /* if yes, jump to actual trampoline */
629                 rgctx_null_jumps [i + 1] = code;
630                 amd64_branch8 (code, X86_CC_Z, -1, 1);
631         }
632
633         /* fetch slot */
634         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, sizeof (gpointer) * (index + 1), 8);
635         /* is the slot null? */
636         amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
637         /* if yes, jump to actual trampoline */
638         rgctx_null_jumps [depth + 1] = code;
639         amd64_branch8 (code, X86_CC_Z, -1, 1);
640         /* otherwise return */
641         amd64_ret (code);
642
643         for (i = mrgctx ? 1 : 0; i <= depth + 1; ++i)
644                 x86_patch (rgctx_null_jumps [i], code);
645
646         g_free (rgctx_null_jumps);
647
648         /* move the rgctx pointer to the VTABLE register */
649         amd64_mov_reg_reg (code, MONO_ARCH_VTABLE_REG, AMD64_ARG_REG1, 8);
650
651         if (aot) {
652                 *ji = mono_patch_info_list_prepend (*ji, code - buf, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot));
653                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
654                 amd64_jump_reg (code, AMD64_R11);
655         } else {
656                 tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
657
658                 /* jump to the actual trampoline */
659                 amd64_jump_code (code, tramp);
660         }
661
662         mono_arch_flush_icache (buf, code - buf);
663
664         g_assert (code - buf <= tramp_size);
665
666         *code_size = code - buf;
667
668         return buf;
669 }
670
671 gpointer
672 mono_arch_create_generic_class_init_trampoline (void)
673 {
674         guint8 *tramp;
675         guint8 *code, *buf;
676         static int byte_offset = -1;
677         static guint8 bitmask;
678         guint8 *jump;
679         int tramp_size;
680
681         tramp_size = 64;
682
683         code = buf = mono_global_codeman_reserve (tramp_size);
684
685         if (byte_offset < 0)
686                 mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
687
688         amd64_test_membase_imm_size (code, MONO_AMD64_ARG_REG1, byte_offset, bitmask, 1);
689         jump = code;
690         amd64_branch8 (code, X86_CC_Z, -1, 1);
691
692         amd64_ret (code);
693
694         x86_patch (jump, code);
695
696         tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
697
698         /* jump to the actual trampoline */
699         amd64_jump_code (code, tramp);
700
701         mono_arch_flush_icache (buf, code - buf);
702
703         g_assert (code - buf <= tramp_size);
704
705         return buf;
706 }
707
708 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
709
710 gpointer
711 mono_arch_create_monitor_enter_trampoline (void)
712 {
713         guint32 code_size;
714         MonoJumpInfo *ji;
715
716         return mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, FALSE);
717 }
718
719 gpointer
720 mono_arch_create_monitor_enter_trampoline_full (guint32 *code_size, MonoJumpInfo **ji, gboolean aot)
721 {
722         guint8 *tramp;
723         guint8 *code, *buf;
724         guint8 *jump_obj_null, *jump_sync_null, *jump_cmpxchg_failed, *jump_other_owner, *jump_tid;
725         int tramp_size;
726         int owner_offset, nest_offset, dummy;
727
728         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == AMD64_RDI);
729
730         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &dummy);
731         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
732         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
733         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
734         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
735
736         tramp_size = 96;
737
738         code = buf = mono_global_codeman_reserve (tramp_size);
739
740         if (mono_thread_get_tls_offset () != -1) {
741                 /* MonoObject* obj is in RDI */
742                 /* is obj null? */
743                 amd64_test_reg_reg (buf, AMD64_RDI, AMD64_RDI);
744                 /* if yes, jump to actual trampoline */
745                 jump_obj_null = buf;
746                 amd64_branch8 (buf, X86_CC_Z, -1, 1);
747
748                 /* load obj->synchronization to RCX */
749                 amd64_mov_reg_membase (buf, AMD64_RCX, AMD64_RDI, G_STRUCT_OFFSET (MonoObject, synchronisation), 8);
750                 /* is synchronization null? */
751                 amd64_test_reg_reg (buf, AMD64_RCX, AMD64_RCX);
752                 /* if yes, jump to actual trampoline */
753                 jump_sync_null = buf;
754                 amd64_branch8 (buf, X86_CC_Z, -1, 1);
755
756                 /* load MonoThread* into RDX */
757                 buf = mono_amd64_emit_tls_get (buf, AMD64_RDX, mono_thread_get_tls_offset ());
758                 /* load TID into RDX */
759                 amd64_mov_reg_membase (buf, AMD64_RDX, AMD64_RDX, G_STRUCT_OFFSET (MonoThread, tid), 8);
760
761                 /* is synchronization->owner null? */
762                 amd64_alu_membase_imm_size (buf, X86_CMP, AMD64_RCX, owner_offset, 0, 8);
763                 /* if not, jump to next case */
764                 jump_tid = buf;
765                 amd64_branch8 (buf, X86_CC_NZ, -1, 1);
766
767                 /* if yes, try a compare-exchange with the TID */
768                 /* zero RAX */
769                 amd64_alu_reg_reg (buf, X86_XOR, AMD64_RAX, AMD64_RAX);
770                 /* compare and exchange */
771                 amd64_prefix (buf, X86_LOCK_PREFIX);
772                 amd64_cmpxchg_membase_reg_size (buf, AMD64_RCX, owner_offset, AMD64_RDX, 8);
773                 /* if not successful, jump to actual trampoline */
774                 jump_cmpxchg_failed = buf;
775                 amd64_branch8 (buf, X86_CC_NZ, -1, 1);
776                 /* if successful, return */
777                 amd64_ret (buf);
778
779                 /* next case: synchronization->owner is not null */
780                 x86_patch (jump_tid, buf);
781                 /* is synchronization->owner == TID? */
782                 amd64_alu_membase_reg_size (buf, X86_CMP, AMD64_RCX, owner_offset, AMD64_RDX, 8);
783                 /* if not, jump to actual trampoline */
784                 jump_other_owner = buf;
785                 amd64_branch8 (buf, X86_CC_NZ, -1, 1);
786                 /* if yes, increment nest */
787                 amd64_inc_membase_size (buf, AMD64_RCX, nest_offset, 4);
788                 /* return */
789                 amd64_ret (buf);
790
791                 x86_patch (jump_obj_null, buf);
792                 x86_patch (jump_sync_null, buf);
793                 x86_patch (jump_cmpxchg_failed, buf);
794                 x86_patch (jump_other_owner, buf);
795         }
796
797         /* jump to the actual trampoline */
798 #if MONO_AMD64_ARG_REG1 != AMD64_RDI
799         amd64_mov_reg_reg (buf, MONO_AMD64_ARG_REG1, AMD64_RDI);
800 #endif
801
802         if (aot) {
803                 *ji = mono_patch_info_list_prepend (*ji, buf - code, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_enter");
804                 amd64_mov_reg_membase (buf, AMD64_R11, AMD64_RIP, 0, 8);
805                 amd64_jump_reg (buf, AMD64_R11);
806         } else {
807                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
808
809                 /* jump to the actual trampoline */
810                 amd64_jump_code (buf, tramp);
811         }
812
813         mono_arch_flush_icache (buf, buf - code);
814         g_assert (buf - code <= tramp_size);
815
816         *code_size = buf - code;
817
818         return code;
819 }
820
821 gpointer
822 mono_arch_create_monitor_exit_trampoline (void)
823 {
824         guint32 code_size;
825         MonoJumpInfo *ji;
826
827         return mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, FALSE);
828 }
829
830 gpointer
831 mono_arch_create_monitor_exit_trampoline_full (guint32 *code_size, MonoJumpInfo **ji, gboolean aot)
832 {
833         guint8 *tramp;
834         guint8 *code, *buf;
835         guint8 *jump_obj_null, *jump_have_waiters;
836         guint8 *jump_next;
837         int tramp_size;
838         int owner_offset, nest_offset, entry_count_offset;
839
840         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == AMD64_RDI);
841
842         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &entry_count_offset);
843         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
844         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
845         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (entry_count_offset) == sizeof (gint32));
846         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
847         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
848         entry_count_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (entry_count_offset);
849
850         tramp_size = 94;
851
852         code = buf = mono_global_codeman_reserve (tramp_size);
853
854         if (mono_thread_get_tls_offset () != -1) {
855                 /* MonoObject* obj is in RDI */
856                 /* is obj null? */
857                 amd64_test_reg_reg (buf, AMD64_RDI, AMD64_RDI);
858                 /* if yes, jump to actual trampoline */
859                 jump_obj_null = buf;
860                 amd64_branch8 (buf, X86_CC_Z, -1, 1);
861
862                 /* load obj->synchronization to RCX */
863                 amd64_mov_reg_membase (buf, AMD64_RCX, AMD64_RDI, G_STRUCT_OFFSET (MonoObject, synchronisation), 8);
864                 /* is synchronization null? */
865                 amd64_test_reg_reg (buf, AMD64_RCX, AMD64_RCX);
866                 /* if not, jump to next case */
867                 jump_next = buf;
868                 amd64_branch8 (buf, X86_CC_NZ, -1, 1);
869                 /* if yes, just return */
870                 amd64_ret (buf);
871
872                 /* next case: synchronization is not null */
873                 x86_patch (jump_next, buf);
874                 /* load MonoThread* into RDX */
875                 buf = mono_amd64_emit_tls_get (buf, AMD64_RDX, mono_thread_get_tls_offset ());
876                 /* load TID into RDX */
877                 amd64_mov_reg_membase (buf, AMD64_RDX, AMD64_RDX, G_STRUCT_OFFSET (MonoThread, tid), 8);
878                 /* is synchronization->owner == TID */
879                 amd64_alu_membase_reg_size (buf, X86_CMP, AMD64_RCX, owner_offset, AMD64_RDX, 8);
880                 /* if yes, jump to next case */
881                 jump_next = buf;
882                 amd64_branch8 (buf, X86_CC_Z, -1, 1);
883                 /* if not, just return */
884                 amd64_ret (buf);
885
886                 /* next case: synchronization->owner == TID */
887                 x86_patch (jump_next, buf);
888                 /* is synchronization->nest == 1 */
889                 amd64_alu_membase_imm_size (buf, X86_CMP, AMD64_RCX, nest_offset, 1, 4);
890                 /* if not, jump to next case */
891                 jump_next = buf;
892                 amd64_branch8 (buf, X86_CC_NZ, -1, 1);
893                 /* if yes, is synchronization->entry_count zero? */
894                 amd64_alu_membase_imm_size (buf, X86_CMP, AMD64_RCX, entry_count_offset, 0, 4);
895                 /* if not, jump to actual trampoline */
896                 jump_have_waiters = buf;
897                 amd64_branch8 (buf, X86_CC_NZ, -1 , 1);
898                 /* if yes, set synchronization->owner to null and return */
899                 amd64_mov_membase_imm (buf, AMD64_RCX, owner_offset, 0, 8);
900                 amd64_ret (buf);
901
902                 /* next case: synchronization->nest is not 1 */
903                 x86_patch (jump_next, buf);
904                 /* decrease synchronization->nest and return */
905                 amd64_dec_membase_size (buf, AMD64_RCX, nest_offset, 4);
906                 amd64_ret (buf);
907
908                 x86_patch (jump_obj_null, buf);
909                 x86_patch (jump_have_waiters, buf);
910         }
911
912         /* jump to the actual trampoline */
913 #if MONO_AMD64_ARG_REG1 != AMD64_RDI
914         amd64_mov_reg_reg (buf, MONO_AMD64_ARG_REG1, AMD64_RDI);
915 #endif
916
917         if (aot) {
918                 *ji = mono_patch_info_list_prepend (*ji, buf - code, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_exit");
919                 amd64_mov_reg_membase (buf, AMD64_R11, AMD64_RIP, 0, 8);
920                 amd64_jump_reg (buf, AMD64_R11);
921         } else {
922                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
923                 amd64_jump_code (buf, tramp);
924         }
925
926         mono_arch_flush_icache (buf, buf - code);
927         g_assert (buf - code <= tramp_size);
928
929         *code_size = buf - code;
930
931         return code;
932 }
933 #endif
934
935 void
936 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
937 {
938         /* FIXME: This is not thread safe */
939         guint8 *code = ji->code_start;
940
941         amd64_mov_reg_imm (code, AMD64_ARG_REG1, func_arg);
942         amd64_mov_reg_imm (code, AMD64_R11, func);
943
944         x86_push_imm (code, (guint64)func_arg);
945         amd64_call_reg (code, AMD64_R11);
946 }