[mini] Document mini_parse_debug_option.
[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                         vtable = mono_class_vtable (domain, method->klass);
1897                         g_assert (vtable);
1898                         tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
1899                         if (tmpEx) {
1900                                 *ex = tmpEx;
1901                                 return NULL;
1902                         }
1903                         return mono_create_ftnptr (target_domain, info->code_start);
1904                 }
1905         }
1906
1907 #ifdef MONO_USE_AOT_COMPILER
1908         if (opt & MONO_OPT_AOT) {
1909                 MonoDomain *domain = mono_domain_get ();
1910
1911                 mono_class_init (method->klass);
1912
1913                 if ((code = mono_aot_get_method (domain, method))) {
1914                         MonoVTable *vtable;
1915
1916                         /*
1917                          * In llvm-only mode, method might be a shared method, so we can't initialize its class.
1918                          * This is not a problem, since it will be initialized when the method is first
1919                          * called by init_method ().
1920                          */
1921                         if (!mono_llvm_only) {
1922                                 vtable = mono_class_vtable (domain, method->klass);
1923                                 g_assert (vtable);
1924                                 mono_runtime_class_init (vtable);
1925                         }
1926                 }
1927         }
1928 #endif
1929
1930         if (!code)
1931                 code = mono_jit_compile_method_inner (method, target_domain, opt, ex);
1932
1933         if (!code && mono_llvm_only) {
1934                 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
1935                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
1936
1937                         if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
1938                                 /*
1939                                  * These wrappers are only created for signatures which are in the program, but
1940                                  * sometimes we load methods too eagerly and have to create them even if they
1941                                  * will never be called.
1942                                  */
1943                                 return no_gsharedvt_in_wrapper;
1944                         }
1945                 }
1946
1947                 printf ("AOT method not found in llvmonly mode: %s\n", mono_method_full_name (method, 1));
1948                 g_assert_not_reached ();
1949         }
1950
1951         if (!code)
1952                 return NULL;
1953
1954         if (method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC) {
1955                 MonoDomain *d;
1956
1957                 /*
1958                  * SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
1959                  */
1960                 ji = mini_jit_info_table_find (mono_domain_get (), (char *)code, &d);
1961                 g_assert (ji);
1962         }
1963
1964         p = mono_create_ftnptr (target_domain, code);
1965
1966         if (callinfo) {
1967                 /*mono_register_jit_icall_wrapper takes the loader lock, so we take it on the outside. */
1968                 mono_loader_lock ();
1969                 mono_jit_lock ();
1970                 if (!callinfo->wrapper) {
1971                         callinfo->wrapper = p;
1972                         mono_register_jit_icall_wrapper (callinfo, p);
1973                 }
1974                 mono_jit_unlock ();
1975                 mono_loader_unlock ();
1976         }
1977
1978         return p;
1979 }
1980
1981 gpointer
1982 mono_jit_compile_method (MonoMethod *method)
1983 {
1984         MonoException *ex = NULL;
1985         gpointer code;
1986
1987         code = mono_jit_compile_method_with_opt (method, mono_get_optimizations_for_method (method, default_opt), &ex);
1988         if (!code) {
1989                 g_assert (ex);
1990                 mono_raise_exception (ex);
1991         }
1992
1993         return code;
1994 }
1995
1996 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
1997 static void
1998 invalidated_delegate_trampoline (char *desc)
1999 {
2000         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
2001                  "See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
2002                  desc);
2003 }
2004 #endif
2005
2006 /*
2007  * mono_jit_free_method:
2008  *
2009  *  Free all memory allocated by the JIT for METHOD.
2010  */
2011 static void
2012 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
2013 {
2014         MonoJitDynamicMethodInfo *ji;
2015         gboolean destroy = TRUE;
2016         GHashTableIter iter;
2017         MonoJumpList *jlist;
2018
2019         g_assert (method->dynamic);
2020
2021         mono_domain_lock (domain);
2022         ji = mono_dynamic_code_hash_lookup (domain, method);
2023         mono_domain_unlock (domain);
2024
2025         if (!ji)
2026                 return;
2027
2028         mono_debug_remove_method (method, domain);
2029
2030         mono_domain_lock (domain);
2031         g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
2032         mono_domain_jit_code_hash_lock (domain);
2033         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
2034         mono_domain_jit_code_hash_unlock (domain);
2035         g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
2036
2037         /* requires the domain lock - took above */
2038         mono_conc_hashtable_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
2039
2040         /* Remove jump targets in this method */
2041         g_hash_table_iter_init (&iter, domain_jit_info (domain)->jump_target_hash);
2042         while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
2043                 GSList *tmp, *remove;
2044
2045                 remove = NULL;
2046                 for (tmp = jlist->list; tmp; tmp = tmp->next) {
2047                         guint8 *ip = (guint8 *)tmp->data;
2048
2049                         if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
2050                                 remove = g_slist_prepend (remove, tmp);
2051                 }
2052                 for (tmp = remove; tmp; tmp = tmp->next) {
2053                         jlist->list = g_slist_delete_link ((GSList *)jlist->list, (GSList *)tmp->data);
2054                 }
2055                 g_slist_free (remove);
2056         }
2057
2058         mono_domain_unlock (domain);
2059
2060 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2061         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
2062                 /*
2063                  * Instead of freeing the code, change it to call an error routine
2064                  * so people can fix their code.
2065                  */
2066                 char *type = mono_type_full_name (&method->klass->byval_arg);
2067                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
2068
2069                 g_free (type);
2070                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
2071                 destroy = FALSE;
2072         }
2073 #endif
2074
2075         /*
2076          * This needs to be done before freeing code_mp, since the code address is the
2077          * key in the table, so if we free the code_mp first, another thread can grab the
2078          * same code address and replace our entry in the table.
2079          */
2080         mono_jit_info_table_remove (domain, ji->ji);
2081
2082         if (destroy)
2083                 mono_code_manager_destroy (ji->code_mp);
2084         g_free (ji);
2085 }
2086
2087 gpointer
2088 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
2089 {
2090         MonoDomain *target_domain;
2091         MonoJitInfo *info;
2092
2093         if (default_opt & MONO_OPT_SHARED)
2094                 target_domain = mono_get_root_domain ();
2095         else
2096                 target_domain = domain;
2097
2098         info = lookup_method (target_domain, method);
2099         if (info) {
2100                 /* We can't use a domain specific method in another domain */
2101                 if (! ((domain != target_domain) && !info->domain_neutral)) {
2102                         mono_jit_stats.methods_lookups++;
2103                         if (ji)
2104                                 *ji = info;
2105                         return info->code_start;
2106                 }
2107         }
2108
2109         if (ji)
2110                 *ji = NULL;
2111         return NULL;
2112 }
2113
2114 static guint32 bisect_opt = 0;
2115 static GHashTable *bisect_methods_hash = NULL;
2116
2117 void
2118 mono_set_bisect_methods (guint32 opt, const char *method_list_filename)
2119 {
2120         FILE *file;
2121         char method_name [2048];
2122
2123         bisect_opt = opt;
2124         bisect_methods_hash = g_hash_table_new (g_str_hash, g_str_equal);
2125         g_assert (bisect_methods_hash);
2126
2127         file = fopen (method_list_filename, "r");
2128         g_assert (file);
2129
2130         while (fgets (method_name, sizeof (method_name), file)) {
2131                 size_t len = strlen (method_name);
2132                 g_assert (len > 0);
2133                 g_assert (method_name [len - 1] == '\n');
2134                 method_name [len - 1] = 0;
2135                 g_hash_table_insert (bisect_methods_hash, g_strdup (method_name), GINT_TO_POINTER (1));
2136         }
2137         g_assert (feof (file));
2138 }
2139
2140 gboolean mono_do_single_method_regression = FALSE;
2141 guint32 mono_single_method_regression_opt = 0;
2142 MonoMethod *mono_current_single_method;
2143 GSList *mono_single_method_list;
2144 GHashTable *mono_single_method_hash;
2145
2146 guint32
2147 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt)
2148 {
2149         g_assert (method);
2150
2151         if (bisect_methods_hash) {
2152                 char *name = mono_method_full_name (method, TRUE);
2153                 void *res = g_hash_table_lookup (bisect_methods_hash, name);
2154                 g_free (name);
2155                 if (res)
2156                         return default_opt | bisect_opt;
2157         }
2158         if (!mono_do_single_method_regression)
2159                 return default_opt;
2160         if (!mono_current_single_method) {
2161                 if (!mono_single_method_hash)
2162                         mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
2163                 if (!g_hash_table_lookup (mono_single_method_hash, method)) {
2164                         g_hash_table_insert (mono_single_method_hash, method, method);
2165                         mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
2166                 }
2167                 return default_opt;
2168         }
2169         if (method == mono_current_single_method)
2170                 return mono_single_method_regression_opt;
2171         return default_opt;
2172 }
2173
2174 gpointer
2175 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
2176 {
2177         return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
2178 }
2179
2180 typedef struct {
2181         MonoMethod *method;
2182         gpointer compiled_method;
2183         gpointer runtime_invoke;
2184         MonoVTable *vtable;
2185         MonoDynCallInfo *dyn_call_info;
2186         MonoClass *ret_box_class;
2187         MonoMethodSignature *sig;
2188         gboolean gsharedvt_invoke;
2189         gpointer *wrapper_arg;
2190 } RuntimeInvokeInfo;
2191
2192 static RuntimeInvokeInfo*
2193 create_runtime_invoke_info (MonoDomain *domain, MonoMethod *method, gpointer compiled_method, gboolean callee_gsharedvt)
2194 {
2195         MonoMethod *invoke;
2196         RuntimeInvokeInfo *info;
2197
2198         info = g_new0 (RuntimeInvokeInfo, 1);
2199         info->compiled_method = compiled_method;
2200         info->sig = mono_method_signature (method);
2201
2202         invoke = mono_marshal_get_runtime_invoke (method, FALSE);
2203         info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
2204         g_assert (info->vtable);
2205
2206         MonoMethodSignature *sig = mono_method_signature (method);
2207         MonoType *ret_type;
2208
2209         /*
2210          * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
2211          * in full-aot mode, so we use a slower, but more generic wrapper if
2212          * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
2213          */
2214 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2215         if (!mono_llvm_only && (mono_aot_only || debug_options.dyn_runtime_invoke)) {
2216                 gboolean supported = TRUE;
2217                 int i;
2218
2219                 if (method->string_ctor)
2220                         sig = mono_marshal_get_string_ctor_signature (method);
2221
2222                 for (i = 0; i < sig->param_count; ++i) {
2223                         MonoType *t = sig->params [i];
2224
2225                         if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
2226                                 supported = FALSE;
2227                 }
2228
2229                 if (mono_class_is_contextbound (method->klass) || !info->compiled_method)
2230                         supported = FALSE;
2231
2232                 if (supported)
2233                         info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
2234         }
2235 #endif
2236
2237         ret_type = sig->ret;
2238         switch (ret_type->type) {
2239         case MONO_TYPE_VOID:
2240                 break;
2241         case MONO_TYPE_I1:
2242         case MONO_TYPE_U1:
2243         case MONO_TYPE_I2:
2244         case MONO_TYPE_U2:
2245         case MONO_TYPE_I4:
2246         case MONO_TYPE_U4:
2247         case MONO_TYPE_I:
2248         case MONO_TYPE_U:
2249         case MONO_TYPE_I8:
2250         case MONO_TYPE_U8:
2251         case MONO_TYPE_BOOLEAN:
2252         case MONO_TYPE_CHAR:
2253         case MONO_TYPE_R4:
2254         case MONO_TYPE_R8:
2255                 info->ret_box_class = mono_class_from_mono_type (ret_type);
2256                 break;
2257         case MONO_TYPE_PTR:
2258                 info->ret_box_class = mono_defaults.int_class;
2259                 break;
2260         case MONO_TYPE_STRING:
2261         case MONO_TYPE_CLASS:
2262         case MONO_TYPE_ARRAY:
2263         case MONO_TYPE_SZARRAY:
2264         case MONO_TYPE_OBJECT:
2265                 break;
2266         case MONO_TYPE_GENERICINST:
2267                 if (!MONO_TYPE_IS_REFERENCE (ret_type))
2268                         info->ret_box_class = mono_class_from_mono_type (ret_type);
2269                 break;
2270         case MONO_TYPE_VALUETYPE:
2271                 info->ret_box_class = mono_class_from_mono_type (ret_type);
2272                 break;
2273         default:
2274                 g_assert_not_reached ();
2275                 break;
2276         }
2277
2278         if (!info->dyn_call_info) {
2279                 if (mono_llvm_only) {
2280 #ifndef ENABLE_GSHAREDVT
2281                         g_assert_not_reached ();
2282 #endif
2283                         if (!callee_gsharedvt) {
2284                                 /* Invoke a gsharedvt out wrapper instead */
2285                                 MonoMethod *wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
2286                                 MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
2287
2288                                 info->gsharedvt_invoke = TRUE;
2289                                 info->wrapper_arg = g_malloc0 (2 * sizeof (gpointer));
2290                                 info->wrapper_arg [0] = info->compiled_method;
2291                                 info->wrapper_arg [1] = mono_method_needs_static_rgctx_invoke (method, TRUE) ? mini_method_get_rgctx (method) : NULL;
2292
2293                                 /* Pass has_rgctx == TRUE since the wrapper has an extra arg */
2294                                 invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
2295                                 g_free (wrapper_sig);
2296
2297                                 info->compiled_method = mono_jit_compile_method (wrapper);
2298                         } else {
2299                                 /* Gsharedvt methods can be invoked the same way */
2300                                 /* The out wrapper has the same signature as the compiled gsharedvt method */
2301                                 MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
2302
2303                                 info->gsharedvt_invoke = TRUE;
2304                                 info->wrapper_arg = mono_method_needs_static_rgctx_invoke (method, TRUE) ? mini_method_get_rgctx (method) : NULL;
2305
2306                                 invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
2307                                 g_free (wrapper_sig);
2308                         }
2309                 }
2310                 info->runtime_invoke = mono_jit_compile_method (invoke);
2311         }
2312
2313         return info;
2314 }
2315
2316 static MonoObject*
2317 mono_llvmonly_runtime_invoke (MonoMethod *method, RuntimeInvokeInfo *info, void *obj, void **params, MonoObject **exc)
2318 {
2319         MonoMethodSignature *sig = info->sig;
2320         MonoDomain *domain = mono_domain_get ();
2321         MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
2322         gpointer *args;
2323         gpointer retval_ptr;
2324         guint8 retval [256];
2325         gpointer *param_refs;
2326         int i, pindex;
2327
2328         g_assert (info->gsharedvt_invoke);
2329
2330         /*
2331          * Instead of invoking the method directly, we invoke a gsharedvt out wrapper.
2332          * The advantage of this is the gsharedvt out wrappers have a reduced set of
2333          * signatures, so we only have to generate runtime invoke wrappers for these
2334          * signatures.
2335          * This code also handles invocation of gsharedvt methods directly, no
2336          * out wrappers are used in that case.
2337          */
2338         args = (void **)g_alloca ((sig->param_count + sig->hasthis + 2) * sizeof (gpointer));
2339         param_refs = (gpointer*)g_alloca ((sig->param_count + sig->hasthis + 2) * sizeof (gpointer));
2340         pindex = 0;
2341         /*
2342          * The runtime invoke wrappers expects pointers to primitive types, so have to
2343          * use indirections.
2344          */
2345         if (sig->hasthis)
2346                 args [pindex ++] = &obj;
2347         if (sig->ret->type != MONO_TYPE_VOID) {
2348                 retval_ptr = (gpointer)&retval;
2349                 args [pindex ++] = &retval_ptr;
2350         }
2351         for (i = 0; i < sig->param_count; ++i) {
2352                 MonoType *t = sig->params [i];
2353
2354                 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
2355                         MonoClass *klass = mono_class_from_mono_type (t);
2356                         guint8 *nullable_buf;
2357                         int size;
2358
2359                         size = mono_class_value_size (klass, NULL);
2360                         nullable_buf = g_alloca (size);
2361                         g_assert (nullable_buf);
2362
2363                         /* The argument pointed to by params [i] is either a boxed vtype or null */
2364                         mono_nullable_init (nullable_buf, (MonoObject*)params [i], klass);
2365                         params [i] = nullable_buf;
2366                 }
2367
2368                 if (MONO_TYPE_IS_REFERENCE (t)) {
2369                         param_refs [i] = params [i];
2370                         params [i] = &(param_refs [i]);
2371                 }
2372                 args [pindex ++] = &params [i];
2373         }
2374         /* The gsharedvt out wrapper has an extra argument which contains the method to call */
2375         args [pindex ++] = &info->wrapper_arg;
2376
2377         runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
2378
2379         runtime_invoke (NULL, args, exc, info->compiled_method);
2380
2381         if (sig->ret->type != MONO_TYPE_VOID && info->ret_box_class)
2382                 return mono_value_box (domain, info->ret_box_class, retval);
2383         else
2384                 return *(MonoObject**)retval;
2385 }
2386
2387 /**
2388  * mono_jit_runtime_invoke:
2389  * @method: the method to invoke
2390  * @obj: this pointer
2391  * @params: array of parameter values.
2392  * @exc: used to catch exceptions objects
2393  */
2394 static MonoObject*
2395 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
2396 {
2397         MonoMethod *invoke, *callee;
2398         MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
2399         MonoDomain *domain = mono_domain_get ();
2400         MonoJitDomainInfo *domain_info;
2401         RuntimeInvokeInfo *info, *info2;
2402         MonoJitInfo *ji = NULL;
2403         gboolean callee_gsharedvt = FALSE;
2404
2405         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
2406                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
2407                 return NULL;
2408         }
2409
2410         domain_info = domain_jit_info (domain);
2411
2412         info = (RuntimeInvokeInfo *)mono_conc_hashtable_lookup (domain_info->runtime_invoke_hash, method);
2413
2414         if (!info) {
2415                 if (mono_security_core_clr_enabled ()) {
2416                         /*
2417                          * This might be redundant since mono_class_vtable () already does this,
2418                          * but keep it just in case for moonlight.
2419                          */
2420                         mono_class_setup_vtable (method->klass);
2421                         if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
2422                                 if (exc)
2423                                         *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
2424                                 else
2425                                         mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
2426                                 return NULL;
2427                         }
2428                 }
2429
2430                 gpointer compiled_method;
2431
2432                 callee = method;
2433                 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
2434                         (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
2435                         /*
2436                          * Array Get/Set/Address methods. The JIT implements them using inline code
2437                          * inside the runtime invoke wrappers, so no need to compile them.
2438                          */
2439                         if (mono_aot_only) {
2440                                 /*
2441                                  * Call a wrapper, since the runtime invoke wrapper was not generated.
2442                                  */
2443                                 MonoMethod *wrapper;
2444
2445                                 wrapper = mono_marshal_get_array_accessor_wrapper (method);
2446                                 invoke = mono_marshal_get_runtime_invoke (wrapper, FALSE);
2447                                 callee = wrapper;
2448                         } else {
2449                                 callee = NULL;
2450                         }
2451                 }
2452
2453                 if (callee) {
2454                         MonoException *jit_ex = NULL;
2455
2456                         compiled_method = mono_jit_compile_method_with_opt (callee, mono_get_optimizations_for_method (callee, default_opt), &jit_ex);
2457                         if (!compiled_method) {
2458                                 g_assert (jit_ex);
2459                                 if (exc) {
2460                                         *exc = (MonoObject*)jit_ex;
2461                                         return NULL;
2462                                 } else {
2463                                         mono_raise_exception (jit_ex);
2464                                         /* coverity[unreachable] */
2465                                 }
2466                         }
2467
2468                         if (mono_llvm_only) {
2469                                 ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
2470                                 callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
2471                         }
2472
2473                         if (!callee_gsharedvt)
2474                                 compiled_method = mini_add_method_trampoline (callee, compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
2475                 } else {
2476                         compiled_method = NULL;
2477                 }
2478
2479                 info = create_runtime_invoke_info (domain, method, compiled_method, callee_gsharedvt);
2480
2481                 mono_domain_lock (domain);
2482                 info2 = (RuntimeInvokeInfo *)mono_conc_hashtable_insert (domain_info->runtime_invoke_hash, method, info);
2483                 mono_domain_unlock (domain);
2484                 if (info2) {
2485                         g_free (info);
2486                         info = info2;
2487                 }
2488         }
2489
2490         /*
2491          * We need this here because mono_marshal_get_runtime_invoke can place
2492          * the helper method in System.Object and not the target class.
2493          */
2494         if (exc) {
2495                 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
2496                 if (*exc)
2497                         return NULL;
2498         } else {
2499                 mono_runtime_class_init (info->vtable);
2500         }
2501
2502         /* The wrappers expect this to be initialized to NULL */
2503         if (exc)
2504                 *exc = NULL;
2505
2506 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2507         if (info->dyn_call_info) {
2508                 MonoMethodSignature *sig = mono_method_signature (method);
2509                 gpointer *args;
2510                 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
2511                 int i, pindex;
2512                 guint8 buf [512];
2513                 guint8 retval [256];
2514
2515                 if (!dyn_runtime_invoke) {
2516                         invoke = mono_marshal_get_runtime_invoke_dynamic ();
2517                         dyn_runtime_invoke = (RuntimeInvokeDynamicFunction)mono_jit_compile_method (invoke);
2518                 }
2519
2520                 /* Convert the arguments to the format expected by start_dyn_call () */
2521                 args = (void **)g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
2522                 pindex = 0;
2523                 if (sig->hasthis)
2524                         args [pindex ++] = &obj;
2525                 for (i = 0; i < sig->param_count; ++i) {
2526                         MonoType *t = sig->params [i];
2527
2528                         if (t->byref) {
2529                                 args [pindex ++] = &params [i];
2530                         } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
2531                                 args [pindex ++] = &params [i];
2532                         } else {
2533                                 args [pindex ++] = params [i];
2534                         }
2535                 }
2536
2537                 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
2538
2539                 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
2540
2541                 dyn_runtime_invoke (buf, exc, info->compiled_method);
2542
2543                 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
2544
2545                 if (info->ret_box_class)
2546                         return mono_value_box (domain, info->ret_box_class, retval);
2547                 else
2548                         return *(MonoObject**)retval;
2549         }
2550 #endif
2551
2552         if (mono_llvm_only)
2553                 return mono_llvmonly_runtime_invoke (method, info, obj, params, exc);
2554
2555         runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
2556
2557         return runtime_invoke ((MonoObject *)obj, params, exc, info->compiled_method);
2558 }
2559
2560 typedef struct {
2561         MonoVTable *vtable;
2562         int slot;
2563 } IMTThunkInfo;
2564
2565 typedef gpointer (*IMTThunkFunc) (gpointer *arg, MonoMethod *imt_method);
2566
2567 /*
2568  * mini_llvmonly_initial_imt_thunk:
2569  *
2570  *  This function is called the first time a call is made through an IMT thunk.
2571  * It should have the same signature as the mono_llvmonly_imt_thunk_... functions.
2572  */
2573 static gpointer
2574 mini_llvmonly_initial_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2575 {
2576         IMTThunkInfo *info = (IMTThunkInfo*)arg;
2577         gpointer *imt;
2578         gpointer *ftndesc;
2579         IMTThunkFunc func;
2580
2581         mono_vtable_build_imt_slot (info->vtable, info->slot);
2582
2583         imt = (gpointer*)info->vtable;
2584         imt -= MONO_IMT_SIZE;
2585
2586         /* Return what the real IMT thunk returns */
2587         ftndesc = imt [info->slot];
2588         func = ftndesc [0];
2589
2590         if (func == (IMTThunkFunc)mini_llvmonly_initial_imt_thunk)
2591                 /* Happens when the imt slot contains only a generic virtual method */
2592                 return NULL;
2593         return func ((gpointer *)ftndesc [1], imt_method);
2594 }
2595
2596 /* This is called indirectly through an imt slot. */
2597 static gpointer
2598 mono_llvmonly_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2599 {
2600         int i = 0;
2601
2602         /* arg points to an array created in mono_llvmonly_get_imt_thunk () */
2603         while (arg [i] && arg [i] != imt_method)
2604                 i += 2;
2605         g_assert (arg [i]);
2606
2607         return arg [i + 1];
2608 }
2609
2610 /* Optimized versions of mono_llvmonly_imt_thunk () for different table sizes */
2611 static gpointer
2612 mono_llvmonly_imt_thunk_1 (gpointer *arg, MonoMethod *imt_method)
2613 {
2614         //g_assert (arg [0] == imt_method);
2615         return arg [1];
2616 }
2617
2618 static gpointer
2619 mono_llvmonly_imt_thunk_2 (gpointer *arg, MonoMethod *imt_method)
2620 {
2621         //g_assert (arg [0] == imt_method || arg [2] == imt_method);
2622         if (arg [0] == imt_method)
2623                 return arg [1];
2624         else
2625                 return arg [3];
2626 }
2627
2628 static gpointer
2629 mono_llvmonly_imt_thunk_3 (gpointer *arg, MonoMethod *imt_method)
2630 {
2631         //g_assert (arg [0] == imt_method || arg [2] == imt_method || arg [4] == imt_method);
2632         if (arg [0] == imt_method)
2633                 return arg [1];
2634         else if (arg [2] == imt_method)
2635                 return arg [3];
2636         else
2637                 return arg [5];
2638 }
2639
2640 /*
2641  * A version of the imt thunk used for generic virtual methods.
2642  * Unlikely a normal imt thunk, its possible that IMT_METHOD is not found
2643  * in the search table. The original JIT code had a 'fallback' trampoline it could
2644  * call, but we can't do that, so we just return NULL, and the compiled code
2645  * will handle it.
2646  */
2647 static gpointer
2648 mono_llvmonly_generic_virtual_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2649 {
2650         int i = 0;
2651
2652         while (arg [i] && arg [i] != imt_method)
2653                 i += 2;
2654         if (!arg [i])
2655                 return NULL;
2656
2657         return arg [i + 1];
2658 }
2659
2660 static gpointer
2661 mono_llvmonly_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
2662 {
2663         gpointer *buf;
2664         gpointer *res;
2665         int i, index, real_count;
2666         gboolean virtual_generic = FALSE;
2667
2668         /*
2669          * Create an array which is passed to the imt thunk functions.
2670          * The array contains MonoMethod-function descriptor pairs, terminated by a NULL entry.
2671          */
2672
2673         real_count = 0;
2674         for (i = 0; i < count; ++i) {
2675                 MonoIMTCheckItem *item = imt_entries [i];
2676
2677                 if (item->is_equals)
2678                         real_count ++;
2679                 if (item->has_target_code)
2680                         virtual_generic = TRUE;
2681         }
2682
2683         /*
2684          * Initialize all vtable entries reachable from this imt slot, so the compiled
2685          * code doesn't have to check it.
2686          */
2687         for (i = 0; i < count; ++i) {
2688                 MonoIMTCheckItem *item = imt_entries [i];
2689                 int vt_slot;
2690
2691                 if (!item->is_equals || item->has_target_code)
2692                         continue;
2693                 vt_slot = item->value.vtable_slot;
2694                 mono_init_vtable_slot (vtable, vt_slot);
2695         }
2696
2697         /* Save the entries into an array */
2698         buf = (void **)mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
2699         index = 0;
2700         for (i = 0; i < count; ++i) {
2701                 MonoIMTCheckItem *item = imt_entries [i];
2702
2703                 if (!item->is_equals)
2704                         continue;
2705
2706                 g_assert (item->key);
2707                 buf [(index * 2)] = item->key;
2708                 if (item->has_target_code)
2709                         buf [(index * 2) + 1] = item->value.target_code;
2710                 else
2711                         buf [(index * 2) + 1] = vtable->vtable [item->value.vtable_slot];
2712                 index ++;
2713         }
2714         buf [(index * 2)] = NULL;
2715         buf [(index * 2) + 1] = fail_tramp;
2716
2717         /*
2718          * Return a function descriptor for a C function with 'buf' as its argument.
2719          * It will by called by JITted code.
2720          */
2721         res = (void **)mono_domain_alloc (domain, 2 * sizeof (gpointer));
2722         switch (real_count) {
2723         case 1:
2724                 res [0] = mono_llvmonly_imt_thunk_1;
2725                 break;
2726         case 2:
2727                 res [0] = mono_llvmonly_imt_thunk_2;
2728                 break;
2729         case 3:
2730                 res [0] = mono_llvmonly_imt_thunk_3;
2731                 break;
2732         default:
2733                 res [0] = mono_llvmonly_imt_thunk;
2734                 break;
2735         }
2736         if (virtual_generic)
2737                 res [0] = mono_llvmonly_generic_virtual_imt_thunk;
2738         res [1] = buf;
2739
2740         return res;
2741 }
2742
2743 MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
2744 {
2745         MonoException *exc = NULL;
2746         MonoJitInfo *ji;
2747         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2748         MONO_SIG_HANDLER_GET_CONTEXT;
2749
2750         ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
2751
2752 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
2753         if (mono_arch_is_int_overflow (ctx, info))
2754                 /*
2755                  * The spec says this throws ArithmeticException, but MS throws the derived
2756                  * OverflowException.
2757                  */
2758                 exc = mono_get_exception_overflow ();
2759         else
2760                 exc = mono_get_exception_divide_by_zero ();
2761 #else
2762         exc = mono_get_exception_divide_by_zero ();
2763 #endif
2764
2765         if (!ji) {
2766                 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2767                         return;
2768
2769                 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2770                 if (mono_do_crash_chaining) {
2771                         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2772                         return;
2773                 }
2774         }
2775
2776         mono_arch_handle_exception (ctx, exc);
2777 }
2778
2779 MONO_SIG_HANDLER_FUNC (, mono_sigill_signal_handler)
2780 {
2781         MonoException *exc;
2782         MONO_SIG_HANDLER_GET_CONTEXT;
2783
2784         exc = mono_get_exception_execution_engine ("SIGILL");
2785
2786         mono_arch_handle_exception (ctx, exc);
2787 }
2788
2789 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
2790 #define HAVE_SIG_INFO
2791 #endif
2792
2793 MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
2794 {
2795         MonoJitInfo *ji;
2796         MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2797         gpointer fault_addr = NULL;
2798 #ifdef HAVE_SIG_INFO
2799         MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2800 #else
2801         void *info = NULL;
2802 #endif
2803         MONO_SIG_HANDLER_GET_CONTEXT;
2804
2805 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
2806         if (mono_arch_is_single_step_event (info, ctx)) {
2807                 mono_debugger_agent_single_step_event (ctx);
2808                 return;
2809         } else if (mono_arch_is_breakpoint_event (info, ctx)) {
2810                 mono_debugger_agent_breakpoint_hit (ctx);
2811                 return;
2812         }
2813 #endif
2814
2815 #if defined(HAVE_SIG_INFO)
2816 #if !defined(HOST_WIN32)
2817         fault_addr = info->si_addr;
2818         if (mono_aot_is_pagefault (info->si_addr)) {
2819                 mono_aot_handle_pagefault (info->si_addr);
2820                 return;
2821         }
2822 #endif
2823
2824         /* The thread might no be registered with the runtime */
2825         if (!mono_domain_get () || !jit_tls) {
2826                 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2827                         return;
2828                 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2829                 if (mono_do_crash_chaining) {
2830                         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2831                         return;
2832                 }
2833         }
2834 #endif
2835
2836         ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
2837
2838 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2839         if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
2840                 return;
2841
2842 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2843         /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
2844         fault_addr = info->si_addr;
2845         if (fault_addr == NULL) {
2846                 MonoContext mctx;
2847
2848                 mono_sigctx_to_monoctx (ctx, &mctx);
2849
2850                 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
2851         }
2852 #endif
2853
2854         if (jit_tls->stack_size &&
2855                 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
2856                 /*
2857                  * The hard-guard page has been hit: there is not much we can do anymore
2858                  * Print a hopefully clear message and abort.
2859                  */
2860                 mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
2861                 g_assert_not_reached ();
2862         } else {
2863                 /* The original handler might not like that it is executed on an altstack... */
2864                 if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2865                         return;
2866
2867                 mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
2868         }
2869 #else
2870
2871         if (!ji) {
2872                 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2873                         return;
2874
2875                 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2876
2877                 if (mono_do_crash_chaining) {
2878                         mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2879                         return;
2880                 }
2881         }
2882
2883         mono_arch_handle_exception (ctx, NULL);
2884 #endif
2885 }
2886
2887 MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
2888 {
2889         MonoException *exc;
2890         MONO_SIG_HANDLER_GET_CONTEXT;
2891
2892         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
2893
2894         mono_arch_handle_exception (ctx, exc);
2895 }
2896
2897 #ifndef DISABLE_REMOTING
2898 /* mono_jit_create_remoting_trampoline:
2899  * @method: pointer to the method info
2900  *
2901  * Creates a trampoline which calls the remoting functions. This
2902  * is used in the vtable of transparent proxies.
2903  *
2904  * Returns: a pointer to the newly created code
2905  */
2906 static gpointer
2907 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
2908 {
2909         MonoMethod *nm;
2910         guint8 *addr = NULL;
2911
2912         if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
2913                 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
2914                         domain, NULL);
2915         }
2916
2917         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
2918             (mono_method_signature (method)->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))) {
2919                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
2920                 addr = (guint8 *)mono_compile_method (nm);
2921         } else
2922         {
2923                 addr = (guint8 *)mono_compile_method (method);
2924         }
2925         return mono_get_addr_from_ftnptr (addr);
2926 }
2927 #endif
2928
2929 static void
2930 no_imt_trampoline (void)
2931 {
2932         g_assert_not_reached ();
2933 }
2934
2935 static void
2936 no_vcall_trampoline (void)
2937 {
2938         g_assert_not_reached ();
2939 }
2940
2941 static gpointer *vtable_trampolines;
2942 static int vtable_trampolines_size;
2943
2944 gpointer
2945 mini_get_vtable_trampoline (MonoVTable *vt, int slot_index)
2946 {
2947         int index = slot_index + MONO_IMT_SIZE;
2948
2949         if (mono_llvm_only) {
2950                 if (slot_index < 0) {
2951                         /* Initialize the IMT thunks to a 'trampoline' so the generated code doesn't have to initialize it */
2952                         // FIXME: Memory management
2953                         gpointer *ftndesc = g_malloc (2 * sizeof (gpointer));
2954                         IMTThunkInfo *info = g_new0 (IMTThunkInfo, 1);
2955                         info->vtable = vt;
2956                         info->slot = index;
2957                         ftndesc [0] = mini_llvmonly_initial_imt_thunk;
2958                         ftndesc [1] = info;
2959                         mono_memory_barrier ();
2960                         return ftndesc;
2961                 } else {
2962                         return NULL;
2963                 }
2964         }
2965
2966         g_assert (slot_index >= - MONO_IMT_SIZE);
2967         if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
2968                 mono_jit_lock ();
2969                 if (!vtable_trampolines || index >= vtable_trampolines_size) {
2970                         int new_size;
2971                         gpointer new_table;
2972
2973                         new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
2974                         while (new_size <= index)
2975                                 new_size *= 2;
2976                         new_table = g_new0 (gpointer, new_size);
2977
2978                         if (vtable_trampolines)
2979                                 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
2980                         g_free (vtable_trampolines);
2981                         mono_memory_barrier ();
2982                         vtable_trampolines = (void **)new_table;
2983                         vtable_trampolines_size = new_size;
2984                 }
2985                 mono_jit_unlock ();
2986         }
2987
2988         if (!vtable_trampolines [index])
2989                 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
2990         return vtable_trampolines [index];
2991 }
2992
2993 static gpointer
2994 mini_get_imt_trampoline (MonoVTable *vt, int slot_index)
2995 {
2996         return mini_get_vtable_trampoline (vt, slot_index - MONO_IMT_SIZE);
2997 }
2998
2999 static gboolean
3000 mini_imt_entry_inited (MonoVTable *vt, int imt_slot_index)
3001 {
3002         if (mono_llvm_only)
3003                 return FALSE;
3004
3005         gpointer *imt = (gpointer*)vt;
3006         imt -= MONO_IMT_SIZE;
3007
3008         return (imt [imt_slot_index] != mini_get_imt_trampoline (vt, imt_slot_index));
3009 }
3010
3011 gpointer
3012 mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
3013 {
3014         gboolean is_virtual_generic, is_interface, load_imt_reg;
3015         int offset, idx;
3016
3017         static guint8 **cache = NULL;
3018         static int cache_size = 0;
3019
3020         if (!method)
3021                 return NULL;
3022
3023         if (MONO_TYPE_ISSTRUCT (sig->ret))
3024                 return NULL;
3025
3026         is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
3027         is_interface = method->klass->flags & TYPE_ATTRIBUTE_INTERFACE ? TRUE : FALSE;
3028         load_imt_reg = is_virtual_generic || is_interface;
3029
3030         if (is_interface)
3031                 offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * SIZEOF_VOID_P;
3032         else
3033                 offset = G_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
3034
3035         idx = (offset / SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
3036         g_assert (idx >= 0);
3037
3038         /* Resize the cache to idx + 1 */
3039         if (cache_size < idx + 1) {
3040                 mono_jit_lock ();
3041                 if (cache_size < idx + 1) {
3042                         guint8 **new_cache;
3043                         int new_cache_size = idx + 1;
3044
3045                         new_cache = g_new0 (guint8*, new_cache_size);
3046                         if (cache)
3047                                 memcpy (new_cache, cache, cache_size * sizeof (guint8*));
3048                         g_free (cache);
3049
3050                         mono_memory_barrier ();
3051                         cache = new_cache;
3052                         cache_size = new_cache_size;
3053                 }
3054                 mono_jit_unlock ();
3055         }
3056
3057         if (cache [idx])
3058                 return cache [idx];
3059
3060         /* FIXME Support more cases */
3061         if (mono_aot_only) {
3062                 char tramp_name [256];
3063                 const char *imt = load_imt_reg ? "_imt" : "";
3064                 int ind = (load_imt_reg ? (-offset) : offset) / SIZEOF_VOID_P;
3065
3066                 sprintf (tramp_name, "delegate_virtual_invoke%s_%d", imt, ind);
3067                 cache [idx] = (guint8 *)mono_aot_get_trampoline (tramp_name);
3068                 g_assert (cache [idx]);
3069         } else {
3070                 cache [idx] = (guint8 *)mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
3071         }
3072         return cache [idx];
3073 }
3074
3075 /**
3076  * mini_parse_debug_option:
3077  * @option: The option to parse.
3078  *
3079  * Parses debug options for the mono runtime. The options are the same as for
3080  * the MONO_DEBUG environment variable.
3081  *
3082  */
3083 gboolean
3084 mini_parse_debug_option (const char *option)
3085 {
3086         if (!strcmp (option, "handle-sigint"))
3087                 debug_options.handle_sigint = TRUE;
3088         else if (!strcmp (option, "keep-delegates"))
3089                 debug_options.keep_delegates = TRUE;
3090         else if (!strcmp (option, "reverse-pinvoke-exceptions"))
3091                 debug_options.reverse_pinvoke_exceptions = TRUE;
3092         else if (!strcmp (option, "collect-pagefault-stats"))
3093                 debug_options.collect_pagefault_stats = TRUE;
3094         else if (!strcmp (option, "break-on-unverified"))
3095                 debug_options.break_on_unverified = TRUE;
3096         else if (!strcmp (option, "no-gdb-backtrace"))
3097                 debug_options.no_gdb_backtrace = TRUE;
3098         else if (!strcmp (option, "suspend-on-sigsegv"))
3099                 debug_options.suspend_on_sigsegv = TRUE;
3100         else if (!strcmp (option, "suspend-on-exception"))
3101                 debug_options.suspend_on_exception = TRUE;
3102         else if (!strcmp (option, "suspend-on-unhandled"))
3103                 debug_options.suspend_on_unhandled = TRUE;
3104         else if (!strcmp (option, "dont-free-domains"))
3105                 mono_dont_free_domains = TRUE;
3106         else if (!strcmp (option, "dyn-runtime-invoke"))
3107                 debug_options.dyn_runtime_invoke = TRUE;
3108         else if (!strcmp (option, "gdb"))
3109                 debug_options.gdb = TRUE;
3110         else if (!strcmp (option, "explicit-null-checks"))
3111                 debug_options.explicit_null_checks = TRUE;
3112         else if (!strcmp (option, "gen-seq-points"))
3113                 debug_options.gen_sdb_seq_points = TRUE;
3114         else if (!strcmp (option, "gen-compact-seq-points"))
3115                 debug_options.gen_seq_points_compact_data = TRUE;
3116         else if (!strcmp (option, "single-imm-size"))
3117                 debug_options.single_imm_size = TRUE;
3118         else if (!strcmp (option, "init-stacks"))
3119                 debug_options.init_stacks = TRUE;
3120         else if (!strcmp (option, "casts"))
3121                 debug_options.better_cast_details = TRUE;
3122         else if (!strcmp (option, "soft-breakpoints"))
3123                 debug_options.soft_breakpoints = TRUE;
3124         else if (!strcmp (option, "check-pinvoke-callconv"))
3125                 debug_options.check_pinvoke_callconv = TRUE;
3126         else if (!strcmp (option, "arm-use-fallback-tls"))
3127                 debug_options.arm_use_fallback_tls = TRUE;
3128         else if (!strcmp (option, "debug-domain-unload"))
3129                 mono_enable_debug_domain_unload (TRUE);
3130         else if (!strcmp (option, "partial-sharing"))
3131                 mono_set_partial_sharing_supported (TRUE);
3132         else if (!strcmp (option, "align-small-structs"))
3133                 mono_align_small_structs = TRUE;
3134         else if (!strcmp (option, "native-debugger-break"))
3135                 debug_options.native_debugger_break = TRUE;
3136         else
3137                 return FALSE;
3138
3139         return TRUE;
3140 }
3141
3142 static void
3143 mini_parse_debug_options (void)
3144 {
3145         const char *options = g_getenv ("MONO_DEBUG");
3146         gchar **args, **ptr;
3147
3148         if (!options)
3149                 return;
3150
3151         args = g_strsplit (options, ",", -1);
3152
3153         for (ptr = args; ptr && *ptr; ptr++) {
3154                 const char *arg = *ptr;
3155
3156                 if (!mini_parse_debug_option (arg)) {
3157                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
3158                         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");
3159                         exit (1);
3160                 }
3161         }
3162
3163         g_strfreev (args);
3164 }
3165
3166 MonoDebugOptions *
3167 mini_get_debug_options (void)
3168 {
3169         return &debug_options;
3170 }
3171
3172 static gpointer
3173 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
3174 {
3175 #if !defined(__ia64__) && (!defined(__ppc64__) && !defined(__powerpc64__) || _CALL_ELF == 2)
3176         return addr;
3177 #else
3178         gpointer* desc = NULL;
3179
3180         if ((desc = g_hash_table_lookup (domain->ftnptrs_hash, addr)))
3181                 return desc;
3182 #       ifdef __ia64__
3183         desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
3184
3185         desc [0] = addr;
3186         desc [1] = NULL;
3187 #       elif defined(__ppc64__) || defined(__powerpc64__)
3188
3189         desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
3190
3191         desc [0] = addr;
3192         desc [1] = NULL;
3193         desc [2] = NULL;
3194 #       endif
3195         g_hash_table_insert (domain->ftnptrs_hash, addr, desc);
3196         return desc;
3197 #endif
3198 }
3199
3200 static gpointer
3201 mini_get_addr_from_ftnptr (gpointer descr)
3202 {
3203 #if defined(__ia64__) || ((defined(__ppc64__) || defined(__powerpc64__)) && _CALL_ELF != 2)
3204         return *(gpointer*)descr;
3205 #else
3206         return descr;
3207 #endif
3208 }
3209
3210 static void
3211 register_jit_stats (void)
3212 {
3213         mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
3214         mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
3215         mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
3216         mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
3217         mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
3218         mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks);
3219         mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks);
3220         mono_counters_register ("Allocated vars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocate_var);
3221         mono_counters_register ("Code reallocs", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.code_reallocs);
3222         mono_counters_register ("Allocated code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_code_size);
3223         mono_counters_register ("Allocated seq points size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_seq_points_size);
3224         mono_counters_register ("Inlineable methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlineable_methods);
3225         mono_counters_register ("Inlined methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlined_methods);
3226         mono_counters_register ("Regvars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.regvars);
3227         mono_counters_register ("Locals stack size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.locals_stack_size);
3228         mono_counters_register ("Method cache lookups", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_lookups);
3229         mono_counters_register ("Compiled CIL code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.cil_code_size);
3230         mono_counters_register ("Native code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.native_code_size);
3231         mono_counters_register ("Aliases found", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_found);
3232         mono_counters_register ("Aliases eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_removed);
3233         mono_counters_register ("Aliased loads eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.loads_eliminated);
3234         mono_counters_register ("Aliased stores eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.stores_eliminated);
3235 }
3236
3237 static void runtime_invoke_info_free (gpointer value);
3238
3239 static gint
3240 class_method_pair_equal (gconstpointer ka, gconstpointer kb)
3241 {
3242         const MonoClassMethodPair *apair = (const MonoClassMethodPair *)ka;
3243         const MonoClassMethodPair *bpair = (const MonoClassMethodPair *)kb;
3244
3245         return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
3246 }
3247
3248 static guint
3249 class_method_pair_hash (gconstpointer data)
3250 {
3251         const MonoClassMethodPair *pair = (const MonoClassMethodPair *)data;
3252
3253         return (gsize)pair->klass ^ (gsize)pair->method;
3254 }
3255
3256 static void
3257 mini_create_jit_domain_info (MonoDomain *domain)
3258 {
3259         MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
3260
3261         info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3262         info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3263         info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
3264         info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3265         info->runtime_invoke_hash = mono_conc_hashtable_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
3266         info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, mono_seq_point_info_free);
3267         info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
3268         info->jump_target_hash = g_hash_table_new (NULL, NULL);
3269
3270         domain->runtime_info = info;
3271 }
3272
3273 static void
3274 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
3275 {
3276         MonoJumpList *jlist = (MonoJumpList *)value;
3277         g_slist_free (jlist->list);
3278 }
3279
3280 static void
3281 delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
3282 {
3283         GSList *list = (GSList *)value;
3284         g_slist_free (list);
3285 }
3286
3287 static void
3288 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
3289 {
3290         MonoJitDynamicMethodInfo *di = (MonoJitDynamicMethodInfo *)value;
3291         mono_code_manager_destroy (di->code_mp);
3292         g_free (di);
3293 }
3294
3295 static void
3296 runtime_invoke_info_free (gpointer value)
3297 {
3298         RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
3299
3300 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3301         if (info->dyn_call_info)
3302                 mono_arch_dyn_call_free (info->dyn_call_info);
3303 #endif
3304         g_free (info);
3305 }
3306
3307 static void
3308 mini_free_jit_domain_info (MonoDomain *domain)
3309 {
3310         MonoJitDomainInfo *info = domain_jit_info (domain);
3311
3312         g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
3313         g_hash_table_destroy (info->jump_target_hash);
3314         if (info->jump_target_got_slot_hash) {
3315                 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
3316                 g_hash_table_destroy (info->jump_target_got_slot_hash);
3317         }
3318         if (info->dynamic_code_hash) {
3319                 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
3320                 g_hash_table_destroy (info->dynamic_code_hash);
3321         }
3322         if (info->method_code_hash)
3323                 g_hash_table_destroy (info->method_code_hash);
3324         g_hash_table_destroy (info->jump_trampoline_hash);
3325         g_hash_table_destroy (info->jit_trampoline_hash);
3326         g_hash_table_destroy (info->delegate_trampoline_hash);
3327         if (info->static_rgctx_trampoline_hash)
3328                 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
3329         g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
3330         mono_conc_hashtable_destroy (info->runtime_invoke_hash);
3331         g_hash_table_destroy (info->seq_points);
3332         g_hash_table_destroy (info->arch_seq_points);
3333         if (info->agent_info)
3334                 mono_debugger_agent_free_domain_info (domain);
3335         if (info->gsharedvt_arg_tramp_hash)
3336                 g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
3337 #ifdef ENABLE_LLVM
3338         mono_llvm_free_domain_info (domain);
3339 #endif
3340
3341         g_free (domain->runtime_info);
3342         domain->runtime_info = NULL;
3343 }
3344
3345 #ifdef ENABLE_LLVM
3346 static gboolean
3347 llvm_init_inner (void)
3348 {
3349         if (!mono_llvm_load (NULL))
3350                 return FALSE;
3351
3352         mono_llvm_init ();
3353         return TRUE;
3354 }
3355 #endif
3356
3357 /*
3358  * mini_llvm_init:
3359  *
3360  *   Load and initialize LLVM support.
3361  * Return TRUE on success.
3362  */
3363 gboolean
3364 mini_llvm_init (void)
3365 {
3366 #ifdef ENABLE_LLVM
3367         static gboolean llvm_inited;
3368         static gboolean init_result;
3369
3370         mono_loader_lock_if_inited ();
3371         if (!llvm_inited) {
3372                 init_result = llvm_init_inner ();
3373                 llvm_inited = TRUE;
3374         }
3375         mono_loader_unlock_if_inited ();
3376         return init_result;
3377 #else
3378         return FALSE;
3379 #endif
3380 }
3381
3382 MonoDomain *
3383 mini_init (const char *filename, const char *runtime_version)
3384 {
3385         MonoDomain *domain;
3386         MonoRuntimeCallbacks callbacks;
3387         MonoThreadInfoRuntimeCallbacks ticallbacks;
3388
3389         MONO_VES_INIT_BEGIN ();
3390
3391         CHECKED_MONO_INIT ();
3392
3393 #if defined(__linux__) && !defined(__native_client__)
3394         if (access ("/proc/self/maps", F_OK) != 0) {
3395                 g_print ("Mono requires /proc to be mounted.\n");
3396                 exit (1);
3397         }
3398 #endif
3399
3400         mono_os_mutex_init_recursive (&jit_mutex);
3401
3402         mono_cross_helpers_run ();
3403
3404         mini_jit_init ();
3405
3406         /* Happens when using the embedding interface */
3407         if (!default_opt_set)
3408                 default_opt = mono_parse_default_optimizations (NULL);
3409
3410 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3411         if (mono_aot_only)
3412                 mono_set_generic_sharing_vt_supported (TRUE);
3413 #else
3414         if (mono_llvm_only)
3415                 mono_set_generic_sharing_vt_supported (TRUE);
3416 #endif
3417
3418 #ifdef MONO_HAVE_FAST_TLS
3419         MONO_FAST_TLS_INIT (mono_jit_tls);
3420         MONO_FAST_TLS_INIT (mono_lmf_addr);
3421 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
3422         MONO_FAST_TLS_INIT (mono_lmf);
3423 #endif
3424 #endif
3425
3426         mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
3427
3428         if (!global_codeman)
3429                 global_codeman = mono_code_manager_new ();
3430
3431         memset (&callbacks, 0, sizeof (callbacks));
3432         callbacks.create_ftnptr = mini_create_ftnptr;
3433         callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
3434         callbacks.get_runtime_build_info = mono_get_runtime_build_info;
3435         callbacks.set_cast_details = mono_set_cast_details;
3436         callbacks.debug_log = mono_debugger_agent_debug_log;
3437         callbacks.debug_log_is_enabled = mono_debugger_agent_debug_log_is_enabled;
3438         callbacks.tls_key_supported = mini_tls_key_supported;
3439
3440         callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
3441         callbacks.get_imt_trampoline = mini_get_imt_trampoline;
3442         callbacks.imt_entry_inited = mini_imt_entry_inited;
3443
3444         mono_install_callbacks (&callbacks);
3445
3446         memset (&ticallbacks, 0, sizeof (ticallbacks));
3447         ticallbacks.setup_async_callback = mono_setup_async_callback;
3448         ticallbacks.thread_state_init_from_sigctx = mono_thread_state_init_from_sigctx;
3449         ticallbacks.thread_state_init_from_handle = mono_thread_state_init_from_handle;
3450         ticallbacks.thread_state_init = mono_thread_state_init;
3451
3452         mono_counters_init ();
3453
3454         mono_threads_runtime_init (&ticallbacks);
3455
3456         if (g_getenv ("MONO_DEBUG") != NULL)
3457                 mini_parse_debug_options ();
3458
3459         mono_code_manager_init ();
3460
3461         mono_hwcap_init ();
3462
3463         mono_arch_cpu_init ();
3464
3465         mono_arch_init ();
3466
3467         mono_unwind_init ();
3468
3469 #ifdef XDEBUG_ENABLED
3470         if (g_getenv ("MONO_XDEBUG")) {
3471                 const char *xdebug_opts = g_getenv ("MONO_XDEBUG");
3472                 mono_xdebug_init (xdebug_opts);
3473                 /* So methods for multiple domains don't have the same address */
3474                 mono_dont_free_domains = TRUE;
3475                 mono_using_xdebug = TRUE;
3476         } else if (mini_get_debug_options ()->gdb) {
3477                 mono_xdebug_init ((char*)"gdb");
3478                 mono_dont_free_domains = TRUE;
3479                 mono_using_xdebug = TRUE;
3480         }
3481 #endif
3482
3483 #ifdef ENABLE_LLVM
3484         if (mono_use_llvm) {
3485                 if (!mono_llvm_load (NULL)) {
3486                         mono_use_llvm = FALSE;
3487                         fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
3488                 }
3489         }
3490         if (mono_use_llvm)
3491                 mono_llvm_init ();
3492 #endif
3493
3494         mono_trampolines_init ();
3495
3496         mono_native_tls_alloc (&mono_jit_tls_id, NULL);
3497
3498         if (default_opt & MONO_OPT_AOT)
3499                 mono_aot_init ();
3500
3501         mono_debugger_agent_init ();
3502
3503 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3504         mono_set_generic_sharing_supported (TRUE);
3505 #endif
3506
3507 #ifndef MONO_CROSS_COMPILE
3508         mono_runtime_install_handlers ();
3509 #endif
3510         mono_threads_install_cleanup (mini_thread_cleanup);
3511
3512 #define JIT_TRAMPOLINES_WORK
3513 #ifdef JIT_TRAMPOLINES_WORK
3514         mono_install_compile_method (mono_jit_compile_method);
3515         mono_install_free_method (mono_jit_free_method);
3516         mono_install_trampoline (mono_create_jit_trampoline);
3517         mono_install_jump_trampoline (mono_create_jump_trampoline);
3518 #ifndef DISABLE_REMOTING
3519         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
3520 #endif
3521         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
3522         mono_install_create_domain_hook (mini_create_jit_domain_info);
3523         mono_install_free_domain_hook (mini_free_jit_domain_info);
3524 #endif
3525 #define JIT_INVOKE_WORKS
3526 #ifdef JIT_INVOKE_WORKS
3527         mono_install_runtime_invoke (mono_jit_runtime_invoke);
3528 #endif
3529         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
3530         mono_install_get_class_from_name (mono_aot_get_class_from_name);
3531         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
3532
3533         if (debug_options.collect_pagefault_stats)
3534                 mono_aot_set_make_unreadable (TRUE);
3535
3536         if (runtime_version)
3537                 domain = mono_init_version (filename, runtime_version);
3538         else
3539                 domain = mono_init_from_assembly (filename, filename);
3540
3541         if (mono_aot_only) {
3542                 /* This helps catch code allocation requests */
3543                 mono_code_manager_set_read_only (domain->code_mp);
3544                 mono_marshal_use_aot_wrappers (TRUE);
3545         }
3546
3547         if (mono_llvm_only) {
3548                 mono_install_imt_thunk_builder (mono_llvmonly_get_imt_thunk);
3549                 mono_set_always_build_imt_thunks (TRUE);
3550         } else if (mono_aot_only) {
3551                 mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
3552         } else {
3553                 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
3554         }
3555
3556         /*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
3557         mono_arch_finish_init ();
3558
3559         mono_icall_init ();
3560
3561         /* This must come after mono_init () in the aot-only case */
3562         mono_exceptions_init ();
3563
3564         /* This should come after mono_init () too */
3565         mini_gc_init ();
3566
3567 #ifndef DISABLE_JIT
3568         mono_create_helper_signatures ();
3569 #endif
3570
3571         register_jit_stats ();
3572
3573 #define JIT_CALLS_WORK
3574 #ifdef JIT_CALLS_WORK
3575         /* Needs to be called here since register_jit_icall depends on it */
3576         mono_marshal_init ();
3577
3578         mono_arch_register_lowlevel_calls ();
3579
3580         register_icalls ();
3581
3582         mono_generic_sharing_init ();
3583 #endif
3584
3585 #ifdef MONO_ARCH_SIMD_INTRINSICS
3586         mono_simd_intrinsics_init ();
3587 #endif
3588
3589 #if MONO_SUPPORT_TASKLETS
3590         mono_tasklets_init ();
3591 #endif
3592
3593         register_trampolines (domain);
3594
3595         if (mono_compile_aot)
3596                 /*
3597                  * Avoid running managed code when AOT compiling, since the platform
3598                  * might only support aot-only execution.
3599                  */
3600                 mono_runtime_set_no_exec (TRUE);
3601
3602 #define JIT_RUNTIME_WORKS
3603 #ifdef JIT_RUNTIME_WORKS
3604         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
3605         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
3606         mono_thread_attach (domain);
3607 #endif
3608
3609         mono_profiler_runtime_initialized ();
3610
3611         MONO_VES_INIT_END ();
3612
3613         return domain;
3614 }
3615
3616 static void
3617 register_icalls (void)
3618 {
3619         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
3620                                 ves_icall_get_frame_info);
3621         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
3622                                 ves_icall_get_trace);
3623         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
3624                                 mono_runtime_install_handlers);
3625
3626 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
3627         mono_add_internal_call ("System.Diagnostics.Debugger::Mono_UnhandledException_internal",
3628                                 mono_debugger_agent_unhandled_exception);
3629 #endif
3630
3631         /*
3632          * It's important that we pass `TRUE` as the last argument here, as
3633          * it causes the JIT to omit a wrapper for these icalls. If the JIT
3634          * *did* emit a wrapper, we'd be looking at infinite recursion since
3635          * the wrapper would call the icall which would call the wrapper and
3636          * so on.
3637          */
3638         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", "void ptr", TRUE);
3639         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", "void ptr", TRUE);
3640
3641         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
3642         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
3643         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
3644         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr", TRUE);
3645         register_icall (mono_jit_set_domain, "mono_jit_set_domain", "void ptr", TRUE);
3646         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
3647
3648         register_icall (mono_llvm_throw_exception, "mono_llvm_throw_exception", "void object", TRUE);
3649         register_icall (mono_llvm_rethrow_exception, "mono_llvm_rethrow_exception", "void object", TRUE);
3650         register_icall (mono_llvm_resume_exception, "mono_llvm_resume_exception", "void", TRUE);
3651         register_icall (mono_llvm_match_exception, "mono_llvm_match_exception", "int ptr int int", TRUE);
3652         register_icall (mono_llvm_clear_exception, "mono_llvm_clear_exception", NULL, TRUE);
3653         register_icall (mono_llvm_load_exception, "mono_llvm_load_exception", "object", TRUE);
3654         register_icall (mono_llvm_throw_corlib_exception, "mono_llvm_throw_corlib_exception", "void int", FALSE);
3655 #if defined(ENABLE_LLVM) && !defined(MONO_LLVM_LOADED)
3656         register_icall (mono_llvm_set_unhandled_exception_handler, "mono_llvm_set_unhandled_exception_handler", NULL, TRUE);
3657
3658         // FIXME: This is broken
3659         register_icall (mono_debug_personality, "mono_debug_personality", "int int int ptr ptr ptr", TRUE);
3660 #endif
3661
3662         register_dyn_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
3663         register_dyn_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
3664         register_dyn_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", "void ptr", TRUE);
3665         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
3666         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "object", FALSE);
3667         register_icall (mono_thread_force_interruption_checkpoint_noraise, "mono_thread_force_interruption_checkpoint_noraise", "object", FALSE);
3668         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
3669 #ifndef DISABLE_REMOTING
3670         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
3671         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
3672 #endif
3673
3674 #if defined(__native_client__) || defined(__native_client_codegen__)
3675         register_icall (mono_nacl_gc, "mono_nacl_gc", "void", FALSE);
3676 #endif
3677
3678         if (mono_threads_is_coop_enabled ())
3679                 register_icall (mono_threads_state_poll, "mono_threads_state_poll", "void", FALSE);
3680
3681 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
3682         register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, "mono_llmult", TRUE);
3683         register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, "mono_lldiv", FALSE);
3684         register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, "mono_lldiv_un", FALSE);
3685         register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, "mono_llrem", FALSE);
3686         register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, "mono_llrem_un", FALSE);
3687 #endif
3688 #if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
3689         register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, "mono_llmult_ovf_un", FALSE);
3690         register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, "mono_llmult_ovf", FALSE);
3691 #endif
3692
3693 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
3694         register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, "mono_lshl", TRUE);
3695         register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, "mono_lshr", TRUE);
3696         register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, "mono_lshr_un", TRUE);
3697 #endif
3698
3699 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
3700         register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, "mono_idiv", FALSE);
3701         register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, "mono_idiv_un", FALSE);
3702         register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, "mono_irem", FALSE);
3703         register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, "mono_irem_un", FALSE);
3704 #endif
3705
3706 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3707         register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, "mono_imul", TRUE);
3708 #endif
3709
3710 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
3711         register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, "mono_imul_ovf", FALSE);
3712         register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, "mono_imul_ovf_un", FALSE);
3713 #endif
3714
3715 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
3716         register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, "mono_fdiv", FALSE);
3717 #endif
3718
3719         register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, "mono_fconv_u8", FALSE);
3720         register_opcode_emulation (OP_RCONV_TO_U8, "__emul_rconv_to_u8", "ulong float", mono_rconv_u8, "mono_rconv_u8", FALSE);
3721         register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, "mono_fconv_u4", FALSE);
3722         register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, "mono_fconv_ovf_i8", FALSE);
3723         register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, "mono_fconv_ovf_u8", FALSE);
3724         register_opcode_emulation (OP_RCONV_TO_OVF_I8, "__emul_rconv_to_ovf_i8", "long float", mono_rconv_ovf_i8, "mono_rconv_ovf_i8", FALSE);
3725         register_opcode_emulation (OP_RCONV_TO_OVF_U8, "__emul_rconv_to_ovf_u8", "ulong float", mono_rconv_ovf_u8, "mono_rconv_ovf_u8", FALSE);
3726
3727
3728 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
3729         register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, "mono_fconv_i8", FALSE);
3730         register_opcode_emulation (OP_RCONV_TO_I8, "__emul_rconv_to_i8", "long float", mono_rconv_i8, "mono_rconv_i8", FALSE);
3731 #endif
3732
3733 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
3734         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);
3735 #endif
3736 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
3737         register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, "mono_lconv_to_r8", FALSE);
3738 #endif
3739 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
3740         register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, "mono_lconv_to_r4", FALSE);
3741 #endif
3742 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
3743         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);
3744 #endif
3745 #ifdef MONO_ARCH_EMULATE_FREM
3746 #if defined(__default_codegen__)
3747         register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, "fmod", FALSE);
3748         register_opcode_emulation (OP_RREM, "__emul_rrem", "float float float", fmodf, "fmodf", FALSE);
3749 #elif defined(__native_client_codegen__)
3750         register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, "mono_fmod", FALSE);
3751 #endif
3752 #endif
3753
3754 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3755         if (mono_arch_is_soft_float ()) {
3756                 register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, "mono_fsub", FALSE);
3757                 register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, "mono_fadd", FALSE);
3758                 register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, "mono_fmul", FALSE);
3759                 register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, "mono_fneg", FALSE);
3760                 register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, "mono_conv_to_r8", FALSE);
3761                 register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, "mono_conv_to_r4", FALSE);
3762                 register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, "mono_fconv_r4", FALSE);
3763                 register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, "mono_fconv_i1", FALSE);
3764                 register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, "mono_fconv_i2", FALSE);
3765                 register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3766                 register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, "mono_fconv_u1", FALSE);
3767                 register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, "mono_fconv_u2", FALSE);
3768
3769 #if SIZEOF_VOID_P == 4
3770                 register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3771 #endif
3772
3773                 register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, "mono_fcmp_eq", FALSE);
3774                 register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, "mono_fcmp_lt", FALSE);
3775                 register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, "mono_fcmp_gt", FALSE);
3776                 register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, "mono_fcmp_le", FALSE);
3777                 register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, "mono_fcmp_ge", FALSE);
3778                 register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, "mono_fcmp_ne_un", FALSE);
3779                 register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, "mono_fcmp_lt_un", FALSE);
3780                 register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, "mono_fcmp_gt_un", FALSE);
3781                 register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, "mono_fcmp_le_un", FALSE);
3782                 register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, "mono_fcmp_ge_un", FALSE);
3783
3784                 register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, "mono_fceq", FALSE);
3785                 register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, "mono_fcgt", FALSE);
3786                 register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, "mono_fcgt_un", FALSE);
3787                 register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, "mono_fclt", FALSE);
3788                 register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, "mono_fclt_un", FALSE);
3789
3790                 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
3791                 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
3792                 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
3793                 register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
3794         }
3795 #endif
3796         register_icall (mono_ckfinite, "mono_ckfinite", "double double", FALSE);
3797
3798 #ifdef COMPRESSED_INTERFACE_BITMAP
3799         register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
3800 #endif
3801
3802 #if SIZEOF_REGISTER == 4
3803         register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, "mono_fconv_u4", TRUE);
3804 #else
3805         register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "ulong double", mono_fconv_u8, "mono_fconv_u8", TRUE);
3806 #endif
3807
3808         /* other jit icalls */
3809         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
3810         register_icall (mono_class_static_field_address , "mono_class_static_field_address",
3811                                  "ptr ptr ptr", FALSE);
3812         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
3813         register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
3814                 "ptr ptr ptr ptr", FALSE);
3815         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
3816         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
3817         register_icall (mono_helper_stelem_ref_check, "mono_helper_stelem_ref_check", "void object object", FALSE);
3818         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
3819         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
3820         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
3821         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
3822         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
3823         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
3824         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
3825         register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
3826         register_icall (mono_helper_compile_generic_method, "mono_helper_compile_generic_method", "ptr object ptr ptr", FALSE);
3827         register_icall (mono_helper_ldstr, "mono_helper_ldstr", "object ptr int", FALSE);
3828         register_icall (mono_helper_ldstr_mscorlib, "mono_helper_ldstr_mscorlib", "object int", FALSE);
3829         register_icall (mono_helper_newobj_mscorlib, "mono_helper_newobj_mscorlib", "object int", FALSE);
3830         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
3831         register_icall (mono_object_castclass_unbox, "mono_object_castclass_unbox", "object object ptr", FALSE);
3832         register_icall (mono_break, "mono_break", NULL, TRUE);
3833         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
3834         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
3835         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
3836         register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
3837         register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
3838         register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
3839         register_icall (mono_array_new_4, "mono_array_new_4", "object ptr int int int int", FALSE);
3840         register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
3841         register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
3842         register_icall (mono_gsharedvt_constrained_call, "mono_gsharedvt_constrained_call", "object ptr ptr ptr ptr ptr", FALSE);
3843         register_icall (mono_gsharedvt_value_copy, "mono_gsharedvt_value_copy", "void ptr ptr ptr", TRUE);
3844
3845         register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
3846
3847         register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
3848         register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
3849         register_icall (mono_generic_class_init, "mono_generic_class_init", "void ptr", FALSE);
3850         register_icall (mono_fill_class_rgctx, "mono_class_fill_rgctx", "ptr ptr int", FALSE);
3851         register_icall (mono_fill_method_rgctx, "mono_method_fill_rgctx", "ptr ptr int", FALSE);
3852
3853         register_icall (mono_debugger_agent_user_break, "mono_debugger_agent_user_break", "void", FALSE);
3854
3855         register_icall (mono_aot_init_llvm_method, "mono_aot_init_llvm_method", "void ptr int", TRUE);
3856         register_icall (mono_aot_init_gshared_method_this, "mono_aot_init_gshared_method_this", "void ptr int object", TRUE);
3857         register_icall (mono_aot_init_gshared_method_rgctx, "mono_aot_init_gshared_method_rgctx", "void ptr int ptr", TRUE);
3858
3859         register_icall_no_wrapper (mono_resolve_iface_call_gsharedvt, "mono_resolve_iface_call_gsharedvt", "ptr object int ptr ptr");
3860         register_icall_no_wrapper (mono_resolve_vcall_gsharedvt, "mono_resolve_vcall_gsharedvt", "ptr object int ptr ptr");
3861         register_icall_no_wrapper (mono_resolve_generic_virtual_call, "mono_resolve_generic_virtual_call", "ptr ptr int ptr");
3862         register_icall_no_wrapper (mono_resolve_generic_virtual_iface_call, "mono_resolve_generic_virtual_iface_call", "ptr ptr int ptr");
3863         /* This needs a wrapper so it can have a preserveall cconv */
3864         register_icall (mono_init_vtable_slot, "mono_init_vtable_slot", "ptr ptr int", FALSE);
3865         register_icall (mono_init_delegate, "mono_init_delegate", "void object object ptr", TRUE);
3866         register_icall (mono_init_delegate_virtual, "mono_init_delegate_virtual", "void object object ptr", TRUE);
3867         register_icall (mono_get_assembly_object, "mono_get_assembly_object", "object ptr", TRUE);
3868
3869 #ifdef TARGET_IOS
3870         register_icall (pthread_getspecific, "pthread_getspecific", "ptr ptr", TRUE);
3871 #endif
3872 }
3873
3874 MonoJitStats mono_jit_stats = {0};
3875
3876 static void
3877 print_jit_stats (void)
3878 {
3879         if (mono_jit_stats.enabled) {
3880                 g_print ("Mono Jit statistics\n");
3881                 g_print ("Max code size ratio:    %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
3882                                  mono_jit_stats.max_ratio_method);
3883                 g_print ("Biggest method:         %ld (%s)\n", mono_jit_stats.biggest_method_size,
3884                                  mono_jit_stats.biggest_method);
3885
3886                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
3887                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
3888                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
3889                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
3890                 g_print ("Methods:                %ld\n", mono_stats.method_count);
3891                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
3892                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
3893                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
3894
3895                 g_print ("\nInitialized classes:    %ld\n", mono_stats.generic_class_count);
3896                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
3897                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
3898
3899                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
3900                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
3901                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
3902                 g_print ("Shared vtype generic methods: %ld\n", mono_stats.gsharedvt_methods);
3903
3904                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
3905                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
3906                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
3907                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
3908                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
3909                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
3910                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
3911                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
3912
3913                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
3914                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
3915                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
3916
3917                 g_free (mono_jit_stats.max_ratio_method);
3918                 mono_jit_stats.max_ratio_method = NULL;
3919                 g_free (mono_jit_stats.biggest_method);
3920                 mono_jit_stats.biggest_method = NULL;
3921         }
3922 }
3923
3924 void
3925 mini_cleanup (MonoDomain *domain)
3926 {
3927         mono_runtime_shutdown_stat_profiler ();
3928
3929 #ifndef DISABLE_COM
3930         cominterop_release_all_rcws ();
3931 #endif
3932
3933 #ifndef MONO_CROSS_COMPILE
3934         /*
3935          * mono_domain_finalize () needs to be called early since it needs the
3936          * execution engine still fully working (it may invoke managed finalizers).
3937          */
3938         mono_domain_finalize (domain, 2000);
3939 #endif
3940
3941         /* This accesses metadata so needs to be called before runtime shutdown */
3942         print_jit_stats ();
3943
3944         mono_profiler_shutdown ();
3945
3946 #ifndef MONO_CROSS_COMPILE
3947         mono_runtime_cleanup (domain);
3948 #endif
3949
3950         free_jit_tls_data ((MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id));
3951
3952         mono_icall_cleanup ();
3953
3954         mono_runtime_cleanup_handlers ();
3955
3956 #ifndef MONO_CROSS_COMPILE
3957         mono_domain_free (domain, TRUE);
3958 #endif
3959
3960 #ifdef ENABLE_LLVM
3961         if (mono_use_llvm)
3962                 mono_llvm_cleanup ();
3963 #endif
3964
3965         mono_aot_cleanup ();
3966
3967         mono_trampolines_cleanup ();
3968
3969         mono_unwind_cleanup ();
3970
3971         mono_code_manager_destroy (global_codeman);
3972         g_free (vtable_trampolines);
3973
3974         mini_jit_cleanup ();
3975
3976         mono_tramp_info_cleanup ();
3977
3978         mono_arch_cleanup ();
3979
3980         mono_generic_sharing_cleanup ();
3981
3982         mono_cleanup ();
3983
3984         mono_trace_cleanup ();
3985
3986         mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, stdout);
3987
3988         if (mono_inject_async_exc_method)
3989                 mono_method_desc_free (mono_inject_async_exc_method);
3990
3991         mono_native_tls_free (mono_jit_tls_id);
3992
3993         mono_os_mutex_destroy (&jit_mutex);
3994
3995         mono_code_manager_cleanup ();
3996
3997 #ifdef USE_JUMP_TABLES
3998         mono_jumptable_cleanup ();
3999 #endif
4000 }
4001
4002 void
4003 mono_set_defaults (int verbose_level, guint32 opts)
4004 {
4005         mini_verbose = verbose_level;
4006         mono_set_optimizations (opts);
4007 }
4008
4009 void
4010 mono_disable_optimizations (guint32 opts)
4011 {
4012         default_opt &= ~opts;
4013 }
4014
4015 void
4016 mono_set_optimizations (guint32 opts)
4017 {
4018         default_opt = opts;
4019         default_opt_set = TRUE;
4020 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
4021         mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
4022 #else
4023         if (mono_llvm_only)
4024                 mono_set_generic_sharing_vt_supported (TRUE);
4025 #endif
4026 }
4027
4028 void
4029 mono_set_verbose_level (guint32 level)
4030 {
4031         mini_verbose = level;
4032 }
4033
4034 /**
4035  * mono_get_runtime_build_info:
4036  *
4037  * Return the runtime version + build date in string format.
4038  * The returned string is owned by the caller. The returned string
4039  * format is "VERSION (FULL_VERSION BUILD_DATE)" and build date is optional.
4040  */
4041 char*
4042 mono_get_runtime_build_info (void)
4043 {
4044         if (mono_build_date)
4045                 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
4046         else
4047                 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
4048 }
4049
4050 static void
4051 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
4052 {
4053         GHashTable *assemblies = (GHashTable*)user_data;
4054         MonoImage *image = mono_assembly_get_image (ass);
4055         MonoMethod *method, *invoke;
4056         int i, count = 0;
4057
4058         if (g_hash_table_lookup (assemblies, ass))
4059                 return;
4060
4061         g_hash_table_insert (assemblies, ass, ass);
4062
4063         if (mini_verbose > 0)
4064                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
4065
4066         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
4067                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
4068                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
4069                         continue;
4070                 if (method->is_generic || method->klass->generic_container)
4071                         continue;
4072
4073                 count++;
4074                 if (mini_verbose > 1) {
4075                         char * desc = mono_method_full_name (method, TRUE);
4076                         g_print ("Compiling %d %s\n", count, desc);
4077                         g_free (desc);
4078                 }
4079                 mono_compile_method (method);
4080                 if (strcmp (method->name, "Finalize") == 0) {
4081                         invoke = mono_marshal_get_runtime_invoke (method, FALSE);
4082                         mono_compile_method (invoke);
4083                 }
4084 #ifndef DISABLE_REMOTING
4085                 if (mono_class_is_marshalbyref (method->klass) && mono_method_signature (method)->hasthis) {
4086                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
4087                         mono_compile_method (invoke);
4088                 }
4089 #endif
4090         }
4091
4092         /* Load and precompile referenced assemblies as well */
4093         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
4094                 mono_assembly_load_reference (image, i);
4095                 if (image->references [i])
4096                         mono_precompile_assembly (image->references [i], assemblies);
4097         }
4098 }
4099
4100 void mono_precompile_assemblies ()
4101 {
4102         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
4103
4104         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
4105
4106         g_hash_table_destroy (assemblies);
4107 }
4108
4109 /*
4110  * Used by LLVM.
4111  * Have to export this for AOT.
4112  */
4113 void
4114 mono_personality (void)
4115 {
4116         /* Not used */
4117         g_assert_not_reached ();
4118 }
4119
4120 #ifdef USE_JUMP_TABLES
4121 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
4122
4123 typedef struct MonoJumpTableChunk {
4124         guint32 total;
4125         guint32 active;
4126         struct MonoJumpTableChunk *previous;
4127         /* gpointer entries[total]; */
4128 } MonoJumpTableChunk;
4129
4130 static MonoJumpTableChunk* g_jumptable;
4131 #define mono_jumptable_lock() mono_os_mutex_lock (&jumptable_mutex)
4132 #define mono_jumptable_unlock() mono_os_mutex_unlock (&jumptable_mutex)
4133 static mono_mutex_t jumptable_mutex;
4134
4135 static  MonoJumpTableChunk*
4136 mono_create_jumptable_chunk (guint32 max_entries)
4137 {
4138         guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
4139         MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
4140         chunk->total = max_entries;
4141         return chunk;
4142 }
4143
4144 void
4145 mono_jumptable_init (void)
4146 {
4147         if (g_jumptable == NULL) {
4148                 mono_os_mutex_init_recursive (&jumptable_mutex);
4149                 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
4150         }
4151 }
4152
4153 gpointer*
4154 mono_jumptable_add_entry (void)
4155 {
4156         return mono_jumptable_add_entries (1);
4157 }
4158
4159 gpointer*
4160 mono_jumptable_add_entries (guint32 entries)
4161 {
4162         guint32 index;
4163         gpointer *result;
4164
4165         mono_jumptable_init ();
4166         mono_jumptable_lock ();
4167         index = g_jumptable->active;
4168         if (index + entries >= g_jumptable->total) {
4169                 /*
4170                  * Grow jumptable, by adding one more chunk.
4171                  * We cannot realloc jumptable, as there could be pointers
4172                  * to existing jump table entries in the code, so instead
4173                  * we just add one more chunk.
4174                  */
4175                 guint32 max_entries = entries;
4176                 MonoJumpTableChunk *new_chunk;
4177
4178                 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
4179                         max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
4180                 new_chunk = mono_create_jumptable_chunk (max_entries);
4181                 /* Link old jumptable, so that we could free it up later. */
4182                 new_chunk->previous = g_jumptable;
4183                 g_jumptable = new_chunk;
4184                 index = 0;
4185         }
4186         g_jumptable->active = index + entries;
4187         result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
4188         mono_jumptable_unlock();
4189
4190         return result;
4191 }
4192
4193 void
4194 mono_jumptable_cleanup (void)
4195 {
4196         if (g_jumptable) {
4197                 MonoJumpTableChunk *current = g_jumptable, *prev;
4198                 while (current != NULL) {
4199                         prev = current->previous;
4200                         g_free (current);
4201                         current = prev;
4202                 }
4203                 g_jumptable = NULL;
4204                 mono_os_mutex_destroy (&jumptable_mutex);
4205         }
4206 }
4207
4208 gpointer*
4209 mono_jumptable_get_entry (guint8 *code_ptr)
4210 {
4211         return mono_arch_jumptable_entry_from_code (code_ptr);
4212 }
4213 #endif