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