2 * mini-runtime.c: Runtime code for the JIT
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * Copyright 2002-2003 Ximian, Inc.
9 * Copyright 2003-2010 Novell, Inc.
10 * Copyright 2011-2015 Xamarin, Inc (http://www.xamarin.com)
21 #ifdef HAVE_SYS_TIME_H
28 #include <mono/utils/memcheck.h>
30 #include <mono/metadata/assembly.h>
31 #include <mono/metadata/loader.h>
32 #include <mono/metadata/tabledefs.h>
33 #include <mono/metadata/class.h>
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/tokentype.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/appdomain.h>
39 #include <mono/metadata/debug-helpers.h>
40 #include "mono/metadata/profiler.h"
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/gc-internal.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/mempool-internals.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/runtime.h>
50 #include <mono/utils/mono-math.h>
51 #include <mono/utils/mono-compiler.h>
52 #include <mono/utils/mono-counters.h>
53 #include <mono/utils/mono-error-internals.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-path.h>
57 #include <mono/utils/mono-tls.h>
58 #include <mono/utils/mono-hwcap.h>
59 #include <mono/utils/dtrace.h>
60 #include <mono/utils/mono-signal-handler.h>
61 #include <mono/utils/mono-threads.h>
62 #include <mono/io-layer/io-layer.h>
65 #include "seq-points.h"
72 #include "jit-icalls.h"
75 #include "debugger-agent.h"
77 static guint32 default_opt = 0;
78 static gboolean default_opt_set = FALSE;
80 MonoNativeTlsKey mono_jit_tls_id;
82 #ifdef MONO_HAVE_FAST_TLS
83 MONO_FAST_TLS_DECLARE(mono_jit_tls);
86 gboolean mono_compile_aot = FALSE;
87 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
88 gboolean mono_aot_only = FALSE;
89 /* Whenever to use IMT */
90 gboolean mono_use_imt = TRUE;
91 const char *mono_build_date;
92 gboolean mono_do_signal_chaining;
93 gboolean mono_do_crash_chaining;
97 * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
98 * it can load AOT code compiled by LLVM.
100 gboolean mono_use_llvm = FALSE;
102 #define mono_jit_lock() mono_mutex_lock (&jit_mutex)
103 #define mono_jit_unlock() mono_mutex_unlock (&jit_mutex)
104 static mono_mutex_t jit_mutex;
106 static MonoCodeManager *global_codeman;
108 MonoDebugOptions debug_options;
110 #ifdef VALGRIND_JIT_REGISTER_MAP
111 int valgrind_register;
114 static GSList *tramp_infos;
116 static void register_icalls (void);
119 mono_running_on_valgrind (void)
121 if (RUNNING_ON_VALGRIND){
122 #ifdef VALGRIND_JIT_REGISTER_MAP
123 valgrind_register = TRUE;
136 find_tramp (gpointer key, gpointer value, gpointer user_data)
138 FindTrampUserData *ud = (FindTrampUserData*)user_data;
141 ud->method = (MonoMethod*)key;
145 G_GNUC_UNUSED static char*
146 get_method_from_ip (void *ip)
151 MonoDomain *domain = mono_domain_get ();
152 MonoDebugSourceLocation *location;
153 FindTrampUserData user_data;
156 domain = mono_get_root_domain ();
158 ji = mono_jit_info_table_find (domain, ip);
161 user_data.method = NULL;
162 mono_domain_lock (domain);
163 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
164 mono_domain_unlock (domain);
165 if (user_data.method) {
166 char *mname = mono_method_full_name (user_data.method, TRUE);
167 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
174 method = mono_method_full_name (jinfo_get_method (ji), TRUE);
175 /* FIXME: unused ? */
176 location = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
178 res = g_strdup_printf (" %s + 0x%x (%p %p) [%p - %s]", method, (int)((char*)ip - (char*)ji->code_start), ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
180 mono_debug_free_source_location (location);
188 * @ip: an instruction pointer address
190 * This method is used from a debugger to get the name of the
191 * method at address @ip. This routine is typically invoked from
192 * a debugger like this:
194 * (gdb) print mono_pmip ($pc)
196 * Returns: the name of the method at address @ip.
201 return get_method_from_ip (ip);
205 * mono_print_method_from_ip
206 * @ip: an instruction pointer address
208 * This method is used from a debugger to get the name of the
209 * method at address @ip.
211 * This prints the name of the method at address @ip in the standard
212 * output. Unlike mono_pmip which returns a string, this routine
213 * prints the value on the standard output.
216 /* Prevent the linker from optimizing this away in embedding setups to help debugging */
217 __attribute__((used))
220 mono_print_method_from_ip (void *ip)
224 MonoDebugSourceLocation *source;
225 MonoDomain *domain = mono_domain_get ();
226 MonoDomain *target_domain = mono_domain_get ();
227 FindTrampUserData user_data;
228 MonoGenericSharingContext*gsctx;
229 const char *shared_type;
232 ji = mini_jit_info_table_find (domain, ip, &target_domain);
235 user_data.method = NULL;
236 mono_domain_lock (domain);
237 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
238 mono_domain_unlock (domain);
239 if (user_data.method) {
240 char *mname = mono_method_full_name (user_data.method, TRUE);
241 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
245 for (l = tramp_infos; l; l = l->next) {
246 MonoTrampInfo *tinfo = l->data;
248 if ((guint8*)ip >= tinfo->code && (guint8*)ip <= tinfo->code + tinfo->code_size) {
249 printf ("IP %p is at offset 0x%x of trampoline '%s'.\n", ip, (int)((guint8*)ip - tinfo->code), tinfo->name);
254 g_print ("No method at %p\n", ip);
258 method = mono_method_full_name (jinfo_get_method (ji), TRUE);
259 source = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
261 gsctx = mono_jit_info_get_generic_sharing_context (ji);
264 if (gsctx->var_is_vt || gsctx->mvar_is_vt)
265 shared_type = "gsharedvt ";
267 shared_type = "gshared ";
270 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);
273 g_print ("%s:%d\n", source->source_file, source->row);
276 mono_debug_free_source_location (source);
281 * mono_method_same_domain:
283 * Determine whenever two compiled methods are in the same domain, thus
284 * the address of the callee can be embedded in the caller.
286 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
290 if (!caller || !callee)
294 * If the call was made from domain-neutral to domain-specific
295 * code, we can't patch the call site.
297 if (caller->domain_neutral && !callee->domain_neutral)
300 cmethod = jinfo_get_method (caller);
301 if ((cmethod->klass == mono_defaults.appdomain_class) &&
302 (strstr (cmethod->name, "InvokeInDomain"))) {
303 /* The InvokeInDomain methods change the current appdomain */
311 * mono_global_codeman_reserve:
313 * Allocate code memory from the global code manager.
315 void *mono_global_codeman_reserve (int size)
320 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
322 if (!global_codeman) {
323 /* This can happen during startup */
324 global_codeman = mono_code_manager_new ();
325 return mono_code_manager_reserve (global_codeman, size);
329 ptr = mono_code_manager_reserve (global_codeman, size);
335 #if defined(__native_client_codegen__) && defined(__native_client__)
339 #ifdef __native_client_gc__
340 __nacl_suspend_thread_if_needed();
344 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
345 * which we are generating code, return a pointer to the destination in the
346 * dynamic code segment into which the code will be copied when
347 * mono_global_codeman_commit is called.
348 * LOCKING: Acquires the jit lock.
351 nacl_global_codeman_get_dest (void *data)
355 dest = nacl_code_manager_get_code_dest (global_codeman, data);
361 mono_global_codeman_commit (void *data, int size, int newsize)
364 mono_code_manager_commit (global_codeman, data, size, newsize);
369 * Convenience function which calls mono_global_codeman_commit to validate and
370 * copy the code. The caller sets *buf_base and *buf_size to the start and size
371 * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
372 * the byte after the last instruction byte. On return, *buf_base will point to
373 * the start of the copied in the code segment, and *code_end will point after
374 * the end of the copied code.
377 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
379 guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
380 mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
381 *code_end = tmp + (*code_end - *buf_base);
385 /* no-op versions of Native Client functions */
387 nacl_global_codeman_get_dest (void *data)
393 mono_global_codeman_commit (void *data, int size, int newsize)
398 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
402 #endif /* __native_client__ */
405 * mono_create_unwind_op:
407 * Create an unwind op with the given parameters.
410 mono_create_unwind_op (int when, int tag, int reg, int val)
412 MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
423 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
425 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
428 res->has_context = context != NULL;
430 memcpy (&res->context, context, sizeof (MonoGenericContext));
436 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
438 return mono_jump_info_token_new2 (mp, image, token, NULL);
442 * mono_tramp_info_create:
444 * Create a MonoTrampInfo structure from the arguments. This function assumes ownership
445 * of JI, and UNWIND_OPS.
448 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
450 MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
452 info->name = g_strdup ((char*)name);
454 info->code_size = code_size;
456 info->unwind_ops = unwind_ops;
462 mono_tramp_info_free (MonoTrampInfo *info)
469 for (l = info->unwind_ops; l; l = l->next)
471 g_slist_free (info->unwind_ops);
476 * mono_tramp_info_register:
478 * Remember INFO for use by xdebug, mono_print_method_from_ip (), jit maps, etc.
483 mono_tramp_info_register (MonoTrampInfo *info)
490 copy = g_new0 (MonoTrampInfo, 1);
491 copy->code = info->code;
492 copy->code_size = info->code_size;
493 copy->name = g_strdup (info->name);
496 tramp_infos = g_slist_prepend (tramp_infos, copy);
499 mono_save_trampoline_xdebug_info (info);
501 if (mono_jit_map_is_enabled ())
502 mono_emit_jit_tramp (info->code, info->code_size, info->name);
504 mono_tramp_info_free (info);
508 mono_tramp_info_cleanup (void)
512 for (l = tramp_infos; l; l = l->next) {
513 MonoTrampInfo *info = l->data;
515 mono_tramp_info_free (info);
517 g_slist_free (tramp_infos);
520 G_GNUC_UNUSED static void
526 * Runtime debugging tool, use if (debug_count ()) <x> else <y> to do <x> the first COUNT times, then do <y> afterwards.
527 * Set a breakpoint in break_count () to break the last time <x> is done.
529 G_GNUC_UNUSED gboolean
530 mono_debug_count (void)
532 static int count = 0;
533 static gboolean inited;
534 static const char *value;
539 value = g_getenv ("COUNT");
546 if (count == atoi (value))
549 if (count > atoi (value))
556 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
560 gconstpointer trampoline;
561 MonoDomain *domain = mono_get_root_domain ();
562 gboolean check_exc = check_for_pending_exc;
564 if (callinfo->wrapper) {
565 return callinfo->wrapper;
568 if (callinfo->trampoline)
569 return callinfo->trampoline;
572 * We use the lock on the root domain instead of the JIT lock to protect
573 * callinfo->trampoline, since we do a lot of stuff inside the critical section.
575 mono_loader_lock (); /*FIXME mono_compile_method requires the loader lock, by large.*/
576 mono_domain_lock (domain);
578 if (callinfo->trampoline) {
579 mono_domain_unlock (domain);
580 mono_loader_unlock ();
581 return callinfo->trampoline;
584 if (!strcmp (callinfo->name, "mono_thread_interruption_checkpoint"))
585 /* This icall is used to check for exceptions, so don't check in the wrapper */
588 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
589 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_exc);
593 trampoline = mono_compile_method (wrapper);
595 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
596 mono_register_jit_icall_wrapper (callinfo, trampoline);
598 callinfo->trampoline = trampoline;
600 mono_domain_unlock (domain);
601 mono_loader_unlock ();
603 return callinfo->trampoline;
607 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
609 return mono_icall_get_wrapper_full (callinfo, FALSE);
613 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
615 if (!domain_jit_info (domain)->dynamic_code_hash)
616 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
617 g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
620 static MonoJitDynamicMethodInfo*
621 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
623 MonoJitDynamicMethodInfo *res;
625 if (domain_jit_info (domain)->dynamic_code_hash)
626 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
633 register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
635 return mini_register_opcode_emulation (opcode, name, sigstr, func, symbol, no_throw);
639 * For JIT icalls implemented in C.
640 * NAME should be the same as the name of the C function whose address is FUNC.
641 * If SAVE is TRUE, no wrapper is generated. This is for perf critical icalls which
642 * can't throw exceptions.
645 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
647 MonoMethodSignature *sig;
650 sig = mono_create_icall_signature (sigstr);
654 mono_register_jit_icall_full (func, name, sig, save, FALSE, save ? name : NULL);
657 /* Register a jit icall which doesn't throw exceptions through mono_raise_exception () */
659 register_icall_noraise (gpointer func, const char *name, const char *sigstr)
661 MonoMethodSignature *sig;
664 sig = mono_create_icall_signature (sigstr);
668 mono_register_jit_icall_full (func, name, sig, TRUE, TRUE, name);
672 register_dyn_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
674 MonoMethodSignature *sig;
677 sig = mono_create_icall_signature (sigstr);
681 mono_register_jit_icall (func, name, sig, save);
684 #ifdef MONO_HAVE_FAST_TLS
685 MONO_FAST_TLS_DECLARE(mono_lmf_addr);
686 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
688 * When this is defined, the current lmf is stored in this tls variable instead of in
691 MONO_FAST_TLS_DECLARE(mono_lmf);
696 mono_get_jit_tls_offset (void)
702 offset = mono_jit_tls_id;
704 /* FIXME: Happens during startup */
707 MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
713 mono_get_lmf_tls_offset (void)
715 #if defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
717 MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
725 mono_get_lmf_addr_tls_offset (void)
728 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
735 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
736 return MONO_FAST_TLS_GET (mono_lmf);
738 MonoJitTlsData *jit_tls;
740 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
743 * We do not assert here because this function can be called from
744 * mini-gc.c on a thread that has not executed any managed code, yet
745 * (the thread object allocation can trigger a collection).
752 mono_get_lmf_addr (void)
754 #ifdef MONO_HAVE_FAST_TLS
755 return MONO_FAST_TLS_GET (mono_lmf_addr);
757 MonoJitTlsData *jit_tls;
759 jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
760 if (G_LIKELY (jit_tls))
761 return &jit_tls->lmf;
764 * When resolving the call to mono_jit_thread_attach full-aot will look
765 * in the plt, which causes a call into the generic trampoline, which in turn
766 * tries to resolve the lmf_addr creating a cyclic dependency. We cannot
767 * call mono_jit_thread_attach from the native-to-managed wrapper, without
768 * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
771 mono_jit_thread_attach (NULL);
773 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
774 return &jit_tls->lmf;
776 g_assert_not_reached ();
782 mono_set_lmf (MonoLMF *lmf)
784 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
785 MONO_FAST_TLS_SET (mono_lmf, lmf);
788 (*mono_get_lmf_addr ()) = lmf;
792 mono_get_jit_tls (void)
794 return mono_native_tls_get_value (mono_jit_tls_id);
798 mono_set_jit_tls (MonoJitTlsData *jit_tls)
800 MonoThreadInfo *info;
802 mono_native_tls_set_value (mono_jit_tls_id, jit_tls);
804 #ifdef MONO_HAVE_FAST_TLS
805 MONO_FAST_TLS_SET (mono_jit_tls, jit_tls);
808 /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
809 info = mono_thread_info_current ();
811 mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
815 mono_set_lmf_addr (gpointer lmf_addr)
817 MonoThreadInfo *info;
819 #ifdef MONO_HAVE_FAST_TLS
820 MONO_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
823 /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
824 info = mono_thread_info_current ();
826 mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
830 * mono_jit_thread_attach:
832 * Called by native->managed wrappers. Returns the original domain which needs to be
836 mono_jit_thread_attach (MonoDomain *domain)
842 * Happens when called from AOTed code which is only used in the root
845 domain = mono_get_root_domain ();
847 #ifdef MONO_HAVE_FAST_TLS
848 if (!MONO_FAST_TLS_GET (mono_lmf_addr)) {
849 mono_thread_attach (domain);
851 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
854 if (!mono_native_tls_get_value (mono_jit_tls_id)) {
855 mono_thread_attach (domain);
856 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
859 orig = mono_domain_get ();
861 mono_domain_set (domain, TRUE);
863 return orig != domain ? orig : NULL;
866 /* Called by native->managed wrappers */
868 mono_jit_set_domain (MonoDomain *domain)
871 mono_domain_set (domain, TRUE);
876 * @obj: exception object
878 * abort the thread, print exception information and stack trace
881 mono_thread_abort (MonoObject *obj)
883 /* MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id); */
885 /* handle_remove should be eventually called for this thread, too
888 if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
889 (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
892 mono_invoke_unhandled_exception_hook (obj);
897 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
899 MonoJitTlsData *jit_tls;
902 jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
906 jit_tls = g_new0 (MonoJitTlsData, 1);
908 jit_tls->abort_func = abort_func;
909 jit_tls->end_of_stack = stack_start;
911 mono_set_jit_tls (jit_tls);
913 lmf = g_new0 (MonoLMF, 1);
914 MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
916 jit_tls->first_lmf = lmf;
918 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
919 /* jit_tls->lmf is unused */
920 MONO_FAST_TLS_SET (mono_lmf, lmf);
921 mono_set_lmf_addr (MONO_FAST_TLS_ADDR (mono_lmf));
923 mono_set_lmf_addr (&jit_tls->lmf);
928 #ifdef MONO_ARCH_HAVE_TLS_INIT
929 mono_arch_tls_init ();
932 mono_setup_altstack (jit_tls);
938 free_jit_tls_data (MonoJitTlsData *jit_tls)
940 mono_arch_free_jit_tls_data (jit_tls);
941 mono_free_altstack (jit_tls);
943 g_free (jit_tls->first_lmf);
948 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
950 MonoInternalThread *thread;
951 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
952 thread = mono_thread_internal_current ();
954 thread->jit_data = jit_tls;
956 mono_arch_cpu_init ();
959 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
962 mono_thread_abort_dummy (MonoObject *obj)
964 if (mono_thread_attach_aborted_cb)
965 mono_thread_attach_aborted_cb (obj);
967 mono_thread_abort (obj);
971 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
973 MonoInternalThread *thread;
974 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
975 thread = mono_thread_internal_current ();
977 thread->jit_data = jit_tls;
978 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
979 mono_runtime_setup_stat_profiler ();
981 mono_arch_cpu_init ();
985 mini_thread_cleanup (MonoInternalThread *thread)
987 MonoJitTlsData *jit_tls = thread->jit_data;
990 /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
991 * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
992 * not a trivial thing.
994 * The current offender is mono_thread_manage which cleanup threads from the outside.
996 if (thread == mono_thread_internal_current ())
997 mono_set_jit_tls (NULL);
999 /* If we attach a thread but never call into managed land, we might never get an lmf.*/
1000 if (mono_get_lmf ()) {
1001 mono_set_lmf (NULL);
1002 mono_set_lmf_addr (NULL);
1005 free_jit_tls_data (jit_tls);
1007 thread->jit_data = NULL;
1012 mini_get_tls_offset (MonoTlsKey key)
1017 case TLS_KEY_THREAD:
1018 offset = mono_thread_get_tls_offset ();
1020 case TLS_KEY_JIT_TLS:
1021 offset = mono_get_jit_tls_offset ();
1023 case TLS_KEY_DOMAIN:
1024 offset = mono_domain_get_tls_offset ();
1027 offset = mono_get_lmf_tls_offset ();
1029 case TLS_KEY_LMF_ADDR:
1030 offset = mono_get_lmf_addr_tls_offset ();
1033 offset = mono_tls_key_get_offset (key);
1034 g_assert (offset != -1);
1042 mini_tls_key_supported (MonoTlsKey key)
1044 if (!MONO_ARCH_HAVE_TLS_GET)
1047 return mini_get_tls_offset (key) != -1;
1051 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
1053 MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
1057 ji->data.target = target;
1064 * mono_patch_info_dup_mp:
1066 * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
1069 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
1071 MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
1072 memcpy (res, patch_info, sizeof (MonoJumpInfo));
1074 switch (patch_info->type) {
1075 case MONO_PATCH_INFO_RVA:
1076 case MONO_PATCH_INFO_LDSTR:
1077 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1078 case MONO_PATCH_INFO_LDTOKEN:
1079 case MONO_PATCH_INFO_DECLSEC:
1080 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
1081 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
1083 case MONO_PATCH_INFO_SWITCH:
1084 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
1085 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
1086 res->data.table->table = mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1087 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1089 case MONO_PATCH_INFO_RGCTX_FETCH:
1090 res->data.rgctx_entry = mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
1091 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
1092 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
1094 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1095 res->data.del_tramp = mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
1096 memcpy (res->data.del_tramp, patch_info->data.del_tramp, sizeof (MonoDelegateClassMethodPair));
1098 case MONO_PATCH_INFO_GSHAREDVT_CALL:
1099 res->data.gsharedvt = mono_mempool_alloc (mp, sizeof (MonoJumpInfoGSharedVtCall));
1100 memcpy (res->data.gsharedvt, patch_info->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
1102 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
1103 MonoGSharedVtMethodInfo *info;
1104 MonoGSharedVtMethodInfo *oinfo;
1107 oinfo = patch_info->data.gsharedvt_method;
1108 info = mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
1109 res->data.gsharedvt_method = info;
1110 memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
1111 info->entries = mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
1112 for (i = 0; i < oinfo->num_entries; ++i) {
1113 MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
1114 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
1116 memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
1118 //info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
1119 //memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
1130 mono_patch_info_hash (gconstpointer data)
1132 const MonoJumpInfo *ji = (MonoJumpInfo*)data;
1135 case MONO_PATCH_INFO_RVA:
1136 case MONO_PATCH_INFO_LDSTR:
1137 case MONO_PATCH_INFO_LDTOKEN:
1138 case MONO_PATCH_INFO_DECLSEC:
1139 return (ji->type << 8) | ji->data.token->token;
1140 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1141 return (ji->type << 8) | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
1142 case MONO_PATCH_INFO_INTERNAL_METHOD:
1143 return (ji->type << 8) | g_str_hash (ji->data.name);
1144 case MONO_PATCH_INFO_VTABLE:
1145 case MONO_PATCH_INFO_CLASS:
1146 case MONO_PATCH_INFO_IID:
1147 case MONO_PATCH_INFO_ADJUSTED_IID:
1148 case MONO_PATCH_INFO_CLASS_INIT:
1149 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1150 case MONO_PATCH_INFO_METHODCONST:
1151 case MONO_PATCH_INFO_METHOD:
1152 case MONO_PATCH_INFO_METHOD_JUMP:
1153 case MONO_PATCH_INFO_IMAGE:
1154 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1155 case MONO_PATCH_INFO_ICALL_ADDR:
1156 case MONO_PATCH_INFO_FIELD:
1157 case MONO_PATCH_INFO_SFLDA:
1158 case MONO_PATCH_INFO_SEQ_POINT_INFO:
1159 case MONO_PATCH_INFO_METHOD_RGCTX:
1160 case MONO_PATCH_INFO_SIGNATURE:
1161 case MONO_PATCH_INFO_TLS_OFFSET:
1162 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
1163 return (ji->type << 8) | (gssize)ji->data.target;
1164 case MONO_PATCH_INFO_GSHAREDVT_CALL:
1165 return (ji->type << 8) | (gssize)ji->data.gsharedvt->method;
1166 case MONO_PATCH_INFO_RGCTX_FETCH: {
1167 MonoJumpInfoRgctxEntry *e = ji->data.rgctx_entry;
1169 return (ji->type << 8) | (gssize)e->method | (e->in_mrgctx) | e->info_type | mono_patch_info_hash (e->data);
1171 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1172 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
1173 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
1174 case MONO_PATCH_INFO_JIT_TLS_ID:
1175 case MONO_PATCH_INFO_MONITOR_ENTER:
1176 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
1177 case MONO_PATCH_INFO_MONITOR_EXIT:
1178 case MONO_PATCH_INFO_GOT_OFFSET:
1179 return (ji->type << 8);
1180 case MONO_PATCH_INFO_CASTCLASS_CACHE:
1181 return (ji->type << 8) | (ji->data.index);
1182 case MONO_PATCH_INFO_SWITCH:
1183 return (ji->type << 8) | ji->data.table->table_size;
1184 case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1185 return (ji->type << 8) | (gssize)ji->data.gsharedvt_method->method;
1186 case MONO_PATCH_INFO_OBJC_SELECTOR_REF:
1187 /* Hash on the selector name */
1188 return g_str_hash (ji->data.target);
1189 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1190 return (ji->type << 8) | (gsize)ji->data.del_tramp->klass | (gsize)ji->data.del_tramp->method | (gsize)ji->data.del_tramp->virtual;
1191 case MONO_PATCH_INFO_LDSTR_LIT:
1192 return g_str_hash (ji->data.target);
1194 printf ("info type: %d\n", ji->type);
1195 mono_print_ji (ji); printf ("\n");
1196 g_assert_not_reached ();
1202 * mono_patch_info_equal:
1204 * This might fail to recognize equivalent patches, i.e. floats, so its only
1205 * usable in those cases where this is not a problem, i.e. sharing GOT slots
1209 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
1211 const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
1212 const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
1214 if (ji1->type != ji2->type)
1217 switch (ji1->type) {
1218 case MONO_PATCH_INFO_RVA:
1219 case MONO_PATCH_INFO_LDSTR:
1220 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1221 case MONO_PATCH_INFO_LDTOKEN:
1222 case MONO_PATCH_INFO_DECLSEC:
1223 if ((ji1->data.token->image != ji2->data.token->image) ||
1224 (ji1->data.token->token != ji2->data.token->token) ||
1225 (ji1->data.token->has_context != ji2->data.token->has_context) ||
1226 (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
1227 (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
1230 case MONO_PATCH_INFO_INTERNAL_METHOD:
1231 return g_str_equal (ji1->data.name, ji2->data.name);
1232 case MONO_PATCH_INFO_RGCTX_FETCH: {
1233 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
1234 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
1236 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);
1238 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
1239 MonoJumpInfoGSharedVtCall *c1 = ji1->data.gsharedvt;
1240 MonoJumpInfoGSharedVtCall *c2 = ji2->data.gsharedvt;
1242 return c1->sig == c2->sig && c1->method == c2->method;
1244 case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1245 return ji1->data.gsharedvt_method->method == ji2->data.gsharedvt_method->method;
1246 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1247 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->virtual == ji2->data.del_tramp->virtual;
1248 case MONO_PATCH_INFO_CASTCLASS_CACHE:
1249 return ji1->data.index == ji2->data.index;
1251 if (ji1->data.target != ji2->data.target)
1260 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
1262 unsigned char *ip = patch_info->ip.i + code;
1263 gconstpointer target = NULL;
1265 switch (patch_info->type) {
1266 case MONO_PATCH_INFO_BB:
1268 * FIXME: This could be hit for methods without a prolog. Should use -1
1269 * but too much code depends on a 0 initial value.
1271 //g_assert (patch_info->data.bb->native_offset);
1272 target = patch_info->data.bb->native_offset + code;
1274 case MONO_PATCH_INFO_ABS:
1275 target = patch_info->data.target;
1277 case MONO_PATCH_INFO_LABEL:
1278 target = patch_info->data.inst->inst_c0 + code;
1280 case MONO_PATCH_INFO_IP:
1281 #if defined(__native_client__) && defined(__native_client_codegen__)
1282 /* Need to transform to the destination address, it's */
1283 /* emitted as an immediate in the code. */
1284 target = nacl_inverse_modify_patch_target(ip);
1289 case MONO_PATCH_INFO_METHOD_REL:
1290 target = code + patch_info->data.offset;
1292 case MONO_PATCH_INFO_INTERNAL_METHOD: {
1293 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1295 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
1296 g_assert_not_reached ();
1298 target = mono_icall_get_wrapper (mi);
1301 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1302 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1304 g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
1305 g_assert_not_reached ();
1310 case MONO_PATCH_INFO_METHOD_JUMP:
1311 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE);
1312 #if defined(__native_client__) && defined(__native_client_codegen__)
1313 # if defined(TARGET_AMD64)
1314 /* This target is an absolute address, not relative to the */
1315 /* current code being emitted on AMD64. */
1316 target = nacl_inverse_modify_patch_target(target);
1320 case MONO_PATCH_INFO_METHOD:
1321 #if defined(__native_client_codegen__) && defined(USE_JUMP_TABLES)
1323 * If we use jumptables, for recursive calls we cannot
1324 * avoid trampoline, as we not yet know where we will
1327 target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
1329 if (patch_info->data.method == method) {
1332 /* get the trampoline to the method from the domain */
1333 target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
1337 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
1340 mono_domain_lock (domain);
1341 if (!domain_jit_info (domain)->method_code_hash)
1342 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
1343 code_slot = g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, patch_info->data.method);
1345 code_slot = mono_domain_alloc0 (domain, sizeof (gpointer));
1346 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, patch_info->data.method, code_slot);
1348 mono_domain_unlock (domain);
1352 case MONO_PATCH_INFO_SWITCH: {
1353 gpointer *jump_table;
1355 #if defined(__native_client__) && defined(__native_client_codegen__)
1356 /* This memory will leak, but we don't care if we're */
1357 /* not deleting JIT'd methods anyway */
1358 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
1360 if (method && method->dynamic) {
1361 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
1363 if (mono_aot_only) {
1364 jump_table = mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1366 jump_table = mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1371 for (i = 0; i < patch_info->data.table->table_size; i++) {
1372 #if defined(__native_client__) && defined(__native_client_codegen__)
1373 /* 'code' is relative to the current code blob, we */
1374 /* need to do this transform on it to make the */
1375 /* pointers in this table absolute */
1376 jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1378 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1382 #if defined(__native_client__) && defined(__native_client_codegen__)
1383 /* jump_table is in the data section, we need to transform */
1384 /* it here so when it gets modified in amd64_patch it will */
1385 /* then point back to the absolute data address */
1386 target = nacl_inverse_modify_patch_target (jump_table);
1388 target = jump_table;
1392 case MONO_PATCH_INFO_METHODCONST:
1393 case MONO_PATCH_INFO_CLASS:
1394 case MONO_PATCH_INFO_IMAGE:
1395 case MONO_PATCH_INFO_FIELD:
1396 case MONO_PATCH_INFO_SIGNATURE:
1397 target = patch_info->data.target;
1399 case MONO_PATCH_INFO_IID:
1400 mono_class_init (patch_info->data.klass);
1401 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
1403 case MONO_PATCH_INFO_ADJUSTED_IID:
1404 mono_class_init (patch_info->data.klass);
1405 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
1407 case MONO_PATCH_INFO_VTABLE:
1408 target = mono_class_vtable (domain, patch_info->data.klass);
1411 case MONO_PATCH_INFO_CLASS_INIT: {
1412 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
1415 target = mono_create_class_init_trampoline (vtable);
1418 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
1419 MonoDelegateClassMethodPair *del_tramp = patch_info->data.del_tramp;
1421 if (del_tramp->virtual)
1422 target = mono_create_delegate_virtual_trampoline (domain, del_tramp->klass, del_tramp->method);
1424 target = mono_create_delegate_trampoline_info (domain, del_tramp->klass, del_tramp->method);
1427 case MONO_PATCH_INFO_SFLDA: {
1428 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
1430 if (mono_class_field_is_special_static (patch_info->data.field)) {
1431 gpointer addr = NULL;
1433 mono_domain_lock (domain);
1434 if (domain->special_static_fields)
1435 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
1436 mono_domain_unlock (domain);
1442 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
1443 /* Done by the generated code */
1447 mono_runtime_class_init (vtable);
1449 target = (char*)mono_vtable_get_static_field_data (vtable) + patch_info->data.field->offset;
1452 case MONO_PATCH_INFO_RVA: {
1453 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
1456 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
1457 target = mono_image_rva_map (patch_info->data.token->image, rva);
1460 case MONO_PATCH_INFO_R4:
1461 case MONO_PATCH_INFO_R8:
1462 target = patch_info->data.target;
1464 case MONO_PATCH_INFO_EXC_NAME:
1465 target = patch_info->data.name;
1467 case MONO_PATCH_INFO_LDSTR:
1469 mono_ldstr (domain, patch_info->data.token->image,
1470 mono_metadata_token_index (patch_info->data.token->token));
1472 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
1474 MonoClass *handle_class;
1477 handle = mono_ldtoken_checked (patch_info->data.token->image,
1478 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, &error);
1479 if (!mono_error_ok (&error))
1480 g_error ("Could not patch ldtoken due to %s", mono_error_get_message (&error));
1481 mono_class_init (handle_class);
1482 mono_class_init (mono_class_from_mono_type (handle));
1485 mono_type_get_object (domain, handle);
1488 case MONO_PATCH_INFO_LDTOKEN: {
1490 MonoClass *handle_class;
1493 handle = mono_ldtoken_checked (patch_info->data.token->image,
1494 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, &error);
1495 if (!mono_error_ok (&error))
1496 g_error ("Could not patch ldtoken due to %s", mono_error_get_message (&error));
1497 mono_class_init (handle_class);
1502 case MONO_PATCH_INFO_DECLSEC:
1503 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
1505 case MONO_PATCH_INFO_ICALL_ADDR:
1506 /* run_cctors == 0 -> AOT */
1507 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1508 const char *exc_class;
1509 const char *exc_arg;
1512 target = mono_lookup_pinvoke_call (patch_info->data.method, &exc_class, &exc_arg);
1515 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
1516 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));
1522 target = mono_lookup_internal_call (patch_info->data.method);
1524 if (!target && run_cctors)
1525 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
1528 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1529 target = mono_thread_interruption_request_flag ();
1531 case MONO_PATCH_INFO_METHOD_RGCTX: {
1532 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
1535 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
1538 case MONO_PATCH_INFO_BB_OVF:
1539 case MONO_PATCH_INFO_EXC_OVF:
1540 case MONO_PATCH_INFO_GOT_OFFSET:
1541 case MONO_PATCH_INFO_NONE:
1543 case MONO_PATCH_INFO_RGCTX_FETCH: {
1544 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
1547 switch (entry->data->type) {
1548 case MONO_PATCH_INFO_CLASS:
1549 slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, &entry->data->data.klass->byval_arg, entry->info_type, mono_method_get_context (entry->method));
1551 case MONO_PATCH_INFO_METHOD:
1552 case MONO_PATCH_INFO_METHODCONST:
1553 slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, entry->data->data.method, entry->info_type, mono_method_get_context (entry->method));
1555 case MONO_PATCH_INFO_FIELD:
1556 slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, entry->data->data.field, entry->info_type, mono_method_get_context (entry->method));
1558 case MONO_PATCH_INFO_SIGNATURE:
1559 slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, entry->data->data.sig, entry->info_type, mono_method_get_context (entry->method));
1561 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
1562 MonoJumpInfoGSharedVtCall *call_info = g_malloc0 (sizeof (MonoJumpInfoGSharedVtCall)); //mono_domain_alloc0 (domain, sizeof (MonoJumpInfoGSharedVtCall));
1564 memcpy (call_info, entry->data->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
1565 slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, call_info, entry->info_type, mono_method_get_context (entry->method));
1568 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
1569 MonoGSharedVtMethodInfo *info;
1570 MonoGSharedVtMethodInfo *oinfo = entry->data->data.gsharedvt_method;
1573 /* Make a copy into the domain mempool */
1574 info = g_malloc0 (sizeof (MonoGSharedVtMethodInfo)); //mono_domain_alloc0 (domain, sizeof (MonoGSharedVtMethodInfo));
1575 info->method = oinfo->method;
1576 info->num_entries = oinfo->num_entries;
1577 info->entries = g_malloc0 (sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
1578 for (i = 0; i < oinfo->num_entries; ++i) {
1579 MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
1580 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
1582 memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
1584 slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, info, entry->info_type, mono_method_get_context (entry->method));
1588 g_assert_not_reached ();
1592 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
1595 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1596 target = mono_create_generic_class_init_trampoline ();
1598 case MONO_PATCH_INFO_MONITOR_ENTER:
1599 target = mono_create_monitor_enter_trampoline ();
1601 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
1602 target = mono_create_monitor_enter_v4_trampoline ();
1604 case MONO_PATCH_INFO_MONITOR_EXIT:
1605 target = mono_create_monitor_exit_trampoline ();
1607 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
1608 case MONO_PATCH_INFO_SEQ_POINT_INFO:
1610 /* AOT, not needed */
1613 target = mono_arch_get_seq_point_info (domain, code);
1616 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1617 #ifdef MONO_ARCH_LLVM_SUPPORTED
1618 g_assert (mono_use_llvm);
1619 target = mono_create_llvm_imt_trampoline (domain, patch_info->data.imt_tramp->method, patch_info->data.imt_tramp->vt_offset);
1621 g_assert_not_reached ();
1624 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
1625 int card_table_shift_bits;
1626 gpointer card_table_mask;
1628 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
1631 case MONO_PATCH_INFO_CASTCLASS_CACHE: {
1632 target = mono_domain_alloc0 (domain, sizeof (gpointer));
1635 case MONO_PATCH_INFO_JIT_TLS_ID: {
1636 target = (gpointer) (size_t) mono_jit_tls_id;
1639 case MONO_PATCH_INFO_TLS_OFFSET: {
1642 offset = mini_get_tls_offset (GPOINTER_TO_INT (patch_info->data.target));
1643 #ifdef MONO_ARCH_HAVE_TRANSLATE_TLS_OFFSET
1644 offset = mono_arch_translate_tls_offset (offset);
1646 target = GINT_TO_POINTER (offset);
1649 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
1653 case MONO_PATCH_INFO_LDSTR_LIT: {
1654 target = mono_string_new (domain, patch_info->data.target);
1658 g_assert_not_reached ();
1661 return (gpointer)target;
1665 get_gsharedvt_type (MonoType *t)
1667 MonoGenericParam *par = t->data.generic_param;
1668 MonoGenericParam *copy;
1670 MonoImage *image = NULL;
1673 * Create an anonymous gparam with a different gshared_constraint so normal gshared and gsharedvt methods have
1674 * a different instantiation.
1676 g_assert (mono_generic_param_info (par));
1678 image = par->owner->image;
1680 mono_image_lock (image);
1681 if (!image->gshared_types) {
1682 image->gshared_types_len = 1;
1683 image->gshared_types = g_new0 (GHashTable, image->gshared_types_len);
1684 image->gshared_types [0] = g_hash_table_new (NULL, NULL);
1686 res = g_hash_table_lookup (image->gshared_types [0], par);
1687 mono_image_unlock (image);
1690 copy = mono_image_alloc0 (image, sizeof (MonoGenericParamFull));
1691 memcpy (copy, par, sizeof (MonoGenericParamFull));
1693 copy = g_memdup (par, sizeof (MonoGenericParam));
1697 copy->image = mono_defaults.corlib;
1698 copy->gshared_constraint = MONO_TYPE_VALUETYPE;
1699 res = mono_metadata_type_dup (NULL, t);
1700 res->data.generic_param = copy;
1703 mono_image_lock (image);
1704 /* Duplicates are ok */
1705 g_hash_table_insert (image->gshared_types [0], par, res);
1706 mono_image_unlock (image);
1713 is_gsharedvt_type (MonoType *t)
1715 return (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && t->data.generic_param->gshared_constraint == MONO_TYPE_VALUETYPE;
1719 is_open_method (MonoMethod *method)
1721 MonoGenericContext *context;
1723 if (!method->is_inflated)
1725 context = mono_method_get_context (method);
1726 if (context->class_inst && context->class_inst->is_open)
1728 if (context->method_inst && context->method_inst->is_open)
1733 static MonoGenericInst*
1734 get_shared_inst (MonoGenericInst *inst, MonoGenericInst *shared_inst, MonoGenericContainer *container, gboolean all_vt, gboolean gsharedvt)
1736 MonoGenericInst *res;
1737 MonoType **type_argv;
1740 type_argv = g_new0 (MonoType*, inst->type_argc);
1741 for (i = 0; i < inst->type_argc; ++i) {
1742 if (!all_vt && (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)) {
1743 type_argv [i] = shared_inst->type_argv [i];
1744 } else if (all_vt) {
1745 type_argv [i] = get_gsharedvt_type (shared_inst->type_argv [i]);
1746 } else if (gsharedvt) {
1747 type_argv [i] = get_gsharedvt_type (shared_inst->type_argv [i]);
1749 type_argv [i] = inst->type_argv [i];
1753 res = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
1759 * mini_get_shared_method_full:
1761 * Return the method which is actually compiled/registered when doing generic sharing.
1762 * If ALL_VT is true, return the shared method belonging to an all-vtype instantiation.
1763 * If IS_GSHAREDVT is true, treat METHOD as a gsharedvt method even if it fails some constraints.
1764 * METHOD can be a non-inflated generic method.
1767 mini_get_shared_method_full (MonoMethod *method, gboolean all_vt, gboolean is_gsharedvt)
1770 MonoGenericContext shared_context;
1771 MonoMethod *declaring_method, *res;
1772 gboolean partial = FALSE;
1773 gboolean gsharedvt = FALSE;
1774 MonoGenericContainer *class_container, *method_container = NULL;
1776 if (method->is_generic || (method->klass->generic_container && !method->is_inflated)) {
1777 declaring_method = method;
1779 declaring_method = mono_method_get_declaring_generic_method (method);
1782 if (declaring_method->is_generic)
1783 shared_context = mono_method_get_generic_container (declaring_method)->context;
1785 shared_context = declaring_method->klass->generic_container->context;
1787 /* Handle gsharedvt/partial sharing */
1788 if ((method != declaring_method && method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) ||
1789 is_gsharedvt || mini_is_gsharedvt_sharable_method (method)) {
1790 MonoGenericContext *context = mono_method_get_context (method);
1791 MonoGenericInst *inst;
1793 partial = mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE);
1795 gsharedvt = is_gsharedvt || (!partial && mini_is_gsharedvt_sharable_method (method));
1797 class_container = declaring_method->klass->generic_container;
1798 method_container = mono_method_get_generic_container (declaring_method);
1801 * Create the shared context by replacing the ref type arguments with
1802 * type parameters, and keeping the rest.
1805 inst = context->class_inst;
1807 inst = shared_context.class_inst;
1809 shared_context.class_inst = get_shared_inst (inst, shared_context.class_inst, class_container, all_vt, gsharedvt);
1812 inst = context->method_inst;
1814 inst = shared_context.method_inst;
1816 shared_context.method_inst = get_shared_inst (inst, shared_context.method_inst, method_container, all_vt, gsharedvt);
1821 res = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
1822 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
1825 /* The result should be an inflated method whose parent is not inflated */
1826 g_assert (!res->klass->is_inflated);
1832 mini_get_shared_method (MonoMethod *method)
1834 return mini_get_shared_method_full (method, FALSE, FALSE);
1838 mini_init_gsctx (MonoDomain *domain, MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
1840 MonoGenericInst *inst;
1843 memset (gsctx, 0, sizeof (MonoGenericSharingContext));
1845 if (context && context->class_inst) {
1846 inst = context->class_inst;
1848 gsctx->var_is_vt = mono_domain_alloc0 (domain, sizeof (gboolean) * inst->type_argc);
1850 gsctx->var_is_vt = mono_mempool_alloc0 (mp, sizeof (gboolean) * inst->type_argc);
1852 gsctx->var_is_vt = g_new0 (gboolean, inst->type_argc);
1854 for (i = 0; i < inst->type_argc; ++i) {
1855 MonoType *type = inst->type_argv [i];
1857 if (is_gsharedvt_type (type))
1858 gsctx->var_is_vt [i] = TRUE;
1861 if (context && context->method_inst) {
1862 inst = context->method_inst;
1864 gsctx->mvar_is_vt = mono_domain_alloc0 (domain, sizeof (gboolean) * inst->type_argc);
1866 gsctx->mvar_is_vt = mono_mempool_alloc0 (mp, sizeof (gboolean) * inst->type_argc);
1868 gsctx->mvar_is_vt = g_new0 (gboolean, inst->type_argc);
1870 for (i = 0; i < inst->type_argc; ++i) {
1871 MonoType *type = inst->type_argv [i];
1873 if (is_gsharedvt_type (type))
1874 gsctx->mvar_is_vt [i] = TRUE;
1880 * LOCKING: Acquires the jit code hash lock.
1883 mini_lookup_method (MonoDomain *domain, MonoMethod *method, MonoMethod *shared)
1886 static gboolean inited = FALSE;
1887 static int lookups = 0;
1888 static int failed_lookups = 0;
1890 mono_domain_jit_code_hash_lock (domain);
1891 ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
1892 if (!ji && shared) {
1893 /* Try generic sharing */
1894 ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, shared);
1895 if (ji && !ji->has_generic_jit_info)
1898 mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
1899 mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
1907 mono_domain_jit_code_hash_unlock (domain);
1913 lookup_method (MonoDomain *domain, MonoMethod *method)
1918 ji = mini_lookup_method (domain, method, NULL);
1921 if (!mono_method_is_generic_sharable (method, FALSE))
1923 shared = mini_get_shared_method (method);
1924 ji = mini_lookup_method (domain, method, shared);
1931 static FILE* perf_map_file;
1934 mono_enable_jit_map (void)
1936 if (!perf_map_file) {
1938 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
1940 perf_map_file = fopen (name, "w");
1945 mono_emit_jit_tramp (void *start, int size, const char *desc)
1948 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
1952 mono_emit_jit_map (MonoJitInfo *jinfo)
1954 if (perf_map_file) {
1955 char *name = mono_method_full_name (jinfo_get_method (jinfo), TRUE);
1956 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
1962 mono_jit_map_is_enabled (void)
1964 return perf_map_file != NULL;
1970 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex)
1972 MonoDomain *target_domain, *domain = mono_domain_get ();
1974 gpointer code = NULL, p;
1976 MonoJitICallInfo *callinfo = NULL;
1977 WrapperInfo *winfo = NULL;
1980 * ICALL wrappers are handled specially, since there is only one copy of them
1981 * shared by all appdomains.
1983 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1984 winfo = mono_marshal_get_wrapper_info (method);
1985 if (winfo && winfo->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
1986 callinfo = mono_find_jit_icall_by_addr (winfo->d.icall.func);
1987 g_assert (callinfo);
1989 /* Must be domain neutral since there is only one copy */
1990 opt |= MONO_OPT_SHARED;
1993 if (method->dynamic)
1994 opt &= ~MONO_OPT_SHARED;
1996 /* These methods can become invalid when a domain is unloaded */
1997 if (method->klass->image != mono_get_corlib () || method->is_inflated)
1998 opt &= ~MONO_OPT_SHARED;
2000 if (opt & MONO_OPT_SHARED)
2001 target_domain = mono_get_root_domain ();
2003 target_domain = domain;
2005 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
2006 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2009 if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
2010 MonoGenericContext *ctx = NULL;
2011 if (method->is_inflated)
2012 ctx = mono_method_get_context (method);
2013 method = info->d.synchronized_inner.method;
2016 method = mono_class_inflate_generic_method_checked (method, ctx, &error);
2017 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2022 info = lookup_method (target_domain, method);
2024 /* We can't use a domain specific method in another domain */
2025 if (! ((domain != target_domain) && !info->domain_neutral)) {
2027 MonoException *tmpEx;
2029 mono_jit_stats.methods_lookups++;
2030 vtable = mono_class_vtable (domain, method->klass);
2032 tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
2037 return mono_create_ftnptr (target_domain, info->code_start);
2041 #ifdef MONO_USE_AOT_COMPILER
2042 if (opt & MONO_OPT_AOT) {
2043 MonoDomain *domain = mono_domain_get ();
2045 mono_class_init (method->klass);
2047 if ((code = mono_aot_get_method (domain, method))) {
2050 vtable = mono_class_vtable (domain, method->klass);
2052 mono_runtime_class_init (vtable);
2058 code = mono_jit_compile_method_inner (method, target_domain, opt, ex);
2062 if (method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC) {
2066 * SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
2068 ji = mini_jit_info_table_find (mono_domain_get (), code, &d);
2072 p = mono_create_ftnptr (target_domain, code);
2075 /*mono_register_jit_icall_wrapper takes the loader lock, so we take it on the outside. */
2076 mono_loader_lock ();
2078 if (!callinfo->wrapper) {
2079 callinfo->wrapper = p;
2080 mono_register_jit_icall_wrapper (callinfo, p);
2083 mono_loader_unlock ();
2090 mono_jit_compile_method (MonoMethod *method)
2092 MonoException *ex = NULL;
2095 code = mono_jit_compile_method_with_opt (method, mono_get_optimizations_for_method (method, default_opt), &ex);
2098 mono_raise_exception (ex);
2104 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2106 invalidated_delegate_trampoline (char *desc)
2108 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
2109 "See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
2115 * mono_jit_free_method:
2117 * Free all memory allocated by the JIT for METHOD.
2120 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
2122 MonoJitDynamicMethodInfo *ji;
2123 gboolean destroy = TRUE;
2124 GHashTableIter iter;
2125 MonoJumpList *jlist;
2127 g_assert (method->dynamic);
2129 mono_domain_lock (domain);
2130 ji = mono_dynamic_code_hash_lookup (domain, method);
2131 mono_domain_unlock (domain);
2136 mono_debug_remove_method (method, domain);
2138 mono_domain_lock (domain);
2139 g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
2140 mono_domain_jit_code_hash_lock (domain);
2141 mono_internal_hash_table_remove (&domain->jit_code_hash, method);
2142 mono_domain_jit_code_hash_unlock (domain);
2143 g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
2144 mono_conc_hashtable_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
2146 /* Remove jump targets in this method */
2147 g_hash_table_iter_init (&iter, domain_jit_info (domain)->jump_target_hash);
2148 while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
2149 GSList *tmp, *remove;
2152 for (tmp = jlist->list; tmp; tmp = tmp->next) {
2153 guint8 *ip = tmp->data;
2155 if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
2156 remove = g_slist_prepend (remove, tmp);
2158 for (tmp = remove; tmp; tmp = tmp->next) {
2159 jlist->list = g_slist_delete_link (jlist->list, tmp->data);
2161 g_slist_free (remove);
2164 mono_domain_unlock (domain);
2166 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2167 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
2169 * Instead of freeing the code, change it to call an error routine
2170 * so people can fix their code.
2172 char *type = mono_type_full_name (&method->klass->byval_arg);
2173 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
2176 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
2182 * This needs to be done before freeing code_mp, since the code address is the
2183 * key in the table, so if we free the code_mp first, another thread can grab the
2184 * same code address and replace our entry in the table.
2186 mono_jit_info_table_remove (domain, ji->ji);
2189 mono_code_manager_destroy (ji->code_mp);
2194 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
2196 MonoDomain *target_domain;
2199 if (default_opt & MONO_OPT_SHARED)
2200 target_domain = mono_get_root_domain ();
2202 target_domain = domain;
2204 info = lookup_method (target_domain, method);
2206 /* We can't use a domain specific method in another domain */
2207 if (! ((domain != target_domain) && !info->domain_neutral)) {
2208 mono_jit_stats.methods_lookups++;
2211 return info->code_start;
2220 gboolean mono_do_single_method_regression = FALSE;
2221 guint32 mono_single_method_regression_opt = 0;
2222 MonoMethod *mono_current_single_method;
2223 GSList *mono_single_method_list;
2224 GHashTable *mono_single_method_hash;
2227 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt)
2231 if (!mono_do_single_method_regression)
2233 if (!mono_current_single_method) {
2234 if (!mono_single_method_hash)
2235 mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
2236 if (!g_hash_table_lookup (mono_single_method_hash, method)) {
2237 g_hash_table_insert (mono_single_method_hash, method, method);
2238 mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
2242 if (method == mono_current_single_method)
2243 return mono_single_method_regression_opt;
2248 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
2250 return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
2255 gpointer compiled_method;
2256 gpointer runtime_invoke;
2258 MonoDynCallInfo *dyn_call_info;
2259 MonoClass *ret_box_class;
2260 } RuntimeInvokeInfo;
2263 * mono_jit_runtime_invoke:
2264 * @method: the method to invoke
2265 * @obj: this pointer
2266 * @params: array of parameter values.
2267 * @exc: used to catch exceptions objects
2270 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
2272 MonoMethod *invoke, *callee;
2273 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
2274 MonoDomain *domain = mono_domain_get ();
2275 MonoJitDomainInfo *domain_info;
2276 RuntimeInvokeInfo *info, *info2;
2278 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
2279 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
2283 domain_info = domain_jit_info (domain);
2285 info = mono_conc_hashtable_lookup (domain_info->runtime_invoke_hash, method);
2288 if (mono_security_core_clr_enabled ()) {
2290 * This might be redundant since mono_class_vtable () already does this,
2291 * but keep it just in case for moonlight.
2293 mono_class_setup_vtable (method->klass);
2294 if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
2296 *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
2298 mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
2303 info = g_new0 (RuntimeInvokeInfo, 1);
2305 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
2306 info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
2307 g_assert (info->vtable);
2310 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
2311 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
2313 * Array Get/Set/Address methods. The JIT implements them using inline code
2314 * inside the runtime invoke wrappers, so no need to compile them.
2316 if (mono_aot_only) {
2318 * Call a wrapper, since the runtime invoke wrapper was not generated.
2320 MonoMethod *wrapper;
2322 wrapper = mono_marshal_get_array_accessor_wrapper (method);
2323 invoke = mono_marshal_get_runtime_invoke (wrapper, FALSE);
2331 MonoException *jit_ex = NULL;
2333 info->compiled_method = mono_jit_compile_method_with_opt (callee, mono_get_optimizations_for_method (callee, default_opt), &jit_ex);
2334 if (!info->compiled_method) {
2338 *exc = (MonoObject*)jit_ex;
2341 mono_raise_exception (jit_ex);
2345 info->compiled_method = mini_add_method_trampoline (NULL, callee, info->compiled_method, mono_method_needs_static_rgctx_invoke (callee, FALSE), FALSE);
2347 info->compiled_method = NULL;
2351 * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
2352 * in full-aot mode, so we use a slower, but more generic wrapper if
2353 * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
2355 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2356 if (mono_aot_only || debug_options.dyn_runtime_invoke) {
2358 MonoMethodSignature *sig = mono_method_signature (method);
2359 gboolean supported = TRUE;
2362 if (method->string_ctor)
2363 sig = mono_marshal_get_string_ctor_signature (method);
2365 for (i = 0; i < sig->param_count; ++i) {
2366 MonoType *t = sig->params [i];
2368 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
2372 if (mono_class_is_contextbound (method->klass) || !info->compiled_method)
2376 info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
2378 ret_type = sig->ret;
2379 if (info->dyn_call_info) {
2380 switch (ret_type->type) {
2381 case MONO_TYPE_VOID:
2393 case MONO_TYPE_BOOLEAN:
2394 case MONO_TYPE_CHAR:
2397 info->ret_box_class = mono_class_from_mono_type (ret_type);
2400 info->ret_box_class = mono_defaults.int_class;
2402 case MONO_TYPE_STRING:
2403 case MONO_TYPE_CLASS:
2404 case MONO_TYPE_ARRAY:
2405 case MONO_TYPE_SZARRAY:
2406 case MONO_TYPE_OBJECT:
2408 case MONO_TYPE_GENERICINST:
2409 if (!MONO_TYPE_IS_REFERENCE (ret_type))
2410 info->ret_box_class = mono_class_from_mono_type (ret_type);
2412 case MONO_TYPE_VALUETYPE:
2413 info->ret_box_class = mono_class_from_mono_type (ret_type);
2416 g_assert_not_reached ();
2423 if (!info->dyn_call_info)
2424 info->runtime_invoke = mono_jit_compile_method (invoke);
2426 info2 = mono_conc_hashtable_insert (domain_info->runtime_invoke_hash, method, info);
2433 runtime_invoke = info->runtime_invoke;
2436 * We need this here because mono_marshal_get_runtime_invoke can place
2437 * the helper method in System.Object and not the target class.
2440 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
2444 mono_runtime_class_init (info->vtable);
2447 /* The wrappers expect this to be initialized to NULL */
2451 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2452 if (info->dyn_call_info) {
2453 MonoMethodSignature *sig = mono_method_signature (method);
2455 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
2458 guint8 retval [256];
2460 if (!dyn_runtime_invoke) {
2461 invoke = mono_marshal_get_runtime_invoke_dynamic ();
2462 dyn_runtime_invoke = mono_jit_compile_method (invoke);
2465 /* Convert the arguments to the format expected by start_dyn_call () */
2466 args = g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
2469 args [pindex ++] = &obj;
2470 for (i = 0; i < sig->param_count; ++i) {
2471 MonoType *t = sig->params [i];
2474 args [pindex ++] = ¶ms [i];
2475 } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
2476 args [pindex ++] = ¶ms [i];
2478 args [pindex ++] = params [i];
2482 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
2484 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
2486 dyn_runtime_invoke (buf, exc, info->compiled_method);
2488 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
2490 if (info->ret_box_class)
2491 return mono_value_box (domain, info->ret_box_class, retval);
2493 return *(MonoObject**)retval;
2497 return runtime_invoke (obj, params, exc, info->compiled_method);
2500 MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
2502 MonoException *exc = NULL;
2504 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2505 MONO_SIG_HANDLER_GET_CONTEXT;
2507 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
2509 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
2510 if (mono_arch_is_int_overflow (ctx, info))
2512 * The spec says this throws ArithmeticException, but MS throws the derived
2513 * OverflowException.
2515 exc = mono_get_exception_overflow ();
2517 exc = mono_get_exception_divide_by_zero ();
2519 exc = mono_get_exception_divide_by_zero ();
2523 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2526 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2527 if (mono_do_crash_chaining) {
2528 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2533 mono_arch_handle_exception (ctx, exc);
2536 MONO_SIG_HANDLER_FUNC (, mono_sigill_signal_handler)
2539 MONO_SIG_HANDLER_GET_CONTEXT;
2541 exc = mono_get_exception_execution_engine ("SIGILL");
2543 mono_arch_handle_exception (ctx, exc);
2546 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
2547 #define HAVE_SIG_INFO
2550 MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
2553 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
2554 gpointer fault_addr = NULL;
2555 #ifdef HAVE_SIG_INFO
2556 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2560 MONO_SIG_HANDLER_GET_CONTEXT;
2562 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
2563 if (mono_arch_is_single_step_event (info, ctx)) {
2564 mono_debugger_agent_single_step_event (ctx);
2566 } else if (mono_arch_is_breakpoint_event (info, ctx)) {
2567 mono_debugger_agent_breakpoint_hit (ctx);
2572 #if defined(HAVE_SIG_INFO)
2573 #if !defined(HOST_WIN32)
2574 fault_addr = info->si_addr;
2575 if (mono_aot_is_pagefault (info->si_addr)) {
2576 mono_aot_handle_pagefault (info->si_addr);
2581 /* The thread might no be registered with the runtime */
2582 if (!mono_domain_get () || !jit_tls) {
2583 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2585 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2586 if (mono_do_crash_chaining) {
2587 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2593 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
2595 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2596 if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
2599 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2600 /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
2601 fault_addr = info->si_addr;
2602 if (fault_addr == NULL) {
2605 mono_sigctx_to_monoctx (ctx, &mctx);
2607 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
2611 if (jit_tls->stack_size &&
2612 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
2614 * The hard-guard page has been hit: there is not much we can do anymore
2615 * Print a hopefully clear message and abort.
2617 mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
2618 g_assert_not_reached ();
2620 /* The original handler might not like that it is executed on an altstack... */
2621 if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2624 mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
2629 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2632 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2634 if (mono_do_crash_chaining) {
2635 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2640 mono_arch_handle_exception (ctx, NULL);
2644 MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
2647 MONO_SIG_HANDLER_GET_CONTEXT;
2649 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
2651 mono_arch_handle_exception (ctx, exc);
2654 #ifndef DISABLE_REMOTING
2655 /* mono_jit_create_remoting_trampoline:
2656 * @method: pointer to the method info
2658 * Creates a trampoline which calls the remoting functions. This
2659 * is used in the vtable of transparent proxies.
2661 * Returns: a pointer to the newly created code
2664 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
2667 guint8 *addr = NULL;
2669 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
2670 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
2674 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
2675 (mono_method_signature (method)->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))) {
2676 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
2677 addr = mono_compile_method (nm);
2680 addr = mono_compile_method (method);
2682 return mono_get_addr_from_ftnptr (addr);
2686 static gpointer *vtable_trampolines;
2687 static int vtable_trampolines_size;
2690 mini_get_vtable_trampoline (int slot_index)
2692 int index = slot_index + MONO_IMT_SIZE;
2694 g_assert (slot_index >= - MONO_IMT_SIZE);
2695 if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
2697 if (!vtable_trampolines || index >= vtable_trampolines_size) {
2701 new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
2702 while (new_size <= index)
2704 new_table = g_new0 (gpointer, new_size);
2706 if (vtable_trampolines)
2707 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
2708 g_free (vtable_trampolines);
2709 mono_memory_barrier ();
2710 vtable_trampolines = new_table;
2711 vtable_trampolines_size = new_size;
2716 if (!vtable_trampolines [index])
2717 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
2718 return vtable_trampolines [index];
2722 mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
2724 gboolean is_virtual_generic, is_interface, load_imt_reg;
2727 static guint8 **cache = NULL;
2728 static int cache_size = 0;
2733 /* FIXME Support more cases */
2737 if (MONO_TYPE_ISSTRUCT (sig->ret))
2740 is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
2741 is_interface = method->klass->flags & TYPE_ATTRIBUTE_INTERFACE ? TRUE : FALSE;
2742 load_imt_reg = is_virtual_generic || is_interface;
2744 if (is_interface && !is_virtual_generic)
2745 offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2747 offset = G_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2749 idx = (offset / SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
2750 g_assert (idx >= 0);
2752 /* Resize the cache to idx + 1 */
2753 if (cache_size < idx + 1) {
2755 if (cache_size < idx + 1) {
2757 int new_cache_size = idx + 1;
2759 new_cache = g_new0 (guint8*, new_cache_size);
2761 memcpy (new_cache, cache, cache_size * sizeof (guint8*));
2764 mono_memory_barrier ();
2766 cache_size = new_cache_size;
2774 return cache [idx] = mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
2778 mini_get_imt_trampoline (int slot_index)
2780 return mini_get_vtable_trampoline (slot_index - MONO_IMT_SIZE);
2784 mini_parse_debug_options (void)
2786 const char *options = g_getenv ("MONO_DEBUG");
2787 gchar **args, **ptr;
2792 args = g_strsplit (options, ",", -1);
2794 for (ptr = args; ptr && *ptr; ptr++) {
2795 const char *arg = *ptr;
2797 if (!strcmp (arg, "handle-sigint"))
2798 debug_options.handle_sigint = TRUE;
2799 else if (!strcmp (arg, "keep-delegates"))
2800 debug_options.keep_delegates = TRUE;
2801 else if (!strcmp (arg, "reverse-pinvoke-exceptions"))
2802 debug_options.reverse_pinvoke_exceptions = TRUE;
2803 else if (!strcmp (arg, "collect-pagefault-stats"))
2804 debug_options.collect_pagefault_stats = TRUE;
2805 else if (!strcmp (arg, "break-on-unverified"))
2806 debug_options.break_on_unverified = TRUE;
2807 else if (!strcmp (arg, "no-gdb-backtrace"))
2808 debug_options.no_gdb_backtrace = TRUE;
2809 else if (!strcmp (arg, "suspend-on-sigsegv"))
2810 debug_options.suspend_on_sigsegv = TRUE;
2811 else if (!strcmp (arg, "suspend-on-exception"))
2812 debug_options.suspend_on_exception = TRUE;
2813 else if (!strcmp (arg, "suspend-on-unhandled"))
2814 debug_options.suspend_on_unhandled = TRUE;
2815 else if (!strcmp (arg, "dont-free-domains"))
2816 mono_dont_free_domains = TRUE;
2817 else if (!strcmp (arg, "dyn-runtime-invoke"))
2818 debug_options.dyn_runtime_invoke = TRUE;
2819 else if (!strcmp (arg, "gdb"))
2820 debug_options.gdb = TRUE;
2821 else if (!strcmp (arg, "explicit-null-checks"))
2822 debug_options.explicit_null_checks = TRUE;
2823 else if (!strcmp (arg, "gen-seq-points"))
2824 debug_options.gen_seq_points_debug_data = TRUE;
2825 else if (!strcmp (arg, "gen-compact-seq-points"))
2826 debug_options.gen_seq_points_compact_data = TRUE;
2827 else if (!strcmp (arg, "init-stacks"))
2828 debug_options.init_stacks = TRUE;
2829 else if (!strcmp (arg, "casts"))
2830 debug_options.better_cast_details = TRUE;
2831 else if (!strcmp (arg, "soft-breakpoints"))
2832 debug_options.soft_breakpoints = TRUE;
2833 else if (!strcmp (arg, "check-pinvoke-callconv"))
2834 debug_options.check_pinvoke_callconv = TRUE;
2835 else if (!strcmp (arg, "debug-domain-unload"))
2836 mono_enable_debug_domain_unload (TRUE);
2838 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
2839 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains', 'suspend-on-sigsegv', 'suspend-on-exception', 'suspend-on-unhandled', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks', 'check-pinvoke-callconv', 'debug-domain-unload'\n");
2848 mini_get_debug_options (void)
2850 return &debug_options;
2854 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
2856 #if !defined(__ia64__) && (!defined(__ppc64__) && !defined(__powerpc64__) || _CALL_ELF == 2)
2859 gpointer* desc = NULL;
2861 if ((desc = g_hash_table_lookup (domain->ftnptrs_hash, addr)))
2864 desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
2868 # elif defined(__ppc64__) || defined(__powerpc64__)
2870 desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
2876 g_hash_table_insert (domain->ftnptrs_hash, addr, desc);
2882 mini_get_addr_from_ftnptr (gpointer descr)
2884 #if defined(__ia64__) || ((defined(__ppc64__) || defined(__powerpc64__)) && _CALL_ELF != 2)
2885 return *(gpointer*)descr;
2892 register_jit_stats (void)
2894 mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
2895 mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
2896 mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
2897 mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
2898 mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
2899 mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks);
2900 mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks);
2901 mono_counters_register ("Allocated vars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocate_var);
2902 mono_counters_register ("Code reallocs", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.code_reallocs);
2903 mono_counters_register ("Allocated code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_code_size);
2904 mono_counters_register ("Allocated seq points size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_seq_points_size);
2905 mono_counters_register ("Inlineable methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlineable_methods);
2906 mono_counters_register ("Inlined methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlined_methods);
2907 mono_counters_register ("Regvars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.regvars);
2908 mono_counters_register ("Locals stack size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.locals_stack_size);
2909 mono_counters_register ("Method cache lookups", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_lookups);
2910 mono_counters_register ("Compiled CIL code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.cil_code_size);
2911 mono_counters_register ("Native code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.native_code_size);
2912 mono_counters_register ("Aliases found", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_found);
2913 mono_counters_register ("Aliases eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_removed);
2914 mono_counters_register ("Aliased loads eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.loads_eliminated);
2915 mono_counters_register ("Aliased stores eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.stores_eliminated);
2918 static void runtime_invoke_info_free (gpointer value);
2921 class_method_pair_equal (gconstpointer ka, gconstpointer kb)
2923 const MonoClassMethodPair *apair = ka;
2924 const MonoClassMethodPair *bpair = kb;
2926 return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
2930 class_method_pair_hash (gconstpointer data)
2932 const MonoClassMethodPair *pair = data;
2934 return (gsize)pair->klass ^ (gsize)pair->method;
2938 mini_create_jit_domain_info (MonoDomain *domain)
2940 MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
2942 info->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2943 info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2944 info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2945 info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
2946 info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2947 info->runtime_invoke_hash = mono_conc_hashtable_new_full (&domain->lock, mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
2948 info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, seq_point_info_free);
2949 info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
2950 info->jump_target_hash = g_hash_table_new (NULL, NULL);
2952 domain->runtime_info = info;
2956 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
2958 MonoJumpList *jlist = value;
2959 g_slist_free (jlist->list);
2963 delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
2965 GSList *list = value;
2966 g_slist_free (list);
2970 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
2972 MonoJitDynamicMethodInfo *di = value;
2973 mono_code_manager_destroy (di->code_mp);
2978 runtime_invoke_info_free (gpointer value)
2980 RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
2982 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2983 if (info->dyn_call_info)
2984 mono_arch_dyn_call_free (info->dyn_call_info);
2990 mini_free_jit_domain_info (MonoDomain *domain)
2992 MonoJitDomainInfo *info = domain_jit_info (domain);
2994 g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
2995 g_hash_table_destroy (info->jump_target_hash);
2996 if (info->jump_target_got_slot_hash) {
2997 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
2998 g_hash_table_destroy (info->jump_target_got_slot_hash);
3000 if (info->dynamic_code_hash) {
3001 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
3002 g_hash_table_destroy (info->dynamic_code_hash);
3004 if (info->method_code_hash)
3005 g_hash_table_destroy (info->method_code_hash);
3006 g_hash_table_destroy (info->class_init_trampoline_hash);
3007 g_hash_table_destroy (info->jump_trampoline_hash);
3008 g_hash_table_destroy (info->jit_trampoline_hash);
3009 g_hash_table_destroy (info->delegate_trampoline_hash);
3010 if (info->static_rgctx_trampoline_hash)
3011 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
3012 g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
3013 mono_conc_hashtable_destroy (info->runtime_invoke_hash);
3014 g_hash_table_destroy (info->seq_points);
3015 g_hash_table_destroy (info->arch_seq_points);
3016 if (info->agent_info)
3017 mono_debugger_agent_free_domain_info (domain);
3018 if (info->gsharedvt_arg_tramp_hash)
3019 g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
3021 mono_llvm_free_domain_info (domain);
3024 g_free (domain->runtime_info);
3025 domain->runtime_info = NULL;
3030 llvm_init_inner (void)
3032 if (!mono_llvm_load (NULL))
3043 * Load and initialize LLVM support.
3044 * Return TRUE on success.
3047 mini_llvm_init (void)
3050 static gboolean llvm_inited;
3051 static gboolean init_result;
3053 mono_loader_lock_if_inited ();
3055 init_result = llvm_init_inner ();
3058 mono_loader_unlock_if_inited ();
3066 mini_init (const char *filename, const char *runtime_version)
3069 MonoRuntimeCallbacks callbacks;
3070 MonoThreadInfoRuntimeCallbacks ticallbacks;
3072 MONO_VES_INIT_BEGIN ();
3074 #if defined(__linux__) && !defined(__native_client__)
3075 if (access ("/proc/self/maps", F_OK) != 0) {
3076 g_print ("Mono requires /proc to be mounted.\n");
3081 mono_mutex_init_recursive (&jit_mutex);
3083 mono_cross_helpers_run ();
3087 /* Happens when using the embedding interface */
3088 if (!default_opt_set)
3089 default_opt = mono_parse_default_optimizations (NULL);
3091 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3093 mono_set_generic_sharing_vt_supported (TRUE);
3096 #ifdef MONO_HAVE_FAST_TLS
3097 MONO_FAST_TLS_INIT (mono_jit_tls);
3098 MONO_FAST_TLS_INIT (mono_lmf_addr);
3099 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
3100 MONO_FAST_TLS_INIT (mono_lmf);
3104 mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
3106 if (!global_codeman)
3107 global_codeman = mono_code_manager_new ();
3109 memset (&callbacks, 0, sizeof (callbacks));
3110 callbacks.create_ftnptr = mini_create_ftnptr;
3111 callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
3112 callbacks.get_runtime_build_info = mono_get_runtime_build_info;
3113 callbacks.set_cast_details = mono_set_cast_details;
3114 callbacks.debug_log = mono_debugger_agent_debug_log;
3115 callbacks.debug_log_is_enabled = mono_debugger_agent_debug_log_is_enabled;
3116 callbacks.tls_key_supported = mini_tls_key_supported;
3119 callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
3120 callbacks.get_imt_trampoline = mini_get_imt_trampoline;
3123 mono_install_callbacks (&callbacks);
3125 memset (&ticallbacks, 0, sizeof (ticallbacks));
3126 ticallbacks.setup_async_callback = mono_setup_async_callback;
3127 ticallbacks.thread_state_init_from_sigctx = mono_thread_state_init_from_sigctx;
3128 ticallbacks.thread_state_init_from_handle = mono_thread_state_init_from_handle;
3130 mono_counters_init ();
3132 mono_threads_runtime_init (&ticallbacks);
3134 if (g_getenv ("MONO_DEBUG") != NULL)
3135 mini_parse_debug_options ();
3137 mono_code_manager_init ();
3141 mono_arch_cpu_init ();
3145 mono_unwind_init ();
3147 if (g_getenv ("MONO_XDEBUG")) {
3148 const char *xdebug_opts = g_getenv ("MONO_XDEBUG");
3149 mono_xdebug_init (xdebug_opts);
3150 /* So methods for multiple domains don't have the same address */
3151 mono_dont_free_domains = TRUE;
3152 mono_using_xdebug = TRUE;
3153 } else if (mini_get_debug_options ()->gdb) {
3154 mono_xdebug_init ((char*)"gdb");
3155 mono_dont_free_domains = TRUE;
3156 mono_using_xdebug = TRUE;
3160 if (mono_use_llvm) {
3161 if (!mono_llvm_load (NULL)) {
3162 mono_use_llvm = FALSE;
3163 fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
3170 mono_trampolines_init ();
3172 mono_native_tls_alloc (&mono_jit_tls_id, NULL);
3174 if (default_opt & MONO_OPT_AOT)
3177 mono_debugger_agent_init ();
3179 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3180 mono_set_generic_sharing_supported (TRUE);
3183 #ifndef MONO_CROSS_COMPILE
3184 mono_runtime_install_handlers ();
3186 mono_threads_install_cleanup (mini_thread_cleanup);
3188 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
3189 check_for_pending_exc = FALSE;
3190 mono_threads_install_notify_pending_exc ((MonoThreadNotifyPendingExcFunc)mono_arch_notify_pending_exc);
3193 #define JIT_TRAMPOLINES_WORK
3194 #ifdef JIT_TRAMPOLINES_WORK
3195 mono_install_compile_method (mono_jit_compile_method);
3196 mono_install_free_method (mono_jit_free_method);
3197 mono_install_trampoline (mono_create_jit_trampoline);
3198 mono_install_jump_trampoline (mono_create_jump_trampoline);
3199 #ifndef DISABLE_REMOTING
3200 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
3202 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
3203 mono_install_create_domain_hook (mini_create_jit_domain_info);
3204 mono_install_free_domain_hook (mini_free_jit_domain_info);
3206 #define JIT_INVOKE_WORKS
3207 #ifdef JIT_INVOKE_WORKS
3208 mono_install_runtime_invoke (mono_jit_runtime_invoke);
3210 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
3211 mono_install_get_class_from_name (mono_aot_get_class_from_name);
3212 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
3214 if (debug_options.collect_pagefault_stats)
3215 mono_aot_set_make_unreadable (TRUE);
3217 if (runtime_version)
3218 domain = mono_init_version (filename, runtime_version);
3220 domain = mono_init_from_assembly (filename, filename);
3222 if (mono_aot_only) {
3223 /* This helps catch code allocation requests */
3224 mono_code_manager_set_read_only (domain->code_mp);
3225 mono_marshal_use_aot_wrappers (TRUE);
3230 mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
3232 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
3235 /*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
3236 mono_arch_finish_init ();
3240 /* This must come after mono_init () in the aot-only case */
3241 mono_exceptions_init ();
3243 /* This should come after mono_init () too */
3247 mono_create_helper_signatures ();
3250 register_jit_stats ();
3252 #define JIT_CALLS_WORK
3253 #ifdef JIT_CALLS_WORK
3254 /* Needs to be called here since register_jit_icall depends on it */
3255 mono_marshal_init ();
3257 mono_arch_register_lowlevel_calls ();
3261 mono_generic_sharing_init ();
3264 #ifdef MONO_ARCH_SIMD_INTRINSICS
3265 mono_simd_intrinsics_init ();
3268 #if MONO_SUPPORT_TASKLETS
3269 mono_tasklets_init ();
3272 if (mono_compile_aot)
3274 * Avoid running managed code when AOT compiling, since the platform
3275 * might only support aot-only execution.
3277 mono_runtime_set_no_exec (TRUE);
3279 #define JIT_RUNTIME_WORKS
3280 #ifdef JIT_RUNTIME_WORKS
3281 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
3282 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
3283 mono_thread_attach (domain);
3286 mono_profiler_runtime_initialized ();
3288 MONO_VES_INIT_END ();
3294 register_icalls (void)
3296 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
3297 ves_icall_get_frame_info);
3298 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
3299 ves_icall_get_trace);
3300 mono_add_internal_call ("System.Exception::get_trace",
3301 ves_icall_System_Exception_get_trace);
3302 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
3303 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
3304 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
3305 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
3306 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
3307 mono_runtime_install_handlers);
3309 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
3310 mono_add_internal_call ("System.Diagnostics.Debugger::Mono_UnhandledException_internal",
3311 mono_debugger_agent_unhandled_exception);
3315 * It's important that we pass `TRUE` as the last argument here, as
3316 * it causes the JIT to omit a wrapper for these icalls. If the JIT
3317 * *did* emit a wrapper, we'd be looking at infinite recursion since
3318 * the wrapper would call the icall which would call the wrapper and
3321 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", "void ptr", TRUE);
3322 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", "void ptr", TRUE);
3324 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
3325 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
3326 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
3327 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr", TRUE);
3328 register_icall (mono_jit_set_domain, "mono_jit_set_domain", "void ptr", TRUE);
3329 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
3331 register_dyn_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
3332 register_dyn_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
3333 register_dyn_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", "void ptr", TRUE);
3334 register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
3335 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "object", FALSE);
3336 register_icall (mono_thread_force_interruption_checkpoint_noraise, "mono_thread_force_interruption_checkpoint_noraise", "object", FALSE);
3337 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
3338 #ifndef DISABLE_REMOTING
3339 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
3340 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
3343 #if defined(__native_client__) || defined(__native_client_codegen__)
3344 register_icall (mono_nacl_gc, "mono_nacl_gc", "void", TRUE);
3346 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
3347 register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, "mono_llmult", TRUE);
3348 register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, "mono_lldiv", FALSE);
3349 register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, "mono_lldiv_un", FALSE);
3350 register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, "mono_llrem", FALSE);
3351 register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, "mono_llrem_un", FALSE);
3353 #if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
3354 register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, "mono_llmult_ovf_un", FALSE);
3355 register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, "mono_llmult_ovf", FALSE);
3358 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
3359 register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, "mono_lshl", TRUE);
3360 register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, "mono_lshr", TRUE);
3361 register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, "mono_lshr_un", TRUE);
3364 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
3365 register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, "mono_idiv", FALSE);
3366 register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, "mono_idiv_un", FALSE);
3367 register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, "mono_irem", FALSE);
3368 register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, "mono_irem_un", FALSE);
3371 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3372 register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, "mono_imul", TRUE);
3375 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
3376 register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, "mono_imul_ovf", FALSE);
3377 register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, "mono_imul_ovf_un", FALSE);
3380 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
3381 if (ARCH_EMULATE_MUL_DIV || mono_arch_is_soft_float ()) {
3382 register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, "mono_fdiv", FALSE);
3386 register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, "mono_fconv_u8", FALSE);
3387 register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, "mono_fconv_u4", FALSE);
3388 register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, "mono_fconv_ovf_i8", FALSE);
3389 register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, "mono_fconv_ovf_u8", FALSE);
3390 register_opcode_emulation (OP_RCONV_TO_OVF_I8, "__emul_rconv_to_ovf_i8", "long float", mono_rconv_ovf_i8, "mono_rconv_ovf_i8", FALSE);
3391 register_opcode_emulation (OP_RCONV_TO_OVF_U8, "__emul_rconv_to_ovf_u8", "ulong float", mono_rconv_ovf_u8, "mono_rconv_ovf_u8", FALSE);
3393 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
3394 register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, "mono_fconv_i8", FALSE);
3395 register_opcode_emulation (OP_RCONV_TO_I8, "__emul_rconv_to_i8", "long float", mono_rconv_i8, "mono_rconv_i8", FALSE);
3397 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
3398 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);
3400 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
3401 register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, "mono_lconv_to_r8", FALSE);
3403 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
3404 register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, "mono_lconv_to_r4", FALSE);
3406 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
3407 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);
3409 #ifdef MONO_ARCH_EMULATE_FREM
3410 #if defined(__default_codegen__)
3411 register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, "fmod", FALSE);
3412 #elif defined(__native_client_codegen__)
3413 register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, "mono_fmod", FALSE);
3417 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3418 if (mono_arch_is_soft_float ()) {
3419 register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, "mono_fsub", FALSE);
3420 register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, "mono_fadd", FALSE);
3421 register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, "mono_fmul", FALSE);
3422 register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, "mono_fneg", FALSE);
3423 register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, "mono_conv_to_r8", FALSE);
3424 register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, "mono_conv_to_r4", FALSE);
3425 register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, "mono_fconv_r4", FALSE);
3426 register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, "mono_fconv_i1", FALSE);
3427 register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, "mono_fconv_i2", FALSE);
3428 register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3429 register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, "mono_fconv_u1", FALSE);
3430 register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, "mono_fconv_u2", FALSE);
3432 #if SIZEOF_VOID_P == 4
3433 register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3436 register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, "mono_fcmp_eq", FALSE);
3437 register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, "mono_fcmp_lt", FALSE);
3438 register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, "mono_fcmp_gt", FALSE);
3439 register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, "mono_fcmp_le", FALSE);
3440 register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, "mono_fcmp_ge", FALSE);
3441 register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, "mono_fcmp_ne_un", FALSE);
3442 register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, "mono_fcmp_lt_un", FALSE);
3443 register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, "mono_fcmp_gt_un", FALSE);
3444 register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, "mono_fcmp_le_un", FALSE);
3445 register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, "mono_fcmp_ge_un", FALSE);
3447 register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, "mono_fceq", FALSE);
3448 register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, "mono_fcgt", FALSE);
3449 register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, "mono_fcgt_un", FALSE);
3450 register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, "mono_fclt", FALSE);
3451 register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, "mono_fclt_un", FALSE);
3453 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
3454 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
3455 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
3456 register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
3460 #ifdef COMPRESSED_INTERFACE_BITMAP
3461 register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
3464 #if SIZEOF_REGISTER == 4
3465 register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, "mono_fconv_u4", TRUE);
3467 register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "ulong double", mono_fconv_u8, "mono_fconv_u8", TRUE);
3470 /* other jit icalls */
3471 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
3472 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
3473 "ptr ptr ptr", FALSE);
3474 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
3475 register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
3476 "ptr ptr ptr ptr", FALSE);
3477 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
3478 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
3479 register_icall (mono_helper_stelem_ref_check, "mono_helper_stelem_ref_check", "void object object", FALSE);
3480 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
3481 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
3482 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
3483 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
3484 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
3485 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
3486 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
3487 register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
3488 register_icall (mono_helper_compile_generic_method, "mono_helper_compile_generic_method", "ptr object ptr ptr", FALSE);
3489 register_icall (mono_helper_ldstr, "mono_helper_ldstr", "object ptr int", FALSE);
3490 register_icall (mono_helper_ldstr_mscorlib, "mono_helper_ldstr_mscorlib", "object int", FALSE);
3491 register_icall (mono_helper_newobj_mscorlib, "mono_helper_newobj_mscorlib", "object int", FALSE);
3492 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
3493 register_icall (mono_object_castclass_unbox, "mono_object_castclass_unbox", "object object ptr", FALSE);
3494 register_icall (mono_break, "mono_break", NULL, TRUE);
3495 register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
3496 register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
3497 register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
3498 register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
3499 register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
3500 register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
3501 register_icall (mono_array_new_4, "mono_array_new_4", "object ptr int int int int", FALSE);
3502 register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
3503 register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
3504 register_icall (mono_gsharedvt_constrained_call, "mono_gsharedvt_constrained_call", "object ptr ptr ptr ptr ptr", FALSE);
3505 register_icall (mono_gsharedvt_value_copy, "mono_gsharedvt_value_copy", "void ptr ptr ptr", TRUE);
3507 register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
3509 register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
3510 register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
3512 register_icall (mono_debugger_agent_user_break, "mono_debugger_agent_user_break", "void", FALSE);
3515 register_icall (pthread_getspecific, "pthread_getspecific", "ptr ptr", TRUE);
3519 MonoJitStats mono_jit_stats = {0};
3522 print_jit_stats (void)
3524 if (mono_jit_stats.enabled) {
3525 g_print ("Mono Jit statistics\n");
3526 g_print ("Max code size ratio: %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
3527 mono_jit_stats.max_ratio_method);
3528 g_print ("Biggest method: %ld (%s)\n", mono_jit_stats.biggest_method_size,
3529 mono_jit_stats.biggest_method);
3531 g_print ("Delegates created: %ld\n", mono_stats.delegate_creations);
3532 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
3533 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
3534 g_print ("Generic vtables: %ld\n", mono_stats.generic_vtable_count);
3535 g_print ("Methods: %ld\n", mono_stats.method_count);
3536 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
3537 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
3538 g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
3540 g_print ("\nInitialized classes: %ld\n", mono_stats.generic_class_count);
3541 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
3542 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
3544 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
3545 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
3546 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
3547 g_print ("Shared vtype generic methods: %ld\n", mono_stats.gsharedvt_methods);
3549 g_print ("IMT tables size: %ld\n", mono_stats.imt_tables_size);
3550 g_print ("IMT number of tables: %ld\n", mono_stats.imt_number_of_tables);
3551 g_print ("IMT number of methods: %ld\n", mono_stats.imt_number_of_methods);
3552 g_print ("IMT used slots: %ld\n", mono_stats.imt_used_slots);
3553 g_print ("IMT colliding slots: %ld\n", mono_stats.imt_slots_with_collisions);
3554 g_print ("IMT max collisions: %ld\n", mono_stats.imt_max_collisions_in_slot);
3555 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
3556 g_print ("IMT thunks size: %ld\n", mono_stats.imt_thunks_size);
3558 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
3559 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
3560 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
3562 if (mono_security_cas_enabled ()) {
3563 g_print ("\nDecl security check : %ld\n", mono_jit_stats.cas_declsec_check);
3564 g_print ("LinkDemand (user) : %ld\n", mono_jit_stats.cas_linkdemand);
3565 g_print ("LinkDemand (icall) : %ld\n", mono_jit_stats.cas_linkdemand_icall);
3566 g_print ("LinkDemand (pinvoke) : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
3567 g_print ("LinkDemand (aptc) : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
3568 g_print ("Demand (code gen) : %ld\n", mono_jit_stats.cas_demand_generation);
3571 g_free (mono_jit_stats.max_ratio_method);
3572 mono_jit_stats.max_ratio_method = NULL;
3573 g_free (mono_jit_stats.biggest_method);
3574 mono_jit_stats.biggest_method = NULL;
3579 mini_cleanup (MonoDomain *domain)
3581 mono_runtime_shutdown_stat_profiler ();
3584 cominterop_release_all_rcws ();
3587 #ifndef MONO_CROSS_COMPILE
3589 * mono_domain_finalize () needs to be called early since it needs the
3590 * execution engine still fully working (it may invoke managed finalizers).
3592 mono_domain_finalize (domain, 2000);
3595 /* This accesses metadata so needs to be called before runtime shutdown */
3598 mono_profiler_shutdown ();
3600 #ifndef MONO_CROSS_COMPILE
3601 mono_runtime_cleanup (domain);
3604 free_jit_tls_data (mono_native_tls_get_value (mono_jit_tls_id));
3606 mono_icall_cleanup ();
3608 mono_runtime_cleanup_handlers ();
3610 #ifndef MONO_CROSS_COMPILE
3611 mono_domain_free (domain, TRUE);
3616 mono_llvm_cleanup ();
3619 mono_aot_cleanup ();
3621 mono_trampolines_cleanup ();
3623 mono_unwind_cleanup ();
3625 mono_code_manager_destroy (global_codeman);
3626 g_free (vtable_trampolines);
3628 mini_jit_cleanup ();
3630 mono_tramp_info_cleanup ();
3632 mono_arch_cleanup ();
3634 mono_generic_sharing_cleanup ();
3638 mono_trace_cleanup ();
3640 mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, stdout);
3642 if (mono_inject_async_exc_method)
3643 mono_method_desc_free (mono_inject_async_exc_method);
3645 mono_native_tls_free (mono_jit_tls_id);
3647 mono_mutex_destroy (&jit_mutex);
3649 mono_mutex_destroy (&mono_delegate_section);
3651 mono_code_manager_cleanup ();
3653 #ifdef USE_JUMP_TABLES
3654 mono_jumptable_cleanup ();
3659 mono_set_defaults (int verbose_level, guint32 opts)
3661 mini_verbose = verbose_level;
3662 mono_set_optimizations (opts);
3666 mono_disable_optimizations (guint32 opts)
3668 default_opt &= ~opts;
3672 mono_set_optimizations (guint32 opts)
3675 default_opt_set = TRUE;
3676 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3677 mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
3682 mono_set_verbose_level (guint32 level)
3684 mini_verbose = level;
3688 * mono_get_runtime_build_info:
3690 * Return the runtime version + build date in string format.
3691 * The returned string is owned by the caller. The returned string
3692 * format is "VERSION (FULL_VERSION BUILD_DATE)" and build date is optional.
3695 mono_get_runtime_build_info (void)
3697 if (mono_build_date)
3698 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
3700 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
3704 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
3706 GHashTable *assemblies = (GHashTable*)user_data;
3707 MonoImage *image = mono_assembly_get_image (ass);
3708 MonoMethod *method, *invoke;
3711 if (g_hash_table_lookup (assemblies, ass))
3714 g_hash_table_insert (assemblies, ass, ass);
3716 if (mini_verbose > 0)
3717 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
3719 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
3720 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
3721 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
3723 if (method->is_generic || method->klass->generic_container)
3727 if (mini_verbose > 1) {
3728 char * desc = mono_method_full_name (method, TRUE);
3729 g_print ("Compiling %d %s\n", count, desc);
3732 mono_compile_method (method);
3733 if (strcmp (method->name, "Finalize") == 0) {
3734 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
3735 mono_compile_method (invoke);
3737 #ifndef DISABLE_REMOTING
3738 if (mono_class_is_marshalbyref (method->klass) && mono_method_signature (method)->hasthis) {
3739 invoke = mono_marshal_get_remoting_invoke_with_check (method);
3740 mono_compile_method (invoke);
3745 /* Load and precompile referenced assemblies as well */
3746 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
3747 mono_assembly_load_reference (image, i);
3748 if (image->references [i])
3749 mono_precompile_assembly (image->references [i], assemblies);
3753 void mono_precompile_assemblies ()
3755 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
3757 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
3759 g_hash_table_destroy (assemblies);
3762 #ifdef USE_JUMP_TABLES
3763 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
3765 typedef struct MonoJumpTableChunk {
3768 struct MonoJumpTableChunk *previous;
3769 /* gpointer entries[total]; */
3770 } MonoJumpTableChunk;
3772 static MonoJumpTableChunk* g_jumptable;
3773 #define mono_jumptable_lock() mono_mutex_lock (&jumptable_mutex)
3774 #define mono_jumptable_unlock() mono_mutex_unlock (&jumptable_mutex)
3775 static mono_mutex_t jumptable_mutex;
3777 static MonoJumpTableChunk*
3778 mono_create_jumptable_chunk (guint32 max_entries)
3780 guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
3781 MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
3782 chunk->total = max_entries;
3787 mono_jumptable_init (void)
3789 if (g_jumptable == NULL) {
3790 mono_mutex_init_recursive (&jumptable_mutex);
3791 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
3796 mono_jumptable_add_entry (void)
3798 return mono_jumptable_add_entries (1);
3802 mono_jumptable_add_entries (guint32 entries)
3807 mono_jumptable_init ();
3808 mono_jumptable_lock ();
3809 index = g_jumptable->active;
3810 if (index + entries >= g_jumptable->total) {
3812 * Grow jumptable, by adding one more chunk.
3813 * We cannot realloc jumptable, as there could be pointers
3814 * to existing jump table entries in the code, so instead
3815 * we just add one more chunk.
3817 guint32 max_entries = entries;
3818 MonoJumpTableChunk *new_chunk;
3820 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
3821 max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
3822 new_chunk = mono_create_jumptable_chunk (max_entries);
3823 /* Link old jumptable, so that we could free it up later. */
3824 new_chunk->previous = g_jumptable;
3825 g_jumptable = new_chunk;
3828 g_jumptable->active = index + entries;
3829 result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
3830 mono_jumptable_unlock();
3836 mono_jumptable_cleanup (void)
3839 MonoJumpTableChunk *current = g_jumptable, *prev;
3840 while (current != NULL) {
3841 prev = current->previous;
3846 mono_mutex_destroy (&jumptable_mutex);
3851 mono_jumptable_get_entry (guint8 *code_ptr)
3853 return mono_arch_jumptable_entry_from_code (code_ptr);