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