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