Merge pull request #876 from knocte/master
[mono.git] / mono / mini / mini-trampolines.c
1 /*
2  * (C) 2003 Ximian, Inc.
3  * (C) 2003-2011 Novell, Inc.
4  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
5  */
6 #include <config.h>
7 #include <glib.h>
8
9 #include <mono/metadata/appdomain.h>
10 #include <mono/metadata/metadata-internals.h>
11 #include <mono/metadata/marshal.h>
12 #include <mono/metadata/tabledefs.h>
13 #include <mono/utils/mono-counters.h>
14 #include <mono/utils/mono-error-internals.h>
15 #include <mono/utils/mono-membar.h>
16
17 #include "mini.h"
18
19 /*
20  * Address of the trampoline code.  This is used by the debugger to check
21  * whether a method is a trampoline.
22  */
23 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
24
25 static GHashTable *class_init_hash_addr = NULL;
26 static GHashTable *rgctx_lazy_fetch_trampoline_hash = NULL;
27 static GHashTable *rgctx_lazy_fetch_trampoline_hash_addr = NULL;
28 static guint32 trampoline_calls, jit_trampolines, unbox_trampolines, static_rgctx_trampolines;
29
30 #define mono_trampolines_lock() EnterCriticalSection (&trampolines_mutex)
31 #define mono_trampolines_unlock() LeaveCriticalSection (&trampolines_mutex)
32 static CRITICAL_SECTION trampolines_mutex;
33
34 #ifdef MONO_ARCH_GSHARED_SUPPORTED
35
36 typedef struct {
37         MonoMethod *m;
38         gpointer addr;
39 } RgctxTrampInfo;
40
41 static gint
42 rgctx_tramp_info_equal (gconstpointer ka, gconstpointer kb)
43 {
44         const RgctxTrampInfo *i1 = ka;
45         const RgctxTrampInfo *i2 = kb;
46
47         if (i1->m == i2->m && i1->addr == i2->addr)
48                 return 1;
49         else
50                 return 0;
51 }
52
53 static guint
54 rgctx_tramp_info_hash (gconstpointer data)
55 {
56         const RgctxTrampInfo *info = data;
57
58         return GPOINTER_TO_UINT (info->m) ^ GPOINTER_TO_UINT (info->addr);
59 }
60
61 /*
62  * mono_create_static_rgctx_trampoline:
63  *
64  *   Return a static rgctx trampoline for M which branches to ADDR which should
65  * point to the compiled code of M.
66  *
67  *   Static rgctx trampolines are used when a shared generic method which doesn't
68  * have a this argument is called indirectly, ie. from code which can't pass in
69  * the rgctx argument. The trampoline sets the rgctx argument and jumps to the
70  * methods code. These trampolines are similar to the unbox trampolines, they
71  * perform the same task as the static rgctx wrappers, but they are smaller/faster,
72  * and can be made to work with full AOT.
73  * On PPC addr should be an ftnptr and the return value is an ftnptr too.
74  */
75 gpointer
76 mono_create_static_rgctx_trampoline (MonoMethod *m, gpointer addr)
77 {
78         gpointer ctx;
79         gpointer res;
80         MonoDomain *domain;
81         RgctxTrampInfo tmp_info;
82         RgctxTrampInfo *info;
83
84 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
85         g_assert (((gpointer*)addr) [2] == 0);
86 #endif
87
88         ctx = mini_method_get_rgctx (m);
89
90         domain = mono_domain_get ();
91
92         /* 
93          * In the AOT case, addr might point to either the method, or to an unbox trampoline,
94          * so make the hash keyed on the m+addr pair.
95          */
96         mono_domain_lock (domain);
97         if (!domain_jit_info (domain)->static_rgctx_trampoline_hash)
98                 domain_jit_info (domain)->static_rgctx_trampoline_hash = g_hash_table_new (rgctx_tramp_info_hash, rgctx_tramp_info_equal);
99         tmp_info.m = m;
100         tmp_info.addr = addr;
101         res = g_hash_table_lookup (domain_jit_info (domain)->static_rgctx_trampoline_hash,
102                                                            &tmp_info);
103         mono_domain_unlock (domain);
104         if (res)
105                 return res;
106
107         if (mono_aot_only)
108                 res = mono_aot_get_static_rgctx_trampoline (ctx, addr);
109         else
110                 res = mono_arch_get_static_rgctx_trampoline (m, ctx, addr);
111
112         mono_domain_lock (domain);
113         /* Duplicates inserted while we didn't hold the lock are OK */
114         info = mono_domain_alloc (domain, sizeof (RgctxTrampInfo));
115         info->m = m;
116         info->addr = addr;
117         g_hash_table_insert (domain_jit_info (domain)->static_rgctx_trampoline_hash, info, res);
118         mono_domain_unlock (domain);
119
120         static_rgctx_trampolines ++;
121
122         return res;
123 }
124 #else
125 gpointer
126 mono_create_static_rgctx_trampoline (MonoMethod *m, gpointer addr)
127 {
128        /* 
129         * This shouldn't happen as all arches which support generic sharing support
130         * static rgctx trampolines as well.
131         */
132        g_assert_not_reached ();
133 }
134 #endif
135
136 #ifdef MONO_ARCH_HAVE_IMT
137
138 /*
139  * Either IMPL_METHOD or AOT_ADDR will be set on return.
140  */
141 static gpointer*
142 #ifdef __GNUC__
143 /*
144  * This works against problems when compiling with gcc 4.6 on arm. The 'then' part of
145  * this line gets executed, even when the condition is false:
146  *              if (impl && mono_method_needs_static_rgctx_invoke (impl, FALSE))
147  *                      *need_rgctx_tramp = TRUE;
148  */
149 __attribute__ ((noinline))
150 #endif
151         mono_convert_imt_slot_to_vtable_slot (gpointer* slot, mgreg_t *regs, guint8 *code, MonoMethod *method, gboolean lookup_aot, MonoMethod **impl_method, gboolean *need_rgctx_tramp, gboolean *variance_used, gpointer *aot_addr)
152 {
153         MonoObject *this_argument = mono_arch_get_this_arg_from_call (regs, code);
154         MonoVTable *vt = this_argument->vtable;
155         int displacement = slot - ((gpointer*)vt);
156
157         if (displacement > 0) {
158                 /* slot is in the vtable, not in the IMT */
159 #if DEBUG_IMT
160                 printf ("mono_convert_imt_slot_to_vtable_slot: slot %p is in the vtable, not in the IMT\n", slot);
161 #endif
162                 return slot;
163         } else {
164                 MonoMethod *imt_method = mono_arch_find_imt_method (regs, code);
165                 MonoMethod *impl;
166                 int interface_offset;
167                 int imt_slot = MONO_IMT_SIZE + displacement;
168
169                 /*This has to be variance aware since imt_method can be from an interface that vt->klass doesn't directly implement*/
170                 interface_offset = mono_class_interface_offset_with_variance (vt->klass, imt_method->klass, variance_used);
171
172                 if (interface_offset < 0) {
173                         g_error ("%s doesn't implement interface %s\n", mono_type_get_name_full (&vt->klass->byval_arg, 0), mono_type_get_name_full (&imt_method->klass->byval_arg, 0));
174                 }
175                 mono_vtable_build_imt_slot (vt, mono_method_get_imt_slot (imt_method));
176
177                 if (imt_method->is_inflated && ((MonoMethodInflated*)imt_method)->context.method_inst) {
178                         MonoGenericContext context = { NULL, NULL };
179
180                         /* 
181                          * Generic virtual method, imt_method contains the inflated interface 
182                          * method, need to get the inflated impl method.
183                          */
184                         /* imt_method->slot might not be set */
185                         impl = mono_class_get_vtable_entry (vt->klass, interface_offset + mono_method_get_declaring_generic_method (imt_method)->slot);
186
187                         if (impl->klass->generic_class)
188                                 context.class_inst = impl->klass->generic_class->context.class_inst;
189                         context.method_inst = ((MonoMethodInflated*)imt_method)->context.method_inst;
190                         impl = mono_class_inflate_generic_method (impl, &context);
191                 } else {
192                         /* Avoid loading metadata or creating a generic vtable if possible */
193                         if (lookup_aot && !vt->klass->valuetype)
194                                 *aot_addr = mono_aot_get_method_from_vt_slot (mono_domain_get (), vt, interface_offset + mono_method_get_vtable_slot (imt_method));
195                         else
196                                 *aot_addr = NULL;
197                         if (*aot_addr)
198                                 impl = NULL;
199                         else
200                                 impl = mono_class_get_vtable_entry (vt->klass, interface_offset + mono_method_get_vtable_slot (imt_method));
201                 }
202
203                 if (impl && mono_method_needs_static_rgctx_invoke (impl, FALSE))
204                         *need_rgctx_tramp = TRUE;
205                 if (impl && impl->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
206                         WrapperInfo *info = mono_marshal_get_wrapper_info (impl);
207
208                         if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
209                                 *need_rgctx_tramp = TRUE;
210                         }
211                 }
212
213                 *impl_method = impl;
214 #if DEBUG_IMT
215                 printf ("mono_convert_imt_slot_to_vtable_slot: method = %s.%s.%s, imt_method = %s.%s.%s\n",
216                                 method->klass->name_space, method->klass->name, method->name, 
217                                 imt_method->klass->name_space, imt_method->klass->name, imt_method->name);
218 #endif
219
220                 g_assert (imt_slot < MONO_IMT_SIZE);
221                 if (vt->imt_collisions_bitmap & (1 << imt_slot)) {
222                         int slot = mono_method_get_vtable_index (imt_method);
223                         int vtable_offset;
224                         gpointer *vtable_slot;
225
226                         g_assert (slot != -1);
227                         vtable_offset = interface_offset + slot;
228                         vtable_slot = & (vt->vtable [vtable_offset]);
229 #if DEBUG_IMT
230                         printf ("mono_convert_imt_slot_to_vtable_slot: slot %p[%d] is in the IMT, and colliding becomes %p[%d] (interface_offset = %d, method->slot = %d)\n", slot, imt_slot, vtable_slot, vtable_offset, interface_offset, imt_method->slot);
231 #endif
232                         return vtable_slot;
233                 } else {
234 #if DEBUG_IMT
235                         printf ("mono_convert_imt_slot_to_vtable_slot: slot %p[%d] is in the IMT, but not colliding\n", slot, imt_slot);
236 #endif
237                         return slot;
238                 }
239         }
240 }
241 #endif
242
243 /*
244  * This is a super-ugly hack to fix bug #616463.
245  *
246  * The problem is that we don't always set is_generic for generic
247  * method definitions.  See the comment at the end of
248  * mono_class_inflate_generic_method_full_checked() in class.c.
249  */
250 static gboolean
251 is_generic_method_definition (MonoMethod *m)
252 {
253         MonoGenericContext *context;
254         if (m->is_generic)
255                 return TRUE;
256         if (!m->is_inflated)
257                 return FALSE;
258
259         context = mono_method_get_context (m);
260         if (!context->method_inst)
261                 return FALSE;
262         if (context->method_inst == mono_method_get_generic_container (((MonoMethodInflated*)m)->declaring)->context.method_inst)
263                 return TRUE;
264         return FALSE;
265 }
266
267 gboolean
268 mini_jit_info_is_gsharedvt (MonoJitInfo *ji)
269 {
270         if (ji && ji->has_generic_jit_info && (mono_jit_info_get_generic_sharing_context (ji)->var_is_vt ||
271                                                                                    mono_jit_info_get_generic_sharing_context (ji)->mvar_is_vt))
272                 return TRUE;
273         else
274                 return FALSE;
275 }
276
277 /*
278  * mini_add_method_trampoline:
279  *
280  *   Add static rgctx/gsharedvt_in/unbox trampolines to M/COMPILED_METHOD if needed. Return the trampoline address, or
281  * COMPILED_METHOD if no trampoline is needed.
282  * ORIG_METHOD is the method the caller originally called i.e. an iface method, or NULL.
283  */
284 gpointer
285 mini_add_method_trampoline (MonoMethod *orig_method, MonoMethod *m, gpointer compiled_method, gboolean add_static_rgctx_tramp, gboolean add_unbox_tramp)
286 {
287         gpointer addr = compiled_method;
288         gboolean callee_gsharedvt, callee_array_helper;
289         MonoMethod *jmethod = NULL;
290         MonoJitInfo *ji;
291
292         // FIXME: This loads information from AOT (perf problem)
293         ji = mini_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (compiled_method), NULL);
294         callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
295
296         callee_array_helper = FALSE;
297         if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
298                 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
299
300                 /*
301                  * generic array helpers.
302                  * Have to replace the wrappers with the original generic instances.
303                  */
304                 if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
305                         callee_array_helper = TRUE;
306                         m = info->d.generic_array_helper.method;
307                 }
308         } else if (m->wrapper_type == MONO_WRAPPER_UNKNOWN) {
309                 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
310
311                 /* Same for synchronized inner wrappers */
312                 if (info && info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
313                         m = info->d.synchronized_inner.method;
314                 }
315         }
316
317         if (!orig_method)
318                 orig_method = m;
319
320         if (callee_gsharedvt)
321                 g_assert (m->is_inflated);
322
323         addr = compiled_method;
324
325         if (add_unbox_tramp) {
326                 /* 
327                  * The unbox trampolines call the method directly, so need to add
328                  * an rgctx tramp before them.
329                  */
330                 if (mono_aot_only) {
331                         addr = mono_aot_get_unbox_trampoline (m);
332                 } else {
333                         unbox_trampolines ++;
334                         addr = mono_arch_get_unbox_trampoline (m, addr);
335                 }
336         }
337
338         if (ji)
339                 jmethod = jinfo_get_method (ji);
340         if (callee_gsharedvt && mini_is_gsharedvt_variable_signature (mono_method_signature (jmethod))) {
341                 MonoGenericSharingContext *gsctx;
342                 MonoMethodSignature *sig, *gsig;
343
344                 /* Here m is a generic instance, while ji->method is the gsharedvt method implementing it */
345
346                 /* Call from normal/gshared code to gsharedvt code with variable signature */
347                 gsctx = mono_jit_info_get_generic_sharing_context (ji);
348
349                 sig = mono_method_signature (m);
350                 gsig = mono_method_signature (jmethod);
351
352                 addr = mini_get_gsharedvt_wrapper (TRUE, addr, sig, gsig, gsctx, -1, FALSE);
353
354                 //printf ("IN: %s\n", mono_method_full_name (m, TRUE));
355         }
356
357         if (callee_array_helper) {
358                 add_static_rgctx_tramp = FALSE;
359                 if (ji && ji->from_aot) {
360                         /* In AOT mode, compiled_method points to one of the InternalArray methods in Array. */
361                         if (mono_method_needs_static_rgctx_invoke (jinfo_get_method (ji), TRUE))
362                                 add_static_rgctx_tramp = TRUE;
363                 }
364         }
365
366         if (add_static_rgctx_tramp)
367                 addr = mono_create_static_rgctx_trampoline (m, addr);
368
369         return addr;
370 }
371
372 /**
373  * common_call_trampoline:
374  *
375  *   The code to handle normal, virtual, and interface method calls and jumps, both
376  * from JITted and LLVM compiled code.
377  */
378 static gpointer
379 common_call_trampoline (mgreg_t *regs, guint8 *code, MonoMethod *m, guint8* tramp, MonoVTable *vt, gpointer *vtable_slot, gboolean need_rgctx_tramp)
380 {
381         gpointer addr, compiled_method;
382         gboolean generic_shared = FALSE;
383         gboolean need_unbox_tramp = FALSE;
384         MonoMethod *declaring = NULL;
385         MonoMethod *generic_virtual = NULL, *variant_iface = NULL, *orig_method = NULL;
386         int context_used;
387         gboolean virtual, variance_used = FALSE;
388         gpointer *orig_vtable_slot, *vtable_slot_to_patch = NULL;
389         MonoJitInfo *ji = NULL;
390
391         virtual = (gpointer)vtable_slot > (gpointer)vt;
392
393         orig_vtable_slot = vtable_slot;
394         vtable_slot_to_patch = vtable_slot;
395
396 #ifdef MONO_ARCH_HAVE_IMT
397         /* IMT call */
398         if (vt && (gpointer)vtable_slot < (gpointer)vt) {
399                 MonoMethod *impl_method = NULL;
400                 MonoObject *this_arg;
401
402                 /* we get the interface method because mono_convert_imt_slot_to_vtable_slot ()
403                  * needs the signature to be able to find the this argument
404                  */
405                 m = mono_arch_find_imt_method (regs, code);
406                 vtable_slot = orig_vtable_slot;
407                 g_assert (vtable_slot);
408
409                 orig_method = m;
410
411                 this_arg = mono_arch_get_this_arg_from_call (regs, code);
412
413                 if (mono_object_is_transparent_proxy (this_arg)) {
414                         /* Use the slow path for now */
415                     m = mono_object_get_virtual_method (this_arg, m);
416                         vtable_slot_to_patch = NULL;
417                 } else {
418                         gboolean lookup_aot;
419
420                         if (m->is_inflated && ((MonoMethodInflated*)m)->context.method_inst) {
421                                 /* Generic virtual method */
422                                 generic_virtual = m;
423                                 need_rgctx_tramp = TRUE;
424                         } else if (variance_used && mono_class_has_variant_generic_params (m->klass)) {
425                                 variant_iface = m;
426                         }
427
428                         addr = NULL;
429                         /* We can only use the AOT compiled code if we don't require further processing */
430                         lookup_aot = !generic_virtual & !variant_iface;
431                         vtable_slot = mono_convert_imt_slot_to_vtable_slot (vtable_slot, regs, code, m, lookup_aot, &impl_method, &need_rgctx_tramp, &variance_used, &addr);
432                         /* This is the vcall slot which gets called through the IMT thunk */
433                         vtable_slot_to_patch = vtable_slot;
434                         /* mono_convert_imt_slot_to_vtable_slot () also gives us the method that is supposed
435                          * to be called, so we compile it and go ahead as usual.
436                          */
437                         /*g_print ("imt found method %p (%s) at %p\n", impl_method, impl_method->name, code);*/
438
439                         if (addr) {
440                                 /*
441                                  * We found AOT compiled code for the method, skip the rest.
442                                  */
443                                 if (mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot))
444                                         *vtable_slot = addr;
445
446                                 return mono_create_ftnptr (mono_domain_get (), addr);
447                         }
448
449                         m = impl_method;
450                 }
451         }
452 #endif
453
454         /*
455          * The virtual check is needed because is_generic_method_definition (m) could
456          * return TRUE for methods used in IMT calls too.
457          */
458         if (virtual && is_generic_method_definition (m)) {
459                 MonoGenericContext context = { NULL, NULL };
460                 MonoMethod *declaring;
461
462                 if (m->is_inflated)
463                         declaring = mono_method_get_declaring_generic_method (m);
464                 else
465                         declaring = m;
466
467                 if (m->klass->generic_class)
468                         context.class_inst = m->klass->generic_class->context.class_inst;
469                 else
470                         g_assert (!m->klass->generic_container);
471
472 #ifdef MONO_ARCH_HAVE_IMT
473                 generic_virtual = mono_arch_find_imt_method (regs, code);
474 #endif
475                 if (generic_virtual) {
476                         g_assert (generic_virtual->is_inflated);
477                         context.method_inst = ((MonoMethodInflated*)generic_virtual)->context.method_inst;
478                 }
479
480                 m = mono_class_inflate_generic_method (declaring, &context);
481                 /* FIXME: only do this if the method is sharable */
482                 need_rgctx_tramp = TRUE;
483         } else if ((context_used = mono_method_check_context_used (m))) {
484                 MonoClass *klass = NULL;
485                 MonoMethod *actual_method = NULL;
486                 MonoVTable *vt = NULL;
487                 MonoGenericInst *method_inst = NULL;
488
489                 vtable_slot = NULL;
490                 generic_shared = TRUE;
491
492                 g_assert (code);
493
494                 if (m->is_inflated && mono_method_get_context (m)->method_inst) {
495 #ifdef MONO_ARCH_RGCTX_REG
496                         MonoMethodRuntimeGenericContext *mrgctx = (MonoMethodRuntimeGenericContext*)mono_arch_find_static_call_vtable (regs, code);
497
498                         klass = mrgctx->class_vtable->klass;
499                         method_inst = mrgctx->method_inst;
500 #else
501                         g_assert_not_reached ();
502 #endif
503                 } else if ((m->flags & METHOD_ATTRIBUTE_STATIC) || m->klass->valuetype) {
504 #ifdef MONO_ARCH_RGCTX_REG
505                         MonoVTable *vtable = mono_arch_find_static_call_vtable (regs, code);
506
507                         klass = vtable->klass;
508 #else
509                         g_assert_not_reached ();
510 #endif
511                 } else {
512 #ifdef MONO_ARCH_HAVE_IMT
513                         MonoObject *this_argument = mono_arch_get_this_arg_from_call (regs, code);
514
515                         vt = this_argument->vtable;
516                         vtable_slot = orig_vtable_slot;
517
518                         g_assert (this_argument->vtable->klass->inited);
519                         //mono_class_init (this_argument->vtable->klass);
520
521                         if (!vtable_slot) {
522                                 mono_class_setup_supertypes (this_argument->vtable->klass);
523                                 klass = this_argument->vtable->klass->supertypes [m->klass->idepth - 1];
524                         }
525 #else
526                         NOT_IMPLEMENTED;
527 #endif
528                 }
529
530                 g_assert (vtable_slot || klass);
531
532                 if (vtable_slot) {
533                         int displacement = vtable_slot - ((gpointer*)vt);
534
535                         g_assert_not_reached ();
536
537                         g_assert (displacement > 0);
538
539                         actual_method = vt->klass->vtable [displacement];
540                 }
541
542                 if (method_inst || m->wrapper_type) {
543                         MonoGenericContext context = { NULL, NULL };
544
545                         if (m->is_inflated)
546                                 declaring = mono_method_get_declaring_generic_method (m);
547                         else
548                                 declaring = m;
549
550                         if (klass->generic_class)
551                                 context.class_inst = klass->generic_class->context.class_inst;
552                         else if (klass->generic_container)
553                                 context.class_inst = klass->generic_container->context.class_inst;
554                         context.method_inst = method_inst;
555
556                         actual_method = mono_class_inflate_generic_method (declaring, &context);
557                 } else {
558                         actual_method = mono_class_get_method_generic (klass, m);
559                 }
560
561                 g_assert (klass);
562                 g_assert (actual_method);
563                 g_assert (actual_method->klass == klass);
564
565                 if (actual_method->is_inflated)
566                         declaring = mono_method_get_declaring_generic_method (actual_method);
567                 else
568                         declaring = NULL;
569
570                 m = actual_method;
571         }
572
573         if (m->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
574                 m = mono_marshal_get_synchronized_wrapper (m);
575                 need_rgctx_tramp = FALSE;
576         }
577
578         /* Calls made through delegates on platforms without delegate trampolines */
579         if (!code && mono_method_needs_static_rgctx_invoke (m, FALSE))
580                 need_rgctx_tramp = TRUE;
581
582         addr = compiled_method = mono_compile_method (m);
583         g_assert (addr);
584
585         if (generic_virtual || variant_iface) {
586                 if (vt->klass->valuetype) /*FIXME is this required variant iface?*/
587                         need_unbox_tramp = TRUE;
588         } else if (orig_vtable_slot) {
589                 if (m->klass->valuetype)
590                         need_unbox_tramp = TRUE;
591         }
592
593         addr = mini_add_method_trampoline (orig_method, m, compiled_method, need_rgctx_tramp, need_unbox_tramp);
594
595         if (generic_virtual || variant_iface) {
596                 MonoMethod *target = generic_virtual ? generic_virtual : variant_iface;
597
598                 vtable_slot = orig_vtable_slot;
599                 g_assert (vtable_slot);
600
601                 mono_method_add_generic_virtual_invocation (mono_domain_get (), 
602                                                                                                         vt, vtable_slot,
603                                                                                                         target, addr);
604
605                 return addr;
606         }
607
608         /* the method was jumped to */
609         if (!code) {
610                 MonoDomain *domain = mono_domain_get ();
611
612                 /* Patch the got entries pointing to this method */
613                 /* 
614                  * We do this here instead of in mono_codegen () to cover the case when m
615                  * was loaded from an aot image.
616                  */
617                 if (domain_jit_info (domain)->jump_target_got_slot_hash) {
618                         GSList *list, *tmp;
619
620                         mono_domain_lock (domain);
621                         list = g_hash_table_lookup (domain_jit_info (domain)->jump_target_got_slot_hash, m);
622                         if (list) {
623                                 for (tmp = list; tmp; tmp = tmp->next) {
624                                         gpointer *got_slot = tmp->data;
625                                         *got_slot = addr;
626                                 }
627                                 g_hash_table_remove (domain_jit_info (domain)->jump_target_got_slot_hash, m);
628                                 g_slist_free (list);
629                         }
630                         mono_domain_unlock (domain);
631                 }
632
633                 return addr;
634         }
635
636         vtable_slot = orig_vtable_slot;
637
638         if (vtable_slot) {
639                 if (vtable_slot_to_patch && (mono_aot_is_got_entry (code, (guint8*)vtable_slot_to_patch) || mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot_to_patch))) {
640                         g_assert (*vtable_slot_to_patch);
641                         *vtable_slot_to_patch = mono_get_addr_from_ftnptr (addr);
642                 }
643         }
644         else {
645                 guint8 *plt_entry = mono_aot_get_plt_entry (code);
646                 gboolean no_patch = FALSE;
647                 MonoJitInfo *target_ji;
648
649                 if (plt_entry) {
650                         if (generic_shared) {
651                                 target_ji =
652                                         mini_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (compiled_method), NULL);
653                                 if (!ji)
654                                         ji = mini_jit_info_table_find (mono_domain_get (), (char*)code, NULL);
655
656                                 if (ji && target_ji && generic_shared && ji->has_generic_jit_info && !target_ji->has_generic_jit_info) {
657                                         no_patch = TRUE;
658                                 }
659                         }
660                         if (!no_patch)
661                                 mono_aot_patch_plt_entry (plt_entry, NULL, regs, addr);
662                 } else {
663                         if (generic_shared) {
664                                 if (m->wrapper_type != MONO_WRAPPER_NONE)
665                                         m = mono_marshal_method_from_wrapper (m);
666                                 //g_assert (mono_method_is_generic_sharable (m, FALSE));
667                         }
668
669                         /* Patch calling code */
670                         target_ji =
671                                 mini_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (compiled_method), NULL);
672                         if (!ji)
673                                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)code, NULL);
674
675                         if (ji && target_ji && generic_shared && ji->has_generic_jit_info && !target_ji->has_generic_jit_info) {
676                                 /* 
677                                  * Can't patch the call as the caller is gshared, but the callee is not. Happens when
678                                  * generic sharing fails.
679                                  * FIXME: Performance problem.
680                                  */
681                                 no_patch = TRUE;
682                         }
683
684                         if (!no_patch && mono_method_same_domain (ji, target_ji))
685                                 mono_arch_patch_callsite (ji->code_start, code, addr);
686                 }
687         }
688
689         return addr;
690 }
691
692 /**
693  * mono_magic_trampoline:
694  *
695  *   This trampoline handles normal calls from JITted code.
696  */
697 gpointer
698 mono_magic_trampoline (mgreg_t *regs, guint8 *code, gpointer arg, guint8* tramp)
699 {
700         trampoline_calls ++;
701
702         return common_call_trampoline (regs, code, arg, tramp, NULL, NULL, FALSE);
703 }
704
705 /*
706  * mono_vcall_trampoline:
707  *
708  *   This trampoline handles virtual calls.
709  */
710 static gpointer
711 mono_vcall_trampoline (mgreg_t *regs, guint8 *code, int slot, guint8 *tramp)
712 {
713         MonoObject *this;
714         MonoVTable *vt;
715         gpointer *vtable_slot;
716         MonoMethod *m;
717         gboolean need_rgctx_tramp = FALSE;
718         gpointer addr;
719
720         trampoline_calls ++;
721
722         /*
723          * We need to obtain the following pieces of information:
724          * - the method which needs to be compiled.
725          * - the vtable slot.
726          * We use one vtable trampoline per vtable slot index, so we need only the vtable,
727          * the other two can be computed from the vtable + the slot index.
728          */
729 #ifndef MONO_ARCH_THIS_AS_FIRST_ARG
730         /* All architectures should support this */
731         g_assert_not_reached ();
732 #endif
733
734         /*
735          * Obtain the vtable from the 'this' arg.
736          */
737         this = mono_arch_get_this_arg_from_call (regs, code);
738         g_assert (this);
739
740         vt = this->vtable;
741
742         if (slot >= 0) {
743                 /* Normal virtual call */
744                 vtable_slot = &(vt->vtable [slot]);
745
746                 /* Avoid loading metadata or creating a generic vtable if possible */
747                 addr = mono_aot_get_method_from_vt_slot (mono_domain_get (), vt, slot);
748                 if (addr && !vt->klass->valuetype) {
749                         if (mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot))
750                                 *vtable_slot = addr;
751
752                         return mono_create_ftnptr (mono_domain_get (), addr);
753                 }
754
755                 /*
756                  * Bug #616463 (see
757                  * is_generic_method_definition() above) also
758                  * goes away if we do a
759                  * mono_class_setup_vtable (vt->klass) here,
760                  * because we then inflate the method
761                  * correctly, put it in the cache, and the
762                  * "wrong" inflation invocation still looks up
763                  * the correctly inflated method.
764                  *
765                  * The hack above seems more stable and
766                  * trustworthy.
767                  */
768                 m = mono_class_get_vtable_entry (vt->klass, slot);
769
770                 need_rgctx_tramp = mono_method_needs_static_rgctx_invoke (m, 0);
771         } else {
772                 /* IMT call */
773                 vtable_slot = &(((gpointer*)vt) [slot]);
774
775                 m = NULL;
776                 need_rgctx_tramp = FALSE;
777         }
778
779         return common_call_trampoline (regs, code, m, tramp, vt, vtable_slot, need_rgctx_tramp);
780 }
781
782 #ifndef DISABLE_REMOTING
783 gpointer
784 mono_generic_virtual_remoting_trampoline (mgreg_t *regs, guint8 *code, MonoMethod *m, guint8 *tramp)
785 {
786         MonoGenericContext context = { NULL, NULL };
787         MonoMethod *imt_method, *declaring;
788         gpointer addr;
789
790         trampoline_calls ++;
791
792         g_assert (m->is_generic);
793
794         if (m->is_inflated)
795                 declaring = mono_method_get_declaring_generic_method (m);
796         else
797                 declaring = m;
798
799         if (m->klass->generic_class)
800                 context.class_inst = m->klass->generic_class->context.class_inst;
801         else
802                 g_assert (!m->klass->generic_container);
803
804 #ifdef MONO_ARCH_HAVE_IMT
805         imt_method = mono_arch_find_imt_method (regs, code);
806         if (imt_method->is_inflated)
807                 context.method_inst = ((MonoMethodInflated*)imt_method)->context.method_inst;
808 #endif
809         m = mono_class_inflate_generic_method (declaring, &context);
810         m = mono_marshal_get_remoting_invoke_with_check (m);
811
812         addr = mono_compile_method (m);
813         g_assert (addr);
814
815         return addr;
816 }
817 #endif
818
819 /*
820  * mono_aot_trampoline:
821  *
822  *   This trampoline handles calls made from AOT code. We try to bypass the 
823  * normal JIT compilation logic to avoid loading the metadata for the method.
824  */
825 #ifdef MONO_ARCH_AOT_SUPPORTED
826 gpointer
827 mono_aot_trampoline (mgreg_t *regs, guint8 *code, guint8 *token_info, 
828                                          guint8* tramp)
829 {
830         MonoImage *image;
831         guint32 token;
832         MonoMethod *method = NULL;
833         gpointer addr;
834         guint8 *plt_entry;
835
836         trampoline_calls ++;
837
838         image = *(gpointer*)(gpointer)token_info;
839         token_info += sizeof (gpointer);
840         token = *(guint32*)(gpointer)token_info;
841
842         addr = mono_aot_get_method_from_token (mono_domain_get (), image, token);
843         if (!addr) {
844                 method = mono_get_method (image, token, NULL);
845                 g_assert (method);
846
847                 /* Use the generic code */
848                 return mono_magic_trampoline (regs, code, method, tramp);
849         }
850
851         addr = mono_create_ftnptr (mono_domain_get (), addr);
852
853         /* This is a normal call through a PLT entry */
854         plt_entry = mono_aot_get_plt_entry (code);
855         g_assert (plt_entry);
856
857         mono_aot_patch_plt_entry (plt_entry, NULL, regs, addr);
858
859         return addr;
860 }
861
862 /*
863  * mono_aot_plt_trampoline:
864  *
865  *   This trampoline handles calls made from AOT code through the PLT table.
866  */
867 gpointer
868 mono_aot_plt_trampoline (mgreg_t *regs, guint8 *code, guint8 *aot_module, 
869                                                  guint8* tramp)
870 {
871         guint32 plt_info_offset = mono_aot_get_plt_info_offset (regs, code);
872         gpointer res;
873
874         trampoline_calls ++;
875
876         res = mono_aot_plt_resolve (aot_module, plt_info_offset, code);
877         if (!res) {
878                 if (mono_loader_get_last_error ())
879                         mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
880                 // FIXME: Error handling (how ?)
881                 g_assert (res);
882         }
883
884         return res;
885 }
886 #endif
887
888 /**
889  * mono_class_init_trampoline:
890  *
891  * This method calls mono_runtime_class_init () to run the static constructor
892  * for the type, then patches the caller code so it is not called again.
893  */
894 void
895 mono_class_init_trampoline (mgreg_t *regs, guint8 *code, MonoVTable *vtable, guint8 *tramp)
896 {
897         guint8 *plt_entry = mono_aot_get_plt_entry (code);
898
899         trampoline_calls ++;
900
901         mono_runtime_class_init (vtable);
902
903         if (vtable->initialized) {
904                 if (plt_entry)
905                         mono_arch_nullify_plt_entry (plt_entry, regs);
906                 else
907                         mono_arch_nullify_class_init_trampoline (code, regs);
908         }
909 }
910
911 /**
912  * mono_generic_class_init_trampoline:
913  *
914  * This method calls mono_runtime_class_init () to run the static constructor
915  * for the type.
916  */
917 void
918 mono_generic_class_init_trampoline (mgreg_t *regs, guint8 *code, MonoVTable *vtable, guint8 *tramp)
919 {
920         trampoline_calls ++;
921
922         mono_runtime_class_init (vtable);
923 }
924
925 static gpointer
926 mono_rgctx_lazy_fetch_trampoline (mgreg_t *regs, guint8 *code, gpointer data, guint8 *tramp)
927 {
928 #ifdef MONO_ARCH_VTABLE_REG
929         static gboolean inited = FALSE;
930         static int num_lookups = 0;
931         guint32 slot = GPOINTER_TO_UINT (data);
932         mgreg_t *r = (mgreg_t*)regs;
933         gpointer arg = (gpointer)(gssize)r [MONO_ARCH_VTABLE_REG];
934         guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
935         gboolean mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
936
937         trampoline_calls ++;
938
939         if (!inited) {
940                 mono_counters_register ("RGCTX unmanaged lookups", MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_lookups);
941                 inited = TRUE;
942         }
943
944         num_lookups++;
945
946         if (mrgctx)
947                 return mono_method_fill_runtime_generic_context (arg, code, index);
948         else
949                 return mono_class_fill_runtime_generic_context (arg, code, index);
950 #else
951         g_assert_not_reached ();
952 #endif
953 }
954
955 void
956 mono_monitor_enter_trampoline (mgreg_t *regs, guint8 *code, MonoObject *obj, guint8 *tramp)
957 {
958         mono_monitor_enter (obj);
959 }
960
961 void
962 mono_monitor_exit_trampoline (mgreg_t *regs, guint8 *code, MonoObject *obj, guint8 *tramp)
963 {
964         mono_monitor_exit (obj);
965 }
966
967 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
968
969 /**
970  * mono_delegate_trampoline:
971  *
972  *   This trampoline handles calls made to Delegate:Invoke ().
973  * This is called once the first time a delegate is invoked, so it must be fast.
974  */
975 gpointer
976 mono_delegate_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
977 {
978         MonoDomain *domain = mono_domain_get ();
979         MonoDelegate *delegate;
980         MonoJitInfo *ji;
981         MonoMethod *m;
982         MonoMethod *method = NULL;
983         gboolean multicast, callvirt = FALSE;
984         gboolean need_rgctx_tramp = FALSE;
985         gboolean need_unbox_tramp = FALSE;
986         gboolean enable_caching = TRUE;
987         MonoMethod *invoke = tramp_data [0];
988         guint8 *impl_this = tramp_data [1];
989         guint8 *impl_nothis = tramp_data [2];
990         MonoError err;
991         MonoMethodSignature *sig;
992         gpointer addr, compiled_method;
993
994         trampoline_calls ++;
995
996         /* Obtain the delegate object according to the calling convention */
997         delegate = mono_arch_get_this_arg_from_call (regs, code);
998
999         if (delegate->method) {
1000                 method = delegate->method;
1001
1002                 /*
1003                  * delegate->method_ptr == NULL means the delegate was initialized by 
1004                  * mini_delegate_ctor, while != NULL means it is initialized by 
1005                  * mono_delegate_ctor_with_method (). In both cases, we need to add wrappers
1006                  * (ctor_with_method () does this, but it doesn't store the wrapper back into
1007                  * delegate->method).
1008                  */
1009 #ifndef DISABLE_REMOTING
1010                 if (delegate->target && delegate->target->vtable->klass == mono_defaults.transparent_proxy_class) {
1011 #ifndef DISABLE_COM
1012                         if (((MonoTransparentProxy *)delegate->target)->remote_class->proxy_class != mono_class_get_com_object_class () &&
1013                            !mono_class_is_com_object (((MonoTransparentProxy *)delegate->target)->remote_class->proxy_class))
1014 #endif
1015                                 method = mono_marshal_get_remoting_invoke (method);
1016                 } else
1017 #endif
1018                 {
1019                         mono_error_init (&err);
1020                         sig = mono_method_signature_checked (method, &err);
1021                         if (!sig)
1022                                 mono_error_raise_exception (&err);
1023                                 
1024                         if (sig->hasthis && method->klass->valuetype) {
1025                                 if (mono_aot_only)
1026                                         need_unbox_tramp = TRUE;
1027                                 else
1028                                         method = mono_marshal_get_unbox_wrapper (method);
1029                         }
1030                 }
1031         } else {
1032                 ji = mono_jit_info_table_find (domain, mono_get_addr_from_ftnptr (delegate->method_ptr));
1033                 if (ji)
1034                         method = jinfo_get_method (ji);
1035         }
1036
1037         if (method) {
1038                 mono_error_init (&err);
1039                 sig = mono_method_signature_checked (method, &err);
1040                 if (!sig)
1041                         mono_error_raise_exception (&err);
1042
1043                 callvirt = !delegate->target && sig->hasthis;
1044                 if (delegate->target && 
1045                         method->flags & METHOD_ATTRIBUTE_VIRTUAL && 
1046                         method->flags & METHOD_ATTRIBUTE_ABSTRACT &&
1047                         method->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) {
1048                         method = mono_object_get_virtual_method (delegate->target, method);
1049                         enable_caching = FALSE;
1050                 }
1051         }
1052
1053         if (method && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1054                 method = mono_marshal_get_synchronized_wrapper (method);
1055
1056         if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
1057                 need_rgctx_tramp = TRUE;
1058
1059         /* 
1060          * If the called address is a trampoline, replace it with the compiled method so
1061          * further calls don't have to go through the trampoline.
1062          */
1063         if (method && !callvirt) {
1064                 /* Avoid the overhead of looking up an already compiled method if possible */
1065                 if (enable_caching && delegate->method_code && *delegate->method_code) {
1066                         delegate->method_ptr = *delegate->method_code;
1067                 } else {
1068                         compiled_method = addr = mono_compile_method (method);
1069                         addr = mini_add_method_trampoline (NULL, method, compiled_method, need_rgctx_tramp, need_unbox_tramp);
1070                         delegate->method_ptr = addr;
1071                         if (enable_caching && delegate->method_code)
1072                                 *delegate->method_code = delegate->method_ptr;
1073                 }
1074         } else {
1075                 if (need_rgctx_tramp)
1076                         delegate->method_ptr = mono_create_static_rgctx_trampoline (method, delegate->method_ptr);
1077         }
1078
1079         multicast = ((MonoMulticastDelegate*)delegate)->prev != NULL;
1080         if (!multicast && !callvirt) {
1081                 if (method && (method->flags & METHOD_ATTRIBUTE_STATIC) && mono_method_signature (method)->param_count == mono_method_signature (invoke)->param_count + 1)
1082                         /* Closed static delegate */
1083                         code = impl_this;
1084                 else
1085                         code = delegate->target ? impl_this : impl_nothis;
1086
1087                 if (code) {
1088                         delegate->invoke_impl = mono_get_addr_from_ftnptr (code);
1089                         return code;
1090                 }
1091         }
1092
1093         /* The general, unoptimized case */
1094         m = mono_marshal_get_delegate_invoke (invoke, delegate);
1095         code = mono_compile_method (m);
1096         code = mini_add_method_trampoline (NULL, m, code, mono_method_needs_static_rgctx_invoke (m, FALSE), FALSE);
1097         delegate->invoke_impl = mono_get_addr_from_ftnptr (code);
1098
1099         return code;
1100 }
1101
1102 #endif
1103
1104 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
1105 static gpointer
1106 mono_handler_block_guard_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
1107 {
1108         MonoContext ctx;
1109         MonoException *exc;
1110         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1111         gpointer resume_ip = jit_tls->handler_block_return_address;
1112
1113         memcpy (&ctx, &jit_tls->handler_block_context, sizeof (MonoContext));
1114         MONO_CONTEXT_SET_IP (&ctx, jit_tls->handler_block_return_address);
1115
1116         jit_tls->handler_block_return_address = NULL;
1117         jit_tls->handler_block = NULL;
1118
1119         if (!resume_ip) /*this should not happen, but we should avoid crashing */
1120                 exc = mono_get_exception_execution_engine ("Invalid internal state, resuming abort after handler block but no resume ip found");
1121         else
1122                 exc = mono_thread_resume_interruption ();
1123
1124         if (exc) {
1125                 mono_handle_exception (&ctx, exc);
1126                 mono_restore_context (&ctx);
1127         }
1128
1129         return resume_ip;
1130 }
1131
1132 gpointer
1133 mono_create_handler_block_trampoline (void)
1134 {
1135         static gpointer code;
1136         if (code) {
1137                 mono_memory_barrier ();
1138                 return code;
1139         }
1140
1141
1142         if (mono_aot_only) {
1143                 g_assert (0);
1144                 return code;
1145         }
1146
1147         mono_trampolines_lock ();
1148
1149         if (!code) {
1150                 gpointer tmp = mono_arch_create_handler_block_trampoline ();
1151                 mono_memory_barrier ();
1152                 code = tmp;
1153         }
1154         mono_trampolines_unlock ();
1155
1156         return code;
1157 }
1158 #endif
1159
1160 /*
1161  * mono_get_trampoline_func:
1162  *
1163  *   Return the C function which needs to be called by the generic trampoline of type
1164  * TRAMP_TYPE.
1165  */
1166 gconstpointer
1167 mono_get_trampoline_func (MonoTrampolineType tramp_type)
1168 {
1169         switch (tramp_type) {
1170         case MONO_TRAMPOLINE_JIT:
1171         case MONO_TRAMPOLINE_JUMP:
1172                 return mono_magic_trampoline;
1173         case MONO_TRAMPOLINE_CLASS_INIT:
1174                 return mono_class_init_trampoline;
1175         case MONO_TRAMPOLINE_GENERIC_CLASS_INIT:
1176                 return mono_generic_class_init_trampoline;
1177         case MONO_TRAMPOLINE_RGCTX_LAZY_FETCH:
1178                 return mono_rgctx_lazy_fetch_trampoline;
1179 #ifdef MONO_ARCH_AOT_SUPPORTED
1180         case MONO_TRAMPOLINE_AOT:
1181                 return mono_aot_trampoline;
1182         case MONO_TRAMPOLINE_AOT_PLT:
1183                 return mono_aot_plt_trampoline;
1184 #endif
1185 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
1186         case MONO_TRAMPOLINE_DELEGATE:
1187                 return mono_delegate_trampoline;
1188 #endif
1189         case MONO_TRAMPOLINE_RESTORE_STACK_PROT:
1190                 return mono_altstack_restore_prot;
1191 #ifndef DISABLE_REMOTING
1192         case MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING:
1193                 return mono_generic_virtual_remoting_trampoline;
1194 #endif
1195         case MONO_TRAMPOLINE_MONITOR_ENTER:
1196                 return mono_monitor_enter_trampoline;
1197         case MONO_TRAMPOLINE_MONITOR_EXIT:
1198                 return mono_monitor_exit_trampoline;
1199         case MONO_TRAMPOLINE_VCALL:
1200                 return mono_vcall_trampoline;
1201 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
1202         case MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD:
1203                 return mono_handler_block_guard_trampoline;
1204 #endif
1205         default:
1206                 g_assert_not_reached ();
1207                 return NULL;
1208         }
1209 }
1210
1211 static guchar*
1212 create_trampoline_code (MonoTrampolineType tramp_type)
1213 {
1214         MonoTrampInfo *info;
1215         guchar *code;
1216
1217         code = mono_arch_create_generic_trampoline (tramp_type, &info, FALSE);
1218         mono_tramp_info_register (info);
1219
1220         return code;
1221 }
1222
1223 void
1224 mono_trampolines_init (void)
1225 {
1226         InitializeCriticalSection (&trampolines_mutex);
1227
1228         if (mono_aot_only)
1229                 return;
1230
1231         mono_trampoline_code [MONO_TRAMPOLINE_JIT] = create_trampoline_code (MONO_TRAMPOLINE_JIT);
1232         mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = create_trampoline_code (MONO_TRAMPOLINE_JUMP);
1233         mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
1234         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC_CLASS_INIT] = create_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
1235         mono_trampoline_code [MONO_TRAMPOLINE_RGCTX_LAZY_FETCH] = create_trampoline_code (MONO_TRAMPOLINE_RGCTX_LAZY_FETCH);
1236 #ifdef MONO_ARCH_AOT_SUPPORTED
1237         mono_trampoline_code [MONO_TRAMPOLINE_AOT] = create_trampoline_code (MONO_TRAMPOLINE_AOT);
1238         mono_trampoline_code [MONO_TRAMPOLINE_AOT_PLT] = create_trampoline_code (MONO_TRAMPOLINE_AOT_PLT);
1239 #endif
1240 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
1241         mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
1242 #endif
1243         mono_trampoline_code [MONO_TRAMPOLINE_RESTORE_STACK_PROT] = create_trampoline_code (MONO_TRAMPOLINE_RESTORE_STACK_PROT);
1244 #ifndef DISABLE_REMOTING
1245         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING] = create_trampoline_code (MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING);
1246 #endif
1247         mono_trampoline_code [MONO_TRAMPOLINE_MONITOR_ENTER] = create_trampoline_code (MONO_TRAMPOLINE_MONITOR_ENTER);
1248         mono_trampoline_code [MONO_TRAMPOLINE_MONITOR_EXIT] = create_trampoline_code (MONO_TRAMPOLINE_MONITOR_EXIT);
1249         mono_trampoline_code [MONO_TRAMPOLINE_VCALL] = create_trampoline_code (MONO_TRAMPOLINE_VCALL);
1250 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
1251         mono_trampoline_code [MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD] = create_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1252         mono_create_handler_block_trampoline ();
1253 #endif
1254
1255         mono_counters_register ("Calls to trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &trampoline_calls);
1256         mono_counters_register ("JIT trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &jit_trampolines);
1257         mono_counters_register ("Unbox trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &unbox_trampolines);
1258         mono_counters_register ("Static rgctx trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &static_rgctx_trampolines);
1259 }
1260
1261 void
1262 mono_trampolines_cleanup (void)
1263 {
1264         if (class_init_hash_addr)
1265                 g_hash_table_destroy (class_init_hash_addr);
1266         if (rgctx_lazy_fetch_trampoline_hash)
1267                 g_hash_table_destroy (rgctx_lazy_fetch_trampoline_hash);
1268         if (rgctx_lazy_fetch_trampoline_hash_addr)
1269                 g_hash_table_destroy (rgctx_lazy_fetch_trampoline_hash_addr);
1270
1271         DeleteCriticalSection (&trampolines_mutex);
1272 }
1273
1274 guint8 *
1275 mono_get_trampoline_code (MonoTrampolineType tramp_type)
1276 {
1277         g_assert (mono_trampoline_code [tramp_type]);
1278
1279         return mono_trampoline_code [tramp_type];
1280 }
1281
1282 gpointer
1283 mono_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
1284 {
1285         if (mono_aot_only)
1286                 return mono_aot_create_specific_trampoline (mono_defaults.corlib, arg1, tramp_type, domain, code_len);
1287         else
1288                 return mono_arch_create_specific_trampoline (arg1, tramp_type, domain, code_len);
1289 }
1290
1291 gpointer
1292 mono_create_class_init_trampoline (MonoVTable *vtable)
1293 {
1294         gpointer code, ptr;
1295         MonoDomain *domain = vtable->domain;
1296
1297         g_assert (!vtable->klass->generic_container);
1298
1299         /* previously created trampoline code */
1300         mono_domain_lock (domain);
1301         ptr = 
1302                 g_hash_table_lookup (domain_jit_info (domain)->class_init_trampoline_hash,
1303                                                                   vtable);
1304         mono_domain_unlock (domain);
1305         if (ptr)
1306                 return ptr;
1307
1308         code = mono_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, domain, NULL);
1309
1310         ptr = mono_create_ftnptr (domain, code);
1311
1312         /* store trampoline address */
1313         mono_domain_lock (domain);
1314         g_hash_table_insert (domain_jit_info (domain)->class_init_trampoline_hash,
1315                                                           vtable, ptr);
1316         mono_domain_unlock (domain);
1317
1318         mono_trampolines_lock ();
1319         if (!class_init_hash_addr)
1320                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
1321         g_hash_table_insert (class_init_hash_addr, ptr, vtable);
1322         mono_trampolines_unlock ();
1323
1324         return ptr;
1325 }
1326
1327 gpointer
1328 mono_create_generic_class_init_trampoline (void)
1329 {
1330 #ifdef MONO_ARCH_VTABLE_REG
1331         static gpointer code;
1332         MonoTrampInfo *info;
1333
1334         mono_trampolines_lock ();
1335
1336         if (!code) {
1337                 if (mono_aot_only)
1338                         /* get_named_code () might return an ftnptr, but our caller expects a direct pointer */
1339                         code = mono_get_addr_from_ftnptr (mono_aot_get_trampoline ("generic_class_init_trampoline"));
1340                 else {
1341                         code = mono_arch_create_generic_class_init_trampoline (&info, FALSE);
1342                         mono_tramp_info_register (info);
1343                 }
1344         }
1345
1346         mono_trampolines_unlock ();
1347
1348         return code;
1349 #else
1350         g_assert_not_reached ();
1351 #endif
1352 }
1353
1354 gpointer
1355 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, gboolean add_sync_wrapper)
1356 {
1357         MonoJitInfo *ji;
1358         gpointer code;
1359         guint32 code_size = 0;
1360
1361         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
1362         /*
1363          * We cannot recover the correct type of a shared generic
1364          * method from its native code address, so we use the
1365          * trampoline instead.
1366          * For synchronized methods, the trampoline adds the wrapper.
1367          */
1368         if (code && !ji->has_generic_jit_info && !(method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1369                 return code;
1370
1371         mono_domain_lock (domain);
1372         code = g_hash_table_lookup (domain_jit_info (domain)->jump_trampoline_hash, method);
1373         mono_domain_unlock (domain);
1374         if (code)
1375                 return code;
1376
1377         code = mono_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
1378         g_assert (code_size);
1379
1380         ji = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO);
1381         ji->code_start = code;
1382         ji->code_size = code_size;
1383         ji->d.method = method;
1384
1385         /*
1386          * mono_delegate_ctor needs to find the method metadata from the 
1387          * trampoline address, so we save it here.
1388          */
1389
1390         mono_jit_info_table_add (domain, ji);
1391
1392         mono_domain_lock (domain);
1393         g_hash_table_insert (domain_jit_info (domain)->jump_trampoline_hash, method, ji->code_start);
1394         mono_domain_unlock (domain);
1395
1396         return ji->code_start;
1397 }
1398
1399 gpointer
1400 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
1401 {
1402         gpointer tramp;
1403
1404         if (mono_aot_only) {
1405                 /* Avoid creating trampolines if possible */
1406                 gpointer code = mono_jit_find_compiled_method (domain, method);
1407                 
1408                 if (code)
1409                         return code;
1410         }
1411
1412         mono_domain_lock (domain);
1413         tramp = g_hash_table_lookup (domain_jit_info (domain)->jit_trampoline_hash, method);
1414         mono_domain_unlock (domain);
1415         if (tramp)
1416                 return tramp;
1417
1418         tramp = mono_create_specific_trampoline (method, MONO_TRAMPOLINE_JIT, domain, NULL);
1419         
1420         mono_domain_lock (domain);
1421         g_hash_table_insert (domain_jit_info (domain)->jit_trampoline_hash, method, tramp);
1422         mono_domain_unlock (domain);
1423
1424         jit_trampolines++;
1425
1426         return tramp;
1427 }       
1428
1429 gpointer
1430 mono_create_jit_trampoline (MonoMethod *method)
1431 {
1432         return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
1433 }
1434
1435 gpointer
1436 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
1437 {
1438         gpointer tramp;
1439
1440         MonoDomain *domain = mono_domain_get ();
1441         guint8 *buf, *start;
1442
1443         buf = start = mono_domain_alloc0 (domain, 2 * sizeof (gpointer));
1444
1445         *(gpointer*)(gpointer)buf = image;
1446         buf += sizeof (gpointer);
1447         *(guint32*)(gpointer)buf = token;
1448
1449         tramp = mono_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
1450
1451         jit_trampolines++;
1452
1453         return tramp;
1454 }       
1455
1456 gpointer
1457 mono_create_delegate_trampoline (MonoDomain *domain, MonoClass *klass)
1458 {
1459 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
1460         gpointer ptr;
1461         guint32 code_size = 0;
1462         gpointer *tramp_data;
1463         MonoMethod *invoke;
1464
1465         mono_domain_lock (domain);
1466         ptr = g_hash_table_lookup (domain_jit_info (domain)->delegate_trampoline_hash, klass);
1467         mono_domain_unlock (domain);
1468         if (ptr)
1469                 return ptr;
1470
1471         // Precompute the delegate invoke impl and pass it to the delegate trampoline
1472         invoke = mono_get_delegate_invoke (klass);
1473         g_assert (invoke);
1474
1475         tramp_data = mono_domain_alloc (domain, sizeof (gpointer) * 3);
1476         tramp_data [0] = invoke;
1477         tramp_data [1] = mono_arch_get_delegate_invoke_impl (mono_method_signature (invoke), TRUE);
1478         tramp_data [2] = mono_arch_get_delegate_invoke_impl (mono_method_signature (invoke), FALSE);
1479
1480         ptr = mono_create_specific_trampoline (tramp_data, MONO_TRAMPOLINE_DELEGATE, domain, &code_size);
1481         g_assert (code_size);
1482
1483         /* store trampoline address */
1484         mono_domain_lock (domain);
1485         g_hash_table_insert (domain_jit_info (domain)->delegate_trampoline_hash,
1486                                                           klass, ptr);
1487         mono_domain_unlock (domain);
1488
1489         return ptr;
1490 #else
1491         return NULL;
1492 #endif
1493 }
1494
1495 gpointer
1496 mono_create_rgctx_lazy_fetch_trampoline (guint32 offset)
1497 {
1498         static gboolean inited = FALSE;
1499         static int num_trampolines = 0;
1500         MonoTrampInfo *info;
1501
1502         gpointer tramp, ptr;
1503
1504         mono_trampolines_lock ();
1505         if (rgctx_lazy_fetch_trampoline_hash)
1506                 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
1507         else
1508                 tramp = NULL;
1509         mono_trampolines_unlock ();
1510         if (tramp)
1511                 return tramp;
1512
1513         if (mono_aot_only) {
1514                 ptr = mono_aot_get_lazy_fetch_trampoline (offset);
1515         } else {
1516                 tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, FALSE);
1517                 mono_tramp_info_register (info);
1518                 ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
1519         }
1520
1521         mono_trampolines_lock ();
1522         if (!rgctx_lazy_fetch_trampoline_hash) {
1523                 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
1524                 rgctx_lazy_fetch_trampoline_hash_addr = g_hash_table_new (NULL, NULL);
1525         }
1526         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
1527         g_assert (offset != -1);
1528         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash_addr, ptr, GUINT_TO_POINTER (offset + 1));
1529         mono_trampolines_unlock ();
1530
1531         if (!inited) {
1532                 mono_counters_register ("RGCTX num lazy fetch trampolines",
1533                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_trampolines);
1534                 inited = TRUE;
1535         }
1536         num_trampolines++;
1537
1538         return ptr;
1539 }
1540
1541 gpointer
1542 mono_create_monitor_enter_trampoline (void)
1543 {
1544         static gpointer code;
1545
1546         if (mono_aot_only) {
1547                 if (!code)
1548                         code = mono_aot_get_trampoline ("monitor_enter_trampoline");
1549                 return code;
1550         }
1551
1552 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1553         mono_trampolines_lock ();
1554
1555         if (!code) {
1556                 MonoTrampInfo *info;
1557
1558                 code = mono_arch_create_monitor_enter_trampoline (&info, FALSE);
1559                 mono_tramp_info_register (info);
1560         }
1561
1562         mono_trampolines_unlock ();
1563 #else
1564         code = NULL;
1565         g_assert_not_reached ();
1566 #endif
1567
1568         return code;
1569 }
1570
1571 gpointer
1572 mono_create_monitor_exit_trampoline (void)
1573 {
1574         static gpointer code;
1575
1576         if (mono_aot_only) {
1577                 if (!code)
1578                         code = mono_aot_get_trampoline ("monitor_exit_trampoline");
1579                 return code;
1580         }
1581
1582 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1583         mono_trampolines_lock ();
1584
1585         if (!code) {
1586                 MonoTrampInfo *info;
1587
1588                 code = mono_arch_create_monitor_exit_trampoline (&info, FALSE);
1589                 mono_tramp_info_register (info);
1590         }
1591
1592         mono_trampolines_unlock ();
1593 #else
1594         code = NULL;
1595         g_assert_not_reached ();
1596 #endif
1597         return code;
1598 }
1599  
1600 #ifdef MONO_ARCH_LLVM_SUPPORTED
1601 /*
1602  * mono_create_llvm_imt_trampoline:
1603  *
1604  *   LLVM compiled code can't pass in the IMT argument, so we use this trampoline, which
1605  * sets the IMT argument, then branches to the contents of the vtable slot given by
1606  * vt_offset in the vtable which is obtained from the argument list.
1607  */
1608 gpointer
1609 mono_create_llvm_imt_trampoline (MonoDomain *domain, MonoMethod *m, int vt_offset)
1610 {
1611 #ifdef MONO_ARCH_HAVE_LLVM_IMT_TRAMPOLINE
1612         return mono_arch_get_llvm_imt_trampoline (domain, m, vt_offset);
1613 #else
1614         g_assert_not_reached ();
1615         return NULL;
1616 #endif
1617 }
1618 #endif
1619
1620 MonoVTable*
1621 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
1622 {
1623         MonoVTable *res;
1624
1625         mono_trampolines_lock ();
1626         if (class_init_hash_addr)
1627                 res = g_hash_table_lookup (class_init_hash_addr, addr);
1628         else
1629                 res = NULL;
1630         mono_trampolines_unlock ();
1631         return res;
1632 }
1633
1634 guint32
1635 mono_find_rgctx_lazy_fetch_trampoline_by_addr (gconstpointer addr)
1636 {
1637         int offset;
1638
1639         mono_trampolines_lock ();
1640         if (rgctx_lazy_fetch_trampoline_hash_addr) {
1641                 /* We store the real offset + 1 so we can detect when the lookup fails */
1642                 offset = GPOINTER_TO_INT (g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash_addr, addr));
1643                 if (offset)
1644                         offset -= 1;
1645                 else
1646                         offset = -1;
1647         } else {
1648                 offset = -1;
1649         }
1650         mono_trampolines_unlock ();
1651         return offset;
1652 }
1653
1654 static const char*tramp_names [MONO_TRAMPOLINE_NUM] = {
1655         "jit",
1656         "jump",
1657         "class_init",
1658         "generic_class_init",
1659         "rgctx_lazy_fetch",
1660         "aot",
1661         "aot_plt",
1662         "delegate",
1663         "restore_stack_prot",
1664         "generic_virtual_remoting",
1665         "monitor_enter",
1666         "monitor_exit",
1667         "vcall",
1668         "handler_block_guard"
1669 };
1670
1671 /*
1672  * mono_get_generic_trampoline_name:
1673  *
1674  *   Returns a pointer to malloc-ed memory.
1675  */
1676 char*
1677 mono_get_generic_trampoline_name (MonoTrampolineType tramp_type)
1678 {
1679         return g_strdup_printf ("generic_trampoline_%s", tramp_names [tramp_type]);
1680 }
1681
1682 /*
1683  * mono_get_rgctx_fetch_trampoline_name:
1684  *
1685  *   Returns a pointer to malloc-ed memory.
1686  */
1687 char*
1688 mono_get_rgctx_fetch_trampoline_name (int slot)
1689 {
1690         gboolean mrgctx;
1691         int index;
1692
1693         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
1694         index = MONO_RGCTX_SLOT_INDEX (slot);
1695
1696         return g_strdup_printf ("rgctx_fetch_trampoline_%s_%d", mrgctx ? "mrgctx" : "rgctx", index);
1697 }
1698
1699 gpointer
1700 mini_get_nullified_class_init_trampoline (void)
1701 {
1702         static gpointer nullified_class_init_trampoline;
1703
1704         if (!nullified_class_init_trampoline) {
1705                 gpointer tramp;
1706                 MonoTrampInfo *info;
1707
1708                 if (mono_aot_only) {
1709                         tramp = mono_aot_get_trampoline ("nullified_class_init_trampoline");
1710                 } else {
1711                         tramp = mono_arch_get_nullified_class_init_trampoline (&info);
1712                         mono_tramp_info_register (info);
1713                 }
1714                 mono_memory_barrier ();
1715                 nullified_class_init_trampoline = tramp;
1716         }
1717
1718         return nullified_class_init_trampoline;
1719 }