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