2 * aot-runtime.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc.
10 * Copyright 2011 Xamarin, Inc.
14 #include <sys/types.h>
20 #ifdef HAVE_SYS_MMAN_H
29 #ifdef HAVE_EXECINFO_H
36 #ifdef HAVE_SYS_WAIT_H
37 #include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
40 #include <mono/metadata/tabledefs.h>
41 #include <mono/metadata/class.h>
42 #include <mono/metadata/object.h>
43 #include <mono/metadata/tokentype.h>
44 #include <mono/metadata/appdomain.h>
45 #include <mono/metadata/debug-helpers.h>
46 #include <mono/metadata/assembly.h>
47 #include <mono/metadata/metadata-internals.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/gc-internal.h>
50 #include <mono/metadata/monitor.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/metadata/mono-endian.h>
53 #include <mono/utils/mono-logger-internal.h>
54 #include <mono/utils/mono-mmap.h>
55 #include "mono/utils/mono-compiler.h"
56 #include <mono/utils/mono-counters.h>
64 #define SHARED_EXT ".dll"
65 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
66 #define SHARED_EXT ".dylib"
67 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
68 #define SHARED_EXT ".dylib"
70 #define SHARED_EXT ".so"
73 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
74 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
75 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
82 typedef struct MonoAotModule {
84 /* Pointer to the Global Offset Table */
86 GHashTable *name_cache;
87 GHashTable *extra_methods;
88 /* Maps methods to their code */
89 GHashTable *method_to_code;
90 /* Maps pointers into the method info to the methods themselves */
91 GHashTable *method_ref_to_method;
92 MonoAssemblyName *image_names;
94 MonoAssembly *assembly;
95 MonoImage **image_table;
96 guint32 image_table_len;
106 gint32 *code_offsets;
107 gpointer *method_addresses;
108 /* This contains <offset, index> pairs sorted by offset */
109 /* This is needed because LLVM emitted methods can be in any order */
110 gint32 *sorted_code_offsets;
111 gint32 sorted_code_offsets_len;
112 guint32 *method_info_offsets;
113 guint32 *got_info_offsets;
114 guint32 *ex_info_offsets;
115 guint32 *class_info_offsets;
116 guint32 *methods_loaded;
117 guint16 *class_name_table;
118 guint32 *extra_method_table;
119 guint32 *extra_method_info_offsets;
120 guint32 *unbox_trampolines;
121 guint32 *unbox_trampolines_end;
125 /* Points to the mono EH data created by LLVM */
126 guint8 *mono_eh_frame;
128 /* Points to the trampolines */
129 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
130 /* The first unused trampoline of each kind */
131 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
133 gboolean use_page_trampolines;
135 MonoAotFileInfo info;
140 JitInfoMap *async_jit_info_table;
145 unsigned char *trampolines;
146 unsigned char *trampolines_end;
149 static GHashTable *aot_modules;
150 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
151 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
152 static CRITICAL_SECTION aot_mutex;
155 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
156 * AOT modules registered by mono_aot_register_module ().
158 static GHashTable *static_aot_modules;
161 * Maps MonoJitInfo* to the aot module they belong to, this can be different
162 * from ji->method->klass->image's aot module for generic instances.
164 static GHashTable *ji_to_amodule;
167 * Whenever to AOT compile loaded assemblies on demand and store them in
168 * a cache under $HOME/.mono/aot-cache.
170 static gboolean use_aot_cache = FALSE;
173 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
174 * use_aot_cache is TRUE.
176 static gboolean spawn_compiler = TRUE;
179 static gint32 mono_last_aot_method = -1;
181 static gboolean make_unreadable = FALSE;
182 static guint32 name_table_accesses = 0;
183 static guint32 n_pagefaults = 0;
185 /* Used to speed-up find_aot_module () */
186 static gsize aot_code_low_addr = (gssize)-1;
187 static gsize aot_code_high_addr = 0;
190 static gint32 async_jit_info_size;
192 static GHashTable *aot_jit_icall_hash;
195 #define USE_PAGE_TRAMPOLINES ((MonoAotModule*)mono_defaults.corlib->aot_module)->use_page_trampolines
197 #define USE_PAGE_TRAMPOLINES 0
200 #define mono_aot_page_lock() EnterCriticalSection (&aot_page_mutex)
201 #define mono_aot_page_unlock() LeaveCriticalSection (&aot_page_mutex)
202 static CRITICAL_SECTION aot_page_mutex;
205 init_plt (MonoAotModule *info);
207 /*****************************************************/
209 /*****************************************************/
214 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
215 * found, and sets the loader error if SET_ERROR is TRUE.
218 load_image (MonoAotModule *amodule, int index, gboolean set_error)
220 MonoAssembly *assembly;
221 MonoImageOpenStatus status;
223 g_assert (index < amodule->image_table_len);
225 if (amodule->image_table [index])
226 return amodule->image_table [index];
227 if (amodule->out_of_date)
230 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
232 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable because dependency %s is not found.\n", amodule->aot_name, amodule->image_names [index].name);
233 amodule->out_of_date = TRUE;
236 char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
237 mono_loader_set_error_assembly_load (full_name, FALSE);
243 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
244 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s').\n", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
245 amodule->out_of_date = TRUE;
249 amodule->image_table [index] = assembly->image;
250 return assembly->image;
254 decode_value (guint8 *ptr, guint8 **rptr)
259 if ((b & 0x80) == 0){
262 } else if ((b & 0x40) == 0){
263 len = ((b & 0x3f) << 8 | ptr [1]);
265 } else if (b != 0xff) {
266 len = ((b & 0x1f) << 24) |
273 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
279 //printf ("DECODE: %d.\n", len);
284 * mono_aot_get_offset:
286 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
290 mono_aot_get_offset (guint32 *table, int index)
292 int i, group, ngroups, index_entry_size;
293 int start_offset, offset, noffsets, group_size;
294 guint8 *data_start, *p;
295 guint32 *index32 = NULL;
296 guint16 *index16 = NULL;
298 noffsets = table [0];
299 group_size = table [1];
301 index_entry_size = table [3];
302 group = index / group_size;
304 if (index_entry_size == 2) {
305 index16 = (guint16*)&table [4];
306 data_start = (guint8*)&index16 [ngroups];
307 p = data_start + index16 [group];
309 index32 = (guint32*)&table [4];
310 data_start = (guint8*)&index32 [ngroups];
311 p = data_start + index32 [group];
314 /* offset will contain the value of offsets [group * group_size] */
315 offset = start_offset = decode_value (p, &p);
316 for (i = group * group_size + 1; i <= index; ++i) {
317 offset += decode_value (p, &p);
320 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
326 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
329 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
332 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
334 static MonoGenericInst*
335 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
338 MonoType **type_argv;
339 MonoGenericInst *inst;
342 type_argc = decode_value (p, &p);
343 type_argv = g_new0 (MonoType*, type_argc);
345 for (i = 0; i < type_argc; ++i) {
346 MonoClass *pclass = decode_klass_ref (module, p, &p);
351 type_argv [i] = &pclass->byval_arg;
354 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
363 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
370 argc = decode_value (p, &p);
373 ctx->class_inst = decode_generic_inst (module, p, &p);
374 if (!ctx->class_inst)
378 argc = decode_value (p, &p);
381 ctx->method_inst = decode_generic_inst (module, p, &p);
382 if (!ctx->method_inst)
391 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
394 MonoClass *klass = NULL, *eklass;
395 guint32 token, rank, idx;
399 reftype = decode_value (p, &p);
406 case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
407 idx = decode_value (p, &p);
408 image = load_image (module, 0, TRUE);
411 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
413 case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
414 idx = decode_value (p, &p);
415 image = load_image (module, decode_value (p, &p), TRUE);
418 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
420 case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
421 token = decode_value (p, &p);
422 image = module->assembly->image;
425 klass = mono_class_get (image, token);
427 case MONO_AOT_TYPEREF_GINST: {
429 MonoGenericContext ctx;
432 gclass = decode_klass_ref (module, p, &p);
435 g_assert (gclass->generic_container);
437 memset (&ctx, 0, sizeof (ctx));
438 ctx.class_inst = decode_generic_inst (module, p, &p);
441 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
442 klass = mono_class_from_mono_type (type);
443 mono_metadata_free_type (type);
446 case MONO_AOT_TYPEREF_VAR: {
448 MonoGenericContainer *container = NULL;
449 int type = decode_value (p, &p);
450 int num = decode_value (p, &p);
451 gboolean has_container = decode_value (p, &p);
455 gboolean is_method = decode_value (p, &p);
458 MonoMethod *method_def;
459 g_assert (type == MONO_TYPE_MVAR);
460 method_def = decode_resolve_method_ref (module, p, &p);
464 container = mono_method_get_generic_container (method_def);
466 MonoClass *class_def;
467 g_assert (type == MONO_TYPE_VAR);
468 class_def = decode_klass_ref (module, p, &p);
472 container = class_def->generic_container;
475 serial = decode_value (p, &p);
478 // FIXME: Memory management
479 t = g_new0 (MonoType, 1);
482 t->data.generic_param = mono_generic_container_get_param (container, num);
483 g_assert (serial == 0);
486 MonoGenericParam *par = (MonoGenericParam*)g_new0 (MonoGenericParamFull, 1);
488 par->serial = serial;
490 par->image = mono_defaults.corlib;
491 t->data.generic_param = par;
494 // FIXME: Maybe use types directly to avoid
495 // the overhead of creating MonoClass-es
496 klass = mono_class_from_mono_type (t);
501 case MONO_AOT_TYPEREF_ARRAY:
503 rank = decode_value (p, &p);
504 eklass = decode_klass_ref (module, p, &p);
505 klass = mono_array_class_get (eklass, rank);
507 case MONO_AOT_TYPEREF_PTR: {
510 t = decode_type (module, p, &p);
513 klass = mono_class_from_mono_type (t);
517 case MONO_AOT_TYPEREF_BLOB_INDEX: {
518 guint32 offset = decode_value (p, &p);
521 p2 = module->blob + offset;
522 klass = decode_klass_ref (module, p2, &p2);
526 g_assert_not_reached ();
529 //printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
534 static MonoClassField*
535 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
537 MonoClass *klass = decode_klass_ref (module, buf, &buf);
544 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
548 return mono_class_get_field (klass, token);
552 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
556 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
561 t = g_malloc0 (sizeof (MonoType));
564 if (*p == MONO_TYPE_PINNED) {
567 } else if (*p == MONO_TYPE_BYREF) {
580 case MONO_TYPE_BOOLEAN:
594 case MONO_TYPE_STRING:
595 case MONO_TYPE_OBJECT:
596 case MONO_TYPE_TYPEDBYREF:
598 case MONO_TYPE_VALUETYPE:
599 case MONO_TYPE_CLASS:
600 t->data.klass = decode_klass_ref (module, p, &p);
602 case MONO_TYPE_SZARRAY:
603 t->data.klass = decode_klass_ref (module, p, &p);
609 t->data.type = decode_type (module, p, &p);
611 case MONO_TYPE_GENERICINST: {
613 MonoGenericContext ctx;
617 gclass = decode_klass_ref (module, p, &p);
620 g_assert (gclass->generic_container);
622 memset (&ctx, 0, sizeof (ctx));
623 ctx.class_inst = decode_generic_inst (module, p, &p);
626 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
627 klass = mono_class_from_mono_type (type);
628 t->data.generic_class = klass->generic_class;
631 case MONO_TYPE_ARRAY: {
632 MonoArrayType *array;
635 // FIXME: memory management
636 array = g_new0 (MonoArrayType, 1);
637 array->eklass = decode_klass_ref (module, p, &p);
640 array->rank = decode_value (p, &p);
641 array->numsizes = decode_value (p, &p);
644 array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
645 for (i = 0; i < array->numsizes; ++i)
646 array->sizes [i] = decode_value (p, &p);
648 array->numlobounds = decode_value (p, &p);
649 if (array->numlobounds)
650 array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
651 for (i = 0; i < array->numlobounds; ++i)
652 array->lobounds [i] = decode_value (p, &p);
653 t->data.array = array;
657 case MONO_TYPE_MVAR: {
658 MonoClass *klass = decode_klass_ref (module, p, &p);
661 t->data.generic_param = klass->byval_arg.data.generic_param;
665 g_assert_not_reached ();
673 // FIXME: Error handling, memory management
675 static MonoMethodSignature*
676 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
678 MonoMethodSignature *sig;
680 int i, param_count, call_conv, gen_param_count = 0;
682 gboolean hasthis, explicit_this, has_gen_params;
686 has_gen_params = (flags & 0x10) != 0;
687 hasthis = (flags & 0x20) != 0;
688 explicit_this = (flags & 0x40) != 0;
689 call_conv = flags & 0x0F;
692 gen_param_count = decode_value (p, &p);
693 param_count = decode_value (p, &p);
694 if (target && param_count != target->param_count)
696 sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
697 sig->param_count = param_count;
698 sig->sentinelpos = -1;
699 sig->hasthis = hasthis;
700 sig->explicit_this = explicit_this;
701 sig->call_convention = call_conv;
702 sig->param_count = param_count;
703 sig->ret = decode_type (module, p, &p);
704 for (i = 0; i < param_count; ++i) {
705 if (*p == MONO_TYPE_SENTINEL) {
706 g_assert (sig->call_convention == MONO_CALL_VARARG);
707 sig->sentinelpos = i;
710 sig->params [i] = decode_type (module, p, &p);
713 if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
714 sig->sentinelpos = sig->param_count;
721 static MonoMethodSignature*
722 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
724 return decode_signature_with_target (module, NULL, buf, endbuf);
728 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
730 MonoMethodSignature *sig;
734 sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
735 res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
741 /* Stores information returned by decode_method_ref () */
746 gboolean no_aot_trampoline;
750 * decode_method_ref_with_target:
752 * Decode a method reference, storing the image/token into a MethodRef structure.
753 * This avoids loading metadata for the method if the caller does not need it. If the method has
754 * no token, then it is loaded from metadata and ref->method is set to the method instance.
755 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
756 * couldn't resolve to TARGET, and return FALSE.
757 * There are some kinds of method references which only support a non-null TARGET.
758 * This means that its not possible to decode this into a method, only to check
759 * that the method reference matches a given method. This is normally not a problem
760 * as these wrappers only occur in the extra_methods table, where we already have
761 * a method we want to lookup.
764 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
766 guint32 image_index, value;
767 MonoImage *image = NULL;
770 memset (ref, 0, sizeof (MethodRef));
772 value = decode_value (p, &p);
773 image_index = value >> 24;
775 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
776 ref->no_aot_trampoline = TRUE;
777 value = decode_value (p, &p);
778 image_index = value >> 24;
781 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
782 if (target && target->wrapper_type)
786 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
787 guint32 wrapper_type;
789 wrapper_type = decode_value (p, &p);
791 if (target && target->wrapper_type != wrapper_type)
795 image = mono_defaults.corlib;
797 switch (wrapper_type) {
798 #ifndef DISABLE_REMOTING
799 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
800 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
804 mono_class_init (m->klass);
805 ref->method = mono_marshal_get_remoting_invoke_with_check (m);
808 case MONO_WRAPPER_PROXY_ISINST: {
809 MonoClass *klass = decode_klass_ref (module, p, &p);
812 ref->method = mono_marshal_get_proxy_cancast (klass);
815 case MONO_WRAPPER_LDFLD:
816 case MONO_WRAPPER_LDFLDA:
817 case MONO_WRAPPER_STFLD:
818 case MONO_WRAPPER_ISINST: {
819 MonoClass *klass = decode_klass_ref (module, p, &p);
822 if (wrapper_type == MONO_WRAPPER_LDFLD)
823 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
824 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
825 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
826 else if (wrapper_type == MONO_WRAPPER_STFLD)
827 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
828 else if (wrapper_type == MONO_WRAPPER_ISINST)
829 ref->method = mono_marshal_get_isinst (klass);
831 g_assert_not_reached ();
834 case MONO_WRAPPER_LDFLD_REMOTE:
835 ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
837 case MONO_WRAPPER_STFLD_REMOTE:
838 ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
841 case MONO_WRAPPER_ALLOC: {
842 int atype = decode_value (p, &p);
844 ref->method = mono_gc_get_managed_allocator_by_type (atype);
845 g_assert (ref->method);
848 case MONO_WRAPPER_WRITE_BARRIER:
849 ref->method = mono_gc_get_write_barrier ();
851 case MONO_WRAPPER_STELEMREF: {
852 int subtype = decode_value (p, &p);
854 if (subtype == WRAPPER_SUBTYPE_NONE) {
855 ref->method = mono_marshal_get_stelemref ();
856 } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
860 kind = decode_value (p, &p);
862 /* Can't decode this */
865 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
866 info = mono_marshal_get_wrapper_info (target);
869 if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
870 ref->method = target;
877 g_assert_not_reached ();
881 case MONO_WRAPPER_SYNCHRONIZED: {
882 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
886 ref->method = mono_marshal_get_synchronized_wrapper (m);
889 case MONO_WRAPPER_UNKNOWN: {
890 MonoMethodDesc *desc;
891 MonoMethod *orig_method;
892 int subtype = decode_value (p, &p);
894 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
895 MonoClass *klass = decode_klass_ref (module, p, &p);
902 if (klass != target->klass)
905 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
906 if (strcmp (target->name, "PtrToStructure"))
908 ref->method = mono_marshal_get_ptr_to_struct (klass);
910 if (strcmp (target->name, "StructureToPtr"))
912 ref->method = mono_marshal_get_struct_to_ptr (klass);
914 } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
915 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
919 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
920 } else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
921 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
925 ref->method = mono_marshal_get_array_accessor_wrapper (m);
926 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
927 ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
928 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
929 ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
931 if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
932 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
933 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
934 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
935 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
936 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
938 g_assert_not_reached ();
939 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
940 g_assert (orig_method);
941 mono_method_desc_free (desc);
942 ref->method = mono_monitor_get_fast_path (orig_method);
946 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
947 int subtype = decode_value (p, &p);
949 if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
950 int rank = decode_value (p, &p);
951 int elem_size = decode_value (p, &p);
953 ref->method = mono_marshal_get_array_address (rank, elem_size);
954 } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
958 m = decode_resolve_method_ref (module, p, &p);
964 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
966 info = mono_marshal_get_wrapper_info (target);
967 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
968 ref->method = target;
974 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
976 int subtype = decode_value (p, &p);
979 if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
984 if (strcmp (target->name, name) != 0)
986 ref->method = target;
988 m = decode_resolve_method_ref (module, p, &p);
993 /* This should only happen when looking for an extra method */
996 if (mono_marshal_method_from_wrapper (target) == m)
997 ref->method = target;
1003 case MONO_WRAPPER_CASTCLASS: {
1004 int subtype = decode_value (p, &p);
1006 if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
1007 ref->method = mono_marshal_get_castclass_with_cache ();
1008 else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
1009 ref->method = mono_marshal_get_isinst_with_cache ();
1011 g_assert_not_reached ();
1014 case MONO_WRAPPER_RUNTIME_INVOKE: {
1015 int subtype = decode_value (p, &p);
1020 if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
1021 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
1023 ref->method = target;
1024 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
1025 /* Direct wrapper */
1026 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1030 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
1031 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
1032 /* Virtual direct wrapper */
1033 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1037 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
1039 MonoMethodSignature *sig;
1042 sig = decode_signature_with_target (module, NULL, p, &p);
1043 info = mono_marshal_get_wrapper_info (target);
1046 if (info->subtype != subtype)
1048 g_assert (info->d.runtime_invoke.sig);
1049 if (mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig))
1050 ref->method = target;
1056 case MONO_WRAPPER_DELEGATE_INVOKE:
1057 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1058 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
1059 gboolean is_inflated = decode_value (p, &p);
1060 WrapperSubtype subtype;
1064 MonoMethod *invoke, *wrapper;
1066 klass = decode_klass_ref (module, p, &p);
1070 switch (wrapper_type) {
1071 case MONO_WRAPPER_DELEGATE_INVOKE:
1072 invoke = mono_get_delegate_invoke (klass);
1073 wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
1075 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1076 invoke = mono_get_delegate_begin_invoke (klass);
1077 wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
1079 case MONO_WRAPPER_DELEGATE_END_INVOKE:
1080 invoke = mono_get_delegate_end_invoke (klass);
1081 wrapper = mono_marshal_get_delegate_end_invoke (invoke);
1084 g_assert_not_reached ();
1087 if (target && wrapper != target)
1089 ref->method = wrapper;
1092 * These wrappers are associated with a signature, not with a method.
1093 * Since we can't decode them into methods, they need a target method.
1098 if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1101 subtype = decode_value (p, &p);
1102 info = mono_marshal_get_wrapper_info (target);
1104 if (info->subtype != subtype)
1107 if (subtype != WRAPPER_SUBTYPE_NONE)
1111 if (sig_matches_target (module, target, p, &p))
1112 ref->method = target;
1118 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1122 m = decode_resolve_method_ref (module, p, &p);
1125 klass = decode_klass_ref (module, p, &p);
1128 ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
1132 g_assert_not_reached ();
1134 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1135 image_index = decode_value (p, &p);
1136 ref->token = decode_value (p, &p);
1138 image = load_image (module, image_index, TRUE);
1141 } else if (image_index == MONO_AOT_METHODREF_GINST) {
1143 MonoGenericContext ctx;
1146 * These methods do not have a token which resolves them, so we
1147 * resolve them immediately.
1149 klass = decode_klass_ref (module, p, &p);
1153 if (target && target->klass != klass)
1156 image_index = decode_value (p, &p);
1157 ref->token = decode_value (p, &p);
1159 image = load_image (module, image_index, TRUE);
1163 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
1167 memset (&ctx, 0, sizeof (ctx));
1169 if (FALSE && klass->generic_class) {
1170 ctx.class_inst = klass->generic_class->context.class_inst;
1171 ctx.method_inst = NULL;
1173 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1176 memset (&ctx, 0, sizeof (ctx));
1178 if (!decode_generic_context (module, &ctx, p, &p))
1181 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1182 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1186 klass = decode_klass_ref (module, p, &p);
1189 method_type = decode_value (p, &p);
1190 switch (method_type) {
1192 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
1195 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
1198 ref->method = mono_class_get_method_from_name (klass, "Get", -1);
1201 ref->method = mono_class_get_method_from_name (klass, "Address", -1);
1204 ref->method = mono_class_get_method_from_name (klass, "Set", -1);
1207 g_assert_not_reached ();
1210 if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
1211 image_index = decode_value (p, &p);
1212 value = decode_value (p, &p);
1215 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1217 image = load_image (module, image_index, TRUE);
1230 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
1232 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
1236 * decode_resolve_method_ref_with_target:
1238 * Similar to decode_method_ref, but resolve and return the method itself.
1241 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
1246 res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
1253 return mono_get_method (ref.image, ref.token, NULL);
1257 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
1259 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
1263 create_cache_structure (void)
1269 home = g_get_home_dir ();
1273 tmp = g_build_filename (home, ".mono", NULL);
1274 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1275 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1279 err = mkdir (tmp, 0777);
1282 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1288 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
1289 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1290 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1294 err = mkdir (tmp, 0777);
1297 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1306 * load_aot_module_from_cache:
1308 * Experimental code to AOT compile loaded assemblies on demand.
1311 * - Add environment variable MONO_AOT_CACHE_OPTIONS
1312 * - Add options for controlling the cache size
1313 * - Handle full cache by deleting old assemblies lru style
1314 * - Add options for excluding assemblies during development
1315 * - Maybe add a threshold after an assembly is AOT compiled
1316 * - invoking a new mono process is a security risk
1317 * - recompile the AOT module if one of its dependencies changes
1320 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
1322 char *fname, *cmd, *tmp2, *aot_options;
1331 if (assembly->image->dynamic)
1334 create_cache_structure ();
1336 home = g_get_home_dir ();
1338 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
1339 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
1343 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
1344 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1347 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
1349 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
1351 aot_options = g_strdup_printf ("outfile=%s", fname);
1353 if (spawn_compiler) {
1354 /* FIXME: security */
1355 /* FIXME: Has to pass the assembly loading path to the child process */
1356 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
1358 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1360 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
1362 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1363 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
1365 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1372 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1374 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
1376 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1380 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1382 g_free (aot_options);
1389 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1393 guint16 *table, *entry;
1396 char *symbol = (char*)name;
1399 symbol = g_strdup_printf ("_%s", name);
1402 /* The first entry points to the hash */
1403 table = globals [0];
1406 table_size = table [0];
1409 hash = mono_metadata_str_hash (symbol) % table_size;
1411 entry = &table [hash * 2];
1413 /* Search the hash for the index into the globals table */
1415 while (entry [0] != 0) {
1416 guint32 index = entry [0] - 1;
1417 guint32 next = entry [1];
1419 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1421 if (!strcmp (globals [index * 2], symbol)) {
1422 global_index = index;
1427 entry = &table [next * 2];
1433 if (global_index != -1)
1434 *value = globals [global_index * 2 + 1];
1441 char *err = mono_dl_symbol (module, name, value);
1449 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
1453 gboolean usable = TRUE;
1456 guint32 excluded_cpu_optimizations;
1458 if (strcmp (assembly->image->guid, info->assembly_guid)) {
1459 msg = g_strdup_printf ("doesn't match assembly");
1463 build_info = mono_get_runtime_build_info ();
1464 if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1465 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1468 g_free (build_info);
1470 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1472 if (mono_aot_only && !full_aot) {
1473 msg = g_strdup_printf ("not compiled with --aot=full");
1476 if (!mono_aot_only && full_aot) {
1477 msg = g_strdup_printf ("compiled with --aot=full");
1481 /* mono_arch_find_imt_method () requires this */
1482 if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1483 msg = g_strdup_printf ("compiled against LLVM");
1486 if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1487 msg = g_strdup_printf ("not compiled against LLVM");
1491 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1492 msg = g_strdup_printf ("not compiled for debugging");
1496 mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1497 if (info->opts & excluded_cpu_optimizations) {
1498 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1502 if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
1503 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1509 if (info->gc_name_index != -1) {
1510 char *gc_name = (char*)&blob [info->gc_name_index];
1511 const char *current_gc_name = mono_gc_get_gc_name ();
1513 if (strcmp (current_gc_name, gc_name) != 0) {
1514 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1523 /* This returns an interop address */
1525 get_arm_bl_target (guint32 *ins_addr)
1528 guint32 ins = *ins_addr;
1531 if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
1533 offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
1534 return (char*)ins_addr + (offset * 2) + 8 + 1;
1536 offset = (((int)ins & 0xffffff) << 8) >> 8;
1537 return (char*)ins_addr + (offset * 4) + 8;
1540 g_assert_not_reached ();
1546 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1549 MonoAotModule *amodule;
1551 gboolean usable = TRUE;
1552 char *version_symbol = NULL;
1554 gpointer *globals = NULL;
1555 MonoAotFileInfo *info = NULL;
1558 gboolean do_load_image = TRUE;
1559 int align_double, align_int64;
1561 if (mono_compile_aot)
1564 if (assembly->image->aot_module)
1566 * Already loaded. This can happen because the assembly loading code might invoke
1567 * the assembly load hooks multiple times for the same assembly.
1571 if (assembly->image->dynamic || assembly->ref_only)
1574 if (mono_security_cas_enabled ())
1578 if (static_aot_modules)
1579 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1585 /* Statically linked AOT module */
1587 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1588 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1589 globals = info->globals;
1592 sofile = load_aot_module_from_cache (assembly, &aot_name);
1595 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1597 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1600 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module '%s' not found: %s\n", aot_name, err);
1606 if (!sofile && !globals) {
1607 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1608 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1616 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1617 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1620 if (version_symbol) {
1621 /* Old file format */
1622 version = atoi (version_symbol);
1625 version = info->version;
1628 if (version != MONO_AOT_FILE_VERSION) {
1629 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1632 usable = check_usable (assembly, info, &msg);
1636 if (mono_aot_only) {
1637 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1640 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1645 mono_dl_close (sofile);
1646 assembly->image->aot_module = NULL;
1650 #if defined (TARGET_ARM) && defined (TARGET_MACH)
1655 memset (&t, 0, sizeof (MonoType));
1656 t.type = MONO_TYPE_R8;
1657 mono_type_size (&t, &align);
1658 align_double = align;
1660 memset (&t, 0, sizeof (MonoType));
1661 t.type = MONO_TYPE_I8;
1662 align_int64 = align;
1665 align_double = __alignof__ (double);
1666 align_int64 = __alignof__ (gint64);
1670 g_assert (info->double_align == align_double);
1671 g_assert (info->long_align == align_int64);
1672 g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
1676 amodule = g_new0 (MonoAotModule, 1);
1677 amodule->aot_name = aot_name;
1678 amodule->assembly = assembly;
1680 memcpy (&amodule->info, info, sizeof (*info));
1682 amodule->got = amodule->info.got;
1683 amodule->got [0] = assembly->image;
1684 amodule->globals = globals;
1685 amodule->sofile = sofile;
1686 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1687 amodule->blob = blob;
1689 /* Read image table */
1691 guint32 table_len, i;
1694 table = info->image_table;
1697 table_len = *(guint32*)table;
1698 table += sizeof (guint32);
1699 amodule->image_table = g_new0 (MonoImage*, table_len);
1700 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1701 amodule->image_guids = g_new0 (char*, table_len);
1702 amodule->image_table_len = table_len;
1703 for (i = 0; i < table_len; ++i) {
1704 MonoAssemblyName *aname = &(amodule->image_names [i]);
1706 aname->name = g_strdup (table);
1707 table += strlen (table) + 1;
1708 amodule->image_guids [i] = g_strdup (table);
1709 table += strlen (table) + 1;
1711 aname->culture = g_strdup (table);
1712 table += strlen (table) + 1;
1713 memcpy (aname->public_key_token, table, strlen (table) + 1);
1714 table += strlen (table) + 1;
1716 table = ALIGN_PTR_TO (table, 8);
1717 aname->flags = *(guint32*)table;
1719 aname->major = *(guint32*)table;
1721 aname->minor = *(guint32*)table;
1723 aname->build = *(guint32*)table;
1725 aname->revision = *(guint32*)table;
1730 amodule->code_offsets = info->code_offsets;
1731 amodule->method_addresses = info->method_addresses;
1732 amodule->code = info->methods;
1734 /* Mask out thumb interop bit */
1735 amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1737 amodule->code_end = info->methods_end;
1738 amodule->method_info_offsets = info->method_info_offsets;
1739 amodule->ex_info_offsets = info->ex_info_offsets;
1740 amodule->class_info_offsets = info->class_info_offsets;
1741 amodule->class_name_table = info->class_name_table;
1742 amodule->extra_method_table = info->extra_method_table;
1743 amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1744 amodule->unbox_trampolines = info->unbox_trampolines;
1745 amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1746 amodule->got_info_offsets = info->got_info_offsets;
1747 amodule->unwind_info = info->unwind_info;
1748 amodule->mem_end = info->mem_end;
1749 amodule->mem_begin = amodule->code;
1750 amodule->plt = info->plt;
1751 amodule->plt_end = info->plt_end;
1752 amodule->mono_eh_frame = info->mono_eh_frame;
1753 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1754 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1755 amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1756 amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = info->gsharedvt_arg_trampolines;
1757 amodule->thumb_end = info->thumb_end;
1759 if (info->flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) {
1760 /* Compute code_offsets from the method addresses */
1761 amodule->code_offsets = g_malloc0 (amodule->info.nmethods * sizeof (gint32));
1762 for (i = 0; i < amodule->info.nmethods; ++i) {
1763 /* method_addresses () contains a table of branches, since the ios linker can update those correctly */
1767 addr = get_call_target ((guint32*)amodule->method_addresses + i);
1768 #elif defined(TARGET_X86) || defined(TARGET_AMD64)
1769 addr = mono_arch_get_call_target ((guint8*)amodule->method_addresses + (i * 5) + 5);
1771 g_assert_not_reached ();
1774 if (addr == amodule->method_addresses)
1775 amodule->code_offsets [i] = 0xffffffff;
1777 amodule->code_offsets [i] = (char*)addr - (char*)amodule->code;
1781 if (make_unreadable) {
1782 #ifndef TARGET_WIN32
1784 guint8 *page_start, *page_end;
1787 addr = amodule->mem_begin;
1788 len = amodule->mem_end - amodule->mem_begin;
1790 /* Round down in both directions to avoid modifying data which is not ours */
1791 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1792 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1793 if (page_end > page_start) {
1794 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1795 g_assert (err == 0);
1802 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1803 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1805 g_hash_table_insert (aot_modules, assembly, amodule);
1808 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1810 assembly->image->aot_module = amodule;
1812 if (mono_aot_only) {
1814 find_symbol (amodule->sofile, amodule->globals, "specific_trampolines_page", (gpointer *)&code);
1815 amodule->use_page_trampolines = code != NULL;
1816 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
1817 if (mono_defaults.corlib) {
1818 /* The second got slot contains the mscorlib got addr */
1819 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1821 amodule->got [1] = mscorlib_amodule->got;
1823 amodule->got [1] = amodule->got;
1827 if (mono_gc_is_moving ()) {
1830 memset (&ji, 0, sizeof (ji));
1831 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1833 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1837 * Since we store methoddef and classdef tokens when referring to methods/classes in
1838 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1839 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1840 * non-lazily, since we can't handle out-of-date errors later.
1841 * The cached class info also depends on the exact assemblies.
1843 #if defined(__native_client__)
1844 /* TODO: Don't 'load_image' on mscorlib due to a */
1845 /* recursive loading problem. This should be */
1846 /* removed if mscorlib is loaded from disk. */
1847 if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1848 do_load_image = TRUE;
1850 do_load_image = FALSE;
1853 if (do_load_image) {
1854 for (i = 0; i < amodule->image_table_len; ++i)
1855 load_image (amodule, i, FALSE);
1858 if (amodule->out_of_date) {
1859 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT Module %s is unusable because a dependency is out-of-date.\n", assembly->image->name);
1860 if (mono_aot_only) {
1861 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode because a dependency cannot be found or it is out of date.\n", aot_name);
1866 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1870 * mono_aot_register_globals:
1872 * This is called by the ctor function in AOT images compiled with the
1873 * 'no-dlsym' option.
1876 mono_aot_register_globals (gpointer *globals)
1878 g_assert_not_reached ();
1882 * mono_aot_register_module:
1884 * This should be called by embedding code to register AOT modules statically linked
1885 * into the executable. AOT_INFO should be the value of the
1886 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1889 mono_aot_register_module (gpointer *aot_info)
1893 MonoAotFileInfo *info = (gpointer)aot_info;
1895 g_assert (info->version == MONO_AOT_FILE_VERSION);
1897 globals = info->globals;
1900 aname = info->assembly_name;
1902 /* This could be called before startup */
1906 if (!static_aot_modules)
1907 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1909 g_hash_table_insert (static_aot_modules, aname, info);
1916 mono_aot_init (void)
1918 InitializeCriticalSection (&aot_mutex);
1919 InitializeCriticalSection (&aot_page_mutex);
1920 aot_modules = g_hash_table_new (NULL, NULL);
1922 #ifndef __native_client__
1923 mono_install_assembly_load_hook (load_aot_module, NULL);
1925 mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
1927 if (g_getenv ("MONO_LASTAOT"))
1928 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1929 if (g_getenv ("MONO_AOT_CACHE"))
1930 use_aot_cache = TRUE;
1934 mono_aot_cleanup (void)
1936 if (aot_jit_icall_hash)
1937 g_hash_table_destroy (aot_jit_icall_hash);
1939 g_hash_table_destroy (aot_modules);
1943 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1949 info->vtable_size = decode_value (buf, &buf);
1950 if (info->vtable_size == -1)
1953 flags = decode_value (buf, &buf);
1954 info->ghcimpl = (flags >> 0) & 0x1;
1955 info->has_finalize = (flags >> 1) & 0x1;
1956 info->has_cctor = (flags >> 2) & 0x1;
1957 info->has_nested_classes = (flags >> 3) & 0x1;
1958 info->blittable = (flags >> 4) & 0x1;
1959 info->has_references = (flags >> 5) & 0x1;
1960 info->has_static_refs = (flags >> 6) & 0x1;
1961 info->no_special_static_fields = (flags >> 7) & 0x1;
1962 info->is_generic_container = (flags >> 8) & 0x1;
1964 if (info->has_cctor) {
1965 res = decode_method_ref (module, &ref, buf, &buf);
1968 info->cctor_token = ref.token;
1970 if (info->has_finalize) {
1971 res = decode_method_ref (module, &ref, buf, &buf);
1974 info->finalize_image = ref.image;
1975 info->finalize_token = ref.token;
1978 info->instance_size = decode_value (buf, &buf);
1979 info->class_size = decode_value (buf, &buf);
1980 info->packing_size = decode_value (buf, &buf);
1981 info->min_align = decode_value (buf, &buf);
1989 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1992 MonoClass *klass = vtable->klass;
1993 MonoAotModule *amodule = klass->image->aot_module;
1995 MonoCachedClassInfo class_info;
2000 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
2003 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
2006 err = decode_cached_class_info (amodule, &class_info, p, &p);
2010 for (i = 0; i < slot; ++i)
2011 decode_method_ref (amodule, &ref, p, &p);
2013 res = decode_method_ref (amodule, &ref, p, &p);
2016 if (ref.no_aot_trampoline)
2019 if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
2022 return mono_aot_get_method_from_token (domain, ref.image, ref.token);
2026 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2028 MonoAotModule *amodule = klass->image->aot_module;
2032 if (klass->rank || !amodule)
2035 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
2037 err = decode_cached_class_info (amodule, res, p, &p);
2045 * mono_aot_get_class_from_name:
2047 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
2048 * using a cache stored in the AOT file.
2049 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
2051 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
2055 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2057 MonoAotModule *amodule = image->aot_module;
2058 guint16 *table, *entry;
2061 char full_name_buf [1024];
2063 const char *name2, *name_space2;
2065 guint32 cols [MONO_TYPEDEF_SIZE];
2066 GHashTable *nspace_table;
2068 if (!amodule || !amodule->class_name_table)
2075 /* First look in the cache */
2076 if (!amodule->name_cache)
2077 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
2078 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2080 *klass = g_hash_table_lookup (nspace_table, name);
2087 table_size = amodule->class_name_table [0];
2088 table = amodule->class_name_table + 1;
2090 if (name_space [0] == '\0')
2091 full_name = g_strdup_printf ("%s", name);
2093 if (strlen (name_space) + strlen (name) < 1000) {
2094 sprintf (full_name_buf, "%s.%s", name_space, name);
2095 full_name = full_name_buf;
2097 full_name = g_strdup_printf ("%s.%s", name_space, name);
2100 hash = mono_metadata_str_hash (full_name) % table_size;
2101 if (full_name != full_name_buf)
2104 entry = &table [hash * 2];
2106 if (entry [0] != 0) {
2107 t = &image->tables [MONO_TABLE_TYPEDEF];
2110 guint32 index = entry [0];
2111 guint32 next = entry [1];
2112 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2114 name_table_accesses ++;
2116 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2118 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2119 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2121 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2123 *klass = mono_class_get (image, token);
2128 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2129 if (!nspace_table) {
2130 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2131 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2133 g_hash_table_insert (nspace_table, (char*)name2, *klass);
2140 entry = &table [next * 2];
2153 * decode_mono_eh_frame:
2155 * Decode the EH information emitted by our modified LLVM compiler and construct a
2156 * MonoJitInfo structure from it.
2157 * LOCKING: Acquires the domain lock.
2160 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
2161 MonoMethod *method, guint8 *code,
2162 MonoJitExceptionInfo *clauses, int num_clauses,
2163 int extra_size, GSList **nesting,
2164 int *this_reg, int *this_offset)
2167 guint8 *fde, *cie, *code_start, *code_end;
2168 int version, fde_count;
2170 int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
2171 MonoJitExceptionInfo *ei;
2172 guint32 fde_len, ei_len, nested_len, nindex;
2173 gpointer *type_info;
2175 MonoLLVMFDEInfo info;
2177 g_assert (amodule->mono_eh_frame);
2179 p = amodule->mono_eh_frame;
2181 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2185 g_assert (version == 3);
2189 p = ALIGN_PTR_TO (p, 4);
2191 fde_count = *(guint32*)p;
2195 /* There is +1 entry in the table */
2196 cie = p + ((fde_count + 1) * 8);
2198 /* Binary search in the table to find the entry for code */
2199 offset = code - amodule->code;
2203 pos = (left + right) / 2;
2205 /* The table contains method index/fde offset pairs */
2206 g_assert (table [(pos * 2)] != -1);
2207 offset1 = amodule->code_offsets [table [(pos * 2)]];
2208 if (pos + 1 == fde_count) {
2209 offset2 = amodule->code_end - amodule->code;
2211 g_assert (table [(pos + 1) * 2] != -1);
2212 offset2 = amodule->code_offsets [table [(pos + 1) * 2]];
2215 if (offset < offset1)
2217 else if (offset >= offset2)
2223 code_start = amodule->code + amodule->code_offsets [table [(pos * 2)]];
2224 if (pos + 1 == fde_count) {
2225 /* The +1 entry in the table contains the length of the last method */
2226 int len = table [(pos + 1) * 2];
2227 code_end = code_start + len;
2229 code_end = amodule->code + amodule->code_offsets [table [(pos + 1) * 2]];
2231 code_len = code_end - code_start;
2233 g_assert (code >= code_start && code < code_end);
2235 if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
2236 /* Clear thumb flag */
2237 code_start = (guint8*)(((mgreg_t)code_start) & ~1);
2239 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
2240 /* This won't overflow because there is +1 entry in the table */
2241 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2243 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
2245 ei_len = info.ex_info_len;
2246 type_info = info.type_info;
2247 *this_reg = info.this_reg;
2248 *this_offset = info.this_offset;
2250 /* Count number of nested clauses */
2252 for (i = 0; i < ei_len; ++i) {
2253 /* This might be unaligned */
2254 gint32 cindex1 = read32 (type_info [i]);
2257 for (l = nesting [cindex1]; l; l = l->next) {
2258 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2260 for (j = 0; j < ei_len; ++j) {
2261 gint32 cindex2 = read32 (type_info [j]);
2263 if (cindex2 == nesting_cindex)
2270 * LLVM might represent one IL region with multiple regions, so have to
2271 * allocate a new JI.
2274 mono_domain_alloc0_lock_free (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2276 jinfo->code_size = code_len;
2277 jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2278 jinfo->d.method = method;
2279 jinfo->code_start = code;
2280 jinfo->domain_neutral = 0;
2281 /* This signals that used_regs points to a normal cached unwind info */
2282 jinfo->from_aot = 0;
2283 jinfo->num_clauses = ei_len + nested_len;
2285 for (i = 0; i < ei_len; ++i) {
2287 * orig_jinfo contains the original IL exception info saved by the AOT
2288 * compiler, we have to combine that with the information produced by LLVM
2290 /* The type_info entries contain IL clause indexes */
2291 int clause_index = read32 (type_info [i]);
2292 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2293 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2295 g_assert (clause_index < num_clauses);
2296 jei->flags = orig_jei->flags;
2297 jei->data.catch_class = orig_jei->data.catch_class;
2299 jei->try_start = ei [i].try_start;
2300 jei->try_end = ei [i].try_end;
2301 jei->handler_start = ei [i].handler_start;
2303 /* Make sure we transition to thumb when a handler starts */
2304 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2305 jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2308 /* See exception_cb () in mini-llvm.c as to why this is needed */
2310 for (i = 0; i < ei_len; ++i) {
2311 gint32 cindex1 = read32 (type_info [i]);
2314 for (l = nesting [cindex1]; l; l = l->next) {
2315 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2317 for (j = 0; j < ei_len; ++j) {
2318 gint32 cindex2 = read32 (type_info [j]);
2320 if (cindex2 == nesting_cindex) {
2322 * The try interval comes from the nested clause, everything else from the
2325 memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2326 jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2327 jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2333 g_assert (nindex == ei_len + nested_len);
2339 alloc0_jit_info_data (MonoDomain *domain, int size, gboolean async_context)
2343 if (async_context) {
2344 res = mono_domain_alloc0_lock_free (domain, size);
2345 InterlockedExchangeAdd (&async_jit_info_size, size);
2347 res = mono_domain_alloc0 (domain, size);
2353 * LOCKING: Acquires the domain lock.
2354 * In async context, this is async safe.
2357 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
2358 MonoMethod *method, guint8* ex_info, guint8 *addr,
2359 guint8 *code, guint32 code_len)
2361 int i, buf_len, num_clauses, len;
2363 guint used_int_regs, flags;
2364 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2365 gboolean from_llvm, has_gc_map;
2367 int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2368 int this_reg = 0, this_offset = 0;
2371 /* Load the method info from the AOT file */
2372 async = mono_thread_info_is_async_context ();
2375 flags = decode_value (p, &p);
2376 has_generic_jit_info = (flags & 1) != 0;
2377 has_dwarf_unwind_info = (flags & 2) != 0;
2378 has_clauses = (flags & 4) != 0;
2379 has_seq_points = (flags & 8) != 0;
2380 from_llvm = (flags & 16) != 0;
2381 has_try_block_holes = (flags & 32) != 0;
2382 has_gc_map = (flags & 64) != 0;
2383 has_arch_eh_jit_info = (flags & 128) != 0;
2385 if (has_dwarf_unwind_info) {
2388 offset = decode_value (p, &p);
2389 g_assert (offset < (1 << 30));
2390 used_int_regs = offset;
2392 used_int_regs = decode_value (p, &p);
2394 if (has_generic_jit_info)
2395 generic_info_size = sizeof (MonoGenericJitInfo);
2397 generic_info_size = 0;
2399 if (has_try_block_holes) {
2400 num_holes = decode_value (p, &p);
2401 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2403 num_holes = try_holes_info_size = 0;
2405 /* Exception table */
2407 num_clauses = decode_value (p, &p);
2410 if (has_arch_eh_jit_info)
2411 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2413 arch_eh_jit_info_size = 0;
2416 MonoJitExceptionInfo *clauses;
2423 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2426 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2427 nesting = g_new0 (GSList*, num_clauses);
2429 for (i = 0; i < num_clauses; ++i) {
2430 MonoJitExceptionInfo *ei = &clauses [i];
2432 ei->flags = decode_value (p, &p);
2434 if (decode_value (p, &p))
2435 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2437 /* Read the list of nesting clauses */
2439 int nesting_index = decode_value (p, &p);
2440 if (nesting_index == -1)
2442 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2446 jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size + arch_eh_jit_info_size, nesting, &this_reg, &this_offset);
2447 jinfo->from_llvm = 1;
2450 for (i = 0; i < num_clauses; ++i)
2451 g_slist_free (nesting [i]);
2454 len = MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size;
2455 jinfo = alloc0_jit_info_data (domain, len, async);
2456 jinfo->num_clauses = num_clauses;
2458 for (i = 0; i < jinfo->num_clauses; ++i) {
2459 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2461 ei->flags = decode_value (p, &p);
2463 ei->exvar_offset = decode_value (p, &p);
2465 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2466 ei->data.filter = code + decode_value (p, &p);
2468 int len = decode_value (p, &p);
2474 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2478 ei->try_start = code + decode_value (p, &p);
2479 ei->try_end = code + decode_value (p, &p);
2480 ei->handler_start = code + decode_value (p, &p);
2483 jinfo->code_size = code_len;
2484 jinfo->used_regs = used_int_regs;
2485 jinfo->d.method = method;
2486 jinfo->code_start = code;
2487 jinfo->domain_neutral = 0;
2488 jinfo->from_aot = 1;
2491 if (has_try_block_holes) {
2492 MonoTryBlockHoleTableJitInfo *table;
2494 jinfo->has_try_block_holes = 1;
2496 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2499 table->num_holes = (guint16)num_holes;
2500 for (i = 0; i < num_holes; ++i) {
2501 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2502 hole->clause = decode_value (p, &p);
2503 hole->length = decode_value (p, &p);
2504 hole->offset = decode_value (p, &p);
2508 if (has_arch_eh_jit_info) {
2509 MonoArchEHJitInfo *eh_info;
2511 jinfo->has_arch_eh_info = 1;
2513 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2514 eh_info->stack_size = decode_value (p, &p);
2518 /* The rest is not needed in async mode */
2519 jinfo->async = TRUE;
2520 jinfo->d.aot_info = amodule;
2525 if (has_generic_jit_info) {
2526 MonoGenericJitInfo *gi;
2529 jinfo->has_generic_jit_info = 1;
2531 gi = mono_jit_info_get_generic_jit_info (jinfo);
2534 gi->nlocs = decode_value (p, &p);
2536 gi->locations = alloc0_jit_info_data (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
2537 for (i = 0; i < gi->nlocs; ++i) {
2538 MonoDwarfLocListEntry *entry = &gi->locations [i];
2540 entry->is_reg = decode_value (p, &p);
2541 entry->reg = decode_value (p, &p);
2543 entry->offset = decode_value (p, &p);
2545 entry->from = decode_value (p, &p);
2546 entry->to = decode_value (p, &p);
2550 gi->has_this = this_reg != -1;
2551 gi->this_reg = this_reg;
2552 gi->this_offset = this_offset;
2554 gi->has_this = decode_value (p, &p);
2555 gi->this_reg = decode_value (p, &p);
2556 gi->this_offset = decode_value (p, &p);
2560 len = decode_value (p, &p);
2564 jinfo->d.method = decode_resolve_method_ref (amodule, p, &p);
2566 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2567 if (decode_value (p, &p)) {
2570 MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
2572 n = decode_value (p, &p);
2574 gsctx->var_is_vt = alloc0_jit_info_data (domain, sizeof (gboolean) * n, async);
2575 for (i = 0; i < n; ++i)
2576 gsctx->var_is_vt [i] = decode_value (p, &p);
2578 n = decode_value (p, &p);
2580 gsctx->mvar_is_vt = alloc0_jit_info_data (domain, sizeof (gboolean) * n, async);
2581 for (i = 0; i < n; ++i)
2582 gsctx->mvar_is_vt [i] = decode_value (p, &p);
2587 if (method && has_seq_points) {
2588 MonoSeqPointInfo *seq_points;
2589 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2591 int len = decode_value (p, &p);
2593 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2594 seq_points->len = len;
2595 last_il_offset = last_native_offset = 0;
2596 for (i = 0; i < len; ++i) {
2597 SeqPoint *sp = &seq_points->seq_points [i];
2598 il_offset = last_il_offset + decode_value (p, &p);
2599 native_offset = last_native_offset + decode_value (p, &p);
2601 sp->il_offset = il_offset;
2602 sp->native_offset = native_offset;
2604 sp->flags = decode_value (p, &p);
2605 sp->next_len = decode_value (p, &p);
2606 sp->next = g_new (int, sp->next_len);
2607 for (j = 0; j < sp->next_len; ++j)
2608 sp->next [j] = decode_value (p, &p);
2610 last_il_offset = il_offset;
2611 last_native_offset = native_offset;
2614 mono_domain_lock (domain);
2615 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2616 mono_domain_unlock (domain);
2619 /* Load debug info */
2620 buf_len = decode_value (p, &p);
2622 mono_debug_add_aot_method (domain, method, code, p, buf_len);
2626 int map_size = decode_value (p, &p);
2627 /* The GC map requires 4 bytes of alignment */
2628 while ((guint64)(gsize)p % 4)
2634 if (amodule != jinfo->d.method->klass->image->aot_module) {
2637 ji_to_amodule = g_hash_table_new (NULL, NULL);
2638 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2646 * mono_aot_get_unwind_info:
2648 * Return a pointer to the DWARF unwind info belonging to JI.
2651 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2653 MonoAotModule *amodule;
2655 guint8 *code = ji->code_start;
2658 amodule = ji->d.aot_info;
2660 amodule = jinfo_get_method (ji)->klass->image->aot_module;
2662 g_assert (ji->from_aot);
2664 if (!(code >= amodule->code && code <= amodule->code_end)) {
2665 /* ji belongs to a different aot module than amodule */
2667 g_assert (ji_to_amodule);
2668 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2670 g_assert (code >= amodule->code && code <= amodule->code_end);
2674 p = amodule->unwind_info + ji->used_regs;
2675 *unwind_info_len = decode_value (p, &p);
2679 static G_GNUC_UNUSED int
2680 compare_ints (const void *a, const void *b)
2682 return *(gint32*)a - *(gint32*)b;
2686 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2688 int mid = (lo + hi) / 2;
2695 for (i = lo; i < hi; ++i)
2696 if (array [(i * 2)] > array [(i * 2) + 2])
2699 /* Already sorted */
2703 msort_code_offsets_internal (array, lo, mid, scratch);
2704 msort_code_offsets_internal (array, mid + 1, hi, scratch);
2706 if (array [mid * 2] < array [(mid + 1) * 2])
2712 for (i = lo; i <= hi; i ++) {
2713 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2714 scratch [(i * 2)] = array [t_lo * 2];
2715 scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2718 scratch [(i * 2)] = array [t_hi * 2];
2719 scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2723 for (i = lo; i <= hi; ++i) {
2724 array [(i * 2)] = scratch [i * 2];
2725 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2730 msort_code_offsets (gint32 *array, int len)
2734 scratch = g_new (gint32, len * 2);
2735 msort_code_offsets_internal (array, 0, len - 1, scratch);
2740 * mono_aot_find_jit_info:
2742 * In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
2743 * to the jit info tables.
2744 * FIXME: Large sizes in the lock free allocator
2747 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2749 int pos, left, right, offset, offset1, offset2, code_len;
2750 int method_index, table_len;
2752 MonoAotModule *amodule = image->aot_module;
2753 MonoMethod *method = NULL;
2755 guint8 *code, *ex_info, *p;
2757 int nmethods = amodule->info.nmethods;
2758 gint32 *code_offsets;
2765 if (domain != mono_get_root_domain ())
2769 async = mono_thread_info_is_async_context ();
2771 offset = (guint8*)addr - amodule->code;
2773 /* Compute a sorted table mapping code offsets to method indexes. */
2774 if (!amodule->sorted_code_offsets) {
2776 code_offsets = g_new0 (gint32, nmethods * 2);
2778 for (i = 0; i < nmethods; ++i) {
2779 /* Skip the -1 entries to speed up sorting */
2780 if (amodule->code_offsets [i] == 0xffffffff)
2782 code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2783 code_offsets [(offsets_len *2) + 1] = i;
2786 /* Use a merge sort as this is mostly sorted */
2787 msort_code_offsets (code_offsets, offsets_len);
2788 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2789 for (i = 0; i < offsets_len -1; ++i)
2790 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2792 amodule->sorted_code_offsets_len = offsets_len;
2793 mono_memory_barrier ();
2794 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2795 /* Somebody got in before us */
2796 g_free (code_offsets);
2799 code_offsets = amodule->sorted_code_offsets;
2800 offsets_len = amodule->sorted_code_offsets_len;
2802 if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
2805 /* Binary search in the sorted_code_offsets table */
2807 right = offsets_len;
2809 pos = (left + right) / 2;
2811 offset1 = code_offsets [(pos * 2)];
2812 if (pos + 1 == offsets_len)
2813 offset2 = amodule->code_end - amodule->code;
2815 offset2 = code_offsets [(pos + 1) * 2];
2817 if (offset < offset1)
2819 else if (offset >= offset2)
2825 g_assert (offset >= code_offsets [(pos * 2)]);
2826 if (pos + 1 < offsets_len)
2827 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2828 method_index = code_offsets [(pos * 2) + 1];
2830 /* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
2832 JitInfoMap *table = amodule->async_jit_info_table;
2836 len = table [0].method_index;
2837 for (i = 1; i < len; ++i) {
2838 if (table [i].method_index == method_index)
2839 return table [i].jinfo;
2844 code = &amodule->code [amodule->code_offsets [method_index]];
2845 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2847 if (pos == offsets_len - 1)
2848 code_len = amodule->code_end - code;
2850 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2852 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2854 /* Might be a wrapper/extra method */
2856 if (amodule->extra_methods) {
2858 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2865 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2867 * This is hit for extra methods which are called directly, so they are
2868 * not in amodule->extra_methods.
2870 table_len = amodule->extra_method_info_offsets [0];
2871 table = amodule->extra_method_info_offsets + 1;
2878 pos = ((left + right) / 2);
2880 g_assert (pos < table_len);
2882 if (table [pos * 2] < method_index)
2884 else if (table [pos * 2] > method_index)
2890 p = amodule->blob + table [(pos * 2) + 1];
2891 method = decode_resolve_method_ref (amodule, p, &p);
2893 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
2896 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2897 method = mono_get_method (image, token, NULL);
2904 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2906 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2908 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2909 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2911 /* Add it to the normal JitInfo tables */
2913 JitInfoMap *old_table, *new_table;
2917 * Use a simple inmutable table with linear search to cache async jit info entries.
2918 * This assumes that the number of entries is small.
2921 /* Copy the table, adding a new entry at the end */
2922 old_table = amodule->async_jit_info_table;
2924 len = old_table[0].method_index;
2927 new_table = alloc0_jit_info_data (domain, (len + 1) * sizeof (JitInfoMap), async);
2929 memcpy (new_table, old_table, len * sizeof (JitInfoMap));
2930 new_table [0].method_index = len + 1;
2931 new_table [len].method_index = method_index;
2932 new_table [len].jinfo = jinfo;
2934 mono_memory_barrier ();
2935 if (InterlockedCompareExchangePointer ((gpointer)&amodule->async_jit_info_table, new_table, old_table) == old_table)
2939 mono_jit_info_table_add (domain, jinfo);
2946 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2954 case MONO_PATCH_INFO_METHOD:
2955 case MONO_PATCH_INFO_METHOD_JUMP:
2956 case MONO_PATCH_INFO_ICALL_ADDR:
2957 case MONO_PATCH_INFO_METHOD_RGCTX:
2958 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
2962 res = decode_method_ref (aot_module, &ref, p, &p);
2966 if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
2967 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2968 ji->type = MONO_PATCH_INFO_ABS;
2972 ji->data.method = ref.method;
2974 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2975 g_assert (ji->data.method);
2976 mono_class_init (ji->data.method->klass);
2980 case MONO_PATCH_INFO_INTERNAL_METHOD:
2981 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2982 guint32 len = decode_value (p, &p);
2984 ji->data.name = (char*)p;
2988 case MONO_PATCH_INFO_METHODCONST:
2990 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2991 if (!ji->data.method)
2994 case MONO_PATCH_INFO_VTABLE:
2995 case MONO_PATCH_INFO_CLASS:
2996 case MONO_PATCH_INFO_IID:
2997 case MONO_PATCH_INFO_ADJUSTED_IID:
2998 case MONO_PATCH_INFO_CLASS_INIT:
3000 ji->data.klass = decode_klass_ref (aot_module, p, &p);
3001 if (!ji->data.klass)
3004 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3005 ji->data.del_tramp = mono_mempool_alloc0 (mp, sizeof (MonoClassMethodPair));
3006 ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p);
3007 if (!ji->data.del_tramp->klass)
3009 if (decode_value (p, &p)) {
3010 ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
3011 if (!ji->data.del_tramp->method)
3015 case MONO_PATCH_INFO_IMAGE:
3016 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
3017 if (!ji->data.image)
3020 case MONO_PATCH_INFO_FIELD:
3021 case MONO_PATCH_INFO_SFLDA:
3023 ji->data.field = decode_field_info (aot_module, p, &p);
3024 if (!ji->data.field)
3027 case MONO_PATCH_INFO_SWITCH:
3028 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
3029 ji->data.table->table_size = decode_value (p, &p);
3030 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
3031 ji->data.table->table = (MonoBasicBlock**)table;
3032 for (i = 0; i < ji->data.table->table_size; i++)
3033 table [i] = (gpointer)(gssize)decode_value (p, &p);
3035 case MONO_PATCH_INFO_R4: {
3038 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
3039 val = decode_value (p, &p);
3040 *(float*)ji->data.target = *(float*)&val;
3043 case MONO_PATCH_INFO_R8: {
3047 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
3049 val [0] = decode_value (p, &p);
3050 val [1] = decode_value (p, &p);
3051 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
3052 *(double*)ji->data.target = *(double*)&v;
3055 case MONO_PATCH_INFO_LDSTR:
3056 image = load_image (aot_module, decode_value (p, &p), TRUE);
3059 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
3061 case MONO_PATCH_INFO_RVA:
3062 case MONO_PATCH_INFO_DECLSEC:
3063 case MONO_PATCH_INFO_LDTOKEN:
3064 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3066 image = load_image (aot_module, decode_value (p, &p), TRUE);
3069 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
3071 ji->data.token->has_context = decode_value (p, &p);
3072 if (ji->data.token->has_context) {
3073 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
3078 case MONO_PATCH_INFO_EXC_NAME:
3079 ji->data.klass = decode_klass_ref (aot_module, p, &p);
3080 if (!ji->data.klass)
3082 ji->data.name = ji->data.klass->name;
3084 case MONO_PATCH_INFO_METHOD_REL:
3085 ji->data.offset = decode_value (p, &p);
3087 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3088 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3089 case MONO_PATCH_INFO_MONITOR_ENTER:
3090 case MONO_PATCH_INFO_MONITOR_EXIT:
3091 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3092 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3093 case MONO_PATCH_INFO_JIT_TLS_ID:
3095 case MONO_PATCH_INFO_RGCTX_FETCH: {
3097 MonoJumpInfoRgctxEntry *entry;
3098 guint32 offset, val;
3101 offset = decode_value (p, &p);
3102 val = decode_value (p, &p);
3104 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3105 p2 = aot_module->blob + offset;
3106 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
3107 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
3108 entry->info_type = (val >> 1) & 0xff;
3109 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3110 entry->data->type = (val >> 9) & 0xff;
3112 res = decode_patch (aot_module, mp, entry->data, p, &p);
3115 ji->data.rgctx_entry = entry;
3118 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3120 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
3121 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
3123 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
3124 imt_tramp->vt_offset = decode_value (p, &p);
3126 ji->data.imt_tramp = imt_tramp;
3129 case MONO_PATCH_INFO_SIGNATURE:
3130 ji->data.target = decode_signature (aot_module, p, &p);
3132 case MONO_PATCH_INFO_TLS_OFFSET:
3133 ji->data.target = GINT_TO_POINTER (decode_value (p, &p));
3135 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
3136 MonoJumpInfoGSharedVtCall *info = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
3137 info->sig = decode_signature (aot_module, p, &p);
3138 g_assert (info->sig);
3139 info->method = decode_resolve_method_ref (aot_module, p, &p);
3140 g_assert (info->method);
3142 ji->data.target = info;
3145 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
3146 MonoGSharedVtMethodInfo *info = mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
3149 info->method = decode_resolve_method_ref (aot_module, p, &p);
3150 g_assert (info->method);
3151 info->num_entries = decode_value (p, &p);
3152 info->count_entries = info->num_entries;
3153 info->entries = mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
3154 for (i = 0; i < info->num_entries; ++i) {
3155 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
3157 template->info_type = decode_value (p, &p);
3158 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
3159 case MONO_PATCH_INFO_CLASS: {
3160 MonoClass *klass = decode_klass_ref (aot_module, p, &p);
3163 template->data = &klass->byval_arg;
3166 case MONO_PATCH_INFO_FIELD:
3167 template->data = decode_field_info (aot_module, p, &p);
3168 if (!template->data)
3172 g_assert_not_reached ();
3176 ji->data.target = info;
3180 g_warning ("unhandled type %d", ji->type);
3181 g_assert_not_reached ();
3192 static MonoJumpInfo*
3193 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
3194 guint32 **got_slots,
3195 guint8 *buf, guint8 **endbuf)
3197 MonoJumpInfo *patches;
3203 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
3205 *got_slots = g_malloc (sizeof (guint32) * n_patches);
3207 for (pindex = 0; pindex < n_patches; ++pindex) {
3208 MonoJumpInfo *ji = &patches [pindex];
3213 got_offset = decode_value (p, &p);
3215 if (aot_module->got [got_offset]) {
3216 /* Already loaded */
3217 //printf ("HIT!\n");
3219 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
3221 ji->type = decode_value (shared_p, &shared_p);
3223 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
3228 (*got_slots) [pindex] = got_offset;
3235 g_free (*got_slots);
3242 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
3245 * Jump addresses cannot be patched by the trampoline code since it
3246 * does not have access to the caller's address. Instead, we collect
3247 * the addresses of the GOT slots pointing to a method, and patch
3248 * them after the method has been compiled.
3250 MonoJitDomainInfo *info = domain_jit_info (domain);
3253 mono_domain_lock (domain);
3254 if (!info->jump_target_got_slot_hash)
3255 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
3256 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
3257 list = g_slist_prepend (list, got_slot);
3258 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
3259 mono_domain_unlock (domain);
3265 * Load the method identified by METHOD_INDEX from the AOT image. Return a
3266 * pointer to the native code of the method, or NULL if not found.
3267 * METHOD might not be set if the caller only has the image/token info.
3270 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
3273 gboolean from_plt = method == NULL;
3275 int i, pindex, n_patches, used_strings;
3276 gboolean keep_patches = TRUE;
3278 MonoJitInfo *jinfo = NULL;
3279 guint8 *code, *info;
3281 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
3284 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
3285 /* Non shared AOT code can't be used in other appdomains */
3288 if (amodule->out_of_date)
3291 if (amodule->code_offsets [method_index] == 0xffffffff) {
3292 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3296 method = mono_get_method (image, token, NULL);
3297 full_name = mono_method_full_name (method, TRUE);
3298 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3304 code = &amodule->code [amodule->code_offsets [method_index]];
3306 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
3308 if (amodule->thumb_end && code < amodule->thumb_end && ((amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) == 0)) {
3309 /* Convert this into a thumb address */
3310 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
3311 code = &amodule->code [amodule->code_offsets [method_index] + 1];
3315 if (!amodule->methods_loaded)
3316 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
3319 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
3322 if (mono_last_aot_method != -1) {
3323 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
3325 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
3327 method = mono_get_method (image, token, NULL);
3329 char *name = mono_method_full_name (method, TRUE);
3330 printf ("LAST AOT METHOD: %s.\n", name);
3333 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
3341 klass = method->klass;
3342 decode_klass_ref (amodule, p, &p);
3344 klass = decode_klass_ref (amodule, p, &p);
3347 if (amodule->info.opts & MONO_OPT_SHARED)
3348 used_strings = decode_value (p, &p);
3352 for (i = 0; i < used_strings; i++) {
3353 guint token = decode_value (p, &p);
3354 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
3357 if (amodule->info.opts & MONO_OPT_SHARED)
3358 keep_patches = FALSE;
3360 n_patches = decode_value (p, &p);
3362 keep_patches = FALSE;
3365 MonoJumpInfo *patches;
3371 mp = mono_mempool_new ();
3373 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3374 if (patches == NULL)
3377 for (pindex = 0; pindex < n_patches; ++pindex) {
3378 MonoJumpInfo *ji = &patches [pindex];
3380 if (!amodule->got [got_slots [pindex]]) {
3381 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
3382 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3383 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
3384 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3385 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
3387 ji->type = MONO_PATCH_INFO_NONE;
3393 mono_mempool_destroy (mp);
3396 if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
3397 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3399 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3403 method = mono_get_method (image, token, NULL);
3405 full_name = mono_method_full_name (method, TRUE);
3408 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3410 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
3416 InterlockedIncrement (&mono_jit_stats.methods_aot);
3418 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
3422 if (method && method->wrapper_type)
3423 g_hash_table_insert (amodule->method_to_code, method, code);
3427 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3431 method = mono_get_method (image, token, NULL);
3434 mono_profiler_method_jit (method);
3435 jinfo = mono_jit_info_table_find (domain, (char*)code);
3437 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3440 if (from_plt && klass && !klass->generic_container)
3441 mono_runtime_class_init (mono_class_vtable (domain, klass));
3446 /* FIXME: The space in domain->mp is wasted */
3447 if (amodule->info.opts & MONO_OPT_SHARED)
3448 /* No need to cache patches */
3449 mono_mempool_destroy (mp);
3458 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
3460 guint32 table_size, entry_size, hash;
3461 guint32 *table, *entry;
3463 static guint32 n_extra_decodes;
3465 if (!amodule || amodule->out_of_date)
3468 table_size = amodule->extra_method_table [0];
3469 table = amodule->extra_method_table + 1;
3472 hash = mono_aot_method_hash (method) % table_size;
3474 entry = &table [hash * entry_size];
3481 guint32 key = entry [0];
3482 guint32 value = entry [1];
3483 guint32 next = entry [entry_size - 1];
3487 p = amodule->blob + key;
3491 if (!amodule->method_ref_to_method)
3492 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3493 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3496 m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3499 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3508 /* Special case: wrappers of shared generic methods */
3509 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3510 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3511 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3512 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3514 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3520 /* Methods decoded needlessly */
3522 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3527 entry = &table [next * entry_size];
3536 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3538 g_ptr_array_add ((GPtrArray*)user_data, value);
3542 * find_extra_method:
3544 * Try finding METHOD in the extra_method table in all AOT images.
3545 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3546 * module where the method was found.
3549 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3555 /* Try the method's module first */
3556 *out_amodule = method->klass->image->aot_module;
3557 index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
3558 if (index != 0xffffff)
3562 * Try all other modules.
3563 * This is needed because generic instances klass->image points to the image
3564 * containing the generic definition, but the native code is generated to the
3565 * AOT image which contains the reference.
3568 /* Make a copy to avoid doing the search inside the aot lock */
3569 modules = g_ptr_array_new ();
3571 g_hash_table_foreach (aot_modules, add_module_cb, modules);
3575 for (i = 0; i < modules->len; ++i) {
3576 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3578 if (amodule != method->klass->image->aot_module)
3579 index = find_extra_method_in_amodule (amodule, method);
3580 if (index != 0xffffff) {
3581 *out_amodule = amodule;
3586 g_ptr_array_free (modules, TRUE);
3592 * mono_aot_get_method:
3594 * Return a pointer to the AOTed native code for METHOD if it can be found,
3596 * On platforms with function pointers, this doesn't return a function pointer.
3599 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3601 MonoClass *klass = method->klass;
3602 guint32 method_index;
3603 MonoAotModule *amodule = klass->image->aot_module;
3609 if (amodule->out_of_date)
3612 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3613 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3614 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3615 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3619 * Use the original method instead of its invoke-with-check wrapper.
3620 * This is not a problem when using full-aot, since it doesn't support
3623 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3624 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3626 g_assert (klass->inited);
3628 /* Find method index */
3629 method_index = 0xffffff;
3630 if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
3632 * For generic methods, we store the fully shared instance in place of the
3635 method = mono_method_get_declaring_generic_method (method);
3636 method_index = mono_metadata_token_index (method->token) - 1;
3637 } else if (method->is_inflated || !method->token) {
3638 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3640 code = g_hash_table_lookup (amodule->method_to_code, method);
3645 method_index = find_extra_method (method, &amodule);
3647 * Special case the ICollection<T> wrappers for arrays, as they cannot
3648 * be statically enumerated, and each wrapper ends up calling the same
3651 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3652 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3654 code = mono_aot_get_method (domain, m);
3660 * Special case Array.GetGenericValueImpl which is a generic icall.
3661 * Generic sharing currently can't handle it, but the icall returns data using
3662 * an out parameter, so the managed-to-native wrappers can share the same code.
3664 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3666 MonoGenericContext ctx;
3667 MonoType *args [16];
3669 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3670 /* Avoid recursion */
3673 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3676 memset (&ctx, 0, sizeof (ctx));
3677 args [0] = &mono_defaults.object_class->byval_arg;
3678 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3680 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3683 * Get the code for the <object> instantiation which should be emitted into
3684 * the mscorlib aot image by the AOT compiler.
3686 code = mono_aot_get_method (domain, m);
3691 /* Same for CompareExchange<T> and Exchange<T> */
3692 /* Same for Volatile.Read<T>/Write<T> */
3693 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib &&
3694 ((!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && (!strcmp (method->name, "CompareExchange") || !strcmp (method->name, "Exchange")) && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1])) ||
3695 (!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Volatile") && (!strcmp (method->name, "Read") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->ret))) ||
3696 (!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Volatile") && (!strcmp (method->name, "Write") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1]))))) {
3698 MonoGenericContext ctx;
3699 MonoType *args [16];
3700 gpointer iter = NULL;
3702 while ((m = mono_class_get_methods (method->klass, &iter))) {
3703 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3708 memset (&ctx, 0, sizeof (ctx));
3709 args [0] = &mono_defaults.object_class->byval_arg;
3710 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3712 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3714 /* Avoid recursion */
3719 * Get the code for the <object> instantiation which should be emitted into
3720 * the mscorlib aot image by the AOT compiler.
3722 code = mono_aot_get_method (domain, m);
3727 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
3728 /* Partial sharing */
3731 shared = mini_get_shared_method (method);
3732 method_index = find_extra_method (shared, &amodule);
3733 if (method_index != 0xffffff)
3737 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
3739 /* Use the all-vt shared method since this is what was AOTed */
3740 method_index = find_extra_method (mini_get_shared_method_full (method, TRUE, TRUE), &amodule);
3741 if (method_index != 0xffffff)
3742 method = mini_get_shared_method_full (method, TRUE, FALSE);
3745 if (method_index == 0xffffff) {
3746 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3749 full_name = mono_method_full_name (method, TRUE);
3750 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3756 if (method_index == 0xffffff)
3759 /* Needed by find_jit_info */
3761 if (!amodule->extra_methods)
3762 amodule->extra_methods = g_hash_table_new (NULL, NULL);
3763 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3767 method_index = mono_metadata_token_index (method->token) - 1;
3770 return load_method (domain, amodule, klass->image, method, method->token, method_index);
3774 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3778 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3780 MonoAotModule *aot_module = image->aot_module;
3786 method_index = mono_metadata_token_index (token) - 1;
3788 return load_method (domain, aot_module, image, NULL, token, method_index);
3794 } IsGotEntryUserData;
3797 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3799 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3800 MonoAotModule *aot_module = (MonoAotModule*)value;
3802 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3807 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3809 IsGotEntryUserData user_data;
3814 user_data.addr = addr;
3815 user_data.res = FALSE;
3817 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3820 return user_data.res;
3825 MonoAotModule *module;
3826 } FindAotModuleUserData;
3829 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3831 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3832 MonoAotModule *aot_module = (MonoAotModule*)value;
3834 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3835 data->module = aot_module;
3838 static inline MonoAotModule*
3839 find_aot_module (guint8 *code)
3841 FindAotModuleUserData user_data;
3846 /* Reading these need no locking */
3847 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3850 user_data.addr = code;
3851 user_data.module = NULL;
3854 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3857 return user_data.module;
3861 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3864 * Since AOT code is only used in the root domain,
3865 * mono_domain_get () != mono_get_root_domain () means the calling method
3866 * is AppDomain:InvokeInDomain, so this is the same check as in
3867 * mono_method_same_domain () but without loading the metadata for the method.
3869 if (mono_domain_get () == mono_get_root_domain ())
3870 mono_arch_patch_plt_entry (code, got, regs, addr);
3874 * mono_aot_plt_resolve:
3876 * This function is called by the entries in the PLT to resolve the actual method that
3877 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3878 * Returns NULL if the something cannot be loaded.
3881 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3883 #ifdef MONO_ARCH_AOT_SUPPORTED
3884 guint8 *p, *target, *plt_entry;
3886 MonoAotModule *module = (MonoAotModule*)aot_module;
3887 gboolean res, no_ftnptr = FALSE;
3889 gboolean using_gsharedvt = FALSE;
3891 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3893 p = &module->blob [plt_info_offset];
3895 ji.type = decode_value (p, &p);
3897 mp = mono_mempool_new_size (512);
3898 res = decode_patch (module, mp, &ji, p, &p);
3901 mono_mempool_destroy (mp);
3905 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3906 using_gsharedvt = TRUE;
3910 * Avoid calling resolve_patch_target in the full-aot case if possible, since
3911 * it would create a trampoline, and we don't need that.
3912 * We could do this only if the method does not need the special handling
3913 * in mono_magic_trampoline ().
3915 if (mono_aot_only && ji.type == MONO_PATCH_INFO_METHOD && !ji.data.method->is_generic && !mono_method_check_context_used (ji.data.method) && !(ji.data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) &&
3916 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
3917 target = mono_jit_compile_method (ji.data.method);
3920 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3924 * The trampoline expects us to return a function descriptor on platforms which use
3925 * it, but resolve_patch_target returns a direct function pointer for some type of
3926 * patches, so have to translate between the two.
3927 * FIXME: Clean this up, but how ?
3929 if (ji.type == MONO_PATCH_INFO_ABS || ji.type == MONO_PATCH_INFO_INTERNAL_METHOD || ji.type == MONO_PATCH_INFO_CLASS_INIT || ji.type == MONO_PATCH_INFO_ICALL_ADDR || ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR || ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
3930 /* These should already have a function descriptor */
3931 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3932 /* Our function descriptors have a 0 environment, gcc created ones don't */
3933 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3934 g_assert (((gpointer*)target) [2] == 0);
3937 } else if (!no_ftnptr) {
3938 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3939 g_assert (((gpointer*)target) [2] != 0);
3941 target = mono_create_ftnptr (mono_domain_get (), target);
3944 mono_mempool_destroy (mp);
3946 /* Patch the PLT entry with target which might be the actual method not a trampoline */
3947 plt_entry = mono_aot_get_plt_entry (code);
3948 g_assert (plt_entry);
3949 mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3953 g_assert_not_reached ();
3961 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
3962 * method in the module is loaded to avoid committing memory by writing to it.
3963 * LOCKING: Assumes the AOT lock is held.
3966 init_plt (MonoAotModule *amodule)
3971 if (amodule->plt_inited)
3974 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3977 * Initialize the PLT entries in the GOT to point to the default targets.
3980 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3981 for (i = 1; i < amodule->info.plt_size; ++i)
3982 /* All the default entries point to the AOT trampoline */
3983 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3985 amodule->plt_inited = TRUE;
3989 * mono_aot_get_plt_entry:
3991 * Return the address of the PLT entry called by the code at CODE if exists.
3994 mono_aot_get_plt_entry (guint8 *code)
3996 MonoAotModule *amodule = find_aot_module (code);
3997 guint8 *target = NULL;
4003 if (amodule->thumb_end && code < amodule->thumb_end) {
4004 return mono_arm_get_thumb_plt_entry (code);
4008 #ifdef MONO_ARCH_AOT_SUPPORTED
4009 target = mono_arch_get_call_target (code);
4011 g_assert_not_reached ();
4015 while (target != NULL) {
4016 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
4019 // Add 4 since mono_arch_get_call_target assumes we're passing
4020 // the instruction after the actual branch instruction.
4021 target = mono_arch_get_call_target (target + 4);
4026 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
4034 * mono_aot_get_plt_info_offset:
4036 * Return the PLT info offset belonging to the plt entry called by CODE.
4039 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4041 guint8 *plt_entry = mono_aot_get_plt_entry (code);
4043 g_assert (plt_entry);
4045 /* The offset is embedded inside the code after the plt entry */
4046 #ifdef MONO_ARCH_AOT_SUPPORTED
4047 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
4049 g_assert_not_reached ();
4055 mono_create_ftnptr_malloc (guint8 *code)
4057 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4058 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
4060 ftnptr->code = code;
4071 * mono_aot_register_jit_icall:
4073 * Register a JIT icall which is called by trampolines in full-aot mode. This should
4074 * be called from mono_arch_init () during startup.
4077 mono_aot_register_jit_icall (const char *name, gpointer addr)
4079 /* No need for locking */
4080 if (!aot_jit_icall_hash)
4081 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
4082 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
4086 * load_function_full:
4088 * Load the function named NAME from the aot image.
4091 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
4095 int n_patches, pindex;
4098 guint32 info_offset;
4102 symbol = g_strdup_printf ("%s", name);
4103 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
4106 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
4108 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
4112 symbol = g_strdup_printf ("%s_p", name);
4113 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
4116 /* Nothing to patch */
4119 info_offset = *(guint32*)p;
4121 MonoTrampInfo *tinfo;
4122 guint32 code_size, uw_info_len, uw_offset;
4124 /* Construct a MonoTrampInfo from the data in the AOT image */
4126 p += sizeof (guint32);
4127 code_size = *(guint32*)p;
4128 p += sizeof (guint32);
4129 uw_offset = *(guint32*)p;
4130 uw_info = amodule->unwind_info + uw_offset;
4131 uw_info_len = decode_value (uw_info, &uw_info);
4133 tinfo = g_new0 (MonoTrampInfo, 1);
4135 tinfo->code_size = code_size;
4136 tinfo->uw_info = uw_info;
4137 tinfo->uw_info_len = uw_info_len;
4142 p = amodule->blob + info_offset;
4144 /* Similar to mono_aot_load_method () */
4146 n_patches = decode_value (p, &p);
4149 MonoJumpInfo *patches;
4152 mp = mono_mempool_new ();
4154 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
4157 for (pindex = 0; pindex < n_patches; ++pindex) {
4158 MonoJumpInfo *ji = &patches [pindex];
4161 if (amodule->got [got_slots [pindex]])
4165 * When this code is executed, the runtime may not be initalized yet, so
4166 * resolve the patch info by hand.
4168 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4169 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
4170 target = mono_get_lmf_addr;
4171 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
4172 target = mono_thread_force_interruption_checkpoint;
4173 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
4174 target = mono_exception_from_token;
4175 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
4176 target = mono_get_throw_exception ();
4177 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
4178 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
4179 target = (gpointer)mono_get_trampoline_func (tramp_type2);
4180 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
4181 /* atoll is needed because the the offset is unsigned */
4185 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
4186 g_assert (res == 1);
4187 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4188 target = mono_create_ftnptr_malloc (target);
4189 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
4190 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
4191 target = mono_create_ftnptr_malloc (target);
4192 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
4193 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
4194 target = mono_create_ftnptr_malloc (target);
4195 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
4196 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
4197 target = mono_create_ftnptr_malloc (target);
4198 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
4199 target = mono_thread_get_and_clear_pending_exception;
4200 } else if (strstr (ji->data.name, "generic_trampoline_")) {
4201 target = mono_aot_get_trampoline (ji->data.name);
4202 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
4203 /* Registered by mono_arch_init () */
4204 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
4206 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
4207 g_assert_not_reached ();
4211 /* Hopefully the code doesn't have patches which need method or
4214 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
4218 amodule->got [got_slots [pindex]] = target;
4223 mono_mempool_destroy (mp);
4230 load_function (MonoAotModule *amodule, const char *name)
4232 return load_function_full (amodule, name, NULL);
4236 * Return the trampoline identified by NAME from the mscorlib AOT file.
4237 * On ppc64, this returns a function descriptor.
4240 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
4243 MonoAotModule *amodule;
4245 image = mono_defaults.corlib;
4248 amodule = image->aot_module;
4251 return mono_create_ftnptr_malloc (load_function_full (amodule, name, out_tinfo));
4255 mono_aot_get_trampoline (const char *name)
4257 return mono_aot_get_trampoline_full (name, NULL);
4261 #include <mach/mach.h>
4263 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
4264 /* these sizes are for ARM code, parametrize if porting to other architectures (see arch_emit_specific_trampoline_pages)
4265 * trampoline size is assumed to be 8 bytes below as well (8 is the minimum for 32 bit archs, since we need to store
4266 * two pointers for trampoline in the data page).
4267 * the minimum for the common code must be at least sizeof(TrampolinePage), since we store the page info at the
4268 * beginning of the data page.
4270 static const int trampolines_pages_code_offsets [MONO_AOT_TRAMP_NUM] = {16, 16, 72, 16};
4272 static unsigned char*
4273 get_new_trampoline_from_page (int tramp_type)
4275 MonoAotModule *amodule;
4277 TrampolinePage *page;
4280 vm_address_t addr, taddr;
4282 vm_prot_t prot, max_prot;
4283 int psize, specific_trampoline_size;
4284 unsigned char *code;
4286 specific_trampoline_size = 2 * sizeof (gpointer);
4288 mono_aot_page_lock ();
4289 page = trampoline_pages [tramp_type];
4290 if (page && page->trampolines < page->trampolines_end) {
4291 code = page->trampolines;
4292 page->trampolines += specific_trampoline_size;
4293 mono_aot_page_unlock ();
4296 mono_aot_page_unlock ();
4297 psize = mono_pagesize ();
4298 /* the trampoline template page is in the mscorlib module */
4299 image = mono_defaults.corlib;
4302 amodule = image->aot_module;
4305 g_assert (amodule->info.tramp_page_size == psize);
4307 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
4308 tpage = load_function (amodule, "specific_trampolines_page");
4309 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
4310 tpage = load_function (amodule, "rgctx_trampolines_page");
4311 else if (tramp_type == MONO_AOT_TRAMP_IMT_THUNK)
4312 tpage = load_function (amodule, "imt_trampolines_page");
4313 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
4314 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
4316 g_error ("Incorrect tramp type for trampolines page");
4318 /*g_warning ("loaded trampolines page at %x", tpage);*/
4320 /* avoid the unlikely case of looping forever */
4323 while (page == NULL && count-- > 0) {
4325 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
4326 * while the second will contain the trampolines.
4328 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
4329 if (ret != KERN_SUCCESS) {
4330 g_error ("Cannot allocate memory for trampolines: %d", ret);
4333 /*g_warning ("allocated trampoline double page at %x", addr);*/
4334 /* replace the second page with a remapped trampoline page */
4335 taddr = addr + psize;
4336 vm_deallocate (mach_task_self (), taddr, psize);
4337 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
4338 if (ret != KERN_SUCCESS) {
4339 /* someone else got the page, try again */
4340 vm_deallocate (mach_task_self (), addr, psize);
4343 /*g_warning ("remapped trampoline page at %x", taddr);*/
4345 mono_aot_page_lock ();
4346 page = trampoline_pages [tramp_type];
4347 /* some other thread already allocated, so use that to avoid wasting memory */
4348 if (page && page->trampolines < page->trampolines_end) {
4349 code = page->trampolines;
4350 page->trampolines += specific_trampoline_size;
4351 mono_aot_page_unlock ();
4352 vm_deallocate (mach_task_self (), addr, psize);
4353 vm_deallocate (mach_task_self (), taddr, psize);
4356 page = (TrampolinePage*)addr;
4357 page->next = trampoline_pages [tramp_type];
4358 trampoline_pages [tramp_type] = page;
4359 page->trampolines = (void*)(taddr + trampolines_pages_code_offsets [tramp_type]);
4360 page->trampolines_end = (void*)(taddr + psize);
4361 code = page->trampolines;
4362 page->trampolines += 8;
4363 mono_aot_page_unlock ();
4366 g_error ("Cannot allocate more trampoline pages: %d", ret);
4371 static unsigned char*
4372 get_new_trampoline_from_page (int tramp_type)
4374 g_error ("Page trampolines not supported.");
4381 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
4386 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
4388 data = (gpointer*)((char*)code - mono_pagesize ());
4391 /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4397 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
4402 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
4404 data = (gpointer*)((char*)code - mono_pagesize ());
4407 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4413 get_new_imt_trampoline_from_page (gpointer arg)
4418 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT_THUNK);
4420 data = (gpointer*)((char*)code - mono_pagesize ());
4422 /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
4428 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
4433 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
4435 data = (gpointer*)((char*)code - mono_pagesize ());
4438 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4442 /* Return a given kind of trampoline */
4444 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
4446 MonoAotModule *amodule;
4447 int index, tramp_size;
4450 /* Currently, we keep all trampolines in the mscorlib AOT image */
4451 image = mono_defaults.corlib;
4456 amodule = image->aot_module;
4459 *out_amodule = amodule;
4462 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
4464 #define MONOTOUCH_TRAMPOLINES_ERROR ""
4466 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
4467 g_error ("Ran out of trampolines of type %d in '%s' (%d)%s\n",
4468 tramp_type, image->name, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
4470 index = amodule->trampoline_index [tramp_type] ++;
4474 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
4476 tramp_size = amodule->info.trampoline_size [tramp_type];
4479 *out_tramp_size = tramp_size;
4481 return amodule->trampolines [tramp_type] + (index * tramp_size);
4485 * Return a specific trampoline from the AOT file.
4488 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4490 MonoAotModule *amodule;
4491 guint32 got_offset, tramp_size;
4492 guint8 *code, *tramp;
4493 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
4494 static gboolean inited;
4495 static guint32 num_trampolines;
4501 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
4510 if (!generic_trampolines [tramp_type]) {
4513 symbol = mono_get_generic_trampoline_name (tramp_type);
4514 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
4518 tramp = generic_trampolines [tramp_type];
4521 if (USE_PAGE_TRAMPOLINES) {
4522 code = get_new_specific_trampoline_from_page (tramp, arg1);
4525 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
4527 amodule->got [got_offset] = tramp;
4528 amodule->got [got_offset + 1] = arg1;
4532 *code_len = tramp_size;
4538 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4540 MonoAotModule *amodule;
4544 if (USE_PAGE_TRAMPOLINES) {
4545 code = get_new_rgctx_trampoline_from_page (addr, ctx);
4547 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
4549 amodule->got [got_offset] = ctx;
4550 amodule->got [got_offset + 1] = addr;
4553 /* The caller expects an ftnptr */
4554 return mono_create_ftnptr (mono_domain_get (), code);
4558 mono_aot_get_unbox_trampoline (MonoMethod *method)
4560 guint32 method_index = mono_metadata_token_index (method->token) - 1;
4561 MonoAotModule *amodule;
4563 guint32 *ut, *ut_end, *entry;
4564 int low, high, entry_index;
4566 if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
4567 method_index = find_extra_method (method, &amodule);
4568 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4569 MonoMethod *shared = mini_get_shared_method_full (method, TRUE, TRUE);
4570 method_index = find_extra_method (shared, &amodule);
4572 g_assert (method_index != 0xffffff);
4574 amodule = method->klass->image->aot_module;
4578 ut = amodule->unbox_trampolines;
4579 ut_end = amodule->unbox_trampolines_end;
4581 /* Do a binary search in the sorted table */
4584 high = (ut_end - ut) / 2;
4585 while (low < high) {
4586 entry_index = (low + high) / 2;
4587 entry = &ut [(entry_index * 2)];
4588 if (entry [0] < method_index) {
4589 low = entry_index + 1;
4590 } else if (entry [0] > method_index) {
4593 if (amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES)
4594 code = get_arm_bl_target (entry + 1);
4596 code = amodule->code + entry [1];
4602 /* The caller expects an ftnptr */
4603 return mono_create_ftnptr (mono_domain_get (), code);
4607 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4611 MonoAotModule *amodule = mono_defaults.corlib->aot_module;
4612 guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
4613 static int count = 0;
4616 if (index >= amodule->info.num_rgctx_fetch_trampolines) {
4617 static gpointer addr;
4621 * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
4624 addr = load_function (amodule, "rgctx_fetch_trampoline_general");
4625 info = mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
4626 info [0] = GUINT_TO_POINTER (slot);
4627 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4628 code = mono_aot_get_static_rgctx_trampoline (info, addr);
4629 return mono_create_ftnptr (mono_domain_get (), code);
4632 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
4633 code = load_function (mono_defaults.corlib->aot_module, symbol);
4635 /* The caller expects an ftnptr */
4636 return mono_create_ftnptr (mono_domain_get (), code);
4640 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4645 int i, index, real_count;
4646 MonoAotModule *amodule;
4649 for (i = 0; i < count; ++i) {
4650 MonoIMTCheckItem *item = imt_entries [i];
4652 if (item->is_equals)
4656 /* Save the entries into an array */
4657 buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
4659 for (i = 0; i < count; ++i) {
4660 MonoIMTCheckItem *item = imt_entries [i];
4662 if (!item->is_equals)
4665 g_assert (item->key);
4667 buf [(index * 2)] = item->key;
4668 if (item->has_target_code) {
4669 gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
4670 *p = item->value.target_code;
4671 buf [(index * 2) + 1] = p;
4673 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
4677 buf [(index * 2)] = NULL;
4678 buf [(index * 2) + 1] = fail_tramp;
4680 if (USE_PAGE_TRAMPOLINES) {
4681 code = get_new_imt_trampoline_from_page (buf);
4683 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
4685 amodule->got [got_offset] = buf;
4692 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
4694 MonoAotModule *amodule;
4698 if (USE_PAGE_TRAMPOLINES) {
4699 code = get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
4701 code = get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
4703 amodule->got [got_offset] = arg;
4704 amodule->got [got_offset + 1] = addr;
4707 /* The caller expects an ftnptr */
4708 return mono_create_ftnptr (mono_domain_get (), code);
4712 * mono_aot_set_make_unreadable:
4714 * Set whenever to make all mmaped memory unreadable. In conjuction with a
4715 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
4718 mono_aot_set_make_unreadable (gboolean unreadable)
4722 make_unreadable = unreadable;
4724 if (make_unreadable && !inited) {
4725 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
4730 MonoAotModule *module;
4735 find_map (gpointer key, gpointer value, gpointer user_data)
4737 MonoAotModule *module = (MonoAotModule*)value;
4738 FindMapUserData *data = (FindMapUserData*)user_data;
4741 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4742 data->module = module;
4745 static MonoAotModule*
4746 find_module_for_addr (void *ptr)
4748 FindMapUserData data;
4750 if (!make_unreadable)
4754 data.ptr = (guint8*)ptr;
4757 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4764 * mono_aot_is_pagefault:
4766 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4767 * within memory allocated by this module.
4770 mono_aot_is_pagefault (void *ptr)
4772 if (!make_unreadable)
4776 * Not signal safe, but SIGSEGV's are synchronous, and
4777 * this is only turned on by a MONO_DEBUG option.
4779 return find_module_for_addr (ptr) != NULL;
4783 * mono_aot_handle_pagefault:
4785 * Handle a pagefault caused by an unreadable page by making it readable again.
4788 mono_aot_handle_pagefault (void *ptr)
4790 #ifndef PLATFORM_WIN32
4791 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
4795 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
4796 g_assert (res == 0);
4807 mono_aot_init (void)
4812 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
4818 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4824 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4830 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
4836 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
4842 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
4848 mono_aot_get_plt_entry (guint8 *code)
4854 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4860 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
4865 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
4871 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4873 g_assert_not_reached ();
4879 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4881 g_assert_not_reached ();
4886 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4888 g_assert_not_reached ();
4893 mono_aot_get_trampoline (const char *name)
4895 g_assert_not_reached ();
4900 mono_aot_get_unbox_trampoline (MonoMethod *method)
4902 g_assert_not_reached ();
4907 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4909 g_assert_not_reached ();
4914 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4916 g_assert_not_reached ();
4921 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
4923 g_assert_not_reached ();
4928 mono_aot_register_jit_icall (const char *name, gpointer addr)