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