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