Fix alignment of the block guard trampoline.
[mono.git] / mono / mini / tramp-x86.c
1 /*
2  * tramp-x86.c: JIT trampoline code for x86
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12
13 #include <mono/metadata/appdomain.h>
14 #include <mono/metadata/metadata-internals.h>
15 #include <mono/metadata/marshal.h>
16 #include <mono/metadata/tabledefs.h>
17 #include <mono/metadata/mono-debug.h>
18 #include <mono/metadata/mono-debug-debugger.h>
19 #include <mono/metadata/monitor.h>
20 #include <mono/metadata/gc-internal.h>
21 #include <mono/arch/x86/x86-codegen.h>
22
23 #include <mono/utils/memcheck.h>
24
25 #include "mini.h"
26 #include "mini-x86.h"
27
28 static guint8* nullified_class_init_trampoline;
29
30 /*
31  * mono_arch_get_unbox_trampoline:
32  * @m: method pointer
33  * @addr: pointer to native code for @m
34  *
35  * when value type methods are called through the vtable we need to unbox the
36  * this argument. This method returns a pointer to a trampoline which does
37  * unboxing before calling the method
38  */
39 gpointer
40 mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
41 {
42         guint8 *code, *start;
43         int this_pos = 4;
44         MonoDomain *domain = mono_domain_get ();
45
46         start = code = mono_domain_code_reserve (domain, 16);
47
48         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
49         x86_jump_code (code, addr);
50         g_assert ((code - start) < 16);
51
52         return start;
53 }
54
55 gpointer
56 mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
57 {
58         guint8 *code, *start;
59         int buf_len;
60
61         MonoDomain *domain = mono_domain_get ();
62
63         buf_len = 10;
64
65         start = code = mono_domain_code_reserve (domain, buf_len);
66
67         x86_mov_reg_imm (code, MONO_ARCH_RGCTX_REG, mrgctx);
68         x86_jump_code (code, addr);
69         g_assert ((code - start) <= buf_len);
70
71         mono_arch_flush_icache (start, code - start);
72
73         return start;
74 }
75
76 gpointer
77 mono_arch_get_llvm_imt_trampoline (MonoDomain *domain, MonoMethod *m, int vt_offset)
78 {
79         guint8 *code, *start;
80         int buf_len;
81         int this_offset;
82
83         buf_len = 32;
84
85         start = code = mono_domain_code_reserve (domain, buf_len);
86
87         this_offset = mono_x86_get_this_arg_offset (NULL, mono_method_signature (m));
88
89         /* Set imt arg */
90         x86_mov_reg_imm (code, MONO_ARCH_IMT_REG, m);
91         /* Load this */
92         x86_mov_reg_membase (code, X86_EAX, X86_ESP, this_offset + 4, 4);
93         /* Load vtable address */
94         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
95         x86_jump_membase (code, X86_EAX, vt_offset);
96
97         g_assert ((code - start) < buf_len);
98
99         mono_arch_flush_icache (start, code - start);
100
101         return start;
102 }
103
104 void
105 mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
106 {
107         guint8 *code;
108         guint8 buf [8];
109         gboolean can_write = mono_breakpoint_clean_code (method_start, orig_code, 8, buf, sizeof (buf));
110
111         code = buf + 8;
112
113         /* go to the start of the call instruction
114          *
115          * address_byte = (m << 6) | (o << 3) | reg
116          * call opcode: 0xff address_byte displacement
117          * 0xff m=1,o=2 imm8
118          * 0xff m=2,o=2 imm32
119          */
120         code -= 6;
121         orig_code -= 6;
122         if ((code [1] == 0xe8)) {
123                 if (can_write) {
124                         InterlockedExchange ((gint32*)(orig_code + 2), (guint)addr - ((guint)orig_code + 1) - 5);
125
126                         /* Tell valgrind to recompile the patched code */
127                         VALGRIND_DISCARD_TRANSLATIONS (orig_code + 2, 4);
128                 }
129         } else if (code [1] == 0xe9) {
130                 /* A PLT entry: jmp <DISP> */
131                 if (can_write)
132                         InterlockedExchange ((gint32*)(orig_code + 2), (guint)addr - ((guint)orig_code + 1) - 5);
133         } else {
134                 printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", code [0], code [1], code [2], code [3],
135                                 code [4], code [5], code [6]);
136                 g_assert_not_reached ();
137         }
138 }
139
140 void
141 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
142 {
143         guint32 offset;
144
145         /* Patch the jump table entry used by the plt entry */
146
147 #if defined(__native_client_codegen__) || defined(__native_client__)
148         /* for both compiler and runtime      */
149         /* A PLT entry:                       */
150         /*        mov <DISP>(%ebx), %ecx      */
151         /*        and 0xffffffe0, %ecx        */
152         /*        jmp *%ecx                   */
153         g_assert (code [0] == 0x8b);
154         g_assert (code [1] == 0x8b);
155
156         offset = *(guint32*)(code + 2);
157 #else
158         /* A PLT entry: jmp *<DISP>(%ebx) */
159         g_assert (code [0] == 0xff);
160         g_assert (code [1] == 0xa3);
161
162         offset = *(guint32*)(code + 2);
163 #endif  /* __native_client_codegen__ */
164         if (!got)
165                 got = (gpointer*)(gsize) regs [MONO_ARCH_GOT_REG];
166         *(guint8**)((guint8*)got + offset) = addr;
167 }
168
169 static gpointer
170 get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
171 {
172         const int kBufSize = NACL_SIZE (8, 16);
173         guint8 buf [64];
174         guint8 reg = 0;
175         gint32 disp = 0;
176
177         mono_breakpoint_clean_code (NULL, code, kBufSize, buf, kBufSize);
178         code = buf + 8;
179
180         *displacement = 0;
181
182         if ((code [0] == 0xff) && ((code [1] & 0x18) == 0x10) && ((code [1] >> 6) == 2)) {
183                 reg = code [1] & 0x07;
184                 disp = *((gint32*)(code + 2));
185 #if defined(__native_client_codegen__) || defined(__native_client__)
186         } else if ((code[1] == 0x83) && (code[2] == 0xe1) && (code[4] == 0xff) &&
187                            (code[5] == 0xd1) && (code[-5] == 0x8b)) {
188                 disp = *((gint32*)(code - 3));
189                 reg = code[-4] & 0x07;
190         } else if ((code[-2] == 0x8b) && (code[1] == 0x83) && (code[4] == 0xff)) {
191                 reg = code[-1] & 0x07;
192                 disp = (signed char)code[0];
193 #endif
194         } else {
195                 g_assert_not_reached ();
196                 return NULL;
197         }
198
199         *displacement = disp;
200         return (gpointer)regs [reg];
201 }
202
203 static gpointer*
204 get_vcall_slot_addr (guint8* code, mgreg_t *regs)
205 {
206         gpointer vt;
207         int displacement;
208         vt = get_vcall_slot (code, regs, &displacement);
209         if (!vt)
210                 return NULL;
211         return (gpointer*)((char*)vt + displacement);
212 }
213
214 void
215 mono_arch_nullify_class_init_trampoline (guint8 *code, mgreg_t *regs)
216 {
217         guint8 buf [16];
218         gboolean can_write = mono_breakpoint_clean_code (NULL, code, 6, buf, sizeof (buf));
219
220         if (!can_write)
221                 return;
222
223         code -= 5;
224         if (code [0] == 0xe8) {
225                 if (!mono_running_on_valgrind ()) {
226                         guint32 ops;
227                         /*
228                          * Thread safe code patching using the algorithm from the paper
229                          * 'Practicing JUDO: Java Under Dynamic Optimizations'
230                          */
231                         /* 
232                          * First atomically change the the first 2 bytes of the call to a
233                          * spinning jump.
234                          */
235                         ops = 0xfeeb;
236                         InterlockedExchange ((gint32*)code, ops);
237
238                         /* Then change the other bytes to a nop */
239                         code [2] = 0x90;
240                         code [3] = 0x90;
241                         code [4] = 0x90;
242
243                         /* Then atomically change the first 4 bytes to a nop as well */
244                         ops = 0x90909090;
245                         InterlockedExchange ((gint32*)code, ops);
246                         /* FIXME: the calltree skin trips on the self modifying code above */
247
248                         /* Tell valgrind to recompile the patched code */
249                         //VALGRIND_DISCARD_TRANSLATIONS (code, 8);
250                 }
251         } else if (code [0] == 0x90 || code [0] == 0xeb) {
252                 /* Already changed by another thread */
253                 ;
254         } else if ((code [-1] == 0xff) && (x86_modrm_reg (code [0]) == 0x2)) {
255                 /* call *<OFFSET>(<REG>) -> Call made from AOT code */
256                 gpointer *vtable_slot;
257
258                 vtable_slot = get_vcall_slot_addr (code + 5, regs);
259                 g_assert (vtable_slot);
260
261                 *vtable_slot = nullified_class_init_trampoline;
262         } else {
263                         printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", code [0], code [1], code [2], code [3],
264                                 code [4], code [5], code [6]);
265                         g_assert_not_reached ();
266                 }
267 }
268
269 void
270 mono_arch_nullify_plt_entry (guint8 *code, mgreg_t *regs)
271 {
272         if (mono_aot_only && !nullified_class_init_trampoline)
273                 nullified_class_init_trampoline = mono_aot_get_trampoline ("nullified_class_init_trampoline");
274
275         mono_arch_patch_plt_entry (code, NULL, regs, nullified_class_init_trampoline);
276 }
277
278 guchar*
279 mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
280 {
281         guint8 *buf, *code, *tramp;
282         int pushed_args, pushed_args_caller_saved;
283         GSList *unwind_ops = NULL;
284         MonoJumpInfo *ji = NULL;
285
286         unwind_ops = mono_arch_get_cie_program ();
287
288         code = buf = mono_global_codeman_reserve (256);
289
290         /* Note that there is a single argument to the trampoline
291          * and it is stored at: esp + pushed_args * sizeof (gpointer)
292          * the ret address is at: esp + (pushed_args + 1) * sizeof (gpointer)
293          */
294
295         /* Put all registers into an array on the stack
296          * If this code is changed, make sure to update the offset value in
297          * mono_arch_get_this_arg_from_call () in mini-x86.c.
298          */
299         x86_push_reg (code, X86_EDI);
300         x86_push_reg (code, X86_ESI);
301         x86_push_reg (code, X86_EBP);
302         x86_push_reg (code, X86_ESP);
303         x86_push_reg (code, X86_EBX);
304         x86_push_reg (code, X86_EDX);
305         x86_push_reg (code, X86_ECX);
306         x86_push_reg (code, X86_EAX);
307
308         pushed_args_caller_saved = pushed_args = 8;
309
310         /* Align stack on apple */
311         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4);
312
313         pushed_args ++;
314
315         /* save LMF begin */
316
317         /* save the IP (caller ip) */
318         if (tramp_type == MONO_TRAMPOLINE_JUMP)
319                 x86_push_imm (code, 0);
320         else
321                 x86_push_membase (code, X86_ESP, (pushed_args + 1) * sizeof (gpointer));
322
323         pushed_args++;
324
325         x86_push_reg (code, X86_EBP);
326         x86_push_reg (code, X86_ESI);
327         x86_push_reg (code, X86_EDI);
328         x86_push_reg (code, X86_EBX);
329
330         pushed_args += 4;
331
332         /* save ESP */
333         x86_push_reg (code, X86_ESP);
334         /* Adjust ESP so it points to the previous frame */
335         x86_alu_membase_imm (code, X86_ADD, X86_ESP, 0, (pushed_args + 2) * 4);
336
337         pushed_args ++;
338
339         /* save method info */
340         if ((tramp_type == MONO_TRAMPOLINE_JIT) || (tramp_type == MONO_TRAMPOLINE_JUMP))
341                 x86_push_membase (code, X86_ESP, pushed_args * sizeof (gpointer));
342         else
343                 x86_push_imm (code, 0);
344
345         pushed_args++;
346
347         /* On apple, the stack is correctly aligned to 16 bytes because pushed_args is
348          * 16 and there is the extra trampoline arg + the return ip pushed by call
349          * FIXME: Note that if an exception happens while some args are pushed
350          * on the stack, the stack will be misaligned.
351          */
352         g_assert (pushed_args == 16);
353
354         /* get the address of lmf for the current thread */
355         if (aot) {
356                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_get_lmf_addr");
357                 x86_call_reg (code, X86_EAX);
358         } else {
359                 x86_call_code (code, mono_get_lmf_addr);
360         }
361         /* push lmf */
362         x86_push_reg (code, X86_EAX); 
363         /* push *lfm (previous_lmf) */
364         x86_push_membase (code, X86_EAX, 0);
365         /* Signal to mono_arch_find_jit_info () that this is a trampoline frame */
366         x86_alu_membase_imm (code, X86_ADD, X86_ESP, 0, 1);
367         /* *(lmf) = ESP */
368         x86_mov_membase_reg (code, X86_EAX, 0, X86_ESP, 4);
369         /* save LFM end */
370
371         pushed_args += 2;
372
373         /* starting the call sequence */
374
375         /* FIXME: Push the trampoline address */
376         x86_push_imm (code, 0);
377
378         pushed_args++;
379
380         /* push the method info */
381         x86_push_membase (code, X86_ESP, pushed_args * sizeof (gpointer));
382
383         pushed_args++;
384
385         /* push the return address onto the stack */
386         if (tramp_type == MONO_TRAMPOLINE_JUMP)
387                 x86_push_imm (code, 0);
388         else
389                 x86_push_membase (code, X86_ESP, (pushed_args + 1) * sizeof (gpointer));
390         pushed_args++;
391         /* push the address of the register array */
392         x86_lea_membase (code, X86_EAX, X86_ESP, (pushed_args - 8) * sizeof (gpointer));
393         x86_push_reg (code, X86_EAX);
394
395         pushed_args++;
396
397 #ifdef __APPLE__
398         /* check the stack is aligned after the ret ip is pushed */
399         /*x86_mov_reg_reg (buf, X86_EDX, X86_ESP, 4);
400         x86_alu_reg_imm (buf, X86_AND, X86_EDX, 15);
401         x86_alu_reg_imm (buf, X86_CMP, X86_EDX, 0);
402         x86_branch_disp (buf, X86_CC_Z, 3, FALSE);
403         x86_breakpoint (buf);*/
404 #endif
405
406         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, X86_ESP, ((pushed_args + 2) * 4));
407
408         if (aot) {
409                 char *icall_name = g_strdup_printf ("trampoline_func_%d", tramp_type);
410                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
411                 x86_call_reg (code, X86_EAX);
412         } else {
413                 tramp = (guint8*)mono_get_trampoline_func (tramp_type);
414                 x86_call_code (code, tramp);
415         }
416
417         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4*4);
418
419         pushed_args -= 4;
420
421         /* Check for thread interruption */
422         /* This is not perf critical code so no need to check the interrupt flag */
423         /* Align the stack on osx */
424         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 3 * 4);
425         x86_push_reg (code, X86_EAX);
426         if (aot) {
427                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_force_interruption_checkpoint");
428                 x86_call_reg (code, X86_EAX);
429         } else {
430                 x86_call_code (code, (guint8*)mono_thread_force_interruption_checkpoint);
431         }
432         x86_pop_reg (code, X86_EAX);
433         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 3 * 4);
434
435         /* Restore LMF */
436
437         /* ebx = previous_lmf */
438         x86_pop_reg (code, X86_EBX);
439         pushed_args--;
440         x86_alu_reg_imm (code, X86_SUB, X86_EBX, 1);
441
442         /* edi = lmf */
443         x86_pop_reg (code, X86_EDI);
444         pushed_args--;
445
446         /* *(lmf) = previous_lmf */
447         x86_mov_membase_reg (code, X86_EDI, 0, X86_EBX, 4);
448
449         /* discard method info */
450         x86_pop_reg (code, X86_ESI);
451         pushed_args--;
452
453         /* discard ESP */
454         x86_pop_reg (code, X86_ESI);
455         pushed_args--;
456
457         /* restore caller saved regs */
458         x86_pop_reg (code, X86_EBX);
459         x86_pop_reg (code, X86_EDI);
460         x86_pop_reg (code, X86_ESI);
461         x86_pop_reg (code, X86_EBP);
462
463         pushed_args -= 4;
464
465         /* discard save IP */
466         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
467         pushed_args--;
468
469         /* restore LMF end */
470
471         if (!MONO_TRAMPOLINE_TYPE_MUST_RETURN (tramp_type)) {
472                 /* 
473                  * Overwrite the method ptr with the address we need to jump to,
474                  * to free %eax.
475                  */
476                 x86_mov_membase_reg (code, X86_ESP, pushed_args * sizeof (gpointer), X86_EAX, 4);
477         }
478
479         /* Restore caller saved registers */
480         x86_mov_reg_membase (code, X86_ECX, X86_ESP, (pushed_args - pushed_args_caller_saved + X86_ECX) * 4, 4);
481         x86_mov_reg_membase (code, X86_EDX, X86_ESP, (pushed_args - pushed_args_caller_saved + X86_EDX) * 4, 4);
482         if ((tramp_type == MONO_TRAMPOLINE_RESTORE_STACK_PROT) || (tramp_type == MONO_TRAMPOLINE_AOT_PLT))
483                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, (pushed_args - pushed_args_caller_saved + X86_EAX) * 4, 4);
484
485         if (!MONO_TRAMPOLINE_TYPE_MUST_RETURN (tramp_type)) {
486                 /* Pop saved reg array + stack align */
487                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 9 * 4);
488                 pushed_args -= 9;
489                 g_assert (pushed_args == 0);
490         } else {
491                 /* Pop saved reg array + stack align + method ptr */
492                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 10 * 4);
493                 pushed_args -= 10;
494
495                 /* We've popped one more stack item than we've pushed (the
496                    method ptr argument), so we must end up at -1. */
497                 g_assert (pushed_args == -1);
498         }
499
500         x86_ret (code);
501
502         g_assert ((code - buf) <= 256);
503
504         if (info)
505                 *info = mono_tramp_info_create (mono_get_generic_trampoline_name (tramp_type), buf, code - buf, ji, unwind_ops);
506
507         if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT) {
508                 /* Initialize the nullified class init trampoline used in the AOT case */
509                 nullified_class_init_trampoline = mono_arch_get_nullified_class_init_trampoline (NULL);
510         }
511
512         return buf;
513 }
514
515 gpointer
516 mono_arch_get_nullified_class_init_trampoline (MonoTrampInfo **info)
517 {
518         guint8 *code, *buf;
519
520         code = buf = mono_global_codeman_reserve (16);
521         x86_ret (code);
522
523         mono_arch_flush_icache (buf, code - buf);
524
525         if (info)
526                 *info = mono_tramp_info_create (g_strdup_printf ("nullified_class_init_trampoline"), buf, code - buf, NULL, NULL);
527
528         if (mono_jit_map_is_enabled ())
529                 mono_emit_jit_tramp (buf, code - buf, "nullified_class_init_trampoline");
530
531         return buf;
532 }
533
534 #define TRAMPOLINE_SIZE 10
535
536 gpointer
537 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
538 {
539         guint8 *code, *buf, *tramp;
540         
541         tramp = mono_get_trampoline_code (tramp_type);
542
543         code = buf = mono_domain_code_reserve_align (domain, TRAMPOLINE_SIZE, NACL_SIZE (4, kNaClAlignment));
544
545         x86_push_imm (buf, arg1);
546         x86_jump_code (buf, tramp);
547         g_assert ((buf - code) <= TRAMPOLINE_SIZE);
548
549         mono_arch_flush_icache (code, buf - code);
550
551         if (code_len)
552                 *code_len = buf - code;
553
554         return code;
555 }
556
557 gpointer
558 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
559 {
560         guint8 *tramp;
561         guint8 *code, *buf;
562         guint8 **rgctx_null_jumps;
563         int tramp_size;
564         int depth, index;
565         int i;
566         gboolean mrgctx;
567         MonoJumpInfo *ji = NULL;
568         GSList *unwind_ops = NULL;
569
570         unwind_ops = mono_arch_get_cie_program ();
571
572         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
573         index = MONO_RGCTX_SLOT_INDEX (slot);
574         if (mrgctx)
575                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
576         for (depth = 0; ; ++depth) {
577                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
578
579                 if (index < size - 1)
580                         break;
581                 index -= size - 1;
582         }
583
584 #ifdef __native_client_codegen__
585         /* TODO: align for Native Client */
586         tramp_size = (aot ? 64 : 36) + 2 * kNaClAlignment +
587                 6 * (depth + kNaClAlignment);
588 #else
589         tramp_size = (aot ? 64 : 36) + 6 * depth;
590 #endif  /* __native_client_codegen__ */
591
592         code = buf = mono_global_codeman_reserve (tramp_size);
593
594         rgctx_null_jumps = g_malloc (sizeof (guint8*) * (depth + 2));
595
596         /* load vtable/mrgctx ptr */
597         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
598         if (!mrgctx) {
599                 /* load rgctx ptr from vtable */
600                 x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context), 4);
601                 /* is the rgctx ptr null? */
602                 x86_test_reg_reg (code, X86_EAX, X86_EAX);
603                 /* if yes, jump to actual trampoline */
604                 rgctx_null_jumps [0] = code;
605                 x86_branch8 (code, X86_CC_Z, -1, 1);
606         }
607
608         for (i = 0; i < depth; ++i) {
609                 /* load ptr to next array */
610                 if (mrgctx && i == 0)
611                         x86_mov_reg_membase (code, X86_EAX, X86_EAX, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT, 4);
612                 else
613                         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
614                 /* is the ptr null? */
615                 x86_test_reg_reg (code, X86_EAX, X86_EAX);
616                 /* if yes, jump to actual trampoline */
617                 rgctx_null_jumps [i + 1] = code;
618                 x86_branch8 (code, X86_CC_Z, -1, 1);
619         }
620
621         /* fetch slot */
622         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer) * (index + 1), 4);
623         /* is the slot null? */
624         x86_test_reg_reg (code, X86_EAX, X86_EAX);
625         /* if yes, jump to actual trampoline */
626         rgctx_null_jumps [depth + 1] = code;
627         x86_branch8 (code, X86_CC_Z, -1, 1);
628         /* otherwise return */
629         x86_ret (code);
630
631         for (i = mrgctx ? 1 : 0; i <= depth + 1; ++i)
632                 x86_patch (rgctx_null_jumps [i], code);
633
634         g_free (rgctx_null_jumps);
635
636         x86_mov_reg_membase (code, MONO_ARCH_VTABLE_REG, X86_ESP, 4, 4);
637
638         if (aot) {
639                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot));
640                 x86_jump_reg (code, X86_EAX);
641         } else {
642                 tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
643
644                 /* jump to the actual trampoline */
645                 x86_jump_code (code, tramp);
646         }
647
648         mono_arch_flush_icache (buf, code - buf);
649
650         g_assert (code - buf <= tramp_size);
651
652         if (info)
653                 *info = mono_tramp_info_create (mono_get_rgctx_fetch_trampoline_name (slot), buf, code - buf, ji, unwind_ops);
654
655         return buf;
656 }
657
658 gpointer
659 mono_arch_create_generic_class_init_trampoline (MonoTrampInfo **info, gboolean aot)
660 {
661         guint8 *tramp;
662         guint8 *code, *buf;
663         static int byte_offset = -1;
664         static guint8 bitmask;
665         guint8 *jump;
666         int tramp_size;
667         GSList *unwind_ops = NULL;
668         MonoJumpInfo *ji = NULL;
669
670         tramp_size = 64;
671
672         code = buf = mono_global_codeman_reserve (tramp_size);
673
674         unwind_ops = mono_arch_get_cie_program ();
675
676         if (byte_offset < 0)
677                 mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
678
679         x86_test_membase_imm (code, MONO_ARCH_VTABLE_REG, byte_offset, bitmask);
680         jump = code;
681         x86_branch8 (code, X86_CC_Z, -1, 1);
682
683         x86_ret (code);
684
685         x86_patch (jump, code);
686
687         /* Push the vtable so the stack is the same as in a specific trampoline */
688         x86_push_reg (code, MONO_ARCH_VTABLE_REG);
689
690         if (aot) {
691                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "generic_trampoline_generic_class_init");
692                 x86_jump_reg (code, X86_EAX);
693         } else {
694                 tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
695
696                 /* jump to the actual trampoline */
697                 x86_jump_code (code, tramp);
698         }
699
700         mono_arch_flush_icache (code, code - buf);
701
702         g_assert (code - buf <= tramp_size);
703 #ifdef __native_client_codegen__
704         g_assert (code - buf <= kNaClAlignment);
705 #endif
706         if (info)
707                 *info = mono_tramp_info_create (g_strdup_printf ("generic_class_init_trampoline"), buf, code - buf, ji, unwind_ops);
708
709         return buf;
710 }
711
712 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
713 /*
714  * The code produced by this trampoline is equivalent to this:
715  *
716  * if (obj) {
717  *      if (obj->synchronisation) {
718  *              if (obj->synchronisation->owner == 0) {
719  *                      if (cmpxch (&obj->synchronisation->owner, TID, 0) == 0)
720  *                              return;
721  *              }
722  *              if (obj->synchronisation->owner == TID) {
723  *                      ++obj->synchronisation->nest;
724  *                      return;
725  *              }
726  *      }
727  * }
728  * return full_monitor_enter ();
729  *
730  */
731 gpointer
732 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean aot)
733 {
734         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_MONITOR_ENTER);
735         guint8 *code, *buf;
736         guint8 *jump_obj_null, *jump_sync_null, *jump_other_owner, *jump_cmpxchg_failed, *jump_tid, *jump_sync_thin_hash = NULL;
737         int tramp_size;
738         int owner_offset, nest_offset, dummy;
739         MonoJumpInfo *ji = NULL;
740         GSList *unwind_ops = NULL;
741
742         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == X86_EAX);
743
744         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &dummy);
745         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
746         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
747         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
748         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
749
750         tramp_size = NACL_SIZE (64, 128);
751
752         code = buf = mono_global_codeman_reserve (tramp_size);
753
754         if (mono_thread_get_tls_offset () != -1) {
755                 /* MonoObject* obj is in EAX */
756                 /* is obj null? */
757                 x86_test_reg_reg (code, X86_EAX, X86_EAX);
758                 /* if yes, jump to actual trampoline */
759                 jump_obj_null = code;
760                 x86_branch8 (code, X86_CC_Z, -1, 1);
761
762                 /* load obj->synchronization to ECX */
763                 x86_mov_reg_membase (code, X86_ECX, X86_EAX, G_STRUCT_OFFSET (MonoObject, synchronisation), 4);
764
765                 if (mono_gc_is_moving ()) {
766                         /*if bit zero is set it's a thin hash*/
767                         /*FIXME use testb encoding*/
768                         x86_test_reg_imm (code, X86_ECX, 0x01);
769                         jump_sync_thin_hash = code;
770                         x86_branch8 (code, X86_CC_NE, -1, 1);
771
772                         /*clear bits used by the gc*/
773                         x86_alu_reg_imm (code, X86_AND, X86_ECX, ~0x3);
774                 }
775
776                 /* is synchronization null? */
777                 x86_test_reg_reg (code, X86_ECX, X86_ECX);
778
779                 /* if yes, jump to actual trampoline */
780                 jump_sync_null = code;
781                 x86_branch8 (code, X86_CC_Z, -1, 1);
782
783                 /* load MonoInternalThread* into EDX */
784                 code = mono_x86_emit_tls_get (code, X86_EDX, mono_thread_get_tls_offset ());
785                 /* load TID into EDX */
786                 x86_mov_reg_membase (code, X86_EDX, X86_EDX, G_STRUCT_OFFSET (MonoInternalThread, tid), 4);
787
788                 /* is synchronization->owner null? */
789                 x86_alu_membase_imm (code, X86_CMP, X86_ECX, owner_offset, 0);
790                 /* if not, jump to next case */
791                 jump_tid = code;
792                 x86_branch8 (code, X86_CC_NZ, -1, 1);
793
794                 /* if yes, try a compare-exchange with the TID */
795                 /* free up register EAX, needed for the zero */
796                 x86_push_reg (code, X86_EAX);
797                 /* zero EAX */
798                 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
799                 /* compare and exchange */
800                 x86_prefix (code, X86_LOCK_PREFIX);
801                 x86_cmpxchg_membase_reg (code, X86_ECX, owner_offset, X86_EDX);
802                 /* if not successful, jump to actual trampoline */
803                 jump_cmpxchg_failed = code;
804                 x86_branch8 (code, X86_CC_NZ, -1, 1);
805                 /* if successful, pop and return */
806                 x86_pop_reg (code, X86_EAX);
807                 x86_ret (code);
808
809                 /* next case: synchronization->owner is not null */
810                 x86_patch (jump_tid, code);
811                 /* is synchronization->owner == TID? */
812                 x86_alu_membase_reg (code, X86_CMP, X86_ECX, owner_offset, X86_EDX);
813                 /* if not, jump to actual trampoline */
814                 jump_other_owner = code;
815                 x86_branch8 (code, X86_CC_NZ, -1, 1);
816                 /* if yes, increment nest */
817                 x86_inc_membase (code, X86_ECX, nest_offset);
818                 /* return */
819                 x86_ret (code);
820
821                 /* push obj */
822                 x86_patch (jump_obj_null, code);
823                 if (jump_sync_thin_hash)
824                         x86_patch (jump_sync_thin_hash, code);
825                 x86_patch (jump_sync_null, code);
826                 x86_patch (jump_other_owner, code);
827                 x86_push_reg (code, X86_EAX);
828                 /* jump to the actual trampoline */
829                 x86_patch (jump_cmpxchg_failed, code);
830                 if (aot) {
831                         /* We are calling the generic trampoline directly, the argument is pushed
832                          * on the stack just like a specific trampoline.
833                          */
834                         code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "generic_trampoline_monitor_enter");
835                         x86_jump_reg (code, X86_EAX);
836                 } else {
837                         x86_jump_code (code, tramp);
838                 }
839         } else {
840                 /* push obj and jump to the actual trampoline */
841                 x86_push_reg (code, X86_EAX);
842                 if (aot) {
843                         code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "generic_trampoline_monitor_enter");
844                         x86_jump_reg (code, X86_EAX);
845                 } else {
846                         x86_jump_code (code, tramp);
847                 }
848         }
849
850         mono_arch_flush_icache (buf, code - buf);
851         g_assert (code - buf <= tramp_size);
852
853         if (info)
854                 *info = mono_tramp_info_create (g_strdup_printf ("monitor_enter_trampoline"), buf, code - buf, ji, unwind_ops);
855
856         return buf;
857 }
858
859 gpointer
860 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
861 {
862         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_MONITOR_EXIT);
863         guint8 *code, *buf;
864         guint8 *jump_obj_null, *jump_have_waiters, *jump_sync_null, *jump_not_owned, *jump_sync_thin_hash = NULL;
865         guint8 *jump_next;
866         int tramp_size;
867         int owner_offset, nest_offset, entry_count_offset;
868         MonoJumpInfo *ji = NULL;
869         GSList *unwind_ops = NULL;
870
871         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == X86_EAX);
872
873         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &entry_count_offset);
874         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
875         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
876         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (entry_count_offset) == sizeof (gint32));
877         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
878         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
879         entry_count_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (entry_count_offset);
880
881         tramp_size = NACL_SIZE (96, 128);
882
883         code = buf = mono_global_codeman_reserve (tramp_size);
884
885         if (mono_thread_get_tls_offset () != -1) {
886                 /* MonoObject* obj is in EAX */
887                 /* is obj null? */
888                 x86_test_reg_reg (code, X86_EAX, X86_EAX);
889                 /* if yes, jump to actual trampoline */
890                 jump_obj_null = code;
891                 x86_branch8 (code, X86_CC_Z, -1, 1);
892
893                 /* load obj->synchronization to ECX */
894                 x86_mov_reg_membase (code, X86_ECX, X86_EAX, G_STRUCT_OFFSET (MonoObject, synchronisation), 4);
895
896                 if (mono_gc_is_moving ()) {
897                         /*if bit zero is set it's a thin hash*/
898                         /*FIXME use testb encoding*/
899                         x86_test_reg_imm (code, X86_ECX, 0x01);
900                         jump_sync_thin_hash = code;
901                         x86_branch8 (code, X86_CC_NE, -1, 1);
902
903                         /*clear bits used by the gc*/
904                         x86_alu_reg_imm (code, X86_AND, X86_ECX, ~0x3);
905                 }
906
907                 /* is synchronization null? */
908                 x86_test_reg_reg (code, X86_ECX, X86_ECX);
909                 /* if yes, jump to actual trampoline */
910                 jump_sync_null = code;
911                 x86_branch8 (code, X86_CC_Z, -1, 1);
912
913                 /* next case: synchronization is not null */
914                 /* load MonoInternalThread* into EDX */
915                 code = mono_x86_emit_tls_get (code, X86_EDX, mono_thread_get_tls_offset ());
916                 /* load TID into EDX */
917                 x86_mov_reg_membase (code, X86_EDX, X86_EDX, G_STRUCT_OFFSET (MonoInternalThread, tid), 4);
918                 /* is synchronization->owner == TID */
919                 x86_alu_membase_reg (code, X86_CMP, X86_ECX, owner_offset, X86_EDX);
920                 /* if no, jump to actual trampoline */
921                 jump_not_owned = code;
922                 x86_branch8 (code, X86_CC_NZ, -1, 1);
923
924                 /* next case: synchronization->owner == TID */
925                 /* is synchronization->nest == 1 */
926                 x86_alu_membase_imm (code, X86_CMP, X86_ECX, nest_offset, 1);
927                 /* if not, jump to next case */
928                 jump_next = code;
929                 x86_branch8 (code, X86_CC_NZ, -1, 1);
930                 /* if yes, is synchronization->entry_count zero? */
931                 x86_alu_membase_imm (code, X86_CMP, X86_ECX, entry_count_offset, 0);
932                 /* if not, jump to actual trampoline */
933                 jump_have_waiters = code;
934                 x86_branch8 (code, X86_CC_NZ, -1 , 1);
935                 /* if yes, set synchronization->owner to null and return */
936                 x86_mov_membase_imm (code, X86_ECX, owner_offset, 0, 4);
937                 x86_ret (code);
938
939                 /* next case: synchronization->nest is not 1 */
940                 x86_patch (jump_next, code);
941                 /* decrease synchronization->nest and return */
942                 x86_dec_membase (code, X86_ECX, nest_offset);
943                 x86_ret (code);
944
945                 /* push obj and jump to the actual trampoline */
946                 x86_patch (jump_obj_null, code);
947                 if (jump_sync_thin_hash)
948                         x86_patch (jump_sync_thin_hash, code);
949                 x86_patch (jump_have_waiters, code);
950                 x86_patch (jump_not_owned, code);
951                 x86_patch (jump_sync_null, code);
952         }
953
954         /* push obj and jump to the actual trampoline */
955         x86_push_reg (code, X86_EAX);
956         if (aot) {
957                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "generic_trampoline_monitor_exit");
958                 x86_jump_reg (code, X86_EAX);
959         } else {
960                 x86_jump_code (code, tramp);
961         }
962
963         mono_arch_flush_icache (buf, code - buf);
964         g_assert (code - buf <= tramp_size);
965
966         if (info)
967                 *info = mono_tramp_info_create (g_strdup_printf ("monitor_exit_trampoline"), buf, code - buf, ji, unwind_ops);
968
969         return buf;
970 }
971
972 #else
973
974 gpointer
975 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean aot)
976 {
977         g_assert_not_reached ();
978         return NULL;
979 }
980
981 gpointer
982 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
983 {
984         g_assert_not_reached ();
985         return NULL;
986 }
987
988 #endif
989
990 void
991 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
992 {
993         /* FIXME: This is not thread safe */
994         guint8 *code = ji->code_start;
995
996         x86_push_imm (code, func_arg);
997         x86_call_code (code, (guint8*)func);
998 }
999
1000 static void
1001 handler_block_trampoline_helper (gpointer *ptr)
1002 {
1003         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1004         *ptr = jit_tls->handler_block_return_address;
1005 }
1006
1007 gpointer
1008 mono_arch_create_handler_block_trampoline (void)
1009 {
1010         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1011         guint8 *code, *buf;
1012         int tramp_size = 64;
1013         code = buf = mono_global_codeman_reserve (tramp_size);
1014
1015         /*
1016         This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
1017         */
1018
1019         if (mono_get_jit_tls_offset () != -1) {
1020                 code = mono_x86_emit_tls_get (code, X86_EAX, mono_get_jit_tls_offset ());
1021                 x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 4);
1022                 /*simulate a call*/
1023                 /*Fix stack alignment*/
1024                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x8);
1025                 x86_push_reg (code, X86_EAX);
1026                 x86_jump_code (code, tramp);
1027         } else {
1028                 /*Slow path uses a c helper*/
1029                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x8);
1030                 x86_push_reg (code, X86_ESP);
1031                 x86_push_imm (code, tramp);
1032                 x86_jump_code (code, handler_block_trampoline_helper);
1033         }
1034
1035         mono_arch_flush_icache (buf, code - buf);
1036         g_assert (code - buf <= tramp_size);
1037
1038         if (mono_jit_map_is_enabled ())
1039                 mono_emit_jit_tramp (buf, code - buf, "handler_block_trampoline");
1040
1041         return buf;
1042 }
1043
1044 guint8*
1045 mono_arch_get_call_target (guint8 *code)
1046 {
1047         if (code [-5] == 0xe8) {
1048                 guint32 disp = *(guint32*)(code - 4);
1049                 guint8 *target = code + disp;
1050
1051                 return target;
1052         } else {
1053                 return NULL;
1054         }
1055 }
1056
1057 guint32
1058 mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
1059 {
1060         return *(guint32*)(plt_entry + NACL_SIZE (6, 12));
1061 }