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