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