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