Fix the build.
[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/abi-details.h>
14 #include <mono/metadata/appdomain.h>
15 #include <mono/metadata/metadata-internals.h>
16 #include <mono/metadata/marshal.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/mono-debug.h>
19 #include <mono/metadata/mono-debug-debugger.h>
20 #include <mono/metadata/profiler-private.h>
21 #include <mono/metadata/gc-internals.h>
22 #include <mono/arch/x86/x86-codegen.h>
23
24 #include <mono/utils/memcheck.h>
25
26 #include "mini.h"
27 #include "mini-x86.h"
28 #include "debugger-agent.h"
29 #include "jit-icalls.h"
30
31 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
32
33 /*
34  * mono_arch_get_unbox_trampoline:
35  * @m: method pointer
36  * @addr: pointer to native code for @m
37  *
38  * when value type methods are called through the vtable we need to unbox the
39  * this argument. This method returns a pointer to a trampoline which does
40  * unboxing before calling the method
41  */
42 gpointer
43 mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
44 {
45         guint8 *code, *start;
46         int this_pos = 4, size = NACL_SIZE(16, 32);
47         MonoDomain *domain = mono_domain_get ();
48         GSList *unwind_ops;
49
50         start = code = mono_domain_code_reserve (domain, size);
51
52         unwind_ops = mono_arch_get_cie_program ();
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) < size);
57
58         nacl_domain_code_validate (domain, &start, size, &code);
59         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_UNBOX_TRAMPOLINE, m);
60
61         mono_tramp_info_register (mono_tramp_info_create (NULL, start, code - start, NULL, unwind_ops), domain);
62
63         return start;
64 }
65
66 gpointer
67 mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
68 {
69         guint8 *code, *start;
70         int buf_len;
71         GSList *unwind_ops;
72
73         MonoDomain *domain = mono_domain_get ();
74
75         buf_len = NACL_SIZE (10, 32);
76
77         start = code = mono_domain_code_reserve (domain, buf_len);
78
79         unwind_ops = mono_arch_get_cie_program ();
80
81         x86_mov_reg_imm (code, MONO_ARCH_RGCTX_REG, mrgctx);
82         x86_jump_code (code, addr);
83         g_assert ((code - start) <= buf_len);
84
85         nacl_domain_code_validate (domain, &start, buf_len, &code);
86         mono_arch_flush_icache (start, code - start);
87         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE, NULL);
88
89         mono_tramp_info_register (mono_tramp_info_create (NULL, start, code - start, NULL, unwind_ops), domain);
90
91         return start;
92 }
93
94 void
95 mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
96 {
97 #if defined(__default_codegen__)
98         guint8 *code;
99         guint8 buf [8];
100         gboolean can_write = mono_breakpoint_clean_code (method_start, orig_code, 8, buf, sizeof (buf));
101
102         code = buf + 8;
103
104         /* go to the start of the call instruction
105          *
106          * address_byte = (m << 6) | (o << 3) | reg
107          * call opcode: 0xff address_byte displacement
108          * 0xff m=1,o=2 imm8
109          * 0xff m=2,o=2 imm32
110          */
111         code -= 6;
112         orig_code -= 6;
113         if (code [1] == 0xe8) {
114                 if (can_write) {
115                         InterlockedExchange ((gint32*)(orig_code + 2), (guint)addr - ((guint)orig_code + 1) - 5);
116
117                         /* Tell valgrind to recompile the patched code */
118                         VALGRIND_DISCARD_TRANSLATIONS (orig_code + 2, 4);
119                 }
120         } else if (code [1] == 0xe9) {
121                 /* A PLT entry: jmp <DISP> */
122                 if (can_write)
123                         InterlockedExchange ((gint32*)(orig_code + 2), (guint)addr - ((guint)orig_code + 1) - 5);
124         } else {
125                 printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", code [0], code [1], code [2], code [3],
126                                 code [4], code [5], code [6]);
127                 g_assert_not_reached ();
128         }
129 #elif defined(__native_client__)
130         /* Target must be bundle-aligned */
131         g_assert (((guint32)addr & kNaClAlignmentMask) == 0);
132
133         /* 0xe8 = call <DISP>, 0xe9 = jump <DISP> */
134         if ((orig_code [-5] == 0xe8) || orig_code [-6] == 0xe9) {
135                 int ret;
136                 gint32 offset = (gint32)addr - (gint32)orig_code;
137                 guint8 buf[sizeof(gint32)];
138                 *((gint32*)(buf)) = offset;
139                 ret = nacl_dyncode_modify (orig_code - sizeof(gint32), buf, sizeof(gint32));
140                 g_assert (ret == 0);
141         } else {
142                 printf ("Invalid trampoline sequence %p: %02x %02x %02x %02x %02x\n", orig_code, orig_code [-5], orig_code [-4], orig_code [-3], orig_code [-2], orig_code[-1]);
143                 g_assert_not_reached ();
144         }
145 #endif
146 }
147
148 void
149 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
150 {
151         guint32 offset;
152
153         /* Patch the jump table entry used by the plt entry */
154
155 #if defined(__native_client_codegen__) || defined(__native_client__)
156         /* for both compiler and runtime      */
157         /* A PLT entry:                       */
158         /*        mov <DISP>(%ebx), %ecx      */
159         /*        and 0xffffffe0, %ecx        */
160         /*        jmp *%ecx                   */
161         g_assert (code [0] == 0x8b);
162         g_assert (code [1] == 0x8b);
163
164         offset = *(guint32*)(code + 2);
165 #elif defined(__default_codegen__)
166         /* A PLT entry: jmp *<DISP>(%ebx) */
167         g_assert (code [0] == 0xff);
168         g_assert (code [1] == 0xa3);
169
170         offset = *(guint32*)(code + 2);
171 #endif  /* __native_client_codegen__ */
172         if (!got)
173                 got = (gpointer*)(gsize) regs [MONO_ARCH_GOT_REG];
174         *(guint8**)((guint8*)got + offset) = addr;
175 }
176
177 static gpointer
178 get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
179 {
180         const int kBufSize = NACL_SIZE (8, 16);
181         guint8 buf [64];
182         guint8 reg = 0;
183         gint32 disp = 0;
184
185         mono_breakpoint_clean_code (NULL, code, kBufSize, buf, kBufSize);
186         code = buf + 8;
187
188         *displacement = 0;
189
190         if ((code [0] == 0xff) && ((code [1] & 0x18) == 0x10) && ((code [1] >> 6) == 2)) {
191                 reg = code [1] & 0x07;
192                 disp = *((gint32*)(code + 2));
193 #if defined(__native_client_codegen__) || defined(__native_client__)
194         } else if ((code[1] == 0x83) && (code[2] == 0xe1) && (code[4] == 0xff) &&
195                            (code[5] == 0xd1) && (code[-5] == 0x8b)) {
196                 disp = *((gint32*)(code - 3));
197                 reg = code[-4] & 0x07;
198         } else if ((code[-2] == 0x8b) && (code[1] == 0x83) && (code[4] == 0xff)) {
199                 reg = code[-1] & 0x07;
200                 disp = (signed char)code[0];
201 #endif
202         } else {
203                 g_assert_not_reached ();
204                 return NULL;
205         }
206
207         *displacement = disp;
208         return (gpointer)regs [reg];
209 }
210
211 static gpointer*
212 get_vcall_slot_addr (guint8* code, mgreg_t *regs)
213 {
214         gpointer vt;
215         int displacement;
216         vt = get_vcall_slot (code, regs, &displacement);
217         if (!vt)
218                 return NULL;
219         return (gpointer*)((char*)vt + displacement);
220 }
221
222 guchar*
223 mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
224 {
225         char *tramp_name;
226         guint8 *buf, *code, *tramp;
227         GSList *unwind_ops = NULL;
228         MonoJumpInfo *ji = NULL;
229         int i, offset, frame_size, regarray_offset, lmf_offset, caller_ip_offset, arg_offset;
230         int cfa_offset; /* cfa = cfa_reg + cfa_offset */
231
232         code = buf = mono_global_codeman_reserve (256);
233
234         /* Note that there is a single argument to the trampoline
235          * and it is stored at: esp + pushed_args * sizeof (gpointer)
236          * the ret address is at: esp + (pushed_args + 1) * sizeof (gpointer)
237          */
238
239         /* Compute frame offsets relative to the frame pointer %ebp */
240         arg_offset = sizeof (mgreg_t);
241         caller_ip_offset = 2 * sizeof (mgreg_t);
242         offset = 0;
243         offset += sizeof (MonoLMF);
244         lmf_offset = -offset;
245         offset += X86_NREG * sizeof (mgreg_t);
246         regarray_offset = -offset;
247         /* Argument area */
248         offset += 4 * sizeof (mgreg_t);
249         frame_size = ALIGN_TO (offset, MONO_ARCH_FRAME_ALIGNMENT);
250
251         /* ret addr and arg are on the stack */
252         cfa_offset = 2 * sizeof (mgreg_t);
253         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, X86_ESP, cfa_offset);
254         // IP saved at CFA - 4
255         mono_add_unwind_op_offset (unwind_ops, code, buf, X86_NREG, -4);
256
257         /* Allocate frame */
258         x86_push_reg (code, X86_EBP);
259         cfa_offset += sizeof (mgreg_t);
260         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
261         mono_add_unwind_op_offset (unwind_ops, code, buf, X86_EBP, -cfa_offset);
262
263         x86_mov_reg_reg (code, X86_EBP, X86_ESP, sizeof (mgreg_t));
264         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, X86_EBP);
265
266         /* There are three words on the stack, adding + 4 aligns the stack to 16, which is needed on osx */
267         x86_alu_reg_imm (code, X86_SUB, X86_ESP, frame_size + sizeof (mgreg_t));
268
269         /* Save all registers */
270         for (i = X86_EAX; i <= X86_EDI; ++i) {
271                 int reg = i;
272
273                 if (i == X86_EBP) {
274                         /* Save original ebp */
275                         /* EAX is already saved */
276                         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 0, sizeof (mgreg_t));
277                         reg = X86_EAX;
278                 } else if (i == X86_ESP) {
279                         /* Save original esp */
280                         /* EAX is already saved */
281                         x86_mov_reg_reg (code, X86_EAX, X86_EBP, sizeof (mgreg_t));
282                         /* Saved ebp + trampoline arg + return addr */
283                         x86_alu_reg_imm (code, X86_ADD, X86_EAX, 3 * sizeof (mgreg_t));
284                         reg = X86_EAX;
285                 }
286                 x86_mov_membase_reg (code, X86_EBP, regarray_offset + (i * sizeof (mgreg_t)), reg, sizeof (mgreg_t));
287         }
288
289         /* Setup LMF */
290         /* eip */
291         if (tramp_type == MONO_TRAMPOLINE_JUMP) {
292                 x86_mov_membase_imm (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, eip), 0, sizeof (mgreg_t));
293         } else {
294                 x86_mov_reg_membase (code, X86_EAX, X86_EBP, caller_ip_offset, sizeof (mgreg_t));
295                 x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, eip), X86_EAX, sizeof (mgreg_t));
296         }
297         /* method */
298         if ((tramp_type == MONO_TRAMPOLINE_JIT) || (tramp_type == MONO_TRAMPOLINE_JUMP)) {
299                 x86_mov_reg_membase (code, X86_EAX, X86_EBP, arg_offset, sizeof (mgreg_t));
300                 x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), X86_EAX, sizeof (mgreg_t));
301         } else {
302                 x86_mov_membase_imm (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), 0, sizeof (mgreg_t));
303         }
304         /* esp */
305         x86_mov_reg_membase (code, X86_EAX, X86_EBP, regarray_offset + (X86_ESP * sizeof (mgreg_t)), sizeof (mgreg_t));
306         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, esp), X86_EAX, sizeof (mgreg_t));
307         /* callee save registers */
308         x86_mov_reg_membase (code, X86_EAX, X86_EBP, regarray_offset + (X86_EBX * sizeof (mgreg_t)), sizeof (mgreg_t));
309         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, ebx), X86_EAX, sizeof (mgreg_t));
310         x86_mov_reg_membase (code, X86_EAX, X86_EBP, regarray_offset + (X86_EDI * sizeof (mgreg_t)), sizeof (mgreg_t));
311         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, edi), X86_EAX, sizeof (mgreg_t));
312         x86_mov_reg_membase (code, X86_EAX, X86_EBP, regarray_offset + (X86_ESI * sizeof (mgreg_t)), sizeof (mgreg_t));
313         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, esi), X86_EAX, sizeof (mgreg_t));
314         x86_mov_reg_membase (code, X86_EAX, X86_EBP, regarray_offset + (X86_EBP * sizeof (mgreg_t)), sizeof (mgreg_t));
315         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, ebp), X86_EAX, sizeof (mgreg_t));
316
317         /* Push LMF */
318         /* get the address of lmf for the current thread */
319         if (aot) {
320                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_get_lmf_addr");
321                 x86_call_reg (code, X86_EAX);
322         } else {
323                 x86_call_code (code, mono_get_lmf_addr);
324         }
325         /* lmf->lmf_addr = lmf_addr (%eax) */
326         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), X86_EAX, sizeof (mgreg_t));
327         /* lmf->previous_lmf = *(lmf_addr) */
328         x86_mov_reg_membase (code, X86_ECX, X86_EAX, 0, sizeof (mgreg_t));
329         /* Signal to mono_arch_unwind_frame () that this is a trampoline frame */
330         x86_alu_reg_imm (code, X86_ADD, X86_ECX, 1);
331         x86_mov_membase_reg (code, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), X86_ECX, sizeof (mgreg_t));
332         /* *lmf_addr = lmf */
333         x86_lea_membase (code, X86_ECX, X86_EBP, lmf_offset);
334         x86_mov_membase_reg (code, X86_EAX, 0, X86_ECX, sizeof (mgreg_t));
335
336         /* Call trampoline function */
337         /* Arg 1 - registers */
338         x86_lea_membase (code, X86_EAX, X86_EBP, regarray_offset);
339         x86_mov_membase_reg (code, X86_ESP, (0 * sizeof (mgreg_t)), X86_EAX, sizeof (mgreg_t));
340         /* Arg2 - calling code */
341         if (tramp_type == MONO_TRAMPOLINE_JUMP) {
342                 x86_mov_membase_imm (code, X86_ESP, (1 * sizeof (mgreg_t)), 0, sizeof (mgreg_t));
343         } else {
344                 x86_mov_reg_membase (code, X86_EAX, X86_EBP, caller_ip_offset, sizeof (mgreg_t));
345                 x86_mov_membase_reg (code, X86_ESP, (1 * sizeof (mgreg_t)), X86_EAX, sizeof (mgreg_t));
346         }
347         /* Arg3 - trampoline argument */
348         x86_mov_reg_membase (code, X86_EAX, X86_EBP, arg_offset, sizeof (mgreg_t));
349         x86_mov_membase_reg (code, X86_ESP, (2 * sizeof (mgreg_t)), X86_EAX, sizeof (mgreg_t));
350         /* Arg4 - trampoline address */
351         // FIXME:
352         x86_mov_membase_imm (code, X86_ESP, (3 * sizeof (mgreg_t)), 0, sizeof (mgreg_t));
353
354 #ifdef __APPLE__
355         /* check the stack is aligned after the ret ip is pushed */
356         /*
357         x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
358         x86_alu_reg_imm (code, X86_AND, X86_EDX, 15);
359         x86_alu_reg_imm (code, X86_CMP, X86_EDX, 0);
360         x86_branch_disp (code, X86_CC_Z, 3, FALSE);
361         x86_breakpoint (code);
362         */
363 #endif
364
365         if (aot) {
366                 char *icall_name = g_strdup_printf ("trampoline_func_%d", tramp_type);
367                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
368                 x86_call_reg (code, X86_EAX);
369         } else {
370                 tramp = (guint8*)mono_get_trampoline_func (tramp_type);
371                 x86_call_code (code, tramp);
372         }
373
374         /*
375          * Overwrite the trampoline argument with the address we need to jump to,
376          * to free %eax.
377          */
378         x86_mov_membase_reg (code, X86_EBP, arg_offset, X86_EAX, 4);
379
380         /* Check for interruptions */
381         if (aot) {
382                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_interruption_checkpoint_from_trampoline");
383                 x86_call_reg (code, X86_EAX);
384         } else {
385                 x86_call_code (code, (guint8*)mono_interruption_checkpoint_from_trampoline);
386         }
387
388         /* Restore LMF */
389         x86_mov_reg_membase (code, X86_EAX, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof (mgreg_t));
390         x86_mov_reg_membase (code, X86_ECX, X86_EBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof (mgreg_t));
391         x86_alu_reg_imm (code, X86_SUB, X86_ECX, 1);
392         x86_mov_membase_reg (code, X86_EAX, 0, X86_ECX, sizeof (mgreg_t));
393
394         /* Restore registers */
395         for (i = X86_EAX; i <= X86_EDI; ++i) {
396                 if (i == X86_ESP || i == X86_EBP)
397                         continue;
398                 if (i == X86_EAX && !((tramp_type == MONO_TRAMPOLINE_RESTORE_STACK_PROT) || (tramp_type == MONO_TRAMPOLINE_AOT_PLT)))
399                         continue;
400                 x86_mov_reg_membase (code, i, X86_EBP, regarray_offset + (i * 4), 4);
401         }
402
403         /* Restore frame */
404         x86_leave (code);
405         cfa_offset -= sizeof (mgreg_t);
406         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, X86_ESP, cfa_offset);
407         mono_add_unwind_op_same_value (unwind_ops, code, buf, X86_EBP);
408
409         if (MONO_TRAMPOLINE_TYPE_MUST_RETURN (tramp_type)) {
410                 /* Load the value returned by the trampoline */
411                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, 0, 4);
412                 /* The trampoline returns normally, pop the trampoline argument */
413                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
414                 cfa_offset -= sizeof (mgreg_t);
415                 mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
416                 x86_ret (code);
417         } else {
418                 /* The trampoline argument is at the top of the stack, and it contains the address we need to branch to */
419                 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD) {
420                         x86_pop_reg (code, X86_EAX);
421                         cfa_offset -= sizeof (mgreg_t);
422                         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
423                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 0x8);
424                         x86_jump_reg (code, X86_EAX);
425                 } else {
426                         x86_ret (code);
427                 }
428         }
429
430         nacl_global_codeman_validate (&buf, 256, &code);
431         g_assert ((code - buf) <= 256);
432         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
433
434         tramp_name = mono_get_generic_trampoline_name (tramp_type);
435         *info = mono_tramp_info_create (tramp_name, buf, code - buf, ji, unwind_ops);
436         g_free (tramp_name);
437
438         return buf;
439 }
440
441 #define TRAMPOLINE_SIZE 10
442
443 gpointer
444 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
445 {
446         guint8 *code, *buf, *tramp;
447         
448         tramp = mono_get_trampoline_code (tramp_type);
449
450         code = buf = mono_domain_code_reserve_align (domain, TRAMPOLINE_SIZE, NACL_SIZE (4, kNaClAlignment));
451
452         x86_push_imm (buf, arg1);
453         x86_jump_code (buf, tramp);
454         g_assert ((buf - code) <= TRAMPOLINE_SIZE);
455
456         nacl_domain_code_validate (domain, &code, NACL_SIZE (4, kNaClAlignment), &buf);
457
458         mono_arch_flush_icache (code, buf - code);
459         mono_profiler_code_buffer_new (code, buf - code, MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE, mono_get_generic_trampoline_simple_name (tramp_type));
460
461         if (code_len)
462                 *code_len = buf - code;
463
464         return code;
465 }
466
467 gpointer
468 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
469 {
470         guint8 *tramp;
471         guint8 *code, *buf;
472         guint8 **rgctx_null_jumps;
473         int tramp_size;
474         int depth, index;
475         int i;
476         gboolean mrgctx;
477         MonoJumpInfo *ji = NULL;
478         GSList *unwind_ops = NULL;
479
480         unwind_ops = mono_arch_get_cie_program ();
481
482         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
483         index = MONO_RGCTX_SLOT_INDEX (slot);
484         if (mrgctx)
485                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
486         for (depth = 0; ; ++depth) {
487                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
488
489                 if (index < size - 1)
490                         break;
491                 index -= size - 1;
492         }
493
494 #if defined(__default_codegen__)
495         tramp_size = (aot ? 64 : 36) + 6 * depth;
496 #elif defined(__native_client_codegen__)
497         tramp_size = (aot ? 64 : 36) + 2 * kNaClAlignment +
498           6 * (depth + kNaClAlignment);
499 #endif
500
501         code = buf = mono_global_codeman_reserve (tramp_size);
502
503         rgctx_null_jumps = g_malloc (sizeof (guint8*) * (depth + 2));
504
505         /* load vtable/mrgctx ptr */
506         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
507         if (!mrgctx) {
508                 /* load rgctx ptr from vtable */
509                 x86_mov_reg_membase (code, X86_EAX, X86_EAX, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context), 4);
510                 /* is the rgctx ptr null? */
511                 x86_test_reg_reg (code, X86_EAX, X86_EAX);
512                 /* if yes, jump to actual trampoline */
513                 rgctx_null_jumps [0] = code;
514                 x86_branch8 (code, X86_CC_Z, -1, 1);
515         }
516
517         for (i = 0; i < depth; ++i) {
518                 /* load ptr to next array */
519                 if (mrgctx && i == 0)
520                         x86_mov_reg_membase (code, X86_EAX, X86_EAX, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT, 4);
521                 else
522                         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
523                 /* is the ptr null? */
524                 x86_test_reg_reg (code, X86_EAX, X86_EAX);
525                 /* if yes, jump to actual trampoline */
526                 rgctx_null_jumps [i + 1] = code;
527                 x86_branch8 (code, X86_CC_Z, -1, 1);
528         }
529
530         /* fetch slot */
531         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer) * (index + 1), 4);
532         /* is the slot null? */
533         x86_test_reg_reg (code, X86_EAX, X86_EAX);
534         /* if yes, jump to actual trampoline */
535         rgctx_null_jumps [depth + 1] = code;
536         x86_branch8 (code, X86_CC_Z, -1, 1);
537         /* otherwise return */
538         x86_ret (code);
539
540         for (i = mrgctx ? 1 : 0; i <= depth + 1; ++i)
541                 x86_patch (rgctx_null_jumps [i], code);
542
543         g_free (rgctx_null_jumps);
544
545         x86_mov_reg_membase (code, MONO_ARCH_VTABLE_REG, X86_ESP, 4, 4);
546
547         if (aot) {
548                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot));
549                 x86_jump_reg (code, X86_EAX);
550         } else {
551                 tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
552
553                 /* jump to the actual trampoline */
554                 x86_jump_code (code, tramp);
555         }
556
557         nacl_global_codeman_validate (&buf, tramp_size, &code);
558         mono_arch_flush_icache (buf, code - buf);
559         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE, NULL);
560
561         g_assert (code - buf <= tramp_size);
562
563         char *name = mono_get_rgctx_fetch_trampoline_name (slot);
564         *info = mono_tramp_info_create (name, buf, code - buf, ji, unwind_ops);
565         g_free (name);
566
567         return buf;
568 }
569
570 /*
571  * mono_arch_create_general_rgctx_lazy_fetch_trampoline:
572  *
573  *   This is a general variant of the rgctx fetch trampolines. It receives a pointer to gpointer[2] in the rgctx reg. The first entry contains the slot, the second
574  * the trampoline to call if the slot is not filled.
575  */
576 gpointer
577 mono_arch_create_general_rgctx_lazy_fetch_trampoline (MonoTrampInfo **info, gboolean aot)
578 {
579         guint8 *code, *buf;
580         int tramp_size;
581         MonoJumpInfo *ji = NULL;
582         GSList *unwind_ops = NULL;
583
584         g_assert (aot);
585
586         unwind_ops = mono_arch_get_cie_program ();
587
588         tramp_size = 64;
589
590         code = buf = mono_global_codeman_reserve (tramp_size);
591
592         // FIXME: Currently, we always go to the slow path.
593         
594         /* Load trampoline addr */
595         x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_RGCTX_REG, 4, 4);
596         /* Load mrgctx/vtable */
597         x86_mov_reg_membase (code, MONO_ARCH_VTABLE_REG, X86_ESP, 4, 4);
598
599         x86_jump_reg (code, X86_EAX);
600
601         nacl_global_codeman_validate (&buf, tramp_size, &code);
602         mono_arch_flush_icache (buf, code - buf);
603         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE, NULL);
604
605         g_assert (code - buf <= tramp_size);
606
607         *info = mono_tramp_info_create ("rgctx_fetch_trampoline_general", buf, code - buf, ji, unwind_ops);
608
609         return buf;
610 }
611
612 void
613 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
614 {
615         /* FIXME: This is not thread safe */
616         guint8 *code = ji->code_start;
617
618         x86_push_imm (code, func_arg);
619         x86_call_code (code, (guint8*)func);
620 }
621
622 static gpointer
623 handler_block_trampoline_helper (void)
624 {
625         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
626         return jit_tls->handler_block_return_address;
627 }
628
629 gpointer
630 mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
631 {
632         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
633         guint8 *code, *buf;
634         int tramp_size = 64;
635         MonoJumpInfo *ji = NULL;
636         int cfa_offset;
637         GSList *unwind_ops = NULL;
638
639         g_assert (!aot);
640
641         code = buf = mono_global_codeman_reserve (tramp_size);
642
643         unwind_ops = mono_arch_get_cie_program ();
644         cfa_offset = sizeof (mgreg_t);
645         /*
646         This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
647         */
648
649         /*
650          * We are in a method frame after the call emitted by OP_CALL_HANDLER.
651          */
652
653         if (mono_get_jit_tls_offset () != -1) {
654                 code = mono_x86_emit_tls_get (code, X86_EAX, mono_get_jit_tls_offset ());
655                 x86_mov_reg_membase (code, X86_EAX, X86_EAX, MONO_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 4);
656         } else {
657                 /*Slow path uses a c helper*/
658                 x86_call_code (code, handler_block_trampoline_helper);
659         }
660         /* Simulate a call */
661         /*Fix stack alignment*/
662         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x4);
663         cfa_offset += sizeof (mgreg_t);
664         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
665
666         /* This is the address the trampoline will return to */
667         x86_push_reg (code, X86_EAX);
668         cfa_offset += sizeof (mgreg_t);
669         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
670
671         /* Dummy trampoline argument, since we call the generic trampoline directly */
672         x86_push_imm (code, 0);
673         cfa_offset += sizeof (mgreg_t);
674         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
675         x86_jump_code (code, tramp);
676
677         nacl_global_codeman_validate (&buf, tramp_size, &code);
678
679         mono_arch_flush_icache (buf, code - buf);
680         mono_profiler_code_buffer_new (buf, code - buf, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
681         g_assert (code - buf <= tramp_size);
682
683         *info = mono_tramp_info_create ("handler_block_trampoline", buf, code - buf, ji, unwind_ops);
684
685         return buf;
686 }
687
688 guint8*
689 mono_arch_get_call_target (guint8 *code)
690 {
691         if (code [-5] == 0xe8) {
692                 gint32 disp = *(gint32*)(code - 4);
693                 guint8 *target = code + disp;
694
695                 return target;
696         } else {
697                 return NULL;
698         }
699 }
700
701 guint32
702 mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
703 {
704         return *(guint32*)(plt_entry + NACL_SIZE (6, 12));
705 }
706
707 /*
708  * mono_arch_get_gsharedvt_arg_trampoline:
709  *
710  *   Return a trampoline which passes ARG to the gsharedvt in/out trampoline ADDR.
711  */
712 gpointer
713 mono_arch_get_gsharedvt_arg_trampoline (MonoDomain *domain, gpointer arg, gpointer addr)
714 {
715         guint8 *code, *start;
716         int buf_len;
717         GSList *unwind_ops;
718
719
720         buf_len = 10;
721
722         start = code = mono_domain_code_reserve (domain, buf_len);
723
724         unwind_ops = mono_arch_get_cie_program ();
725
726         x86_mov_reg_imm (code, X86_EAX, arg);
727         x86_jump_code (code, addr);
728         g_assert ((code - start) <= buf_len);
729
730         nacl_domain_code_validate (domain, &start, buf_len, &code);
731         mono_arch_flush_icache (start, code - start);
732         mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE, NULL);
733
734         mono_tramp_info_register (mono_tramp_info_create (NULL, start, code - start, NULL, unwind_ops), domain);
735
736         return start;
737 }
738
739 /*
740  * mono_arch_create_sdb_trampoline:
741  *
742  *   Return a trampoline which captures the current context, passes it to
743  * debugger_agent_single_step_from_context ()/debugger_agent_breakpoint_from_context (),
744  * then restores the (potentially changed) context.
745  */
746 guint8*
747 mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gboolean aot)
748 {
749         int tramp_size = 256;
750         int framesize, ctx_offset, cfa_offset;
751         guint8 *code, *buf;
752         GSList *unwind_ops = NULL;
753         MonoJumpInfo *ji = NULL;
754
755         code = buf = mono_global_codeman_reserve (tramp_size);
756
757         framesize = 0;
758
759         /* Argument area */
760         framesize += sizeof (mgreg_t);
761
762         framesize = ALIGN_TO (framesize, 8);
763         ctx_offset = framesize;
764         framesize += sizeof (MonoContext);
765
766         framesize = ALIGN_TO (framesize, MONO_ARCH_FRAME_ALIGNMENT);
767
768         // CFA = sp + 4
769         cfa_offset = 4;
770         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, X86_ESP, 4);
771         // IP saved at CFA - 4
772         mono_add_unwind_op_offset (unwind_ops, code, buf, X86_NREG, -cfa_offset);
773
774         x86_push_reg (code, X86_EBP);
775         cfa_offset += sizeof(mgreg_t);
776         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
777         mono_add_unwind_op_offset (unwind_ops, code, buf, X86_EBP, - cfa_offset);
778
779         x86_mov_reg_reg (code, X86_EBP, X86_ESP, sizeof(mgreg_t));
780         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, X86_EBP);
781         /* The + 8 makes the stack aligned */
782         x86_alu_reg_imm (code, X86_SUB, X86_ESP, framesize + 8);
783
784         /* Initialize a MonoContext structure on the stack */
785         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, eax), X86_EAX, sizeof (mgreg_t));
786         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, ebx), X86_EBX, sizeof (mgreg_t));
787         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, ecx), X86_ECX, sizeof (mgreg_t));
788         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, edx), X86_EDX, sizeof (mgreg_t));
789         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 0, sizeof (mgreg_t));
790         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, ebp), X86_EAX, sizeof (mgreg_t));
791         x86_mov_reg_reg (code, X86_EAX, X86_EBP, sizeof (mgreg_t));
792         x86_alu_reg_imm (code, X86_ADD, X86_EAX, cfa_offset);
793         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, esp), X86_ESP, sizeof (mgreg_t));
794         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, esi), X86_ESI, sizeof (mgreg_t));
795         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, edi), X86_EDI, sizeof (mgreg_t));
796         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 4, sizeof (mgreg_t));
797         x86_mov_membase_reg (code, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, eip), X86_EAX, sizeof (mgreg_t));
798
799         /* Call the single step/breakpoint function in sdb */
800         x86_lea_membase (code, X86_EAX, X86_ESP, ctx_offset);
801         x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, sizeof (mgreg_t));
802
803         if (aot) {
804                 x86_breakpoint (code);
805         } else {
806                 if (single_step)
807                         x86_call_code (code, debugger_agent_single_step_from_context);
808                 else
809                         x86_call_code (code, debugger_agent_breakpoint_from_context);
810         }
811
812         /* Restore registers from ctx */
813         /* Overwrite the saved ebp */
814         x86_mov_reg_membase (code, X86_EAX, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, ebp), sizeof (mgreg_t));
815         x86_mov_membase_reg (code, X86_EBP, 0, X86_EAX, sizeof (mgreg_t));
816         /* Overwrite saved eip */
817         x86_mov_reg_membase (code, X86_EAX, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, eip), sizeof (mgreg_t));
818         x86_mov_membase_reg (code, X86_EBP, 4, X86_EAX, sizeof (mgreg_t));
819         x86_mov_reg_membase (code, X86_EAX, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, eax), sizeof (mgreg_t));
820         x86_mov_reg_membase (code, X86_EBX, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, ebx), sizeof (mgreg_t));
821         x86_mov_reg_membase (code, X86_ECX, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, ecx), sizeof (mgreg_t));
822         x86_mov_reg_membase (code, X86_EDX, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, edx), sizeof (mgreg_t));
823         x86_mov_reg_membase (code, X86_ESI, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, esi), sizeof (mgreg_t));
824         x86_mov_reg_membase (code, X86_EDI, X86_ESP, ctx_offset + G_STRUCT_OFFSET (MonoContext, edi), sizeof (mgreg_t));
825
826         x86_leave (code);
827         cfa_offset -= sizeof (mgreg_t);
828         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, X86_ESP, cfa_offset);
829         x86_ret (code);
830
831         mono_arch_flush_icache (code, code - buf);
832         g_assert (code - buf <= tramp_size);
833
834         const char *tramp_name = single_step ? "sdb_single_step_trampoline" : "sdb_breakpoint_trampoline";
835         *info = mono_tramp_info_create (tramp_name, buf, code - buf, ji, unwind_ops);
836
837         return buf;
838 }
839
840 #if defined(ENABLE_GSHAREDVT)
841
842 #include "../../../mono-extensions/mono/mini/tramp-x86-gsharedvt.c"
843
844 #else
845
846 gpointer
847 mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot)
848 {
849         *info = NULL;
850         return NULL;
851 }
852
853 #endif /* !MONOTOUCH */