2008-10-21 Rodrigo Kumpera <rkumpera@novell.com>
[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/arch/x86/x86-codegen.h>
20
21 #ifdef HAVE_VALGRIND_MEMCHECK_H
22 #include <valgrind/memcheck.h>
23 #endif
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  * @gsctx: the generic sharing context
33  * @m: method pointer
34  * @addr: pointer to native code for @m
35  *
36  * when value type methods are called through the vtable we need to unbox the
37  * this argument. This method returns a pointer to a trampoline which does
38  * unboxing before calling the method
39  */
40 gpointer
41 mono_arch_get_unbox_trampoline (MonoGenericSharingContext *gsctx, MonoMethod *m, gpointer addr)
42 {
43         guint8 *code, *start;
44         int this_pos = 4;
45         MonoDomain *domain = mono_domain_get ();
46
47         if (MONO_TYPE_ISSTRUCT (mono_method_signature (m)->ret))
48                 this_pos = 8;
49             
50         mono_domain_lock (domain);
51         start = code = mono_code_manager_reserve (domain->code_mp, 16);
52         mono_domain_unlock (domain);
53
54         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
55         x86_jump_code (code, addr);
56         g_assert ((code - start) < 16);
57
58         return start;
59 }
60
61 void
62 mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
63 {
64         guint8 *code;
65         guint8 buf [8];
66         gboolean can_write = mono_breakpoint_clean_code (method_start, orig_code, 8, buf, sizeof (buf));
67
68         code = buf + 8;
69         if (mono_running_on_valgrind ())
70                 can_write = FALSE;
71
72         /* go to the start of the call instruction
73          *
74          * address_byte = (m << 6) | (o << 3) | reg
75          * call opcode: 0xff address_byte displacement
76          * 0xff m=1,o=2 imm8
77          * 0xff m=2,o=2 imm32
78          */
79         code -= 6;
80         orig_code -= 6;
81         if ((code [1] == 0xe8)) {
82                 if (can_write) {
83                         InterlockedExchange ((gint32*)(orig_code + 2), (guint)addr - ((guint)orig_code + 1) - 5);
84
85 #ifdef HAVE_VALGRIND_MEMCHECK_H
86                                 /* Tell valgrind to recompile the patched code */
87                                 //VALGRIND_DISCARD_TRANSLATIONS (code + 2, code + 6);
88 #endif
89                 }
90         } else if (code [1] == 0xe9) {
91                 /* A PLT entry: jmp <DISP> */
92                 if (can_write)
93                         InterlockedExchange ((gint32*)(orig_code + 2), (guint)addr - ((guint)orig_code + 1) - 5);
94         } else {
95                 printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", code [0], code [1], code [2], code [3],
96                                 code [4], code [5], code [6]);
97                 g_assert_not_reached ();
98         }
99 }
100
101 void
102 mono_arch_patch_plt_entry (guint8 *code, guint8 *addr)
103 {
104         /* A PLT entry: jmp <DISP> */
105         g_assert (code [0] == 0xe9);
106
107         if (!mono_running_on_valgrind ())
108                 InterlockedExchange ((gint32*)(code + 1), (guint)addr - (guint)code - 5);
109 }
110
111 void
112 mono_arch_nullify_class_init_trampoline (guint8 *code, gssize *regs)
113 {
114         guint8 buf [16];
115         gboolean can_write = mono_breakpoint_clean_code (NULL, code, 6, buf, sizeof (buf));
116
117         if (!can_write)
118                 return;
119
120         code -= 5;
121         if (code [0] == 0xe8) {
122                 if (!mono_running_on_valgrind ()) {
123                         guint32 ops;
124                         /*
125                          * Thread safe code patching using the algorithm from the paper
126                          * 'Practicing JUDO: Java Under Dynamic Optimizations'
127                          */
128                         /* 
129                          * First atomically change the the first 2 bytes of the call to a
130                          * spinning jump.
131                          */
132                         ops = 0xfeeb;
133                         InterlockedExchange ((gint32*)code, ops);
134
135                         /* Then change the other bytes to a nop */
136                         code [2] = 0x90;
137                         code [3] = 0x90;
138                         code [4] = 0x90;
139
140                         /* Then atomically change the first 4 bytes to a nop as well */
141                         ops = 0x90909090;
142                         InterlockedExchange ((gint32*)code, ops);
143 #ifdef HAVE_VALGRIND_MEMCHECK_H
144                         /* FIXME: the calltree skin trips on the self modifying code above */
145
146                         /* Tell valgrind to recompile the patched code */
147                         //VALGRIND_DISCARD_TRANSLATIONS (code, code + 8);
148 #endif
149                 }
150         } else if (code [0] == 0x90 || code [0] == 0xeb) {
151                 /* Already changed by another thread */
152                 ;
153         } else if ((code [-1] == 0xff) && (x86_modrm_reg (code [0]) == 0x2)) {
154                 /* call *<OFFSET>(<REG>) -> Call made from AOT code */
155                 gpointer *vtable_slot;
156
157                 vtable_slot = mono_arch_get_vcall_slot_addr (code + 5, (gpointer*)regs);
158                 g_assert (vtable_slot);
159
160                 *vtable_slot = nullified_class_init_trampoline;
161         } else {
162                         printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", code [0], code [1], code [2], code [3],
163                                 code [4], code [5], code [6]);
164                         g_assert_not_reached ();
165                 }
166 }
167
168 void
169 mono_arch_nullify_plt_entry (guint8 *code)
170 {
171         if (!mono_running_on_valgrind ()) {
172                 guint32 ops;
173
174                 ops = 0xfeeb;
175                 InterlockedExchange ((gint32*)code, ops);
176
177                 /* Then change the other bytes to a nop */
178                 code [2] = 0x90;
179                 code [3] = 0x90;
180                 code [4] = 0x90;
181
182                 /* Change the first byte to a nop */
183                 ops = 0xc3;
184                 InterlockedExchange ((gint32*)code, ops);
185         }
186 }
187
188 guchar*
189 mono_arch_create_trampoline_code (MonoTrampolineType tramp_type)
190 {
191         guint8 *buf, *code, *tramp;
192         int pushed_args, pushed_args_caller_saved;
193
194         code = buf = mono_global_codeman_reserve (256);
195
196         /* Note that there is a single argument to the trampoline
197          * and it is stored at: esp + pushed_args * sizeof (gpointer)
198          * the ret address is at: esp + (pushed_args + 1) * sizeof (gpointer)
199          */
200
201         /* Put all registers into an array on the stack
202          * If this code is changed, make sure to update the offset value in
203          * mono_arch_find_this_argument () in mini-x86.c.
204          */
205         x86_push_reg (buf, X86_EDI);
206         x86_push_reg (buf, X86_ESI);
207         x86_push_reg (buf, X86_EBP);
208         x86_push_reg (buf, X86_ESP);
209         x86_push_reg (buf, X86_EBX);
210         x86_push_reg (buf, X86_EDX);
211         x86_push_reg (buf, X86_ECX);
212         x86_push_reg (buf, X86_EAX);
213
214         pushed_args_caller_saved = pushed_args = 8;
215
216         /* Align stack on apple */
217         x86_alu_reg_imm (buf, X86_SUB, X86_ESP, 4);
218
219         pushed_args ++;
220
221         /* save LMF begin */
222
223         /* save the IP (caller ip) */
224         if (tramp_type == MONO_TRAMPOLINE_JUMP)
225                 x86_push_imm (buf, 0);
226         else
227                 x86_push_membase (buf, X86_ESP, (pushed_args + 1) * sizeof (gpointer));
228
229         pushed_args++;
230
231         x86_push_reg (buf, X86_EBP);
232         x86_push_reg (buf, X86_ESI);
233         x86_push_reg (buf, X86_EDI);
234         x86_push_reg (buf, X86_EBX);
235
236         pushed_args += 4;
237
238         /* save ESP */
239         x86_push_reg (buf, X86_ESP);
240         /* Adjust ESP so it points to the previous frame */
241         x86_alu_membase_imm (buf, X86_ADD, X86_ESP, 0, (pushed_args + 2) * 4);
242
243         pushed_args ++;
244
245         /* save method info */
246         if ((tramp_type == MONO_TRAMPOLINE_JIT) || (tramp_type == MONO_TRAMPOLINE_JUMP))
247                 x86_push_membase (buf, X86_ESP, pushed_args * sizeof (gpointer));
248         else
249                 x86_push_imm (buf, 0);
250
251         pushed_args++;
252
253         /* On apple, the stack is correctly aligned to 16 bytes because pushed_args is
254          * 16 and there is the extra trampoline arg + the return ip pushed by call
255          * FIXME: Note that if an exception happens while some args are pushed
256          * on the stack, the stack will be misaligned.
257          */
258         g_assert (pushed_args == 16);
259
260         /* get the address of lmf for the current thread */
261         x86_call_code (buf, mono_get_lmf_addr);
262         /* push lmf */
263         x86_push_reg (buf, X86_EAX); 
264         /* push *lfm (previous_lmf) */
265         x86_push_membase (buf, X86_EAX, 0);
266         /* Signal to mono_arch_find_jit_info () that this is a trampoline frame */
267         x86_alu_membase_imm (buf, X86_ADD, X86_ESP, 0, 1);
268         /* *(lmf) = ESP */
269         x86_mov_membase_reg (buf, X86_EAX, 0, X86_ESP, 4);
270         /* save LFM end */
271
272         pushed_args += 2;
273
274         /* starting the call sequence */
275
276         /* FIXME: Push the trampoline address */
277         x86_push_imm (buf, 0);
278
279         pushed_args++;
280
281         /* push the method info */
282         x86_push_membase (buf, X86_ESP, pushed_args * sizeof (gpointer));
283
284         pushed_args++;
285
286         /* push the return address onto the stack */
287         if (tramp_type == MONO_TRAMPOLINE_JUMP)
288                 x86_push_imm (buf, 0);
289         else
290                 x86_push_membase (buf, X86_ESP, (pushed_args + 1) * sizeof (gpointer));
291         pushed_args++;
292         /* push the address of the register array */
293         x86_lea_membase (buf, X86_EAX, X86_ESP, (pushed_args - 8) * sizeof (gpointer));
294         x86_push_reg (buf, X86_EAX);
295
296         pushed_args++;
297
298 #ifdef __APPLE__
299         /* check the stack is aligned after the ret ip is pushed */
300         /*x86_mov_reg_reg (buf, X86_EDX, X86_ESP, 4);
301         x86_alu_reg_imm (buf, X86_AND, X86_EDX, 15);
302         x86_alu_reg_imm (buf, X86_CMP, X86_EDX, 0);
303         x86_branch_disp (buf, X86_CC_Z, 3, FALSE);
304         x86_breakpoint (buf);*/
305 #endif
306
307         tramp = (guint8*)mono_get_trampoline_func (tramp_type);
308         x86_call_code (buf, tramp);
309
310         x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 4*4);
311
312         pushed_args -= 4;
313
314         /* Check for thread interruption */
315         /* This is not perf critical code so no need to check the interrupt flag */
316         x86_push_reg (buf, X86_EAX);
317         x86_call_code (buf, (guint8*)mono_thread_force_interruption_checkpoint);
318         x86_pop_reg (buf, X86_EAX);
319
320         /* Restore LMF */
321
322         /* ebx = previous_lmf */
323         x86_pop_reg (buf, X86_EBX);
324         pushed_args--;
325         x86_alu_reg_imm (buf, X86_SUB, X86_EBX, 1);
326
327         /* edi = lmf */
328         x86_pop_reg (buf, X86_EDI);
329         pushed_args--;
330
331         /* *(lmf) = previous_lmf */
332         x86_mov_membase_reg (buf, X86_EDI, 0, X86_EBX, 4);
333
334         /* discard method info */
335         x86_pop_reg (buf, X86_ESI);
336         pushed_args--;
337
338         /* discard ESP */
339         x86_pop_reg (buf, X86_ESI);
340         pushed_args--;
341
342         /* restore caller saved regs */
343         x86_pop_reg (buf, X86_EBX);
344         x86_pop_reg (buf, X86_EDI);
345         x86_pop_reg (buf, X86_ESI);
346         x86_pop_reg (buf, X86_EBP);
347
348         pushed_args -= 4;
349
350         /* discard save IP */
351         x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 4);
352         pushed_args--;
353
354         /* restore LMF end */
355
356         /* Restore caller saved registers */
357         x86_mov_reg_membase (buf, X86_ECX, X86_ESP, (pushed_args - pushed_args_caller_saved + X86_ECX) * 4, 4);
358         x86_mov_reg_membase (buf, X86_EDX, X86_ESP, (pushed_args - pushed_args_caller_saved + X86_EDX) * 4, 4);
359         if (tramp_type == MONO_TRAMPOLINE_RESTORE_STACK_PROT)
360                 x86_mov_reg_membase (buf, X86_EAX, X86_ESP, (pushed_args - pushed_args_caller_saved + X86_EAX) * 4, 4);
361
362         /* Pop saved reg array + stack align + method ptr */
363         x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 10 * 4);
364
365         pushed_args -= 10;
366
367         /* We've popped one more stack item than we've pushed (the
368            method ptr argument), so we must end up at -1. */
369         g_assert (pushed_args == -1);
370
371         if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT ||
372                         tramp_type == MONO_TRAMPOLINE_GENERIC_CLASS_INIT ||
373                         tramp_type == MONO_TRAMPOLINE_RESTORE_STACK_PROT ||
374                         tramp_type == MONO_TRAMPOLINE_RGCTX_LAZY_FETCH)
375                 x86_ret (buf);
376         else
377                 /* call the compiled method */
378                 x86_jump_reg (buf, X86_EAX);
379
380         g_assert ((buf - code) <= 256);
381
382         if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT) {
383                 /* Initialize the nullified class init trampoline used in the AOT case */
384                 nullified_class_init_trampoline = buf = mono_global_codeman_reserve (16);
385                 x86_ret (buf);
386         }
387
388         return code;
389 }
390
391 #define TRAMPOLINE_SIZE 10
392
393 gpointer
394 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
395 {
396         guint8 *code, *buf, *tramp;
397         
398         tramp = mono_get_trampoline_code (tramp_type);
399
400         mono_domain_lock (domain);
401         code = buf = mono_code_manager_reserve_align (domain->code_mp, TRAMPOLINE_SIZE, 4);
402         mono_domain_unlock (domain);
403
404         x86_push_imm (buf, arg1);
405         x86_jump_code (buf, tramp);
406         g_assert ((buf - code) <= TRAMPOLINE_SIZE);
407
408         mono_arch_flush_icache (code, buf - code);
409
410         if (code_len)
411                 *code_len = buf - code;
412
413         return code;
414 }
415
416 gpointer
417 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot)
418 {
419         guint8 *tramp;
420         guint8 *code, *buf;
421         guint8 **rgctx_null_jumps;
422         int tramp_size;
423         int depth, index;
424         int i;
425         gboolean mrgctx;
426
427         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
428         index = MONO_RGCTX_SLOT_INDEX (slot);
429         if (mrgctx)
430                 index += sizeof (MonoMethodRuntimeGenericContext) / sizeof (gpointer);
431         for (depth = 0; ; ++depth) {
432                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
433
434                 if (index < size - 1)
435                         break;
436                 index -= size - 1;
437         }
438
439         tramp_size = 36 + 6 * depth;
440
441         code = buf = mono_global_codeman_reserve (tramp_size);
442
443         rgctx_null_jumps = g_malloc (sizeof (guint8*) * (depth + 2));
444
445         /* load vtable/mrgctx ptr */
446         x86_mov_reg_membase (buf, X86_EAX, X86_ESP, 4, 4);
447         if (!mrgctx) {
448                 /* load rgctx ptr from vtable */
449                 x86_mov_reg_membase (buf, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context), 4);
450                 /* is the rgctx ptr null? */
451                 x86_test_reg_reg (buf, X86_EAX, X86_EAX);
452                 /* if yes, jump to actual trampoline */
453                 rgctx_null_jumps [0] = buf;
454                 x86_branch8 (buf, X86_CC_Z, -1, 1);
455         }
456
457         for (i = 0; i < depth; ++i) {
458                 /* load ptr to next array */
459                 if (mrgctx && i == 0)
460                         x86_mov_reg_membase (buf, X86_EAX, X86_EAX, sizeof (MonoMethodRuntimeGenericContext), 4);
461                 else
462                         x86_mov_reg_membase (buf, X86_EAX, X86_EAX, 0, 4);
463                 /* is the ptr null? */
464                 x86_test_reg_reg (buf, X86_EAX, X86_EAX);
465                 /* if yes, jump to actual trampoline */
466                 rgctx_null_jumps [i + 1] = buf;
467                 x86_branch8 (buf, X86_CC_Z, -1, 1);
468         }
469
470         /* fetch slot */
471         x86_mov_reg_membase (buf, X86_EAX, X86_EAX, sizeof (gpointer) * (index + 1), 4);
472         /* is the slot null? */
473         x86_test_reg_reg (buf, X86_EAX, X86_EAX);
474         /* if yes, jump to actual trampoline */
475         rgctx_null_jumps [depth + 1] = buf;
476         x86_branch8 (buf, X86_CC_Z, -1, 1);
477         /* otherwise return */
478         x86_ret (buf);
479
480         for (i = mrgctx ? 1 : 0; i <= depth + 1; ++i)
481                 x86_patch (rgctx_null_jumps [i], buf);
482
483         g_free (rgctx_null_jumps);
484
485         x86_mov_reg_membase (buf, MONO_ARCH_VTABLE_REG, X86_ESP, 4, 4);
486
487         tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
488
489         /* jump to the actual trampoline */
490         x86_jump_code (buf, tramp);
491
492         mono_arch_flush_icache (code, buf - code);
493
494         g_assert (buf - code <= tramp_size);
495
496         return code;
497 }
498
499 gpointer
500 mono_arch_create_generic_class_init_trampoline (void)
501 {
502         guint8 *tramp;
503         guint8 *code, *buf;
504         static int byte_offset = -1;
505         static guint8 bitmask;
506         guint8 *jump;
507         int tramp_size;
508
509         tramp_size = 64;
510
511         code = buf = mono_global_codeman_reserve (tramp_size);
512
513         if (byte_offset < 0)
514                 mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
515
516         x86_test_membase_imm (code, MONO_ARCH_VTABLE_REG, byte_offset, bitmask);
517         jump = code;
518         x86_branch8 (code, X86_CC_Z, -1, 1);
519
520         x86_ret (code);
521
522         x86_patch (jump, code);
523
524         /* Push the vtable so the stack is the same as in a specific trampoline */
525         x86_push_reg (code, MONO_ARCH_VTABLE_REG);
526
527         tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
528
529         /* jump to the actual trampoline */
530         x86_jump_code (code, tramp);
531
532         mono_arch_flush_icache (code, code - buf);
533
534         g_assert (code - buf <= tramp_size);
535
536         return buf;
537 }
538
539 void
540 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
541 {
542         /* FIXME: This is not thread safe */
543         guint8 *code = ji->code_start;
544
545         x86_push_imm (code, func_arg);
546         x86_call_code (code, (guint8*)func);
547 }