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