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