2 * mini-runtime.c: Runtime code for the JIT
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * Copyright 2002-2003 Ximian, Inc.
9 * Copyright 2003-2010 Novell, Inc.
10 * Copyright 2011-2015 Xamarin, Inc (http://www.xamarin.com)
21 #ifdef HAVE_SYS_TIME_H
28 #include <mono/utils/memcheck.h>
30 #include <mono/metadata/assembly.h>
31 #include <mono/metadata/loader.h>
32 #include <mono/metadata/tabledefs.h>
33 #include <mono/metadata/class.h>
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/tokentype.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/appdomain.h>
39 #include <mono/metadata/debug-helpers.h>
40 #include "mono/metadata/profiler.h"
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/gc-internal.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/mempool-internals.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/runtime.h>
50 #include <mono/utils/mono-math.h>
51 #include <mono/utils/mono-compiler.h>
52 #include <mono/utils/mono-counters.h>
53 #include <mono/utils/mono-error-internals.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-path.h>
57 #include <mono/utils/mono-tls.h>
58 #include <mono/utils/mono-hwcap.h>
59 #include <mono/utils/dtrace.h>
60 #include <mono/utils/mono-signal-handler.h>
61 #include <mono/utils/mono-threads.h>
62 #include <mono/io-layer/io-layer.h>
65 #include "seq-points.h"
72 #include "jit-icalls.h"
75 #include "debugger-agent.h"
77 static guint32 default_opt = 0;
78 static gboolean default_opt_set = FALSE;
80 MonoNativeTlsKey mono_jit_tls_id;
82 #ifdef MONO_HAVE_FAST_TLS
83 MONO_FAST_TLS_DECLARE(mono_jit_tls);
86 gboolean mono_compile_aot = FALSE;
87 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
88 gboolean mono_aot_only = FALSE;
89 MonoAotMode mono_aot_mode = MONO_AOT_MODE_NONE;
91 const char *mono_build_date;
92 gboolean mono_do_signal_chaining;
93 gboolean mono_do_crash_chaining;
97 * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
98 * it can load AOT code compiled by LLVM.
100 gboolean mono_use_llvm = FALSE;
102 #define mono_jit_lock() mono_mutex_lock (&jit_mutex)
103 #define mono_jit_unlock() mono_mutex_unlock (&jit_mutex)
104 static mono_mutex_t jit_mutex;
106 static MonoCodeManager *global_codeman;
108 MonoDebugOptions debug_options;
110 #ifdef VALGRIND_JIT_REGISTER_MAP
111 int valgrind_register;
114 static GSList *tramp_infos;
116 static void register_icalls (void);
119 mono_running_on_valgrind (void)
121 if (RUNNING_ON_VALGRIND){
122 #ifdef VALGRIND_JIT_REGISTER_MAP
123 valgrind_register = TRUE;
136 find_tramp (gpointer key, gpointer value, gpointer user_data)
138 FindTrampUserData *ud = (FindTrampUserData*)user_data;
141 ud->method = (MonoMethod*)key;
145 G_GNUC_UNUSED static char*
146 get_method_from_ip (void *ip)
151 MonoDomain *domain = mono_domain_get ();
152 MonoDebugSourceLocation *location;
153 FindTrampUserData user_data;
156 domain = mono_get_root_domain ();
158 ji = mono_jit_info_table_find_internal (domain, ip, TRUE, TRUE);
161 user_data.method = NULL;
162 mono_domain_lock (domain);
163 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
164 mono_domain_unlock (domain);
165 if (user_data.method) {
166 char *mname = mono_method_full_name (user_data.method, TRUE);
167 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
173 } else if (ji->is_trampoline) {
174 res = g_strdup_printf ("<%p - %s trampoline>", ip, ((MonoTrampInfo*)ji->d.tramp_info)->name);
178 method = mono_method_full_name (jinfo_get_method (ji), TRUE);
179 /* FIXME: unused ? */
180 location = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
182 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);
184 mono_debug_free_source_location (location);
192 * @ip: an instruction pointer address
194 * This method is used from a debugger to get the name of the
195 * method at address @ip. This routine is typically invoked from
196 * a debugger like this:
198 * (gdb) print mono_pmip ($pc)
200 * Returns: the name of the method at address @ip.
205 return get_method_from_ip (ip);
209 * mono_print_method_from_ip
210 * @ip: an instruction pointer address
212 * This method is used from a debugger to get the name of the
213 * method at address @ip.
215 * This prints the name of the method at address @ip in the standard
216 * output. Unlike mono_pmip which returns a string, this routine
217 * prints the value on the standard output.
220 /* Prevent the linker from optimizing this away in embedding setups to help debugging */
221 __attribute__((used))
224 mono_print_method_from_ip (void *ip)
228 MonoDebugSourceLocation *source;
229 MonoDomain *domain = mono_domain_get ();
230 MonoDomain *target_domain = mono_domain_get ();
231 FindTrampUserData user_data;
232 MonoGenericSharingContext*gsctx;
233 const char *shared_type;
235 ji = mini_jit_info_table_find_ext (domain, ip, TRUE, &target_domain);
236 if (ji && ji->is_trampoline) {
237 MonoTrampInfo *tinfo = ji->d.tramp_info;
239 printf ("IP %p is at offset 0x%x of trampoline '%s'.\n", ip, (int)((guint8*)ip - tinfo->code), tinfo->name);
245 user_data.method = NULL;
246 mono_domain_lock (domain);
247 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
248 mono_domain_unlock (domain);
250 if (user_data.method) {
251 char *mname = mono_method_full_name (user_data.method, TRUE);
252 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
257 g_print ("No method at %p\n", ip);
261 method = mono_method_full_name (jinfo_get_method (ji), TRUE);
262 source = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
264 gsctx = mono_jit_info_get_generic_sharing_context (ji);
267 if (gsctx->is_gsharedvt)
268 shared_type = "gsharedvt ";
270 shared_type = "gshared ";
273 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);
276 g_print ("%s:%d\n", source->source_file, source->row);
279 mono_debug_free_source_location (source);
284 * mono_method_same_domain:
286 * Determine whenever two compiled methods are in the same domain, thus
287 * the address of the callee can be embedded in the caller.
289 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
293 if (!caller || caller->is_trampoline || !callee || callee->is_trampoline)
297 * If the call was made from domain-neutral to domain-specific
298 * code, we can't patch the call site.
300 if (caller->domain_neutral && !callee->domain_neutral)
303 cmethod = jinfo_get_method (caller);
304 if ((cmethod->klass == mono_defaults.appdomain_class) &&
305 (strstr (cmethod->name, "InvokeInDomain"))) {
306 /* The InvokeInDomain methods change the current appdomain */
314 * mono_global_codeman_reserve:
316 * Allocate code memory from the global code manager.
318 void *mono_global_codeman_reserve (int size)
323 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
325 if (!global_codeman) {
326 /* This can happen during startup */
327 global_codeman = mono_code_manager_new ();
328 return mono_code_manager_reserve (global_codeman, size);
332 ptr = mono_code_manager_reserve (global_codeman, size);
338 #if defined(__native_client_codegen__) && defined(__native_client__)
342 #ifdef __native_client_gc__
343 __nacl_suspend_thread_if_needed();
347 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
348 * which we are generating code, return a pointer to the destination in the
349 * dynamic code segment into which the code will be copied when
350 * mono_global_codeman_commit is called.
351 * LOCKING: Acquires the jit lock.
354 nacl_global_codeman_get_dest (void *data)
358 dest = nacl_code_manager_get_code_dest (global_codeman, data);
364 mono_global_codeman_commit (void *data, int size, int newsize)
367 mono_code_manager_commit (global_codeman, data, size, newsize);
372 * Convenience function which calls mono_global_codeman_commit to validate and
373 * copy the code. The caller sets *buf_base and *buf_size to the start and size
374 * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
375 * the byte after the last instruction byte. On return, *buf_base will point to
376 * the start of the copied in the code segment, and *code_end will point after
377 * the end of the copied code.
380 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
382 guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
383 mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
384 *code_end = tmp + (*code_end - *buf_base);
388 /* no-op versions of Native Client functions */
390 nacl_global_codeman_get_dest (void *data)
396 mono_global_codeman_commit (void *data, int size, int newsize)
401 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
405 #endif /* __native_client__ */
408 * mono_create_unwind_op:
410 * Create an unwind op with the given parameters.
413 mono_create_unwind_op (int when, int tag, int reg, int val)
415 MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
426 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
428 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
431 res->has_context = context != NULL;
433 memcpy (&res->context, context, sizeof (MonoGenericContext));
439 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
441 return mono_jump_info_token_new2 (mp, image, token, NULL);
445 * mono_tramp_info_create:
447 * Create a MonoTrampInfo structure from the arguments. This function assumes ownership
448 * of JI, and UNWIND_OPS.
451 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
453 MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
455 info->name = g_strdup ((char*)name);
457 info->code_size = code_size;
459 info->unwind_ops = unwind_ops;
465 mono_tramp_info_free (MonoTrampInfo *info)
472 for (l = info->unwind_ops; l; l = l->next)
474 g_slist_free (info->unwind_ops);
479 register_trampoline_jit_info (MonoDomain *domain, MonoTrampInfo *info)
483 ji = mono_domain_alloc0 (domain, mono_jit_info_size (0, 0, 0));
484 mono_jit_info_init (ji, NULL, info->code, info->code_size, 0, 0, 0);
485 ji->d.tramp_info = info;
486 ji->is_trampoline = TRUE;
488 ji->unwind_info = mono_cache_unwind_info (info->uw_info, info->uw_info_len);
490 mono_jit_info_table_add (domain, ji);
494 * mono_tramp_info_register:
496 * Remember INFO for use by xdebug, mono_print_method_from_ip (), jit maps, etc.
501 mono_tramp_info_register (MonoTrampInfo *info)
508 copy = g_new0 (MonoTrampInfo, 1);
509 copy->code = info->code;
510 copy->code_size = info->code_size;
511 copy->name = g_strdup (info->name);
513 if (info->unwind_ops) {
514 copy->uw_info = mono_unwind_ops_encode (info->unwind_ops, ©->uw_info_len);
516 /* Trampolines from aot have the unwind ops already encoded */
517 copy->uw_info = info->uw_info;
518 copy->uw_info_len = info->uw_info_len;
522 tramp_infos = g_slist_prepend (tramp_infos, copy);
525 mono_save_trampoline_xdebug_info (info);
527 /* Only register trampolines that have unwind infos */
528 if (mono_get_root_domain () && copy->uw_info)
529 register_trampoline_jit_info (mono_get_root_domain (), copy);
531 if (mono_jit_map_is_enabled ())
532 mono_emit_jit_tramp (info->code, info->code_size, info->name);
534 mono_tramp_info_free (info);
538 mono_tramp_info_cleanup (void)
542 for (l = tramp_infos; l; l = l->next) {
543 MonoTrampInfo *info = l->data;
545 mono_tramp_info_free (info);
547 g_slist_free (tramp_infos);
550 /* Register trampolines created before the root domain was created in the jit info tables */
552 register_trampolines (MonoDomain *domain)
556 for (l = tramp_infos; l; l = l->next) {
557 MonoTrampInfo *info = l->data;
559 register_trampoline_jit_info (domain, info);
563 G_GNUC_UNUSED static void
569 * Runtime debugging tool, use if (debug_count ()) <x> else <y> to do <x> the first COUNT times, then do <y> afterwards.
570 * Set a breakpoint in break_count () to break the last time <x> is done.
572 G_GNUC_UNUSED gboolean
573 mono_debug_count (void)
575 static int count = 0;
576 static gboolean inited;
577 static const char *value;
582 value = g_getenv ("COUNT");
589 if (count == atoi (value))
592 if (count > atoi (value))
599 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
603 gconstpointer trampoline;
604 MonoDomain *domain = mono_get_root_domain ();
605 gboolean check_exc = TRUE;
607 if (callinfo->wrapper) {
608 return callinfo->wrapper;
611 if (callinfo->trampoline)
612 return callinfo->trampoline;
615 * We use the lock on the root domain instead of the JIT lock to protect
616 * callinfo->trampoline, since we do a lot of stuff inside the critical section.
618 mono_loader_lock (); /*FIXME mono_compile_method requires the loader lock, by large.*/
619 mono_domain_lock (domain);
621 if (callinfo->trampoline) {
622 mono_domain_unlock (domain);
623 mono_loader_unlock ();
624 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);
638 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
639 mono_register_jit_icall_wrapper (callinfo, trampoline);
641 callinfo->trampoline = trampoline;
643 mono_domain_unlock (domain);
644 mono_loader_unlock ();
646 return callinfo->trampoline;
650 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
652 return mono_icall_get_wrapper_full (callinfo, FALSE);
655 static MonoJitDynamicMethodInfo*
656 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
658 MonoJitDynamicMethodInfo *res;
660 if (domain_jit_info (domain)->dynamic_code_hash)
661 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
668 register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
670 mini_register_opcode_emulation (opcode, name, sigstr, func, symbol, no_throw);
674 * For JIT icalls implemented in C.
675 * NAME should be the same as the name of the C function whose address is FUNC.
676 * If @avoid_wrapper is TRUE, no wrapper is generated. This is for perf critical icalls which
677 * can't throw exceptions.
680 register_icall (gpointer func, const char *name, const char *sigstr, gboolean avoid_wrapper)
682 MonoMethodSignature *sig;
685 sig = mono_create_icall_signature (sigstr);
689 mono_register_jit_icall_full (func, name, sig, avoid_wrapper, FALSE, avoid_wrapper ? name : NULL);
693 register_dyn_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
695 MonoMethodSignature *sig;
698 sig = mono_create_icall_signature (sigstr);
702 mono_register_jit_icall (func, name, sig, save);
705 #ifdef MONO_HAVE_FAST_TLS
706 MONO_FAST_TLS_DECLARE(mono_lmf_addr);
707 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
709 * When this is defined, the current lmf is stored in this tls variable instead of in
712 MONO_FAST_TLS_DECLARE(mono_lmf);
717 mono_get_jit_tls_offset (void)
723 offset = mono_jit_tls_id;
725 /* FIXME: Happens during startup */
728 MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
734 mono_get_lmf_tls_offset (void)
736 #if defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
738 MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
746 mono_get_lmf_addr_tls_offset (void)
749 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
756 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
757 return MONO_FAST_TLS_GET (mono_lmf);
759 MonoJitTlsData *jit_tls;
761 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
764 * We do not assert here because this function can be called from
765 * mini-gc.c on a thread that has not executed any managed code, yet
766 * (the thread object allocation can trigger a collection).
773 mono_get_lmf_addr (void)
775 #ifdef MONO_HAVE_FAST_TLS
776 return MONO_FAST_TLS_GET (mono_lmf_addr);
778 MonoJitTlsData *jit_tls;
780 jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
781 if (G_LIKELY (jit_tls))
782 return &jit_tls->lmf;
785 * When resolving the call to mono_jit_thread_attach full-aot will look
786 * in the plt, which causes a call into the generic trampoline, which in turn
787 * tries to resolve the lmf_addr creating a cyclic dependency. We cannot
788 * call mono_jit_thread_attach from the native-to-managed wrapper, without
789 * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
792 mono_jit_thread_attach (NULL);
794 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
795 return &jit_tls->lmf;
797 g_assert_not_reached ();
803 mono_set_lmf (MonoLMF *lmf)
805 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
806 MONO_FAST_TLS_SET (mono_lmf, lmf);
809 (*mono_get_lmf_addr ()) = lmf;
813 mono_get_jit_tls (void)
815 return mono_native_tls_get_value (mono_jit_tls_id);
819 mono_set_jit_tls (MonoJitTlsData *jit_tls)
821 MonoThreadInfo *info;
823 mono_native_tls_set_value (mono_jit_tls_id, jit_tls);
825 #ifdef MONO_HAVE_FAST_TLS
826 MONO_FAST_TLS_SET (mono_jit_tls, jit_tls);
829 /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
830 info = mono_thread_info_current ();
832 mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
836 mono_set_lmf_addr (gpointer lmf_addr)
838 MonoThreadInfo *info;
840 #ifdef MONO_HAVE_FAST_TLS
841 MONO_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
844 /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
845 info = mono_thread_info_current ();
847 mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
851 * mono_jit_thread_attach:
853 * Called by native->managed wrappers. Returns the original domain which needs to be
857 mono_jit_thread_attach (MonoDomain *domain)
863 * Happens when called from AOTed code which is only used in the root
866 domain = mono_get_root_domain ();
868 #ifdef MONO_HAVE_FAST_TLS
869 if (!MONO_FAST_TLS_GET (mono_lmf_addr)) {
870 mono_thread_attach (domain);
872 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
875 if (!mono_native_tls_get_value (mono_jit_tls_id)) {
876 mono_thread_attach (domain);
877 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
880 orig = mono_domain_get ();
882 mono_domain_set (domain, TRUE);
884 return orig != domain ? orig : NULL;
887 /* Called by native->managed wrappers */
889 mono_jit_set_domain (MonoDomain *domain)
892 mono_domain_set (domain, TRUE);
897 * @obj: exception object
899 * abort the thread, print exception information and stack trace
902 mono_thread_abort (MonoObject *obj)
904 /* MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id); */
906 /* handle_remove should be eventually called for this thread, too
909 if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
910 (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
913 mono_invoke_unhandled_exception_hook (obj);
918 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
920 MonoJitTlsData *jit_tls;
923 jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
927 jit_tls = g_new0 (MonoJitTlsData, 1);
929 jit_tls->abort_func = abort_func;
930 jit_tls->end_of_stack = stack_start;
932 mono_set_jit_tls (jit_tls);
934 lmf = g_new0 (MonoLMF, 1);
935 MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
937 jit_tls->first_lmf = lmf;
939 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
940 /* jit_tls->lmf is unused */
941 MONO_FAST_TLS_SET (mono_lmf, lmf);
942 mono_set_lmf_addr (MONO_FAST_TLS_ADDR (mono_lmf));
944 mono_set_lmf_addr (&jit_tls->lmf);
949 #ifdef MONO_ARCH_HAVE_TLS_INIT
950 mono_arch_tls_init ();
953 mono_setup_altstack (jit_tls);
959 free_jit_tls_data (MonoJitTlsData *jit_tls)
961 mono_arch_free_jit_tls_data (jit_tls);
962 mono_free_altstack (jit_tls);
964 g_free (jit_tls->first_lmf);
969 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
971 MonoThreadInfo *thread;
972 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
973 thread = mono_thread_info_current_unchecked ();
975 thread->jit_data = jit_tls;
977 mono_arch_cpu_init ();
980 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
983 mono_thread_abort_dummy (MonoObject *obj)
985 if (mono_thread_attach_aborted_cb)
986 mono_thread_attach_aborted_cb (obj);
988 mono_thread_abort (obj);
992 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
994 MonoThreadInfo *thread;
995 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
996 thread = mono_thread_info_current_unchecked ();
998 thread->jit_data = jit_tls;
999 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
1000 mono_runtime_setup_stat_profiler ();
1002 mono_arch_cpu_init ();
1006 mini_thread_cleanup (MonoNativeThreadId tid)
1008 MonoJitTlsData *jit_tls = NULL;
1009 MonoThreadInfo *info;
1011 info = mono_thread_info_current_unchecked ();
1013 /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
1014 * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
1015 * not a trivial thing.
1017 * The current offender is mono_thread_manage which cleanup threads from the outside.
1019 if (info && mono_thread_info_get_tid (info) == tid) {
1020 jit_tls = info->jit_data;
1021 info->jit_data = NULL;
1023 mono_set_jit_tls (NULL);
1025 /* If we attach a thread but never call into managed land, we might never get an lmf.*/
1026 if (mono_get_lmf ()) {
1027 mono_set_lmf (NULL);
1028 mono_set_lmf_addr (NULL);
1031 info = mono_thread_info_lookup (tid);
1033 jit_tls = info->jit_data;
1034 info->jit_data = NULL;
1036 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
1040 free_jit_tls_data (jit_tls);
1044 mini_get_tls_offset (MonoTlsKey key)
1047 g_assert (MONO_ARCH_HAVE_TLS_GET);
1050 case TLS_KEY_THREAD:
1051 offset = mono_thread_get_tls_offset ();
1053 case TLS_KEY_JIT_TLS:
1054 offset = mono_get_jit_tls_offset ();
1056 case TLS_KEY_DOMAIN:
1057 offset = mono_domain_get_tls_offset ();
1060 offset = mono_get_lmf_tls_offset ();
1062 case TLS_KEY_LMF_ADDR:
1063 offset = mono_get_lmf_addr_tls_offset ();
1066 offset = mono_tls_key_get_offset (key);
1067 g_assert (offset != -1);
1075 mini_tls_key_supported (MonoTlsKey key)
1077 if (!MONO_ARCH_HAVE_TLS_GET)
1080 return mini_get_tls_offset (key) != -1;
1084 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
1086 MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
1090 ji->data.target = target;
1097 * mono_patch_info_dup_mp:
1099 * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
1102 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
1104 MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
1105 memcpy (res, patch_info, sizeof (MonoJumpInfo));
1107 switch (patch_info->type) {
1108 case MONO_PATCH_INFO_RVA:
1109 case MONO_PATCH_INFO_LDSTR:
1110 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1111 case MONO_PATCH_INFO_LDTOKEN:
1112 case MONO_PATCH_INFO_DECLSEC:
1113 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
1114 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
1116 case MONO_PATCH_INFO_SWITCH:
1117 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
1118 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
1119 res->data.table->table = mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1120 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
1122 case MONO_PATCH_INFO_RGCTX_FETCH:
1123 res->data.rgctx_entry = mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
1124 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
1125 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
1127 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1128 res->data.del_tramp = mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
1129 memcpy (res->data.del_tramp, patch_info->data.del_tramp, sizeof (MonoDelegateClassMethodPair));
1131 case MONO_PATCH_INFO_GSHAREDVT_CALL:
1132 res->data.gsharedvt = mono_mempool_alloc (mp, sizeof (MonoJumpInfoGSharedVtCall));
1133 memcpy (res->data.gsharedvt, patch_info->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
1135 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
1136 MonoGSharedVtMethodInfo *info;
1137 MonoGSharedVtMethodInfo *oinfo;
1140 oinfo = patch_info->data.gsharedvt_method;
1141 info = mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
1142 res->data.gsharedvt_method = info;
1143 memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
1144 info->entries = mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
1145 for (i = 0; i < oinfo->num_entries; ++i) {
1146 MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
1147 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
1149 memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
1151 //info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
1152 //memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
1155 case MONO_PATCH_INFO_VIRT_METHOD: {
1156 MonoJumpInfoVirtMethod *info;
1157 MonoJumpInfoVirtMethod *oinfo;
1159 oinfo = patch_info->data.virt_method;
1160 info = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
1161 res->data.virt_method = info;
1162 memcpy (info, oinfo, sizeof (MonoJumpInfoVirtMethod));
1173 mono_patch_info_hash (gconstpointer data)
1175 const MonoJumpInfo *ji = (MonoJumpInfo*)data;
1178 case MONO_PATCH_INFO_RVA:
1179 case MONO_PATCH_INFO_LDSTR:
1180 case MONO_PATCH_INFO_LDTOKEN:
1181 case MONO_PATCH_INFO_DECLSEC:
1182 return (ji->type << 8) | ji->data.token->token;
1183 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1184 return (ji->type << 8) | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
1185 case MONO_PATCH_INFO_INTERNAL_METHOD:
1186 return (ji->type << 8) | g_str_hash (ji->data.name);
1187 case MONO_PATCH_INFO_VTABLE:
1188 case MONO_PATCH_INFO_CLASS:
1189 case MONO_PATCH_INFO_IID:
1190 case MONO_PATCH_INFO_ADJUSTED_IID:
1191 case MONO_PATCH_INFO_METHODCONST:
1192 case MONO_PATCH_INFO_METHOD:
1193 case MONO_PATCH_INFO_METHOD_JUMP:
1194 case MONO_PATCH_INFO_IMAGE:
1195 case MONO_PATCH_INFO_ICALL_ADDR:
1196 case MONO_PATCH_INFO_FIELD:
1197 case MONO_PATCH_INFO_SFLDA:
1198 case MONO_PATCH_INFO_SEQ_POINT_INFO:
1199 case MONO_PATCH_INFO_METHOD_RGCTX:
1200 case MONO_PATCH_INFO_SIGNATURE:
1201 case MONO_PATCH_INFO_TLS_OFFSET:
1202 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
1203 return (ji->type << 8) | (gssize)ji->data.target;
1204 case MONO_PATCH_INFO_GSHAREDVT_CALL:
1205 return (ji->type << 8) | (gssize)ji->data.gsharedvt->method;
1206 case MONO_PATCH_INFO_RGCTX_FETCH: {
1207 MonoJumpInfoRgctxEntry *e = ji->data.rgctx_entry;
1209 return (ji->type << 8) | (gssize)e->method | (e->in_mrgctx) | e->info_type | mono_patch_info_hash (e->data);
1211 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1212 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
1213 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
1214 case MONO_PATCH_INFO_GC_NURSERY_START:
1215 case MONO_PATCH_INFO_JIT_TLS_ID:
1216 case MONO_PATCH_INFO_MONITOR_ENTER:
1217 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
1218 case MONO_PATCH_INFO_MONITOR_EXIT:
1219 case MONO_PATCH_INFO_GOT_OFFSET:
1220 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
1221 return (ji->type << 8);
1222 case MONO_PATCH_INFO_CASTCLASS_CACHE:
1223 return (ji->type << 8) | (ji->data.index);
1224 case MONO_PATCH_INFO_SWITCH:
1225 return (ji->type << 8) | ji->data.table->table_size;
1226 case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1227 return (ji->type << 8) | (gssize)ji->data.gsharedvt_method->method;
1228 case MONO_PATCH_INFO_OBJC_SELECTOR_REF:
1229 /* Hash on the selector name */
1230 return g_str_hash (ji->data.target);
1231 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1232 return (ji->type << 8) | (gsize)ji->data.del_tramp->klass | (gsize)ji->data.del_tramp->method | (gsize)ji->data.del_tramp->virtual;
1233 case MONO_PATCH_INFO_LDSTR_LIT:
1234 return g_str_hash (ji->data.target);
1235 case MONO_PATCH_INFO_VIRT_METHOD: {
1236 MonoJumpInfoVirtMethod *info = ji->data.virt_method;
1238 return (ji->type << 8) | (gssize)info->klass | (gssize)info->method;
1240 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1241 return (ji->type << 8) | g_str_hash (ji->data.target);
1243 printf ("info type: %d\n", ji->type);
1244 mono_print_ji (ji); printf ("\n");
1245 g_assert_not_reached ();
1251 * mono_patch_info_equal:
1253 * This might fail to recognize equivalent patches, i.e. floats, so its only
1254 * usable in those cases where this is not a problem, i.e. sharing GOT slots
1258 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
1260 const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
1261 const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
1263 if (ji1->type != ji2->type)
1266 switch (ji1->type) {
1267 case MONO_PATCH_INFO_RVA:
1268 case MONO_PATCH_INFO_LDSTR:
1269 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1270 case MONO_PATCH_INFO_LDTOKEN:
1271 case MONO_PATCH_INFO_DECLSEC:
1272 if ((ji1->data.token->image != ji2->data.token->image) ||
1273 (ji1->data.token->token != ji2->data.token->token) ||
1274 (ji1->data.token->has_context != ji2->data.token->has_context) ||
1275 (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
1276 (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
1279 case MONO_PATCH_INFO_INTERNAL_METHOD:
1280 return g_str_equal (ji1->data.name, ji2->data.name);
1281 case MONO_PATCH_INFO_RGCTX_FETCH: {
1282 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
1283 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
1285 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);
1287 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
1288 MonoJumpInfoGSharedVtCall *c1 = ji1->data.gsharedvt;
1289 MonoJumpInfoGSharedVtCall *c2 = ji2->data.gsharedvt;
1291 return c1->sig == c2->sig && c1->method == c2->method;
1293 case MONO_PATCH_INFO_GSHAREDVT_METHOD:
1294 return ji1->data.gsharedvt_method->method == ji2->data.gsharedvt_method->method;
1295 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1296 return ji1->data.del_tramp->klass == ji2->data.del_tramp->klass && ji1->data.del_tramp->method == ji2->data.del_tramp->method && ji1->data.del_tramp->virtual == ji2->data.del_tramp->virtual;
1297 case MONO_PATCH_INFO_CASTCLASS_CACHE:
1298 return ji1->data.index == ji2->data.index;
1299 case MONO_PATCH_INFO_VIRT_METHOD:
1300 return ji1->data.virt_method->klass == ji2->data.virt_method->klass && ji1->data.virt_method->method == ji2->data.virt_method->method;
1301 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1302 if (ji1->data.target == ji2->data.target)
1304 return strcmp (ji1->data.target, ji2->data.target) == 0 ? 1 : 0;
1306 if (ji1->data.target != ji2->data.target)
1315 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
1317 unsigned char *ip = patch_info->ip.i + code;
1318 gconstpointer target = NULL;
1320 switch (patch_info->type) {
1321 case MONO_PATCH_INFO_BB:
1323 * FIXME: This could be hit for methods without a prolog. Should use -1
1324 * but too much code depends on a 0 initial value.
1326 //g_assert (patch_info->data.bb->native_offset);
1327 target = patch_info->data.bb->native_offset + code;
1329 case MONO_PATCH_INFO_ABS:
1330 target = patch_info->data.target;
1332 case MONO_PATCH_INFO_LABEL:
1333 target = patch_info->data.inst->inst_c0 + code;
1335 case MONO_PATCH_INFO_IP:
1336 #if defined(__native_client__) && defined(__native_client_codegen__)
1337 /* Need to transform to the destination address, it's */
1338 /* emitted as an immediate in the code. */
1339 target = nacl_inverse_modify_patch_target(ip);
1344 case MONO_PATCH_INFO_METHOD_REL:
1345 target = code + patch_info->data.offset;
1347 case MONO_PATCH_INFO_INTERNAL_METHOD: {
1348 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1350 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
1351 g_assert_not_reached ();
1353 target = mono_icall_get_wrapper (mi);
1356 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1357 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
1359 g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
1360 g_assert_not_reached ();
1365 case MONO_PATCH_INFO_METHOD_JUMP:
1366 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE);
1367 #if defined(__native_client__) && defined(__native_client_codegen__)
1368 # if defined(TARGET_AMD64)
1369 /* This target is an absolute address, not relative to the */
1370 /* current code being emitted on AMD64. */
1371 target = nacl_inverse_modify_patch_target(target);
1375 case MONO_PATCH_INFO_METHOD:
1376 #if defined(__native_client_codegen__) && defined(USE_JUMP_TABLES)
1378 * If we use jumptables, for recursive calls we cannot
1379 * avoid trampoline, as we not yet know where we will
1382 target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
1384 if (patch_info->data.method == method) {
1387 /* get the trampoline to the method from the domain */
1388 target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
1392 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
1395 mono_domain_lock (domain);
1396 if (!domain_jit_info (domain)->method_code_hash)
1397 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
1398 code_slot = g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, patch_info->data.method);
1400 code_slot = mono_domain_alloc0 (domain, sizeof (gpointer));
1401 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, patch_info->data.method, code_slot);
1403 mono_domain_unlock (domain);
1407 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
1408 #if defined(__native_client_codegen__)
1409 target = (gpointer)&__nacl_thread_suspension_needed;
1410 #elif defined (USE_COOP_GC)
1411 target = (gpointer)&mono_polling_required;
1413 g_error ("Unsuported patch target");
1416 case MONO_PATCH_INFO_SWITCH: {
1417 gpointer *jump_table;
1419 #if defined(__native_client__) && defined(__native_client_codegen__)
1420 /* This memory will leak, but we don't care if we're */
1421 /* not deleting JIT'd methods anyway */
1422 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
1424 if (method && method->dynamic) {
1425 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
1427 if (mono_aot_only) {
1428 jump_table = mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1430 jump_table = mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
1435 for (i = 0; i < patch_info->data.table->table_size; i++) {
1436 #if defined(__native_client__) && defined(__native_client_codegen__)
1437 /* 'code' is relative to the current code blob, we */
1438 /* need to do this transform on it to make the */
1439 /* pointers in this table absolute */
1440 jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1442 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
1446 #if defined(__native_client__) && defined(__native_client_codegen__)
1447 /* jump_table is in the data section, we need to transform */
1448 /* it here so when it gets modified in amd64_patch it will */
1449 /* then point back to the absolute data address */
1450 target = nacl_inverse_modify_patch_target (jump_table);
1452 target = jump_table;
1456 case MONO_PATCH_INFO_METHODCONST:
1457 case MONO_PATCH_INFO_CLASS:
1458 case MONO_PATCH_INFO_IMAGE:
1459 case MONO_PATCH_INFO_FIELD:
1460 case MONO_PATCH_INFO_SIGNATURE:
1461 target = patch_info->data.target;
1463 case MONO_PATCH_INFO_IID:
1464 mono_class_init (patch_info->data.klass);
1465 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
1467 case MONO_PATCH_INFO_ADJUSTED_IID:
1468 mono_class_init (patch_info->data.klass);
1469 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
1471 case MONO_PATCH_INFO_VTABLE:
1472 target = mono_class_vtable (domain, patch_info->data.klass);
1475 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
1476 MonoDelegateClassMethodPair *del_tramp = patch_info->data.del_tramp;
1478 if (del_tramp->virtual)
1479 target = mono_create_delegate_virtual_trampoline (domain, del_tramp->klass, del_tramp->method);
1481 target = mono_create_delegate_trampoline_info (domain, del_tramp->klass, del_tramp->method);
1484 case MONO_PATCH_INFO_SFLDA: {
1485 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
1487 if (mono_class_field_is_special_static (patch_info->data.field)) {
1488 gpointer addr = NULL;
1490 mono_domain_lock (domain);
1491 if (domain->special_static_fields)
1492 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
1493 mono_domain_unlock (domain);
1499 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
1500 /* Done by the generated code */
1504 mono_runtime_class_init (vtable);
1506 target = (char*)mono_vtable_get_static_field_data (vtable) + patch_info->data.field->offset;
1509 case MONO_PATCH_INFO_RVA: {
1510 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
1513 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
1514 target = mono_image_rva_map (patch_info->data.token->image, rva);
1517 case MONO_PATCH_INFO_R4:
1518 case MONO_PATCH_INFO_R8:
1519 target = patch_info->data.target;
1521 case MONO_PATCH_INFO_EXC_NAME:
1522 target = patch_info->data.name;
1524 case MONO_PATCH_INFO_LDSTR:
1526 mono_ldstr (domain, patch_info->data.token->image,
1527 mono_metadata_token_index (patch_info->data.token->token));
1529 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
1531 MonoClass *handle_class;
1534 handle = mono_ldtoken_checked (patch_info->data.token->image,
1535 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, &error);
1536 if (!mono_error_ok (&error))
1537 g_error ("Could not patch ldtoken due to %s", mono_error_get_message (&error));
1538 mono_class_init (handle_class);
1539 mono_class_init (mono_class_from_mono_type (handle));
1542 mono_type_get_object (domain, handle);
1545 case MONO_PATCH_INFO_LDTOKEN: {
1547 MonoClass *handle_class;
1550 handle = mono_ldtoken_checked (patch_info->data.token->image,
1551 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, &error);
1552 if (!mono_error_ok (&error))
1553 g_error ("Could not patch ldtoken due to %s", mono_error_get_message (&error));
1554 mono_class_init (handle_class);
1559 case MONO_PATCH_INFO_DECLSEC:
1560 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
1562 case MONO_PATCH_INFO_ICALL_ADDR:
1563 /* run_cctors == 0 -> AOT */
1564 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1565 const char *exc_class;
1566 const char *exc_arg;
1569 target = mono_lookup_pinvoke_call (patch_info->data.method, &exc_class, &exc_arg);
1572 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
1573 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));
1579 target = mono_lookup_internal_call (patch_info->data.method);
1581 if (!target && run_cctors)
1582 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
1585 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1586 target = mono_thread_interruption_request_flag ();
1588 case MONO_PATCH_INFO_METHOD_RGCTX: {
1589 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
1592 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
1595 case MONO_PATCH_INFO_BB_OVF:
1596 case MONO_PATCH_INFO_EXC_OVF:
1597 case MONO_PATCH_INFO_GOT_OFFSET:
1598 case MONO_PATCH_INFO_NONE:
1600 case MONO_PATCH_INFO_RGCTX_FETCH: {
1601 int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
1603 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
1606 case MONO_PATCH_INFO_MONITOR_ENTER:
1607 target = mono_create_monitor_enter_trampoline ();
1609 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
1610 target = mono_create_monitor_enter_v4_trampoline ();
1612 case MONO_PATCH_INFO_MONITOR_EXIT:
1613 target = mono_create_monitor_exit_trampoline ();
1615 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
1616 case MONO_PATCH_INFO_SEQ_POINT_INFO:
1618 /* AOT, not needed */
1621 target = mono_arch_get_seq_point_info (domain, code);
1624 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1625 #ifdef MONO_ARCH_LLVM_SUPPORTED
1626 g_assert (mono_use_llvm);
1627 target = mono_create_llvm_imt_trampoline (domain, patch_info->data.imt_tramp->method, patch_info->data.imt_tramp->vt_offset);
1629 g_assert_not_reached ();
1632 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
1633 int card_table_shift_bits;
1634 gpointer card_table_mask;
1636 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
1639 case MONO_PATCH_INFO_GC_NURSERY_START: {
1643 target = mono_gc_get_nursery (&shift_bits, &size);
1646 case MONO_PATCH_INFO_CASTCLASS_CACHE: {
1647 target = mono_domain_alloc0 (domain, sizeof (gpointer));
1650 case MONO_PATCH_INFO_JIT_TLS_ID: {
1651 target = (gpointer) (size_t) mono_jit_tls_id;
1654 case MONO_PATCH_INFO_TLS_OFFSET: {
1657 offset = mini_get_tls_offset (GPOINTER_TO_INT (patch_info->data.target));
1658 #ifdef MONO_ARCH_HAVE_TRANSLATE_TLS_OFFSET
1659 offset = mono_arch_translate_tls_offset (offset);
1661 target = GINT_TO_POINTER (offset);
1664 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
1668 case MONO_PATCH_INFO_LDSTR_LIT: {
1672 len = strlen (patch_info->data.target);
1673 s = mono_domain_alloc0 (domain, len + 1);
1674 memcpy (s, patch_info->data.target, len);
1680 g_assert_not_reached ();
1683 return (gpointer)target;
1687 mini_init_gsctx (MonoDomain *domain, MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
1689 MonoGenericInst *inst;
1692 memset (gsctx, 0, sizeof (MonoGenericSharingContext));
1694 if (context && context->class_inst) {
1695 inst = context->class_inst;
1696 for (i = 0; i < inst->type_argc; ++i) {
1697 MonoType *type = inst->type_argv [i];
1699 if (mini_is_gsharedvt_gparam (type))
1700 gsctx->is_gsharedvt = TRUE;
1703 if (context && context->method_inst) {
1704 inst = context->method_inst;
1706 for (i = 0; i < inst->type_argc; ++i) {
1707 MonoType *type = inst->type_argv [i];
1709 if (mini_is_gsharedvt_gparam (type))
1710 gsctx->is_gsharedvt = TRUE;
1716 * LOCKING: Acquires the jit code hash lock.
1719 mini_lookup_method (MonoDomain *domain, MonoMethod *method, MonoMethod *shared)
1722 static gboolean inited = FALSE;
1723 static int lookups = 0;
1724 static int failed_lookups = 0;
1726 mono_domain_jit_code_hash_lock (domain);
1727 ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
1728 if (!ji && shared) {
1729 /* Try generic sharing */
1730 ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, shared);
1731 if (ji && !ji->has_generic_jit_info)
1734 mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
1735 mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
1743 mono_domain_jit_code_hash_unlock (domain);
1749 lookup_method (MonoDomain *domain, MonoMethod *method)
1754 ji = mini_lookup_method (domain, method, NULL);
1757 if (!mono_method_is_generic_sharable (method, FALSE))
1759 shared = mini_get_shared_method (method);
1760 ji = mini_lookup_method (domain, method, shared);
1767 mono_get_jit_info_from_method (MonoDomain *domain, MonoMethod *method)
1769 return lookup_method (domain, method);
1773 static FILE* perf_map_file;
1776 mono_enable_jit_map (void)
1778 if (!perf_map_file) {
1780 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
1782 perf_map_file = fopen (name, "w");
1787 mono_emit_jit_tramp (void *start, int size, const char *desc)
1790 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
1794 mono_emit_jit_map (MonoJitInfo *jinfo)
1796 if (perf_map_file) {
1797 char *name = mono_method_full_name (jinfo_get_method (jinfo), TRUE);
1798 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
1804 mono_jit_map_is_enabled (void)
1806 return perf_map_file != NULL;
1812 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex)
1814 MonoDomain *target_domain, *domain = mono_domain_get ();
1816 gpointer code = NULL, p;
1818 MonoJitICallInfo *callinfo = NULL;
1819 WrapperInfo *winfo = NULL;
1822 * ICALL wrappers are handled specially, since there is only one copy of them
1823 * shared by all appdomains.
1825 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1826 winfo = mono_marshal_get_wrapper_info (method);
1827 if (winfo && winfo->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
1828 callinfo = mono_find_jit_icall_by_addr (winfo->d.icall.func);
1829 g_assert (callinfo);
1831 /* Must be domain neutral since there is only one copy */
1832 opt |= MONO_OPT_SHARED;
1835 if (method->dynamic)
1836 opt &= ~MONO_OPT_SHARED;
1838 /* These methods can become invalid when a domain is unloaded */
1839 if (method->klass->image != mono_get_corlib () || method->is_inflated)
1840 opt &= ~MONO_OPT_SHARED;
1842 if (opt & MONO_OPT_SHARED)
1843 target_domain = mono_get_root_domain ();
1845 target_domain = domain;
1847 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
1848 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
1851 if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
1852 MonoGenericContext *ctx = NULL;
1853 if (method->is_inflated)
1854 ctx = mono_method_get_context (method);
1855 method = info->d.synchronized_inner.method;
1858 method = mono_class_inflate_generic_method_checked (method, ctx, &error);
1859 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
1864 info = lookup_method (target_domain, method);
1866 /* We can't use a domain specific method in another domain */
1867 if (! ((domain != target_domain) && !info->domain_neutral)) {
1869 MonoException *tmpEx;
1871 mono_jit_stats.methods_lookups++;
1872 vtable = mono_class_vtable (domain, method->klass);
1874 tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
1879 return mono_create_ftnptr (target_domain, info->code_start);
1883 #ifdef MONO_USE_AOT_COMPILER
1884 if (opt & MONO_OPT_AOT) {
1885 MonoDomain *domain = mono_domain_get ();
1887 mono_class_init (method->klass);
1889 if ((code = mono_aot_get_method (domain, method))) {
1892 vtable = mono_class_vtable (domain, method->klass);
1894 mono_runtime_class_init (vtable);
1900 code = mono_jit_compile_method_inner (method, target_domain, opt, ex);
1904 if (method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC) {
1908 * SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
1910 ji = mini_jit_info_table_find (mono_domain_get (), code, &d);
1914 p = mono_create_ftnptr (target_domain, code);
1917 /*mono_register_jit_icall_wrapper takes the loader lock, so we take it on the outside. */
1918 mono_loader_lock ();
1920 if (!callinfo->wrapper) {
1921 callinfo->wrapper = p;
1922 mono_register_jit_icall_wrapper (callinfo, p);
1925 mono_loader_unlock ();
1932 mono_jit_compile_method (MonoMethod *method)
1934 MonoException *ex = NULL;
1937 code = mono_jit_compile_method_with_opt (method, mono_get_optimizations_for_method (method, default_opt), &ex);
1940 mono_raise_exception (ex);
1946 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
1948 invalidated_delegate_trampoline (char *desc)
1950 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
1951 "See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
1957 * mono_jit_free_method:
1959 * Free all memory allocated by the JIT for METHOD.
1962 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
1964 MonoJitDynamicMethodInfo *ji;
1965 gboolean destroy = TRUE;
1966 GHashTableIter iter;
1967 MonoJumpList *jlist;
1969 g_assert (method->dynamic);
1971 mono_domain_lock (domain);
1972 ji = mono_dynamic_code_hash_lookup (domain, method);
1973 mono_domain_unlock (domain);
1978 mono_debug_remove_method (method, domain);
1980 mono_domain_lock (domain);
1981 g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
1982 mono_domain_jit_code_hash_lock (domain);
1983 mono_internal_hash_table_remove (&domain->jit_code_hash, method);
1984 mono_domain_jit_code_hash_unlock (domain);
1985 g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
1986 mono_conc_hashtable_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
1988 /* Remove jump targets in this method */
1989 g_hash_table_iter_init (&iter, domain_jit_info (domain)->jump_target_hash);
1990 while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
1991 GSList *tmp, *remove;
1994 for (tmp = jlist->list; tmp; tmp = tmp->next) {
1995 guint8 *ip = tmp->data;
1997 if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
1998 remove = g_slist_prepend (remove, tmp);
2000 for (tmp = remove; tmp; tmp = tmp->next) {
2001 jlist->list = g_slist_delete_link (jlist->list, tmp->data);
2003 g_slist_free (remove);
2006 mono_domain_unlock (domain);
2008 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
2009 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
2011 * Instead of freeing the code, change it to call an error routine
2012 * so people can fix their code.
2014 char *type = mono_type_full_name (&method->klass->byval_arg);
2015 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
2018 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
2024 * This needs to be done before freeing code_mp, since the code address is the
2025 * key in the table, so if we free the code_mp first, another thread can grab the
2026 * same code address and replace our entry in the table.
2028 mono_jit_info_table_remove (domain, ji->ji);
2031 mono_code_manager_destroy (ji->code_mp);
2036 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
2038 MonoDomain *target_domain;
2041 if (default_opt & MONO_OPT_SHARED)
2042 target_domain = mono_get_root_domain ();
2044 target_domain = domain;
2046 info = lookup_method (target_domain, method);
2048 /* We can't use a domain specific method in another domain */
2049 if (! ((domain != target_domain) && !info->domain_neutral)) {
2050 mono_jit_stats.methods_lookups++;
2053 return info->code_start;
2062 gboolean mono_do_single_method_regression = FALSE;
2063 guint32 mono_single_method_regression_opt = 0;
2064 MonoMethod *mono_current_single_method;
2065 GSList *mono_single_method_list;
2066 GHashTable *mono_single_method_hash;
2069 mono_get_optimizations_for_method (MonoMethod *method, guint32 default_opt)
2073 if (!mono_do_single_method_regression)
2075 if (!mono_current_single_method) {
2076 if (!mono_single_method_hash)
2077 mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
2078 if (!g_hash_table_lookup (mono_single_method_hash, method)) {
2079 g_hash_table_insert (mono_single_method_hash, method, method);
2080 mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
2084 if (method == mono_current_single_method)
2085 return mono_single_method_regression_opt;
2090 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
2092 return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
2097 gpointer compiled_method;
2098 gpointer runtime_invoke;
2100 MonoDynCallInfo *dyn_call_info;
2101 MonoClass *ret_box_class;
2102 } RuntimeInvokeInfo;
2105 * mono_jit_runtime_invoke:
2106 * @method: the method to invoke
2107 * @obj: this pointer
2108 * @params: array of parameter values.
2109 * @exc: used to catch exceptions objects
2112 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
2114 MonoMethod *invoke, *callee;
2115 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
2116 MonoDomain *domain = mono_domain_get ();
2117 MonoJitDomainInfo *domain_info;
2118 RuntimeInvokeInfo *info, *info2;
2120 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
2121 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
2125 domain_info = domain_jit_info (domain);
2127 info = mono_conc_hashtable_lookup (domain_info->runtime_invoke_hash, method);
2130 if (mono_security_core_clr_enabled ()) {
2132 * This might be redundant since mono_class_vtable () already does this,
2133 * but keep it just in case for moonlight.
2135 mono_class_setup_vtable (method->klass);
2136 if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
2138 *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
2140 mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
2145 info = g_new0 (RuntimeInvokeInfo, 1);
2147 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
2148 info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
2149 g_assert (info->vtable);
2152 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
2153 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
2155 * Array Get/Set/Address methods. The JIT implements them using inline code
2156 * inside the runtime invoke wrappers, so no need to compile them.
2158 if (mono_aot_only) {
2160 * Call a wrapper, since the runtime invoke wrapper was not generated.
2162 MonoMethod *wrapper;
2164 wrapper = mono_marshal_get_array_accessor_wrapper (method);
2165 invoke = mono_marshal_get_runtime_invoke (wrapper, FALSE);
2173 MonoException *jit_ex = NULL;
2175 info->compiled_method = mono_jit_compile_method_with_opt (callee, mono_get_optimizations_for_method (callee, default_opt), &jit_ex);
2176 if (!info->compiled_method) {
2180 *exc = (MonoObject*)jit_ex;
2183 mono_raise_exception (jit_ex);
2184 /* coverity[unreachable] */
2188 info->compiled_method = mini_add_method_trampoline (callee, info->compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
2190 info->compiled_method = NULL;
2194 * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
2195 * in full-aot mode, so we use a slower, but more generic wrapper if
2196 * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
2198 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2199 if (mono_aot_only || debug_options.dyn_runtime_invoke) {
2201 MonoMethodSignature *sig = mono_method_signature (method);
2202 gboolean supported = TRUE;
2205 if (method->string_ctor)
2206 sig = mono_marshal_get_string_ctor_signature (method);
2208 for (i = 0; i < sig->param_count; ++i) {
2209 MonoType *t = sig->params [i];
2211 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
2215 if (mono_class_is_contextbound (method->klass) || !info->compiled_method)
2219 info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
2221 ret_type = sig->ret;
2222 if (info->dyn_call_info) {
2223 switch (ret_type->type) {
2224 case MONO_TYPE_VOID:
2236 case MONO_TYPE_BOOLEAN:
2237 case MONO_TYPE_CHAR:
2240 info->ret_box_class = mono_class_from_mono_type (ret_type);
2243 info->ret_box_class = mono_defaults.int_class;
2245 case MONO_TYPE_STRING:
2246 case MONO_TYPE_CLASS:
2247 case MONO_TYPE_ARRAY:
2248 case MONO_TYPE_SZARRAY:
2249 case MONO_TYPE_OBJECT:
2251 case MONO_TYPE_GENERICINST:
2252 if (!MONO_TYPE_IS_REFERENCE (ret_type))
2253 info->ret_box_class = mono_class_from_mono_type (ret_type);
2255 case MONO_TYPE_VALUETYPE:
2256 info->ret_box_class = mono_class_from_mono_type (ret_type);
2259 g_assert_not_reached ();
2266 if (!info->dyn_call_info)
2267 info->runtime_invoke = mono_jit_compile_method (invoke);
2269 info2 = mono_conc_hashtable_insert (domain_info->runtime_invoke_hash, method, info);
2276 runtime_invoke = info->runtime_invoke;
2279 * We need this here because mono_marshal_get_runtime_invoke can place
2280 * the helper method in System.Object and not the target class.
2283 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
2287 mono_runtime_class_init (info->vtable);
2290 /* The wrappers expect this to be initialized to NULL */
2294 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2295 if (info->dyn_call_info) {
2296 MonoMethodSignature *sig = mono_method_signature (method);
2298 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
2301 guint8 retval [256];
2303 if (!dyn_runtime_invoke) {
2304 invoke = mono_marshal_get_runtime_invoke_dynamic ();
2305 dyn_runtime_invoke = mono_jit_compile_method (invoke);
2308 /* Convert the arguments to the format expected by start_dyn_call () */
2309 args = g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
2312 args [pindex ++] = &obj;
2313 for (i = 0; i < sig->param_count; ++i) {
2314 MonoType *t = sig->params [i];
2317 args [pindex ++] = ¶ms [i];
2318 } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
2319 args [pindex ++] = ¶ms [i];
2321 args [pindex ++] = params [i];
2325 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
2327 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
2329 dyn_runtime_invoke (buf, exc, info->compiled_method);
2331 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
2333 if (info->ret_box_class)
2334 return mono_value_box (domain, info->ret_box_class, retval);
2336 return *(MonoObject**)retval;
2340 return runtime_invoke (obj, params, exc, info->compiled_method);
2343 MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
2345 MonoException *exc = NULL;
2347 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2348 MONO_SIG_HANDLER_GET_CONTEXT;
2350 ji = mono_jit_info_table_find_internal (mono_domain_get (), mono_arch_ip_from_context (ctx), TRUE, TRUE);
2352 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
2353 if (mono_arch_is_int_overflow (ctx, info))
2355 * The spec says this throws ArithmeticException, but MS throws the derived
2356 * OverflowException.
2358 exc = mono_get_exception_overflow ();
2360 exc = mono_get_exception_divide_by_zero ();
2362 exc = mono_get_exception_divide_by_zero ();
2366 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2369 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2370 if (mono_do_crash_chaining) {
2371 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2376 mono_arch_handle_exception (ctx, exc);
2379 MONO_SIG_HANDLER_FUNC (, mono_sigill_signal_handler)
2382 MONO_SIG_HANDLER_GET_CONTEXT;
2384 exc = mono_get_exception_execution_engine ("SIGILL");
2386 mono_arch_handle_exception (ctx, exc);
2389 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
2390 #define HAVE_SIG_INFO
2393 MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
2396 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
2397 gpointer fault_addr = NULL;
2398 #ifdef HAVE_SIG_INFO
2399 MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
2403 MONO_SIG_HANDLER_GET_CONTEXT;
2405 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
2406 if (mono_arch_is_single_step_event (info, ctx)) {
2407 mono_debugger_agent_single_step_event (ctx);
2409 } else if (mono_arch_is_breakpoint_event (info, ctx)) {
2410 mono_debugger_agent_breakpoint_hit (ctx);
2415 #if defined(HAVE_SIG_INFO)
2416 #if !defined(HOST_WIN32)
2417 fault_addr = info->si_addr;
2418 if (mono_aot_is_pagefault (info->si_addr)) {
2419 mono_aot_handle_pagefault (info->si_addr);
2424 /* The thread might no be registered with the runtime */
2425 if (!mono_domain_get () || !jit_tls) {
2426 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2428 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2429 if (mono_do_crash_chaining) {
2430 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2436 ji = mono_jit_info_table_find_internal (mono_domain_get (), mono_arch_ip_from_context (ctx), TRUE, TRUE);
2438 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
2439 if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
2442 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
2443 /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
2444 fault_addr = info->si_addr;
2445 if (fault_addr == NULL) {
2448 mono_sigctx_to_monoctx (ctx, &mctx);
2450 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
2454 if (jit_tls->stack_size &&
2455 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
2457 * The hard-guard page has been hit: there is not much we can do anymore
2458 * Print a hopefully clear message and abort.
2460 mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
2461 g_assert_not_reached ();
2463 /* The original handler might not like that it is executed on an altstack... */
2464 if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2467 mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
2472 if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
2475 mono_handle_native_sigsegv (SIGSEGV, ctx, info);
2477 if (mono_do_crash_chaining) {
2478 mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
2483 mono_arch_handle_exception (ctx, NULL);
2487 MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
2490 MONO_SIG_HANDLER_GET_CONTEXT;
2492 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
2494 mono_arch_handle_exception (ctx, exc);
2497 #ifndef DISABLE_REMOTING
2498 /* mono_jit_create_remoting_trampoline:
2499 * @method: pointer to the method info
2501 * Creates a trampoline which calls the remoting functions. This
2502 * is used in the vtable of transparent proxies.
2504 * Returns: a pointer to the newly created code
2507 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
2510 guint8 *addr = NULL;
2512 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
2513 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
2517 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
2518 (mono_method_signature (method)->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))) {
2519 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
2520 addr = mono_compile_method (nm);
2523 addr = mono_compile_method (method);
2525 return mono_get_addr_from_ftnptr (addr);
2529 static gpointer *vtable_trampolines;
2530 static int vtable_trampolines_size;
2533 mini_get_vtable_trampoline (int slot_index)
2535 int index = slot_index + MONO_IMT_SIZE;
2537 g_assert (slot_index >= - MONO_IMT_SIZE);
2538 if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
2540 if (!vtable_trampolines || index >= vtable_trampolines_size) {
2544 new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
2545 while (new_size <= index)
2547 new_table = g_new0 (gpointer, new_size);
2549 if (vtable_trampolines)
2550 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
2551 g_free (vtable_trampolines);
2552 mono_memory_barrier ();
2553 vtable_trampolines = new_table;
2554 vtable_trampolines_size = new_size;
2559 if (!vtable_trampolines [index])
2560 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
2561 return vtable_trampolines [index];
2565 mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
2567 gboolean is_virtual_generic, is_interface, load_imt_reg;
2570 static guint8 **cache = NULL;
2571 static int cache_size = 0;
2576 if (MONO_TYPE_ISSTRUCT (sig->ret))
2579 is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
2580 is_interface = method->klass->flags & TYPE_ATTRIBUTE_INTERFACE ? TRUE : FALSE;
2581 load_imt_reg = is_virtual_generic || is_interface;
2583 if (is_interface && !is_virtual_generic)
2584 offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2586 offset = G_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2588 idx = (offset / SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
2589 g_assert (idx >= 0);
2591 /* Resize the cache to idx + 1 */
2592 if (cache_size < idx + 1) {
2594 if (cache_size < idx + 1) {
2596 int new_cache_size = idx + 1;
2598 new_cache = g_new0 (guint8*, new_cache_size);
2600 memcpy (new_cache, cache, cache_size * sizeof (guint8*));
2603 mono_memory_barrier ();
2605 cache_size = new_cache_size;
2613 /* FIXME Support more cases */
2614 if (mono_aot_only) {
2615 char tramp_name [256];
2616 const char *imt = load_imt_reg ? "_imt" : "";
2617 int ind = (load_imt_reg ? (-offset) : offset) / SIZEOF_VOID_P;
2619 sprintf (tramp_name, "delegate_virtual_invoke%s_%d", imt, ind);
2620 cache [idx] = mono_aot_get_trampoline (tramp_name);
2621 g_assert (cache [idx]);
2623 cache [idx] = mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
2629 mini_get_imt_trampoline (int slot_index)
2631 return mini_get_vtable_trampoline (slot_index - MONO_IMT_SIZE);
2635 mini_parse_debug_options (void)
2637 const char *options = g_getenv ("MONO_DEBUG");
2638 gchar **args, **ptr;
2643 args = g_strsplit (options, ",", -1);
2645 for (ptr = args; ptr && *ptr; ptr++) {
2646 const char *arg = *ptr;
2648 if (!strcmp (arg, "handle-sigint"))
2649 debug_options.handle_sigint = TRUE;
2650 else if (!strcmp (arg, "keep-delegates"))
2651 debug_options.keep_delegates = TRUE;
2652 else if (!strcmp (arg, "reverse-pinvoke-exceptions"))
2653 debug_options.reverse_pinvoke_exceptions = TRUE;
2654 else if (!strcmp (arg, "collect-pagefault-stats"))
2655 debug_options.collect_pagefault_stats = TRUE;
2656 else if (!strcmp (arg, "break-on-unverified"))
2657 debug_options.break_on_unverified = TRUE;
2658 else if (!strcmp (arg, "no-gdb-backtrace"))
2659 debug_options.no_gdb_backtrace = TRUE;
2660 else if (!strcmp (arg, "suspend-on-sigsegv"))
2661 debug_options.suspend_on_sigsegv = TRUE;
2662 else if (!strcmp (arg, "suspend-on-exception"))
2663 debug_options.suspend_on_exception = TRUE;
2664 else if (!strcmp (arg, "suspend-on-unhandled"))
2665 debug_options.suspend_on_unhandled = TRUE;
2666 else if (!strcmp (arg, "dont-free-domains"))
2667 mono_dont_free_domains = TRUE;
2668 else if (!strcmp (arg, "dyn-runtime-invoke"))
2669 debug_options.dyn_runtime_invoke = TRUE;
2670 else if (!strcmp (arg, "gdb"))
2671 debug_options.gdb = TRUE;
2672 else if (!strcmp (arg, "explicit-null-checks"))
2673 debug_options.explicit_null_checks = TRUE;
2674 else if (!strcmp (arg, "gen-seq-points"))
2675 debug_options.gen_sdb_seq_points = TRUE;
2676 else if (!strcmp (arg, "gen-compact-seq-points"))
2677 debug_options.gen_seq_points_compact_data = TRUE;
2678 else if (!strcmp (arg, "init-stacks"))
2679 debug_options.init_stacks = TRUE;
2680 else if (!strcmp (arg, "casts"))
2681 debug_options.better_cast_details = TRUE;
2682 else if (!strcmp (arg, "soft-breakpoints"))
2683 debug_options.soft_breakpoints = TRUE;
2684 else if (!strcmp (arg, "check-pinvoke-callconv"))
2685 debug_options.check_pinvoke_callconv = TRUE;
2686 else if (!strcmp (arg, "arm-use-fallback-tls"))
2687 debug_options.arm_use_fallback_tls = TRUE;
2688 else if (!strcmp (arg, "debug-domain-unload"))
2689 mono_enable_debug_domain_unload (TRUE);
2690 else if (!strcmp (arg, "partial-sharing"))
2691 mono_set_partial_sharing_supported (TRUE);
2692 else if (!strcmp (arg, "align-small-structs"))
2693 mono_align_small_structs = TRUE;
2695 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
2696 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains', 'suspend-on-sigsegv', 'suspend-on-exception', 'suspend-on-unhandled', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks', 'check-pinvoke-callconv', 'arm-use-fallback-tls', 'debug-domain-unload', 'partial-sharing', 'align-small-structs'\n");
2705 mini_get_debug_options (void)
2707 return &debug_options;
2711 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
2713 #if !defined(__ia64__) && (!defined(__ppc64__) && !defined(__powerpc64__) || _CALL_ELF == 2)
2716 gpointer* desc = NULL;
2718 if ((desc = g_hash_table_lookup (domain->ftnptrs_hash, addr)))
2721 desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
2725 # elif defined(__ppc64__) || defined(__powerpc64__)
2727 desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
2733 g_hash_table_insert (domain->ftnptrs_hash, addr, desc);
2739 mini_get_addr_from_ftnptr (gpointer descr)
2741 #if defined(__ia64__) || ((defined(__ppc64__) || defined(__powerpc64__)) && _CALL_ELF != 2)
2742 return *(gpointer*)descr;
2749 register_jit_stats (void)
2751 mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
2752 mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
2753 mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
2754 mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
2755 mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
2756 mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks);
2757 mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks);
2758 mono_counters_register ("Allocated vars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocate_var);
2759 mono_counters_register ("Code reallocs", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.code_reallocs);
2760 mono_counters_register ("Allocated code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_code_size);
2761 mono_counters_register ("Allocated seq points size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_seq_points_size);
2762 mono_counters_register ("Inlineable methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlineable_methods);
2763 mono_counters_register ("Inlined methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlined_methods);
2764 mono_counters_register ("Regvars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.regvars);
2765 mono_counters_register ("Locals stack size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.locals_stack_size);
2766 mono_counters_register ("Method cache lookups", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_lookups);
2767 mono_counters_register ("Compiled CIL code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.cil_code_size);
2768 mono_counters_register ("Native code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.native_code_size);
2769 mono_counters_register ("Aliases found", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_found);
2770 mono_counters_register ("Aliases eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.alias_removed);
2771 mono_counters_register ("Aliased loads eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.loads_eliminated);
2772 mono_counters_register ("Aliased stores eliminated", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.stores_eliminated);
2775 static void runtime_invoke_info_free (gpointer value);
2778 class_method_pair_equal (gconstpointer ka, gconstpointer kb)
2780 const MonoClassMethodPair *apair = ka;
2781 const MonoClassMethodPair *bpair = kb;
2783 return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
2787 class_method_pair_hash (gconstpointer data)
2789 const MonoClassMethodPair *pair = data;
2791 return (gsize)pair->klass ^ (gsize)pair->method;
2795 mini_create_jit_domain_info (MonoDomain *domain)
2797 MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
2799 info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2800 info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2801 info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
2802 info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
2803 info->runtime_invoke_hash = mono_conc_hashtable_new_full (&domain->lock, mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
2804 info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, mono_seq_point_info_free);
2805 info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
2806 info->jump_target_hash = g_hash_table_new (NULL, NULL);
2808 domain->runtime_info = info;
2812 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
2814 MonoJumpList *jlist = value;
2815 g_slist_free (jlist->list);
2819 delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
2821 GSList *list = value;
2822 g_slist_free (list);
2826 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
2828 MonoJitDynamicMethodInfo *di = value;
2829 mono_code_manager_destroy (di->code_mp);
2834 runtime_invoke_info_free (gpointer value)
2836 RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
2838 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2839 if (info->dyn_call_info)
2840 mono_arch_dyn_call_free (info->dyn_call_info);
2846 mini_free_jit_domain_info (MonoDomain *domain)
2848 MonoJitDomainInfo *info = domain_jit_info (domain);
2850 g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
2851 g_hash_table_destroy (info->jump_target_hash);
2852 if (info->jump_target_got_slot_hash) {
2853 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
2854 g_hash_table_destroy (info->jump_target_got_slot_hash);
2856 if (info->dynamic_code_hash) {
2857 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
2858 g_hash_table_destroy (info->dynamic_code_hash);
2860 if (info->method_code_hash)
2861 g_hash_table_destroy (info->method_code_hash);
2862 g_hash_table_destroy (info->jump_trampoline_hash);
2863 g_hash_table_destroy (info->jit_trampoline_hash);
2864 g_hash_table_destroy (info->delegate_trampoline_hash);
2865 if (info->static_rgctx_trampoline_hash)
2866 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
2867 g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
2868 mono_conc_hashtable_destroy (info->runtime_invoke_hash);
2869 g_hash_table_destroy (info->seq_points);
2870 g_hash_table_destroy (info->arch_seq_points);
2871 if (info->agent_info)
2872 mono_debugger_agent_free_domain_info (domain);
2873 if (info->gsharedvt_arg_tramp_hash)
2874 g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
2876 mono_llvm_free_domain_info (domain);
2879 g_free (domain->runtime_info);
2880 domain->runtime_info = NULL;
2885 llvm_init_inner (void)
2887 if (!mono_llvm_load (NULL))
2898 * Load and initialize LLVM support.
2899 * Return TRUE on success.
2902 mini_llvm_init (void)
2905 static gboolean llvm_inited;
2906 static gboolean init_result;
2908 mono_loader_lock_if_inited ();
2910 init_result = llvm_init_inner ();
2913 mono_loader_unlock_if_inited ();
2921 mini_init (const char *filename, const char *runtime_version)
2924 MonoRuntimeCallbacks callbacks;
2925 MonoThreadInfoRuntimeCallbacks ticallbacks;
2927 MONO_VES_INIT_BEGIN ();
2929 #if defined(__linux__) && !defined(__native_client__)
2930 if (access ("/proc/self/maps", F_OK) != 0) {
2931 g_print ("Mono requires /proc to be mounted.\n");
2936 mono_mutex_init_recursive (&jit_mutex);
2938 mono_cross_helpers_run ();
2942 /* Happens when using the embedding interface */
2943 if (!default_opt_set)
2944 default_opt = mono_parse_default_optimizations (NULL);
2946 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
2948 mono_set_generic_sharing_vt_supported (TRUE);
2951 #ifdef MONO_HAVE_FAST_TLS
2952 MONO_FAST_TLS_INIT (mono_jit_tls);
2953 MONO_FAST_TLS_INIT (mono_lmf_addr);
2954 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
2955 MONO_FAST_TLS_INIT (mono_lmf);
2959 mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
2961 if (!global_codeman)
2962 global_codeman = mono_code_manager_new ();
2964 memset (&callbacks, 0, sizeof (callbacks));
2965 callbacks.create_ftnptr = mini_create_ftnptr;
2966 callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
2967 callbacks.get_runtime_build_info = mono_get_runtime_build_info;
2968 callbacks.set_cast_details = mono_set_cast_details;
2969 callbacks.debug_log = mono_debugger_agent_debug_log;
2970 callbacks.debug_log_is_enabled = mono_debugger_agent_debug_log_is_enabled;
2971 callbacks.tls_key_supported = mini_tls_key_supported;
2973 callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
2974 callbacks.get_imt_trampoline = mini_get_imt_trampoline;
2976 mono_install_callbacks (&callbacks);
2978 memset (&ticallbacks, 0, sizeof (ticallbacks));
2979 ticallbacks.setup_async_callback = mono_setup_async_callback;
2980 ticallbacks.thread_state_init_from_sigctx = mono_thread_state_init_from_sigctx;
2981 ticallbacks.thread_state_init_from_handle = mono_thread_state_init_from_handle;
2983 mono_counters_init ();
2985 mono_threads_runtime_init (&ticallbacks);
2987 if (g_getenv ("MONO_DEBUG") != NULL)
2988 mini_parse_debug_options ();
2990 mono_code_manager_init ();
2994 mono_arch_cpu_init ();
2998 mono_unwind_init ();
3000 #ifdef XDEBUG_ENABLED
3001 if (g_getenv ("MONO_XDEBUG")) {
3002 const char *xdebug_opts = g_getenv ("MONO_XDEBUG");
3003 mono_xdebug_init (xdebug_opts);
3004 /* So methods for multiple domains don't have the same address */
3005 mono_dont_free_domains = TRUE;
3006 mono_using_xdebug = TRUE;
3007 } else if (mini_get_debug_options ()->gdb) {
3008 mono_xdebug_init ((char*)"gdb");
3009 mono_dont_free_domains = TRUE;
3010 mono_using_xdebug = TRUE;
3015 if (mono_use_llvm) {
3016 if (!mono_llvm_load (NULL)) {
3017 mono_use_llvm = FALSE;
3018 fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
3025 mono_trampolines_init ();
3027 mono_native_tls_alloc (&mono_jit_tls_id, NULL);
3029 if (default_opt & MONO_OPT_AOT)
3032 mono_debugger_agent_init ();
3034 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3035 mono_set_generic_sharing_supported (TRUE);
3038 #ifndef MONO_CROSS_COMPILE
3039 mono_runtime_install_handlers ();
3041 mono_threads_install_cleanup (mini_thread_cleanup);
3043 #define JIT_TRAMPOLINES_WORK
3044 #ifdef JIT_TRAMPOLINES_WORK
3045 mono_install_compile_method (mono_jit_compile_method);
3046 mono_install_free_method (mono_jit_free_method);
3047 mono_install_trampoline (mono_create_jit_trampoline);
3048 mono_install_jump_trampoline (mono_create_jump_trampoline);
3049 #ifndef DISABLE_REMOTING
3050 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
3052 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
3053 mono_install_create_domain_hook (mini_create_jit_domain_info);
3054 mono_install_free_domain_hook (mini_free_jit_domain_info);
3056 #define JIT_INVOKE_WORKS
3057 #ifdef JIT_INVOKE_WORKS
3058 mono_install_runtime_invoke (mono_jit_runtime_invoke);
3060 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
3061 mono_install_get_class_from_name (mono_aot_get_class_from_name);
3062 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
3064 if (debug_options.collect_pagefault_stats)
3065 mono_aot_set_make_unreadable (TRUE);
3067 if (runtime_version)
3068 domain = mono_init_version (filename, runtime_version);
3070 domain = mono_init_from_assembly (filename, filename);
3072 if (mono_aot_only) {
3073 /* This helps catch code allocation requests */
3074 mono_code_manager_set_read_only (domain->code_mp);
3075 mono_marshal_use_aot_wrappers (TRUE);
3079 mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
3081 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
3083 /*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
3084 mono_arch_finish_init ();
3088 /* This must come after mono_init () in the aot-only case */
3089 mono_exceptions_init ();
3091 /* This should come after mono_init () too */
3095 mono_create_helper_signatures ();
3098 register_jit_stats ();
3100 #define JIT_CALLS_WORK
3101 #ifdef JIT_CALLS_WORK
3102 /* Needs to be called here since register_jit_icall depends on it */
3103 mono_marshal_init ();
3105 mono_arch_register_lowlevel_calls ();
3109 mono_generic_sharing_init ();
3112 #ifdef MONO_ARCH_SIMD_INTRINSICS
3113 mono_simd_intrinsics_init ();
3116 #if MONO_SUPPORT_TASKLETS
3117 mono_tasklets_init ();
3120 register_trampolines (domain);
3122 if (mono_compile_aot)
3124 * Avoid running managed code when AOT compiling, since the platform
3125 * might only support aot-only execution.
3127 mono_runtime_set_no_exec (TRUE);
3129 #define JIT_RUNTIME_WORKS
3130 #ifdef JIT_RUNTIME_WORKS
3131 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
3132 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
3133 mono_thread_attach (domain);
3136 mono_profiler_runtime_initialized ();
3138 MONO_VES_INIT_END ();
3144 register_icalls (void)
3146 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
3147 ves_icall_get_frame_info);
3148 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
3149 ves_icall_get_trace);
3150 mono_add_internal_call ("System.Exception::get_trace",
3151 ves_icall_System_Exception_get_trace);
3152 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
3153 mono_runtime_install_handlers);
3155 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
3156 mono_add_internal_call ("System.Diagnostics.Debugger::Mono_UnhandledException_internal",
3157 mono_debugger_agent_unhandled_exception);
3161 * It's important that we pass `TRUE` as the last argument here, as
3162 * it causes the JIT to omit a wrapper for these icalls. If the JIT
3163 * *did* emit a wrapper, we'd be looking at infinite recursion since
3164 * the wrapper would call the icall which would call the wrapper and
3167 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", "void ptr", TRUE);
3168 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", "void ptr", TRUE);
3170 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
3171 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
3172 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
3173 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "ptr ptr", TRUE);
3174 register_icall (mono_jit_set_domain, "mono_jit_set_domain", "void ptr", TRUE);
3175 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
3177 register_dyn_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
3178 register_dyn_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
3179 register_dyn_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", "void ptr", TRUE);
3180 register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
3181 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "object", FALSE);
3182 register_icall (mono_thread_force_interruption_checkpoint_noraise, "mono_thread_force_interruption_checkpoint_noraise", "object", FALSE);
3183 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
3184 #ifndef DISABLE_REMOTING
3185 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
3186 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
3189 #if defined(__native_client__) || defined(__native_client_codegen__)
3190 register_icall (mono_nacl_gc, "mono_nacl_gc", "void", FALSE);
3192 #if defined(USE_COOP_GC)
3193 register_icall (mono_threads_state_poll, "mono_threads_state_poll", "void", FALSE);
3196 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
3197 register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, "mono_llmult", TRUE);
3198 register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, "mono_lldiv", FALSE);
3199 register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, "mono_lldiv_un", FALSE);
3200 register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, "mono_llrem", FALSE);
3201 register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, "mono_llrem_un", FALSE);
3203 #if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
3204 register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, "mono_llmult_ovf_un", FALSE);
3205 register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, "mono_llmult_ovf", FALSE);
3208 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
3209 register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, "mono_lshl", TRUE);
3210 register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, "mono_lshr", TRUE);
3211 register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, "mono_lshr_un", TRUE);
3214 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
3215 register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, "mono_idiv", FALSE);
3216 register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, "mono_idiv_un", FALSE);
3217 register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, "mono_irem", FALSE);
3218 register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, "mono_irem_un", FALSE);
3221 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3222 register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, "mono_imul", TRUE);
3225 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
3226 register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, "mono_imul_ovf", FALSE);
3227 register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, "mono_imul_ovf_un", FALSE);
3230 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
3231 if (ARCH_EMULATE_MUL_DIV || mono_arch_is_soft_float ()) {
3232 register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, "mono_fdiv", FALSE);
3236 register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, "mono_fconv_u8", FALSE);
3237 register_opcode_emulation (OP_RCONV_TO_U8, "__emul_rconv_to_u8", "ulong float", mono_rconv_u8, "mono_rconv_u8", FALSE);
3238 register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, "mono_fconv_u4", FALSE);
3239 register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, "mono_fconv_ovf_i8", FALSE);
3240 register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, "mono_fconv_ovf_u8", FALSE);
3241 register_opcode_emulation (OP_RCONV_TO_OVF_I8, "__emul_rconv_to_ovf_i8", "long float", mono_rconv_ovf_i8, "mono_rconv_ovf_i8", FALSE);
3242 register_opcode_emulation (OP_RCONV_TO_OVF_U8, "__emul_rconv_to_ovf_u8", "ulong float", mono_rconv_ovf_u8, "mono_rconv_ovf_u8", FALSE);
3245 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
3246 register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, "mono_fconv_i8", FALSE);
3247 register_opcode_emulation (OP_RCONV_TO_I8, "__emul_rconv_to_i8", "long float", mono_rconv_i8, "mono_rconv_i8", FALSE);
3250 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
3251 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);
3253 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
3254 register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, "mono_lconv_to_r8", FALSE);
3256 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
3257 register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, "mono_lconv_to_r4", FALSE);
3259 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
3260 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);
3262 #ifdef MONO_ARCH_EMULATE_FREM
3263 #if defined(__default_codegen__)
3264 register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, "fmod", FALSE);
3265 register_opcode_emulation (OP_RREM, "__emul_rrem", "float float float", fmodf, "fmodf", FALSE);
3266 #elif defined(__native_client_codegen__)
3267 register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, "mono_fmod", FALSE);
3271 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3272 if (mono_arch_is_soft_float ()) {
3273 register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, "mono_fsub", FALSE);
3274 register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, "mono_fadd", FALSE);
3275 register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, "mono_fmul", FALSE);
3276 register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, "mono_fneg", FALSE);
3277 register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, "mono_conv_to_r8", FALSE);
3278 register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, "mono_conv_to_r4", FALSE);
3279 register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, "mono_fconv_r4", FALSE);
3280 register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, "mono_fconv_i1", FALSE);
3281 register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, "mono_fconv_i2", FALSE);
3282 register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3283 register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, "mono_fconv_u1", FALSE);
3284 register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, "mono_fconv_u2", FALSE);
3286 #if SIZEOF_VOID_P == 4
3287 register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, "mono_fconv_i4", FALSE);
3290 register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, "mono_fcmp_eq", FALSE);
3291 register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, "mono_fcmp_lt", FALSE);
3292 register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, "mono_fcmp_gt", FALSE);
3293 register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, "mono_fcmp_le", FALSE);
3294 register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, "mono_fcmp_ge", FALSE);
3295 register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, "mono_fcmp_ne_un", FALSE);
3296 register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, "mono_fcmp_lt_un", FALSE);
3297 register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, "mono_fcmp_gt_un", FALSE);
3298 register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, "mono_fcmp_le_un", FALSE);
3299 register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, "mono_fcmp_ge_un", FALSE);
3301 register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, "mono_fceq", FALSE);
3302 register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, "mono_fcgt", FALSE);
3303 register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, "mono_fcgt_un", FALSE);
3304 register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, "mono_fclt", FALSE);
3305 register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, "mono_fclt_un", FALSE);
3307 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
3308 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
3309 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
3310 register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
3314 #ifdef COMPRESSED_INTERFACE_BITMAP
3315 register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
3318 #if SIZEOF_REGISTER == 4
3319 register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, "mono_fconv_u4", TRUE);
3321 register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "ulong double", mono_fconv_u8, "mono_fconv_u8", TRUE);
3324 /* other jit icalls */
3325 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
3326 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
3327 "ptr ptr ptr", FALSE);
3328 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
3329 register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
3330 "ptr ptr ptr ptr", FALSE);
3331 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
3332 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
3333 register_icall (mono_helper_stelem_ref_check, "mono_helper_stelem_ref_check", "void object object", FALSE);
3334 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
3335 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
3336 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
3337 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
3338 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
3339 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
3340 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
3341 register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
3342 register_icall (mono_helper_compile_generic_method, "mono_helper_compile_generic_method", "ptr object ptr ptr", FALSE);
3343 register_icall (mono_helper_ldstr, "mono_helper_ldstr", "object ptr int", FALSE);
3344 register_icall (mono_helper_ldstr_mscorlib, "mono_helper_ldstr_mscorlib", "object int", FALSE);
3345 register_icall (mono_helper_newobj_mscorlib, "mono_helper_newobj_mscorlib", "object int", FALSE);
3346 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
3347 register_icall (mono_object_castclass_unbox, "mono_object_castclass_unbox", "object object ptr", FALSE);
3348 register_icall (mono_break, "mono_break", NULL, TRUE);
3349 register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
3350 register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
3351 register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
3352 register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
3353 register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
3354 register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
3355 register_icall (mono_array_new_4, "mono_array_new_4", "object ptr int int int int", FALSE);
3356 register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
3357 register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
3358 register_icall (mono_gsharedvt_constrained_call, "mono_gsharedvt_constrained_call", "object ptr ptr ptr ptr ptr", FALSE);
3359 register_icall (mono_gsharedvt_value_copy, "mono_gsharedvt_value_copy", "void ptr ptr ptr", TRUE);
3361 register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
3363 register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
3364 register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
3365 register_icall (mono_generic_class_init, "mono_generic_class_init", "void ptr", FALSE);
3366 register_icall (mono_fill_class_rgctx, "mono_class_fill_rgctx", "ptr ptr int", FALSE);
3367 register_icall (mono_fill_method_rgctx, "mono_method_fill_rgctx", "ptr ptr int", FALSE);
3369 register_icall (mono_debugger_agent_user_break, "mono_debugger_agent_user_break", "void", FALSE);
3372 register_icall (pthread_getspecific, "pthread_getspecific", "ptr ptr", TRUE);
3376 MonoJitStats mono_jit_stats = {0};
3379 print_jit_stats (void)
3381 if (mono_jit_stats.enabled) {
3382 g_print ("Mono Jit statistics\n");
3383 g_print ("Max code size ratio: %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
3384 mono_jit_stats.max_ratio_method);
3385 g_print ("Biggest method: %ld (%s)\n", mono_jit_stats.biggest_method_size,
3386 mono_jit_stats.biggest_method);
3388 g_print ("Delegates created: %ld\n", mono_stats.delegate_creations);
3389 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
3390 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
3391 g_print ("Generic vtables: %ld\n", mono_stats.generic_vtable_count);
3392 g_print ("Methods: %ld\n", mono_stats.method_count);
3393 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
3394 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
3395 g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
3397 g_print ("\nInitialized classes: %ld\n", mono_stats.generic_class_count);
3398 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
3399 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
3401 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
3402 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
3403 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
3404 g_print ("Shared vtype generic methods: %ld\n", mono_stats.gsharedvt_methods);
3406 g_print ("IMT tables size: %ld\n", mono_stats.imt_tables_size);
3407 g_print ("IMT number of tables: %ld\n", mono_stats.imt_number_of_tables);
3408 g_print ("IMT number of methods: %ld\n", mono_stats.imt_number_of_methods);
3409 g_print ("IMT used slots: %ld\n", mono_stats.imt_used_slots);
3410 g_print ("IMT colliding slots: %ld\n", mono_stats.imt_slots_with_collisions);
3411 g_print ("IMT max collisions: %ld\n", mono_stats.imt_max_collisions_in_slot);
3412 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
3413 g_print ("IMT thunks size: %ld\n", mono_stats.imt_thunks_size);
3415 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
3416 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
3417 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
3419 g_free (mono_jit_stats.max_ratio_method);
3420 mono_jit_stats.max_ratio_method = NULL;
3421 g_free (mono_jit_stats.biggest_method);
3422 mono_jit_stats.biggest_method = NULL;
3427 mini_cleanup (MonoDomain *domain)
3429 mono_runtime_shutdown_stat_profiler ();
3432 cominterop_release_all_rcws ();
3435 #ifndef MONO_CROSS_COMPILE
3437 * mono_domain_finalize () needs to be called early since it needs the
3438 * execution engine still fully working (it may invoke managed finalizers).
3440 mono_domain_finalize (domain, 2000);
3443 /* This accesses metadata so needs to be called before runtime shutdown */
3446 mono_profiler_shutdown ();
3448 #ifndef MONO_CROSS_COMPILE
3449 mono_runtime_cleanup (domain);
3452 free_jit_tls_data (mono_native_tls_get_value (mono_jit_tls_id));
3454 mono_icall_cleanup ();
3456 mono_runtime_cleanup_handlers ();
3458 #ifndef MONO_CROSS_COMPILE
3459 mono_domain_free (domain, TRUE);
3460 mono_gc_mutex_cleanup ();
3465 mono_llvm_cleanup ();
3468 mono_aot_cleanup ();
3470 mono_trampolines_cleanup ();
3472 mono_unwind_cleanup ();
3474 mono_code_manager_destroy (global_codeman);
3475 g_free (vtable_trampolines);
3477 mini_jit_cleanup ();
3479 mono_tramp_info_cleanup ();
3481 mono_arch_cleanup ();
3483 mono_generic_sharing_cleanup ();
3487 mono_trace_cleanup ();
3489 mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, stdout);
3491 if (mono_inject_async_exc_method)
3492 mono_method_desc_free (mono_inject_async_exc_method);
3494 mono_native_tls_free (mono_jit_tls_id);
3496 mono_mutex_destroy (&jit_mutex);
3498 mono_mutex_destroy (&mono_delegate_section);
3500 mono_code_manager_cleanup ();
3502 #ifdef USE_JUMP_TABLES
3503 mono_jumptable_cleanup ();
3508 mono_set_defaults (int verbose_level, guint32 opts)
3510 mini_verbose = verbose_level;
3511 mono_set_optimizations (opts);
3515 mono_disable_optimizations (guint32 opts)
3517 default_opt &= ~opts;
3521 mono_set_optimizations (guint32 opts)
3524 default_opt_set = TRUE;
3525 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3526 mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
3531 mono_set_verbose_level (guint32 level)
3533 mini_verbose = level;
3537 * mono_get_runtime_build_info:
3539 * Return the runtime version + build date in string format.
3540 * The returned string is owned by the caller. The returned string
3541 * format is "VERSION (FULL_VERSION BUILD_DATE)" and build date is optional.
3544 mono_get_runtime_build_info (void)
3546 if (mono_build_date)
3547 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
3549 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
3553 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
3555 GHashTable *assemblies = (GHashTable*)user_data;
3556 MonoImage *image = mono_assembly_get_image (ass);
3557 MonoMethod *method, *invoke;
3560 if (g_hash_table_lookup (assemblies, ass))
3563 g_hash_table_insert (assemblies, ass, ass);
3565 if (mini_verbose > 0)
3566 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
3568 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
3569 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
3570 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
3572 if (method->is_generic || method->klass->generic_container)
3576 if (mini_verbose > 1) {
3577 char * desc = mono_method_full_name (method, TRUE);
3578 g_print ("Compiling %d %s\n", count, desc);
3581 mono_compile_method (method);
3582 if (strcmp (method->name, "Finalize") == 0) {
3583 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
3584 mono_compile_method (invoke);
3586 #ifndef DISABLE_REMOTING
3587 if (mono_class_is_marshalbyref (method->klass) && mono_method_signature (method)->hasthis) {
3588 invoke = mono_marshal_get_remoting_invoke_with_check (method);
3589 mono_compile_method (invoke);
3594 /* Load and precompile referenced assemblies as well */
3595 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
3596 mono_assembly_load_reference (image, i);
3597 if (image->references [i])
3598 mono_precompile_assembly (image->references [i], assemblies);
3602 void mono_precompile_assemblies ()
3604 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
3606 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
3608 g_hash_table_destroy (assemblies);
3613 * Have to export this for AOT.
3616 mono_personality (void)
3619 g_assert_not_reached ();
3622 #ifdef USE_JUMP_TABLES
3623 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
3625 typedef struct MonoJumpTableChunk {
3628 struct MonoJumpTableChunk *previous;
3629 /* gpointer entries[total]; */
3630 } MonoJumpTableChunk;
3632 static MonoJumpTableChunk* g_jumptable;
3633 #define mono_jumptable_lock() mono_mutex_lock (&jumptable_mutex)
3634 #define mono_jumptable_unlock() mono_mutex_unlock (&jumptable_mutex)
3635 static mono_mutex_t jumptable_mutex;
3637 static MonoJumpTableChunk*
3638 mono_create_jumptable_chunk (guint32 max_entries)
3640 guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
3641 MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
3642 chunk->total = max_entries;
3647 mono_jumptable_init (void)
3649 if (g_jumptable == NULL) {
3650 mono_mutex_init_recursive (&jumptable_mutex);
3651 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
3656 mono_jumptable_add_entry (void)
3658 return mono_jumptable_add_entries (1);
3662 mono_jumptable_add_entries (guint32 entries)
3667 mono_jumptable_init ();
3668 mono_jumptable_lock ();
3669 index = g_jumptable->active;
3670 if (index + entries >= g_jumptable->total) {
3672 * Grow jumptable, by adding one more chunk.
3673 * We cannot realloc jumptable, as there could be pointers
3674 * to existing jump table entries in the code, so instead
3675 * we just add one more chunk.
3677 guint32 max_entries = entries;
3678 MonoJumpTableChunk *new_chunk;
3680 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
3681 max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
3682 new_chunk = mono_create_jumptable_chunk (max_entries);
3683 /* Link old jumptable, so that we could free it up later. */
3684 new_chunk->previous = g_jumptable;
3685 g_jumptable = new_chunk;
3688 g_jumptable->active = index + entries;
3689 result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
3690 mono_jumptable_unlock();
3696 mono_jumptable_cleanup (void)
3699 MonoJumpTableChunk *current = g_jumptable, *prev;
3700 while (current != NULL) {
3701 prev = current->previous;
3706 mono_mutex_destroy (&jumptable_mutex);
3711 mono_jumptable_get_entry (guint8 *code_ptr)
3713 return mono_arch_jumptable_entry_from_code (code_ptr);