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