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