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-internals.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/metadata/reflection-internals.h>
51 #include <mono/metadata/monitor.h>
52 #include <mono/utils/mono-math.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-counters.h>
55 #include <mono/utils/mono-error-internals.h>
56 #include <mono/utils/mono-logger-internals.h>
57 #include <mono/utils/mono-mmap.h>
58 #include <mono/utils/mono-path.h>
59 #include <mono/utils/mono-tls.h>
60 #include <mono/utils/mono-hwcap.h>
61 #include <mono/utils/dtrace.h>
62 #include <mono/utils/mono-signal-handler.h>
63 #include <mono/utils/mono-threads.h>
64 #include <mono/utils/checked-build.h>
65 #include <mono/io-layer/io-layer.h>
68 #include "seq-points.h"
75 #include "jit-icalls.h"
78 #include "mini-llvm.h"
79 #include "debugger-agent.h"
81 #ifdef MONO_ARCH_LLVM_SUPPORTED
83 #include "mini-llvm-cpp.h"
88 static guint32 default_opt = 0;
89 static gboolean default_opt_set = FALSE;
91 MonoNativeTlsKey mono_jit_tls_id;
93 #ifdef MONO_HAVE_FAST_TLS
94 MONO_FAST_TLS_DECLARE(mono_jit_tls);
97 gboolean mono_compile_aot = FALSE;
98 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
99 gboolean mono_aot_only = FALSE;
100 /* Same as mono_aot_only, but only LLVM compiled code is used, no trampolines */
101 gboolean mono_llvm_only = FALSE;
102 MonoAotMode mono_aot_mode = MONO_AOT_MODE_NONE;
104 const char *mono_build_date;
105 gboolean mono_do_signal_chaining;
106 gboolean mono_do_crash_chaining;
107 int mini_verbose = 0;
110 * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
111 * it can load AOT code compiled by LLVM.
113 gboolean mono_use_llvm = FALSE;
115 #define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
116 #define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
117 static mono_mutex_t jit_mutex;
119 static MonoCodeManager *global_codeman;
121 MonoDebugOptions debug_options;
123 #ifdef VALGRIND_JIT_REGISTER_MAP
124 int valgrind_register;
127 static GSList *tramp_infos;
129 static void register_icalls (void);
132 mono_running_on_valgrind (void)
135 if (RUNNING_ON_VALGRIND){
136 #ifdef VALGRIND_JIT_REGISTER_MAP
137 valgrind_register = TRUE;
151 find_tramp (gpointer key, gpointer value, gpointer user_data)
153 FindTrampUserData *ud = (FindTrampUserData*)user_data;
156 ud->method = (MonoMethod*)key;
160 G_GNUC_UNUSED static char*
161 get_method_from_ip (void *ip)
166 MonoDomain *domain = mono_domain_get ();
167 MonoDebugSourceLocation *location;
168 FindTrampUserData user_data;
171 domain = mono_get_root_domain ();
173 ji = mono_jit_info_table_find_internal (domain, (char *)ip, TRUE, TRUE);
176 user_data.method = NULL;
177 mono_domain_lock (domain);
178 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
179 mono_domain_unlock (domain);
180 if (user_data.method) {
181 char *mname = mono_method_full_name (user_data.method, TRUE);
182 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
188 } else if (ji->is_trampoline) {
189 res = g_strdup_printf ("<%p - %s trampoline>", ip, ((MonoTrampInfo*)ji->d.tramp_info)->name);
193 method = mono_method_full_name (jinfo_get_method (ji), TRUE);
194 /* FIXME: unused ? */
195 location = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
197 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);
199 mono_debug_free_source_location (location);
207 * @ip: an instruction pointer address
209 * This method is used from a debugger to get the name of the
210 * method at address @ip. This routine is typically invoked from
211 * a debugger like this:
213 * (gdb) print mono_pmip ($pc)
215 * Returns: the name of the method at address @ip.
220 return get_method_from_ip (ip);
224 * mono_print_method_from_ip
225 * @ip: an instruction pointer address
227 * This method is used from a debugger to get the name of the
228 * method at address @ip.
230 * This prints the name of the method at address @ip in the standard
231 * output. Unlike mono_pmip which returns a string, this routine
232 * prints the value on the standard output.
235 /* Prevent the linker from optimizing this away in embedding setups to help debugging */
236 __attribute__((used))
239 mono_print_method_from_ip (void *ip)
243 MonoDebugSourceLocation *source;
244 MonoDomain *domain = mono_domain_get ();
245 MonoDomain *target_domain = mono_domain_get ();
246 FindTrampUserData user_data;
247 MonoGenericSharingContext*gsctx;
248 const char *shared_type;
250 ji = mini_jit_info_table_find_ext (domain, (char *)ip, TRUE, &target_domain);
251 if (ji && ji->is_trampoline) {
252 MonoTrampInfo *tinfo = (MonoTrampInfo *)ji->d.tramp_info;
254 printf ("IP %p is at offset 0x%x of trampoline '%s'.\n", ip, (int)((guint8*)ip - tinfo->code), tinfo->name);
260 user_data.method = NULL;
261 mono_domain_lock (domain);
262 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
263 mono_domain_unlock (domain);
265 if (user_data.method) {
266 char *mname = mono_method_full_name (user_data.method, TRUE);
267 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
272 g_print ("No method at %p\n", ip);
276 method = mono_method_full_name (jinfo_get_method (ji), TRUE);
277 source = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
279 gsctx = mono_jit_info_get_generic_sharing_context (ji);
282 if (gsctx->is_gsharedvt)
283 shared_type = "gsharedvt ";
285 shared_type = "gshared ";
288 g_print ("IP %p at offset 0x%x of %smethod %s (%p %p)[domain %p - %s]\n", ip, (int)((char*)ip - (char*)ji->code_start), shared_type, method, ji->code_start, (char*)ji->code_start + ji->code_size, target_domain, target_domain->friendly_name);
291 g_print ("%s:%d\n", source->source_file, source->row);
294 mono_debug_free_source_location (source);
299 * mono_method_same_domain:
301 * Determine whenever two compiled methods are in the same domain, thus
302 * the address of the callee can be embedded in the caller.
304 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
308 if (!caller || caller->is_trampoline || !callee || callee->is_trampoline)
312 * If the call was made from domain-neutral to domain-specific
313 * code, we can't patch the call site.
315 if (caller->domain_neutral && !callee->domain_neutral)
318 cmethod = jinfo_get_method (caller);
319 if ((cmethod->klass == mono_defaults.appdomain_class) &&
320 (strstr (cmethod->name, "InvokeInDomain"))) {
321 /* The InvokeInDomain methods change the current appdomain */
329 * mono_global_codeman_reserve:
331 * Allocate code memory from the global code manager.
333 void *mono_global_codeman_reserve (int size)
338 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
340 if (!global_codeman) {
341 /* This can happen during startup */
342 global_codeman = mono_code_manager_new ();
343 return mono_code_manager_reserve (global_codeman, size);
347 ptr = mono_code_manager_reserve (global_codeman, size);
353 #if defined(__native_client_codegen__) && defined(__native_client__)
357 #ifdef __native_client_gc__
358 __nacl_suspend_thread_if_needed();
362 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
363 * which we are generating code, return a pointer to the destination in the
364 * dynamic code segment into which the code will be copied when
365 * mono_global_codeman_commit is called.
366 * LOCKING: Acquires the jit lock.
369 nacl_global_codeman_get_dest (void *data)
373 dest = nacl_code_manager_get_code_dest (global_codeman, data);
379 mono_global_codeman_commit (void *data, int size, int newsize)
382 mono_code_manager_commit (global_codeman, data, size, newsize);
387 * Convenience function which calls mono_global_codeman_commit to validate and
388 * copy the code. The caller sets *buf_base and *buf_size to the start and size
389 * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
390 * the byte after the last instruction byte. On return, *buf_base will point to
391 * the start of the copied in the code segment, and *code_end will point after
392 * the end of the copied code.
395 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
397 guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
398 mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
399 *code_end = tmp + (*code_end - *buf_base);
403 /* no-op versions of Native Client functions */
405 nacl_global_codeman_get_dest (void *data)
411 mono_global_codeman_commit (void *data, int size, int newsize)
416 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
420 #endif /* __native_client__ */
423 * mono_create_unwind_op:
425 * Create an unwind op with the given parameters.
428 mono_create_unwind_op (int when, int tag, int reg, int val)
430 MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
441 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
443 MonoJumpInfoToken *res = (MonoJumpInfoToken *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
446 res->has_context = context != NULL;
448 memcpy (&res->context, context, sizeof (MonoGenericContext));
454 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
456 return mono_jump_info_token_new2 (mp, image, token, NULL);
460 * mono_tramp_info_create:
462 * Create a MonoTrampInfo structure from the arguments. This function assumes ownership
463 * of JI, and UNWIND_OPS.
466 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
468 MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
470 info->name = g_strdup ((char*)name);
472 info->code_size = code_size;
474 info->unwind_ops = unwind_ops;
480 mono_tramp_info_free (MonoTrampInfo *info)
485 mono_free_unwind_info (info->unwind_ops);
490 register_trampoline_jit_info (MonoDomain *domain, MonoTrampInfo *info)
494 ji = (MonoJitInfo *)mono_domain_alloc0 (domain, mono_jit_info_size ((MonoJitInfoFlags)0, 0, 0));
495 mono_jit_info_init (ji, NULL, info->code, info->code_size, (MonoJitInfoFlags)0, 0, 0);
496 ji->d.tramp_info = info;
497 ji->is_trampoline = TRUE;
499 ji->unwind_info = mono_cache_unwind_info (info->uw_info, info->uw_info_len);
501 mono_jit_info_table_add (domain, ji);
505 * mono_tramp_info_register:
507 * Remember INFO for use by xdebug, mono_print_method_from_ip (), jit maps, etc.
512 mono_tramp_info_register (MonoTrampInfo *info, MonoDomain *domain)
520 domain = mono_get_root_domain ();
522 copy = g_new0 (MonoTrampInfo, 1);
523 copy->code = info->code;
524 copy->code_size = info->code_size;
525 copy->name = g_strdup (info->name);
527 if (info->unwind_ops) {
528 copy->uw_info = mono_unwind_ops_encode (info->unwind_ops, ©->uw_info_len);
530 /* Trampolines from aot have the unwind ops already encoded */
531 copy->uw_info = info->uw_info;
532 copy->uw_info_len = info->uw_info_len;
536 tramp_infos = g_slist_prepend (tramp_infos, copy);
539 mono_save_trampoline_xdebug_info (info);
541 /* Only register trampolines that have unwind infos */
542 if (mono_get_root_domain () && copy->uw_info)
543 register_trampoline_jit_info (domain, copy);
545 if (mono_jit_map_is_enabled ())
546 mono_emit_jit_tramp (info->code, info->code_size, info->name);
548 mono_tramp_info_free (info);
552 mono_tramp_info_cleanup (void)
556 for (l = tramp_infos; l; l = l->next) {
557 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
559 mono_tramp_info_free (info);
561 g_slist_free (tramp_infos);
564 /* Register trampolines created before the root domain was created in the jit info tables */
566 register_trampolines (MonoDomain *domain)
570 for (l = tramp_infos; l; l = l->next) {
571 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
573 register_trampoline_jit_info (domain, info);
577 G_GNUC_UNUSED static void
583 * Runtime debugging tool, use if (debug_count ()) <x> else <y> to do <x> the first COUNT times, then do <y> afterwards.
584 * Set a breakpoint in break_count () to break the last time <x> is done.
586 G_GNUC_UNUSED gboolean
587 mono_debug_count (void)
589 static int count = 0;
590 static gboolean inited;
591 static const char *value;
596 value = g_getenv ("COUNT");
603 if (count == atoi (value))
606 if (count > atoi (value))
613 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
617 gconstpointer trampoline;
618 MonoDomain *domain = mono_get_root_domain ();
619 gboolean check_exc = TRUE;
621 if (callinfo->wrapper)
622 return callinfo->wrapper;
624 if (callinfo->trampoline)
625 return callinfo->trampoline;
627 if (!strcmp (callinfo->name, "mono_thread_interruption_checkpoint"))
628 /* This icall is used to check for exceptions, so don't check in the wrapper */
631 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
632 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_exc);
636 trampoline = mono_compile_method (wrapper);
640 trampoline = mono_create_jit_trampoline (domain, wrapper, &error);
641 mono_error_assert_ok (&error);
642 trampoline = mono_create_ftnptr (domain, (gpointer)trampoline);
646 if (!callinfo->trampoline) {
647 mono_register_jit_icall_wrapper (callinfo, trampoline);
648 callinfo->trampoline = trampoline;
650 mono_loader_unlock ();
652 return callinfo->trampoline;
656 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
658 return mono_icall_get_wrapper_full (callinfo, FALSE);
661 static MonoJitDynamicMethodInfo*
662 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
664 MonoJitDynamicMethodInfo *res;
666 if (domain_jit_info (domain)->dynamic_code_hash)
667 res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
674 register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
677 mini_register_opcode_emulation (opcode, name, sigstr, func, symbol, no_throw);
679 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
681 g_assert (!sig->hasthis);
682 g_assert (sig->param_count < 3);
684 /* Opcode emulation functions are assumed to don't call mono_raise_exception () */
685 mono_register_jit_icall_full (func, name, sig, no_throw, TRUE, symbol);
690 * For JIT icalls implemented in C.
691 * NAME should be the same as the name of the C function whose address is FUNC.
692 * If @avoid_wrapper is TRUE, no wrapper is generated. This is for perf critical icalls which
693 * can't throw exceptions.
696 register_icall (gpointer func, const char *name, const char *sigstr, gboolean avoid_wrapper)
698 MonoMethodSignature *sig;
701 sig = mono_create_icall_signature (sigstr);
705 mono_register_jit_icall_full (func, name, sig, avoid_wrapper, FALSE, avoid_wrapper ? name : NULL);
709 register_icall_no_wrapper (gpointer func, const char *name, const char *sigstr)
711 MonoMethodSignature *sig;
714 sig = mono_create_icall_signature (sigstr);
718 mono_register_jit_icall_full (func, name, sig, TRUE, FALSE, name);
722 register_icall_with_wrapper (gpointer func, const char *name, const char *sigstr)
724 MonoMethodSignature *sig;
727 sig = mono_create_icall_signature (sigstr);
731 mono_register_jit_icall_full (func, name, sig, FALSE, FALSE, NULL);
735 register_dyn_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
737 MonoMethodSignature *sig;
740 sig = mono_create_icall_signature (sigstr);
744 mono_register_jit_icall (func, name, sig, save);
747 #ifdef MONO_HAVE_FAST_TLS
748 MONO_FAST_TLS_DECLARE(mono_lmf_addr);
749 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
751 * When this is defined, the current lmf is stored in this tls variable instead of in
754 MONO_FAST_TLS_DECLARE(mono_lmf);
759 mono_get_jit_tls_offset (void)
765 offset = mono_jit_tls_id;
767 /* FIXME: Happens during startup */
770 MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
776 mono_get_lmf_tls_offset (void)
778 #if defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
780 MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
788 mono_get_lmf_addr_tls_offset (void)
791 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
798 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
799 return (MonoLMF *)MONO_FAST_TLS_GET (mono_lmf);
801 MonoJitTlsData *jit_tls;
803 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
806 * We do not assert here because this function can be called from
807 * mini-gc.c on a thread that has not executed any managed code, yet
808 * (the thread object allocation can trigger a collection).
815 mono_get_lmf_addr (void)
817 #ifdef MONO_HAVE_FAST_TLS
818 return (MonoLMF **)MONO_FAST_TLS_GET (mono_lmf_addr);
820 MonoJitTlsData *jit_tls;
822 jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
823 if (G_LIKELY (jit_tls))
824 return &jit_tls->lmf;
827 * When resolving the call to mono_jit_thread_attach full-aot will look
828 * in the plt, which causes a call into the generic trampoline, which in turn
829 * tries to resolve the lmf_addr creating a cyclic dependency. We cannot
830 * call mono_jit_thread_attach from the native-to-managed wrapper, without
831 * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
834 mono_thread_attach (mono_get_root_domain ());
835 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
837 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
838 return &jit_tls->lmf;
840 g_assert_not_reached ();
846 mono_set_lmf (MonoLMF *lmf)
848 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
849 MONO_FAST_TLS_SET (mono_lmf, lmf);
852 (*mono_get_lmf_addr ()) = lmf;
856 mono_get_jit_tls (void)
858 return (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
862 mono_set_jit_tls (MonoJitTlsData *jit_tls)
864 MonoThreadInfo *info;
866 mono_native_tls_set_value (mono_jit_tls_id, jit_tls);
868 #ifdef MONO_HAVE_FAST_TLS
869 MONO_FAST_TLS_SET (mono_jit_tls, jit_tls);
872 /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
873 info = mono_thread_info_current ();
875 mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
879 mono_set_lmf_addr (gpointer lmf_addr)
881 MonoThreadInfo *info;
883 #ifdef MONO_HAVE_FAST_TLS
884 MONO_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
887 /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
888 info = mono_thread_info_current ();
890 mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
894 * mono_jit_thread_attach: called by native->managed wrappers
898 * - @return: the original domain which needs to be restored, or NULL.
901 * - @dummy: contains the original domain
902 * - @return: a cookie containing current MonoThreadInfo* if it was in BLOCKING mode, NULL otherwise
905 mono_jit_thread_attach (MonoDomain *domain, gpointer *dummy)
910 /* Happens when called from AOTed code which is only used in the root domain. */
911 domain = mono_get_root_domain ();
916 if (!mono_threads_is_coop_enabled ()) {
919 #ifdef MONO_HAVE_FAST_TLS
920 attached = MONO_FAST_TLS_GET (mono_lmf_addr) != NULL;
922 attached = mono_native_tls_get_value (mono_jit_tls_id) != NULL;
926 mono_thread_attach (domain);
929 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
932 orig = mono_domain_get ();
934 mono_domain_set (domain, TRUE);
936 return orig != domain ? orig : NULL;
938 MonoThreadInfo *info;
940 info = mono_thread_info_current_unchecked ();
941 if (!info || !mono_thread_info_is_live (info)) {
942 /* thread state STARTING -> RUNNING */
943 mono_thread_attach (domain);
946 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
950 /* mono_threads_reset_blocking_start returns the current MonoThreadInfo
951 * if we were in BLOCKING mode */
952 return mono_thread_info_current ();
954 orig = mono_domain_get ();
956 /* orig might be null if we did an attach -> detach -> attach sequence */
959 mono_domain_set (domain, TRUE);
963 /* thread state (BLOCKING|RUNNING) -> RUNNING */
964 return mono_threads_reset_blocking_start (dummy);
970 * mono_jit_thread_detach: called by native->managed wrappers
973 * - @cookie: the original domain which needs to be restored, or NULL.
977 * - @cookie: contains current MonoThreadInfo* if it was in BLOCKING mode, NULL otherwise
978 * - @dummy: contains the original domain
981 mono_jit_thread_detach (gpointer cookie, gpointer *dummy)
983 MonoDomain *domain, *orig;
985 if (!mono_threads_is_coop_enabled ()) {
986 orig = (MonoDomain*) cookie;
989 mono_domain_set (orig, TRUE);
991 orig = (MonoDomain*) *dummy;
993 domain = mono_domain_get ();
996 /* it won't do anything if cookie is NULL
997 * thread state RUNNING -> (RUNNING|BLOCKING) */
998 mono_threads_reset_blocking_end (cookie, dummy);
1000 if (orig != domain) {
1002 mono_domain_unset ();
1004 mono_domain_set (orig, TRUE);
1010 * mono_thread_abort:
1011 * @obj: exception object
1013 * abort the thread, print exception information and stack trace
1016 mono_thread_abort (MonoObject *obj)
1018 /* MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id); */
1020 /* handle_remove should be eventually called for this thread, too
1023 if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
1024 (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
1025 mono_thread_exit ();
1027 mono_invoke_unhandled_exception_hook (obj);
1032 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
1034 MonoJitTlsData *jit_tls;
1037 jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
1041 jit_tls = g_new0 (MonoJitTlsData, 1);
1043 jit_tls->abort_func = (void (*)(MonoObject *))abort_func;
1044 jit_tls->end_of_stack = stack_start;
1046 mono_set_jit_tls (jit_tls);
1048 lmf = g_new0 (MonoLMF, 1);
1049 MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
1051 jit_tls->first_lmf = lmf;
1053 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
1054 /* jit_tls->lmf is unused */
1055 MONO_FAST_TLS_SET (mono_lmf, lmf);
1056 mono_set_lmf_addr (MONO_FAST_TLS_ADDR (mono_lmf));
1058 mono_set_lmf_addr (&jit_tls->lmf);
1063 #ifdef MONO_ARCH_HAVE_TLS_INIT
1064 mono_arch_tls_init ();
1067 mono_setup_altstack (jit_tls);
1073 free_jit_tls_data (MonoJitTlsData *jit_tls)
1075 mono_arch_free_jit_tls_data (jit_tls);
1076 mono_free_altstack (jit_tls);
1078 g_free (jit_tls->first_lmf);
1083 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
1085 MonoThreadInfo *thread;
1086 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
1087 thread = mono_thread_info_current_unchecked ();
1089 thread->jit_data = jit_tls;
1091 mono_arch_cpu_init ();
1094 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
1097 mono_thread_abort_dummy (MonoObject *obj)
1099 if (mono_thread_attach_aborted_cb)
1100 mono_thread_attach_aborted_cb (obj);
1102 mono_thread_abort (obj);
1106 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
1108 MonoThreadInfo *thread;
1109 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
1110 thread = mono_thread_info_current_unchecked ();
1112 thread->jit_data = jit_tls;
1113 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
1114 mono_runtime_setup_stat_profiler ();
1116 mono_arch_cpu_init ();
1120 mini_thread_cleanup (MonoNativeThreadId tid)
1122 MonoJitTlsData *jit_tls = NULL;
1123 MonoThreadInfo *info;
1125 info = mono_thread_info_current_unchecked ();
1127 /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
1128 * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
1129 * not a trivial thing.
1131 * The current offender is mono_thread_manage which cleanup threads from the outside.
1133 if (info && mono_thread_info_get_tid (info) == tid) {
1134 jit_tls = (MonoJitTlsData *)info->jit_data;
1135 info->jit_data = NULL;
1137 mono_set_jit_tls (NULL);
1139 /* If we attach a thread but never call into managed land, we might never get an lmf.*/
1140 if (mono_get_lmf ()) {
1141 mono_set_lmf (NULL);
1142 mono_set_lmf_addr (NULL);
1145 info = mono_thread_info_lookup (tid);
1147 jit_tls = (MonoJitTlsData *)info->jit_data;
1148 info->jit_data = NULL;
1150 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
1154 free_jit_tls_data (jit_tls);
1158 mini_get_tls_offset (MonoTlsKey key)
1161 g_assert (MONO_ARCH_HAVE_TLS_GET);
1164 case TLS_KEY_THREAD:
1165 offset = mono_thread_get_tls_offset ();
1167 case TLS_KEY_JIT_TLS:
1168 offset = mono_get_jit_tls_offset ();
1170 case TLS_KEY_DOMAIN:
1171 offset = mono_domain_get_tls_offset ();
1174 offset = mono_get_lmf_tls_offset ();
1176 case TLS_KEY_LMF_ADDR:
1177 offset = mono_get_lmf_addr_tls_offset ();
1180 offset = mono_tls_key_get_offset (key);
1181 g_assert (offset != -1);
1189 mini_tls_key_supported (MonoTlsKey key)
1191 if (!MONO_ARCH_HAVE_TLS_GET)
1194 return mini_get_tls_offset (key) != -1;
1198 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
1200 MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
1204 ji->data.target = target;
1211 * mono_patch_info_dup_mp:
1213 * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
1216 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
1218 MonoJumpInfo *res = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
1219 memcpy (res, patch_info, sizeof (MonoJumpInfo));
1221 switch (patch_info->type) {
1222 case MONO_PATCH_INFO_RVA:
1223 case MONO_PATCH_INFO_LDSTR:
1224 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1225 case MONO_PATCH_INFO_LDTOKEN:
1226 case MONO_PATCH_INFO_DECLSEC:
1227 res->data.token = (MonoJumpInfoToken *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
1228 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
1230 case MONO_PATCH_INFO_SWITCH:
1231 res->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
1232 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
1233 res->data.table->table = (MonoBasicBlock **)mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1234 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1236 case MONO_PATCH_INFO_RGCTX_FETCH:
1237 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
1238 res->data.rgctx_entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
1239 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
1240 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
1242 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1243 res->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
1244 memcpy (res->data.del_tramp, patch_info->data.del_tramp, sizeof (MonoDelegateClassMethodPair));
1246 case MONO_PATCH_INFO_GSHAREDVT_CALL:
1247 res->data.gsharedvt = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoGSharedVtCall));
1248 memcpy (res->data.gsharedvt, patch_info->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
1250 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
1251 MonoGSharedVtMethodInfo *info;
1252 MonoGSharedVtMethodInfo *oinfo;
1255 oinfo = patch_info->data.gsharedvt_method;
1256 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
1257 res->data.gsharedvt_method = info;
1258 memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
1259 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
1260 for (i = 0; i < oinfo->num_entries; ++i) {
1261 MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
1262 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
1264 memcpy (template_, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
1266 //info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
1267 //memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
1270 case MONO_PATCH_INFO_VIRT_METHOD: {
1271 MonoJumpInfoVirtMethod *info;
1272 MonoJumpInfoVirtMethod *oinfo;
1274 oinfo = patch_info->data.virt_method;
1275 info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
1276 res->data.virt_method = info;
1277 memcpy (info, oinfo, sizeof (MonoJumpInfoVirtMethod));
1288 mono_patch_info_hash (gconstpointer data)
1290 const MonoJumpInfo *ji = (MonoJumpInfo*)data;
1293 case MONO_PATCH_INFO_RVA:
1294 case MONO_PATCH_INFO_LDSTR:
1295 case MONO_PATCH_INFO_LDTOKEN:
1296 case MONO_PATCH_INFO_DECLSEC:
1297 return (ji->type << 8) | ji->data.token->token;
1298 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1299 return (ji->type << 8) | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
1300 case MONO_PATCH_INFO_INTERNAL_METHOD:
1301 return (ji->type << 8) | g_str_hash (ji->data.name);
1302 case MONO_PATCH_INFO_VTABLE:
1303 case MONO_PATCH_INFO_CLASS:
1304 case MONO_PATCH_INFO_IID:
1305 case MONO_PATCH_INFO_ADJUSTED_IID:
1306 case MONO_PATCH_INFO_METHODCONST:
1307 case MONO_PATCH_INFO_METHOD:
1308 case MONO_PATCH_INFO_METHOD_JUMP:
1309 case MONO_PATCH_INFO_IMAGE:
1310 case MONO_PATCH_INFO_ICALL_ADDR:
1311 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
1312 case MONO_PATCH_INFO_FIELD:
1313 case MONO_PATCH_INFO_SFLDA:
1314 case MONO_PATCH_INFO_SEQ_POINT_INFO:
1315 case MONO_PATCH_INFO_METHOD_RGCTX:
1316 case MONO_PATCH_INFO_SIGNATURE:
1317 case MONO_PATCH_INFO_TLS_OFFSET:
1318 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
1319 case MONO_PATCH_INFO_AOT_JIT_INFO:
1320 return (ji->type << 8) | (gssize)ji->data.target;
1321 case MONO_PATCH_INFO_GSHAREDVT_CALL:
1322 return (ji->type << 8) | (gssize)ji->data.gsharedvt->method;
1323 case MONO_PATCH_INFO_RGCTX_FETCH:
1324 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
1325 MonoJumpInfoRgctxEntry *e = ji->data.rgctx_entry;
1327 return (ji->type << 8) | (gssize)e->method | (e->in_mrgctx) | e->info_type | mono_patch_info_hash (e->data);
1329 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1330 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
1331 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
1332 case MONO_PATCH_INFO_GC_NURSERY_START:
1333 case MONO_PATCH_INFO_GC_NURSERY_BITS:
1334 case MONO_PATCH_INFO_JIT_TLS_ID:
1335 case MONO_PATCH_INFO_GOT_OFFSET:
1336 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
1337 case MONO_PATCH_INFO_AOT_MODULE:
1338 return (ji->type << 8);
1339 case MONO_PATCH_INFO_CASTCLASS_CACHE:
1340 return (ji->type << 8) | (ji->data.index);
1341 case MONO_PATCH_INFO_SWITCH:
1342 return (ji->type << 8) | ji->data.table->table_size;
1343 case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1344 return (ji->type << 8) | (gssize)ji->data.gsharedvt_method->method;
1345 case MONO_PATCH_INFO_OBJC_SELECTOR_REF:
1346 /* Hash on the selector name */
1347 return g_str_hash (ji->data.target);
1348 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1349 return (ji->type << 8) | (gsize)ji->data.del_tramp->klass | (gsize)ji->data.del_tramp->method | (gsize)ji->data.del_tramp->is_virtual;
1350 case MONO_PATCH_INFO_LDSTR_LIT:
1351 return g_str_hash (ji->data.target);
1352 case MONO_PATCH_INFO_VIRT_METHOD: {
1353 MonoJumpInfoVirtMethod *info = ji->data.virt_method;
1355 return (ji->type << 8) | (gssize)info->klass | (gssize)info->method;
1357 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1358 return (ji->type << 8) | g_str_hash (ji->data.target);
1359 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
1360 return (ji->type << 8) | mono_signature_hash (ji->data.sig);
1362 printf ("info type: %d\n", ji->type);
1363 mono_print_ji (ji); printf ("\n");
1364 g_assert_not_reached ();
1370 * mono_patch_info_equal:
1372 * This might fail to recognize equivalent patches, i.e. floats, so its only
1373 * usable in those cases where this is not a problem, i.e. sharing GOT slots
1377 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
1379 const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
1380 const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
1382 if (ji1->type != ji2->type)
1385 switch (ji1->type) {
1386 case MONO_PATCH_INFO_RVA:
1387 case MONO_PATCH_INFO_LDSTR:
1388 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1389 case MONO_PATCH_INFO_LDTOKEN:
1390 case MONO_PATCH_INFO_DECLSEC:
1391 if ((ji1->data.token->image != ji2->data.token->image) ||
1392 (ji1->data.token->token != ji2->data.token->token) ||
1393 (ji1->data.token->has_context != ji2->data.token->has_context) ||
1394 (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
1395 (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
1398 case MONO_PATCH_INFO_INTERNAL_METHOD:
1399 return g_str_equal (ji1->data.name, ji2->data.name);
1400 case MONO_PATCH_INFO_RGCTX_FETCH:
1401 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
1402 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
1403 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
1405 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);
1407 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
1408 MonoJumpInfoGSharedVtCall *c1 = ji1->data.gsharedvt;
1409 MonoJumpInfoGSharedVtCall *c2 = ji2->data.gsharedvt;
1411 return c1->sig == c2->sig && c1->method == c2->method;
1413 case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1414 return ji1->data.gsharedvt_method->method == ji2->data.gsharedvt_method->method;
1415 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1416 return ji1->data.del_tramp->klass == ji2->data.del_tramp->klass && ji1->data.del_tramp->method == ji2->data.del_tramp->method && ji1->data.del_tramp->is_virtual == ji2->data.del_tramp->is_virtual;
1417 case MONO_PATCH_INFO_CASTCLASS_CACHE:
1418 return ji1->data.index == ji2->data.index;
1419 case MONO_PATCH_INFO_VIRT_METHOD:
1420 return ji1->data.virt_method->klass == ji2->data.virt_method->klass && ji1->data.virt_method->method == ji2->data.virt_method->method;
1421 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1422 if (ji1->data.target == ji2->data.target)
1424 return strcmp (ji1->data.target, ji2->data.target) == 0 ? 1 : 0;
1425 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
1426 return mono_metadata_signature_equal (ji1->data.sig, ji2->data.sig) ? 1 : 0;
1428 if (ji1->data.target != ji2->data.target)
1437 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error)
1439 unsigned char *ip = patch_info->ip.i + code;
1440 gconstpointer target = NULL;
1442 mono_error_init (error);
1444 switch (patch_info->type) {
1445 case MONO_PATCH_INFO_BB:
1447 * FIXME: This could be hit for methods without a prolog. Should use -1
1448 * but too much code depends on a 0 initial value.
1450 //g_assert (patch_info->data.bb->native_offset);
1451 target = patch_info->data.bb->native_offset + code;
1453 case MONO_PATCH_INFO_ABS:
1454 target = patch_info->data.target;
1456 case MONO_PATCH_INFO_LABEL:
1457 target = patch_info->data.inst->inst_c0 + code;
1459 case MONO_PATCH_INFO_IP:
1460 #if defined(__native_client__) && defined(__native_client_codegen__)
1461 /* Need to transform to the destination address, it's */
1462 /* emitted as an immediate in the code. */
1463 target = nacl_inverse_modify_patch_target(ip);
1468 case MONO_PATCH_INFO_METHOD_REL:
1469 target = code + patch_info->data.offset;
1471 case MONO_PATCH_INFO_INTERNAL_METHOD: {
1472 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1474 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
1475 g_assert_not_reached ();
1477 target = mono_icall_get_wrapper (mi);
1480 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1481 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1483 g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
1484 g_assert_not_reached ();
1489 case MONO_PATCH_INFO_METHOD_JUMP:
1490 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE, error);
1491 if (!mono_error_ok (error))
1493 #if defined(__native_client__) && defined(__native_client_codegen__)
1494 # if defined(TARGET_AMD64)
1495 /* This target is an absolute address, not relative to the */
1496 /* current code being emitted on AMD64. */
1497 target = nacl_inverse_modify_patch_target(target);
1501 case MONO_PATCH_INFO_METHOD:
1502 #if defined(__native_client_codegen__) && defined(USE_JUMP_TABLES)
1504 * If we use jumptables, for recursive calls we cannot
1505 * avoid trampoline, as we not yet know where we will
1508 target = mono_create_jit_trampoline (domain, patch_info->data.method, error);
1509 if (!mono_error_ok (error))
1512 if (patch_info->data.method == method) {
1515 /* get the trampoline to the method from the domain */
1516 target = mono_create_jit_trampoline (domain, patch_info->data.method, error);
1517 if (!mono_error_ok (error))
1522 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
1525 mono_domain_lock (domain);
1526 if (!domain_jit_info (domain)->method_code_hash)
1527 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
1528 code_slot = g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, patch_info->data.method);
1530 code_slot = mono_domain_alloc0 (domain, sizeof (gpointer));
1531 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, patch_info->data.method, code_slot);
1533 mono_domain_unlock (domain);
1537 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
1538 #if defined(__native_client_codegen__)
1539 target = (gpointer)&__nacl_thread_suspension_needed;
1541 g_assert (mono_threads_is_coop_enabled ());
1542 target = (gpointer)&mono_polling_required;
1545 case MONO_PATCH_INFO_SWITCH: {
1546 gpointer *jump_table;
1548 #if defined(__native_client__) && defined(__native_client_codegen__)
1549 /* This memory will leak, but we don't care if we're */
1550 /* not deleting JIT'd methods anyway */
1551 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
1553 if (method && method->dynamic) {
1554 jump_table = (void **)mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
1556 if (mono_aot_only) {
1557 jump_table = (void **)mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1559 jump_table = (void **)mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1564 for (i = 0; i < patch_info->data.table->table_size; i++) {
1565 #if defined(__native_client__) && defined(__native_client_codegen__)
1566 /* 'code' is relative to the current code blob, we */
1567 /* need to do this transform on it to make the */
1568 /* pointers in this table absolute */
1569 jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1571 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1575 #if defined(__native_client__) && defined(__native_client_codegen__)
1576 /* jump_table is in the data section, we need to transform */
1577 /* it here so when it gets modified in amd64_patch it will */
1578 /* then point back to the absolute data address */
1579 target = nacl_inverse_modify_patch_target (jump_table);
1581 target = jump_table;
1585 case MONO_PATCH_INFO_METHODCONST:
1586 case MONO_PATCH_INFO_CLASS:
1587 case MONO_PATCH_INFO_IMAGE:
1588 case MONO_PATCH_INFO_FIELD:
1589 case MONO_PATCH_INFO_SIGNATURE:
1590 case MONO_PATCH_INFO_AOT_MODULE:
1591 target = patch_info->data.target;
1593 case MONO_PATCH_INFO_IID:
1594 mono_class_init (patch_info->data.klass);
1595 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
1597 case MONO_PATCH_INFO_ADJUSTED_IID:
1598 mono_class_init (patch_info->data.klass);
1599 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
1601 case MONO_PATCH_INFO_VTABLE:
1602 target = mono_class_vtable (domain, patch_info->data.klass);
1605 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
1606 MonoDelegateClassMethodPair *del_tramp = patch_info->data.del_tramp;
1608 if (del_tramp->is_virtual)
1609 target = mono_create_delegate_virtual_trampoline (domain, del_tramp->klass, del_tramp->method);
1611 target = mono_create_delegate_trampoline_info (domain, del_tramp->klass, del_tramp->method);
1614 case MONO_PATCH_INFO_SFLDA: {
1615 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
1617 if (mono_class_field_is_special_static (patch_info->data.field)) {
1618 gpointer addr = NULL;
1620 mono_domain_lock (domain);
1621 if (domain->special_static_fields)
1622 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
1623 mono_domain_unlock (domain);
1629 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
1630 /* Done by the generated code */
1634 if (!mono_runtime_class_init_full (vtable, error)) {
1639 target = (char*)mono_vtable_get_static_field_data (vtable) + patch_info->data.field->offset;
1642 case MONO_PATCH_INFO_RVA: {
1643 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
1646 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
1647 target = mono_image_rva_map (patch_info->data.token->image, rva);
1650 case MONO_PATCH_INFO_R4:
1651 case MONO_PATCH_INFO_R8:
1652 target = patch_info->data.target;
1654 case MONO_PATCH_INFO_EXC_NAME:
1655 target = patch_info->data.name;
1657 case MONO_PATCH_INFO_LDSTR:
1659 mono_ldstr (domain, patch_info->data.token->image,
1660 mono_metadata_token_index (patch_info->data.token->token));
1662 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
1664 MonoClass *handle_class;
1666 handle = mono_ldtoken_checked (patch_info->data.token->image,
1667 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, error);
1668 if (!mono_error_ok (error))
1669 g_error ("Could not patch ldtoken due to %s", mono_error_get_message (error));
1670 mono_class_init (handle_class);
1671 mono_class_init (mono_class_from_mono_type ((MonoType *)handle));
1673 target = mono_type_get_object_checked (domain, (MonoType *)handle, error);
1674 if (!mono_error_ok (error))
1678 case MONO_PATCH_INFO_LDTOKEN: {
1680 MonoClass *handle_class;
1682 handle = mono_ldtoken_checked (patch_info->data.token->image,
1683 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, error);
1684 if (!mono_error_ok (error))
1685 g_error ("Could not patch ldtoken due to %s", mono_error_get_message (error));
1686 mono_class_init (handle_class);
1691 case MONO_PATCH_INFO_DECLSEC:
1692 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
1694 case MONO_PATCH_INFO_ICALL_ADDR:
1695 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
1696 /* run_cctors == 0 -> AOT */
1697 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1698 const char *exc_class;
1699 const char *exc_arg;
1702 target = mono_lookup_pinvoke_call (patch_info->data.method, &exc_class, &exc_arg);
1704 if (mono_aot_only) {
1705 mono_error_set_exception_instance (error, mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
1708 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));
1714 target = mono_lookup_internal_call (patch_info->data.method);
1716 if (!target && run_cctors)
1717 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
1720 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1721 target = mono_thread_interruption_request_flag ();
1723 case MONO_PATCH_INFO_METHOD_RGCTX: {
1724 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
1727 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
1730 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
1731 int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
1733 target = GINT_TO_POINTER (MONO_RGCTX_SLOT_INDEX (slot));
1736 case MONO_PATCH_INFO_BB_OVF:
1737 case MONO_PATCH_INFO_EXC_OVF:
1738 case MONO_PATCH_INFO_GOT_OFFSET:
1739 case MONO_PATCH_INFO_NONE:
1741 case MONO_PATCH_INFO_RGCTX_FETCH: {
1742 int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
1744 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
1747 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
1748 case MONO_PATCH_INFO_SEQ_POINT_INFO:
1750 /* AOT, not needed */
1753 target = mono_arch_get_seq_point_info (domain, code);
1756 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
1757 int card_table_shift_bits;
1758 gpointer card_table_mask;
1760 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
1763 case MONO_PATCH_INFO_GC_NURSERY_START: {
1767 target = mono_gc_get_nursery (&shift_bits, &size);
1770 case MONO_PATCH_INFO_GC_NURSERY_BITS: {
1774 mono_gc_get_nursery (&shift_bits, &size);
1776 target = (gpointer)(mgreg_t)shift_bits;
1779 case MONO_PATCH_INFO_CASTCLASS_CACHE: {
1780 target = mono_domain_alloc0 (domain, sizeof (gpointer));
1783 case MONO_PATCH_INFO_JIT_TLS_ID: {
1784 target = (gpointer) (size_t) mono_jit_tls_id;
1787 case MONO_PATCH_INFO_TLS_OFFSET: {
1790 offset = mini_get_tls_offset ((MonoTlsKey)GPOINTER_TO_INT (patch_info->data.target));
1791 #ifdef MONO_ARCH_HAVE_TRANSLATE_TLS_OFFSET
1792 offset = mono_arch_translate_tls_offset (offset);
1794 target = GINT_TO_POINTER (offset);
1797 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
1801 case MONO_PATCH_INFO_LDSTR_LIT: {
1805 len = strlen ((const char *)patch_info->data.target);
1806 s = (char *)mono_domain_alloc0 (domain, len + 1);
1807 memcpy (s, patch_info->data.target, len);
1812 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
1813 target = mini_get_gsharedvt_wrapper (TRUE, NULL, patch_info->data.sig, NULL, -1, FALSE);
1816 g_assert_not_reached ();
1819 return (gpointer)target;
1823 mini_init_gsctx (MonoDomain *domain, MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
1825 MonoGenericInst *inst;
1828 memset (gsctx, 0, sizeof (MonoGenericSharingContext));
1830 if (context && context->class_inst) {
1831 inst = context->class_inst;
1832 for (i = 0; i < inst->type_argc; ++i) {
1833 MonoType *type = inst->type_argv [i];
1835 if (mini_is_gsharedvt_gparam (type))
1836 gsctx->is_gsharedvt = TRUE;
1839 if (context && context->method_inst) {
1840 inst = context->method_inst;
1842 for (i = 0; i < inst->type_argc; ++i) {
1843 MonoType *type = inst->type_argv [i];
1845 if (mini_is_gsharedvt_gparam (type))
1846 gsctx->is_gsharedvt = TRUE;
1852 * LOCKING: Acquires the jit code hash lock.
1855 mini_lookup_method (MonoDomain *domain, MonoMethod *method, MonoMethod *shared)
1858 static gboolean inited = FALSE;
1859 static int lookups = 0;
1860 static int failed_lookups = 0;
1862 mono_domain_jit_code_hash_lock (domain);
1863 ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
1864 if (!ji && shared) {
1865 /* Try generic sharing */
1866 ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&domain->jit_code_hash, shared);
1867 if (ji && !ji->has_generic_jit_info)
1870 mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
1871 mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
1879 mono_domain_jit_code_hash_unlock (domain);
1885 lookup_method (MonoDomain *domain, MonoMethod *method)
1890 ji = mini_lookup_method (domain, method, NULL);
1893 if (!mono_method_is_generic_sharable (method, FALSE))
1895 shared = mini_get_shared_method (method);
1896 ji = mini_lookup_method (domain, method, shared);
1903 mono_get_jit_info_from_method (MonoDomain *domain, MonoMethod *method)
1905 return lookup_method (domain, method);
1909 static FILE* perf_map_file;
1912 mono_enable_jit_map (void)
1914 if (!perf_map_file) {
1916 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
1918 perf_map_file = fopen (name, "w");
1923 mono_emit_jit_tramp (void *start, int size, const char *desc)
1926 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
1930 mono_emit_jit_map (MonoJitInfo *jinfo)
1932 if (perf_map_file) {
1933 char *name = mono_method_full_name (jinfo_get_method (jinfo), TRUE);
1934 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
1940 mono_jit_map_is_enabled (void)
1942 return perf_map_file != NULL;
1948 no_gsharedvt_in_wrapper (void)
1950 g_assert_not_reached ();
1954 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoError *error)
1956 MonoDomain *target_domain, *domain = mono_domain_get ();
1958 gpointer code = NULL, p;
1960 MonoJitICallInfo *callinfo = NULL;
1961 WrapperInfo *winfo = NULL;
1963 mono_error_init (error);
1966 * ICALL wrappers are handled specially, since there is only one copy of them
1967 * shared by all appdomains.
1969 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1970 winfo = mono_marshal_get_wrapper_info (method);
1971 if (winfo && winfo->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
1972 callinfo = mono_find_jit_icall_by_addr (winfo->d.icall.func);
1973 g_assert (callinfo);
1975 /* Must be domain neutral since there is only one copy */
1976 opt |= MONO_OPT_SHARED;
1978 /* MONO_OPT_SHARED is no longer supported, we only use it for icall wrappers */
1979 opt &= ~MONO_OPT_SHARED;
1982 if (opt & MONO_OPT_SHARED)
1983 target_domain = mono_get_root_domain ();
1985 target_domain = domain;
1987 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
1988 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
1991 if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
1992 MonoGenericContext *ctx = NULL;
1993 if (method->is_inflated)
1994 ctx = mono_method_get_context (method);
1995 method = info->d.synchronized_inner.method;
1997 method = mono_class_inflate_generic_method_checked (method, ctx, error);
1998 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
2003 info = lookup_method (target_domain, method);
2005 /* We can't use a domain specific method in another domain */
2006 if (! ((domain != target_domain) && !info->domain_neutral)) {
2009 mono_jit_stats.methods_lookups++;
2010 vtable = mono_class_vtable (domain, method->klass);
2012 if (!mono_runtime_class_init_full (vtable, error))
2014 return mono_create_ftnptr (target_domain, info->code_start);
2018 #ifdef MONO_USE_AOT_COMPILER
2019 if (opt & MONO_OPT_AOT) {
2020 MonoDomain *domain = mono_domain_get ();
2022 mono_class_init (method->klass);
2024 if ((code = mono_aot_get_method (domain, method))) {
2028 * In llvm-only mode, method might be a shared method, so we can't initialize its class.
2029 * This is not a problem, since it will be initialized when the method is first
2030 * called by init_method ().
2032 if (!mono_llvm_only) {
2033 vtable = mono_class_vtable (domain, method->klass);
2035 if (!mono_runtime_class_init_full (vtable, error))
2042 if (!code && mono_llvm_only) {
2043 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
2044 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2046 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
2048 * These wrappers are only created for signatures which are in the program, but
2049 * sometimes we load methods too eagerly and have to create them even if they
2050 * will never be called.
2052 return no_gsharedvt_in_wrapper;
2058 code = mono_jit_compile_method_inner (method, target_domain, opt, error);
2059 if (!mono_error_ok (error))
2062 if (!code && mono_llvm_only) {
2063 printf ("AOT method not found in llvmonly mode: %s\n", mono_method_full_name (method, 1));
2064 g_assert_not_reached ();
2070 if (method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC) {
2074 * SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
2076 ji = mini_jit_info_table_find (mono_domain_get (), (char *)code, &d);
2080 p = mono_create_ftnptr (target_domain, code);
2083 /*mono_register_jit_icall_wrapper takes the loader lock, so we take it on the outside. */
2084 mono_loader_lock ();
2086 if (!callinfo->wrapper) {
2087 callinfo->wrapper = p;
2088 mono_register_jit_icall_wrapper (callinfo, p);
2091 mono_loader_unlock ();
2098 mono_jit_compile_method (MonoMethod *method, MonoError *error)
2102 code = mono_jit_compile_method_with_opt (method, mono_get_optimizations_for_method (method, default_opt), error);
2106 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2108 invalidated_delegate_trampoline (char *desc)
2110 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
2111 "See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
2117 * mono_jit_free_method:
2119 * Free all memory allocated by the JIT for METHOD.
2122 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
2124 MonoJitDynamicMethodInfo *ji;
2125 gboolean destroy = TRUE;
2126 GHashTableIter iter;
2127 MonoJumpList *jlist;
2129 g_assert (method->dynamic);
2131 mono_domain_lock (domain);
2132 ji = mono_dynamic_code_hash_lookup (domain, method);
2133 mono_domain_unlock (domain);
2138 mono_debug_remove_method (method, domain);
2140 mono_domain_lock (domain);
2141 g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
2142 mono_domain_jit_code_hash_lock (domain);
2143 mono_internal_hash_table_remove (&domain->jit_code_hash, method);
2144 mono_domain_jit_code_hash_unlock (domain);
2145 g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
2147 /* requires the domain lock - took above */
2148 mono_conc_hashtable_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
2150 /* Remove jump targets in this method */
2151 g_hash_table_iter_init (&iter, domain_jit_info (domain)->jump_target_hash);
2152 while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
2153 GSList *tmp, *remove;
2156 for (tmp = jlist->list; tmp; tmp = tmp->next) {
2157 guint8 *ip = (guint8 *)tmp->data;
2159 if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
2160 remove = g_slist_prepend (remove, tmp);
2162 for (tmp = remove; tmp; tmp = tmp->next) {
2163 jlist->list = g_slist_delete_link ((GSList *)jlist->list, (GSList *)tmp->data);
2165 g_slist_free (remove);
2168 mono_domain_unlock (domain);
2170 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2171 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
2173 * Instead of freeing the code, change it to call an error routine
2174 * so people can fix their code.
2176 char *type = mono_type_full_name (&method->klass->byval_arg);
2177 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
2180 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
2186 * This needs to be done before freeing code_mp, since the code address is the
2187 * key in the table, so if we free the code_mp first, another thread can grab the
2188 * same code address and replace our entry in the table.
2190 mono_jit_info_table_remove (domain, ji->ji);
2193 mono_code_manager_destroy (ji->code_mp);
2198 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
2200 MonoDomain *target_domain;
2203 if (default_opt & MONO_OPT_SHARED)
2204 target_domain = mono_get_root_domain ();
2206 target_domain = domain;
2208 info = lookup_method (target_domain, method);
2210 /* We can't use a domain specific method in another domain */
2211 if (! ((domain != target_domain) && !info->domain_neutral)) {
2212 mono_jit_stats.methods_lookups++;
2215 return info->code_start;
2224 static guint32 bisect_opt = 0;
2225 static GHashTable *bisect_methods_hash = NULL;
2228 mono_set_bisect_methods (guint32 opt, const char *method_list_filename)
2231 char method_name [2048];
2234 bisect_methods_hash = g_hash_table_new (g_str_hash, g_str_equal);
2235 g_assert (bisect_methods_hash);
2237 file = fopen (method_list_filename, "r");
2240 while (fgets (method_name, sizeof (method_name), file)) {
2241 size_t len = strlen (method_name);
2243 g_assert (method_name [len - 1] == '\n');
2244 method_name [len - 1] = 0;
2245 g_hash_table_insert (bisect_methods_hash, g_strdup (method_name), GINT_TO_POINTER (1));
2247 g_assert (feof (file));
2250 gboolean mono_do_single_method_regression = FALSE;
2251 guint32 mono_single_method_regression_opt = 0;
2252 MonoMethod *mono_current_single_method;
2253 GSList *mono_single_method_list;
2254 GHashTable *mono_single_method_hash;
2257 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt)
2261 if (bisect_methods_hash) {
2262 char *name = mono_method_full_name (method, TRUE);
2263 void *res = g_hash_table_lookup (bisect_methods_hash, name);
2266 return default_opt | bisect_opt;
2268 if (!mono_do_single_method_regression)
2270 if (!mono_current_single_method) {
2271 if (!mono_single_method_hash)
2272 mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
2273 if (!g_hash_table_lookup (mono_single_method_hash, method)) {
2274 g_hash_table_insert (mono_single_method_hash, method, method);
2275 mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
2279 if (method == mono_current_single_method)
2280 return mono_single_method_regression_opt;
2285 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
2287 return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
2292 gpointer compiled_method;
2293 gpointer runtime_invoke;
2295 MonoDynCallInfo *dyn_call_info;
2296 MonoClass *ret_box_class;
2297 MonoMethodSignature *sig;
2298 gboolean gsharedvt_invoke;
2299 gpointer *wrapper_arg;
2300 } RuntimeInvokeInfo;
2302 static RuntimeInvokeInfo*
2303 create_runtime_invoke_info (MonoDomain *domain, MonoMethod *method, gpointer compiled_method, gboolean callee_gsharedvt, MonoError *error)
2306 RuntimeInvokeInfo *info;
2308 info = g_new0 (RuntimeInvokeInfo, 1);
2309 info->compiled_method = compiled_method;
2310 info->sig = mono_method_signature (method);
2312 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
2313 info->vtable = mono_class_vtable_full (domain, method->klass, error);
2314 if (!mono_error_ok (error))
2316 g_assert (info->vtable);
2318 MonoMethodSignature *sig = mono_method_signature (method);
2322 * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
2323 * in full-aot mode, so we use a slower, but more generic wrapper if
2324 * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
2326 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2327 if (!mono_llvm_only && (mono_aot_only || debug_options.dyn_runtime_invoke)) {
2328 gboolean supported = TRUE;
2331 if (method->string_ctor)
2332 sig = mono_marshal_get_string_ctor_signature (method);
2334 for (i = 0; i < sig->param_count; ++i) {
2335 MonoType *t = sig->params [i];
2337 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
2341 if (mono_class_is_contextbound (method->klass) || !info->compiled_method)
2345 info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
2349 ret_type = sig->ret;
2350 switch (ret_type->type) {
2351 case MONO_TYPE_VOID:
2363 case MONO_TYPE_BOOLEAN:
2364 case MONO_TYPE_CHAR:
2367 info->ret_box_class = mono_class_from_mono_type (ret_type);
2370 info->ret_box_class = mono_defaults.int_class;
2372 case MONO_TYPE_STRING:
2373 case MONO_TYPE_CLASS:
2374 case MONO_TYPE_ARRAY:
2375 case MONO_TYPE_SZARRAY:
2376 case MONO_TYPE_OBJECT:
2378 case MONO_TYPE_GENERICINST:
2379 if (!MONO_TYPE_IS_REFERENCE (ret_type))
2380 info->ret_box_class = mono_class_from_mono_type (ret_type);
2382 case MONO_TYPE_VALUETYPE:
2383 info->ret_box_class = mono_class_from_mono_type (ret_type);
2386 g_assert_not_reached ();
2390 if (!info->dyn_call_info) {
2391 if (mono_llvm_only) {
2392 #ifndef ENABLE_GSHAREDVT
2393 g_assert_not_reached ();
2395 info->gsharedvt_invoke = TRUE;
2396 if (!callee_gsharedvt) {
2397 /* Invoke a gsharedvt out wrapper instead */
2398 MonoMethod *wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
2399 MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
2401 info->wrapper_arg = g_malloc0 (2 * sizeof (gpointer));
2402 info->wrapper_arg [0] = mini_add_method_wrappers_llvmonly (method, info->compiled_method, FALSE, FALSE, &(info->wrapper_arg [1]));
2404 /* Pass has_rgctx == TRUE since the wrapper has an extra arg */
2405 invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
2406 g_free (wrapper_sig);
2408 info->compiled_method = mono_jit_compile_method (wrapper, error);
2409 if (!mono_error_ok (error)) {
2414 /* Gsharedvt methods can be invoked the same way */
2415 /* The out wrapper has the same signature as the compiled gsharedvt method */
2416 MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
2418 info->wrapper_arg = mono_method_needs_static_rgctx_invoke (method, TRUE) ? mini_method_get_rgctx (method) : NULL;
2420 invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
2421 g_free (wrapper_sig);
2424 info->runtime_invoke = mono_jit_compile_method (invoke, error);
2425 if (!mono_error_ok (error)) {
2435 mono_llvmonly_runtime_invoke (MonoMethod *method, RuntimeInvokeInfo *info, void *obj, void **params, MonoObject **exc, MonoError *error)
2437 MonoMethodSignature *sig = info->sig;
2438 MonoDomain *domain = mono_domain_get ();
2439 MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
2441 gpointer retval_ptr;
2442 guint8 retval [256];
2443 gpointer *param_refs;
2446 mono_error_init (error);
2448 g_assert (info->gsharedvt_invoke);
2451 * Instead of invoking the method directly, we invoke a gsharedvt out wrapper.
2452 * The advantage of this is the gsharedvt out wrappers have a reduced set of
2453 * signatures, so we only have to generate runtime invoke wrappers for these
2455 * This code also handles invocation of gsharedvt methods directly, no
2456 * out wrappers are used in that case.
2458 args = (void **)g_alloca ((sig->param_count + sig->hasthis + 2) * sizeof (gpointer));
2459 param_refs = (gpointer*)g_alloca ((sig->param_count + sig->hasthis + 2) * sizeof (gpointer));
2462 * The runtime invoke wrappers expects pointers to primitive types, so have to
2466 args [pindex ++] = &obj;
2467 if (sig->ret->type != MONO_TYPE_VOID) {
2468 retval_ptr = (gpointer)&retval;
2469 args [pindex ++] = &retval_ptr;
2471 for (i = 0; i < sig->param_count; ++i) {
2472 MonoType *t = sig->params [i];
2474 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
2475 MonoClass *klass = mono_class_from_mono_type (t);
2476 guint8 *nullable_buf;
2479 size = mono_class_value_size (klass, NULL);
2480 nullable_buf = g_alloca (size);
2481 g_assert (nullable_buf);
2483 /* The argument pointed to by params [i] is either a boxed vtype or null */
2484 mono_nullable_init (nullable_buf, (MonoObject*)params [i], klass);
2485 params [i] = nullable_buf;
2488 if (!t->byref && (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR)) {
2489 param_refs [i] = params [i];
2490 params [i] = &(param_refs [i]);
2492 args [pindex ++] = ¶ms [i];
2494 /* The gsharedvt out wrapper has an extra argument which contains the method to call */
2495 args [pindex ++] = &info->wrapper_arg;
2497 runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
2499 runtime_invoke (NULL, args, exc, info->compiled_method);
2501 mono_error_set_exception_instance (error, (MonoException*) *exc);
2503 if (sig->ret->type != MONO_TYPE_VOID && info->ret_box_class)
2504 return mono_value_box (domain, info->ret_box_class, retval);
2506 return *(MonoObject**)retval;
2510 * mono_jit_runtime_invoke:
2511 * @method: the method to invoke
2512 * @obj: this pointer
2513 * @params: array of parameter values.
2514 * @exc: Set to the exception raised in the managed method. If NULL, error is thrown instead.
2515 * If coop is enabled, this argument is ignored - all exceptoins are caught and propagated
2517 * @error: error or caught exception object
2520 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
2522 MonoMethod *invoke, *callee;
2523 MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
2524 MonoDomain *domain = mono_domain_get ();
2525 MonoJitDomainInfo *domain_info;
2526 RuntimeInvokeInfo *info, *info2;
2527 MonoJitInfo *ji = NULL;
2528 gboolean callee_gsharedvt = FALSE;
2530 mono_error_init (error);
2532 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
2533 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
2537 domain_info = domain_jit_info (domain);
2539 info = (RuntimeInvokeInfo *)mono_conc_hashtable_lookup (domain_info->runtime_invoke_hash, method);
2542 if (mono_security_core_clr_enabled ()) {
2544 * This might be redundant since mono_class_vtable () already does this,
2545 * but keep it just in case for moonlight.
2547 mono_class_setup_vtable (method->klass);
2548 if (mono_class_has_failure (method->klass)) {
2549 MonoException *fail_exc = mono_class_get_exception_for_failure (method->klass);
2551 *exc = (MonoObject*)fail_exc;
2552 mono_error_set_exception_instance (error, fail_exc);
2557 gpointer compiled_method;
2560 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
2561 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
2563 * Array Get/Set/Address methods. The JIT implements them using inline code
2564 * inside the runtime invoke wrappers, so no need to compile them.
2566 if (mono_aot_only) {
2568 * Call a wrapper, since the runtime invoke wrapper was not generated.
2570 MonoMethod *wrapper;
2572 wrapper = mono_marshal_get_array_accessor_wrapper (method);
2573 invoke = mono_marshal_get_runtime_invoke (wrapper, FALSE);
2581 compiled_method = mono_jit_compile_method_with_opt (callee, mono_get_optimizations_for_method (callee, default_opt), error);
2582 if (!compiled_method) {
2583 g_assert (!mono_error_ok (error));
2587 if (mono_llvm_only) {
2588 ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
2589 callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
2590 if (callee_gsharedvt)
2591 callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature (jinfo_get_method (ji)));
2594 if (!callee_gsharedvt)
2595 compiled_method = mini_add_method_trampoline (callee, compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
2597 compiled_method = NULL;
2600 info = create_runtime_invoke_info (domain, method, compiled_method, callee_gsharedvt, error);
2601 if (!mono_error_ok (error))
2604 mono_domain_lock (domain);
2605 info2 = (RuntimeInvokeInfo *)mono_conc_hashtable_insert (domain_info->runtime_invoke_hash, method, info);
2606 mono_domain_unlock (domain);
2614 * We need this here because mono_marshal_get_runtime_invoke can place
2615 * the helper method in System.Object and not the target class.
2617 if (!mono_runtime_class_init_full (info->vtable, error)) {
2619 *exc = (MonoObject*) mono_error_convert_to_exception (error);
2623 /* If coop is enabled, and the caller didn't ask for the exception to be caught separately,
2624 we always catch the exception and propagate it through the MonoError */
2625 gboolean catchExcInMonoError =
2626 (exc == NULL) && mono_threads_is_coop_enabled ();
2627 MonoObject *invoke_exc = NULL;
2628 if (catchExcInMonoError)
2631 /* The wrappers expect this to be initialized to NULL */
2635 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2636 if (info->dyn_call_info) {
2637 MonoMethodSignature *sig = mono_method_signature (method);
2639 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
2642 guint8 retval [256];
2644 if (!dyn_runtime_invoke) {
2645 invoke = mono_marshal_get_runtime_invoke_dynamic ();
2646 dyn_runtime_invoke = (RuntimeInvokeDynamicFunction)mono_jit_compile_method (invoke, error);
2647 if (!mono_error_ok (error))
2651 /* Convert the arguments to the format expected by start_dyn_call () */
2652 args = (void **)g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
2655 args [pindex ++] = &obj;
2656 for (i = 0; i < sig->param_count; ++i) {
2657 MonoType *t = sig->params [i];
2660 args [pindex ++] = ¶ms [i];
2661 } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
2662 args [pindex ++] = ¶ms [i];
2664 args [pindex ++] = params [i];
2668 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
2670 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
2672 dyn_runtime_invoke (buf, exc, info->compiled_method);
2673 if (catchExcInMonoError && *exc != NULL)
2674 mono_error_set_exception_instance (error, (MonoException*) *exc);
2676 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
2678 if (info->ret_box_class)
2679 return mono_value_box (domain, info->ret_box_class, retval);
2681 return *(MonoObject**)retval;
2686 return mono_llvmonly_runtime_invoke (method, info, obj, params, exc, error);
2688 runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
2690 MonoObject *result = runtime_invoke ((MonoObject *)obj, params, exc, info->compiled_method);
2691 if (catchExcInMonoError && *exc != NULL)
2692 mono_error_set_exception_instance (error, (MonoException*) *exc);
2701 typedef gpointer (*IMTThunkFunc) (gpointer *arg, MonoMethod *imt_method);
2704 * mini_llvmonly_initial_imt_thunk:
2706 * This function is called the first time a call is made through an IMT thunk.
2707 * It should have the same signature as the mono_llvmonly_imt_thunk_... functions.
2710 mini_llvmonly_initial_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2712 IMTThunkInfo *info = (IMTThunkInfo*)arg;
2717 mono_vtable_build_imt_slot (info->vtable, info->slot);
2719 imt = (gpointer*)info->vtable;
2720 imt -= MONO_IMT_SIZE;
2722 /* Return what the real IMT thunk returns */
2723 ftndesc = imt [info->slot];
2726 if (func == (IMTThunkFunc)mini_llvmonly_initial_imt_thunk)
2727 /* Happens when the imt slot contains only a generic virtual method */
2729 return func ((gpointer *)ftndesc [1], imt_method);
2732 /* This is called indirectly through an imt slot. */
2734 mono_llvmonly_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2738 /* arg points to an array created in mono_llvmonly_get_imt_thunk () */
2739 while (arg [i] && arg [i] != imt_method)
2746 /* Optimized versions of mono_llvmonly_imt_thunk () for different table sizes */
2748 mono_llvmonly_imt_thunk_1 (gpointer *arg, MonoMethod *imt_method)
2750 //g_assert (arg [0] == imt_method);
2755 mono_llvmonly_imt_thunk_2 (gpointer *arg, MonoMethod *imt_method)
2757 //g_assert (arg [0] == imt_method || arg [2] == imt_method);
2758 if (arg [0] == imt_method)
2765 mono_llvmonly_imt_thunk_3 (gpointer *arg, MonoMethod *imt_method)
2767 //g_assert (arg [0] == imt_method || arg [2] == imt_method || arg [4] == imt_method);
2768 if (arg [0] == imt_method)
2770 else if (arg [2] == imt_method)
2777 * A version of the imt thunk used for generic virtual/variant iface methods.
2778 * Unlikely a normal imt thunk, its possible that IMT_METHOD is not found
2779 * in the search table. The original JIT code had a 'fallback' trampoline it could
2780 * call, but we can't do that, so we just return NULL, and the compiled code
2784 mono_llvmonly_fallback_imt_thunk (gpointer *arg, MonoMethod *imt_method)
2788 while (arg [i] && arg [i] != imt_method)
2797 mono_llvmonly_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
2801 int i, index, real_count;
2802 gboolean virtual_generic = FALSE;
2805 * Create an array which is passed to the imt thunk functions.
2806 * The array contains MonoMethod-function descriptor pairs, terminated by a NULL entry.
2810 for (i = 0; i < count; ++i) {
2811 MonoIMTCheckItem *item = imt_entries [i];
2813 if (item->is_equals)
2815 if (item->has_target_code)
2816 virtual_generic = TRUE;
2820 * Initialize all vtable entries reachable from this imt slot, so the compiled
2821 * code doesn't have to check it.
2823 for (i = 0; i < count; ++i) {
2824 MonoIMTCheckItem *item = imt_entries [i];
2827 if (!item->is_equals || item->has_target_code)
2829 vt_slot = item->value.vtable_slot;
2830 mono_init_vtable_slot (vtable, vt_slot);
2833 /* Save the entries into an array */
2834 buf = (void **)mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
2836 for (i = 0; i < count; ++i) {
2837 MonoIMTCheckItem *item = imt_entries [i];
2839 if (!item->is_equals)
2842 g_assert (item->key);
2843 buf [(index * 2)] = item->key;
2844 if (item->has_target_code)
2845 buf [(index * 2) + 1] = item->value.target_code;
2847 buf [(index * 2) + 1] = vtable->vtable [item->value.vtable_slot];
2850 buf [(index * 2)] = NULL;
2851 buf [(index * 2) + 1] = fail_tramp;
2854 * Return a function descriptor for a C function with 'buf' as its argument.
2855 * It will by called by JITted code.
2857 res = (void **)mono_domain_alloc (domain, 2 * sizeof (gpointer));
2858 switch (real_count) {
2860 res [0] = mono_llvmonly_imt_thunk_1;
2863 res [0] = mono_llvmonly_imt_thunk_2;
2866 res [0] = mono_llvmonly_imt_thunk_3;
2869 res [0] = mono_llvmonly_imt_thunk;
2872 if (virtual_generic || fail_tramp)
2873 res [0] = mono_llvmonly_fallback_imt_thunk;
2879 MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
2881 MonoException *exc = NULL;
2883 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2884 MONO_SIG_HANDLER_GET_CONTEXT;
2886 ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
2888 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
2889 if (mono_arch_is_int_overflow (ctx, info))
2891 * The spec says this throws ArithmeticException, but MS throws the derived
2892 * OverflowException.
2894 exc = mono_get_exception_overflow ();
2896 exc = mono_get_exception_divide_by_zero ();
2898 exc = mono_get_exception_divide_by_zero ();
2902 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2905 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2906 if (mono_do_crash_chaining) {
2907 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2912 mono_arch_handle_exception (ctx, exc);
2915 MONO_SIG_HANDLER_FUNC (, mono_sigill_signal_handler)
2918 MONO_SIG_HANDLER_GET_CONTEXT;
2920 exc = mono_get_exception_execution_engine ("SIGILL");
2922 mono_arch_handle_exception (ctx, exc);
2925 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
2926 #define HAVE_SIG_INFO
2929 MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
2932 MonoJitTlsData *jit_tls = (MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id);
2933 gpointer fault_addr = NULL;
2934 #ifdef HAVE_SIG_INFO
2935 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2939 MONO_SIG_HANDLER_GET_CONTEXT;
2941 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
2942 if (mono_arch_is_single_step_event (info, ctx)) {
2943 mono_debugger_agent_single_step_event (ctx);
2945 } else if (mono_arch_is_breakpoint_event (info, ctx)) {
2946 mono_debugger_agent_breakpoint_hit (ctx);
2951 #if defined(HAVE_SIG_INFO)
2952 #if !defined(HOST_WIN32)
2953 fault_addr = info->si_addr;
2954 if (mono_aot_is_pagefault (info->si_addr)) {
2955 mono_aot_handle_pagefault (info->si_addr);
2960 /* The thread might no be registered with the runtime */
2961 if (!mono_domain_get () || !jit_tls) {
2962 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2964 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2965 if (mono_do_crash_chaining) {
2966 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2972 ji = mono_jit_info_table_find_internal (mono_domain_get (), (char *)mono_arch_ip_from_context (ctx), TRUE, TRUE);
2974 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2975 if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
2978 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2979 /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
2980 fault_addr = info->si_addr;
2981 if (fault_addr == NULL) {
2984 mono_sigctx_to_monoctx (ctx, &mctx);
2986 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
2990 if (jit_tls->stack_size &&
2991 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
2993 * The hard-guard page has been hit: there is not much we can do anymore
2994 * Print a hopefully clear message and abort.
2996 mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
2997 g_assert_not_reached ();
2999 /* The original handler might not like that it is executed on an altstack... */
3000 if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
3003 mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
3008 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
3011 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
3013 if (mono_do_crash_chaining) {
3014 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
3019 mono_arch_handle_exception (ctx, NULL);
3023 MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
3026 MONO_SIG_HANDLER_GET_CONTEXT;
3028 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
3030 mono_arch_handle_exception (ctx, exc);
3033 #ifndef DISABLE_REMOTING
3034 /* mono_jit_create_remoting_trampoline:
3035 * @method: pointer to the method info
3037 * Creates a trampoline which calls the remoting functions. This
3038 * is used in the vtable of transparent proxies.
3040 * Returns: a pointer to the newly created code
3043 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
3046 guint8 *addr = NULL;
3048 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
3049 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
3053 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
3054 (mono_method_signature (method)->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))) {
3055 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
3056 addr = (guint8 *)mono_compile_method (nm);
3059 addr = (guint8 *)mono_compile_method (method);
3061 return mono_get_addr_from_ftnptr (addr);
3066 no_imt_trampoline (void)
3068 g_assert_not_reached ();
3072 no_vcall_trampoline (void)
3074 g_assert_not_reached ();
3077 static gpointer *vtable_trampolines;
3078 static int vtable_trampolines_size;
3081 mini_get_vtable_trampoline (MonoVTable *vt, int slot_index)
3083 int index = slot_index + MONO_IMT_SIZE;
3085 if (mono_llvm_only) {
3086 if (slot_index < 0) {
3087 /* Initialize the IMT thunks to a 'trampoline' so the generated code doesn't have to initialize it */
3088 // FIXME: Memory management
3089 gpointer *ftndesc = g_malloc (2 * sizeof (gpointer));
3090 IMTThunkInfo *info = g_new0 (IMTThunkInfo, 1);
3093 ftndesc [0] = mini_llvmonly_initial_imt_thunk;
3095 mono_memory_barrier ();
3102 g_assert (slot_index >= - MONO_IMT_SIZE);
3103 if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
3105 if (!vtable_trampolines || index >= vtable_trampolines_size) {
3109 new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
3110 while (new_size <= index)
3112 new_table = g_new0 (gpointer, new_size);
3114 if (vtable_trampolines)
3115 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
3116 g_free (vtable_trampolines);
3117 mono_memory_barrier ();
3118 vtable_trampolines = (void **)new_table;
3119 vtable_trampolines_size = new_size;
3124 if (!vtable_trampolines [index])
3125 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
3126 return vtable_trampolines [index];
3130 mini_get_imt_trampoline (MonoVTable *vt, int slot_index)
3132 return mini_get_vtable_trampoline (vt, slot_index - MONO_IMT_SIZE);
3136 mini_imt_entry_inited (MonoVTable *vt, int imt_slot_index)
3141 gpointer *imt = (gpointer*)vt;
3142 imt -= MONO_IMT_SIZE;
3144 return (imt [imt_slot_index] != mini_get_imt_trampoline (vt, imt_slot_index));
3148 is_callee_gsharedvt_variable (gpointer addr)
3151 gboolean callee_gsharedvt;
3153 ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (addr), NULL);
3155 callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
3156 if (callee_gsharedvt)
3157 callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature (jinfo_get_method (ji)));
3158 return callee_gsharedvt;
3162 mini_get_delegate_arg (MonoMethod *method, gpointer method_ptr)
3164 gpointer arg = NULL;
3166 if (mono_method_needs_static_rgctx_invoke (method, FALSE))
3167 arg = mini_method_get_rgctx (method);
3170 * Avoid adding gsharedvt in wrappers since they might not exist if
3171 * this delegate is called through a gsharedvt delegate invoke wrapper.
3172 * Instead, encode that the method is gsharedvt in del->extra_arg,
3173 * the CEE_MONO_CALLI_EXTRA_ARG implementation in the JIT depends on this.
3175 if (method->is_inflated && is_callee_gsharedvt_variable (method_ptr)) {
3176 g_assert ((((mgreg_t)arg) & 1) == 0);
3177 arg = (gpointer)(((mgreg_t)arg) | 1);
3183 mini_init_delegate (MonoDelegate *del)
3186 del->extra_arg = mini_get_delegate_arg (del->method, del->method_ptr);
3190 mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
3192 gboolean is_virtual_generic, is_interface, load_imt_reg;
3195 static guint8 **cache = NULL;
3196 static int cache_size = 0;
3201 if (MONO_TYPE_ISSTRUCT (sig->ret))
3204 is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
3205 is_interface = method->klass->flags & TYPE_ATTRIBUTE_INTERFACE ? TRUE : FALSE;
3206 load_imt_reg = is_virtual_generic || is_interface;
3209 offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * SIZEOF_VOID_P;
3211 offset = G_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
3213 idx = (offset / SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
3214 g_assert (idx >= 0);
3216 /* Resize the cache to idx + 1 */
3217 if (cache_size < idx + 1) {
3219 if (cache_size < idx + 1) {
3221 int new_cache_size = idx + 1;
3223 new_cache = g_new0 (guint8*, new_cache_size);
3225 memcpy (new_cache, cache, cache_size * sizeof (guint8*));
3228 mono_memory_barrier ();
3230 cache_size = new_cache_size;
3238 /* FIXME Support more cases */
3239 if (mono_aot_only) {
3240 char tramp_name [256];
3241 const char *imt = load_imt_reg ? "_imt" : "";
3242 int ind = (load_imt_reg ? (-offset) : offset) / SIZEOF_VOID_P;
3244 sprintf (tramp_name, "delegate_virtual_invoke%s_%d", imt, ind);
3245 cache [idx] = (guint8 *)mono_aot_get_trampoline (tramp_name);
3246 g_assert (cache [idx]);
3248 cache [idx] = (guint8 *)mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
3254 * mini_parse_debug_option:
3255 * @option: The option to parse.
3257 * Parses debug options for the mono runtime. The options are the same as for
3258 * the MONO_DEBUG environment variable.
3262 mini_parse_debug_option (const char *option)
3264 if (!strcmp (option, "handle-sigint"))
3265 debug_options.handle_sigint = TRUE;
3266 else if (!strcmp (option, "keep-delegates"))
3267 debug_options.keep_delegates = TRUE;
3268 else if (!strcmp (option, "reverse-pinvoke-exceptions"))
3269 debug_options.reverse_pinvoke_exceptions = TRUE;
3270 else if (!strcmp (option, "collect-pagefault-stats"))
3271 debug_options.collect_pagefault_stats = TRUE;
3272 else if (!strcmp (option, "break-on-unverified"))
3273 debug_options.break_on_unverified = TRUE;
3274 else if (!strcmp (option, "no-gdb-backtrace"))
3275 debug_options.no_gdb_backtrace = TRUE;
3276 else if (!strcmp (option, "suspend-on-sigsegv"))
3277 debug_options.suspend_on_sigsegv = TRUE;
3278 else if (!strcmp (option, "suspend-on-exception"))
3279 debug_options.suspend_on_exception = TRUE;
3280 else if (!strcmp (option, "suspend-on-unhandled"))
3281 debug_options.suspend_on_unhandled = TRUE;
3282 else if (!strcmp (option, "dont-free-domains"))
3283 mono_dont_free_domains = TRUE;
3284 else if (!strcmp (option, "dyn-runtime-invoke"))
3285 debug_options.dyn_runtime_invoke = TRUE;
3286 else if (!strcmp (option, "gdb"))
3287 debug_options.gdb = TRUE;
3288 else if (!strcmp (option, "explicit-null-checks"))
3289 debug_options.explicit_null_checks = TRUE;
3290 else if (!strcmp (option, "gen-seq-points"))
3291 debug_options.gen_sdb_seq_points = TRUE;
3292 else if (!strcmp (option, "gen-compact-seq-points"))
3293 debug_options.gen_seq_points_compact_data = TRUE;
3294 else if (!strcmp (option, "single-imm-size"))
3295 debug_options.single_imm_size = TRUE;
3296 else if (!strcmp (option, "init-stacks"))
3297 debug_options.init_stacks = TRUE;
3298 else if (!strcmp (option, "casts"))
3299 debug_options.better_cast_details = TRUE;
3300 else if (!strcmp (option, "soft-breakpoints"))
3301 debug_options.soft_breakpoints = TRUE;
3302 else if (!strcmp (option, "check-pinvoke-callconv"))
3303 debug_options.check_pinvoke_callconv = TRUE;
3304 else if (!strcmp (option, "arm-use-fallback-tls"))
3305 debug_options.arm_use_fallback_tls = TRUE;
3306 else if (!strcmp (option, "debug-domain-unload"))
3307 mono_enable_debug_domain_unload (TRUE);
3308 else if (!strcmp (option, "partial-sharing"))
3309 mono_set_partial_sharing_supported (TRUE);
3310 else if (!strcmp (option, "align-small-structs"))
3311 mono_align_small_structs = TRUE;
3312 else if (!strcmp (option, "native-debugger-break"))
3313 debug_options.native_debugger_break = TRUE;
3321 mini_parse_debug_options (void)
3323 const char *options = g_getenv ("MONO_DEBUG");
3324 gchar **args, **ptr;
3329 args = g_strsplit (options, ",", -1);
3331 for (ptr = args; ptr && *ptr; ptr++) {
3332 const char *arg = *ptr;
3334 if (!mini_parse_debug_option (arg)) {
3335 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
3336 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'suspend-on-sigsegv', 'suspend-on-exception', 'suspend-on-unhandled', 'dont-free-domains', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'gen-seq-points', 'gen-compact-seq-points', 'single-imm-size', 'init-stacks', 'casts', 'soft-breakpoints', 'check-pinvoke-callconv', 'arm-use-fallback-tls', 'debug-domain-unload', 'partial-sharing', 'align-small-structs', 'native-debugger-break'\n");
3345 mini_get_debug_options (void)
3347 return &debug_options;
3351 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
3353 #if !defined(__ia64__) && (!defined(__ppc64__) && !defined(__powerpc64__) || _CALL_ELF == 2)
3356 gpointer* desc = NULL;
3358 if ((desc = g_hash_table_lookup (domain->ftnptrs_hash, addr)))
3361 desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
3365 # elif defined(__ppc64__) || defined(__powerpc64__)
3367 desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
3373 g_hash_table_insert (domain->ftnptrs_hash, addr, desc);
3379 mini_get_addr_from_ftnptr (gpointer descr)
3381 #if defined(__ia64__) || ((defined(__ppc64__) || defined(__powerpc64__)) && _CALL_ELF != 2)
3382 return *(gpointer*)descr;
3389 register_jit_stats (void)
3391 mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
3392 mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
3393 mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
3394 mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
3395 mono_counters_register ("JIT/method-to-IR (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_method_to_ir);
3396 mono_counters_register ("JIT/liveness_handle_exception_clauses (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_liveness_handle_exception_clauses);
3397 mono_counters_register ("JIT/handle_out_of_line_bblock (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_out_of_line_bblock);
3398 mono_counters_register ("JIT/decompose_long_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_long_opts);
3399 mono_counters_register ("JIT/local_cprop (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_cprop);
3400 mono_counters_register ("JIT/local_emulate_ops (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_emulate_ops);
3401 mono_counters_register ("JIT/optimize_branches (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_optimize_branches);
3402 mono_counters_register ("JIT/handle_global_vregs (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_global_vregs);
3403 mono_counters_register ("JIT/local_deadce (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_deadce);
3404 mono_counters_register ("JIT/local_alias_analysis (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_alias_analysis);
3405 mono_counters_register ("JIT/if_conversion (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_if_conversion);
3406 mono_counters_register ("JIT/bb_ordering (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_bb_ordering);
3407 mono_counters_register ("JIT/compile_dominator_info (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_compile_dominator_info);
3408 mono_counters_register ("JIT/compute_natural_loops (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_compute_natural_loops);
3409 mono_counters_register ("JIT/insert_safepoints (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_insert_safepoints);
3410 mono_counters_register ("JIT/ssa_compute (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_compute);
3411 mono_counters_register ("JIT/ssa_cprop (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_cprop);
3412 mono_counters_register ("JIT/ssa_deadce(sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_deadce);
3413 mono_counters_register ("JIT/perform_abc_removal (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_perform_abc_removal);
3414 mono_counters_register ("JIT/ssa_remove (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_ssa_remove);
3415 mono_counters_register ("JIT/local_cprop2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_cprop2);
3416 mono_counters_register ("JIT/handle_global_vregs2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_global_vregs2);
3417 mono_counters_register ("JIT/local_deadce2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_deadce2);
3418 mono_counters_register ("JIT/optimize_branches2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_optimize_branches2);
3419 mono_counters_register ("JIT/decompose_vtype_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_vtype_opts);
3420 mono_counters_register ("JIT/decompose_array_access_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_array_access_opts);
3421 mono_counters_register ("JIT/liveness_handle_exception_clauses2 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_liveness_handle_exception_clauses2);
3422 mono_counters_register ("JIT/analyze_liveness (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_analyze_liveness);
3423 mono_counters_register ("JIT/linear_scan (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_linear_scan);
3424 mono_counters_register ("JIT/arch_allocate_vars (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_arch_allocate_vars);
3425 mono_counters_register ("JIT/spill_global_vars (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_spill_global_vars);
3426 mono_counters_register ("JIT/local_cprop3 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_cprop3);
3427 mono_counters_register ("JIT/local_deadce3 (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_local_deadce3);
3428 mono_counters_register ("JIT/codegen (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_codegen);
3429 mono_counters_register ("JIT/create_jit_info (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_create_jit_info);
3430 mono_counters_register ("JIT/gc_create_gc_map (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_gc_create_gc_map);
3431 mono_counters_register ("JIT/save_seq_point_info (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_save_seq_point_info);
3432 mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
3433 mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks);
3434 mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks);
3435 mono_counters_register ("Allocated vars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocate_var);
3436 mono_counters_register ("Code reallocs", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.code_reallocs);
3437 mono_counters_register ("Allocated code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_code_size);
3438 mono_counters_register ("Allocated seq points size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_seq_points_size);
3439 mono_counters_register ("Inlineable methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlineable_methods);
3440 mono_counters_register ("Inlined methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlined_methods);
3441 mono_counters_register ("Regvars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.regvars);
3442 mono_counters_register ("Locals stack size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.locals_stack_size);
3443 mono_counters_register ("Method cache lookups", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_lookups);
3444 mono_counters_register ("Compiled CIL code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.cil_code_size);
3445 mono_counters_register ("Native code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.native_code_size);
3446 mono_counters_register ("Aliases found", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_found);
3447 mono_counters_register ("Aliases eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_removed);
3448 mono_counters_register ("Aliased loads eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.loads_eliminated);
3449 mono_counters_register ("Aliased stores eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.stores_eliminated);
3452 static void runtime_invoke_info_free (gpointer value);
3455 class_method_pair_equal (gconstpointer ka, gconstpointer kb)
3457 const MonoClassMethodPair *apair = (const MonoClassMethodPair *)ka;
3458 const MonoClassMethodPair *bpair = (const MonoClassMethodPair *)kb;
3460 return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
3464 class_method_pair_hash (gconstpointer data)
3466 const MonoClassMethodPair *pair = (const MonoClassMethodPair *)data;
3468 return (gsize)pair->klass ^ (gsize)pair->method;
3472 mini_create_jit_domain_info (MonoDomain *domain)
3474 MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
3476 info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3477 info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3478 info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
3479 info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
3480 info->runtime_invoke_hash = mono_conc_hashtable_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
3481 info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, mono_seq_point_info_free);
3482 info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
3483 info->jump_target_hash = g_hash_table_new (NULL, NULL);
3485 domain->runtime_info = info;
3489 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
3491 MonoJumpList *jlist = (MonoJumpList *)value;
3492 g_slist_free (jlist->list);
3496 delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
3498 GSList *list = (GSList *)value;
3499 g_slist_free (list);
3503 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
3505 MonoJitDynamicMethodInfo *di = (MonoJitDynamicMethodInfo *)value;
3506 mono_code_manager_destroy (di->code_mp);
3511 runtime_invoke_info_free (gpointer value)
3513 RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
3515 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3516 if (info->dyn_call_info)
3517 mono_arch_dyn_call_free (info->dyn_call_info);
3523 mini_free_jit_domain_info (MonoDomain *domain)
3525 MonoJitDomainInfo *info = domain_jit_info (domain);
3527 g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
3528 g_hash_table_destroy (info->jump_target_hash);
3529 if (info->jump_target_got_slot_hash) {
3530 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
3531 g_hash_table_destroy (info->jump_target_got_slot_hash);
3533 if (info->dynamic_code_hash) {
3534 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
3535 g_hash_table_destroy (info->dynamic_code_hash);
3537 if (info->method_code_hash)
3538 g_hash_table_destroy (info->method_code_hash);
3539 g_hash_table_destroy (info->jump_trampoline_hash);
3540 g_hash_table_destroy (info->jit_trampoline_hash);
3541 g_hash_table_destroy (info->delegate_trampoline_hash);
3542 if (info->static_rgctx_trampoline_hash)
3543 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
3544 g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
3545 mono_conc_hashtable_destroy (info->runtime_invoke_hash);
3546 g_hash_table_destroy (info->seq_points);
3547 g_hash_table_destroy (info->arch_seq_points);
3548 if (info->agent_info)
3549 mono_debugger_agent_free_domain_info (domain);
3550 if (info->gsharedvt_arg_tramp_hash)
3551 g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
3553 mono_llvm_free_domain_info (domain);
3556 g_free (domain->runtime_info);
3557 domain->runtime_info = NULL;
3562 llvm_init_inner (void)
3564 if (!mono_llvm_load (NULL))
3575 * Load and initialize LLVM support.
3576 * Return TRUE on success.
3579 mini_llvm_init (void)
3582 static gboolean llvm_inited;
3583 static gboolean init_result;
3585 mono_loader_lock_if_inited ();
3587 init_result = llvm_init_inner ();
3590 mono_loader_unlock_if_inited ();
3598 mini_init (const char *filename, const char *runtime_version)
3602 MonoRuntimeCallbacks callbacks;
3603 MonoThreadInfoRuntimeCallbacks ticallbacks;
3605 MONO_VES_INIT_BEGIN ();
3607 CHECKED_MONO_INIT ();
3609 #if defined(__linux__) && !defined(__native_client__)
3610 if (access ("/proc/self/maps", F_OK) != 0) {
3611 g_print ("Mono requires /proc to be mounted.\n");
3616 mono_os_mutex_init_recursive (&jit_mutex);
3618 mono_cross_helpers_run ();
3622 /* Happens when using the embedding interface */
3623 if (!default_opt_set)
3624 default_opt = mono_parse_default_optimizations (NULL);
3626 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3628 mono_set_generic_sharing_vt_supported (TRUE);
3631 mono_set_generic_sharing_vt_supported (TRUE);
3634 #ifdef MONO_HAVE_FAST_TLS
3635 MONO_FAST_TLS_INIT (mono_jit_tls);
3636 MONO_FAST_TLS_INIT (mono_lmf_addr);
3637 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
3638 MONO_FAST_TLS_INIT (mono_lmf);
3642 mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
3644 if (!global_codeman)
3645 global_codeman = mono_code_manager_new ();
3647 memset (&callbacks, 0, sizeof (callbacks));
3648 callbacks.create_ftnptr = mini_create_ftnptr;
3649 callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
3650 callbacks.get_runtime_build_info = mono_get_runtime_build_info;
3651 callbacks.set_cast_details = mono_set_cast_details;
3652 callbacks.debug_log = mono_debugger_agent_debug_log;
3653 callbacks.debug_log_is_enabled = mono_debugger_agent_debug_log_is_enabled;
3654 callbacks.tls_key_supported = mini_tls_key_supported;
3655 callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
3656 callbacks.get_imt_trampoline = mini_get_imt_trampoline;
3657 callbacks.imt_entry_inited = mini_imt_entry_inited;
3658 callbacks.init_delegate = mini_init_delegate;
3659 #define JIT_INVOKE_WORKS
3660 #ifdef JIT_INVOKE_WORKS
3661 callbacks.runtime_invoke = mono_jit_runtime_invoke;
3663 #define JIT_TRAMPOLINES_WORK
3664 #ifdef JIT_TRAMPOLINES_WORK
3665 callbacks.compile_method = mono_jit_compile_method;
3666 callbacks.create_jump_trampoline = mono_create_jump_trampoline;
3667 callbacks.create_jit_trampoline = mono_create_jit_trampoline;
3670 mono_install_callbacks (&callbacks);
3672 memset (&ticallbacks, 0, sizeof (ticallbacks));
3673 ticallbacks.setup_async_callback = mono_setup_async_callback;
3674 ticallbacks.thread_state_init_from_sigctx = mono_thread_state_init_from_sigctx;
3675 ticallbacks.thread_state_init_from_handle = mono_thread_state_init_from_handle;
3676 ticallbacks.thread_state_init = mono_thread_state_init;
3678 mono_counters_init ();
3680 mono_threads_runtime_init (&ticallbacks);
3682 if (g_getenv ("MONO_DEBUG") != NULL)
3683 mini_parse_debug_options ();
3685 mono_code_manager_init ();
3689 mono_arch_cpu_init ();
3693 mono_unwind_init ();
3695 #ifdef XDEBUG_ENABLED
3696 if (g_getenv ("MONO_XDEBUG")) {
3697 const char *xdebug_opts = g_getenv ("MONO_XDEBUG");
3698 mono_xdebug_init (xdebug_opts);
3699 /* So methods for multiple domains don't have the same address */
3700 mono_dont_free_domains = TRUE;
3701 mono_using_xdebug = TRUE;
3702 } else if (mini_get_debug_options ()->gdb) {
3703 mono_xdebug_init ((char*)"gdb");
3704 mono_dont_free_domains = TRUE;
3705 mono_using_xdebug = TRUE;
3710 if (mono_use_llvm) {
3711 if (!mono_llvm_load (NULL)) {
3712 mono_use_llvm = FALSE;
3713 fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
3720 mono_trampolines_init ();
3722 mono_native_tls_alloc (&mono_jit_tls_id, NULL);
3724 if (default_opt & MONO_OPT_AOT)
3727 mono_debugger_agent_init ();
3729 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3730 mono_set_generic_sharing_supported (TRUE);
3733 #ifndef MONO_CROSS_COMPILE
3734 mono_runtime_install_handlers ();
3736 mono_threads_install_cleanup (mini_thread_cleanup);
3738 #ifdef JIT_TRAMPOLINES_WORK
3739 mono_install_free_method (mono_jit_free_method);
3740 #ifndef DISABLE_REMOTING
3741 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
3743 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
3744 mono_install_create_domain_hook (mini_create_jit_domain_info);
3745 mono_install_free_domain_hook (mini_free_jit_domain_info);
3747 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
3748 mono_install_get_class_from_name (mono_aot_get_class_from_name);
3749 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
3751 if (debug_options.collect_pagefault_stats)
3752 mono_aot_set_make_unreadable (TRUE);
3754 if (runtime_version)
3755 domain = mono_init_version (filename, runtime_version);
3757 domain = mono_init_from_assembly (filename, filename);
3759 if (mono_aot_only) {
3760 /* This helps catch code allocation requests */
3761 mono_code_manager_set_read_only (domain->code_mp);
3762 mono_marshal_use_aot_wrappers (TRUE);
3765 if (mono_llvm_only) {
3766 mono_install_imt_thunk_builder (mono_llvmonly_get_imt_thunk);
3767 mono_set_always_build_imt_thunks (TRUE);
3768 } else if (mono_aot_only) {
3769 mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
3771 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
3774 /*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
3775 mono_arch_finish_init ();
3779 /* This must come after mono_init () in the aot-only case */
3780 mono_exceptions_init ();
3782 /* This should come after mono_init () too */
3786 mono_create_helper_signatures ();
3789 register_jit_stats ();
3791 #define JIT_CALLS_WORK
3792 #ifdef JIT_CALLS_WORK
3793 /* Needs to be called here since register_jit_icall depends on it */
3794 mono_marshal_init ();
3796 mono_arch_register_lowlevel_calls ();
3800 mono_generic_sharing_init ();
3803 #ifdef MONO_ARCH_SIMD_INTRINSICS
3804 mono_simd_intrinsics_init ();
3807 #if MONO_SUPPORT_TASKLETS
3808 mono_tasklets_init ();
3811 register_trampolines (domain);
3813 if (mono_compile_aot)
3815 * Avoid running managed code when AOT compiling, since the platform
3816 * might only support aot-only execution.
3818 mono_runtime_set_no_exec (TRUE);
3820 #define JIT_RUNTIME_WORKS
3821 #ifdef JIT_RUNTIME_WORKS
3822 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
3823 mono_runtime_init_checked (domain, mono_thread_start_cb, mono_thread_attach_cb, &error);
3824 mono_error_assert_ok (&error);
3825 mono_thread_attach (domain);
3828 mono_profiler_runtime_initialized ();
3830 MONO_VES_INIT_END ();
3836 register_icalls (void)
3838 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
3839 ves_icall_get_frame_info);
3840 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
3841 ves_icall_get_trace);
3842 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
3843 mono_runtime_install_handlers);
3845 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
3846 mono_add_internal_call ("System.Diagnostics.Debugger::Mono_UnhandledException_internal",
3847 mono_debugger_agent_unhandled_exception);
3851 * It's important that we pass `TRUE` as the last argument here, as
3852 * it causes the JIT to omit a wrapper for these icalls. If the JIT
3853 * *did* emit a wrapper, we'd be looking at infinite recursion since
3854 * the wrapper would call the icall which would call the wrapper and
3857 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", "void ptr", TRUE);
3858 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", "void ptr", TRUE);
3860 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
3861 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
3862 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
3863 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr ptr", TRUE);
3864 register_icall (mono_jit_thread_detach, "mono_jit_thread_detach", "void ptr ptr", TRUE);
3865 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
3867 register_icall (mono_llvm_throw_exception, "mono_llvm_throw_exception", "void object", TRUE);
3868 register_icall (mono_llvm_rethrow_exception, "mono_llvm_rethrow_exception", "void object", TRUE);
3869 register_icall (mono_llvm_resume_exception, "mono_llvm_resume_exception", "void", TRUE);
3870 register_icall (mono_llvm_match_exception, "mono_llvm_match_exception", "int ptr int int", TRUE);
3871 register_icall (mono_llvm_clear_exception, "mono_llvm_clear_exception", NULL, TRUE);
3872 register_icall (mono_llvm_load_exception, "mono_llvm_load_exception", "object", TRUE);
3873 register_icall (mono_llvm_throw_corlib_exception, "mono_llvm_throw_corlib_exception", "void int", TRUE);
3874 #if defined(ENABLE_LLVM) && !defined(MONO_LLVM_LOADED)
3875 register_icall (mono_llvm_set_unhandled_exception_handler, "mono_llvm_set_unhandled_exception_handler", NULL, TRUE);
3877 // FIXME: This is broken
3878 register_icall (mono_debug_personality, "mono_debug_personality", "int int int ptr ptr ptr", TRUE);
3881 register_dyn_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
3882 register_dyn_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
3883 register_dyn_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", "void ptr", TRUE);
3884 register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
3885 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "object", FALSE);
3886 register_icall (mono_thread_force_interruption_checkpoint_noraise, "mono_thread_force_interruption_checkpoint_noraise", "object", FALSE);
3887 #ifndef DISABLE_REMOTING
3888 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
3889 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
3892 #if defined(__native_client__) || defined(__native_client_codegen__)
3893 register_icall (mono_nacl_gc, "mono_nacl_gc", "void", FALSE);
3896 if (mono_threads_is_coop_enabled ())
3897 register_icall (mono_threads_state_poll, "mono_threads_state_poll", "void", FALSE);
3899 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
3900 register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, "mono_llmult", TRUE);
3901 register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, "mono_lldiv", FALSE);
3902 register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, "mono_lldiv_un", FALSE);
3903 register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, "mono_llrem", FALSE);
3904 register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, "mono_llrem_un", FALSE);
3906 #if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
3907 register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, "mono_llmult_ovf_un", FALSE);
3908 register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, "mono_llmult_ovf", FALSE);
3911 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
3912 register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, "mono_lshl", TRUE);
3913 register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, "mono_lshr", TRUE);
3914 register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, "mono_lshr_un", TRUE);
3917 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
3918 register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, "mono_idiv", FALSE);
3919 register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, "mono_idiv_un", FALSE);
3920 register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, "mono_irem", FALSE);
3921 register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, "mono_irem_un", FALSE);
3924 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3925 register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, "mono_imul", TRUE);
3928 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
3929 register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, "mono_imul_ovf", FALSE);
3930 register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, "mono_imul_ovf_un", FALSE);
3933 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
3934 register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, "mono_fdiv", FALSE);
3937 register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, "mono_fconv_u8", FALSE);
3938 register_opcode_emulation (OP_RCONV_TO_U8, "__emul_rconv_to_u8", "ulong float", mono_rconv_u8, "mono_rconv_u8", FALSE);
3939 register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, "mono_fconv_u4", FALSE);
3940 register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, "mono_fconv_ovf_i8", FALSE);
3941 register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, "mono_fconv_ovf_u8", FALSE);
3942 register_opcode_emulation (OP_RCONV_TO_OVF_I8, "__emul_rconv_to_ovf_i8", "long float", mono_rconv_ovf_i8, "mono_rconv_ovf_i8", FALSE);
3943 register_opcode_emulation (OP_RCONV_TO_OVF_U8, "__emul_rconv_to_ovf_u8", "ulong float", mono_rconv_ovf_u8, "mono_rconv_ovf_u8", FALSE);
3946 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
3947 register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, "mono_fconv_i8", FALSE);
3948 register_opcode_emulation (OP_RCONV_TO_I8, "__emul_rconv_to_i8", "long float", mono_rconv_i8, "mono_rconv_i8", FALSE);
3951 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
3952 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);
3954 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
3955 register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, "mono_lconv_to_r8", FALSE);
3957 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
3958 register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, "mono_lconv_to_r4", FALSE);
3960 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
3961 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);
3963 #ifdef MONO_ARCH_EMULATE_FREM
3964 #if defined(__default_codegen__)
3965 register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, "fmod", FALSE);
3966 register_opcode_emulation (OP_RREM, "__emul_rrem", "float float float", fmodf, "fmodf", FALSE);
3967 #elif defined(__native_client_codegen__)
3968 register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, "mono_fmod", FALSE);
3972 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3973 if (mono_arch_is_soft_float ()) {
3974 register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, "mono_fsub", FALSE);
3975 register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, "mono_fadd", FALSE);
3976 register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, "mono_fmul", FALSE);
3977 register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, "mono_fneg", FALSE);
3978 register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, "mono_conv_to_r8", FALSE);
3979 register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, "mono_conv_to_r4", FALSE);
3980 register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, "mono_fconv_r4", FALSE);
3981 register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, "mono_fconv_i1", FALSE);
3982 register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, "mono_fconv_i2", FALSE);
3983 register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3984 register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, "mono_fconv_u1", FALSE);
3985 register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, "mono_fconv_u2", FALSE);
3987 #if SIZEOF_VOID_P == 4
3988 register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3991 register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, "mono_fcmp_eq", FALSE);
3992 register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, "mono_fcmp_lt", FALSE);
3993 register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, "mono_fcmp_gt", FALSE);
3994 register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, "mono_fcmp_le", FALSE);
3995 register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, "mono_fcmp_ge", FALSE);
3996 register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, "mono_fcmp_ne_un", FALSE);
3997 register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, "mono_fcmp_lt_un", FALSE);
3998 register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, "mono_fcmp_gt_un", FALSE);
3999 register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, "mono_fcmp_le_un", FALSE);
4000 register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, "mono_fcmp_ge_un", FALSE);
4002 register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, "mono_fceq", FALSE);
4003 register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, "mono_fcgt", FALSE);
4004 register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, "mono_fcgt_un", FALSE);
4005 register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, "mono_fclt", FALSE);
4006 register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, "mono_fclt_un", FALSE);
4008 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
4009 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
4010 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
4011 register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
4014 register_icall (mono_ckfinite, "mono_ckfinite", "double double", FALSE);
4016 #ifdef COMPRESSED_INTERFACE_BITMAP
4017 register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
4020 #if SIZEOF_REGISTER == 4
4021 register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, "mono_fconv_u4", TRUE);
4023 register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "ulong double", mono_fconv_u8, "mono_fconv_u8", TRUE);
4026 /* other jit icalls */
4027 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
4028 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
4029 "ptr ptr ptr", FALSE);
4030 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
4031 register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
4032 "ptr ptr ptr ptr", FALSE);
4033 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
4034 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
4035 register_icall (mono_helper_stelem_ref_check, "mono_helper_stelem_ref_check", "void object object", FALSE);
4036 register_icall (ves_icall_object_new, "ves_icall_object_new", "object ptr ptr", FALSE);
4037 register_icall (ves_icall_object_new_specific, "ves_icall_object_new_specific", "object ptr", FALSE);
4038 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
4039 register_icall (ves_icall_array_new_specific, "ves_icall_array_new_specific", "object ptr int32", FALSE);
4040 register_icall (ves_icall_runtime_class_init, "ves_icall_runtime_class_init", "void ptr", FALSE);
4041 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
4042 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
4043 register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
4044 register_icall (mono_helper_compile_generic_method, "mono_helper_compile_generic_method", "ptr object ptr ptr", FALSE);
4045 register_icall (mono_helper_ldstr, "mono_helper_ldstr", "object ptr int", FALSE);
4046 register_icall (mono_helper_ldstr_mscorlib, "mono_helper_ldstr_mscorlib", "object int", FALSE);
4047 register_icall (mono_helper_newobj_mscorlib, "mono_helper_newobj_mscorlib", "object int", FALSE);
4048 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
4049 register_icall (mono_object_castclass_unbox, "mono_object_castclass_unbox", "object object ptr", FALSE);
4050 register_icall (mono_break, "mono_break", NULL, TRUE);
4051 register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
4052 register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
4053 register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
4054 register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
4055 register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
4056 register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
4057 register_icall (mono_array_new_4, "mono_array_new_4", "object ptr int int int int", FALSE);
4058 register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
4059 register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
4060 register_icall (mono_gsharedvt_constrained_call, "mono_gsharedvt_constrained_call", "object ptr ptr ptr ptr ptr", FALSE);
4061 register_icall (mono_gsharedvt_value_copy, "mono_gsharedvt_value_copy", "void ptr ptr ptr", TRUE);
4063 register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
4065 register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
4066 register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
4067 register_icall (mono_generic_class_init, "mono_generic_class_init", "void ptr", FALSE);
4068 register_icall (mono_fill_class_rgctx, "mono_class_fill_rgctx", "ptr ptr int", FALSE);
4069 register_icall (mono_fill_method_rgctx, "mono_method_fill_rgctx", "ptr ptr int", FALSE);
4071 register_icall (mono_debugger_agent_user_break, "mono_debugger_agent_user_break", "void", FALSE);
4073 register_icall (mono_aot_init_llvm_method, "mono_aot_init_llvm_method", "void ptr int", TRUE);
4074 register_icall (mono_aot_init_gshared_method_this, "mono_aot_init_gshared_method_this", "void ptr int object", TRUE);
4075 register_icall (mono_aot_init_gshared_method_mrgctx, "mono_aot_init_gshared_method_mrgctx", "void ptr int ptr", TRUE);
4076 register_icall (mono_aot_init_gshared_method_vtable, "mono_aot_init_gshared_method_vtable", "void ptr int ptr", TRUE);
4078 register_icall_no_wrapper (mono_resolve_iface_call_gsharedvt, "mono_resolve_iface_call_gsharedvt", "ptr object int ptr ptr");
4079 register_icall_no_wrapper (mono_resolve_vcall_gsharedvt, "mono_resolve_vcall_gsharedvt", "ptr object int ptr ptr");
4080 register_icall_no_wrapper (mono_resolve_generic_virtual_call, "mono_resolve_generic_virtual_call", "ptr ptr int ptr");
4081 register_icall_no_wrapper (mono_resolve_generic_virtual_iface_call, "mono_resolve_generic_virtual_iface_call", "ptr ptr int ptr");
4082 /* This needs a wrapper so it can have a preserveall cconv */
4083 register_icall (mono_init_vtable_slot, "mono_init_vtable_slot", "ptr ptr int", FALSE);
4084 register_icall (mono_llvmonly_init_delegate, "mono_llvmonly_init_delegate", "void object", TRUE);
4085 register_icall (mono_llvmonly_init_delegate_virtual, "mono_llvmonly_init_delegate_virtual", "void object object ptr", TRUE);
4086 register_icall (mono_get_assembly_object, "mono_get_assembly_object", "object ptr", TRUE);
4087 register_icall (mono_get_method_object, "mono_get_method_object", "object ptr", TRUE);
4089 register_icall_with_wrapper (mono_monitor_enter, "mono_monitor_enter", "void obj");
4090 register_icall_with_wrapper (mono_monitor_enter_v4, "mono_monitor_enter_v4", "void obj ptr");
4091 register_icall_no_wrapper (mono_monitor_enter_fast, "mono_monitor_enter_fast", "int obj");
4092 register_icall_no_wrapper (mono_monitor_enter_v4_fast, "mono_monitor_enter_v4_fast", "int obj ptr");
4095 register_icall (pthread_getspecific, "pthread_getspecific", "ptr ptr", TRUE);
4099 MonoJitStats mono_jit_stats = {0};
4102 print_jit_stats (void)
4104 if (mono_jit_stats.enabled) {
4105 g_print ("Mono Jit statistics\n");
4106 g_print ("Max code size ratio: %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
4107 mono_jit_stats.max_ratio_method);
4108 g_print ("Biggest method: %ld (%s)\n", mono_jit_stats.biggest_method_size,
4109 mono_jit_stats.biggest_method);
4111 g_print ("Delegates created: %ld\n", mono_stats.delegate_creations);
4112 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
4113 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
4114 g_print ("Generic vtables: %ld\n", mono_stats.generic_vtable_count);
4115 g_print ("Methods: %ld\n", mono_stats.method_count);
4116 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
4117 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
4118 g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
4120 g_print ("\nInitialized classes: %ld\n", mono_stats.generic_class_count);
4121 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
4122 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
4124 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
4125 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
4126 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
4127 g_print ("Shared vtype generic methods: %ld\n", mono_stats.gsharedvt_methods);
4129 g_print ("IMT tables size: %ld\n", mono_stats.imt_tables_size);
4130 g_print ("IMT number of tables: %ld\n", mono_stats.imt_number_of_tables);
4131 g_print ("IMT number of methods: %ld\n", mono_stats.imt_number_of_methods);
4132 g_print ("IMT used slots: %ld\n", mono_stats.imt_used_slots);
4133 g_print ("IMT colliding slots: %ld\n", mono_stats.imt_slots_with_collisions);
4134 g_print ("IMT max collisions: %ld\n", mono_stats.imt_max_collisions_in_slot);
4135 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
4136 g_print ("IMT thunks size: %ld\n", mono_stats.imt_thunks_size);
4138 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
4139 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
4140 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
4142 g_free (mono_jit_stats.max_ratio_method);
4143 mono_jit_stats.max_ratio_method = NULL;
4144 g_free (mono_jit_stats.biggest_method);
4145 mono_jit_stats.biggest_method = NULL;
4150 mini_cleanup (MonoDomain *domain)
4152 mono_runtime_shutdown_stat_profiler ();
4155 cominterop_release_all_rcws ();
4158 #ifndef MONO_CROSS_COMPILE
4160 * mono_domain_finalize () needs to be called early since it needs the
4161 * execution engine still fully working (it may invoke managed finalizers).
4163 mono_domain_finalize (domain, 2000);
4166 /* This accesses metadata so needs to be called before runtime shutdown */
4169 mono_profiler_shutdown ();
4171 #ifndef MONO_CROSS_COMPILE
4172 mono_runtime_cleanup (domain);
4175 free_jit_tls_data ((MonoJitTlsData *)mono_native_tls_get_value (mono_jit_tls_id));
4177 mono_icall_cleanup ();
4179 mono_runtime_cleanup_handlers ();
4181 #ifndef MONO_CROSS_COMPILE
4182 mono_domain_free (domain, TRUE);
4187 mono_llvm_cleanup ();
4190 mono_aot_cleanup ();
4192 mono_trampolines_cleanup ();
4194 mono_unwind_cleanup ();
4196 mono_code_manager_destroy (global_codeman);
4197 g_free (vtable_trampolines);
4199 mini_jit_cleanup ();
4201 mono_tramp_info_cleanup ();
4203 mono_arch_cleanup ();
4205 mono_generic_sharing_cleanup ();
4209 mono_trace_cleanup ();
4211 mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, stdout);
4213 if (mono_inject_async_exc_method)
4214 mono_method_desc_free (mono_inject_async_exc_method);
4216 mono_native_tls_free (mono_jit_tls_id);
4218 mono_os_mutex_destroy (&jit_mutex);
4220 mono_code_manager_cleanup ();
4222 #ifdef USE_JUMP_TABLES
4223 mono_jumptable_cleanup ();
4228 mono_set_defaults (int verbose_level, guint32 opts)
4230 mini_verbose = verbose_level;
4231 mono_set_optimizations (opts);
4235 mono_disable_optimizations (guint32 opts)
4237 default_opt &= ~opts;
4241 mono_set_optimizations (guint32 opts)
4244 default_opt_set = TRUE;
4245 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
4246 mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
4249 mono_set_generic_sharing_vt_supported (TRUE);
4254 mono_set_verbose_level (guint32 level)
4256 mini_verbose = level;
4260 * mono_get_runtime_build_info:
4262 * Return the runtime version + build date in string format.
4263 * The returned string is owned by the caller. The returned string
4264 * format is "VERSION (FULL_VERSION BUILD_DATE)" and build date is optional.
4267 mono_get_runtime_build_info (void)
4269 if (mono_build_date)
4270 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
4272 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
4276 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
4278 GHashTable *assemblies = (GHashTable*)user_data;
4279 MonoImage *image = mono_assembly_get_image (ass);
4280 MonoMethod *method, *invoke;
4283 if (g_hash_table_lookup (assemblies, ass))
4286 g_hash_table_insert (assemblies, ass, ass);
4288 if (mini_verbose > 0)
4289 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
4291 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
4294 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, &error);
4296 mono_error_cleanup (&error); /* FIXME don't swallow the error */
4299 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
4301 if (method->is_generic || method->klass->generic_container)
4305 if (mini_verbose > 1) {
4306 char * desc = mono_method_full_name (method, TRUE);
4307 g_print ("Compiling %d %s\n", count, desc);
4310 mono_compile_method (method);
4311 if (strcmp (method->name, "Finalize") == 0) {
4312 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
4313 mono_compile_method (invoke);
4315 #ifndef DISABLE_REMOTING
4316 if (mono_class_is_marshalbyref (method->klass) && mono_method_signature (method)->hasthis) {
4317 invoke = mono_marshal_get_remoting_invoke_with_check (method);
4318 mono_compile_method (invoke);
4323 /* Load and precompile referenced assemblies as well */
4324 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
4325 mono_assembly_load_reference (image, i);
4326 if (image->references [i])
4327 mono_precompile_assembly (image->references [i], assemblies);
4331 void mono_precompile_assemblies ()
4333 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
4335 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
4337 g_hash_table_destroy (assemblies);
4342 * Have to export this for AOT.
4345 mono_personality (void)
4348 g_assert_not_reached ();
4351 #ifdef USE_JUMP_TABLES
4352 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
4354 typedef struct MonoJumpTableChunk {
4357 struct MonoJumpTableChunk *previous;
4358 /* gpointer entries[total]; */
4359 } MonoJumpTableChunk;
4361 static MonoJumpTableChunk* g_jumptable;
4362 #define mono_jumptable_lock() mono_os_mutex_lock (&jumptable_mutex)
4363 #define mono_jumptable_unlock() mono_os_mutex_unlock (&jumptable_mutex)
4364 static mono_mutex_t jumptable_mutex;
4366 static MonoJumpTableChunk*
4367 mono_create_jumptable_chunk (guint32 max_entries)
4369 guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
4370 MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
4371 chunk->total = max_entries;
4376 mono_jumptable_init (void)
4378 if (g_jumptable == NULL) {
4379 mono_os_mutex_init_recursive (&jumptable_mutex);
4380 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
4385 mono_jumptable_add_entry (void)
4387 return mono_jumptable_add_entries (1);
4391 mono_jumptable_add_entries (guint32 entries)
4396 mono_jumptable_init ();
4397 mono_jumptable_lock ();
4398 index = g_jumptable->active;
4399 if (index + entries >= g_jumptable->total) {
4401 * Grow jumptable, by adding one more chunk.
4402 * We cannot realloc jumptable, as there could be pointers
4403 * to existing jump table entries in the code, so instead
4404 * we just add one more chunk.
4406 guint32 max_entries = entries;
4407 MonoJumpTableChunk *new_chunk;
4409 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
4410 max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
4411 new_chunk = mono_create_jumptable_chunk (max_entries);
4412 /* Link old jumptable, so that we could free it up later. */
4413 new_chunk->previous = g_jumptable;
4414 g_jumptable = new_chunk;
4417 g_jumptable->active = index + entries;
4418 result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
4419 mono_jumptable_unlock();
4425 mono_jumptable_cleanup (void)
4428 MonoJumpTableChunk *current = g_jumptable, *prev;
4429 while (current != NULL) {
4430 prev = current->previous;
4435 mono_os_mutex_destroy (&jumptable_mutex);
4440 mono_jumptable_get_entry (guint8 *code_ptr)
4442 return mono_arch_jumptable_entry_from_code (code_ptr);