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;
141 CRITICAL_SECTION mutex;
146 unsigned char *trampolines;
147 unsigned char *trampolines_end;
150 static GHashTable *aot_modules;
151 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
152 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
153 static CRITICAL_SECTION aot_mutex;
156 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
157 * AOT modules registered by mono_aot_register_module ().
159 static GHashTable *static_aot_modules;
162 * Maps MonoJitInfo* to the aot module they belong to, this can be different
163 * from ji->method->klass->image's aot module for generic instances.
165 static GHashTable *ji_to_amodule;
168 * Whenever to AOT compile loaded assemblies on demand and store them in
169 * a cache under $HOME/.mono/aot-cache.
171 static gboolean use_aot_cache = FALSE;
174 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
175 * use_aot_cache is TRUE.
177 static gboolean spawn_compiler = TRUE;
180 static gint32 mono_last_aot_method = -1;
182 static gboolean make_unreadable = FALSE;
183 static guint32 name_table_accesses = 0;
184 static guint32 n_pagefaults = 0;
186 /* Used to speed-up find_aot_module () */
187 static gsize aot_code_low_addr = (gssize)-1;
188 static gsize aot_code_high_addr = 0;
191 static gint32 async_jit_info_size;
193 static GHashTable *aot_jit_icall_hash;
196 #define USE_PAGE_TRAMPOLINES ((MonoAotModule*)mono_defaults.corlib->aot_module)->use_page_trampolines
198 #define USE_PAGE_TRAMPOLINES 0
201 #define mono_aot_page_lock() EnterCriticalSection (&aot_page_mutex)
202 #define mono_aot_page_unlock() LeaveCriticalSection (&aot_page_mutex)
203 static CRITICAL_SECTION aot_page_mutex;
206 init_plt (MonoAotModule *info);
208 /*****************************************************/
210 /*****************************************************/
213 amodule_lock (MonoAotModule *amodule)
215 EnterCriticalSection (&amodule->mutex);
219 amodule_unlock (MonoAotModule *amodule)
221 LeaveCriticalSection (&amodule->mutex);
227 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
228 * found, and sets the loader error if SET_ERROR is TRUE.
231 load_image (MonoAotModule *amodule, int index, gboolean set_error)
233 MonoAssembly *assembly;
234 MonoImageOpenStatus status;
236 g_assert (index < amodule->image_table_len);
238 if (amodule->image_table [index])
239 return amodule->image_table [index];
240 if (amodule->out_of_date)
243 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
245 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);
246 amodule->out_of_date = TRUE;
249 char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
250 mono_loader_set_error_assembly_load (full_name, FALSE);
256 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
257 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);
258 amodule->out_of_date = TRUE;
262 amodule->image_table [index] = assembly->image;
263 return assembly->image;
267 decode_value (guint8 *ptr, guint8 **rptr)
272 if ((b & 0x80) == 0){
275 } else if ((b & 0x40) == 0){
276 len = ((b & 0x3f) << 8 | ptr [1]);
278 } else if (b != 0xff) {
279 len = ((b & 0x1f) << 24) |
286 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
292 //printf ("DECODE: %d.\n", len);
297 * mono_aot_get_offset:
299 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
303 mono_aot_get_offset (guint32 *table, int index)
305 int i, group, ngroups, index_entry_size;
306 int start_offset, offset, noffsets, group_size;
307 guint8 *data_start, *p;
308 guint32 *index32 = NULL;
309 guint16 *index16 = NULL;
311 noffsets = table [0];
312 group_size = table [1];
314 index_entry_size = table [3];
315 group = index / group_size;
317 if (index_entry_size == 2) {
318 index16 = (guint16*)&table [4];
319 data_start = (guint8*)&index16 [ngroups];
320 p = data_start + index16 [group];
322 index32 = (guint32*)&table [4];
323 data_start = (guint8*)&index32 [ngroups];
324 p = data_start + index32 [group];
327 /* offset will contain the value of offsets [group * group_size] */
328 offset = start_offset = decode_value (p, &p);
329 for (i = group * group_size + 1; i <= index; ++i) {
330 offset += decode_value (p, &p);
333 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
339 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
342 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
345 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
347 static MonoGenericInst*
348 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
351 MonoType **type_argv;
352 MonoGenericInst *inst;
355 type_argc = decode_value (p, &p);
356 type_argv = g_new0 (MonoType*, type_argc);
358 for (i = 0; i < type_argc; ++i) {
359 MonoClass *pclass = decode_klass_ref (module, p, &p);
364 type_argv [i] = &pclass->byval_arg;
367 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
376 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
383 argc = decode_value (p, &p);
386 ctx->class_inst = decode_generic_inst (module, p, &p);
387 if (!ctx->class_inst)
391 argc = decode_value (p, &p);
394 ctx->method_inst = decode_generic_inst (module, p, &p);
395 if (!ctx->method_inst)
404 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
407 MonoClass *klass = NULL, *eklass;
408 guint32 token, rank, idx;
412 reftype = decode_value (p, &p);
419 case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
420 idx = decode_value (p, &p);
421 image = load_image (module, 0, TRUE);
424 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
426 case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
427 idx = decode_value (p, &p);
428 image = load_image (module, decode_value (p, &p), TRUE);
431 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
433 case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
434 token = decode_value (p, &p);
435 image = module->assembly->image;
438 klass = mono_class_get (image, token);
440 case MONO_AOT_TYPEREF_GINST: {
442 MonoGenericContext ctx;
445 gclass = decode_klass_ref (module, p, &p);
448 g_assert (gclass->generic_container);
450 memset (&ctx, 0, sizeof (ctx));
451 ctx.class_inst = decode_generic_inst (module, p, &p);
454 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
455 klass = mono_class_from_mono_type (type);
456 mono_metadata_free_type (type);
459 case MONO_AOT_TYPEREF_VAR: {
461 MonoGenericContainer *container = NULL;
462 int type = decode_value (p, &p);
463 int num = decode_value (p, &p);
464 gboolean has_container = decode_value (p, &p);
468 gboolean is_method = decode_value (p, &p);
471 MonoMethod *method_def;
472 g_assert (type == MONO_TYPE_MVAR);
473 method_def = decode_resolve_method_ref (module, p, &p);
477 container = mono_method_get_generic_container (method_def);
479 MonoClass *class_def;
480 g_assert (type == MONO_TYPE_VAR);
481 class_def = decode_klass_ref (module, p, &p);
485 container = class_def->generic_container;
488 serial = decode_value (p, &p);
491 // FIXME: Memory management
492 t = g_new0 (MonoType, 1);
495 t->data.generic_param = mono_generic_container_get_param (container, num);
496 g_assert (serial == 0);
499 MonoGenericParam *par = (MonoGenericParam*)g_new0 (MonoGenericParamFull, 1);
501 par->serial = serial;
503 par->image = mono_defaults.corlib;
504 t->data.generic_param = par;
507 // FIXME: Maybe use types directly to avoid
508 // the overhead of creating MonoClass-es
509 klass = mono_class_from_mono_type (t);
514 case MONO_AOT_TYPEREF_ARRAY:
516 rank = decode_value (p, &p);
517 eklass = decode_klass_ref (module, p, &p);
518 klass = mono_array_class_get (eklass, rank);
520 case MONO_AOT_TYPEREF_PTR: {
523 t = decode_type (module, p, &p);
526 klass = mono_class_from_mono_type (t);
530 case MONO_AOT_TYPEREF_BLOB_INDEX: {
531 guint32 offset = decode_value (p, &p);
534 p2 = module->blob + offset;
535 klass = decode_klass_ref (module, p2, &p2);
539 g_assert_not_reached ();
542 //printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
547 static MonoClassField*
548 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
550 MonoClass *klass = decode_klass_ref (module, buf, &buf);
557 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
561 return mono_class_get_field (klass, token);
565 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
569 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
574 t = g_malloc0 (sizeof (MonoType));
577 if (*p == MONO_TYPE_PINNED) {
580 } else if (*p == MONO_TYPE_BYREF) {
593 case MONO_TYPE_BOOLEAN:
607 case MONO_TYPE_STRING:
608 case MONO_TYPE_OBJECT:
609 case MONO_TYPE_TYPEDBYREF:
611 case MONO_TYPE_VALUETYPE:
612 case MONO_TYPE_CLASS:
613 t->data.klass = decode_klass_ref (module, p, &p);
615 case MONO_TYPE_SZARRAY:
616 t->data.klass = decode_klass_ref (module, p, &p);
622 t->data.type = decode_type (module, p, &p);
624 case MONO_TYPE_GENERICINST: {
626 MonoGenericContext ctx;
630 gclass = decode_klass_ref (module, p, &p);
633 g_assert (gclass->generic_container);
635 memset (&ctx, 0, sizeof (ctx));
636 ctx.class_inst = decode_generic_inst (module, p, &p);
639 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
640 klass = mono_class_from_mono_type (type);
641 t->data.generic_class = klass->generic_class;
644 case MONO_TYPE_ARRAY: {
645 MonoArrayType *array;
648 // FIXME: memory management
649 array = g_new0 (MonoArrayType, 1);
650 array->eklass = decode_klass_ref (module, p, &p);
653 array->rank = decode_value (p, &p);
654 array->numsizes = decode_value (p, &p);
657 array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
658 for (i = 0; i < array->numsizes; ++i)
659 array->sizes [i] = decode_value (p, &p);
661 array->numlobounds = decode_value (p, &p);
662 if (array->numlobounds)
663 array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
664 for (i = 0; i < array->numlobounds; ++i)
665 array->lobounds [i] = decode_value (p, &p);
666 t->data.array = array;
670 case MONO_TYPE_MVAR: {
671 MonoClass *klass = decode_klass_ref (module, p, &p);
674 t->data.generic_param = klass->byval_arg.data.generic_param;
678 g_assert_not_reached ();
686 // FIXME: Error handling, memory management
688 static MonoMethodSignature*
689 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
691 MonoMethodSignature *sig;
693 int i, param_count, call_conv, gen_param_count = 0;
695 gboolean hasthis, explicit_this, has_gen_params;
699 has_gen_params = (flags & 0x10) != 0;
700 hasthis = (flags & 0x20) != 0;
701 explicit_this = (flags & 0x40) != 0;
702 call_conv = flags & 0x0F;
705 gen_param_count = decode_value (p, &p);
706 param_count = decode_value (p, &p);
707 if (target && param_count != target->param_count)
709 sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
710 sig->param_count = param_count;
711 sig->sentinelpos = -1;
712 sig->hasthis = hasthis;
713 sig->explicit_this = explicit_this;
714 sig->call_convention = call_conv;
715 sig->param_count = param_count;
716 sig->ret = decode_type (module, p, &p);
717 for (i = 0; i < param_count; ++i) {
718 if (*p == MONO_TYPE_SENTINEL) {
719 g_assert (sig->call_convention == MONO_CALL_VARARG);
720 sig->sentinelpos = i;
723 sig->params [i] = decode_type (module, p, &p);
726 if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
727 sig->sentinelpos = sig->param_count;
734 static MonoMethodSignature*
735 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
737 return decode_signature_with_target (module, NULL, buf, endbuf);
741 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
743 MonoMethodSignature *sig;
747 sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
748 res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
754 /* Stores information returned by decode_method_ref () */
759 gboolean no_aot_trampoline;
763 * decode_method_ref_with_target:
765 * Decode a method reference, storing the image/token into a MethodRef structure.
766 * This avoids loading metadata for the method if the caller does not need it. If the method has
767 * no token, then it is loaded from metadata and ref->method is set to the method instance.
768 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
769 * couldn't resolve to TARGET, and return FALSE.
770 * There are some kinds of method references which only support a non-null TARGET.
771 * This means that its not possible to decode this into a method, only to check
772 * that the method reference matches a given method. This is normally not a problem
773 * as these wrappers only occur in the extra_methods table, where we already have
774 * a method we want to lookup.
777 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
779 guint32 image_index, value;
780 MonoImage *image = NULL;
783 memset (ref, 0, sizeof (MethodRef));
785 value = decode_value (p, &p);
786 image_index = value >> 24;
788 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
789 ref->no_aot_trampoline = TRUE;
790 value = decode_value (p, &p);
791 image_index = value >> 24;
794 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
795 if (target && target->wrapper_type)
799 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
800 guint32 wrapper_type;
802 wrapper_type = decode_value (p, &p);
804 if (target && target->wrapper_type != wrapper_type)
808 image = mono_defaults.corlib;
810 switch (wrapper_type) {
811 #ifndef DISABLE_REMOTING
812 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
813 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
817 mono_class_init (m->klass);
818 ref->method = mono_marshal_get_remoting_invoke_with_check (m);
821 case MONO_WRAPPER_PROXY_ISINST: {
822 MonoClass *klass = decode_klass_ref (module, p, &p);
825 ref->method = mono_marshal_get_proxy_cancast (klass);
828 case MONO_WRAPPER_LDFLD:
829 case MONO_WRAPPER_LDFLDA:
830 case MONO_WRAPPER_STFLD:
831 case MONO_WRAPPER_ISINST: {
832 MonoClass *klass = decode_klass_ref (module, p, &p);
835 if (wrapper_type == MONO_WRAPPER_LDFLD)
836 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
837 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
838 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
839 else if (wrapper_type == MONO_WRAPPER_STFLD)
840 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
841 else if (wrapper_type == MONO_WRAPPER_ISINST)
842 ref->method = mono_marshal_get_isinst (klass);
844 g_assert_not_reached ();
847 case MONO_WRAPPER_LDFLD_REMOTE:
848 ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
850 case MONO_WRAPPER_STFLD_REMOTE:
851 ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
854 case MONO_WRAPPER_ALLOC: {
855 int atype = decode_value (p, &p);
857 ref->method = mono_gc_get_managed_allocator_by_type (atype);
858 g_assert (ref->method);
861 case MONO_WRAPPER_WRITE_BARRIER:
862 ref->method = mono_gc_get_write_barrier ();
864 case MONO_WRAPPER_STELEMREF: {
865 int subtype = decode_value (p, &p);
867 if (subtype == WRAPPER_SUBTYPE_NONE) {
868 ref->method = mono_marshal_get_stelemref ();
869 } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
873 kind = decode_value (p, &p);
875 /* Can't decode this */
878 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
879 info = mono_marshal_get_wrapper_info (target);
882 if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
883 ref->method = target;
890 g_assert_not_reached ();
894 case MONO_WRAPPER_SYNCHRONIZED: {
895 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
899 ref->method = mono_marshal_get_synchronized_wrapper (m);
902 case MONO_WRAPPER_UNKNOWN: {
903 MonoMethodDesc *desc;
904 MonoMethod *orig_method;
905 int subtype = decode_value (p, &p);
907 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
908 MonoClass *klass = decode_klass_ref (module, p, &p);
915 if (klass != target->klass)
918 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
919 if (strcmp (target->name, "PtrToStructure"))
921 ref->method = mono_marshal_get_ptr_to_struct (klass);
923 if (strcmp (target->name, "StructureToPtr"))
925 ref->method = mono_marshal_get_struct_to_ptr (klass);
927 } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
928 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
932 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
933 } else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
934 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
938 ref->method = mono_marshal_get_array_accessor_wrapper (m);
939 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
940 ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
941 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
942 ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
944 if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
945 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
946 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
947 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
948 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
949 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
951 g_assert_not_reached ();
952 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
953 g_assert (orig_method);
954 mono_method_desc_free (desc);
955 ref->method = mono_monitor_get_fast_path (orig_method);
959 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
960 int subtype = decode_value (p, &p);
962 if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
963 int rank = decode_value (p, &p);
964 int elem_size = decode_value (p, &p);
966 ref->method = mono_marshal_get_array_address (rank, elem_size);
967 } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
971 m = decode_resolve_method_ref (module, p, &p);
977 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
979 info = mono_marshal_get_wrapper_info (target);
980 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
981 ref->method = target;
987 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
989 int subtype = decode_value (p, &p);
992 if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
997 if (strcmp (target->name, name) != 0)
999 ref->method = target;
1001 m = decode_resolve_method_ref (module, p, &p);
1006 /* This should only happen when looking for an extra method */
1009 if (mono_marshal_method_from_wrapper (target) == m)
1010 ref->method = target;
1016 case MONO_WRAPPER_CASTCLASS: {
1017 int subtype = decode_value (p, &p);
1019 if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
1020 ref->method = mono_marshal_get_castclass_with_cache ();
1021 else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
1022 ref->method = mono_marshal_get_isinst_with_cache ();
1024 g_assert_not_reached ();
1027 case MONO_WRAPPER_RUNTIME_INVOKE: {
1028 int subtype = decode_value (p, &p);
1033 if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
1034 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
1036 ref->method = target;
1037 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
1038 /* Direct wrapper */
1039 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1043 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
1044 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
1045 /* Virtual direct wrapper */
1046 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1050 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
1052 MonoMethodSignature *sig;
1055 sig = decode_signature_with_target (module, NULL, p, &p);
1056 info = mono_marshal_get_wrapper_info (target);
1059 if (info->subtype != subtype)
1061 g_assert (info->d.runtime_invoke.sig);
1062 if (mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig))
1063 ref->method = target;
1069 case MONO_WRAPPER_DELEGATE_INVOKE:
1070 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1071 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
1072 gboolean is_inflated = decode_value (p, &p);
1073 WrapperSubtype subtype;
1077 MonoMethod *invoke, *wrapper;
1079 klass = decode_klass_ref (module, p, &p);
1083 switch (wrapper_type) {
1084 case MONO_WRAPPER_DELEGATE_INVOKE:
1085 invoke = mono_get_delegate_invoke (klass);
1086 wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
1088 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1089 invoke = mono_get_delegate_begin_invoke (klass);
1090 wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
1092 case MONO_WRAPPER_DELEGATE_END_INVOKE:
1093 invoke = mono_get_delegate_end_invoke (klass);
1094 wrapper = mono_marshal_get_delegate_end_invoke (invoke);
1097 g_assert_not_reached ();
1100 if (target && wrapper != target)
1102 ref->method = wrapper;
1105 * These wrappers are associated with a signature, not with a method.
1106 * Since we can't decode them into methods, they need a target method.
1111 if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1114 subtype = decode_value (p, &p);
1115 info = mono_marshal_get_wrapper_info (target);
1117 if (info->subtype != subtype)
1120 if (subtype != WRAPPER_SUBTYPE_NONE)
1124 if (sig_matches_target (module, target, p, &p))
1125 ref->method = target;
1131 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1135 m = decode_resolve_method_ref (module, p, &p);
1138 klass = decode_klass_ref (module, p, &p);
1141 ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
1145 g_assert_not_reached ();
1147 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1148 image_index = decode_value (p, &p);
1149 ref->token = decode_value (p, &p);
1151 image = load_image (module, image_index, TRUE);
1154 } else if (image_index == MONO_AOT_METHODREF_GINST) {
1156 MonoGenericContext ctx;
1159 * These methods do not have a token which resolves them, so we
1160 * resolve them immediately.
1162 klass = decode_klass_ref (module, p, &p);
1166 if (target && target->klass != klass)
1169 image_index = decode_value (p, &p);
1170 ref->token = decode_value (p, &p);
1172 image = load_image (module, image_index, TRUE);
1176 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
1180 memset (&ctx, 0, sizeof (ctx));
1182 if (FALSE && klass->generic_class) {
1183 ctx.class_inst = klass->generic_class->context.class_inst;
1184 ctx.method_inst = NULL;
1186 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1189 memset (&ctx, 0, sizeof (ctx));
1191 if (!decode_generic_context (module, &ctx, p, &p))
1194 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1195 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1199 klass = decode_klass_ref (module, p, &p);
1202 method_type = decode_value (p, &p);
1203 switch (method_type) {
1205 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
1208 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
1211 ref->method = mono_class_get_method_from_name (klass, "Get", -1);
1214 ref->method = mono_class_get_method_from_name (klass, "Address", -1);
1217 ref->method = mono_class_get_method_from_name (klass, "Set", -1);
1220 g_assert_not_reached ();
1223 if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
1224 image_index = decode_value (p, &p);
1225 value = decode_value (p, &p);
1228 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1230 image = load_image (module, image_index, TRUE);
1243 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
1245 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
1249 * decode_resolve_method_ref_with_target:
1251 * Similar to decode_method_ref, but resolve and return the method itself.
1254 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
1259 res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
1266 return mono_get_method (ref.image, ref.token, NULL);
1270 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
1272 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
1276 create_cache_structure (void)
1282 home = g_get_home_dir ();
1286 tmp = g_build_filename (home, ".mono", NULL);
1287 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1288 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1292 err = mkdir (tmp, 0777);
1295 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1301 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
1302 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1303 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1307 err = mkdir (tmp, 0777);
1310 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1319 * load_aot_module_from_cache:
1321 * Experimental code to AOT compile loaded assemblies on demand.
1324 * - Add environment variable MONO_AOT_CACHE_OPTIONS
1325 * - Add options for controlling the cache size
1326 * - Handle full cache by deleting old assemblies lru style
1327 * - Add options for excluding assemblies during development
1328 * - Maybe add a threshold after an assembly is AOT compiled
1329 * - invoking a new mono process is a security risk
1330 * - recompile the AOT module if one of its dependencies changes
1333 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
1335 char *fname, *cmd, *tmp2, *aot_options;
1344 if (assembly->image->dynamic)
1347 create_cache_structure ();
1349 home = g_get_home_dir ();
1351 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
1352 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
1356 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
1357 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1360 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
1362 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
1364 aot_options = g_strdup_printf ("outfile=%s", fname);
1366 if (spawn_compiler) {
1367 /* FIXME: security */
1368 /* FIXME: Has to pass the assembly loading path to the child process */
1369 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
1371 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1373 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
1375 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1376 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
1378 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1385 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1387 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
1389 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1393 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1395 g_free (aot_options);
1402 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1406 guint16 *table, *entry;
1409 char *symbol = (char*)name;
1412 symbol = g_strdup_printf ("_%s", name);
1415 /* The first entry points to the hash */
1416 table = globals [0];
1419 table_size = table [0];
1422 hash = mono_metadata_str_hash (symbol) % table_size;
1424 entry = &table [hash * 2];
1426 /* Search the hash for the index into the globals table */
1428 while (entry [0] != 0) {
1429 guint32 index = entry [0] - 1;
1430 guint32 next = entry [1];
1432 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1434 if (!strcmp (globals [index * 2], symbol)) {
1435 global_index = index;
1440 entry = &table [next * 2];
1446 if (global_index != -1)
1447 *value = globals [global_index * 2 + 1];
1454 char *err = mono_dl_symbol (module, name, value);
1462 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
1466 gboolean usable = TRUE;
1469 guint32 excluded_cpu_optimizations;
1471 if (strcmp (assembly->image->guid, info->assembly_guid)) {
1472 msg = g_strdup_printf ("doesn't match assembly");
1476 build_info = mono_get_runtime_build_info ();
1477 if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1478 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1481 g_free (build_info);
1483 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1485 if (mono_aot_only && !full_aot) {
1486 msg = g_strdup_printf ("not compiled with --aot=full");
1489 if (!mono_aot_only && full_aot) {
1490 msg = g_strdup_printf ("compiled with --aot=full");
1494 /* mono_arch_find_imt_method () requires this */
1495 if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1496 msg = g_strdup_printf ("compiled against LLVM");
1499 if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1500 msg = g_strdup_printf ("not compiled against LLVM");
1504 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1505 msg = g_strdup_printf ("not compiled for debugging");
1509 mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1510 if (info->opts & excluded_cpu_optimizations) {
1511 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1515 if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
1516 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1522 if (info->gc_name_index != -1) {
1523 char *gc_name = (char*)&blob [info->gc_name_index];
1524 const char *current_gc_name = mono_gc_get_gc_name ();
1526 if (strcmp (current_gc_name, gc_name) != 0) {
1527 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1536 /* This returns an interop address */
1538 get_arm_bl_target (guint32 *ins_addr)
1541 guint32 ins = *ins_addr;
1544 if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
1546 offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
1547 return (char*)ins_addr + (offset * 2) + 8 + 1;
1549 offset = (((int)ins & 0xffffff) << 8) >> 8;
1550 return (char*)ins_addr + (offset * 4) + 8;
1553 g_assert_not_reached ();
1559 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1562 MonoAotModule *amodule;
1564 gboolean usable = TRUE;
1565 char *version_symbol = NULL;
1567 gpointer *globals = NULL;
1568 MonoAotFileInfo *info = NULL;
1571 gboolean do_load_image = TRUE;
1572 int align_double, align_int64;
1574 if (mono_compile_aot)
1577 if (assembly->image->aot_module)
1579 * Already loaded. This can happen because the assembly loading code might invoke
1580 * the assembly load hooks multiple times for the same assembly.
1584 if (assembly->image->dynamic || assembly->ref_only)
1587 if (mono_security_cas_enabled ())
1591 if (static_aot_modules)
1592 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1598 /* Statically linked AOT module */
1600 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1601 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1602 globals = info->globals;
1605 sofile = load_aot_module_from_cache (assembly, &aot_name);
1608 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1610 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1613 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module '%s' not found: %s\n", aot_name, err);
1619 if (!sofile && !globals) {
1620 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1621 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1629 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1630 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1633 if (version_symbol) {
1634 /* Old file format */
1635 version = atoi (version_symbol);
1638 version = info->version;
1641 if (version != MONO_AOT_FILE_VERSION) {
1642 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1645 usable = check_usable (assembly, info, &msg);
1649 if (mono_aot_only) {
1650 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1653 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1658 mono_dl_close (sofile);
1659 assembly->image->aot_module = NULL;
1663 #if defined (TARGET_ARM) && defined (TARGET_MACH)
1668 memset (&t, 0, sizeof (MonoType));
1669 t.type = MONO_TYPE_R8;
1670 mono_type_size (&t, &align);
1671 align_double = align;
1673 memset (&t, 0, sizeof (MonoType));
1674 t.type = MONO_TYPE_I8;
1675 align_int64 = align;
1678 align_double = __alignof__ (double);
1679 align_int64 = __alignof__ (gint64);
1683 g_assert (info->double_align == align_double);
1684 g_assert (info->long_align == align_int64);
1685 g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
1689 amodule = g_new0 (MonoAotModule, 1);
1690 amodule->aot_name = aot_name;
1691 amodule->assembly = assembly;
1693 memcpy (&amodule->info, info, sizeof (*info));
1695 amodule->got = amodule->info.got;
1696 amodule->got [0] = assembly->image;
1697 amodule->globals = globals;
1698 amodule->sofile = sofile;
1699 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1700 amodule->blob = blob;
1702 InitializeCriticalSection (&amodule->mutex);
1704 /* Read image table */
1706 guint32 table_len, i;
1709 table = info->image_table;
1712 table_len = *(guint32*)table;
1713 table += sizeof (guint32);
1714 amodule->image_table = g_new0 (MonoImage*, table_len);
1715 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1716 amodule->image_guids = g_new0 (char*, table_len);
1717 amodule->image_table_len = table_len;
1718 for (i = 0; i < table_len; ++i) {
1719 MonoAssemblyName *aname = &(amodule->image_names [i]);
1721 aname->name = g_strdup (table);
1722 table += strlen (table) + 1;
1723 amodule->image_guids [i] = g_strdup (table);
1724 table += strlen (table) + 1;
1726 aname->culture = g_strdup (table);
1727 table += strlen (table) + 1;
1728 memcpy (aname->public_key_token, table, strlen (table) + 1);
1729 table += strlen (table) + 1;
1731 table = ALIGN_PTR_TO (table, 8);
1732 aname->flags = *(guint32*)table;
1734 aname->major = *(guint32*)table;
1736 aname->minor = *(guint32*)table;
1738 aname->build = *(guint32*)table;
1740 aname->revision = *(guint32*)table;
1745 amodule->code_offsets = info->code_offsets;
1746 amodule->method_addresses = info->method_addresses;
1747 amodule->code = info->methods;
1749 /* Mask out thumb interop bit */
1750 amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1752 amodule->code_end = info->methods_end;
1753 amodule->method_info_offsets = info->method_info_offsets;
1754 amodule->ex_info_offsets = info->ex_info_offsets;
1755 amodule->class_info_offsets = info->class_info_offsets;
1756 amodule->class_name_table = info->class_name_table;
1757 amodule->extra_method_table = info->extra_method_table;
1758 amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1759 amodule->unbox_trampolines = info->unbox_trampolines;
1760 amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1761 amodule->got_info_offsets = info->got_info_offsets;
1762 amodule->unwind_info = info->unwind_info;
1763 amodule->mem_end = info->mem_end;
1764 amodule->mem_begin = amodule->code;
1765 amodule->plt = info->plt;
1766 amodule->plt_end = info->plt_end;
1767 amodule->mono_eh_frame = info->mono_eh_frame;
1768 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1769 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1770 amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1771 amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = info->gsharedvt_arg_trampolines;
1772 amodule->thumb_end = info->thumb_end;
1774 if (info->flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) {
1775 /* Compute code_offsets from the method addresses */
1776 amodule->code_offsets = g_malloc0 (amodule->info.nmethods * sizeof (gint32));
1777 for (i = 0; i < amodule->info.nmethods; ++i) {
1778 /* method_addresses () contains a table of branches, since the ios linker can update those correctly */
1782 addr = get_arm_bl_target ((guint32*)amodule->method_addresses + i);
1783 #elif defined(TARGET_X86) || defined(TARGET_AMD64)
1784 addr = mono_arch_get_call_target ((guint8*)amodule->method_addresses + (i * 5) + 5);
1786 g_assert_not_reached ();
1789 if (addr == amodule->method_addresses)
1790 amodule->code_offsets [i] = 0xffffffff;
1792 amodule->code_offsets [i] = (char*)addr - (char*)amodule->code;
1796 if (make_unreadable) {
1797 #ifndef TARGET_WIN32
1799 guint8 *page_start, *page_end;
1802 addr = amodule->mem_begin;
1803 len = amodule->mem_end - amodule->mem_begin;
1805 /* Round down in both directions to avoid modifying data which is not ours */
1806 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1807 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1808 if (page_end > page_start) {
1809 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1810 g_assert (err == 0);
1817 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1818 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1820 g_hash_table_insert (aot_modules, assembly, amodule);
1823 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1825 assembly->image->aot_module = amodule;
1827 if (mono_aot_only) {
1829 find_symbol (amodule->sofile, amodule->globals, "specific_trampolines_page", (gpointer *)&code);
1830 amodule->use_page_trampolines = code != NULL;
1831 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
1832 if (mono_defaults.corlib) {
1833 /* The second got slot contains the mscorlib got addr */
1834 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1836 amodule->got [1] = mscorlib_amodule->got;
1838 amodule->got [1] = amodule->got;
1842 if (mono_gc_is_moving ()) {
1845 memset (&ji, 0, sizeof (ji));
1846 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1848 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1852 * Since we store methoddef and classdef tokens when referring to methods/classes in
1853 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1854 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1855 * non-lazily, since we can't handle out-of-date errors later.
1856 * The cached class info also depends on the exact assemblies.
1858 #if defined(__native_client__)
1859 /* TODO: Don't 'load_image' on mscorlib due to a */
1860 /* recursive loading problem. This should be */
1861 /* removed if mscorlib is loaded from disk. */
1862 if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1863 do_load_image = TRUE;
1865 do_load_image = FALSE;
1868 if (do_load_image) {
1869 for (i = 0; i < amodule->image_table_len; ++i)
1870 load_image (amodule, i, FALSE);
1873 if (amodule->out_of_date) {
1874 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);
1875 if (mono_aot_only) {
1876 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);
1881 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1885 * mono_aot_register_globals:
1887 * This is called by the ctor function in AOT images compiled with the
1888 * 'no-dlsym' option.
1891 mono_aot_register_globals (gpointer *globals)
1893 g_assert_not_reached ();
1897 * mono_aot_register_module:
1899 * This should be called by embedding code to register AOT modules statically linked
1900 * into the executable. AOT_INFO should be the value of the
1901 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1904 mono_aot_register_module (gpointer *aot_info)
1908 MonoAotFileInfo *info = (gpointer)aot_info;
1910 g_assert (info->version == MONO_AOT_FILE_VERSION);
1912 globals = info->globals;
1915 aname = info->assembly_name;
1917 /* This could be called before startup */
1921 if (!static_aot_modules)
1922 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1924 g_hash_table_insert (static_aot_modules, aname, info);
1931 mono_aot_init (void)
1933 InitializeCriticalSection (&aot_mutex);
1934 InitializeCriticalSection (&aot_page_mutex);
1935 aot_modules = g_hash_table_new (NULL, NULL);
1937 #ifndef __native_client__
1938 mono_install_assembly_load_hook (load_aot_module, NULL);
1940 mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
1942 if (g_getenv ("MONO_LASTAOT"))
1943 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1944 if (g_getenv ("MONO_AOT_CACHE"))
1945 use_aot_cache = TRUE;
1949 mono_aot_cleanup (void)
1951 if (aot_jit_icall_hash)
1952 g_hash_table_destroy (aot_jit_icall_hash);
1954 g_hash_table_destroy (aot_modules);
1958 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1964 info->vtable_size = decode_value (buf, &buf);
1965 if (info->vtable_size == -1)
1968 flags = decode_value (buf, &buf);
1969 info->ghcimpl = (flags >> 0) & 0x1;
1970 info->has_finalize = (flags >> 1) & 0x1;
1971 info->has_cctor = (flags >> 2) & 0x1;
1972 info->has_nested_classes = (flags >> 3) & 0x1;
1973 info->blittable = (flags >> 4) & 0x1;
1974 info->has_references = (flags >> 5) & 0x1;
1975 info->has_static_refs = (flags >> 6) & 0x1;
1976 info->no_special_static_fields = (flags >> 7) & 0x1;
1977 info->is_generic_container = (flags >> 8) & 0x1;
1979 if (info->has_cctor) {
1980 res = decode_method_ref (module, &ref, buf, &buf);
1983 info->cctor_token = ref.token;
1985 if (info->has_finalize) {
1986 res = decode_method_ref (module, &ref, buf, &buf);
1989 info->finalize_image = ref.image;
1990 info->finalize_token = ref.token;
1993 info->instance_size = decode_value (buf, &buf);
1994 info->class_size = decode_value (buf, &buf);
1995 info->packing_size = decode_value (buf, &buf);
1996 info->min_align = decode_value (buf, &buf);
2004 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
2007 MonoClass *klass = vtable->klass;
2008 MonoAotModule *amodule = klass->image->aot_module;
2010 MonoCachedClassInfo class_info;
2015 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
2018 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
2021 err = decode_cached_class_info (amodule, &class_info, p, &p);
2025 for (i = 0; i < slot; ++i)
2026 decode_method_ref (amodule, &ref, p, &p);
2028 res = decode_method_ref (amodule, &ref, p, &p);
2031 if (ref.no_aot_trampoline)
2034 if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
2037 return mono_aot_get_method_from_token (domain, ref.image, ref.token);
2041 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2043 MonoAotModule *amodule = klass->image->aot_module;
2047 if (klass->rank || !amodule)
2050 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
2052 err = decode_cached_class_info (amodule, res, p, &p);
2060 * mono_aot_get_class_from_name:
2062 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
2063 * using a cache stored in the AOT file.
2064 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
2066 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
2070 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2072 MonoAotModule *amodule = image->aot_module;
2073 guint16 *table, *entry;
2076 char full_name_buf [1024];
2078 const char *name2, *name_space2;
2080 guint32 cols [MONO_TYPEDEF_SIZE];
2081 GHashTable *nspace_table;
2083 if (!amodule || !amodule->class_name_table)
2086 amodule_lock (amodule);
2090 /* First look in the cache */
2091 if (!amodule->name_cache)
2092 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
2093 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2095 *klass = g_hash_table_lookup (nspace_table, name);
2097 amodule_unlock (amodule);
2102 table_size = amodule->class_name_table [0];
2103 table = amodule->class_name_table + 1;
2105 if (name_space [0] == '\0')
2106 full_name = g_strdup_printf ("%s", name);
2108 if (strlen (name_space) + strlen (name) < 1000) {
2109 sprintf (full_name_buf, "%s.%s", name_space, name);
2110 full_name = full_name_buf;
2112 full_name = g_strdup_printf ("%s.%s", name_space, name);
2115 hash = mono_metadata_str_hash (full_name) % table_size;
2116 if (full_name != full_name_buf)
2119 entry = &table [hash * 2];
2121 if (entry [0] != 0) {
2122 t = &image->tables [MONO_TABLE_TYPEDEF];
2125 guint32 index = entry [0];
2126 guint32 next = entry [1];
2127 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2129 name_table_accesses ++;
2131 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2133 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2134 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2136 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2137 amodule_unlock (amodule);
2138 *klass = mono_class_get (image, token);
2142 amodule_lock (amodule);
2143 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2144 if (!nspace_table) {
2145 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2146 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2148 g_hash_table_insert (nspace_table, (char*)name2, *klass);
2149 amodule_unlock (amodule);
2155 entry = &table [next * 2];
2162 amodule_unlock (amodule);
2168 * decode_mono_eh_frame:
2170 * Decode the EH information emitted by our modified LLVM compiler and construct a
2171 * MonoJitInfo structure from it.
2172 * LOCKING: Acquires the domain lock.
2175 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
2176 MonoMethod *method, guint8 *code,
2177 MonoJitExceptionInfo *clauses, int num_clauses,
2178 int extra_size, GSList **nesting,
2179 int *this_reg, int *this_offset)
2182 guint8 *fde, *cie, *code_start, *code_end;
2183 int version, fde_count;
2185 int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
2186 MonoJitExceptionInfo *ei;
2187 guint32 fde_len, ei_len, nested_len, nindex;
2188 gpointer *type_info;
2190 MonoLLVMFDEInfo info;
2192 g_assert (amodule->mono_eh_frame);
2194 p = amodule->mono_eh_frame;
2196 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2200 g_assert (version == 3);
2204 p = ALIGN_PTR_TO (p, 4);
2206 fde_count = *(guint32*)p;
2210 /* There is +1 entry in the table */
2211 cie = p + ((fde_count + 1) * 8);
2213 /* Binary search in the table to find the entry for code */
2214 offset = code - amodule->code;
2218 pos = (left + right) / 2;
2220 /* The table contains method index/fde offset pairs */
2221 g_assert (table [(pos * 2)] != -1);
2222 offset1 = amodule->code_offsets [table [(pos * 2)]];
2223 if (pos + 1 == fde_count) {
2224 offset2 = amodule->code_end - amodule->code;
2226 g_assert (table [(pos + 1) * 2] != -1);
2227 offset2 = amodule->code_offsets [table [(pos + 1) * 2]];
2230 if (offset < offset1)
2232 else if (offset >= offset2)
2238 code_start = amodule->code + amodule->code_offsets [table [(pos * 2)]];
2239 if (pos + 1 == fde_count) {
2240 /* The +1 entry in the table contains the length of the last method */
2241 int len = table [(pos + 1) * 2];
2242 code_end = code_start + len;
2244 code_end = amodule->code + amodule->code_offsets [table [(pos + 1) * 2]];
2246 code_len = code_end - code_start;
2248 g_assert (code >= code_start && code < code_end);
2250 if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
2251 /* Clear thumb flag */
2252 code_start = (guint8*)(((mgreg_t)code_start) & ~1);
2254 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
2255 /* This won't overflow because there is +1 entry in the table */
2256 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2258 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
2260 ei_len = info.ex_info_len;
2261 type_info = info.type_info;
2262 *this_reg = info.this_reg;
2263 *this_offset = info.this_offset;
2265 /* Count number of nested clauses */
2267 for (i = 0; i < ei_len; ++i) {
2268 /* This might be unaligned */
2269 gint32 cindex1 = read32 (type_info [i]);
2272 for (l = nesting [cindex1]; l; l = l->next) {
2273 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2275 for (j = 0; j < ei_len; ++j) {
2276 gint32 cindex2 = read32 (type_info [j]);
2278 if (cindex2 == nesting_cindex)
2285 * LLVM might represent one IL region with multiple regions, so have to
2286 * allocate a new JI.
2289 mono_domain_alloc0_lock_free (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2291 jinfo->code_size = code_len;
2292 jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2293 jinfo->d.method = method;
2294 jinfo->code_start = code;
2295 jinfo->domain_neutral = 0;
2296 /* This signals that used_regs points to a normal cached unwind info */
2297 jinfo->from_aot = 0;
2298 jinfo->num_clauses = ei_len + nested_len;
2300 for (i = 0; i < ei_len; ++i) {
2302 * orig_jinfo contains the original IL exception info saved by the AOT
2303 * compiler, we have to combine that with the information produced by LLVM
2305 /* The type_info entries contain IL clause indexes */
2306 int clause_index = read32 (type_info [i]);
2307 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2308 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2310 g_assert (clause_index < num_clauses);
2311 jei->flags = orig_jei->flags;
2312 jei->data.catch_class = orig_jei->data.catch_class;
2314 jei->try_start = ei [i].try_start;
2315 jei->try_end = ei [i].try_end;
2316 jei->handler_start = ei [i].handler_start;
2318 /* Make sure we transition to thumb when a handler starts */
2319 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2320 jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2323 /* See exception_cb () in mini-llvm.c as to why this is needed */
2325 for (i = 0; i < ei_len; ++i) {
2326 gint32 cindex1 = read32 (type_info [i]);
2329 for (l = nesting [cindex1]; l; l = l->next) {
2330 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2332 for (j = 0; j < ei_len; ++j) {
2333 gint32 cindex2 = read32 (type_info [j]);
2335 if (cindex2 == nesting_cindex) {
2337 * The try interval comes from the nested clause, everything else from the
2340 memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2341 jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2342 jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2348 g_assert (nindex == ei_len + nested_len);
2354 alloc0_jit_info_data (MonoDomain *domain, int size, gboolean async_context)
2358 if (async_context) {
2359 res = mono_domain_alloc0_lock_free (domain, size);
2360 InterlockedExchangeAdd (&async_jit_info_size, size);
2362 res = mono_domain_alloc0 (domain, size);
2368 * LOCKING: Acquires the domain lock.
2369 * In async context, this is async safe.
2372 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
2373 MonoMethod *method, guint8* ex_info, guint8 *addr,
2374 guint8 *code, guint32 code_len)
2376 int i, buf_len, num_clauses, len;
2378 guint used_int_regs, flags;
2379 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2380 gboolean from_llvm, has_gc_map;
2382 int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2383 int this_reg = 0, this_offset = 0;
2386 /* Load the method info from the AOT file */
2387 async = mono_thread_info_is_async_context ();
2390 flags = decode_value (p, &p);
2391 has_generic_jit_info = (flags & 1) != 0;
2392 has_dwarf_unwind_info = (flags & 2) != 0;
2393 has_clauses = (flags & 4) != 0;
2394 has_seq_points = (flags & 8) != 0;
2395 from_llvm = (flags & 16) != 0;
2396 has_try_block_holes = (flags & 32) != 0;
2397 has_gc_map = (flags & 64) != 0;
2398 has_arch_eh_jit_info = (flags & 128) != 0;
2400 if (has_dwarf_unwind_info) {
2403 offset = decode_value (p, &p);
2404 g_assert (offset < (1 << 30));
2405 used_int_regs = offset;
2407 used_int_regs = decode_value (p, &p);
2409 if (has_generic_jit_info)
2410 generic_info_size = sizeof (MonoGenericJitInfo);
2412 generic_info_size = 0;
2414 if (has_try_block_holes) {
2415 num_holes = decode_value (p, &p);
2416 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2418 num_holes = try_holes_info_size = 0;
2420 /* Exception table */
2422 num_clauses = decode_value (p, &p);
2425 if (has_arch_eh_jit_info)
2426 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2428 arch_eh_jit_info_size = 0;
2431 MonoJitExceptionInfo *clauses;
2438 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2441 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2442 nesting = g_new0 (GSList*, num_clauses);
2444 for (i = 0; i < num_clauses; ++i) {
2445 MonoJitExceptionInfo *ei = &clauses [i];
2447 ei->flags = decode_value (p, &p);
2449 if (decode_value (p, &p))
2450 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2452 /* Read the list of nesting clauses */
2454 int nesting_index = decode_value (p, &p);
2455 if (nesting_index == -1)
2457 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2461 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);
2462 jinfo->from_llvm = 1;
2465 for (i = 0; i < num_clauses; ++i)
2466 g_slist_free (nesting [i]);
2469 len = MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size;
2470 jinfo = alloc0_jit_info_data (domain, len, async);
2471 jinfo->num_clauses = num_clauses;
2473 for (i = 0; i < jinfo->num_clauses; ++i) {
2474 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2476 ei->flags = decode_value (p, &p);
2478 ei->exvar_offset = decode_value (p, &p);
2480 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2481 ei->data.filter = code + decode_value (p, &p);
2483 int len = decode_value (p, &p);
2489 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2493 ei->try_start = code + decode_value (p, &p);
2494 ei->try_end = code + decode_value (p, &p);
2495 ei->handler_start = code + decode_value (p, &p);
2498 jinfo->code_size = code_len;
2499 jinfo->used_regs = used_int_regs;
2500 jinfo->d.method = method;
2501 jinfo->code_start = code;
2502 jinfo->domain_neutral = 0;
2503 jinfo->from_aot = 1;
2506 if (has_try_block_holes) {
2507 MonoTryBlockHoleTableJitInfo *table;
2509 jinfo->has_try_block_holes = 1;
2511 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2514 table->num_holes = (guint16)num_holes;
2515 for (i = 0; i < num_holes; ++i) {
2516 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2517 hole->clause = decode_value (p, &p);
2518 hole->length = decode_value (p, &p);
2519 hole->offset = decode_value (p, &p);
2523 if (has_arch_eh_jit_info) {
2524 MonoArchEHJitInfo *eh_info;
2526 jinfo->has_arch_eh_info = 1;
2528 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2529 eh_info->stack_size = decode_value (p, &p);
2533 /* The rest is not needed in async mode */
2534 jinfo->async = TRUE;
2535 jinfo->d.aot_info = amodule;
2540 if (has_generic_jit_info) {
2541 MonoGenericJitInfo *gi;
2544 jinfo->has_generic_jit_info = 1;
2546 gi = mono_jit_info_get_generic_jit_info (jinfo);
2549 gi->nlocs = decode_value (p, &p);
2551 gi->locations = alloc0_jit_info_data (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
2552 for (i = 0; i < gi->nlocs; ++i) {
2553 MonoDwarfLocListEntry *entry = &gi->locations [i];
2555 entry->is_reg = decode_value (p, &p);
2556 entry->reg = decode_value (p, &p);
2558 entry->offset = decode_value (p, &p);
2560 entry->from = decode_value (p, &p);
2561 entry->to = decode_value (p, &p);
2565 gi->has_this = this_reg != -1;
2566 gi->this_reg = this_reg;
2567 gi->this_offset = this_offset;
2569 gi->has_this = decode_value (p, &p);
2570 gi->this_reg = decode_value (p, &p);
2571 gi->this_offset = decode_value (p, &p);
2575 len = decode_value (p, &p);
2579 jinfo->d.method = decode_resolve_method_ref (amodule, p, &p);
2581 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2582 if (decode_value (p, &p)) {
2585 MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
2587 n = decode_value (p, &p);
2589 gsctx->var_is_vt = alloc0_jit_info_data (domain, sizeof (gboolean) * n, async);
2590 for (i = 0; i < n; ++i)
2591 gsctx->var_is_vt [i] = decode_value (p, &p);
2593 n = decode_value (p, &p);
2595 gsctx->mvar_is_vt = alloc0_jit_info_data (domain, sizeof (gboolean) * n, async);
2596 for (i = 0; i < n; ++i)
2597 gsctx->mvar_is_vt [i] = decode_value (p, &p);
2602 if (method && has_seq_points) {
2603 MonoSeqPointInfo *seq_points;
2604 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2606 int len = decode_value (p, &p);
2608 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2609 seq_points->len = len;
2610 last_il_offset = last_native_offset = 0;
2611 for (i = 0; i < len; ++i) {
2612 SeqPoint *sp = &seq_points->seq_points [i];
2613 il_offset = last_il_offset + decode_value (p, &p);
2614 native_offset = last_native_offset + decode_value (p, &p);
2616 sp->il_offset = il_offset;
2617 sp->native_offset = native_offset;
2619 sp->flags = decode_value (p, &p);
2620 sp->next_len = decode_value (p, &p);
2621 sp->next = g_new (int, sp->next_len);
2622 for (j = 0; j < sp->next_len; ++j)
2623 sp->next [j] = decode_value (p, &p);
2625 last_il_offset = il_offset;
2626 last_native_offset = native_offset;
2629 mono_domain_lock (domain);
2630 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2631 mono_domain_unlock (domain);
2634 /* Load debug info */
2635 buf_len = decode_value (p, &p);
2637 mono_debug_add_aot_method (domain, method, code, p, buf_len);
2641 int map_size = decode_value (p, &p);
2642 /* The GC map requires 4 bytes of alignment */
2643 while ((guint64)(gsize)p % 4)
2649 if (amodule != jinfo->d.method->klass->image->aot_module) {
2652 ji_to_amodule = g_hash_table_new (NULL, NULL);
2653 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2661 * mono_aot_get_unwind_info:
2663 * Return a pointer to the DWARF unwind info belonging to JI.
2666 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2668 MonoAotModule *amodule;
2670 guint8 *code = ji->code_start;
2673 amodule = ji->d.aot_info;
2675 amodule = jinfo_get_method (ji)->klass->image->aot_module;
2677 g_assert (ji->from_aot);
2679 if (!(code >= amodule->code && code <= amodule->code_end)) {
2680 /* ji belongs to a different aot module than amodule */
2682 g_assert (ji_to_amodule);
2683 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2685 g_assert (code >= amodule->code && code <= amodule->code_end);
2689 p = amodule->unwind_info + ji->used_regs;
2690 *unwind_info_len = decode_value (p, &p);
2694 static G_GNUC_UNUSED int
2695 compare_ints (const void *a, const void *b)
2697 return *(gint32*)a - *(gint32*)b;
2701 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2703 int mid = (lo + hi) / 2;
2710 for (i = lo; i < hi; ++i)
2711 if (array [(i * 2)] > array [(i * 2) + 2])
2714 /* Already sorted */
2718 msort_code_offsets_internal (array, lo, mid, scratch);
2719 msort_code_offsets_internal (array, mid + 1, hi, scratch);
2721 if (array [mid * 2] < array [(mid + 1) * 2])
2727 for (i = lo; i <= hi; i ++) {
2728 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2729 scratch [(i * 2)] = array [t_lo * 2];
2730 scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2733 scratch [(i * 2)] = array [t_hi * 2];
2734 scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2738 for (i = lo; i <= hi; ++i) {
2739 array [(i * 2)] = scratch [i * 2];
2740 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2745 msort_code_offsets (gint32 *array, int len)
2749 scratch = g_new (gint32, len * 2);
2750 msort_code_offsets_internal (array, 0, len - 1, scratch);
2755 * mono_aot_find_jit_info:
2757 * In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
2758 * to the jit info tables.
2759 * FIXME: Large sizes in the lock free allocator
2762 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2764 int pos, left, right, offset, offset1, offset2, code_len;
2765 int method_index, table_len;
2767 MonoAotModule *amodule = image->aot_module;
2768 MonoMethod *method = NULL;
2770 guint8 *code, *ex_info, *p;
2772 int nmethods = amodule->info.nmethods;
2773 gint32 *code_offsets;
2780 if (domain != mono_get_root_domain ())
2784 async = mono_thread_info_is_async_context ();
2786 offset = (guint8*)addr - amodule->code;
2788 /* Compute a sorted table mapping code offsets to method indexes. */
2789 if (!amodule->sorted_code_offsets) {
2791 code_offsets = g_new0 (gint32, nmethods * 2);
2793 for (i = 0; i < nmethods; ++i) {
2794 /* Skip the -1 entries to speed up sorting */
2795 if (amodule->code_offsets [i] == 0xffffffff)
2797 code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2798 code_offsets [(offsets_len *2) + 1] = i;
2801 /* Use a merge sort as this is mostly sorted */
2802 msort_code_offsets (code_offsets, offsets_len);
2803 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2804 for (i = 0; i < offsets_len -1; ++i)
2805 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2807 amodule->sorted_code_offsets_len = offsets_len;
2808 mono_memory_barrier ();
2809 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2810 /* Somebody got in before us */
2811 g_free (code_offsets);
2814 code_offsets = amodule->sorted_code_offsets;
2815 offsets_len = amodule->sorted_code_offsets_len;
2817 if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
2820 /* Binary search in the sorted_code_offsets table */
2822 right = offsets_len;
2824 pos = (left + right) / 2;
2826 offset1 = code_offsets [(pos * 2)];
2827 if (pos + 1 == offsets_len)
2828 offset2 = amodule->code_end - amodule->code;
2830 offset2 = code_offsets [(pos + 1) * 2];
2832 if (offset < offset1)
2834 else if (offset >= offset2)
2840 g_assert (offset >= code_offsets [(pos * 2)]);
2841 if (pos + 1 < offsets_len)
2842 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2843 method_index = code_offsets [(pos * 2) + 1];
2845 /* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
2847 JitInfoMap *table = amodule->async_jit_info_table;
2851 len = table [0].method_index;
2852 for (i = 1; i < len; ++i) {
2853 if (table [i].method_index == method_index)
2854 return table [i].jinfo;
2859 code = &amodule->code [amodule->code_offsets [method_index]];
2860 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2862 if (pos == offsets_len - 1)
2863 code_len = amodule->code_end - code;
2865 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2867 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2869 /* Might be a wrapper/extra method */
2871 if (amodule->extra_methods) {
2872 amodule_lock (amodule);
2873 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2874 amodule_unlock (amodule);
2880 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2882 * This is hit for extra methods which are called directly, so they are
2883 * not in amodule->extra_methods.
2885 table_len = amodule->extra_method_info_offsets [0];
2886 table = amodule->extra_method_info_offsets + 1;
2893 pos = ((left + right) / 2);
2895 g_assert (pos < table_len);
2897 if (table [pos * 2] < method_index)
2899 else if (table [pos * 2] > method_index)
2905 p = amodule->blob + table [(pos * 2) + 1];
2906 method = decode_resolve_method_ref (amodule, p, &p);
2908 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
2911 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2912 method = mono_get_method (image, token, NULL);
2919 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2921 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2923 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2924 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2926 /* Add it to the normal JitInfo tables */
2928 JitInfoMap *old_table, *new_table;
2932 * Use a simple inmutable table with linear search to cache async jit info entries.
2933 * This assumes that the number of entries is small.
2936 /* Copy the table, adding a new entry at the end */
2937 old_table = amodule->async_jit_info_table;
2939 len = old_table[0].method_index;
2942 new_table = alloc0_jit_info_data (domain, (len + 1) * sizeof (JitInfoMap), async);
2944 memcpy (new_table, old_table, len * sizeof (JitInfoMap));
2945 new_table [0].method_index = len + 1;
2946 new_table [len].method_index = method_index;
2947 new_table [len].jinfo = jinfo;
2949 mono_memory_barrier ();
2950 if (InterlockedCompareExchangePointer ((gpointer)&amodule->async_jit_info_table, new_table, old_table) == old_table)
2954 mono_jit_info_table_add (domain, jinfo);
2961 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2969 case MONO_PATCH_INFO_METHOD:
2970 case MONO_PATCH_INFO_METHOD_JUMP:
2971 case MONO_PATCH_INFO_ICALL_ADDR:
2972 case MONO_PATCH_INFO_METHOD_RGCTX:
2973 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
2977 res = decode_method_ref (aot_module, &ref, p, &p);
2981 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)) {
2982 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2983 ji->type = MONO_PATCH_INFO_ABS;
2987 ji->data.method = ref.method;
2989 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2990 g_assert (ji->data.method);
2991 mono_class_init (ji->data.method->klass);
2995 case MONO_PATCH_INFO_INTERNAL_METHOD:
2996 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2997 guint32 len = decode_value (p, &p);
2999 ji->data.name = (char*)p;
3003 case MONO_PATCH_INFO_METHODCONST:
3005 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
3006 if (!ji->data.method)
3009 case MONO_PATCH_INFO_VTABLE:
3010 case MONO_PATCH_INFO_CLASS:
3011 case MONO_PATCH_INFO_IID:
3012 case MONO_PATCH_INFO_ADJUSTED_IID:
3013 case MONO_PATCH_INFO_CLASS_INIT:
3015 ji->data.klass = decode_klass_ref (aot_module, p, &p);
3016 if (!ji->data.klass)
3019 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3020 ji->data.del_tramp = mono_mempool_alloc0 (mp, sizeof (MonoClassMethodPair));
3021 ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p);
3022 if (!ji->data.del_tramp->klass)
3024 if (decode_value (p, &p)) {
3025 ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
3026 if (!ji->data.del_tramp->method)
3030 case MONO_PATCH_INFO_IMAGE:
3031 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
3032 if (!ji->data.image)
3035 case MONO_PATCH_INFO_FIELD:
3036 case MONO_PATCH_INFO_SFLDA:
3038 ji->data.field = decode_field_info (aot_module, p, &p);
3039 if (!ji->data.field)
3042 case MONO_PATCH_INFO_SWITCH:
3043 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
3044 ji->data.table->table_size = decode_value (p, &p);
3045 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
3046 ji->data.table->table = (MonoBasicBlock**)table;
3047 for (i = 0; i < ji->data.table->table_size; i++)
3048 table [i] = (gpointer)(gssize)decode_value (p, &p);
3050 case MONO_PATCH_INFO_R4: {
3053 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
3054 val = decode_value (p, &p);
3055 *(float*)ji->data.target = *(float*)&val;
3058 case MONO_PATCH_INFO_R8: {
3062 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
3064 val [0] = decode_value (p, &p);
3065 val [1] = decode_value (p, &p);
3066 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
3067 *(double*)ji->data.target = *(double*)&v;
3070 case MONO_PATCH_INFO_LDSTR:
3071 image = load_image (aot_module, decode_value (p, &p), TRUE);
3074 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
3076 case MONO_PATCH_INFO_RVA:
3077 case MONO_PATCH_INFO_DECLSEC:
3078 case MONO_PATCH_INFO_LDTOKEN:
3079 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3081 image = load_image (aot_module, decode_value (p, &p), TRUE);
3084 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
3086 ji->data.token->has_context = decode_value (p, &p);
3087 if (ji->data.token->has_context) {
3088 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
3093 case MONO_PATCH_INFO_EXC_NAME:
3094 ji->data.klass = decode_klass_ref (aot_module, p, &p);
3095 if (!ji->data.klass)
3097 ji->data.name = ji->data.klass->name;
3099 case MONO_PATCH_INFO_METHOD_REL:
3100 ji->data.offset = decode_value (p, &p);
3102 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3103 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3104 case MONO_PATCH_INFO_MONITOR_ENTER:
3105 case MONO_PATCH_INFO_MONITOR_EXIT:
3106 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3107 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3108 case MONO_PATCH_INFO_JIT_TLS_ID:
3110 case MONO_PATCH_INFO_RGCTX_FETCH: {
3112 MonoJumpInfoRgctxEntry *entry;
3113 guint32 offset, val;
3116 offset = decode_value (p, &p);
3117 val = decode_value (p, &p);
3119 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3120 p2 = aot_module->blob + offset;
3121 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
3122 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
3123 entry->info_type = (val >> 1) & 0xff;
3124 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3125 entry->data->type = (val >> 9) & 0xff;
3127 res = decode_patch (aot_module, mp, entry->data, p, &p);
3130 ji->data.rgctx_entry = entry;
3133 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3135 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
3136 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
3138 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
3139 imt_tramp->vt_offset = decode_value (p, &p);
3141 ji->data.imt_tramp = imt_tramp;
3144 case MONO_PATCH_INFO_SIGNATURE:
3145 ji->data.target = decode_signature (aot_module, p, &p);
3147 case MONO_PATCH_INFO_TLS_OFFSET:
3148 ji->data.target = GINT_TO_POINTER (decode_value (p, &p));
3150 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
3151 MonoJumpInfoGSharedVtCall *info = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
3152 info->sig = decode_signature (aot_module, p, &p);
3153 g_assert (info->sig);
3154 info->method = decode_resolve_method_ref (aot_module, p, &p);
3155 g_assert (info->method);
3157 ji->data.target = info;
3160 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
3161 MonoGSharedVtMethodInfo *info = mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
3164 info->method = decode_resolve_method_ref (aot_module, p, &p);
3165 g_assert (info->method);
3166 info->num_entries = decode_value (p, &p);
3167 info->count_entries = info->num_entries;
3168 info->entries = mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
3169 for (i = 0; i < info->num_entries; ++i) {
3170 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
3172 template->info_type = decode_value (p, &p);
3173 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
3174 case MONO_PATCH_INFO_CLASS: {
3175 MonoClass *klass = decode_klass_ref (aot_module, p, &p);
3178 template->data = &klass->byval_arg;
3181 case MONO_PATCH_INFO_FIELD:
3182 template->data = decode_field_info (aot_module, p, &p);
3183 if (!template->data)
3187 g_assert_not_reached ();
3191 ji->data.target = info;
3195 g_warning ("unhandled type %d", ji->type);
3196 g_assert_not_reached ();
3207 static MonoJumpInfo*
3208 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
3209 guint32 **got_slots,
3210 guint8 *buf, guint8 **endbuf)
3212 MonoJumpInfo *patches;
3218 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
3220 *got_slots = g_malloc (sizeof (guint32) * n_patches);
3222 for (pindex = 0; pindex < n_patches; ++pindex) {
3223 MonoJumpInfo *ji = &patches [pindex];
3228 got_offset = decode_value (p, &p);
3230 if (aot_module->got [got_offset]) {
3231 /* Already loaded */
3232 //printf ("HIT!\n");
3234 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
3236 ji->type = decode_value (shared_p, &shared_p);
3238 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
3243 (*got_slots) [pindex] = got_offset;
3250 g_free (*got_slots);
3257 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
3260 * Jump addresses cannot be patched by the trampoline code since it
3261 * does not have access to the caller's address. Instead, we collect
3262 * the addresses of the GOT slots pointing to a method, and patch
3263 * them after the method has been compiled.
3265 MonoJitDomainInfo *info = domain_jit_info (domain);
3268 mono_domain_lock (domain);
3269 if (!info->jump_target_got_slot_hash)
3270 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
3271 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
3272 list = g_slist_prepend (list, got_slot);
3273 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
3274 mono_domain_unlock (domain);
3280 * Load the method identified by METHOD_INDEX from the AOT image. Return a
3281 * pointer to the native code of the method, or NULL if not found.
3282 * METHOD might not be set if the caller only has the image/token info.
3285 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
3288 gboolean from_plt = method == NULL;
3290 int i, pindex, n_patches, used_strings;
3291 gboolean keep_patches = TRUE;
3293 MonoJitInfo *jinfo = NULL;
3294 guint8 *code, *info;
3296 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
3299 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
3300 /* Non shared AOT code can't be used in other appdomains */
3303 if (amodule->out_of_date)
3306 if (amodule->code_offsets [method_index] == 0xffffffff) {
3307 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3311 method = mono_get_method (image, token, NULL);
3312 full_name = mono_method_full_name (method, TRUE);
3313 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3319 code = &amodule->code [amodule->code_offsets [method_index]];
3321 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
3323 if (amodule->thumb_end && code < amodule->thumb_end && ((amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) == 0)) {
3324 /* Convert this into a thumb address */
3325 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
3326 code = &amodule->code [amodule->code_offsets [method_index] + 1];
3329 if (!amodule->methods_loaded) {
3330 amodule_lock (amodule);
3331 if (!amodule->methods_loaded) {
3334 loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
3335 mono_memory_barrier ();
3336 amodule->methods_loaded = loaded;
3338 amodule_unlock (amodule);
3341 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
3344 if (mono_last_aot_method != -1) {
3345 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
3347 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
3349 method = mono_get_method (image, token, NULL);
3351 char *name = mono_method_full_name (method, TRUE);
3352 printf ("LAST AOT METHOD: %s.\n", name);
3355 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
3363 klass = method->klass;
3364 decode_klass_ref (amodule, p, &p);
3366 klass = decode_klass_ref (amodule, p, &p);
3369 if (amodule->info.opts & MONO_OPT_SHARED)
3370 used_strings = decode_value (p, &p);
3374 for (i = 0; i < used_strings; i++) {
3375 guint token = decode_value (p, &p);
3376 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
3379 if (amodule->info.opts & MONO_OPT_SHARED)
3380 keep_patches = FALSE;
3382 n_patches = decode_value (p, &p);
3384 keep_patches = FALSE;
3387 MonoJumpInfo *patches;
3393 mp = mono_mempool_new ();
3395 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3396 if (patches == NULL)
3399 for (pindex = 0; pindex < n_patches; ++pindex) {
3400 MonoJumpInfo *ji = &patches [pindex];
3402 if (!amodule->got [got_slots [pindex]]) {
3403 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
3404 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3405 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
3406 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3407 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
3409 ji->type = MONO_PATCH_INFO_NONE;
3415 mono_mempool_destroy (mp);
3418 if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
3419 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3421 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3425 method = mono_get_method (image, token, NULL);
3427 full_name = mono_method_full_name (method, TRUE);
3430 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3432 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
3436 amodule_lock (amodule);
3438 InterlockedIncrement (&mono_jit_stats.methods_aot);
3440 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
3444 if (method && method->wrapper_type)
3445 g_hash_table_insert (amodule->method_to_code, method, code);
3447 amodule_unlock (amodule);
3449 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3453 method = mono_get_method (image, token, NULL);
3456 mono_profiler_method_jit (method);
3457 jinfo = mono_jit_info_table_find (domain, (char*)code);
3459 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3462 if (from_plt && klass && !klass->generic_container)
3463 mono_runtime_class_init (mono_class_vtable (domain, klass));
3468 /* FIXME: The space in domain->mp is wasted */
3469 if (amodule->info.opts & MONO_OPT_SHARED)
3470 /* No need to cache patches */
3471 mono_mempool_destroy (mp);
3480 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
3482 guint32 table_size, entry_size, hash;
3483 guint32 *table, *entry;
3485 static guint32 n_extra_decodes;
3487 if (!amodule || amodule->out_of_date)
3490 table_size = amodule->extra_method_table [0];
3491 table = amodule->extra_method_table + 1;
3494 hash = mono_aot_method_hash (method) % table_size;
3496 entry = &table [hash * entry_size];
3503 guint32 key = entry [0];
3504 guint32 value = entry [1];
3505 guint32 next = entry [entry_size - 1];
3509 p = amodule->blob + key;
3512 amodule_lock (amodule);
3513 if (!amodule->method_ref_to_method)
3514 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3515 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3516 amodule_unlock (amodule);
3518 m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3520 amodule_lock (amodule);
3521 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3522 amodule_unlock (amodule);
3530 /* Special case: wrappers of shared generic methods */
3531 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3532 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3533 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3534 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3536 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3542 /* Methods decoded needlessly */
3544 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3549 entry = &table [next * entry_size];
3558 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3560 g_ptr_array_add ((GPtrArray*)user_data, value);
3564 * find_extra_method:
3566 * Try finding METHOD in the extra_method table in all AOT images.
3567 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3568 * module where the method was found.
3571 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3577 /* Try the method's module first */
3578 *out_amodule = method->klass->image->aot_module;
3579 index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
3580 if (index != 0xffffff)
3584 * Try all other modules.
3585 * This is needed because generic instances klass->image points to the image
3586 * containing the generic definition, but the native code is generated to the
3587 * AOT image which contains the reference.
3590 /* Make a copy to avoid doing the search inside the aot lock */
3591 modules = g_ptr_array_new ();
3593 g_hash_table_foreach (aot_modules, add_module_cb, modules);
3597 for (i = 0; i < modules->len; ++i) {
3598 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3600 if (amodule != method->klass->image->aot_module)
3601 index = find_extra_method_in_amodule (amodule, method);
3602 if (index != 0xffffff) {
3603 *out_amodule = amodule;
3608 g_ptr_array_free (modules, TRUE);
3614 * mono_aot_get_method:
3616 * Return a pointer to the AOTed native code for METHOD if it can be found,
3618 * On platforms with function pointers, this doesn't return a function pointer.
3621 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3623 MonoClass *klass = method->klass;
3624 guint32 method_index;
3625 MonoAotModule *amodule = klass->image->aot_module;
3631 if (amodule->out_of_date)
3634 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3635 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3636 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3637 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3641 * Use the original method instead of its invoke-with-check wrapper.
3642 * This is not a problem when using full-aot, since it doesn't support
3645 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3646 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3648 g_assert (klass->inited);
3650 /* Find method index */
3651 method_index = 0xffffff;
3652 if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
3654 * For generic methods, we store the fully shared instance in place of the
3657 method = mono_method_get_declaring_generic_method (method);
3658 method_index = mono_metadata_token_index (method->token) - 1;
3659 } else if (method->is_inflated || !method->token) {
3660 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3661 amodule_lock (amodule);
3662 code = g_hash_table_lookup (amodule->method_to_code, method);
3663 amodule_unlock (amodule);
3667 method_index = find_extra_method (method, &amodule);
3669 * Special case the ICollection<T> wrappers for arrays, as they cannot
3670 * be statically enumerated, and each wrapper ends up calling the same
3673 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3674 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3676 code = mono_aot_get_method (domain, m);
3682 * Special case Array.GetGenericValueImpl which is a generic icall.
3683 * Generic sharing currently can't handle it, but the icall returns data using
3684 * an out parameter, so the managed-to-native wrappers can share the same code.
3686 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3688 MonoGenericContext ctx;
3689 MonoType *args [16];
3691 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3692 /* Avoid recursion */
3695 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3698 memset (&ctx, 0, sizeof (ctx));
3699 args [0] = &mono_defaults.object_class->byval_arg;
3700 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3702 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3705 * Get the code for the <object> instantiation which should be emitted into
3706 * the mscorlib aot image by the AOT compiler.
3708 code = mono_aot_get_method (domain, m);
3713 /* Same for CompareExchange<T> and Exchange<T> */
3714 /* Same for Volatile.Read<T>/Write<T> */
3715 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib &&
3716 ((!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])) ||
3717 (!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))) ||
3718 (!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]))))) {
3720 MonoGenericContext ctx;
3721 MonoType *args [16];
3722 gpointer iter = NULL;
3724 while ((m = mono_class_get_methods (method->klass, &iter))) {
3725 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3730 memset (&ctx, 0, sizeof (ctx));
3731 args [0] = &mono_defaults.object_class->byval_arg;
3732 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3734 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3736 /* Avoid recursion */
3741 * Get the code for the <object> instantiation which should be emitted into
3742 * the mscorlib aot image by the AOT compiler.
3744 code = mono_aot_get_method (domain, m);
3749 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
3750 /* Partial sharing */
3753 shared = mini_get_shared_method (method);
3754 method_index = find_extra_method (shared, &amodule);
3755 if (method_index != 0xffffff)
3759 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
3761 /* Use the all-vt shared method since this is what was AOTed */
3762 method_index = find_extra_method (mini_get_shared_method_full (method, TRUE, TRUE), &amodule);
3763 if (method_index != 0xffffff)
3764 method = mini_get_shared_method_full (method, TRUE, FALSE);
3767 if (method_index == 0xffffff) {
3768 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3771 full_name = mono_method_full_name (method, TRUE);
3772 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3778 if (method_index == 0xffffff)
3781 /* Needed by find_jit_info */
3782 amodule_lock (amodule);
3783 if (!amodule->extra_methods)
3784 amodule->extra_methods = g_hash_table_new (NULL, NULL);
3785 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3786 amodule_unlock (amodule);
3789 method_index = mono_metadata_token_index (method->token) - 1;
3792 return load_method (domain, amodule, klass->image, method, method->token, method_index);
3796 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3800 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3802 MonoAotModule *aot_module = image->aot_module;
3808 method_index = mono_metadata_token_index (token) - 1;
3810 return load_method (domain, aot_module, image, NULL, token, method_index);
3816 } IsGotEntryUserData;
3819 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3821 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3822 MonoAotModule *aot_module = (MonoAotModule*)value;
3824 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3829 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3831 IsGotEntryUserData user_data;
3836 user_data.addr = addr;
3837 user_data.res = FALSE;
3839 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3842 return user_data.res;
3847 MonoAotModule *module;
3848 } FindAotModuleUserData;
3851 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3853 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3854 MonoAotModule *aot_module = (MonoAotModule*)value;
3856 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3857 data->module = aot_module;
3860 static inline MonoAotModule*
3861 find_aot_module (guint8 *code)
3863 FindAotModuleUserData user_data;
3868 /* Reading these need no locking */
3869 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3872 user_data.addr = code;
3873 user_data.module = NULL;
3876 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3879 return user_data.module;
3883 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3886 * Since AOT code is only used in the root domain,
3887 * mono_domain_get () != mono_get_root_domain () means the calling method
3888 * is AppDomain:InvokeInDomain, so this is the same check as in
3889 * mono_method_same_domain () but without loading the metadata for the method.
3891 if (mono_domain_get () == mono_get_root_domain ())
3892 mono_arch_patch_plt_entry (code, got, regs, addr);
3896 * mono_aot_plt_resolve:
3898 * This function is called by the entries in the PLT to resolve the actual method that
3899 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3900 * Returns NULL if the something cannot be loaded.
3903 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3905 #ifdef MONO_ARCH_AOT_SUPPORTED
3906 guint8 *p, *target, *plt_entry;
3908 MonoAotModule *module = (MonoAotModule*)aot_module;
3909 gboolean res, no_ftnptr = FALSE;
3911 gboolean using_gsharedvt = FALSE;
3913 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3915 p = &module->blob [plt_info_offset];
3917 ji.type = decode_value (p, &p);
3919 mp = mono_mempool_new_size (512);
3920 res = decode_patch (module, mp, &ji, p, &p);
3923 mono_mempool_destroy (mp);
3927 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3928 using_gsharedvt = TRUE;
3932 * Avoid calling resolve_patch_target in the full-aot case if possible, since
3933 * it would create a trampoline, and we don't need that.
3934 * We could do this only if the method does not need the special handling
3935 * in mono_magic_trampoline ().
3937 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) &&
3938 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
3939 target = mono_jit_compile_method (ji.data.method);
3942 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3946 * The trampoline expects us to return a function descriptor on platforms which use
3947 * it, but resolve_patch_target returns a direct function pointer for some type of
3948 * patches, so have to translate between the two.
3949 * FIXME: Clean this up, but how ?
3951 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) {
3952 /* These should already have a function descriptor */
3953 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3954 /* Our function descriptors have a 0 environment, gcc created ones don't */
3955 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3956 g_assert (((gpointer*)target) [2] == 0);
3959 } else if (!no_ftnptr) {
3960 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3961 g_assert (((gpointer*)target) [2] != 0);
3963 target = mono_create_ftnptr (mono_domain_get (), target);
3966 mono_mempool_destroy (mp);
3968 /* Patch the PLT entry with target which might be the actual method not a trampoline */
3969 plt_entry = mono_aot_get_plt_entry (code);
3970 g_assert (plt_entry);
3971 mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3975 g_assert_not_reached ();
3983 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
3984 * method in the module is loaded to avoid committing memory by writing to it.
3985 * LOCKING: Assumes the AMODULE lock is held.
3988 init_plt (MonoAotModule *amodule)
3993 if (amodule->plt_inited)
3996 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3999 * Initialize the PLT entries in the GOT to point to the default targets.
4002 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
4003 for (i = 1; i < amodule->info.plt_size; ++i)
4004 /* All the default entries point to the AOT trampoline */
4005 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
4007 amodule->plt_inited = TRUE;
4011 * mono_aot_get_plt_entry:
4013 * Return the address of the PLT entry called by the code at CODE if exists.
4016 mono_aot_get_plt_entry (guint8 *code)
4018 MonoAotModule *amodule = find_aot_module (code);
4019 guint8 *target = NULL;
4025 if (amodule->thumb_end && code < amodule->thumb_end) {
4026 return mono_arm_get_thumb_plt_entry (code);
4030 #ifdef MONO_ARCH_AOT_SUPPORTED
4031 target = mono_arch_get_call_target (code);
4033 g_assert_not_reached ();
4037 while (target != NULL) {
4038 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
4041 // Add 4 since mono_arch_get_call_target assumes we're passing
4042 // the instruction after the actual branch instruction.
4043 target = mono_arch_get_call_target (target + 4);
4048 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
4056 * mono_aot_get_plt_info_offset:
4058 * Return the PLT info offset belonging to the plt entry called by CODE.
4061 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4063 guint8 *plt_entry = mono_aot_get_plt_entry (code);
4065 g_assert (plt_entry);
4067 /* The offset is embedded inside the code after the plt entry */
4068 #ifdef MONO_ARCH_AOT_SUPPORTED
4069 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
4071 g_assert_not_reached ();
4077 mono_create_ftnptr_malloc (guint8 *code)
4079 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4080 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
4082 ftnptr->code = code;
4093 * mono_aot_register_jit_icall:
4095 * Register a JIT icall which is called by trampolines in full-aot mode. This should
4096 * be called from mono_arch_init () during startup.
4099 mono_aot_register_jit_icall (const char *name, gpointer addr)
4101 /* No need for locking */
4102 if (!aot_jit_icall_hash)
4103 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
4104 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
4108 * load_function_full:
4110 * Load the function named NAME from the aot image.
4113 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
4117 int n_patches, pindex;
4120 guint32 info_offset;
4124 symbol = g_strdup_printf ("%s", name);
4125 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
4128 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
4130 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
4134 symbol = g_strdup_printf ("%s_p", name);
4135 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
4138 /* Nothing to patch */
4141 info_offset = *(guint32*)p;
4143 MonoTrampInfo *tinfo;
4144 guint32 code_size, uw_info_len, uw_offset;
4146 /* Construct a MonoTrampInfo from the data in the AOT image */
4148 p += sizeof (guint32);
4149 code_size = *(guint32*)p;
4150 p += sizeof (guint32);
4151 uw_offset = *(guint32*)p;
4152 uw_info = amodule->unwind_info + uw_offset;
4153 uw_info_len = decode_value (uw_info, &uw_info);
4155 tinfo = g_new0 (MonoTrampInfo, 1);
4157 tinfo->code_size = code_size;
4158 tinfo->uw_info = uw_info;
4159 tinfo->uw_info_len = uw_info_len;
4164 p = amodule->blob + info_offset;
4166 /* Similar to mono_aot_load_method () */
4168 n_patches = decode_value (p, &p);
4171 MonoJumpInfo *patches;
4174 mp = mono_mempool_new ();
4176 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
4179 for (pindex = 0; pindex < n_patches; ++pindex) {
4180 MonoJumpInfo *ji = &patches [pindex];
4183 if (amodule->got [got_slots [pindex]])
4187 * When this code is executed, the runtime may not be initalized yet, so
4188 * resolve the patch info by hand.
4190 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4191 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
4192 target = mono_get_lmf_addr;
4193 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
4194 target = mono_thread_force_interruption_checkpoint;
4195 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
4196 target = mono_exception_from_token;
4197 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
4198 target = mono_get_throw_exception ();
4199 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
4200 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
4201 target = (gpointer)mono_get_trampoline_func (tramp_type2);
4202 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
4203 /* atoll is needed because the the offset is unsigned */
4207 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
4208 g_assert (res == 1);
4209 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4210 target = mono_create_ftnptr_malloc (target);
4211 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
4212 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
4213 target = mono_create_ftnptr_malloc (target);
4214 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
4215 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
4216 target = mono_create_ftnptr_malloc (target);
4217 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
4218 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
4219 target = mono_create_ftnptr_malloc (target);
4220 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
4221 target = mono_thread_get_and_clear_pending_exception;
4222 } else if (strstr (ji->data.name, "generic_trampoline_")) {
4223 target = mono_aot_get_trampoline (ji->data.name);
4224 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
4225 /* Registered by mono_arch_init () */
4226 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
4228 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
4229 g_assert_not_reached ();
4233 /* Hopefully the code doesn't have patches which need method or
4236 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
4240 amodule->got [got_slots [pindex]] = target;
4245 mono_mempool_destroy (mp);
4252 load_function (MonoAotModule *amodule, const char *name)
4254 return load_function_full (amodule, name, NULL);
4258 * Return the trampoline identified by NAME from the mscorlib AOT file.
4259 * On ppc64, this returns a function descriptor.
4262 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
4265 MonoAotModule *amodule;
4267 image = mono_defaults.corlib;
4270 amodule = image->aot_module;
4273 return mono_create_ftnptr_malloc (load_function_full (amodule, name, out_tinfo));
4277 mono_aot_get_trampoline (const char *name)
4279 return mono_aot_get_trampoline_full (name, NULL);
4283 #include <mach/mach.h>
4285 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
4286 /* these sizes are for ARM code, parametrize if porting to other architectures (see arch_emit_specific_trampoline_pages)
4287 * trampoline size is assumed to be 8 bytes below as well (8 is the minimum for 32 bit archs, since we need to store
4288 * two pointers for trampoline in the data page).
4289 * the minimum for the common code must be at least sizeof(TrampolinePage), since we store the page info at the
4290 * beginning of the data page.
4292 static const int trampolines_pages_code_offsets [MONO_AOT_TRAMP_NUM] = {16, 16, 72, 16};
4294 static unsigned char*
4295 get_new_trampoline_from_page (int tramp_type)
4297 MonoAotModule *amodule;
4299 TrampolinePage *page;
4302 vm_address_t addr, taddr;
4304 vm_prot_t prot, max_prot;
4305 int psize, specific_trampoline_size;
4306 unsigned char *code;
4308 specific_trampoline_size = 2 * sizeof (gpointer);
4310 mono_aot_page_lock ();
4311 page = trampoline_pages [tramp_type];
4312 if (page && page->trampolines < page->trampolines_end) {
4313 code = page->trampolines;
4314 page->trampolines += specific_trampoline_size;
4315 mono_aot_page_unlock ();
4318 mono_aot_page_unlock ();
4319 psize = mono_pagesize ();
4320 /* the trampoline template page is in the mscorlib module */
4321 image = mono_defaults.corlib;
4324 amodule = image->aot_module;
4327 g_assert (amodule->info.tramp_page_size == psize);
4329 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
4330 tpage = load_function (amodule, "specific_trampolines_page");
4331 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
4332 tpage = load_function (amodule, "rgctx_trampolines_page");
4333 else if (tramp_type == MONO_AOT_TRAMP_IMT_THUNK)
4334 tpage = load_function (amodule, "imt_trampolines_page");
4335 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
4336 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
4338 g_error ("Incorrect tramp type for trampolines page");
4340 /*g_warning ("loaded trampolines page at %x", tpage);*/
4342 /* avoid the unlikely case of looping forever */
4345 while (page == NULL && count-- > 0) {
4347 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
4348 * while the second will contain the trampolines.
4350 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
4351 if (ret != KERN_SUCCESS) {
4352 g_error ("Cannot allocate memory for trampolines: %d", ret);
4355 /*g_warning ("allocated trampoline double page at %x", addr);*/
4356 /* replace the second page with a remapped trampoline page */
4357 taddr = addr + psize;
4358 vm_deallocate (mach_task_self (), taddr, psize);
4359 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
4360 if (ret != KERN_SUCCESS) {
4361 /* someone else got the page, try again */
4362 vm_deallocate (mach_task_self (), addr, psize);
4365 /*g_warning ("remapped trampoline page at %x", taddr);*/
4367 mono_aot_page_lock ();
4368 page = trampoline_pages [tramp_type];
4369 /* some other thread already allocated, so use that to avoid wasting memory */
4370 if (page && page->trampolines < page->trampolines_end) {
4371 code = page->trampolines;
4372 page->trampolines += specific_trampoline_size;
4373 mono_aot_page_unlock ();
4374 vm_deallocate (mach_task_self (), addr, psize);
4375 vm_deallocate (mach_task_self (), taddr, psize);
4378 page = (TrampolinePage*)addr;
4379 page->next = trampoline_pages [tramp_type];
4380 trampoline_pages [tramp_type] = page;
4381 page->trampolines = (void*)(taddr + trampolines_pages_code_offsets [tramp_type]);
4382 page->trampolines_end = (void*)(taddr + psize);
4383 code = page->trampolines;
4384 page->trampolines += 8;
4385 mono_aot_page_unlock ();
4388 g_error ("Cannot allocate more trampoline pages: %d", ret);
4393 static unsigned char*
4394 get_new_trampoline_from_page (int tramp_type)
4396 g_error ("Page trampolines not supported.");
4403 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
4408 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
4410 data = (gpointer*)((char*)code - mono_pagesize ());
4413 /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4419 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
4424 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
4426 data = (gpointer*)((char*)code - mono_pagesize ());
4429 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4435 get_new_imt_trampoline_from_page (gpointer arg)
4440 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT_THUNK);
4442 data = (gpointer*)((char*)code - mono_pagesize ());
4444 /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
4450 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
4455 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
4457 data = (gpointer*)((char*)code - mono_pagesize ());
4460 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4464 /* Return a given kind of trampoline */
4466 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
4468 MonoAotModule *amodule;
4469 int index, tramp_size;
4472 /* Currently, we keep all trampolines in the mscorlib AOT image */
4473 image = mono_defaults.corlib;
4478 amodule = image->aot_module;
4481 *out_amodule = amodule;
4484 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
4486 #define MONOTOUCH_TRAMPOLINES_ERROR ""
4488 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
4489 g_error ("Ran out of trampolines of type %d in '%s' (%d)%s\n",
4490 tramp_type, image->name, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
4492 index = amodule->trampoline_index [tramp_type] ++;
4496 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
4498 tramp_size = amodule->info.trampoline_size [tramp_type];
4501 *out_tramp_size = tramp_size;
4503 return amodule->trampolines [tramp_type] + (index * tramp_size);
4507 * Return a specific trampoline from the AOT file.
4510 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4512 MonoAotModule *amodule;
4513 guint32 got_offset, tramp_size;
4514 guint8 *code, *tramp;
4515 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
4516 static gboolean inited;
4517 static guint32 num_trampolines;
4523 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
4532 if (!generic_trampolines [tramp_type]) {
4535 symbol = mono_get_generic_trampoline_name (tramp_type);
4536 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
4540 tramp = generic_trampolines [tramp_type];
4543 if (USE_PAGE_TRAMPOLINES) {
4544 code = get_new_specific_trampoline_from_page (tramp, arg1);
4547 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
4549 amodule->got [got_offset] = tramp;
4550 amodule->got [got_offset + 1] = arg1;
4554 *code_len = tramp_size;
4560 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4562 MonoAotModule *amodule;
4566 if (USE_PAGE_TRAMPOLINES) {
4567 code = get_new_rgctx_trampoline_from_page (addr, ctx);
4569 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
4571 amodule->got [got_offset] = ctx;
4572 amodule->got [got_offset + 1] = addr;
4575 /* The caller expects an ftnptr */
4576 return mono_create_ftnptr (mono_domain_get (), code);
4580 mono_aot_get_unbox_trampoline (MonoMethod *method)
4582 guint32 method_index = mono_metadata_token_index (method->token) - 1;
4583 MonoAotModule *amodule;
4585 guint32 *ut, *ut_end, *entry;
4586 int low, high, entry_index;
4588 if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
4589 method_index = find_extra_method (method, &amodule);
4590 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4591 MonoMethod *shared = mini_get_shared_method_full (method, TRUE, TRUE);
4592 method_index = find_extra_method (shared, &amodule);
4594 g_assert (method_index != 0xffffff);
4596 amodule = method->klass->image->aot_module;
4600 ut = amodule->unbox_trampolines;
4601 ut_end = amodule->unbox_trampolines_end;
4603 /* Do a binary search in the sorted table */
4606 high = (ut_end - ut) / 2;
4607 while (low < high) {
4608 entry_index = (low + high) / 2;
4609 entry = &ut [(entry_index * 2)];
4610 if (entry [0] < method_index) {
4611 low = entry_index + 1;
4612 } else if (entry [0] > method_index) {
4615 if (amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES)
4616 code = get_arm_bl_target (entry + 1);
4618 code = amodule->code + entry [1];
4624 /* The caller expects an ftnptr */
4625 return mono_create_ftnptr (mono_domain_get (), code);
4629 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4633 MonoAotModule *amodule = mono_defaults.corlib->aot_module;
4634 guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
4635 static int count = 0;
4638 if (index >= amodule->info.num_rgctx_fetch_trampolines) {
4639 static gpointer addr;
4643 * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
4646 addr = load_function (amodule, "rgctx_fetch_trampoline_general");
4647 info = mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
4648 info [0] = GUINT_TO_POINTER (slot);
4649 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4650 code = mono_aot_get_static_rgctx_trampoline (info, addr);
4651 return mono_create_ftnptr (mono_domain_get (), code);
4654 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
4655 code = load_function (mono_defaults.corlib->aot_module, symbol);
4657 /* The caller expects an ftnptr */
4658 return mono_create_ftnptr (mono_domain_get (), code);
4662 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4667 int i, index, real_count;
4668 MonoAotModule *amodule;
4671 for (i = 0; i < count; ++i) {
4672 MonoIMTCheckItem *item = imt_entries [i];
4674 if (item->is_equals)
4678 /* Save the entries into an array */
4679 buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
4681 for (i = 0; i < count; ++i) {
4682 MonoIMTCheckItem *item = imt_entries [i];
4684 if (!item->is_equals)
4687 g_assert (item->key);
4689 buf [(index * 2)] = item->key;
4690 if (item->has_target_code) {
4691 gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
4692 *p = item->value.target_code;
4693 buf [(index * 2) + 1] = p;
4695 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
4699 buf [(index * 2)] = NULL;
4700 buf [(index * 2) + 1] = fail_tramp;
4702 if (USE_PAGE_TRAMPOLINES) {
4703 code = get_new_imt_trampoline_from_page (buf);
4705 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
4707 amodule->got [got_offset] = buf;
4714 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
4716 MonoAotModule *amodule;
4720 if (USE_PAGE_TRAMPOLINES) {
4721 code = get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
4723 code = get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
4725 amodule->got [got_offset] = arg;
4726 amodule->got [got_offset + 1] = addr;
4729 /* The caller expects an ftnptr */
4730 return mono_create_ftnptr (mono_domain_get (), code);
4734 * mono_aot_set_make_unreadable:
4736 * Set whenever to make all mmaped memory unreadable. In conjuction with a
4737 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
4740 mono_aot_set_make_unreadable (gboolean unreadable)
4744 make_unreadable = unreadable;
4746 if (make_unreadable && !inited) {
4747 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
4752 MonoAotModule *module;
4757 find_map (gpointer key, gpointer value, gpointer user_data)
4759 MonoAotModule *module = (MonoAotModule*)value;
4760 FindMapUserData *data = (FindMapUserData*)user_data;
4763 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4764 data->module = module;
4767 static MonoAotModule*
4768 find_module_for_addr (void *ptr)
4770 FindMapUserData data;
4772 if (!make_unreadable)
4776 data.ptr = (guint8*)ptr;
4779 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4786 * mono_aot_is_pagefault:
4788 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4789 * within memory allocated by this module.
4792 mono_aot_is_pagefault (void *ptr)
4794 if (!make_unreadable)
4798 * Not signal safe, but SIGSEGV's are synchronous, and
4799 * this is only turned on by a MONO_DEBUG option.
4801 return find_module_for_addr (ptr) != NULL;
4805 * mono_aot_handle_pagefault:
4807 * Handle a pagefault caused by an unreadable page by making it readable again.
4810 mono_aot_handle_pagefault (void *ptr)
4812 #ifndef PLATFORM_WIN32
4813 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
4817 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
4818 g_assert (res == 0);
4829 mono_aot_init (void)
4834 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
4840 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4846 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4852 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
4858 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
4864 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
4870 mono_aot_get_plt_entry (guint8 *code)
4876 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4882 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
4887 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
4893 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4895 g_assert_not_reached ();
4901 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4903 g_assert_not_reached ();
4908 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4910 g_assert_not_reached ();
4915 mono_aot_get_trampoline (const char *name)
4917 g_assert_not_reached ();
4922 mono_aot_get_unbox_trampoline (MonoMethod *method)
4924 g_assert_not_reached ();
4929 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4931 g_assert_not_reached ();
4936 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4938 g_assert_not_reached ();
4943 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
4945 g_assert_not_reached ();
4950 mono_aot_register_jit_icall (const char *name, gpointer addr)