Merge pull request #2570 from lambdageek/monoerror-reflection-bubble-2
[mono.git] / mono / mini / mini-runtime.c
1 /*
2  * mini-runtime.c: Runtime code for the JIT
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * Copyright 2002-2003 Ximian, Inc.
9  * Copyright 2003-2010 Novell, Inc.
10  * Copyright 2011-2015 Xamarin, Inc (http://www.xamarin.com)
11  */
12
13 #include <config.h>
14 #ifdef HAVE_ALLOCA_H
15 #include <alloca.h>
16 #endif
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #include <math.h>
21 #ifdef HAVE_SYS_TIME_H
22 #include <sys/time.h>
23 #endif
24 #ifdef HAVE_SIGNAL_H
25 #include <signal.h>
26 #endif
27
28 #include <mono/utils/memcheck.h>
29
30 #include <mono/metadata/assembly.h>
31 #include <mono/metadata/loader.h>
32 #include <mono/metadata/tabledefs.h>
33 #include <mono/metadata/class.h>
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/tokentype.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/appdomain.h>
39 #include <mono/metadata/debug-helpers.h>
40 #include "mono/metadata/profiler.h"
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/gc-internals.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/mempool-internals.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/runtime.h>
50 #include <mono/metadata/reflection-internals.h>
51 #include <mono/utils/mono-math.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-counters.h>
54 #include <mono/utils/mono-error-internals.h>
55 #include <mono/utils/mono-logger-internals.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-path.h>
58 #include <mono/utils/mono-tls.h>
59 #include <mono/utils/mono-hwcap.h>
60 #include <mono/utils/dtrace.h>
61 #include <mono/utils/mono-signal-handler.h>
62 #include <mono/utils/mono-threads.h>
63 #include <mono/utils/checked-build.h>
64 #include <mono/io-layer/io-layer.h>
65
66 #include "mini.h"
67 #include "seq-points.h"
68 #include "tasklets.h"
69 #include <string.h>
70 #include <ctype.h>
71 #include "trace.h"
72 #include "version.h"
73
74 #include "jit-icalls.h"
75
76 #include "mini-gc.h"
77 #include "mini-llvm.h"
78 #include "debugger-agent.h"
79
80 #ifdef MONO_ARCH_LLVM_SUPPORTED
81 #ifdef ENABLE_LLVM
82 #include "mini-llvm-cpp.h"
83 #endif
84 #endif
85
86 static guint32 default_opt = 0;
87 static gboolean default_opt_set = FALSE;
88
89 MonoNativeTlsKey mono_jit_tls_id;
90
91 #ifdef MONO_HAVE_FAST_TLS
92 MONO_FAST_TLS_DECLARE(mono_jit_tls);
93 #endif
94
95 gboolean mono_compile_aot = FALSE;
96 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
97 gboolean mono_aot_only = FALSE;
98 /* Same as mono_aot_only, but only LLVM compiled code is used, no trampolines */
99 gboolean mono_llvm_only = FALSE;
100 MonoAotMode mono_aot_mode = MONO_AOT_MODE_NONE;
101
102 const char *mono_build_date;
103 gboolean mono_do_signal_chaining;
104 gboolean mono_do_crash_chaining;
105 int mini_verbose = 0;
106
107 /*
108  * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
109  * it can load AOT code compiled by LLVM.
110  */
111 gboolean mono_use_llvm = FALSE;
112
113 #define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
114 #define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
115 static mono_mutex_t jit_mutex;
116
117 static MonoCodeManager *global_codeman;
118
119 MonoDebugOptions debug_options;
120
121 #ifdef VALGRIND_JIT_REGISTER_MAP
122 int valgrind_register;
123 #endif
124
125 static GSList *tramp_infos;
126
127 static void register_icalls (void);
128
129 gboolean
130 mono_running_on_valgrind (void)
131 {
132 #ifndef HOST_WIN32
133         if (RUNNING_ON_VALGRIND){
134 #ifdef VALGRIND_JIT_REGISTER_MAP
135                 valgrind_register = TRUE;
136 #endif
137                 return TRUE;
138         } else
139 #endif
140                 return FALSE;
141 }
142
143 typedef struct {
144         void *ip;
145         MonoMethod *method;
146 } FindTrampUserData;
147
148 static void
149 find_tramp (gpointer key, gpointer value, gpointer user_data)
150 {
151         FindTrampUserData *ud = (FindTrampUserData*)user_data;
152
153         if (value == ud->ip)
154                 ud->method = (MonoMethod*)key;
155 }
156
157 /* debug function */
158 G_GNUC_UNUSED static char*
159 get_method_from_ip (void *ip)
160 {
161         MonoJitInfo *ji;
162         char *method;
163         char *res;
164         MonoDomain *domain = mono_domain_get ();
165         MonoDebugSourceLocation *location;
166         FindTrampUserData user_data;
167
168         if (!domain)
169                 domain = mono_get_root_domain ();
170
171         ji = mono_jit_info_table_find_internal (domain, (char *)ip, TRUE, TRUE);
172         if (!ji) {
173                 user_data.ip = ip;
174                 user_data.method = NULL;
175                 mono_domain_lock (domain);
176                 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
177                 mono_domain_unlock (domain);
178                 if (user_data.method) {
179                         char *mname = mono_method_full_name (user_data.method, TRUE);
180                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
181                         g_free (mname);
182                         return res;
183                 }
184                 else
185                         return NULL;
186         } else if (ji->is_trampoline) {
187                 res = g_strdup_printf ("<%p - %s trampoline>", ip, ((MonoTrampInfo*)ji->d.tramp_info)->name);
188                 return res;
189         }
190
191         method = mono_method_full_name (jinfo_get_method (ji), TRUE);
192         /* FIXME: unused ? */
193         location = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
194
195         res = g_strdup_printf (" %s + 0x%x (%p %p) [%p - %s]", method, (int)((char*)ip - (char*)ji->code_start), ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
196
197         mono_debug_free_source_location (location);
198         g_free (method);
199
200         return res;
201 }
202
203 /**
204  * mono_pmip:
205  * @ip: an instruction pointer address
206  *
207  * This method is used from a debugger to get the name of the
208  * method at address @ip.   This routine is typically invoked from
209  * a debugger like this:
210  *
211  * (gdb) print mono_pmip ($pc)
212  *
213  * Returns: the name of the method at address @ip.
214  */
215 G_GNUC_UNUSED char *
216 mono_pmip (void *ip)
217 {
218         return get_method_from_ip (ip);
219 }
220
221 /**
222  * mono_print_method_from_ip
223  * @ip: an instruction pointer address
224  *
225  * This method is used from a debugger to get the name of the
226  * method at address @ip.
227  *
228  * This prints the name of the method at address @ip in the standard
229  * output.  Unlike mono_pmip which returns a string, this routine
230  * prints the value on the standard output.
231  */
232 #ifdef __GNUC__
233 /* Prevent the linker from optimizing this away in embedding setups to help debugging */
234  __attribute__((used))
235 #endif
236 void
237 mono_print_method_from_ip (void *ip)
238 {
239         MonoJitInfo *ji;
240         char *method;
241         MonoDebugSourceLocation *source;
242         MonoDomain *domain = mono_domain_get ();
243         MonoDomain *target_domain = mono_domain_get ();
244         FindTrampUserData user_data;
245         MonoGenericSharingContext*gsctx;
246         const char *shared_type;
247
248         ji = mini_jit_info_table_find_ext (domain, (char *)ip, TRUE, &target_domain);
249         if (ji && ji->is_trampoline) {
250                 MonoTrampInfo *tinfo = (MonoTrampInfo *)ji->d.tramp_info;
251
252                 printf ("IP %p is at offset 0x%x of trampoline '%s'.\n", ip, (int)((guint8*)ip - tinfo->code), tinfo->name);
253                 return;
254         }
255
256         if (!ji) {
257                 user_data.ip = ip;
258                 user_data.method = NULL;
259                 mono_domain_lock (domain);
260                 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
261                 mono_domain_unlock (domain);
262
263                 if (user_data.method) {
264                         char *mname = mono_method_full_name (user_data.method, TRUE);
265                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
266                         g_free (mname);
267                         return;
268                 }
269
270                 g_print ("No method at %p\n", ip);
271                 fflush (stdout);
272                 return;
273         }
274         method = mono_method_full_name (jinfo_get_method (ji), TRUE);
275         source = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
276
277         gsctx = mono_jit_info_get_generic_sharing_context (ji);
278         shared_type = "";
279         if (gsctx) {
280                 if (gsctx->is_gsharedvt)
281                         shared_type = "gsharedvt ";
282                 else
283                         shared_type = "gshared ";
284         }
285
286         g_print ("IP %p at offset 0x%x of %smethod %s (%p %p)[domain %p - %s]\n", ip, (int)((char*)ip - (char*)ji->code_start), shared_type, method, ji->code_start, (char*)ji->code_start + ji->code_size, target_domain, target_domain->friendly_name);
287
288         if (source)
289                 g_print ("%s:%d\n", source->source_file, source->row);
290         fflush (stdout);
291
292         mono_debug_free_source_location (source);
293         g_free (method);
294 }
295
296 /*
297  * mono_method_same_domain:
298  *
299  * Determine whenever two compiled methods are in the same domain, thus
300  * the address of the callee can be embedded in the caller.
301  */
302 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
303 {
304         MonoMethod *cmethod;
305
306         if (!caller || caller->is_trampoline || !callee || callee->is_trampoline)
307                 return FALSE;
308
309         /*
310          * If the call was made from domain-neutral to domain-specific
311          * code, we can't patch the call site.
312          */
313         if (caller->domain_neutral && !callee->domain_neutral)
314                 return FALSE;
315
316         cmethod = jinfo_get_method (caller);
317         if ((cmethod->klass == mono_defaults.appdomain_class) &&
318                 (strstr (cmethod->name, "InvokeInDomain"))) {
319                  /* The InvokeInDomain methods change the current appdomain */
320                 return FALSE;
321         }
322
323         return TRUE;
324 }
325
326 /*
327  * mono_global_codeman_reserve:
328  *
329  *  Allocate code memory from the global code manager.
330  */
331 void *mono_global_codeman_reserve (int size)
332 {
333         void *ptr;
334
335         if (mono_aot_only)
336                 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
337
338         if (!global_codeman) {
339                 /* This can happen during startup */
340                 global_codeman = mono_code_manager_new ();
341                 return mono_code_manager_reserve (global_codeman, size);
342         }
343         else {
344                 mono_jit_lock ();
345                 ptr = mono_code_manager_reserve (global_codeman, size);
346                 mono_jit_unlock ();
347                 return ptr;
348         }
349 }
350
351 #if defined(__native_client_codegen__) && defined(__native_client__)
352 void
353 mono_nacl_gc()
354 {
355 #ifdef __native_client_gc__
356         __nacl_suspend_thread_if_needed();
357 #endif
358 }
359
360 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
361  * which we are generating code, return a pointer to the destination in the
362  * dynamic code segment into which the code will be copied when
363  * mono_global_codeman_commit is called.
364  * LOCKING: Acquires the jit lock.
365  */
366 void*
367 nacl_global_codeman_get_dest (void *data)
368 {
369         void *dest;
370         mono_jit_lock ();
371         dest = nacl_code_manager_get_code_dest (global_codeman, data);
372         mono_jit_unlock ();
373         return dest;
374 }
375
376 void
377 mono_global_codeman_commit (void *data, int size, int newsize)
378 {
379         mono_jit_lock ();
380         mono_code_manager_commit (global_codeman, data, size, newsize);
381         mono_jit_unlock ();
382 }
383
384 /*
385  * Convenience function which calls mono_global_codeman_commit to validate and
386  * copy the code. The caller sets *buf_base and *buf_size to the start and size
387  * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
388  * the byte after the last instruction byte. On return, *buf_base will point to
389  * the start of the copied in the code segment, and *code_end will point after
390  * the end of the copied code.
391  */
392 void
393 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
394 {
395         guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
396         mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
397         *code_end = tmp + (*code_end - *buf_base);
398         *buf_base = tmp;
399 }
400 #else
401 /* no-op versions of Native Client functions */
402 void*
403 nacl_global_codeman_get_dest (void *data)
404 {
405         return data;
406 }
407
408 void
409 mono_global_codeman_commit (void *data, int size, int newsize)
410 {
411 }
412
413 void
414 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
415 {
416 }
417
418 #endif /* __native_client__ */
419
420 /**
421  * mono_create_unwind_op:
422  *
423  *   Create an unwind op with the given parameters.
424  */
425 MonoUnwindOp*
426 mono_create_unwind_op (int when, int tag, int reg, int val)
427 {
428         MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
429
430         op->op = tag;
431         op->reg = reg;
432         op->val = val;
433         op->when = when;
434
435         return op;
436 }
437
438 MonoJumpInfoToken *
439 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
440 {
441         MonoJumpInfoToken *res = (MonoJumpInfoToken *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
442         res->image = image;
443         res->token = token;
444         res->has_context = context != NULL;
445         if (context)
446                 memcpy (&res->context, context, sizeof (MonoGenericContext));
447
448         return res;
449 }
450
451 MonoJumpInfoToken *
452 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
453 {
454         return mono_jump_info_token_new2 (mp, image, token, NULL);
455 }
456
457 /*
458  * mono_tramp_info_create:
459  *
460  *   Create a MonoTrampInfo structure from the arguments. This function assumes ownership
461  * of JI, and UNWIND_OPS.
462  */
463 MonoTrampInfo*
464 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
465 {
466         MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
467
468         info->name = g_strdup ((char*)name);
469         info->code = code;
470         info->code_size = code_size;
471         info->ji = ji;
472         info->unwind_ops = unwind_ops;
473
474         return info;
475 }
476
477 void
478 mono_tramp_info_free (MonoTrampInfo *info)
479 {
480         g_free (info->name);
481
482         // FIXME: ji
483         mono_free_unwind_info (info->unwind_ops);
484         g_free (info);
485 }
486
487 static void
488 register_trampoline_jit_info (MonoDomain *domain, MonoTrampInfo *info)
489 {
490         MonoJitInfo *ji;
491
492         ji = (MonoJitInfo *)mono_domain_alloc0 (domain, mono_jit_info_size ((MonoJitInfoFlags)0, 0, 0));
493         mono_jit_info_init (ji, NULL, info->code, info->code_size, (MonoJitInfoFlags)0, 0, 0);
494         ji->d.tramp_info = info;
495         ji->is_trampoline = TRUE;
496
497         ji->unwind_info = mono_cache_unwind_info (info->uw_info, info->uw_info_len);
498
499         mono_jit_info_table_add (domain, ji);
500 }
501
502 /*
503  * mono_tramp_info_register:
504  *
505  * Remember INFO for use by xdebug, mono_print_method_from_ip (), jit maps, etc.
506  * INFO can be NULL.
507  * Frees INFO.
508  */
509 void
510 mono_tramp_info_register (MonoTrampInfo *info, MonoDomain *domain)
511 {
512         MonoTrampInfo *copy;
513
514         if (!info)
515                 return;
516
517         if (!domain)
518                 domain = mono_get_root_domain ();
519
520         copy = g_new0 (MonoTrampInfo, 1);
521         copy->code = info->code;
522         copy->code_size = info->code_size;
523         copy->name = g_strdup (info->name);
524
525         if (info->unwind_ops) {
526                 copy->uw_info = mono_unwind_ops_encode (info->unwind_ops, &copy->uw_info_len);
527         } else {
528                 /* Trampolines from aot have the unwind ops already encoded */
529                 copy->uw_info = info->uw_info;
530                 copy->uw_info_len = info->uw_info_len;
531         }
532
533         mono_jit_lock ();
534         tramp_infos = g_slist_prepend (tramp_infos, copy);
535         mono_jit_unlock ();
536
537         mono_save_trampoline_xdebug_info (info);
538
539         /* Only register trampolines that have unwind infos */
540         if (mono_get_root_domain () && copy->uw_info)
541                 register_trampoline_jit_info (domain, copy);
542
543         if (mono_jit_map_is_enabled ())
544                 mono_emit_jit_tramp (info->code, info->code_size, info->name);
545
546         mono_tramp_info_free (info);
547 }
548
549 static void
550 mono_tramp_info_cleanup (void)
551 {
552         GSList *l;
553
554         for (l = tramp_infos; l; l = l->next) {
555                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
556
557                 mono_tramp_info_free (info);
558         }
559         g_slist_free (tramp_infos);
560 }
561
562 /* Register trampolines created before the root domain was created in the jit info tables */
563 static void
564 register_trampolines (MonoDomain *domain)
565 {
566         GSList *l;
567
568         for (l = tramp_infos; l; l = l->next) {
569                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
570
571                 register_trampoline_jit_info (domain, info);
572         }
573 }
574
575 G_GNUC_UNUSED static void
576 break_count (void)
577 {
578 }
579
580 /*
581  * Runtime debugging tool, use if (debug_count ()) <x> else <y> to do <x> the first COUNT times, then do <y> afterwards.
582  * Set a breakpoint in break_count () to break the last time <x> is done.
583  */
584 G_GNUC_UNUSED gboolean
585 mono_debug_count (void)
586 {
587         static int count = 0;
588         static gboolean inited;
589         static const char *value;
590
591         count ++;
592
593         if (!inited) {
594                 value = g_getenv ("COUNT");
595                 inited = TRUE;
596         }
597
598         if (!value)
599                 return TRUE;
600
601         if (count == atoi (value))
602                 break_count ();
603
604         if (count > atoi (value))
605                 return FALSE;
606
607         return TRUE;
608 }
609
610 gconstpointer
611 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
612 {
613         char *name;
614         MonoMethod *wrapper;
615         gconstpointer trampoline;
616         MonoDomain *domain = mono_get_root_domain ();
617         gboolean check_exc = TRUE;
618
619         if (callinfo->wrapper)
620                 return callinfo->wrapper;
621
622         if (callinfo->trampoline)
623                 return callinfo->trampoline;
624
625         if (!strcmp (callinfo->name, "mono_thread_interruption_checkpoint"))
626                 /* This icall is used to check for exceptions, so don't check in the wrapper */
627                 check_exc = FALSE;
628
629         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
630         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_exc);
631         g_free (name);
632
633         if (do_compile)
634                 trampoline = mono_compile_method (wrapper);
635         else
636                 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
637
638         mono_loader_lock ();
639         if (!callinfo->trampoline) {
640                 mono_register_jit_icall_wrapper (callinfo, trampoline);
641                 callinfo->trampoline = trampoline;
642         }
643         mono_loader_unlock ();
644
645         return callinfo->trampoline;
646 }
647
648 gconstpointer
649 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
650 {
651         return mono_icall_get_wrapper_full (callinfo, FALSE);
652 }
653
654 static MonoJitDynamicMethodInfo*
655 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
656 {
657         MonoJitDynamicMethodInfo *res;
658
659         if (domain_jit_info (domain)->dynamic_code_hash)
660                 res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
661         else
662                 res = NULL;
663         return res;
664 }
665
666 static void
667 register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
668 {
669 #ifndef DISABLE_JIT
670         mini_register_opcode_emulation (opcode, name, sigstr, func, symbol, no_throw);
671 #else
672         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
673
674         g_assert (!sig->hasthis);
675         g_assert (sig->param_count < 3);
676
677         /* Opcode emulation functions are assumed to don't call mono_raise_exception () */
678         mono_register_jit_icall_full (func, name, sig, no_throw, TRUE, symbol);
679 #endif
680 }
681
682 /*
683  * For JIT icalls implemented in C.
684  * NAME should be the same as the name of the C function whose address is FUNC.
685  * If @avoid_wrapper is TRUE, no wrapper is generated. This is for perf critical icalls which
686  * can't throw exceptions.
687  */
688 static void
689 register_icall (gpointer func, const char *name, const char *sigstr, gboolean avoid_wrapper)
690 {
691         MonoMethodSignature *sig;
692
693         if (sigstr)
694                 sig = mono_create_icall_signature (sigstr);
695         else
696                 sig = NULL;
697
698         mono_register_jit_icall_full (func, name, sig, avoid_wrapper, FALSE, avoid_wrapper ? name : NULL);
699 }
700
701 static void
702 register_icall_no_wrapper (gpointer func, const char *name, const char *sigstr)
703 {
704         MonoMethodSignature *sig;
705
706         if (sigstr)
707                 sig = mono_create_icall_signature (sigstr);
708         else
709                 sig = NULL;
710
711         mono_register_jit_icall_full (func, name, sig, TRUE, FALSE, name);
712 }
713
714 static void
715 register_dyn_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
716 {
717         MonoMethodSignature *sig;
718
719         if (sigstr)
720                 sig = mono_create_icall_signature (sigstr);
721         else
722                 sig = NULL;
723
724         mono_register_jit_icall (func, name, sig, save);
725 }
726
727 #ifdef MONO_HAVE_FAST_TLS
728 MONO_FAST_TLS_DECLARE(mono_lmf_addr);
729 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
730 /*
731  * When this is defined, the current lmf is stored in this tls variable instead of in
732  * jit_tls->lmf.
733  */
734 MONO_FAST_TLS_DECLARE(mono_lmf);
735 #endif
736 #endif
737
738 gint32
739 mono_get_jit_tls_offset (void)
740 {
741         int offset;
742
743 #ifdef HOST_WIN32
744         if (mono_jit_tls_id)
745                 offset = mono_jit_tls_id;
746         else
747                 /* FIXME: Happens during startup */
748                 offset = -1;
749 #else
750         MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
751 #endif
752         return offset;
753 }
754
755 gint32
756 mono_get_lmf_tls_offset (void)
757 {
758 #if defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
759         int offset;
760         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
761         return offset;
762 #else
763         return -1;
764 #endif
765 }
766
767 gint32
768 mono_get_lmf_addr_tls_offset (void)
769 {
770         int offset;
771         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
772         return offset;
773 }
774
775 MonoLMF *
776 mono_get_lmf (void)
777 {
778 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
779         return (MonoLMF *)MONO_FAST_TLS_GET (mono_lmf);
780 #else
781         MonoJitTlsData *jit_tls;
782
783         if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
784                 return jit_tls->lmf;
785         /*
786          * We do not assert here because this function can be called from
787          * mini-gc.c on a thread that has not executed any managed code, yet
788          * (the thread object allocation can trigger a collection).
789          */
790         return NULL;
791 #endif
792 }
793
794 MonoLMF **
795 mono_get_lmf_addr (void)
796 {
797 #ifdef MONO_HAVE_FAST_TLS
798         return (MonoLMF **)MONO_FAST_TLS_GET (mono_lmf_addr);
799 #else
800         MonoJitTlsData *jit_tls;
801
802         jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
803         if (G_LIKELY (jit_tls))
804                 return &jit_tls->lmf;
805
806         /*
807          * When resolving the call to mono_jit_thread_attach full-aot will look
808          * in the plt, which causes a call into the generic trampoline, which in turn
809          * tries to resolve the lmf_addr creating a cyclic dependency.  We cannot
810          * call mono_jit_thread_attach from the native-to-managed wrapper, without
811          * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
812          */
813
814         mono_jit_thread_attach (NULL);
815
816         if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
817                 return &jit_tls->lmf;
818
819         g_assert_not_reached ();
820         return NULL;
821 #endif
822 }
823
824 void
825 mono_set_lmf (MonoLMF *lmf)
826 {
827 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
828         MONO_FAST_TLS_SET (mono_lmf, lmf);
829 #endif
830
831         (*mono_get_lmf_addr ()) = lmf;
832 }
833
834 MonoJitTlsData*
835 mono_get_jit_tls (void)
836 {
837         return (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
838 }
839
840 static void
841 mono_set_jit_tls (MonoJitTlsData *jit_tls)
842 {
843         MonoThreadInfo *info;
844
845         mono_native_tls_set_value (mono_jit_tls_id, jit_tls);
846
847 #ifdef MONO_HAVE_FAST_TLS
848         MONO_FAST_TLS_SET (mono_jit_tls, jit_tls);
849 #endif
850
851         /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
852         info = mono_thread_info_current ();
853         if (info)
854                 mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
855 }
856
857 static void
858 mono_set_lmf_addr (gpointer lmf_addr)
859 {
860         MonoThreadInfo *info;
861
862 #ifdef MONO_HAVE_FAST_TLS
863         MONO_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
864 #endif
865
866         /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
867         info = mono_thread_info_current ();
868         if (info)
869                 mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
870 }
871
872 /*
873  * mono_jit_thread_attach:
874  *
875  * Called by native->managed wrappers. Returns the original domain which needs to be
876  * restored, or NULL.
877  */
878 MonoDomain*
879 mono_jit_thread_attach (MonoDomain *domain)
880 {
881         MonoDomain *orig;
882
883         if (!domain)
884                 /*
885                  * Happens when called from AOTed code which is only used in the root
886                  * domain.
887                  */
888                 domain = mono_get_root_domain ();
889
890 #ifdef MONO_HAVE_FAST_TLS
891         if (!MONO_FAST_TLS_GET (mono_lmf_addr)) {
892                 mono_thread_attach (domain);
893                 // #678164
894                 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
895         }
896 #else
897         if (!mono_native_tls_get_value (mono_jit_tls_id)) {
898                 mono_thread_attach (domain);
899                 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
900         }
901 #endif
902         orig = mono_domain_get ();
903         if (orig != domain)
904                 mono_domain_set (domain, TRUE);
905
906         return orig != domain ? orig : NULL;
907 }
908
909 /* Called by native->managed wrappers */
910 void
911 mono_jit_set_domain (MonoDomain *domain)
912 {
913         if (domain)
914                 mono_domain_set (domain, TRUE);
915 }
916
917 /**
918  * mono_thread_abort:
919  * @obj: exception object
920  *
921  * abort the thread, print exception information and stack trace
922  */
923 static void
924 mono_thread_abort (MonoObject *obj)
925 {
926         /* MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id); */
927
928         /* handle_remove should be eventually called for this thread, too
929         g_free (jit_tls);*/
930
931         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
932                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
933                 mono_thread_exit ();
934         } else {
935                 mono_invoke_unhandled_exception_hook (obj);
936         }
937 }
938
939 static void*
940 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
941 {
942         MonoJitTlsData *jit_tls;
943         MonoLMF *lmf;
944
945         jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
946         if (jit_tls)
947                 return jit_tls;
948
949         jit_tls = g_new0 (MonoJitTlsData, 1);
950
951         jit_tls->abort_func = (void (*)(MonoObject *))abort_func;
952         jit_tls->end_of_stack = stack_start;
953
954         mono_set_jit_tls (jit_tls);
955
956         lmf = g_new0 (MonoLMF, 1);
957         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
958
959         jit_tls->first_lmf = lmf;
960
961 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
962         /* jit_tls->lmf is unused */
963         MONO_FAST_TLS_SET (mono_lmf, lmf);
964         mono_set_lmf_addr (MONO_FAST_TLS_ADDR (mono_lmf));
965 #else
966         mono_set_lmf_addr (&jit_tls->lmf);
967
968         jit_tls->lmf = lmf;
969 #endif
970
971 #ifdef MONO_ARCH_HAVE_TLS_INIT
972         mono_arch_tls_init ();
973 #endif
974
975         mono_setup_altstack (jit_tls);
976
977         return jit_tls;
978 }
979
980 static void
981 free_jit_tls_data (MonoJitTlsData *jit_tls)
982 {
983         mono_arch_free_jit_tls_data (jit_tls);
984         mono_free_altstack (jit_tls);
985
986         g_free (jit_tls->first_lmf);
987         g_free (jit_tls);
988 }
989
990 static void
991 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
992 {
993         MonoThreadInfo *thread;
994         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
995         thread = mono_thread_info_current_unchecked ();
996         if (thread)
997                 thread->jit_data = jit_tls;
998
999         mono_arch_cpu_init ();
1000 }
1001
1002 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
1003
1004 static void
1005 mono_thread_abort_dummy (MonoObject *obj)
1006 {
1007   if (mono_thread_attach_aborted_cb)
1008     mono_thread_attach_aborted_cb (obj);
1009   else
1010     mono_thread_abort (obj);
1011 }
1012
1013 static void
1014 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
1015 {
1016         MonoThreadInfo *thread;
1017         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
1018         thread = mono_thread_info_current_unchecked ();
1019         if (thread)
1020                 thread->jit_data = jit_tls;
1021         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
1022                 mono_runtime_setup_stat_profiler ();
1023
1024         mono_arch_cpu_init ();
1025 }
1026
1027 static void
1028 mini_thread_cleanup (MonoNativeThreadId tid)
1029 {
1030         MonoJitTlsData *jit_tls = NULL;
1031         MonoThreadInfo *info;
1032
1033         info = mono_thread_info_current_unchecked ();
1034
1035         /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
1036          * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
1037          * not a trivial thing.
1038          *
1039          * The current offender is mono_thread_manage which cleanup threads from the outside.
1040          */
1041         if (info && mono_thread_info_get_tid (info) == tid) {
1042                 jit_tls = (MonoJitTlsData *)info->jit_data;
1043                 info->jit_data = NULL;
1044
1045                 mono_set_jit_tls (NULL);
1046
1047                 /* If we attach a thread but never call into managed land, we might never get an lmf.*/
1048                 if (mono_get_lmf ()) {
1049                         mono_set_lmf (NULL);
1050                         mono_set_lmf_addr (NULL);
1051                 }
1052         } else {
1053                 info = mono_thread_info_lookup (tid);
1054                 if (info) {
1055                         jit_tls = (MonoJitTlsData *)info->jit_data;
1056                         info->jit_data = NULL;
1057                 }
1058                 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
1059         }
1060
1061         if (jit_tls)
1062                 free_jit_tls_data (jit_tls);
1063 }
1064
1065 int
1066 mini_get_tls_offset (MonoTlsKey key)
1067 {
1068         int offset;
1069         g_assert (MONO_ARCH_HAVE_TLS_GET);
1070
1071         switch (key) {
1072         case TLS_KEY_THREAD:
1073                 offset = mono_thread_get_tls_offset ();
1074                 break;
1075         case TLS_KEY_JIT_TLS:
1076                 offset = mono_get_jit_tls_offset ();
1077                 break;
1078         case TLS_KEY_DOMAIN:
1079                 offset = mono_domain_get_tls_offset ();
1080                 break;
1081         case TLS_KEY_LMF:
1082                 offset = mono_get_lmf_tls_offset ();
1083                 break;
1084         case TLS_KEY_LMF_ADDR:
1085                 offset = mono_get_lmf_addr_tls_offset ();
1086                 break;
1087         default:
1088                 offset = mono_tls_key_get_offset (key);
1089                 g_assert (offset != -1);
1090                 break;
1091         }
1092
1093         return offset;
1094 }
1095
1096 static gboolean
1097 mini_tls_key_supported (MonoTlsKey key)
1098 {
1099         if (!MONO_ARCH_HAVE_TLS_GET)
1100                 return FALSE;
1101
1102         return mini_get_tls_offset (key) != -1;
1103 }
1104
1105 MonoJumpInfo *
1106 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
1107 {
1108         MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
1109
1110         ji->ip.i = ip;
1111         ji->type = type;
1112         ji->data.target = target;
1113         ji->next = list;
1114
1115         return ji;
1116 }
1117
1118 /**
1119  * mono_patch_info_dup_mp:
1120  *
1121  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
1122  */
1123 MonoJumpInfo*
1124 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
1125 {
1126         MonoJumpInfo *res = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
1127         memcpy (res, patch_info, sizeof (MonoJumpInfo));
1128
1129         switch (patch_info->type) {
1130         case MONO_PATCH_INFO_RVA:
1131         case MONO_PATCH_INFO_LDSTR:
1132         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1133         case MONO_PATCH_INFO_LDTOKEN:
1134         case MONO_PATCH_INFO_DECLSEC:
1135                 res->data.token = (MonoJumpInfoToken *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
1136                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
1137                 break;
1138         case MONO_PATCH_INFO_SWITCH:
1139                 res->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
1140                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
1141                 res->data.table->table = (MonoBasicBlock **)mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1142                 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1143                 break;
1144         case MONO_PATCH_INFO_RGCTX_FETCH:
1145         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
1146                 res->data.rgctx_entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
1147                 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
1148                 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
1149                 break;
1150         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1151                 res->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
1152                 memcpy (res->data.del_tramp, patch_info->data.del_tramp, sizeof (MonoDelegateClassMethodPair));
1153                 break;
1154         case MONO_PATCH_INFO_GSHAREDVT_CALL:
1155                 res->data.gsharedvt = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoGSharedVtCall));
1156                 memcpy (res->data.gsharedvt, patch_info->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
1157                 break;
1158         case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
1159                 MonoGSharedVtMethodInfo *info;
1160                 MonoGSharedVtMethodInfo *oinfo;
1161                 int i;
1162
1163                 oinfo = patch_info->data.gsharedvt_method;
1164                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
1165                 res->data.gsharedvt_method = info;
1166                 memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
1167                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
1168                 for (i = 0; i < oinfo->num_entries; ++i) {
1169                         MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
1170                         MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
1171
1172                         memcpy (template_, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
1173                 }
1174                 //info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
1175                 //memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
1176                 break;
1177         }
1178         case MONO_PATCH_INFO_VIRT_METHOD: {
1179                 MonoJumpInfoVirtMethod *info;
1180                 MonoJumpInfoVirtMethod *oinfo;
1181
1182                 oinfo = patch_info->data.virt_method;
1183                 info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
1184                 res->data.virt_method = info;
1185                 memcpy (info, oinfo, sizeof (MonoJumpInfoVirtMethod));
1186                 break;
1187         }
1188         default:
1189                 break;
1190         }
1191
1192         return res;
1193 }
1194
1195 guint
1196 mono_patch_info_hash (gconstpointer data)
1197 {
1198         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
1199
1200         switch (ji->type) {
1201         case MONO_PATCH_INFO_RVA:
1202         case MONO_PATCH_INFO_LDSTR:
1203         case MONO_PATCH_INFO_LDTOKEN:
1204         case MONO_PATCH_INFO_DECLSEC:
1205                 return (ji->type << 8) | ji->data.token->token;
1206         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1207                 return (ji->type << 8) | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
1208         case MONO_PATCH_INFO_INTERNAL_METHOD:
1209                 return (ji->type << 8) | g_str_hash (ji->data.name);
1210         case MONO_PATCH_INFO_VTABLE:
1211         case MONO_PATCH_INFO_CLASS:
1212         case MONO_PATCH_INFO_IID:
1213         case MONO_PATCH_INFO_ADJUSTED_IID:
1214         case MONO_PATCH_INFO_METHODCONST:
1215         case MONO_PATCH_INFO_METHOD:
1216         case MONO_PATCH_INFO_METHOD_JUMP:
1217         case MONO_PATCH_INFO_IMAGE:
1218         case MONO_PATCH_INFO_ICALL_ADDR:
1219         case MONO_PATCH_INFO_FIELD:
1220         case MONO_PATCH_INFO_SFLDA:
1221         case MONO_PATCH_INFO_SEQ_POINT_INFO:
1222         case MONO_PATCH_INFO_METHOD_RGCTX:
1223         case MONO_PATCH_INFO_SIGNATURE:
1224         case MONO_PATCH_INFO_TLS_OFFSET:
1225         case MONO_PATCH_INFO_METHOD_CODE_SLOT:
1226         case MONO_PATCH_INFO_AOT_JIT_INFO:
1227                 return (ji->type << 8) | (gssize)ji->data.target;
1228         case MONO_PATCH_INFO_GSHAREDVT_CALL:
1229                 return (ji->type << 8) | (gssize)ji->data.gsharedvt->method;
1230         case MONO_PATCH_INFO_RGCTX_FETCH:
1231         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
1232                 MonoJumpInfoRgctxEntry *e = ji->data.rgctx_entry;
1233
1234                 return (ji->type << 8) | (gssize)e->method | (e->in_mrgctx) | e->info_type | mono_patch_info_hash (e->data);
1235         }
1236         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1237         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
1238         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
1239         case MONO_PATCH_INFO_GC_NURSERY_START:
1240         case MONO_PATCH_INFO_GC_NURSERY_BITS:
1241         case MONO_PATCH_INFO_JIT_TLS_ID:
1242         case MONO_PATCH_INFO_GOT_OFFSET:
1243         case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
1244         case MONO_PATCH_INFO_AOT_MODULE:
1245                 return (ji->type << 8);
1246         case MONO_PATCH_INFO_CASTCLASS_CACHE:
1247                 return (ji->type << 8) | (ji->data.index);
1248         case MONO_PATCH_INFO_SWITCH:
1249                 return (ji->type << 8) | ji->data.table->table_size;
1250         case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1251                 return (ji->type << 8) | (gssize)ji->data.gsharedvt_method->method;
1252         case MONO_PATCH_INFO_OBJC_SELECTOR_REF:
1253                 /* Hash on the selector name */
1254                 return g_str_hash (ji->data.target);
1255         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1256                 return (ji->type << 8) | (gsize)ji->data.del_tramp->klass | (gsize)ji->data.del_tramp->method | (gsize)ji->data.del_tramp->is_virtual;
1257         case MONO_PATCH_INFO_LDSTR_LIT:
1258                 return g_str_hash (ji->data.target);
1259         case MONO_PATCH_INFO_VIRT_METHOD: {
1260                 MonoJumpInfoVirtMethod *info = ji->data.virt_method;
1261
1262                 return (ji->type << 8) | (gssize)info->klass | (gssize)info->method;
1263         }
1264         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1265                 return (ji->type << 8) | g_str_hash (ji->data.target);
1266         case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
1267                 return (ji->type << 8) | mono_signature_hash (ji->data.sig);
1268         default:
1269                 printf ("info type: %d\n", ji->type);
1270                 mono_print_ji (ji); printf ("\n");
1271                 g_assert_not_reached ();
1272                 return 0;
1273         }
1274 }
1275
1276 /*
1277  * mono_patch_info_equal:
1278  *
1279  * This might fail to recognize equivalent patches, i.e. floats, so its only
1280  * usable in those cases where this is not a problem, i.e. sharing GOT slots
1281  * in AOT.
1282  */
1283 gint
1284 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
1285 {
1286         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
1287         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
1288
1289         if (ji1->type != ji2->type)
1290                 return 0;
1291
1292         switch (ji1->type) {
1293         case MONO_PATCH_INFO_RVA:
1294         case MONO_PATCH_INFO_LDSTR:
1295         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1296         case MONO_PATCH_INFO_LDTOKEN:
1297         case MONO_PATCH_INFO_DECLSEC:
1298                 if ((ji1->data.token->image != ji2->data.token->image) ||
1299                         (ji1->data.token->token != ji2->data.token->token) ||
1300                         (ji1->data.token->has_context != ji2->data.token->has_context) ||
1301                         (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
1302                         (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
1303                         return 0;
1304                 break;
1305         case MONO_PATCH_INFO_INTERNAL_METHOD:
1306                 return g_str_equal (ji1->data.name, ji2->data.name);
1307         case MONO_PATCH_INFO_RGCTX_FETCH:
1308         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
1309                 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
1310                 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
1311
1312                 return e1->method == e2->method && e1->in_mrgctx == e2->in_mrgctx && e1->info_type == e2->info_type && mono_patch_info_equal (e1->data, e2->data);
1313         }
1314         case MONO_PATCH_INFO_GSHAREDVT_CALL: {
1315                 MonoJumpInfoGSharedVtCall *c1 = ji1->data.gsharedvt;
1316                 MonoJumpInfoGSharedVtCall *c2 = ji2->data.gsharedvt;
1317
1318                 return c1->sig == c2->sig && c1->method == c2->method;
1319         }
1320         case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1321                 return ji1->data.gsharedvt_method->method == ji2->data.gsharedvt_method->method;
1322         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1323                 return ji1->data.del_tramp->klass == ji2->data.del_tramp->klass && ji1->data.del_tramp->method == ji2->data.del_tramp->method && ji1->data.del_tramp->is_virtual == ji2->data.del_tramp->is_virtual;
1324         case MONO_PATCH_INFO_CASTCLASS_CACHE:
1325                 return ji1->data.index == ji2->data.index;
1326         case MONO_PATCH_INFO_VIRT_METHOD:
1327                 return ji1->data.virt_method->klass == ji2->data.virt_method->klass && ji1->data.virt_method->method == ji2->data.virt_method->method;
1328         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1329                 if (ji1->data.target == ji2->data.target)
1330                         return 1;
1331                 return strcmp (ji1->data.target, ji2->data.target) == 0 ? 1 : 0;
1332         case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
1333                 return mono_metadata_signature_equal (ji1->data.sig, ji2->data.sig) ? 1 : 0;
1334         default:
1335                 if (ji1->data.target != ji2->data.target)
1336                         return 0;
1337                 break;
1338         }
1339
1340         return 1;
1341 }
1342
1343 gpointer
1344 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
1345 {
1346         unsigned char *ip = patch_info->ip.i + code;
1347         gconstpointer target = NULL;
1348
1349         switch (patch_info->type) {
1350         case MONO_PATCH_INFO_BB:
1351                 /*
1352                  * FIXME: This could be hit for methods without a prolog. Should use -1
1353                  * but too much code depends on a 0 initial value.
1354                  */
1355                 //g_assert (patch_info->data.bb->native_offset);
1356                 target = patch_info->data.bb->native_offset + code;
1357                 break;
1358         case MONO_PATCH_INFO_ABS:
1359                 target = patch_info->data.target;
1360                 break;
1361         case MONO_PATCH_INFO_LABEL:
1362                 target = patch_info->data.inst->inst_c0 + code;
1363                 break;
1364         case MONO_PATCH_INFO_IP:
1365 #if defined(__native_client__) && defined(__native_client_codegen__)
1366                 /* Need to transform to the destination address, it's */
1367                 /* emitted as an immediate in the code. */
1368                 target = nacl_inverse_modify_patch_target(ip);
1369 #else
1370                 target = ip;
1371 #endif
1372                 break;
1373         case MONO_PATCH_INFO_METHOD_REL:
1374                 target = code + patch_info->data.offset;
1375                 break;
1376         case MONO_PATCH_INFO_INTERNAL_METHOD: {
1377                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1378                 if (!mi) {
1379                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
1380                         g_assert_not_reached ();
1381                 }
1382                 target = mono_icall_get_wrapper (mi);
1383                 break;
1384         }
1385         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1386                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1387                 if (!mi) {
1388                         g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
1389                         g_assert_not_reached ();
1390                 }
1391                 target = mi->func;
1392                 break;
1393         }
1394         case MONO_PATCH_INFO_METHOD_JUMP:
1395                 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE);
1396 #if defined(__native_client__) && defined(__native_client_codegen__)
1397 # if defined(TARGET_AMD64)
1398                 /* This target is an absolute address, not relative to the */
1399                 /* current code being emitted on AMD64. */
1400                 target = nacl_inverse_modify_patch_target(target);
1401 # endif
1402 #endif
1403                 break;
1404         case MONO_PATCH_INFO_METHOD:
1405 #if defined(__native_client_codegen__) && defined(USE_JUMP_TABLES)
1406                 /*
1407                  * If we use jumptables, for recursive calls we cannot
1408                  * avoid trampoline, as we not yet know where we will
1409                  * be installed.
1410                  */
1411                 target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
1412 #else
1413                 if (patch_info->data.method == method) {
1414                         target = code;
1415                 } else {
1416                         /* get the trampoline to the method from the domain */
1417                         target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
1418                 }
1419 #endif
1420                 break;
1421         case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
1422                 gpointer code_slot;
1423
1424                 mono_domain_lock (domain);
1425                 if (!domain_jit_info (domain)->method_code_hash)
1426                         domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
1427                 code_slot = g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, patch_info->data.method);
1428                 if (!code_slot) {
1429                         code_slot = mono_domain_alloc0 (domain, sizeof (gpointer));
1430                         g_hash_table_insert (domain_jit_info (domain)->method_code_hash, patch_info->data.method, code_slot);
1431                 }
1432                 mono_domain_unlock (domain);
1433                 target = code_slot;
1434                 break;
1435         }
1436         case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
1437 #if defined(__native_client_codegen__)
1438                 target = (gpointer)&__nacl_thread_suspension_needed;
1439 #else
1440                 g_assert (mono_threads_is_coop_enabled ());
1441                 target = (gpointer)&mono_polling_required;
1442 #endif
1443                 break;
1444         case MONO_PATCH_INFO_SWITCH: {
1445                 gpointer *jump_table;
1446                 int i;
1447 #if defined(__native_client__) && defined(__native_client_codegen__)
1448                 /* This memory will leak, but we don't care if we're */
1449                 /* not deleting JIT'd methods anyway                 */
1450                 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
1451 #else
1452                 if (method && method->dynamic) {
1453                         jump_table = (void **)mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
1454                 } else {
1455                         if (mono_aot_only) {
1456                                 jump_table = (void **)mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1457                         } else {
1458                                 jump_table = (void **)mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1459                         }
1460                 }
1461 #endif
1462
1463                 for (i = 0; i < patch_info->data.table->table_size; i++) {
1464 #if defined(__native_client__) && defined(__native_client_codegen__)
1465                         /* 'code' is relative to the current code blob, we */
1466                         /* need to do this transform on it to make the     */
1467                         /* pointers in this table absolute                 */
1468                         jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1469 #else
1470                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1471 #endif
1472                 }
1473
1474 #if defined(__native_client__) && defined(__native_client_codegen__)
1475                 /* jump_table is in the data section, we need to transform */
1476                 /* it here so when it gets modified in amd64_patch it will */
1477                 /* then point back to the absolute data address            */
1478                 target = nacl_inverse_modify_patch_target (jump_table);
1479 #else
1480                 target = jump_table;
1481 #endif
1482                 break;
1483         }
1484         case MONO_PATCH_INFO_METHODCONST:
1485         case MONO_PATCH_INFO_CLASS:
1486         case MONO_PATCH_INFO_IMAGE:
1487         case MONO_PATCH_INFO_FIELD:
1488         case MONO_PATCH_INFO_SIGNATURE:
1489         case MONO_PATCH_INFO_AOT_MODULE:
1490                 target = patch_info->data.target;
1491                 break;
1492         case MONO_PATCH_INFO_IID:
1493                 mono_class_init (patch_info->data.klass);
1494                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
1495                 break;
1496         case MONO_PATCH_INFO_ADJUSTED_IID:
1497                 mono_class_init (patch_info->data.klass);
1498                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
1499                 break;
1500         case MONO_PATCH_INFO_VTABLE:
1501                 target = mono_class_vtable (domain, patch_info->data.klass);
1502                 g_assert (target);
1503                 break;
1504         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
1505                 MonoDelegateClassMethodPair *del_tramp = patch_info->data.del_tramp;
1506
1507                 if (del_tramp->is_virtual)
1508                         target = mono_create_delegate_virtual_trampoline (domain, del_tramp->klass, del_tramp->method);
1509                 else
1510                         target = mono_create_delegate_trampoline_info (domain, del_tramp->klass, del_tramp->method);
1511                 break;
1512         }
1513         case MONO_PATCH_INFO_SFLDA: {
1514                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
1515
1516                 if (mono_class_field_is_special_static (patch_info->data.field)) {
1517                         gpointer addr = NULL;
1518
1519                         mono_domain_lock (domain);
1520                         if (domain->special_static_fields)
1521                                 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
1522                         mono_domain_unlock (domain);
1523                         g_assert (addr);
1524                         return addr;
1525                 }
1526
1527                 g_assert (vtable);
1528                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
1529                         /* Done by the generated code */
1530                         ;
1531                 else {
1532                         if (run_cctors)
1533                                 mono_runtime_class_init (vtable);
1534                 }
1535                 target = (char*)mono_vtable_get_static_field_data (vtable) + patch_info->data.field->offset;
1536                 break;
1537         }
1538         case MONO_PATCH_INFO_RVA: {
1539                 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
1540                 guint32 rva;
1541
1542                 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
1543                 target = mono_image_rva_map (patch_info->data.token->image, rva);
1544                 break;
1545         }
1546         case MONO_PATCH_INFO_R4:
1547         case MONO_PATCH_INFO_R8:
1548                 target = patch_info->data.target;
1549                 break;
1550         case MONO_PATCH_INFO_EXC_NAME:
1551                 target = patch_info->data.name;
1552                 break;
1553         case MONO_PATCH_INFO_LDSTR:
1554                 target =
1555                         mono_ldstr (domain, patch_info->data.token->image,
1556                                                 mono_metadata_token_index (patch_info->data.token->token));
1557                 break;
1558         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
1559                 gpointer handle;
1560                 MonoClass *handle_class;
1561                 MonoError error;
1562
1563                 handle = mono_ldtoken_checked (patch_info->data.token->image,
1564                                                            patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, &error);
1565                 if (!mono_error_ok (&error))
1566                         g_error ("Could not patch ldtoken due to %s", mono_error_get_message (&error));
1567                 mono_class_init (handle_class);
1568                 mono_class_init (mono_class_from_mono_type ((MonoType *)handle));
1569
1570                 target = mono_type_get_object_checked (domain, (MonoType *)handle, &error);
1571                 mono_error_raise_exception (&error);
1572
1573                 break;
1574         }
1575         case MONO_PATCH_INFO_LDTOKEN: {
1576                 gpointer handle;
1577                 MonoClass *handle_class;
1578                 MonoError error;
1579
1580                 handle = mono_ldtoken_checked (patch_info->data.token->image,
1581                                                            patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, &error);
1582                 if (!mono_error_ok (&error))
1583                         g_error ("Could not patch ldtoken due to %s", mono_error_get_message (&error));
1584                 mono_class_init (handle_class);
1585
1586                 target = handle;
1587                 break;
1588         }
1589         case MONO_PATCH_INFO_DECLSEC:
1590                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
1591                 break;
1592         case MONO_PATCH_INFO_ICALL_ADDR:
1593                 /* run_cctors == 0 -> AOT */
1594                 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1595                         const char *exc_class;
1596                         const char *exc_arg;
1597
1598                         if (run_cctors) {
1599                                 target = mono_lookup_pinvoke_call (patch_info->data.method, &exc_class, &exc_arg);
1600                                 if (!target) {
1601                                         if (mono_aot_only)
1602                                                 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
1603                                         g_error ("Unable to resolve pinvoke method '%s' Re-run with MONO_LOG_LEVEL=debug for more information.\n", mono_method_full_name (patch_info->data.method, TRUE));
1604                                 }
1605                         } else {
1606                                 target = NULL;
1607                         }
1608                 } else {
1609                         target = mono_lookup_internal_call (patch_info->data.method);
1610
1611                         if (!target && run_cctors)
1612                                 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
1613                 }
1614                 break;
1615         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1616                 target = mono_thread_interruption_request_flag ();
1617                 break;
1618         case MONO_PATCH_INFO_METHOD_RGCTX: {
1619                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
1620                 g_assert (vtable);
1621
1622                 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
1623                 break;
1624         }
1625         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
1626                 int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
1627
1628                 target = GINT_TO_POINTER (MONO_RGCTX_SLOT_INDEX (slot));
1629                 break;
1630         }
1631         case MONO_PATCH_INFO_BB_OVF:
1632         case MONO_PATCH_INFO_EXC_OVF:
1633         case MONO_PATCH_INFO_GOT_OFFSET:
1634         case MONO_PATCH_INFO_NONE:
1635                 break;
1636         case MONO_PATCH_INFO_RGCTX_FETCH: {
1637                 int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
1638
1639                 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
1640                 break;
1641         }
1642 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
1643         case MONO_PATCH_INFO_SEQ_POINT_INFO:
1644                 if (!run_cctors)
1645                         /* AOT, not needed */
1646                         target = NULL;
1647                 else
1648                         target = mono_arch_get_seq_point_info (domain, code);
1649                 break;
1650 #endif
1651         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
1652                 int card_table_shift_bits;
1653                 gpointer card_table_mask;
1654
1655                 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
1656                 break;
1657         }
1658         case MONO_PATCH_INFO_GC_NURSERY_START: {
1659                 int shift_bits;
1660                 size_t size;
1661
1662                 target = mono_gc_get_nursery (&shift_bits, &size);
1663                 break;
1664         }
1665         case MONO_PATCH_INFO_GC_NURSERY_BITS: {
1666                 int shift_bits;
1667                 size_t size;
1668
1669                 mono_gc_get_nursery (&shift_bits, &size);
1670
1671                 target = (gpointer)(mgreg_t)shift_bits;
1672                 break;
1673         }
1674         case MONO_PATCH_INFO_CASTCLASS_CACHE: {
1675                 target = mono_domain_alloc0 (domain, sizeof (gpointer));
1676                 break;
1677         }
1678         case MONO_PATCH_INFO_JIT_TLS_ID: {
1679                 target = (gpointer) (size_t) mono_jit_tls_id;
1680                 break;
1681         }
1682         case MONO_PATCH_INFO_TLS_OFFSET: {
1683                 int offset;
1684
1685                 offset = mini_get_tls_offset ((MonoTlsKey)GPOINTER_TO_INT (patch_info->data.target));
1686 #ifdef MONO_ARCH_HAVE_TRANSLATE_TLS_OFFSET
1687                 offset = mono_arch_translate_tls_offset (offset);
1688 #endif
1689                 target = GINT_TO_POINTER (offset);
1690                 break;
1691         }
1692         case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
1693                 target = NULL;
1694                 break;
1695         }
1696         case MONO_PATCH_INFO_LDSTR_LIT: {
1697                 int len;
1698                 char *s;
1699
1700                 len = strlen ((const char *)patch_info->data.target);
1701                 s = (char *)mono_domain_alloc0 (domain, len + 1);
1702                 memcpy (s, patch_info->data.target, len);
1703                 target = s;
1704
1705                 break;
1706         }
1707         case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
1708                 target = mini_get_gsharedvt_wrapper (TRUE, NULL, patch_info->data.sig, NULL, -1, FALSE);
1709                 break;
1710         default:
1711                 g_assert_not_reached ();
1712         }
1713
1714         return (gpointer)target;
1715 }
1716
1717 void
1718 mini_init_gsctx (MonoDomain *domain, MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
1719 {
1720         MonoGenericInst *inst;
1721         int i;
1722
1723         memset (gsctx, 0, sizeof (MonoGenericSharingContext));
1724
1725         if (context && context->class_inst) {
1726                 inst = context->class_inst;
1727                 for (i = 0; i < inst->type_argc; ++i) {
1728                         MonoType *type = inst->type_argv [i];
1729
1730                         if (mini_is_gsharedvt_gparam (type))
1731                                 gsctx->is_gsharedvt = TRUE;
1732                 }
1733         }
1734         if (context && context->method_inst) {
1735                 inst = context->method_inst;
1736
1737                 for (i = 0; i < inst->type_argc; ++i) {
1738                         MonoType *type = inst->type_argv [i];
1739
1740                         if (mini_is_gsharedvt_gparam (type))
1741                                 gsctx->is_gsharedvt = TRUE;
1742                 }
1743         }
1744 }
1745
1746 /*
1747  * LOCKING: Acquires the jit code hash lock.
1748  */
1749 MonoJitInfo*
1750 mini_lookup_method (MonoDomain *domain, MonoMethod *method, MonoMethod *shared)
1751 {
1752         MonoJitInfo *ji;
1753         static gboolean inited = FALSE;
1754         static int lookups = 0;
1755         static int failed_lookups = 0;
1756
1757         mono_domain_jit_code_hash_lock (domain);
1758         ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
1759         if (!ji && shared) {
1760                 /* Try generic sharing */
1761                 ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&domain->jit_code_hash, shared);
1762                 if (ji && !ji->has_generic_jit_info)
1763                         ji = NULL;
1764                 if (!inited) {
1765                         mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
1766                         mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
1767                         inited = TRUE;
1768                 }
1769
1770                 ++lookups;
1771                 if (!ji)
1772                         ++failed_lookups;
1773         }
1774         mono_domain_jit_code_hash_unlock (domain);
1775
1776         return ji;
1777 }
1778
1779 static MonoJitInfo*
1780 lookup_method (MonoDomain *domain, MonoMethod *method)
1781 {
1782         MonoJitInfo *ji;
1783         MonoMethod *shared;
1784
1785         ji = mini_lookup_method (domain, method, NULL);
1786
1787         if (!ji) {
1788                 if (!mono_method_is_generic_sharable (method, FALSE))
1789                         return NULL;
1790                 shared = mini_get_shared_method (method);
1791                 ji = mini_lookup_method (domain, method, shared);
1792         }
1793
1794         return ji;
1795 }
1796
1797 MonoJitInfo *
1798 mono_get_jit_info_from_method (MonoDomain *domain, MonoMethod *method)
1799 {
1800         return lookup_method (domain, method);
1801 }
1802
1803 #if ENABLE_JIT_MAP
1804 static FILE* perf_map_file;
1805
1806 void
1807 mono_enable_jit_map (void)
1808 {
1809         if (!perf_map_file) {
1810                 char name [64];
1811                 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
1812                 unlink (name);
1813                 perf_map_file = fopen (name, "w");
1814         }
1815 }
1816
1817 void
1818 mono_emit_jit_tramp (void *start, int size, const char *desc)
1819 {
1820         if (perf_map_file)
1821                 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
1822 }
1823
1824 void
1825 mono_emit_jit_map (MonoJitInfo *jinfo)
1826 {
1827         if (perf_map_file) {
1828                 char *name = mono_method_full_name (jinfo_get_method (jinfo), TRUE);
1829                 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
1830                 g_free (name);
1831         }
1832 }
1833
1834 gboolean
1835 mono_jit_map_is_enabled (void)
1836 {
1837         return perf_map_file != NULL;
1838 }
1839
1840 #endif
1841
1842 static void
1843 no_gsharedvt_in_wrapper (void)
1844 {
1845         g_assert_not_reached ();
1846 }
1847
1848 static gpointer
1849 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoError *error)
1850 {
1851         MonoDomain *target_domain, *domain = mono_domain_get ();
1852         MonoJitInfo *info;
1853         gpointer code = NULL, p;
1854         MonoJitInfo *ji;
1855         MonoJitICallInfo *callinfo = NULL;
1856         WrapperInfo *winfo = NULL;
1857
1858         mono_error_init (error);
1859
1860         /*
1861          * ICALL wrappers are handled specially, since there is only one copy of them
1862          * shared by all appdomains.
1863          */
1864         if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1865                 winfo = mono_marshal_get_wrapper_info (method);
1866         if (winfo && winfo->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
1867                 callinfo = mono_find_jit_icall_by_addr (winfo->d.icall.func);
1868                 g_assert (callinfo);
1869
1870                 /* Must be domain neutral since there is only one copy */
1871                 opt |= MONO_OPT_SHARED;
1872         } else {
1873                 /* MONO_OPT_SHARED is no longer supported, we only use it for icall wrappers */
1874                 opt &= ~MONO_OPT_SHARED;
1875         }
1876
1877         if (opt & MONO_OPT_SHARED)
1878                 target_domain = mono_get_root_domain ();
1879         else
1880                 target_domain = domain;
1881
1882         if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
1883                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
1884
1885                 g_assert (info);
1886                 if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
1887                         MonoGenericContext *ctx = NULL;
1888                         if (method->is_inflated)
1889                                 ctx = mono_method_get_context (method);
1890                         method = info->d.synchronized_inner.method;
1891                         if (ctx) {
1892                                 method = mono_class_inflate_generic_method_checked (method, ctx, error);
1893                                 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
1894                         }
1895                 }
1896         }
1897
1898         info = lookup_method (target_domain, method);
1899         if (info) {
1900                 /* We can't use a domain specific method in another domain */
1901                 if (! ((domain != target_domain) && !info->domain_neutral)) {
1902                         MonoVTable *vtable;
1903                         MonoException *tmpEx;
1904
1905                         mono_jit_stats.methods_lookups++;
1906                         vtable = mono_class_vtable (domain, method->klass);
1907                         g_assert (vtable);
1908                         tmpEx = mono_runtime_class_init_full (vtable, FALSE);
1909                         if (tmpEx) {
1910                                 mono_error_set_exception_instance (error, tmpEx);
1911                                 return NULL;
1912                         }
1913                         return mono_create_ftnptr (target_domain, info->code_start);
1914                 }
1915         }
1916
1917 #ifdef MONO_USE_AOT_COMPILER
1918         if (opt & MONO_OPT_AOT) {
1919                 MonoDomain *domain = mono_domain_get ();
1920
1921                 mono_class_init (method->klass);
1922
1923                 if ((code = mono_aot_get_method (domain, method))) {
1924                         MonoVTable *vtable;
1925
1926                         /*
1927                          * In llvm-only mode, method might be a shared method, so we can't initialize its class.
1928                          * This is not a problem, since it will be initialized when the method is first
1929                          * called by init_method ().
1930                          */
1931                         if (!mono_llvm_only) {
1932                                 vtable = mono_class_vtable (domain, method->klass);
1933                                 g_assert (vtable);
1934                                 mono_runtime_class_init (vtable);
1935                         }
1936                 }
1937         }
1938 #endif
1939
1940         if (!code && mono_llvm_only) {
1941                 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
1942                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
1943
1944                         if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
1945                                 /*
1946                                  * These wrappers are only created for signatures which are in the program, but
1947                                  * sometimes we load methods too eagerly and have to create them even if they
1948                                  * will never be called.
1949                                  */
1950                                 return no_gsharedvt_in_wrapper;
1951                         }
1952                 }
1953         }
1954
1955         if (!code)
1956                 code = mono_jit_compile_method_inner (method, target_domain, opt, error);
1957         if (!mono_error_ok (error))
1958                 return NULL;
1959
1960         if (!code && mono_llvm_only) {
1961                 printf ("AOT method not found in llvmonly mode: %s\n", mono_method_full_name (method, 1));
1962                 g_assert_not_reached ();
1963         }
1964
1965         if (!code)
1966                 return NULL;
1967
1968         if (method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC) {
1969                 MonoDomain *d;
1970
1971                 /*
1972                  * SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
1973                  */
1974                 ji = mini_jit_info_table_find (mono_domain_get (), (char *)code, &d);
1975                 g_assert (ji);
1976         }
1977
1978         p = mono_create_ftnptr (target_domain, code);
1979
1980         if (callinfo) {
1981                 /*mono_register_jit_icall_wrapper takes the loader lock, so we take it on the outside. */
1982                 mono_loader_lock ();
1983                 mono_jit_lock ();
1984                 if (!callinfo->wrapper) {
1985                         callinfo->wrapper = p;
1986                         mono_register_jit_icall_wrapper (callinfo, p);
1987                 }
1988                 mono_jit_unlock ();
1989                 mono_loader_unlock ();
1990         }
1991
1992         return p;
1993 }
1994
1995 gpointer
1996 mono_jit_compile_method (MonoMethod *method, MonoError *error)
1997 {
1998         gpointer code;
1999
2000         code = mono_jit_compile_method_with_opt (method, mono_get_optimizations_for_method (method, default_opt), error);
2001         return code;
2002 }
2003
2004 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2005 static void
2006 invalidated_delegate_trampoline (char *desc)
2007 {
2008         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
2009                  "See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
2010                  desc);
2011 }
2012 #endif
2013
2014 /*
2015  * mono_jit_free_method:
2016  *
2017  *  Free all memory allocated by the JIT for METHOD.
2018  */
2019 static void
2020 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
2021 {
2022         MonoJitDynamicMethodInfo *ji;
2023         gboolean destroy = TRUE;
2024         GHashTableIter iter;
2025         MonoJumpList *jlist;
2026
2027         g_assert (method->dynamic);
2028
2029         mono_domain_lock (domain);
2030         ji = mono_dynamic_code_hash_lookup (domain, method);
2031         mono_domain_unlock (domain);
2032
2033         if (!ji)
2034                 return;
2035
2036         mono_debug_remove_method (method, domain);
2037
2038         mono_domain_lock (domain);
2039         g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
2040         mono_domain_jit_code_hash_lock (domain);
2041         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
2042         mono_domain_jit_code_hash_unlock (domain);
2043         g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
2044
2045         /* requires the domain lock - took above */
2046         mono_conc_hashtable_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
2047
2048         /* Remove jump targets in this method */
2049         g_hash_table_iter_init (&iter, domain_jit_info (domain)->jump_target_hash);
2050         while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
2051                 GSList *tmp, *remove;
2052
2053                 remove = NULL;
2054                 for (tmp = jlist->list; tmp; tmp = tmp->next) {
2055                         guint8 *ip = (guint8 *)tmp->data;
2056
2057                         if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
2058                                 remove = g_slist_prepend (remove, tmp);
2059                 }
2060                 for (tmp = remove; tmp; tmp = tmp->next) {
2061                         jlist->list = g_slist_delete_link ((GSList *)jlist->list, (GSList *)tmp->data);
2062                 }
2063                 g_slist_free (remove);
2064         }
2065
2066         mono_domain_unlock (domain);
2067
2068 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2069         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
2070                 /*
2071                  * Instead of freeing the code, change it to call an error routine
2072                  * so people can fix their code.
2073                  */
2074                 char *type = mono_type_full_name (&method->klass->byval_arg);
2075                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
2076
2077                 g_free (type);
2078                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
2079                 destroy = FALSE;
2080         }
2081 #endif
2082
2083         /*
2084          * This needs to be done before freeing code_mp, since the code address is the
2085          * key in the table, so if we free the code_mp first, another thread can grab the
2086          * same code address and replace our entry in the table.
2087          */
2088         mono_jit_info_table_remove (domain, ji->ji);
2089
2090         if (destroy)
2091                 mono_code_manager_destroy (ji->code_mp);
2092         g_free (ji);
2093 }
2094
2095 gpointer
2096 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
2097 {
2098         MonoDomain *target_domain;
2099         MonoJitInfo *info;
2100
2101         if (default_opt & MONO_OPT_SHARED)
2102                 target_domain = mono_get_root_domain ();
2103         else
2104                 target_domain = domain;
2105
2106         info = lookup_method (target_domain, method);
2107         if (info) {
2108                 /* We can't use a domain specific method in another domain */
2109                 if (! ((domain != target_domain) && !info->domain_neutral)) {
2110                         mono_jit_stats.methods_lookups++;
2111                         if (ji)
2112                                 *ji = info;
2113                         return info->code_start;
2114                 }
2115         }
2116
2117         if (ji)
2118                 *ji = NULL;
2119         return NULL;
2120 }
2121
2122 static guint32 bisect_opt = 0;
2123 static GHashTable *bisect_methods_hash = NULL;
2124
2125 void
2126 mono_set_bisect_methods (guint32 opt, const char *method_list_filename)
2127 {
2128         FILE *file;
2129         char method_name [2048];
2130
2131         bisect_opt = opt;
2132         bisect_methods_hash = g_hash_table_new (g_str_hash, g_str_equal);
2133         g_assert (bisect_methods_hash);
2134
2135         file = fopen (method_list_filename, "r");
2136         g_assert (file);
2137
2138         while (fgets (method_name, sizeof (method_name), file)) {
2139                 size_t len = strlen (method_name);
2140                 g_assert (len > 0);
2141                 g_assert (method_name [len - 1] == '\n');
2142                 method_name [len - 1] = 0;
2143                 g_hash_table_insert (bisect_methods_hash, g_strdup (method_name), GINT_TO_POINTER (1));
2144         }
2145         g_assert (feof (file));
2146 }
2147
2148 gboolean mono_do_single_method_regression = FALSE;
2149 guint32 mono_single_method_regression_opt = 0;
2150 MonoMethod *mono_current_single_method;
2151 GSList *mono_single_method_list;
2152 GHashTable *mono_single_method_hash;
2153
2154 guint32
2155 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt)
2156 {
2157         g_assert (method);
2158
2159         if (bisect_methods_hash) {
2160                 char *name = mono_method_full_name (method, TRUE);
2161                 void *res = g_hash_table_lookup (bisect_methods_hash, name);
2162                 g_free (name);
2163                 if (res)
2164                         return default_opt | bisect_opt;
2165         }
2166         if (!mono_do_single_method_regression)
2167                 return default_opt;
2168         if (!mono_current_single_method) {
2169                 if (!mono_single_method_hash)
2170                         mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
2171                 if (!g_hash_table_lookup (mono_single_method_hash, method)) {
2172                         g_hash_table_insert (mono_single_method_hash, method, method);
2173                         mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
2174                 }
2175                 return default_opt;
2176         }
2177         if (method == mono_current_single_method)
2178                 return mono_single_method_regression_opt;
2179         return default_opt;
2180 }
2181
2182 gpointer
2183 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
2184 {
2185         return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
2186 }
2187
2188 typedef struct {
2189         MonoMethod *method;
2190         gpointer compiled_method;
2191         gpointer runtime_invoke;
2192         MonoVTable *vtable;
2193         MonoDynCallInfo *dyn_call_info;
2194         MonoClass *ret_box_class;
2195         MonoMethodSignature *sig;
2196         gboolean gsharedvt_invoke;
2197         gpointer *wrapper_arg;
2198 } RuntimeInvokeInfo;
2199
2200 static RuntimeInvokeInfo*
2201 create_runtime_invoke_info (MonoDomain *domain, MonoMethod *method, gpointer compiled_method, gboolean callee_gsharedvt, MonoError *error)
2202 {
2203         MonoMethod *invoke;
2204         RuntimeInvokeInfo *info;
2205
2206         info = g_new0 (RuntimeInvokeInfo, 1);
2207         info->compiled_method = compiled_method;
2208         info->sig = mono_method_signature (method);
2209
2210         invoke = mono_marshal_get_runtime_invoke (method, FALSE);
2211         info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
2212         g_assert (info->vtable);
2213
2214         MonoMethodSignature *sig = mono_method_signature (method);
2215         MonoType *ret_type;
2216
2217         /*
2218          * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
2219          * in full-aot mode, so we use a slower, but more generic wrapper if
2220          * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
2221          */
2222 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2223         if (!mono_llvm_only && (mono_aot_only || debug_options.dyn_runtime_invoke)) {
2224                 gboolean supported = TRUE;
2225                 int i;
2226
2227                 if (method->string_ctor)
2228                         sig = mono_marshal_get_string_ctor_signature (method);
2229
2230                 for (i = 0; i < sig->param_count; ++i) {
2231                         MonoType *t = sig->params [i];
2232
2233                         if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
2234                                 supported = FALSE;
2235                 }
2236
2237                 if (mono_class_is_contextbound (method->klass) || !info->compiled_method)
2238                         supported = FALSE;
2239
2240                 if (supported)
2241                         info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
2242         }
2243 #endif
2244
2245         ret_type = sig->ret;
2246         switch (ret_type->type) {
2247         case MONO_TYPE_VOID:
2248                 break;
2249         case MONO_TYPE_I1:
2250         case MONO_TYPE_U1:
2251         case MONO_TYPE_I2:
2252         case MONO_TYPE_U2:
2253         case MONO_TYPE_I4:
2254         case MONO_TYPE_U4:
2255         case MONO_TYPE_I:
2256         case MONO_TYPE_U:
2257         case MONO_TYPE_I8:
2258         case MONO_TYPE_U8:
2259         case MONO_TYPE_BOOLEAN:
2260         case MONO_TYPE_CHAR:
2261         case MONO_TYPE_R4:
2262         case MONO_TYPE_R8:
2263                 info->ret_box_class = mono_class_from_mono_type (ret_type);
2264                 break;
2265         case MONO_TYPE_PTR:
2266                 info->ret_box_class = mono_defaults.int_class;
2267                 break;
2268         case MONO_TYPE_STRING:
2269         case MONO_TYPE_CLASS:
2270         case MONO_TYPE_ARRAY:
2271         case MONO_TYPE_SZARRAY:
2272         case MONO_TYPE_OBJECT:
2273                 break;
2274         case MONO_TYPE_GENERICINST:
2275                 if (!MONO_TYPE_IS_REFERENCE (ret_type))
2276                         info->ret_box_class = mono_class_from_mono_type (ret_type);
2277                 break;
2278         case MONO_TYPE_VALUETYPE:
2279                 info->ret_box_class = mono_class_from_mono_type (ret_type);
2280                 break;
2281         default:
2282                 g_assert_not_reached ();
2283                 break;
2284         }
2285
2286         if (!info->dyn_call_info) {
2287                 if (mono_llvm_only) {
2288 #ifndef ENABLE_GSHAREDVT
2289                         g_assert_not_reached ();
2290 #endif
2291                         info->gsharedvt_invoke = TRUE;
2292                         if (!callee_gsharedvt) {
2293                                 /* Invoke a gsharedvt out wrapper instead */
2294                                 MonoMethod *wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
2295                                 MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
2296
2297                                 info->wrapper_arg = g_malloc0 (2 * sizeof (gpointer));
2298                                 info->wrapper_arg [0] = mini_add_method_wrappers_llvmonly (method, info->compiled_method, FALSE, FALSE, &(info->wrapper_arg [1]));
2299
2300                                 /* Pass has_rgctx == TRUE since the wrapper has an extra arg */
2301                                 invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
2302                                 g_free (wrapper_sig);
2303
2304                                 info->compiled_method = mono_jit_compile_method (wrapper, error);
2305                                 if (!mono_error_ok (error)) {
2306                                         g_free (info);
2307                                         return NULL;
2308                                 }
2309                         } else {
2310                                 /* Gsharedvt methods can be invoked the same way */
2311                                 /* The out wrapper has the same signature as the compiled gsharedvt method */
2312                                 MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
2313
2314                                 info->wrapper_arg = mono_method_needs_static_rgctx_invoke (method, TRUE) ? mini_method_get_rgctx (method) : NULL;
2315
2316                                 invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
2317                                 g_free (wrapper_sig);
2318                         }
2319                 }
2320                 info->runtime_invoke = mono_jit_compile_method (invoke, error);
2321                 if (!mono_error_ok (error)) {
2322                         g_free (info);
2323                         return NULL;
2324                 }
2325         }
2326
2327         return info;
2328 }
2329
2330 static MonoObject*
2331 mono_llvmonly_runtime_invoke (MonoMethod *method, RuntimeInvokeInfo *info, void *obj, void **params, MonoObject **exc, MonoError *error)
2332 {
2333         MonoMethodSignature *sig = info->sig;
2334         MonoDomain *domain = mono_domain_get ();
2335         MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
2336         gpointer *args;
2337         gpointer retval_ptr;
2338         guint8 retval [256];
2339         gpointer *param_refs;
2340         int i, pindex;
2341
2342         mono_error_init (error);
2343
2344         g_assert (info->gsharedvt_invoke);
2345
2346         /*
2347          * Instead of invoking the method directly, we invoke a gsharedvt out wrapper.
2348          * The advantage of this is the gsharedvt out wrappers have a reduced set of
2349          * signatures, so we only have to generate runtime invoke wrappers for these
2350          * signatures.
2351          * This code also handles invocation of gsharedvt methods directly, no
2352          * out wrappers are used in that case.
2353          */
2354         args = (void **)g_alloca ((sig->param_count + sig->hasthis + 2) * sizeof (gpointer));
2355         param_refs = (gpointer*)g_alloca ((sig->param_count + sig->hasthis + 2) * sizeof (gpointer));
2356         pindex = 0;
2357         /*
2358          * The runtime invoke wrappers expects pointers to primitive types, so have to
2359          * use indirections.
2360          */
2361         if (sig->hasthis)
2362                 args [pindex ++] = &obj;
2363         if (sig->ret->type != MONO_TYPE_VOID) {
2364                 retval_ptr = (gpointer)&retval;
2365                 args [pindex ++] = &retval_ptr;
2366         }
2367         for (i = 0; i < sig->param_count; ++i) {
2368                 MonoType *t = sig->params [i];
2369
2370                 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
2371                         MonoClass *klass = mono_class_from_mono_type (t);
2372                         guint8 *nullable_buf;
2373                         int size;
2374
2375                         size = mono_class_value_size (klass, NULL);
2376                         nullable_buf = g_alloca (size);
2377                         g_assert (nullable_buf);
2378
2379                         /* The argument pointed to by params [i] is either a boxed vtype or null */
2380                         mono_nullable_init (nullable_buf, (MonoObject*)params [i], klass);
2381                         params [i] = nullable_buf;
2382                 }
2383
2384                 if (!t->byref && (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR)) {
2385                         param_refs [i] = params [i];
2386                         params [i] = &(param_refs [i]);
2387                 }
2388                 args [pindex ++] = &params [i];
2389         }
2390         /* The gsharedvt out wrapper has an extra argument which contains the method to call */
2391         args [pindex ++] = &info->wrapper_arg;
2392
2393         runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
2394
2395         runtime_invoke (NULL, args, exc, info->compiled_method);
2396         if (exc && *exc)
2397                 mono_error_set_exception_instance (error, (MonoException*) *exc);
2398
2399         if (sig->ret->type != MONO_TYPE_VOID && info->ret_box_class)
2400                 return mono_value_box (domain, info->ret_box_class, retval);
2401         else
2402                 return *(MonoObject**)retval;
2403 }
2404
2405 /**
2406  * mono_jit_runtime_invoke:
2407  * @method: the method to invoke
2408  * @obj: this pointer
2409  * @params: array of parameter values.
2410  * @exc: Set to the exception raised in the managed method.  If NULL, error is thrown instead.
2411  *       If coop is enabled, this argument is ignored - all exceptoins are caught and propagated
2412  *       through @error
2413  * @error: error or caught exception object
2414  */
2415 static MonoObject*
2416 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
2417 {
2418         MonoMethod *invoke, *callee;
2419         MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
2420         MonoDomain *domain = mono_domain_get ();
2421         MonoJitDomainInfo *domain_info;
2422         RuntimeInvokeInfo *info, *info2;
2423         MonoJitInfo *ji = NULL;
2424         gboolean callee_gsharedvt = FALSE;
2425
2426         mono_error_init (error);
2427
2428         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
2429                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
2430                 return NULL;
2431         }
2432
2433         domain_info = domain_jit_info (domain);
2434
2435         info = (RuntimeInvokeInfo *)mono_conc_hashtable_lookup (domain_info->runtime_invoke_hash, method);
2436
2437         if (!info) {
2438                 if (mono_security_core_clr_enabled ()) {
2439                         /*
2440                          * This might be redundant since mono_class_vtable () already does this,
2441                          * but keep it just in case for moonlight.
2442                          */
2443                         mono_class_setup_vtable (method->klass);
2444                         if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
2445                                 MonoException *fail_exc = mono_class_get_exception_for_failure (method->klass);
2446                                 if (exc)
2447                                         *exc = (MonoObject*)fail_exc;
2448                                 mono_error_set_exception_instance (error, fail_exc);
2449                                 return NULL;
2450                         }
2451                 }
2452
2453                 gpointer compiled_method;
2454
2455                 callee = method;
2456                 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
2457                         (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
2458                         /*
2459                          * Array Get/Set/Address methods. The JIT implements them using inline code
2460                          * inside the runtime invoke wrappers, so no need to compile them.
2461                          */
2462                         if (mono_aot_only) {
2463                                 /*
2464                                  * Call a wrapper, since the runtime invoke wrapper was not generated.
2465                                  */
2466                                 MonoMethod *wrapper;
2467
2468                                 wrapper = mono_marshal_get_array_accessor_wrapper (method);
2469                                 invoke = mono_marshal_get_runtime_invoke (wrapper, FALSE);
2470                                 callee = wrapper;
2471                         } else {
2472                                 callee = NULL;
2473                         }
2474                 }
2475
2476                 if (callee) {
2477                         compiled_method = mono_jit_compile_method_with_opt (callee, mono_get_optimizations_for_method (callee, default_opt), error);
2478                         if (!compiled_method) {
2479                                 g_assert (!mono_error_ok (error));
2480                                 return NULL;
2481                         }
2482
2483                         if (mono_llvm_only) {
2484                                 ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
2485                                 callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
2486                                 if (callee_gsharedvt)
2487                                         callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature (jinfo_get_method (ji)));
2488                         }
2489
2490                         if (!callee_gsharedvt)
2491                                 compiled_method = mini_add_method_trampoline (callee, compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
2492                 } else {
2493                         compiled_method = NULL;
2494                 }
2495
2496                 info = create_runtime_invoke_info (domain, method, compiled_method, callee_gsharedvt, error);
2497                 if (!mono_error_ok (error))
2498                         return NULL;
2499
2500                 mono_domain_lock (domain);
2501                 info2 = (RuntimeInvokeInfo *)mono_conc_hashtable_insert (domain_info->runtime_invoke_hash, method, info);
2502                 mono_domain_unlock (domain);
2503                 if (info2) {
2504                         g_free (info);
2505                         info = info2;
2506                 }
2507         }
2508
2509         /*
2510          * We need this here because mono_marshal_get_runtime_invoke can place
2511          * the helper method in System.Object and not the target class.
2512          */
2513         if (exc)
2514         {
2515                 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
2516                 if (*exc) {
2517                         mono_error_set_exception_instance (error, (MonoException*) *exc);
2518                         return NULL;
2519                 }
2520         } else {
2521                 mono_runtime_class_init (info->vtable);
2522         }
2523
2524         /* If coop is enabled, and the caller didn't ask for the exception to be caught separately,
2525            we always catch the exception and propagate it through the MonoError */
2526         gboolean catchExcInMonoError =
2527                 (exc == NULL) && mono_threads_is_coop_enabled ();
2528         MonoObject *invoke_exc = NULL;
2529         if (catchExcInMonoError)
2530                 exc = &invoke_exc;
2531
2532         /* The wrappers expect this to be initialized to NULL */
2533         if (exc)
2534                 *exc = NULL;
2535
2536 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2537         if (info->dyn_call_info) {
2538                 MonoMethodSignature *sig = mono_method_signature (method);
2539                 gpointer *args;
2540                 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
2541                 int i, pindex;
2542                 guint8 buf [512];
2543                 guint8 retval [256];
2544
2545                 if (!dyn_runtime_invoke) {
2546                         invoke = mono_marshal_get_runtime_invoke_dynamic ();
2547                         dyn_runtime_invoke = (RuntimeInvokeDynamicFunction)mono_jit_compile_method (invoke, error);
2548                         if (!mono_error_ok (error))
2549                                 return NULL;
2550                 }
2551
2552                 /* Convert the arguments to the format expected by start_dyn_call () */
2553                 args = (void **)g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
2554                 pindex = 0;
2555                 if (sig->hasthis)
2556                         args [pindex ++] = &obj;
2557                 for (i = 0; i < sig->param_count; ++i) {
2558                         MonoType *t = sig->params [i];
2559
2560                         if (t->byref) {
2561                                 args [pindex ++] = &params [i];
2562                         } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
2563                                 args [pindex ++] = &params [i];
2564                         } else {
2565                                 args [pindex ++] = params [i];
2566                         }
2567                 }
2568
2569                 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
2570
2571                 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
2572
2573                 dyn_runtime_invoke (buf, exc, info->compiled_method);
2574                 if (catchExcInMonoError && *exc != NULL)
2575                         mono_error_set_exception_instance (error, (MonoException*) *exc);
2576
2577                 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
2578
2579                 if (info->ret_box_class)
2580                         return mono_value_box (domain, info->ret_box_class, retval);
2581                 else
2582                         return *(MonoObject**)retval;
2583         }
2584 #endif
2585
2586         if (mono_llvm_only)
2587                 return mono_llvmonly_runtime_invoke (method, info, obj, params, exc, error);
2588
2589         runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
2590
2591         MonoObject *result = runtime_invoke ((MonoObject *)obj, params, exc, info->compiled_method);
2592         if (catchExcInMonoError && *exc != NULL)
2593                 mono_error_set_exception_instance (error, (MonoException*) *exc);
2594         return result;
2595 }
2596
2597 typedef struct {
2598         MonoVTable *vtable;
2599         int slot;
2600 } IMTThunkInfo;
2601
2602 typedef gpointer (*IMTThunkFunc) (gpointer *arg, MonoMethod *imt_method);
2603
2604 /*
2605  * mini_llvmonly_initial_imt_thunk:
2606  *
2607  *  This function is called the first time a call is made through an IMT thunk.
2608  * It should have the same signature as the mono_llvmonly_imt_thunk_... functions.
2609  */
2610 static gpointer
2611 mini_llvmonly_initial_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2612 {
2613         IMTThunkInfo *info = (IMTThunkInfo*)arg;
2614         gpointer *imt;
2615         gpointer *ftndesc;
2616         IMTThunkFunc func;
2617
2618         mono_vtable_build_imt_slot (info->vtable, info->slot);
2619
2620         imt = (gpointer*)info->vtable;
2621         imt -= MONO_IMT_SIZE;
2622
2623         /* Return what the real IMT thunk returns */
2624         ftndesc = imt [info->slot];
2625         func = ftndesc [0];
2626
2627         if (func == (IMTThunkFunc)mini_llvmonly_initial_imt_thunk)
2628                 /* Happens when the imt slot contains only a generic virtual method */
2629                 return NULL;
2630         return func ((gpointer *)ftndesc [1], imt_method);
2631 }
2632
2633 /* This is called indirectly through an imt slot. */
2634 static gpointer
2635 mono_llvmonly_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2636 {
2637         int i = 0;
2638
2639         /* arg points to an array created in mono_llvmonly_get_imt_thunk () */
2640         while (arg [i] && arg [i] != imt_method)
2641                 i += 2;
2642         g_assert (arg [i]);
2643
2644         return arg [i + 1];
2645 }
2646
2647 /* Optimized versions of mono_llvmonly_imt_thunk () for different table sizes */
2648 static gpointer
2649 mono_llvmonly_imt_thunk_1 (gpointer *arg, MonoMethod *imt_method)
2650 {
2651         //g_assert (arg [0] == imt_method);
2652         return arg [1];
2653 }
2654
2655 static gpointer
2656 mono_llvmonly_imt_thunk_2 (gpointer *arg, MonoMethod *imt_method)
2657 {
2658         //g_assert (arg [0] == imt_method || arg [2] == imt_method);
2659         if (arg [0] == imt_method)
2660                 return arg [1];
2661         else
2662                 return arg [3];
2663 }
2664
2665 static gpointer
2666 mono_llvmonly_imt_thunk_3 (gpointer *arg, MonoMethod *imt_method)
2667 {
2668         //g_assert (arg [0] == imt_method || arg [2] == imt_method || arg [4] == imt_method);
2669         if (arg [0] == imt_method)
2670                 return arg [1];
2671         else if (arg [2] == imt_method)
2672                 return arg [3];
2673         else
2674                 return arg [5];
2675 }
2676
2677 /*
2678  * A version of the imt thunk used for generic virtual/variant iface methods.
2679  * Unlikely a normal imt thunk, its possible that IMT_METHOD is not found
2680  * in the search table. The original JIT code had a 'fallback' trampoline it could
2681  * call, but we can't do that, so we just return NULL, and the compiled code
2682  * will handle it.
2683  */
2684 static gpointer
2685 mono_llvmonly_fallback_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2686 {
2687         int i = 0;
2688
2689         while (arg [i] && arg [i] != imt_method)
2690                 i += 2;
2691         if (!arg [i])
2692                 return NULL;
2693
2694         return arg [i + 1];
2695 }
2696
2697 static gpointer
2698 mono_llvmonly_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
2699 {
2700         gpointer *buf;
2701         gpointer *res;
2702         int i, index, real_count;
2703         gboolean virtual_generic = FALSE;
2704
2705         /*
2706          * Create an array which is passed to the imt thunk functions.
2707          * The array contains MonoMethod-function descriptor pairs, terminated by a NULL entry.
2708          */
2709
2710         real_count = 0;
2711         for (i = 0; i < count; ++i) {
2712                 MonoIMTCheckItem *item = imt_entries [i];
2713
2714                 if (item->is_equals)
2715                         real_count ++;
2716                 if (item->has_target_code)
2717                         virtual_generic = TRUE;
2718         }
2719
2720         /*
2721          * Initialize all vtable entries reachable from this imt slot, so the compiled
2722          * code doesn't have to check it.
2723          */
2724         for (i = 0; i < count; ++i) {
2725                 MonoIMTCheckItem *item = imt_entries [i];
2726                 int vt_slot;
2727
2728                 if (!item->is_equals || item->has_target_code)
2729                         continue;
2730                 vt_slot = item->value.vtable_slot;
2731                 mono_init_vtable_slot (vtable, vt_slot);
2732         }
2733
2734         /* Save the entries into an array */
2735         buf = (void **)mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
2736         index = 0;
2737         for (i = 0; i < count; ++i) {
2738                 MonoIMTCheckItem *item = imt_entries [i];
2739
2740                 if (!item->is_equals)
2741                         continue;
2742
2743                 g_assert (item->key);
2744                 buf [(index * 2)] = item->key;
2745                 if (item->has_target_code)
2746                         buf [(index * 2) + 1] = item->value.target_code;
2747                 else
2748                         buf [(index * 2) + 1] = vtable->vtable [item->value.vtable_slot];
2749                 index ++;
2750         }
2751         buf [(index * 2)] = NULL;
2752         buf [(index * 2) + 1] = fail_tramp;
2753
2754         /*
2755          * Return a function descriptor for a C function with 'buf' as its argument.
2756          * It will by called by JITted code.
2757          */
2758         res = (void **)mono_domain_alloc (domain, 2 * sizeof (gpointer));
2759         switch (real_count) {
2760         case 1:
2761                 res [0] = mono_llvmonly_imt_thunk_1;
2762                 break;
2763         case 2:
2764                 res [0] = mono_llvmonly_imt_thunk_2;
2765                 break;
2766         case 3:
2767                 res [0] = mono_llvmonly_imt_thunk_3;
2768                 break;
2769         default:
2770                 res [0] = mono_llvmonly_imt_thunk;
2771                 break;
2772         }
2773         if (virtual_generic || fail_tramp)
2774                 res [0] = mono_llvmonly_fallback_imt_thunk;
2775         res [1] = buf;
2776
2777         return res;
2778 }
2779
2780 MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
2781 {
2782         MonoException *exc = NULL;
2783         MonoJitInfo *ji;
2784         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2785         MONO_SIG_HANDLER_GET_CONTEXT;
2786
2787         ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
2788
2789 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
2790         if (mono_arch_is_int_overflow (ctx, info))
2791                 /*
2792                  * The spec says this throws ArithmeticException, but MS throws the derived
2793                  * OverflowException.
2794                  */
2795                 exc = mono_get_exception_overflow ();
2796         else
2797                 exc = mono_get_exception_divide_by_zero ();
2798 #else
2799         exc = mono_get_exception_divide_by_zero ();
2800 #endif
2801
2802         if (!ji) {
2803                 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2804                         return;
2805
2806                 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2807                 if (mono_do_crash_chaining) {
2808                         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2809                         return;
2810                 }
2811         }
2812
2813         mono_arch_handle_exception (ctx, exc);
2814 }
2815
2816 MONO_SIG_HANDLER_FUNC (, mono_sigill_signal_handler)
2817 {
2818         MonoException *exc;
2819         MONO_SIG_HANDLER_GET_CONTEXT;
2820
2821         exc = mono_get_exception_execution_engine ("SIGILL");
2822
2823         mono_arch_handle_exception (ctx, exc);
2824 }
2825
2826 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
2827 #define HAVE_SIG_INFO
2828 #endif
2829
2830 MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
2831 {
2832         MonoJitInfo *ji;
2833         MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2834         gpointer fault_addr = NULL;
2835 #ifdef HAVE_SIG_INFO
2836         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2837 #else
2838         void *info = NULL;
2839 #endif
2840         MONO_SIG_HANDLER_GET_CONTEXT;
2841
2842 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
2843         if (mono_arch_is_single_step_event (info, ctx)) {
2844                 mono_debugger_agent_single_step_event (ctx);
2845                 return;
2846         } else if (mono_arch_is_breakpoint_event (info, ctx)) {
2847                 mono_debugger_agent_breakpoint_hit (ctx);
2848                 return;
2849         }
2850 #endif
2851
2852 #if defined(HAVE_SIG_INFO)
2853 #if !defined(HOST_WIN32)
2854         fault_addr = info->si_addr;
2855         if (mono_aot_is_pagefault (info->si_addr)) {
2856                 mono_aot_handle_pagefault (info->si_addr);
2857                 return;
2858         }
2859 #endif
2860
2861         /* The thread might no be registered with the runtime */
2862         if (!mono_domain_get () || !jit_tls) {
2863                 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2864                         return;
2865                 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2866                 if (mono_do_crash_chaining) {
2867                         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2868                         return;
2869                 }
2870         }
2871 #endif
2872
2873         ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
2874
2875 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2876         if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
2877                 return;
2878
2879 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2880         /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
2881         fault_addr = info->si_addr;
2882         if (fault_addr == NULL) {
2883                 MonoContext mctx;
2884
2885                 mono_sigctx_to_monoctx (ctx, &mctx);
2886
2887                 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
2888         }
2889 #endif
2890
2891         if (jit_tls->stack_size &&
2892                 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
2893                 /*
2894                  * The hard-guard page has been hit: there is not much we can do anymore
2895                  * Print a hopefully clear message and abort.
2896                  */
2897                 mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
2898                 g_assert_not_reached ();
2899         } else {
2900                 /* The original handler might not like that it is executed on an altstack... */
2901                 if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2902                         return;
2903
2904                 mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
2905         }
2906 #else
2907
2908         if (!ji) {
2909                 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2910                         return;
2911
2912                 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2913
2914                 if (mono_do_crash_chaining) {
2915                         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2916                         return;
2917                 }
2918         }
2919
2920         mono_arch_handle_exception (ctx, NULL);
2921 #endif
2922 }
2923
2924 MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
2925 {
2926         MonoException *exc;
2927         MONO_SIG_HANDLER_GET_CONTEXT;
2928
2929         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
2930
2931         mono_arch_handle_exception (ctx, exc);
2932 }
2933
2934 #ifndef DISABLE_REMOTING
2935 /* mono_jit_create_remoting_trampoline:
2936  * @method: pointer to the method info
2937  *
2938  * Creates a trampoline which calls the remoting functions. This
2939  * is used in the vtable of transparent proxies.
2940  *
2941  * Returns: a pointer to the newly created code
2942  */
2943 static gpointer
2944 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
2945 {
2946         MonoMethod *nm;
2947         guint8 *addr = NULL;
2948
2949         if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
2950                 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
2951                         domain, NULL);
2952         }
2953
2954         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
2955             (mono_method_signature (method)->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))) {
2956                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
2957                 addr = (guint8 *)mono_compile_method (nm);
2958         } else
2959         {
2960                 addr = (guint8 *)mono_compile_method (method);
2961         }
2962         return mono_get_addr_from_ftnptr (addr);
2963 }
2964 #endif
2965
2966 static void
2967 no_imt_trampoline (void)
2968 {
2969         g_assert_not_reached ();
2970 }
2971
2972 static void
2973 no_vcall_trampoline (void)
2974 {
2975         g_assert_not_reached ();
2976 }
2977
2978 static gpointer *vtable_trampolines;
2979 static int vtable_trampolines_size;
2980
2981 gpointer
2982 mini_get_vtable_trampoline (MonoVTable *vt, int slot_index)
2983 {
2984         int index = slot_index + MONO_IMT_SIZE;
2985
2986         if (mono_llvm_only) {
2987                 if (slot_index < 0) {
2988                         /* Initialize the IMT thunks to a 'trampoline' so the generated code doesn't have to initialize it */
2989                         // FIXME: Memory management
2990                         gpointer *ftndesc = g_malloc (2 * sizeof (gpointer));
2991                         IMTThunkInfo *info = g_new0 (IMTThunkInfo, 1);
2992                         info->vtable = vt;
2993                         info->slot = index;
2994                         ftndesc [0] = mini_llvmonly_initial_imt_thunk;
2995                         ftndesc [1] = info;
2996                         mono_memory_barrier ();
2997                         return ftndesc;
2998                 } else {
2999                         return NULL;
3000                 }
3001         }
3002
3003         g_assert (slot_index >= - MONO_IMT_SIZE);
3004         if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
3005                 mono_jit_lock ();
3006                 if (!vtable_trampolines || index >= vtable_trampolines_size) {
3007                         int new_size;
3008                         gpointer new_table;
3009
3010                         new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
3011                         while (new_size <= index)
3012                                 new_size *= 2;
3013                         new_table = g_new0 (gpointer, new_size);
3014
3015                         if (vtable_trampolines)
3016                                 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
3017                         g_free (vtable_trampolines);
3018                         mono_memory_barrier ();
3019                         vtable_trampolines = (void **)new_table;
3020                         vtable_trampolines_size = new_size;
3021                 }
3022                 mono_jit_unlock ();
3023         }
3024
3025         if (!vtable_trampolines [index])
3026                 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
3027         return vtable_trampolines [index];
3028 }
3029
3030 static gpointer
3031 mini_get_imt_trampoline (MonoVTable *vt, int slot_index)
3032 {
3033         return mini_get_vtable_trampoline (vt, slot_index - MONO_IMT_SIZE);
3034 }
3035
3036 static gboolean
3037 mini_imt_entry_inited (MonoVTable *vt, int imt_slot_index)
3038 {
3039         if (mono_llvm_only)
3040                 return FALSE;
3041
3042         gpointer *imt = (gpointer*)vt;
3043         imt -= MONO_IMT_SIZE;
3044
3045         return (imt [imt_slot_index] != mini_get_imt_trampoline (vt, imt_slot_index));
3046 }
3047
3048 static gboolean
3049 is_callee_gsharedvt_variable (gpointer addr)
3050 {
3051         MonoJitInfo *ji;
3052         gboolean callee_gsharedvt;
3053
3054         ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (addr), NULL);
3055         g_assert (ji);
3056         callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
3057         if (callee_gsharedvt)
3058                 callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature (jinfo_get_method (ji)));
3059         return callee_gsharedvt;
3060 }
3061
3062 gpointer
3063 mini_get_delegate_arg (MonoMethod *method, gpointer method_ptr)
3064 {
3065         gpointer arg = NULL;
3066
3067         if (mono_method_needs_static_rgctx_invoke (method, FALSE))
3068                 arg = mini_method_get_rgctx (method);
3069
3070         /*
3071          * Avoid adding gsharedvt in wrappers since they might not exist if
3072          * this delegate is called through a gsharedvt delegate invoke wrapper.
3073          * Instead, encode that the method is gsharedvt in del->extra_arg,
3074          * the CEE_MONO_CALLI_EXTRA_ARG implementation in the JIT depends on this.
3075          */
3076         if (method->is_inflated && is_callee_gsharedvt_variable (method_ptr)) {
3077                 g_assert ((((mgreg_t)arg) & 1) == 0);
3078                 arg = (gpointer)(((mgreg_t)arg) | 1);
3079         }
3080         return arg;
3081 }
3082
3083 void
3084 mini_init_delegate (MonoDelegate *del)
3085 {
3086         if (mono_llvm_only)
3087                 del->extra_arg = mini_get_delegate_arg (del->method, del->method_ptr);
3088 }
3089
3090 gpointer
3091 mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
3092 {
3093         gboolean is_virtual_generic, is_interface, load_imt_reg;
3094         int offset, idx;
3095
3096         static guint8 **cache = NULL;
3097         static int cache_size = 0;
3098
3099         if (!method)
3100                 return NULL;
3101
3102         if (MONO_TYPE_ISSTRUCT (sig->ret))
3103                 return NULL;
3104
3105         is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
3106         is_interface = method->klass->flags & TYPE_ATTRIBUTE_INTERFACE ? TRUE : FALSE;
3107         load_imt_reg = is_virtual_generic || is_interface;
3108
3109         if (is_interface)
3110                 offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * SIZEOF_VOID_P;
3111         else
3112                 offset = G_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
3113
3114         idx = (offset / SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
3115         g_assert (idx >= 0);
3116
3117         /* Resize the cache to idx + 1 */
3118         if (cache_size < idx + 1) {
3119                 mono_jit_lock ();
3120                 if (cache_size < idx + 1) {
3121                         guint8 **new_cache;
3122                         int new_cache_size = idx + 1;
3123
3124                         new_cache = g_new0 (guint8*, new_cache_size);
3125                         if (cache)
3126                                 memcpy (new_cache, cache, cache_size * sizeof (guint8*));
3127                         g_free (cache);
3128
3129                         mono_memory_barrier ();
3130                         cache = new_cache;
3131                         cache_size = new_cache_size;
3132                 }
3133                 mono_jit_unlock ();
3134         }
3135
3136         if (cache [idx])
3137                 return cache [idx];
3138
3139         /* FIXME Support more cases */
3140         if (mono_aot_only) {
3141                 char tramp_name [256];
3142                 const char *imt = load_imt_reg ? "_imt" : "";
3143                 int ind = (load_imt_reg ? (-offset) : offset) / SIZEOF_VOID_P;
3144
3145                 sprintf (tramp_name, "delegate_virtual_invoke%s_%d", imt, ind);
3146                 cache [idx] = (guint8 *)mono_aot_get_trampoline (tramp_name);
3147                 g_assert (cache [idx]);
3148         } else {
3149                 cache [idx] = (guint8 *)mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
3150         }
3151         return cache [idx];
3152 }
3153
3154 /**
3155  * mini_parse_debug_option:
3156  * @option: The option to parse.
3157  *
3158  * Parses debug options for the mono runtime. The options are the same as for
3159  * the MONO_DEBUG environment variable.
3160  *
3161  */
3162 gboolean
3163 mini_parse_debug_option (const char *option)
3164 {
3165         if (!strcmp (option, "handle-sigint"))
3166                 debug_options.handle_sigint = TRUE;
3167         else if (!strcmp (option, "keep-delegates"))
3168                 debug_options.keep_delegates = TRUE;
3169         else if (!strcmp (option, "reverse-pinvoke-exceptions"))
3170                 debug_options.reverse_pinvoke_exceptions = TRUE;
3171         else if (!strcmp (option, "collect-pagefault-stats"))
3172                 debug_options.collect_pagefault_stats = TRUE;
3173         else if (!strcmp (option, "break-on-unverified"))
3174                 debug_options.break_on_unverified = TRUE;
3175         else if (!strcmp (option, "no-gdb-backtrace"))
3176                 debug_options.no_gdb_backtrace = TRUE;
3177         else if (!strcmp (option, "suspend-on-sigsegv"))
3178                 debug_options.suspend_on_sigsegv = TRUE;
3179         else if (!strcmp (option, "suspend-on-exception"))
3180                 debug_options.suspend_on_exception = TRUE;
3181         else if (!strcmp (option, "suspend-on-unhandled"))
3182                 debug_options.suspend_on_unhandled = TRUE;
3183         else if (!strcmp (option, "dont-free-domains"))
3184                 mono_dont_free_domains = TRUE;
3185         else if (!strcmp (option, "dyn-runtime-invoke"))
3186                 debug_options.dyn_runtime_invoke = TRUE;
3187         else if (!strcmp (option, "gdb"))
3188                 debug_options.gdb = TRUE;
3189         else if (!strcmp (option, "explicit-null-checks"))
3190                 debug_options.explicit_null_checks = TRUE;
3191         else if (!strcmp (option, "gen-seq-points"))
3192                 debug_options.gen_sdb_seq_points = TRUE;
3193         else if (!strcmp (option, "gen-compact-seq-points"))
3194                 debug_options.gen_seq_points_compact_data = TRUE;
3195         else if (!strcmp (option, "single-imm-size"))
3196                 debug_options.single_imm_size = TRUE;
3197         else if (!strcmp (option, "init-stacks"))
3198                 debug_options.init_stacks = TRUE;
3199         else if (!strcmp (option, "casts"))
3200                 debug_options.better_cast_details = TRUE;
3201         else if (!strcmp (option, "soft-breakpoints"))
3202                 debug_options.soft_breakpoints = TRUE;
3203         else if (!strcmp (option, "check-pinvoke-callconv"))
3204                 debug_options.check_pinvoke_callconv = TRUE;
3205         else if (!strcmp (option, "arm-use-fallback-tls"))
3206                 debug_options.arm_use_fallback_tls = TRUE;
3207         else if (!strcmp (option, "debug-domain-unload"))
3208                 mono_enable_debug_domain_unload (TRUE);
3209         else if (!strcmp (option, "partial-sharing"))
3210                 mono_set_partial_sharing_supported (TRUE);
3211         else if (!strcmp (option, "align-small-structs"))
3212                 mono_align_small_structs = TRUE;
3213         else if (!strcmp (option, "native-debugger-break"))
3214                 debug_options.native_debugger_break = TRUE;
3215         else
3216                 return FALSE;
3217
3218         return TRUE;
3219 }
3220
3221 static void
3222 mini_parse_debug_options (void)
3223 {
3224         const char *options = g_getenv ("MONO_DEBUG");
3225         gchar **args, **ptr;
3226
3227         if (!options)
3228                 return;
3229
3230         args = g_strsplit (options, ",", -1);
3231
3232         for (ptr = args; ptr && *ptr; ptr++) {
3233                 const char *arg = *ptr;
3234
3235                 if (!mini_parse_debug_option (arg)) {
3236                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
3237                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'suspend-on-sigsegv', 'suspend-on-exception', 'suspend-on-unhandled', 'dont-free-domains', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'gen-seq-points', 'gen-compact-seq-points', 'single-imm-size', 'init-stacks', 'casts', 'soft-breakpoints', 'check-pinvoke-callconv', 'arm-use-fallback-tls', 'debug-domain-unload', 'partial-sharing', 'align-small-structs', 'native-debugger-break'\n");
3238                         exit (1);
3239                 }
3240         }
3241
3242         g_strfreev (args);
3243 }
3244
3245 MonoDebugOptions *
3246 mini_get_debug_options (void)
3247 {
3248         return &debug_options;
3249 }
3250
3251 static gpointer
3252 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
3253 {
3254 #if !defined(__ia64__) && (!defined(__ppc64__) && !defined(__powerpc64__) || _CALL_ELF == 2)
3255         return addr;
3256 #else
3257         gpointer* desc = NULL;
3258
3259         if ((desc = g_hash_table_lookup (domain->ftnptrs_hash, addr)))
3260                 return desc;
3261 #       ifdef __ia64__
3262         desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
3263
3264         desc [0] = addr;
3265         desc [1] = NULL;
3266 #       elif defined(__ppc64__) || defined(__powerpc64__)
3267
3268         desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
3269
3270         desc [0] = addr;
3271         desc [1] = NULL;
3272         desc [2] = NULL;
3273 #       endif
3274         g_hash_table_insert (domain->ftnptrs_hash, addr, desc);
3275         return desc;
3276 #endif
3277 }
3278
3279 static gpointer
3280 mini_get_addr_from_ftnptr (gpointer descr)
3281 {
3282 #if defined(__ia64__) || ((defined(__ppc64__) || defined(__powerpc64__)) && _CALL_ELF != 2)
3283         return *(gpointer*)descr;
3284 #else
3285         return descr;
3286 #endif
3287 }
3288
3289 static void
3290 register_jit_stats (void)
3291 {
3292         mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
3293         mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
3294         mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
3295         mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
3296         mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
3297         mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks);
3298         mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks);
3299         mono_counters_register ("Allocated vars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocate_var);
3300         mono_counters_register ("Code reallocs", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.code_reallocs);
3301         mono_counters_register ("Allocated code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_code_size);
3302         mono_counters_register ("Allocated seq points size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_seq_points_size);
3303         mono_counters_register ("Inlineable methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlineable_methods);
3304         mono_counters_register ("Inlined methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlined_methods);
3305         mono_counters_register ("Regvars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.regvars);
3306         mono_counters_register ("Locals stack size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.locals_stack_size);
3307         mono_counters_register ("Method cache lookups", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_lookups);
3308         mono_counters_register ("Compiled CIL code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.cil_code_size);
3309         mono_counters_register ("Native code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.native_code_size);
3310         mono_counters_register ("Aliases found", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_found);
3311         mono_counters_register ("Aliases eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_removed);
3312         mono_counters_register ("Aliased loads eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.loads_eliminated);
3313         mono_counters_register ("Aliased stores eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.stores_eliminated);
3314 }
3315
3316 static void runtime_invoke_info_free (gpointer value);
3317
3318 static gint
3319 class_method_pair_equal (gconstpointer ka, gconstpointer kb)
3320 {
3321         const MonoClassMethodPair *apair = (const MonoClassMethodPair *)ka;
3322         const MonoClassMethodPair *bpair = (const MonoClassMethodPair *)kb;
3323
3324         return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
3325 }
3326
3327 static guint
3328 class_method_pair_hash (gconstpointer data)
3329 {
3330         const MonoClassMethodPair *pair = (const MonoClassMethodPair *)data;
3331
3332         return (gsize)pair->klass ^ (gsize)pair->method;
3333 }
3334
3335 static void
3336 mini_create_jit_domain_info (MonoDomain *domain)
3337 {
3338         MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
3339
3340         info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3341         info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3342         info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
3343         info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3344         info->runtime_invoke_hash = mono_conc_hashtable_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
3345         info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, mono_seq_point_info_free);
3346         info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
3347         info->jump_target_hash = g_hash_table_new (NULL, NULL);
3348
3349         domain->runtime_info = info;
3350 }
3351
3352 static void
3353 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
3354 {
3355         MonoJumpList *jlist = (MonoJumpList *)value;
3356         g_slist_free (jlist->list);
3357 }
3358
3359 static void
3360 delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
3361 {
3362         GSList *list = (GSList *)value;
3363         g_slist_free (list);
3364 }
3365
3366 static void
3367 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
3368 {
3369         MonoJitDynamicMethodInfo *di = (MonoJitDynamicMethodInfo *)value;
3370         mono_code_manager_destroy (di->code_mp);
3371         g_free (di);
3372 }
3373
3374 static void
3375 runtime_invoke_info_free (gpointer value)
3376 {
3377         RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
3378
3379 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3380         if (info->dyn_call_info)
3381                 mono_arch_dyn_call_free (info->dyn_call_info);
3382 #endif
3383         g_free (info);
3384 }
3385
3386 static void
3387 mini_free_jit_domain_info (MonoDomain *domain)
3388 {
3389         MonoJitDomainInfo *info = domain_jit_info (domain);
3390
3391         g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
3392         g_hash_table_destroy (info->jump_target_hash);
3393         if (info->jump_target_got_slot_hash) {
3394                 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
3395                 g_hash_table_destroy (info->jump_target_got_slot_hash);
3396         }
3397         if (info->dynamic_code_hash) {
3398                 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
3399                 g_hash_table_destroy (info->dynamic_code_hash);
3400         }
3401         if (info->method_code_hash)
3402                 g_hash_table_destroy (info->method_code_hash);
3403         g_hash_table_destroy (info->jump_trampoline_hash);
3404         g_hash_table_destroy (info->jit_trampoline_hash);
3405         g_hash_table_destroy (info->delegate_trampoline_hash);
3406         if (info->static_rgctx_trampoline_hash)
3407                 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
3408         g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
3409         mono_conc_hashtable_destroy (info->runtime_invoke_hash);
3410         g_hash_table_destroy (info->seq_points);
3411         g_hash_table_destroy (info->arch_seq_points);
3412         if (info->agent_info)
3413                 mono_debugger_agent_free_domain_info (domain);
3414         if (info->gsharedvt_arg_tramp_hash)
3415                 g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
3416 #ifdef ENABLE_LLVM
3417         mono_llvm_free_domain_info (domain);
3418 #endif
3419
3420         g_free (domain->runtime_info);
3421         domain->runtime_info = NULL;
3422 }
3423
3424 #ifdef ENABLE_LLVM
3425 static gboolean
3426 llvm_init_inner (void)
3427 {
3428         if (!mono_llvm_load (NULL))
3429                 return FALSE;
3430
3431         mono_llvm_init ();
3432         return TRUE;
3433 }
3434 #endif
3435
3436 /*
3437  * mini_llvm_init:
3438  *
3439  *   Load and initialize LLVM support.
3440  * Return TRUE on success.
3441  */
3442 gboolean
3443 mini_llvm_init (void)
3444 {
3445 #ifdef ENABLE_LLVM
3446         static gboolean llvm_inited;
3447         static gboolean init_result;
3448
3449         mono_loader_lock_if_inited ();
3450         if (!llvm_inited) {
3451                 init_result = llvm_init_inner ();
3452                 llvm_inited = TRUE;
3453         }
3454         mono_loader_unlock_if_inited ();
3455         return init_result;
3456 #else
3457         return FALSE;
3458 #endif
3459 }
3460
3461 MonoDomain *
3462 mini_init (const char *filename, const char *runtime_version)
3463 {
3464         MonoDomain *domain;
3465         MonoRuntimeCallbacks callbacks;
3466         MonoThreadInfoRuntimeCallbacks ticallbacks;
3467
3468         MONO_VES_INIT_BEGIN ();
3469
3470         CHECKED_MONO_INIT ();
3471
3472 #if defined(__linux__) && !defined(__native_client__)
3473         if (access ("/proc/self/maps", F_OK) != 0) {
3474                 g_print ("Mono requires /proc to be mounted.\n");
3475                 exit (1);
3476         }
3477 #endif
3478
3479         mono_os_mutex_init_recursive (&jit_mutex);
3480
3481         mono_cross_helpers_run ();
3482
3483         mini_jit_init ();
3484
3485         /* Happens when using the embedding interface */
3486         if (!default_opt_set)
3487                 default_opt = mono_parse_default_optimizations (NULL);
3488
3489 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3490         if (mono_aot_only)
3491                 mono_set_generic_sharing_vt_supported (TRUE);
3492 #else
3493         if (mono_llvm_only)
3494                 mono_set_generic_sharing_vt_supported (TRUE);
3495 #endif
3496
3497 #ifdef MONO_HAVE_FAST_TLS
3498         MONO_FAST_TLS_INIT (mono_jit_tls);
3499         MONO_FAST_TLS_INIT (mono_lmf_addr);
3500 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
3501         MONO_FAST_TLS_INIT (mono_lmf);
3502 #endif
3503 #endif
3504
3505         mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
3506
3507         if (!global_codeman)
3508                 global_codeman = mono_code_manager_new ();
3509
3510         memset (&callbacks, 0, sizeof (callbacks));
3511         callbacks.create_ftnptr = mini_create_ftnptr;
3512         callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
3513         callbacks.get_runtime_build_info = mono_get_runtime_build_info;
3514         callbacks.set_cast_details = mono_set_cast_details;
3515         callbacks.debug_log = mono_debugger_agent_debug_log;
3516         callbacks.debug_log_is_enabled = mono_debugger_agent_debug_log_is_enabled;
3517         callbacks.tls_key_supported = mini_tls_key_supported;
3518         callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
3519         callbacks.get_imt_trampoline = mini_get_imt_trampoline;
3520         callbacks.imt_entry_inited = mini_imt_entry_inited;
3521         callbacks.init_delegate = mini_init_delegate;
3522 #define JIT_INVOKE_WORKS
3523 #ifdef JIT_INVOKE_WORKS
3524         callbacks.runtime_invoke = mono_jit_runtime_invoke;
3525 #endif
3526 #define JIT_TRAMPOLINES_WORK
3527 #ifdef JIT_TRAMPOLINES_WORK
3528         callbacks.compile_method = mono_jit_compile_method;
3529 #endif
3530
3531         mono_install_callbacks (&callbacks);
3532
3533         memset (&ticallbacks, 0, sizeof (ticallbacks));
3534         ticallbacks.setup_async_callback = mono_setup_async_callback;
3535         ticallbacks.thread_state_init_from_sigctx = mono_thread_state_init_from_sigctx;
3536         ticallbacks.thread_state_init_from_handle = mono_thread_state_init_from_handle;
3537         ticallbacks.thread_state_init = mono_thread_state_init;
3538
3539         mono_counters_init ();
3540
3541         mono_threads_runtime_init (&ticallbacks);
3542
3543         if (g_getenv ("MONO_DEBUG") != NULL)
3544                 mini_parse_debug_options ();
3545
3546         mono_code_manager_init ();
3547
3548         mono_hwcap_init ();
3549
3550         mono_arch_cpu_init ();
3551
3552         mono_arch_init ();
3553
3554         mono_unwind_init ();
3555
3556 #ifdef XDEBUG_ENABLED
3557         if (g_getenv ("MONO_XDEBUG")) {
3558                 const char *xdebug_opts = g_getenv ("MONO_XDEBUG");
3559                 mono_xdebug_init (xdebug_opts);
3560                 /* So methods for multiple domains don't have the same address */
3561                 mono_dont_free_domains = TRUE;
3562                 mono_using_xdebug = TRUE;
3563         } else if (mini_get_debug_options ()->gdb) {
3564                 mono_xdebug_init ((char*)"gdb");
3565                 mono_dont_free_domains = TRUE;
3566                 mono_using_xdebug = TRUE;
3567         }
3568 #endif
3569
3570 #ifdef ENABLE_LLVM
3571         if (mono_use_llvm) {
3572                 if (!mono_llvm_load (NULL)) {
3573                         mono_use_llvm = FALSE;
3574                         fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
3575                 }
3576         }
3577         if (mono_use_llvm)
3578                 mono_llvm_init ();
3579 #endif
3580
3581         mono_trampolines_init ();
3582
3583         mono_native_tls_alloc (&mono_jit_tls_id, NULL);
3584
3585         if (default_opt & MONO_OPT_AOT)
3586                 mono_aot_init ();
3587
3588         mono_debugger_agent_init ();
3589
3590 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3591         mono_set_generic_sharing_supported (TRUE);
3592 #endif
3593
3594 #ifndef MONO_CROSS_COMPILE
3595         mono_runtime_install_handlers ();
3596 #endif
3597         mono_threads_install_cleanup (mini_thread_cleanup);
3598
3599 #ifdef JIT_TRAMPOLINES_WORK
3600         mono_install_free_method (mono_jit_free_method);
3601         mono_install_trampoline (mono_create_jit_trampoline);
3602         mono_install_jump_trampoline (mono_create_jump_trampoline);
3603 #ifndef DISABLE_REMOTING
3604         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
3605 #endif
3606         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
3607         mono_install_create_domain_hook (mini_create_jit_domain_info);
3608         mono_install_free_domain_hook (mini_free_jit_domain_info);
3609 #endif
3610         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
3611         mono_install_get_class_from_name (mono_aot_get_class_from_name);
3612         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
3613
3614         if (debug_options.collect_pagefault_stats)
3615                 mono_aot_set_make_unreadable (TRUE);
3616
3617         if (runtime_version)
3618                 domain = mono_init_version (filename, runtime_version);
3619         else
3620                 domain = mono_init_from_assembly (filename, filename);
3621
3622         if (mono_aot_only) {
3623                 /* This helps catch code allocation requests */
3624                 mono_code_manager_set_read_only (domain->code_mp);
3625                 mono_marshal_use_aot_wrappers (TRUE);
3626         }
3627
3628         if (mono_llvm_only) {
3629                 mono_install_imt_thunk_builder (mono_llvmonly_get_imt_thunk);
3630                 mono_set_always_build_imt_thunks (TRUE);
3631         } else if (mono_aot_only) {
3632                 mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
3633         } else {
3634                 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
3635         }
3636
3637         /*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
3638         mono_arch_finish_init ();
3639
3640         mono_icall_init ();
3641
3642         /* This must come after mono_init () in the aot-only case */
3643         mono_exceptions_init ();
3644
3645         /* This should come after mono_init () too */
3646         mini_gc_init ();
3647
3648 #ifndef DISABLE_JIT
3649         mono_create_helper_signatures ();
3650 #endif
3651
3652         register_jit_stats ();
3653
3654 #define JIT_CALLS_WORK
3655 #ifdef JIT_CALLS_WORK
3656         /* Needs to be called here since register_jit_icall depends on it */
3657         mono_marshal_init ();
3658
3659         mono_arch_register_lowlevel_calls ();
3660
3661         register_icalls ();
3662
3663         mono_generic_sharing_init ();
3664 #endif
3665
3666 #ifdef MONO_ARCH_SIMD_INTRINSICS
3667         mono_simd_intrinsics_init ();
3668 #endif
3669
3670 #if MONO_SUPPORT_TASKLETS
3671         mono_tasklets_init ();
3672 #endif
3673
3674         register_trampolines (domain);
3675
3676         if (mono_compile_aot)
3677                 /*
3678                  * Avoid running managed code when AOT compiling, since the platform
3679                  * might only support aot-only execution.
3680                  */
3681                 mono_runtime_set_no_exec (TRUE);
3682
3683 #define JIT_RUNTIME_WORKS
3684 #ifdef JIT_RUNTIME_WORKS
3685         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
3686         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
3687         mono_thread_attach (domain);
3688 #endif
3689
3690         mono_profiler_runtime_initialized ();
3691
3692         MONO_VES_INIT_END ();
3693
3694         return domain;
3695 }
3696
3697 static void
3698 register_icalls (void)
3699 {
3700         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
3701                                 ves_icall_get_frame_info);
3702         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
3703                                 ves_icall_get_trace);
3704         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
3705                                 mono_runtime_install_handlers);
3706
3707 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
3708         mono_add_internal_call ("System.Diagnostics.Debugger::Mono_UnhandledException_internal",
3709                                 mono_debugger_agent_unhandled_exception);
3710 #endif
3711
3712         /*
3713          * It's important that we pass `TRUE` as the last argument here, as
3714          * it causes the JIT to omit a wrapper for these icalls. If the JIT
3715          * *did* emit a wrapper, we'd be looking at infinite recursion since
3716          * the wrapper would call the icall which would call the wrapper and
3717          * so on.
3718          */
3719         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", "void ptr", TRUE);
3720         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", "void ptr", TRUE);
3721
3722         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
3723         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
3724         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
3725         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr", TRUE);
3726         register_icall (mono_jit_set_domain, "mono_jit_set_domain", "void ptr", TRUE);
3727         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
3728
3729         register_icall (mono_llvm_throw_exception, "mono_llvm_throw_exception", "void object", TRUE);
3730         register_icall (mono_llvm_rethrow_exception, "mono_llvm_rethrow_exception", "void object", TRUE);
3731         register_icall (mono_llvm_resume_exception, "mono_llvm_resume_exception", "void", TRUE);
3732         register_icall (mono_llvm_match_exception, "mono_llvm_match_exception", "int ptr int int", TRUE);
3733         register_icall (mono_llvm_clear_exception, "mono_llvm_clear_exception", NULL, TRUE);
3734         register_icall (mono_llvm_load_exception, "mono_llvm_load_exception", "object", TRUE);
3735         register_icall (mono_llvm_throw_corlib_exception, "mono_llvm_throw_corlib_exception", "void int", TRUE);
3736 #if defined(ENABLE_LLVM) && !defined(MONO_LLVM_LOADED)
3737         register_icall (mono_llvm_set_unhandled_exception_handler, "mono_llvm_set_unhandled_exception_handler", NULL, TRUE);
3738
3739         // FIXME: This is broken
3740         register_icall (mono_debug_personality, "mono_debug_personality", "int int int ptr ptr ptr", TRUE);
3741 #endif
3742
3743         register_dyn_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
3744         register_dyn_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
3745         register_dyn_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", "void ptr", TRUE);
3746         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
3747         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "object", FALSE);
3748         register_icall (mono_thread_force_interruption_checkpoint_noraise, "mono_thread_force_interruption_checkpoint_noraise", "object", FALSE);
3749 #ifndef DISABLE_REMOTING
3750         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
3751         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
3752 #endif
3753
3754 #if defined(__native_client__) || defined(__native_client_codegen__)
3755         register_icall (mono_nacl_gc, "mono_nacl_gc", "void", FALSE);
3756 #endif
3757
3758         if (mono_threads_is_coop_enabled ())
3759                 register_icall (mono_threads_state_poll, "mono_threads_state_poll", "void", FALSE);
3760
3761 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
3762         register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, "mono_llmult", TRUE);
3763         register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, "mono_lldiv", FALSE);
3764         register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, "mono_lldiv_un", FALSE);
3765         register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, "mono_llrem", FALSE);
3766         register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, "mono_llrem_un", FALSE);
3767 #endif
3768 #if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
3769         register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, "mono_llmult_ovf_un", FALSE);
3770         register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, "mono_llmult_ovf", FALSE);
3771 #endif
3772
3773 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
3774         register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, "mono_lshl", TRUE);
3775         register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, "mono_lshr", TRUE);
3776         register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, "mono_lshr_un", TRUE);
3777 #endif
3778
3779 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
3780         register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, "mono_idiv", FALSE);
3781         register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, "mono_idiv_un", FALSE);
3782         register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, "mono_irem", FALSE);
3783         register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, "mono_irem_un", FALSE);
3784 #endif
3785
3786 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3787         register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, "mono_imul", TRUE);
3788 #endif
3789
3790 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
3791         register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, "mono_imul_ovf", FALSE);
3792         register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, "mono_imul_ovf_un", FALSE);
3793 #endif
3794
3795 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
3796         register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, "mono_fdiv", FALSE);
3797 #endif
3798
3799         register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, "mono_fconv_u8", FALSE);
3800         register_opcode_emulation (OP_RCONV_TO_U8, "__emul_rconv_to_u8", "ulong float", mono_rconv_u8, "mono_rconv_u8", FALSE);
3801         register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, "mono_fconv_u4", FALSE);
3802         register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, "mono_fconv_ovf_i8", FALSE);
3803         register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, "mono_fconv_ovf_u8", FALSE);
3804         register_opcode_emulation (OP_RCONV_TO_OVF_I8, "__emul_rconv_to_ovf_i8", "long float", mono_rconv_ovf_i8, "mono_rconv_ovf_i8", FALSE);
3805         register_opcode_emulation (OP_RCONV_TO_OVF_U8, "__emul_rconv_to_ovf_u8", "ulong float", mono_rconv_ovf_u8, "mono_rconv_ovf_u8", FALSE);
3806
3807
3808 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
3809         register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, "mono_fconv_i8", FALSE);
3810         register_opcode_emulation (OP_RCONV_TO_I8, "__emul_rconv_to_i8", "long float", mono_rconv_i8, "mono_rconv_i8", FALSE);
3811 #endif
3812
3813 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
3814         register_opcode_emulation (OP_ICONV_TO_R_UN, "__emul_iconv_to_r_un", "double int32", mono_conv_to_r8_un, "mono_conv_to_r8_un", FALSE);
3815 #endif
3816 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
3817         register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, "mono_lconv_to_r8", FALSE);
3818 #endif
3819 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
3820         register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, "mono_lconv_to_r4", FALSE);
3821 #endif
3822 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
3823         register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, "mono_lconv_to_r8_un", FALSE);
3824 #endif
3825 #ifdef MONO_ARCH_EMULATE_FREM
3826 #if defined(__default_codegen__)
3827         register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, "fmod", FALSE);
3828         register_opcode_emulation (OP_RREM, "__emul_rrem", "float float float", fmodf, "fmodf", FALSE);
3829 #elif defined(__native_client_codegen__)
3830         register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, "mono_fmod", FALSE);
3831 #endif
3832 #endif
3833
3834 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3835         if (mono_arch_is_soft_float ()) {
3836                 register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, "mono_fsub", FALSE);
3837                 register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, "mono_fadd", FALSE);
3838                 register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, "mono_fmul", FALSE);
3839                 register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, "mono_fneg", FALSE);
3840                 register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, "mono_conv_to_r8", FALSE);
3841                 register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, "mono_conv_to_r4", FALSE);
3842                 register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, "mono_fconv_r4", FALSE);
3843                 register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, "mono_fconv_i1", FALSE);
3844                 register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, "mono_fconv_i2", FALSE);
3845                 register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3846                 register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, "mono_fconv_u1", FALSE);
3847                 register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, "mono_fconv_u2", FALSE);
3848
3849 #if SIZEOF_VOID_P == 4
3850                 register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3851 #endif
3852
3853                 register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, "mono_fcmp_eq", FALSE);
3854                 register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, "mono_fcmp_lt", FALSE);
3855                 register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, "mono_fcmp_gt", FALSE);
3856                 register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, "mono_fcmp_le", FALSE);
3857                 register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, "mono_fcmp_ge", FALSE);
3858                 register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, "mono_fcmp_ne_un", FALSE);
3859                 register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, "mono_fcmp_lt_un", FALSE);
3860                 register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, "mono_fcmp_gt_un", FALSE);
3861                 register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, "mono_fcmp_le_un", FALSE);
3862                 register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, "mono_fcmp_ge_un", FALSE);
3863
3864                 register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, "mono_fceq", FALSE);
3865                 register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, "mono_fcgt", FALSE);
3866                 register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, "mono_fcgt_un", FALSE);
3867                 register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, "mono_fclt", FALSE);
3868                 register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, "mono_fclt_un", FALSE);
3869
3870                 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
3871                 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
3872                 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
3873                 register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
3874         }
3875 #endif
3876         register_icall (mono_ckfinite, "mono_ckfinite", "double double", FALSE);
3877
3878 #ifdef COMPRESSED_INTERFACE_BITMAP
3879         register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
3880 #endif
3881
3882 #if SIZEOF_REGISTER == 4
3883         register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, "mono_fconv_u4", TRUE);
3884 #else
3885         register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "ulong double", mono_fconv_u8, "mono_fconv_u8", TRUE);
3886 #endif
3887
3888         /* other jit icalls */
3889         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
3890         register_icall (mono_class_static_field_address , "mono_class_static_field_address",
3891                                  "ptr ptr ptr", FALSE);
3892         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
3893         register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
3894                 "ptr ptr ptr ptr", FALSE);
3895         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
3896         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
3897         register_icall (mono_helper_stelem_ref_check, "mono_helper_stelem_ref_check", "void object object", FALSE);
3898         register_icall (ves_icall_object_new, "ves_icall_object_new", "object ptr ptr", FALSE);
3899         register_icall (ves_icall_object_new_specific, "ves_icall_object_new_specific", "object ptr", FALSE);
3900         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
3901         register_icall (ves_icall_array_new_specific, "ves_icall_array_new_specific", "object ptr int32", FALSE);
3902         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
3903         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
3904         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
3905         register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
3906         register_icall (mono_helper_compile_generic_method, "mono_helper_compile_generic_method", "ptr object ptr ptr", FALSE);
3907         register_icall (mono_helper_ldstr, "mono_helper_ldstr", "object ptr int", FALSE);
3908         register_icall (mono_helper_ldstr_mscorlib, "mono_helper_ldstr_mscorlib", "object int", FALSE);
3909         register_icall (mono_helper_newobj_mscorlib, "mono_helper_newobj_mscorlib", "object int", FALSE);
3910         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
3911         register_icall (mono_object_castclass_unbox, "mono_object_castclass_unbox", "object object ptr", FALSE);
3912         register_icall (mono_break, "mono_break", NULL, TRUE);
3913         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
3914         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
3915         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
3916         register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
3917         register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
3918         register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
3919         register_icall (mono_array_new_4, "mono_array_new_4", "object ptr int int int int", FALSE);
3920         register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
3921         register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
3922         register_icall (mono_gsharedvt_constrained_call, "mono_gsharedvt_constrained_call", "object ptr ptr ptr ptr ptr", FALSE);
3923         register_icall (mono_gsharedvt_value_copy, "mono_gsharedvt_value_copy", "void ptr ptr ptr", TRUE);
3924
3925         register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
3926
3927         register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
3928         register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
3929         register_icall (mono_generic_class_init, "mono_generic_class_init", "void ptr", FALSE);
3930         register_icall (mono_fill_class_rgctx, "mono_class_fill_rgctx", "ptr ptr int", FALSE);
3931         register_icall (mono_fill_method_rgctx, "mono_method_fill_rgctx", "ptr ptr int", FALSE);
3932
3933         register_icall (mono_debugger_agent_user_break, "mono_debugger_agent_user_break", "void", FALSE);
3934
3935         register_icall (mono_aot_init_llvm_method, "mono_aot_init_llvm_method", "void ptr int", TRUE);
3936         register_icall (mono_aot_init_gshared_method_this, "mono_aot_init_gshared_method_this", "void ptr int object", TRUE);
3937         register_icall (mono_aot_init_gshared_method_mrgctx, "mono_aot_init_gshared_method_mrgctx", "void ptr int ptr", TRUE);
3938         register_icall (mono_aot_init_gshared_method_vtable, "mono_aot_init_gshared_method_vtable", "void ptr int ptr", TRUE);
3939
3940         register_icall_no_wrapper (mono_resolve_iface_call_gsharedvt, "mono_resolve_iface_call_gsharedvt", "ptr object int ptr ptr");
3941         register_icall_no_wrapper (mono_resolve_vcall_gsharedvt, "mono_resolve_vcall_gsharedvt", "ptr object int ptr ptr");
3942         register_icall_no_wrapper (mono_resolve_generic_virtual_call, "mono_resolve_generic_virtual_call", "ptr ptr int ptr");
3943         register_icall_no_wrapper (mono_resolve_generic_virtual_iface_call, "mono_resolve_generic_virtual_iface_call", "ptr ptr int ptr");
3944         /* This needs a wrapper so it can have a preserveall cconv */
3945         register_icall (mono_init_vtable_slot, "mono_init_vtable_slot", "ptr ptr int", FALSE);
3946         register_icall (mono_llvmonly_init_delegate, "mono_llvmonly_init_delegate", "void object", TRUE);
3947         register_icall (mono_llvmonly_init_delegate_virtual, "mono_llvmonly_init_delegate_virtual", "void object object ptr", TRUE);
3948         register_icall (mono_get_assembly_object, "mono_get_assembly_object", "object ptr", TRUE);
3949         register_icall (mono_get_method_object, "mono_get_method_object", "object ptr", TRUE);
3950
3951 #ifdef TARGET_IOS
3952         register_icall (pthread_getspecific, "pthread_getspecific", "ptr ptr", TRUE);
3953 #endif
3954 }
3955
3956 MonoJitStats mono_jit_stats = {0};
3957
3958 static void
3959 print_jit_stats (void)
3960 {
3961         if (mono_jit_stats.enabled) {
3962                 g_print ("Mono Jit statistics\n");
3963                 g_print ("Max code size ratio:    %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
3964                                  mono_jit_stats.max_ratio_method);
3965                 g_print ("Biggest method:         %ld (%s)\n", mono_jit_stats.biggest_method_size,
3966                                  mono_jit_stats.biggest_method);
3967
3968                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
3969                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
3970                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
3971                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
3972                 g_print ("Methods:                %ld\n", mono_stats.method_count);
3973                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
3974                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
3975                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
3976
3977                 g_print ("\nInitialized classes:    %ld\n", mono_stats.generic_class_count);
3978                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
3979                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
3980
3981                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
3982                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
3983                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
3984                 g_print ("Shared vtype generic methods: %ld\n", mono_stats.gsharedvt_methods);
3985
3986                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
3987                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
3988                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
3989                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
3990                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
3991                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
3992                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
3993                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
3994
3995                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
3996                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
3997                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
3998
3999                 g_free (mono_jit_stats.max_ratio_method);
4000                 mono_jit_stats.max_ratio_method = NULL;
4001                 g_free (mono_jit_stats.biggest_method);
4002                 mono_jit_stats.biggest_method = NULL;
4003         }
4004 }
4005
4006 void
4007 mini_cleanup (MonoDomain *domain)
4008 {
4009         mono_runtime_shutdown_stat_profiler ();
4010
4011 #ifndef DISABLE_COM
4012         cominterop_release_all_rcws ();
4013 #endif
4014
4015 #ifndef MONO_CROSS_COMPILE
4016         /*
4017          * mono_domain_finalize () needs to be called early since it needs the
4018          * execution engine still fully working (it may invoke managed finalizers).
4019          */
4020         mono_domain_finalize (domain, 2000);
4021 #endif
4022
4023         /* This accesses metadata so needs to be called before runtime shutdown */
4024         print_jit_stats ();
4025
4026         mono_profiler_shutdown ();
4027
4028 #ifndef MONO_CROSS_COMPILE
4029         mono_runtime_cleanup (domain);
4030 #endif
4031
4032         free_jit_tls_data ((MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id));
4033
4034         mono_icall_cleanup ();
4035
4036         mono_runtime_cleanup_handlers ();
4037
4038 #ifndef MONO_CROSS_COMPILE
4039         mono_domain_free (domain, TRUE);
4040 #endif
4041
4042 #ifdef ENABLE_LLVM
4043         if (mono_use_llvm)
4044                 mono_llvm_cleanup ();
4045 #endif
4046
4047         mono_aot_cleanup ();
4048
4049         mono_trampolines_cleanup ();
4050
4051         mono_unwind_cleanup ();
4052
4053         mono_code_manager_destroy (global_codeman);
4054         g_free (vtable_trampolines);
4055
4056         mini_jit_cleanup ();
4057
4058         mono_tramp_info_cleanup ();
4059
4060         mono_arch_cleanup ();
4061
4062         mono_generic_sharing_cleanup ();
4063
4064         mono_cleanup ();
4065
4066         mono_trace_cleanup ();
4067
4068         mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, stdout);
4069
4070         if (mono_inject_async_exc_method)
4071                 mono_method_desc_free (mono_inject_async_exc_method);
4072
4073         mono_native_tls_free (mono_jit_tls_id);
4074
4075         mono_os_mutex_destroy (&jit_mutex);
4076
4077         mono_code_manager_cleanup ();
4078
4079 #ifdef USE_JUMP_TABLES
4080         mono_jumptable_cleanup ();
4081 #endif
4082 }
4083
4084 void
4085 mono_set_defaults (int verbose_level, guint32 opts)
4086 {
4087         mini_verbose = verbose_level;
4088         mono_set_optimizations (opts);
4089 }
4090
4091 void
4092 mono_disable_optimizations (guint32 opts)
4093 {
4094         default_opt &= ~opts;
4095 }
4096
4097 void
4098 mono_set_optimizations (guint32 opts)
4099 {
4100         default_opt = opts;
4101         default_opt_set = TRUE;
4102 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
4103         mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
4104 #else
4105         if (mono_llvm_only)
4106                 mono_set_generic_sharing_vt_supported (TRUE);
4107 #endif
4108 }
4109
4110 void
4111 mono_set_verbose_level (guint32 level)
4112 {
4113         mini_verbose = level;
4114 }
4115
4116 /**
4117  * mono_get_runtime_build_info:
4118  *
4119  * Return the runtime version + build date in string format.
4120  * The returned string is owned by the caller. The returned string
4121  * format is "VERSION (FULL_VERSION BUILD_DATE)" and build date is optional.
4122  */
4123 char*
4124 mono_get_runtime_build_info (void)
4125 {
4126         if (mono_build_date)
4127                 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
4128         else
4129                 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
4130 }
4131
4132 static void
4133 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
4134 {
4135         GHashTable *assemblies = (GHashTable*)user_data;
4136         MonoImage *image = mono_assembly_get_image (ass);
4137         MonoMethod *method, *invoke;
4138         int i, count = 0;
4139
4140         if (g_hash_table_lookup (assemblies, ass))
4141                 return;
4142
4143         g_hash_table_insert (assemblies, ass, ass);
4144
4145         if (mini_verbose > 0)
4146                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
4147
4148         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
4149                 MonoError error;
4150
4151                 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, &error);
4152                 if (!method) {
4153                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
4154                         continue;
4155                 }
4156                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
4157                         continue;
4158                 if (method->is_generic || method->klass->generic_container)
4159                         continue;
4160
4161                 count++;
4162                 if (mini_verbose > 1) {
4163                         char * desc = mono_method_full_name (method, TRUE);
4164                         g_print ("Compiling %d %s\n", count, desc);
4165                         g_free (desc);
4166                 }
4167                 mono_compile_method (method);
4168                 if (strcmp (method->name, "Finalize") == 0) {
4169                         invoke = mono_marshal_get_runtime_invoke (method, FALSE);
4170                         mono_compile_method (invoke);
4171                 }
4172 #ifndef DISABLE_REMOTING
4173                 if (mono_class_is_marshalbyref (method->klass) && mono_method_signature (method)->hasthis) {
4174                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
4175                         mono_compile_method (invoke);
4176                 }
4177 #endif
4178         }
4179
4180         /* Load and precompile referenced assemblies as well */
4181         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
4182                 mono_assembly_load_reference (image, i);
4183                 if (image->references [i])
4184                         mono_precompile_assembly (image->references [i], assemblies);
4185         }
4186 }
4187
4188 void mono_precompile_assemblies ()
4189 {
4190         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
4191
4192         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
4193
4194         g_hash_table_destroy (assemblies);
4195 }
4196
4197 /*
4198  * Used by LLVM.
4199  * Have to export this for AOT.
4200  */
4201 void
4202 mono_personality (void)
4203 {
4204         /* Not used */
4205         g_assert_not_reached ();
4206 }
4207
4208 #ifdef USE_JUMP_TABLES
4209 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
4210
4211 typedef struct MonoJumpTableChunk {
4212         guint32 total;
4213         guint32 active;
4214         struct MonoJumpTableChunk *previous;
4215         /* gpointer entries[total]; */
4216 } MonoJumpTableChunk;
4217
4218 static MonoJumpTableChunk* g_jumptable;
4219 #define mono_jumptable_lock() mono_os_mutex_lock (&jumptable_mutex)
4220 #define mono_jumptable_unlock() mono_os_mutex_unlock (&jumptable_mutex)
4221 static mono_mutex_t jumptable_mutex;
4222
4223 static  MonoJumpTableChunk*
4224 mono_create_jumptable_chunk (guint32 max_entries)
4225 {
4226         guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
4227         MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
4228         chunk->total = max_entries;
4229         return chunk;
4230 }
4231
4232 void
4233 mono_jumptable_init (void)
4234 {
4235         if (g_jumptable == NULL) {
4236                 mono_os_mutex_init_recursive (&jumptable_mutex);
4237                 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
4238         }
4239 }
4240
4241 gpointer*
4242 mono_jumptable_add_entry (void)
4243 {
4244         return mono_jumptable_add_entries (1);
4245 }
4246
4247 gpointer*
4248 mono_jumptable_add_entries (guint32 entries)
4249 {
4250         guint32 index;
4251         gpointer *result;
4252
4253         mono_jumptable_init ();
4254         mono_jumptable_lock ();
4255         index = g_jumptable->active;
4256         if (index + entries >= g_jumptable->total) {
4257                 /*
4258                  * Grow jumptable, by adding one more chunk.
4259                  * We cannot realloc jumptable, as there could be pointers
4260                  * to existing jump table entries in the code, so instead
4261                  * we just add one more chunk.
4262                  */
4263                 guint32 max_entries = entries;
4264                 MonoJumpTableChunk *new_chunk;
4265
4266                 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
4267                         max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
4268                 new_chunk = mono_create_jumptable_chunk (max_entries);
4269                 /* Link old jumptable, so that we could free it up later. */
4270                 new_chunk->previous = g_jumptable;
4271                 g_jumptable = new_chunk;
4272                 index = 0;
4273         }
4274         g_jumptable->active = index + entries;
4275         result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
4276         mono_jumptable_unlock();
4277
4278         return result;
4279 }
4280
4281 void
4282 mono_jumptable_cleanup (void)
4283 {
4284         if (g_jumptable) {
4285                 MonoJumpTableChunk *current = g_jumptable, *prev;
4286                 while (current != NULL) {
4287                         prev = current->previous;
4288                         g_free (current);
4289                         current = prev;
4290                 }
4291                 g_jumptable = NULL;
4292                 mono_os_mutex_destroy (&jumptable_mutex);
4293         }
4294 }
4295
4296 gpointer*
4297 mono_jumptable_get_entry (guint8 *code_ptr)
4298 {
4299         return mono_arch_jumptable_entry_from_code (code_ptr);
4300 }
4301 #endif