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