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