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_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
74 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
76 typedef struct MonoAotModule {
78 /* Pointer to the Global Offset Table */
80 GHashTable *name_cache;
81 GHashTable *extra_methods;
82 /* Maps methods to their code */
83 GHashTable *method_to_code;
84 /* Maps pointers into the method info to the methods themselves */
85 GHashTable *method_ref_to_method;
86 MonoAssemblyName *image_names;
88 MonoAssembly *assembly;
89 MonoImage **image_table;
90 guint32 image_table_len;
100 gint32 *code_offsets;
101 /* This contains <offset, index> pairs sorted by offset */
102 /* This is needed because LLVM emitted methods can be in any order */
103 gint32 *sorted_code_offsets;
104 gint32 sorted_code_offsets_len;
105 guint32 *method_info_offsets;
106 guint32 *got_info_offsets;
107 guint32 *ex_info_offsets;
108 guint32 *class_info_offsets;
109 guint32 *methods_loaded;
110 guint16 *class_name_table;
111 guint32 *extra_method_table;
112 guint32 *extra_method_info_offsets;
113 guint32 *unbox_trampolines;
114 guint32 *unbox_trampolines_end;
118 /* Points to the mono EH data created by LLVM */
119 guint8 *mono_eh_frame;
121 /* Points to the trampolines */
122 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
123 /* The first unused trampoline of each kind */
124 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
126 MonoAotFileInfo info;
132 static GHashTable *aot_modules;
133 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
134 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
135 static CRITICAL_SECTION aot_mutex;
138 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
139 * AOT modules registered by mono_aot_register_module ().
141 static GHashTable *static_aot_modules;
144 * Maps MonoJitInfo* to the aot module they belong to, this can be different
145 * from ji->method->klass->image's aot module for generic instances.
147 static GHashTable *ji_to_amodule;
150 * Whenever to AOT compile loaded assemblies on demand and store them in
151 * a cache under $HOME/.mono/aot-cache.
153 static gboolean use_aot_cache = FALSE;
156 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
157 * use_aot_cache is TRUE.
159 static gboolean spawn_compiler = TRUE;
162 static gint32 mono_last_aot_method = -1;
164 static gboolean make_unreadable = FALSE;
165 static guint32 name_table_accesses = 0;
166 static guint32 n_pagefaults = 0;
168 /* Used to speed-up find_aot_module () */
169 static gsize aot_code_low_addr = (gssize)-1;
170 static gsize aot_code_high_addr = 0;
172 static GHashTable *aot_jit_icall_hash;
175 init_plt (MonoAotModule *info);
177 /*****************************************************/
179 /*****************************************************/
184 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
185 * found, and sets the loader error if SET_ERROR is TRUE.
188 load_image (MonoAotModule *amodule, int index, gboolean set_error)
190 MonoAssembly *assembly;
191 MonoImageOpenStatus status;
193 g_assert (index < amodule->image_table_len);
195 if (amodule->image_table [index])
196 return amodule->image_table [index];
197 if (amodule->out_of_date)
200 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
202 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);
203 amodule->out_of_date = TRUE;
206 char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
207 mono_loader_set_error_assembly_load (full_name, FALSE);
213 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
214 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);
215 amodule->out_of_date = TRUE;
219 amodule->image_table [index] = assembly->image;
220 return assembly->image;
224 decode_value (guint8 *ptr, guint8 **rptr)
229 if ((b & 0x80) == 0){
232 } else if ((b & 0x40) == 0){
233 len = ((b & 0x3f) << 8 | ptr [1]);
235 } else if (b != 0xff) {
236 len = ((b & 0x1f) << 24) |
243 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
249 //printf ("DECODE: %d.\n", len);
254 * mono_aot_get_offset:
256 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
260 mono_aot_get_offset (guint32 *table, int index)
262 int i, group, ngroups, index_entry_size;
263 int start_offset, offset, noffsets, group_size;
264 guint8 *data_start, *p;
265 guint32 *index32 = NULL;
266 guint16 *index16 = NULL;
268 noffsets = table [0];
269 group_size = table [1];
271 index_entry_size = table [3];
272 group = index / group_size;
274 if (index_entry_size == 2) {
275 index16 = (guint16*)&table [4];
276 data_start = (guint8*)&index16 [ngroups];
277 p = data_start + index16 [group];
279 index32 = (guint32*)&table [4];
280 data_start = (guint8*)&index32 [ngroups];
281 p = data_start + index32 [group];
284 /* offset will contain the value of offsets [group * group_size] */
285 offset = start_offset = decode_value (p, &p);
286 for (i = group * group_size + 1; i <= index; ++i) {
287 offset += decode_value (p, &p);
290 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
296 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
299 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
302 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
304 static MonoGenericInst*
305 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
308 MonoType **type_argv;
309 MonoGenericInst *inst;
312 type_argc = decode_value (p, &p);
313 type_argv = g_new0 (MonoType*, type_argc);
315 for (i = 0; i < type_argc; ++i) {
316 MonoClass *pclass = decode_klass_ref (module, p, &p);
321 type_argv [i] = &pclass->byval_arg;
324 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
333 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
340 argc = decode_value (p, &p);
343 ctx->class_inst = decode_generic_inst (module, p, &p);
344 if (!ctx->class_inst)
348 argc = decode_value (p, &p);
351 ctx->method_inst = decode_generic_inst (module, p, &p);
352 if (!ctx->method_inst)
361 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
364 MonoClass *klass = NULL, *eklass;
365 guint32 token, rank, idx;
369 reftype = decode_value (p, &p);
376 case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
377 idx = decode_value (p, &p);
378 image = load_image (module, 0, TRUE);
381 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
383 case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
384 idx = decode_value (p, &p);
385 image = load_image (module, decode_value (p, &p), TRUE);
388 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
390 case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
391 token = decode_value (p, &p);
392 image = module->assembly->image;
395 klass = mono_class_get (image, token);
397 case MONO_AOT_TYPEREF_GINST: {
399 MonoGenericContext ctx;
402 gclass = decode_klass_ref (module, p, &p);
405 g_assert (gclass->generic_container);
407 memset (&ctx, 0, sizeof (ctx));
408 ctx.class_inst = decode_generic_inst (module, p, &p);
411 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
412 klass = mono_class_from_mono_type (type);
413 mono_metadata_free_type (type);
416 case MONO_AOT_TYPEREF_VAR: {
418 MonoGenericContainer *container;
419 int type = decode_value (p, &p);
420 int num = decode_value (p, &p);
421 gboolean is_method = decode_value (p, &p);
424 MonoMethod *method_def;
425 g_assert (type == MONO_TYPE_MVAR);
426 method_def = decode_resolve_method_ref (module, p, &p);
430 container = mono_method_get_generic_container (method_def);
432 MonoClass *class_def;
433 g_assert (type == MONO_TYPE_VAR);
434 class_def = decode_klass_ref (module, p, &p);
438 container = class_def->generic_container;
441 g_assert (container);
443 // FIXME: Memory management
444 t = g_new0 (MonoType, 1);
446 t->data.generic_param = mono_generic_container_get_param (container, num);
448 // FIXME: Maybe use types directly to avoid
449 // the overhead of creating MonoClass-es
450 klass = mono_class_from_mono_type (t);
455 case MONO_AOT_TYPEREF_ARRAY:
457 rank = decode_value (p, &p);
458 eklass = decode_klass_ref (module, p, &p);
459 klass = mono_array_class_get (eklass, rank);
461 case MONO_AOT_TYPEREF_PTR: {
464 t = decode_type (module, p, &p);
467 klass = mono_class_from_mono_type (t);
471 case MONO_AOT_TYPEREF_BLOB_INDEX: {
472 guint32 offset = decode_value (p, &p);
475 p2 = module->blob + offset;
476 klass = decode_klass_ref (module, p2, &p2);
480 g_assert_not_reached ();
483 //printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
488 static MonoClassField*
489 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
491 MonoClass *klass = decode_klass_ref (module, buf, &buf);
498 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
502 return mono_class_get_field (klass, token);
506 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
510 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
515 t = g_malloc0 (sizeof (MonoType));
518 if (*p == MONO_TYPE_PINNED) {
521 } else if (*p == MONO_TYPE_BYREF) {
534 case MONO_TYPE_BOOLEAN:
548 case MONO_TYPE_STRING:
549 case MONO_TYPE_OBJECT:
550 case MONO_TYPE_TYPEDBYREF:
552 case MONO_TYPE_VALUETYPE:
553 case MONO_TYPE_CLASS:
554 t->data.klass = decode_klass_ref (module, p, &p);
556 case MONO_TYPE_SZARRAY:
557 t->data.klass = decode_klass_ref (module, p, &p);
563 t->data.type = decode_type (module, p, &p);
565 case MONO_TYPE_GENERICINST: {
567 MonoGenericContext ctx;
571 gclass = decode_klass_ref (module, p, &p);
574 g_assert (gclass->generic_container);
576 memset (&ctx, 0, sizeof (ctx));
577 ctx.class_inst = decode_generic_inst (module, p, &p);
580 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
581 klass = mono_class_from_mono_type (type);
582 t->data.generic_class = klass->generic_class;
585 case MONO_TYPE_ARRAY: {
586 MonoArrayType *array;
589 // FIXME: memory management
590 array = g_new0 (MonoArrayType, 1);
591 array->eklass = decode_klass_ref (module, p, &p);
594 array->rank = decode_value (p, &p);
595 array->numsizes = decode_value (p, &p);
598 array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
599 for (i = 0; i < array->numsizes; ++i)
600 array->sizes [i] = decode_value (p, &p);
602 array->numlobounds = decode_value (p, &p);
603 if (array->numlobounds)
604 array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
605 for (i = 0; i < array->numlobounds; ++i)
606 array->lobounds [i] = decode_value (p, &p);
607 t->data.array = array;
611 g_assert_not_reached ();
619 // FIXME: Error handling, memory management
621 static MonoMethodSignature*
622 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
624 MonoMethodSignature *sig;
626 int i, param_count, call_conv;
628 gboolean hasthis, explicit_this, has_gen_params;
632 has_gen_params = (flags & 0x10) != 0;
633 hasthis = (flags & 0x20) != 0;
634 explicit_this = (flags & 0x40) != 0;
635 call_conv = flags & 0x0F;
637 g_assert (!has_gen_params);
639 param_count = decode_value (p, &p);
640 if (target && param_count != target->param_count)
642 sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
643 sig->param_count = param_count;
644 sig->sentinelpos = -1;
645 sig->hasthis = hasthis;
646 sig->explicit_this = explicit_this;
647 sig->call_convention = call_conv;
648 sig->param_count = param_count;
649 sig->ret = decode_type (module, p, &p);
650 for (i = 0; i < param_count; ++i) {
651 if (*p == MONO_TYPE_SENTINEL) {
652 g_assert (sig->call_convention == MONO_CALL_VARARG);
653 sig->sentinelpos = i;
656 sig->params [i] = decode_type (module, p, &p);
659 if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
660 sig->sentinelpos = sig->param_count;
667 static MonoMethodSignature*
668 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
670 return decode_signature_with_target (module, NULL, buf, endbuf);
674 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
676 MonoMethodSignature *sig;
680 sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
681 res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
687 /* Stores information returned by decode_method_ref () */
692 gboolean no_aot_trampoline;
696 * decode_method_ref_with_target:
698 * Decode a method reference, storing the image/token into a MethodRef structure.
699 * This avoids loading metadata for the method if the caller does not need it. If the method has
700 * no token, then it is loaded from metadata and ref->method is set to the method instance.
701 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
702 * couldn't resolve to TARGET, and return FALSE.
703 * There are some kinds of method references which only support a non-null TARGET.
704 * This means that its not possible to decode this into a method, only to check
705 * that the method reference matches a given method. This is normally not a problem
706 * as these wrappers only occur in the extra_methods table, where we already have
707 * a method we want to lookup.
710 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
712 guint32 image_index, value;
713 MonoImage *image = NULL;
716 memset (ref, 0, sizeof (MethodRef));
718 value = decode_value (p, &p);
719 image_index = value >> 24;
721 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
722 ref->no_aot_trampoline = TRUE;
723 value = decode_value (p, &p);
724 image_index = value >> 24;
727 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
728 if (target && target->wrapper_type)
732 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
733 guint32 wrapper_type;
735 wrapper_type = decode_value (p, &p);
737 if (target && target->wrapper_type != wrapper_type)
741 image = mono_defaults.corlib;
743 switch (wrapper_type) {
744 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
745 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
749 mono_class_init (m->klass);
750 ref->method = mono_marshal_get_remoting_invoke_with_check (m);
753 case MONO_WRAPPER_PROXY_ISINST: {
754 MonoClass *klass = decode_klass_ref (module, p, &p);
757 ref->method = mono_marshal_get_proxy_cancast (klass);
760 case MONO_WRAPPER_LDFLD:
761 case MONO_WRAPPER_LDFLDA:
762 case MONO_WRAPPER_STFLD:
763 case MONO_WRAPPER_ISINST: {
764 MonoClass *klass = decode_klass_ref (module, p, &p);
767 if (wrapper_type == MONO_WRAPPER_LDFLD)
768 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
769 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
770 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
771 else if (wrapper_type == MONO_WRAPPER_STFLD)
772 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
773 else if (wrapper_type == MONO_WRAPPER_ISINST)
774 ref->method = mono_marshal_get_isinst (klass);
776 g_assert_not_reached ();
779 case MONO_WRAPPER_LDFLD_REMOTE:
780 ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
782 case MONO_WRAPPER_STFLD_REMOTE:
783 ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
785 case MONO_WRAPPER_ALLOC: {
786 int atype = decode_value (p, &p);
788 ref->method = mono_gc_get_managed_allocator_by_type (atype);
789 g_assert (ref->method);
792 case MONO_WRAPPER_WRITE_BARRIER:
793 ref->method = mono_gc_get_write_barrier ();
795 case MONO_WRAPPER_STELEMREF: {
796 int subtype = decode_value (p, &p);
798 if (subtype == WRAPPER_SUBTYPE_NONE) {
799 ref->method = mono_marshal_get_stelemref ();
800 } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
804 kind = decode_value (p, &p);
806 /* Can't decode this */
809 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
810 info = mono_marshal_get_wrapper_info (target);
813 if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
814 ref->method = target;
821 g_assert_not_reached ();
825 case MONO_WRAPPER_SYNCHRONIZED: {
826 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
830 ref->method = mono_marshal_get_synchronized_wrapper (m);
833 case MONO_WRAPPER_UNKNOWN: {
834 MonoMethodDesc *desc;
835 MonoMethod *orig_method;
836 int subtype = decode_value (p, &p);
838 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
839 MonoClass *klass = decode_klass_ref (module, p, &p);
846 if (klass != target->klass)
849 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
850 if (strcmp (target->name, "PtrToStructure"))
852 ref->method = mono_marshal_get_ptr_to_struct (klass);
854 if (strcmp (target->name, "StructureToPtr"))
856 ref->method = mono_marshal_get_struct_to_ptr (klass);
858 } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
859 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
863 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
865 if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
866 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
867 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
868 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
869 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
870 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
872 g_assert_not_reached ();
873 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
874 g_assert (orig_method);
875 mono_method_desc_free (desc);
876 ref->method = mono_monitor_get_fast_path (orig_method);
880 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
881 int subtype = decode_value (p, &p);
883 if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
884 int rank = decode_value (p, &p);
885 int elem_size = decode_value (p, &p);
887 ref->method = mono_marshal_get_array_address (rank, elem_size);
888 } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
892 m = decode_resolve_method_ref (module, p, &p);
898 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
900 info = mono_marshal_get_wrapper_info (target);
901 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
902 ref->method = target;
908 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
910 int subtype = decode_value (p, &p);
913 if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
918 if (strcmp (target->name, name) != 0)
920 ref->method = target;
922 m = decode_resolve_method_ref (module, p, &p);
927 /* This should only happen when looking for an extra method */
930 if (mono_marshal_method_from_wrapper (target) == m)
931 ref->method = target;
937 case MONO_WRAPPER_CASTCLASS: {
938 int subtype = decode_value (p, &p);
940 if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
941 ref->method = mono_marshal_get_castclass_with_cache ();
942 else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
943 ref->method = mono_marshal_get_isinst_with_cache ();
945 g_assert_not_reached ();
948 case MONO_WRAPPER_RUNTIME_INVOKE: {
949 int subtype = decode_value (p, &p);
954 if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
955 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
957 ref->method = target;
958 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
960 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
964 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
965 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
966 /* Virtual direct wrapper */
967 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
971 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
973 if (sig_matches_target (module, target, p, &p))
974 ref->method = target;
980 case MONO_WRAPPER_DELEGATE_INVOKE:
981 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
982 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
984 * These wrappers are associated with a signature, not with a method.
985 * Since we can't decode them into methods, they need a target method.
990 if (sig_matches_target (module, target, p, &p))
991 ref->method = target;
996 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1000 m = decode_resolve_method_ref (module, p, &p);
1003 klass = decode_klass_ref (module, p, &p);
1006 ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
1010 g_assert_not_reached ();
1012 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1013 image_index = decode_value (p, &p);
1014 ref->token = decode_value (p, &p);
1016 image = load_image (module, image_index, TRUE);
1019 } else if (image_index == MONO_AOT_METHODREF_GINST) {
1021 MonoGenericContext ctx;
1024 * These methods do not have a token which resolves them, so we
1025 * resolve them immediately.
1027 klass = decode_klass_ref (module, p, &p);
1031 if (target && target->klass != klass)
1034 image_index = decode_value (p, &p);
1035 ref->token = decode_value (p, &p);
1037 image = load_image (module, image_index, TRUE);
1041 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
1045 memset (&ctx, 0, sizeof (ctx));
1047 if (FALSE && klass->generic_class) {
1048 ctx.class_inst = klass->generic_class->context.class_inst;
1049 ctx.method_inst = NULL;
1051 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1054 memset (&ctx, 0, sizeof (ctx));
1056 if (!decode_generic_context (module, &ctx, p, &p))
1059 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1060 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1064 klass = decode_klass_ref (module, p, &p);
1067 method_type = decode_value (p, &p);
1068 switch (method_type) {
1070 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
1073 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
1076 ref->method = mono_class_get_method_from_name (klass, "Get", -1);
1079 ref->method = mono_class_get_method_from_name (klass, "Address", -1);
1082 ref->method = mono_class_get_method_from_name (klass, "Set", -1);
1085 g_assert_not_reached ();
1088 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1089 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1091 image = load_image (module, image_index, TRUE);
1104 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
1106 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
1110 * decode_resolve_method_ref_with_target:
1112 * Similar to decode_method_ref, but resolve and return the method itself.
1115 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
1120 res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
1127 return mono_get_method (ref.image, ref.token, NULL);
1131 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
1133 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
1137 create_cache_structure (void)
1143 home = g_get_home_dir ();
1147 tmp = g_build_filename (home, ".mono", NULL);
1148 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1149 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1153 err = mkdir (tmp, 0777);
1156 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1162 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
1163 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1164 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1168 err = mkdir (tmp, 0777);
1171 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1180 * load_aot_module_from_cache:
1182 * Experimental code to AOT compile loaded assemblies on demand.
1185 * - Add environment variable MONO_AOT_CACHE_OPTIONS
1186 * - Add options for controlling the cache size
1187 * - Handle full cache by deleting old assemblies lru style
1188 * - Add options for excluding assemblies during development
1189 * - Maybe add a threshold after an assembly is AOT compiled
1190 * - invoking a new mono process is a security risk
1191 * - recompile the AOT module if one of its dependencies changes
1194 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
1196 char *fname, *cmd, *tmp2, *aot_options;
1205 if (assembly->image->dynamic)
1208 create_cache_structure ();
1210 home = g_get_home_dir ();
1212 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
1213 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
1217 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
1218 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1221 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
1223 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
1225 aot_options = g_strdup_printf ("outfile=%s", fname);
1227 if (spawn_compiler) {
1228 /* FIXME: security */
1229 /* FIXME: Has to pass the assembly loading path to the child process */
1230 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
1232 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1234 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
1236 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1237 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
1239 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1246 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1248 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
1250 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1254 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1256 g_free (aot_options);
1263 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1267 guint16 *table, *entry;
1271 /* The first entry points to the hash */
1272 table = globals [0];
1275 table_size = table [0];
1278 hash = mono_metadata_str_hash (name) % table_size;
1280 entry = &table [hash * 2];
1282 /* Search the hash for the index into the globals table */
1284 while (entry [0] != 0) {
1285 guint32 index = entry [0] - 1;
1286 guint32 next = entry [1];
1288 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1290 if (!strcmp (globals [index * 2], name)) {
1291 global_index = index;
1296 entry = &table [next * 2];
1302 if (global_index != -1)
1303 *value = globals [global_index * 2 + 1];
1307 char *err = mono_dl_symbol (module, name, value);
1315 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
1319 gboolean usable = TRUE;
1322 guint32 excluded_cpu_optimizations;
1324 if (strcmp (assembly->image->guid, info->assembly_guid)) {
1325 msg = g_strdup_printf ("doesn't match assembly");
1329 build_info = mono_get_runtime_build_info ();
1330 if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1331 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1334 g_free (build_info);
1336 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1338 if (mono_aot_only && !full_aot) {
1339 msg = g_strdup_printf ("not compiled with --aot=full");
1342 if (!mono_aot_only && full_aot) {
1343 msg = g_strdup_printf ("compiled with --aot=full");
1347 /* mono_arch_find_imt_method () requires this */
1348 if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1349 msg = g_strdup_printf ("compiled against LLVM");
1352 if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1353 msg = g_strdup_printf ("not compiled against LLVM");
1357 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1358 msg = g_strdup_printf ("not compiled for debugging");
1362 mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1363 if (info->opts & excluded_cpu_optimizations) {
1364 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1368 if (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ()) {
1369 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1375 if (info->gc_name_index != -1) {
1376 char *gc_name = (char*)&blob [info->gc_name_index];
1377 const char *current_gc_name = mono_gc_get_gc_name ();
1379 if (strcmp (current_gc_name, gc_name) != 0) {
1380 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1390 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1393 MonoAotModule *amodule;
1395 gboolean usable = TRUE;
1396 char *version_symbol = NULL;
1398 gpointer *globals = NULL;
1399 MonoAotFileInfo *info = NULL;
1402 gboolean do_load_image = TRUE;
1404 if (mono_compile_aot)
1407 if (assembly->image->aot_module)
1409 * Already loaded. This can happen because the assembly loading code might invoke
1410 * the assembly load hooks multiple times for the same assembly.
1414 if (assembly->image->dynamic)
1417 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
1421 if (static_aot_modules)
1422 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1428 /* Statically linked AOT module */
1430 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1431 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1432 globals = info->globals;
1435 sofile = load_aot_module_from_cache (assembly, &aot_name);
1438 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1440 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1443 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1449 if (!sofile && !globals) {
1450 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1451 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1459 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1460 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1463 if (version_symbol) {
1464 /* Old file format */
1465 version = atoi (version_symbol);
1468 version = info->version;
1471 if (version != MONO_AOT_FILE_VERSION) {
1472 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1475 usable = check_usable (assembly, info, &msg);
1479 if (mono_aot_only) {
1480 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1483 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1488 mono_dl_close (sofile);
1489 assembly->image->aot_module = NULL;
1494 g_assert (info->double_align == __alignof__ (double));
1495 g_assert (info->long_align == __alignof__ (gint64));
1499 amodule = g_new0 (MonoAotModule, 1);
1500 amodule->aot_name = aot_name;
1501 amodule->assembly = assembly;
1503 memcpy (&amodule->info, info, sizeof (*info));
1505 amodule->got = amodule->info.got;
1506 amodule->got [0] = assembly->image;
1507 amodule->globals = globals;
1508 amodule->sofile = sofile;
1509 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1510 amodule->blob = blob;
1512 /* Read image table */
1514 guint32 table_len, i;
1517 table = info->image_table;
1520 table_len = *(guint32*)table;
1521 table += sizeof (guint32);
1522 amodule->image_table = g_new0 (MonoImage*, table_len);
1523 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1524 amodule->image_guids = g_new0 (char*, table_len);
1525 amodule->image_table_len = table_len;
1526 for (i = 0; i < table_len; ++i) {
1527 MonoAssemblyName *aname = &(amodule->image_names [i]);
1529 aname->name = g_strdup (table);
1530 table += strlen (table) + 1;
1531 amodule->image_guids [i] = g_strdup (table);
1532 table += strlen (table) + 1;
1534 aname->culture = g_strdup (table);
1535 table += strlen (table) + 1;
1536 memcpy (aname->public_key_token, table, strlen (table) + 1);
1537 table += strlen (table) + 1;
1539 table = ALIGN_PTR_TO (table, 8);
1540 aname->flags = *(guint32*)table;
1542 aname->major = *(guint32*)table;
1544 aname->minor = *(guint32*)table;
1546 aname->build = *(guint32*)table;
1548 aname->revision = *(guint32*)table;
1553 amodule->code_offsets = info->code_offsets;
1554 amodule->code = info->methods;
1556 /* Mask out thumb interop bit */
1557 amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1559 amodule->code_end = info->methods_end;
1560 amodule->method_info_offsets = info->method_info_offsets;
1561 amodule->ex_info_offsets = info->ex_info_offsets;
1562 amodule->class_info_offsets = info->class_info_offsets;
1563 amodule->class_name_table = info->class_name_table;
1564 amodule->extra_method_table = info->extra_method_table;
1565 amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1566 amodule->unbox_trampolines = info->unbox_trampolines;
1567 amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1568 amodule->got_info_offsets = info->got_info_offsets;
1569 amodule->unwind_info = info->unwind_info;
1570 amodule->mem_end = info->mem_end;
1571 amodule->mem_begin = amodule->code;
1572 amodule->plt = info->plt;
1573 amodule->plt_end = info->plt_end;
1574 amodule->mono_eh_frame = info->mono_eh_frame;
1575 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1576 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1577 amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1578 amodule->thumb_end = info->thumb_end;
1580 if (make_unreadable) {
1581 #ifndef TARGET_WIN32
1583 guint8 *page_start, *page_end;
1586 addr = amodule->mem_begin;
1587 len = amodule->mem_end - amodule->mem_begin;
1589 /* Round down in both directions to avoid modifying data which is not ours */
1590 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1591 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1592 if (page_end > page_start) {
1593 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1594 g_assert (err == 0);
1601 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1602 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1604 g_hash_table_insert (aot_modules, assembly, amodule);
1607 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1609 assembly->image->aot_module = amodule;
1611 if (mono_aot_only) {
1612 if (mono_defaults.corlib) {
1613 /* The second got slot contains the mscorlib got addr */
1614 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1616 amodule->got [1] = mscorlib_amodule->got;
1618 amodule->got [1] = amodule->got;
1622 if (mono_gc_is_moving ()) {
1625 memset (&ji, 0, sizeof (ji));
1626 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1628 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1632 * Since we store methoddef and classdef tokens when referring to methods/classes in
1633 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1634 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1635 * non-lazily, since we can't handle out-of-date errors later.
1636 * The cached class info also depends on the exact assemblies.
1638 #if defined(__native_client__)
1639 /* TODO: Don't 'load_image' on mscorlib due to a */
1640 /* recursive loading problem. This should be */
1641 /* removed if mscorlib is loaded from disk. */
1642 if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1643 do_load_image = TRUE;
1645 do_load_image = FALSE;
1648 if (do_load_image) {
1649 for (i = 0; i < amodule->image_table_len; ++i)
1650 load_image (amodule, i, FALSE);
1653 if (amodule->out_of_date) {
1654 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);
1655 if (mono_aot_only) {
1656 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);
1661 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1665 * mono_aot_register_globals:
1667 * This is called by the ctor function in AOT images compiled with the
1668 * 'no-dlsym' option.
1671 mono_aot_register_globals (gpointer *globals)
1673 g_assert_not_reached ();
1677 * mono_aot_register_module:
1679 * This should be called by embedding code to register AOT modules statically linked
1680 * into the executable. AOT_INFO should be the value of the
1681 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1684 mono_aot_register_module (gpointer *aot_info)
1688 MonoAotFileInfo *info = (gpointer)aot_info;
1690 g_assert (info->version == MONO_AOT_FILE_VERSION);
1692 globals = info->globals;
1695 aname = info->assembly_name;
1697 /* This could be called before startup */
1701 if (!static_aot_modules)
1702 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1704 g_hash_table_insert (static_aot_modules, aname, info);
1711 mono_aot_init (void)
1713 InitializeCriticalSection (&aot_mutex);
1714 aot_modules = g_hash_table_new (NULL, NULL);
1716 mono_install_assembly_load_hook (load_aot_module, NULL);
1718 if (g_getenv ("MONO_LASTAOT"))
1719 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1720 if (g_getenv ("MONO_AOT_CACHE"))
1721 use_aot_cache = TRUE;
1725 mono_aot_cleanup (void)
1727 if (aot_jit_icall_hash)
1728 g_hash_table_destroy (aot_jit_icall_hash);
1730 g_hash_table_destroy (aot_modules);
1734 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1740 info->vtable_size = decode_value (buf, &buf);
1741 if (info->vtable_size == -1)
1744 flags = decode_value (buf, &buf);
1745 info->ghcimpl = (flags >> 0) & 0x1;
1746 info->has_finalize = (flags >> 1) & 0x1;
1747 info->has_cctor = (flags >> 2) & 0x1;
1748 info->has_nested_classes = (flags >> 3) & 0x1;
1749 info->blittable = (flags >> 4) & 0x1;
1750 info->has_references = (flags >> 5) & 0x1;
1751 info->has_static_refs = (flags >> 6) & 0x1;
1752 info->no_special_static_fields = (flags >> 7) & 0x1;
1753 info->is_generic_container = (flags >> 8) & 0x1;
1755 if (info->has_cctor) {
1756 res = decode_method_ref (module, &ref, buf, &buf);
1759 info->cctor_token = ref.token;
1761 if (info->has_finalize) {
1762 res = decode_method_ref (module, &ref, buf, &buf);
1765 info->finalize_image = ref.image;
1766 info->finalize_token = ref.token;
1769 info->instance_size = decode_value (buf, &buf);
1770 info->class_size = decode_value (buf, &buf);
1771 info->packing_size = decode_value (buf, &buf);
1772 info->min_align = decode_value (buf, &buf);
1780 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1783 MonoClass *klass = vtable->klass;
1784 MonoAotModule *amodule = klass->image->aot_module;
1786 MonoCachedClassInfo class_info;
1791 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
1794 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1797 err = decode_cached_class_info (amodule, &class_info, p, &p);
1801 for (i = 0; i < slot; ++i)
1802 decode_method_ref (amodule, &ref, p, &p);
1804 res = decode_method_ref (amodule, &ref, p, &p);
1807 if (ref.no_aot_trampoline)
1810 if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
1813 return mono_aot_get_method_from_token (domain, ref.image, ref.token);
1817 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1819 MonoAotModule *amodule = klass->image->aot_module;
1823 if (klass->rank || !amodule)
1826 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1828 err = decode_cached_class_info (amodule, res, p, &p);
1836 * mono_aot_get_class_from_name:
1838 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1839 * using a cache stored in the AOT file.
1840 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1842 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
1846 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1848 MonoAotModule *amodule = image->aot_module;
1849 guint16 *table, *entry;
1852 char full_name_buf [1024];
1854 const char *name2, *name_space2;
1856 guint32 cols [MONO_TYPEDEF_SIZE];
1857 GHashTable *nspace_table;
1859 if (!amodule || !amodule->class_name_table)
1866 /* First look in the cache */
1867 if (!amodule->name_cache)
1868 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1869 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1871 *klass = g_hash_table_lookup (nspace_table, name);
1878 table_size = amodule->class_name_table [0];
1879 table = amodule->class_name_table + 1;
1881 if (name_space [0] == '\0')
1882 full_name = g_strdup_printf ("%s", name);
1884 if (strlen (name_space) + strlen (name) < 1000) {
1885 sprintf (full_name_buf, "%s.%s", name_space, name);
1886 full_name = full_name_buf;
1888 full_name = g_strdup_printf ("%s.%s", name_space, name);
1891 hash = mono_metadata_str_hash (full_name) % table_size;
1892 if (full_name != full_name_buf)
1895 entry = &table [hash * 2];
1897 if (entry [0] != 0) {
1898 t = &image->tables [MONO_TABLE_TYPEDEF];
1901 guint32 index = entry [0];
1902 guint32 next = entry [1];
1903 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1905 name_table_accesses ++;
1907 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1909 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1910 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1912 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1914 *klass = mono_class_get (image, token);
1919 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1920 if (!nspace_table) {
1921 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1922 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
1924 g_hash_table_insert (nspace_table, (char*)name2, *klass);
1931 entry = &table [next * 2];
1944 * decode_mono_eh_frame:
1946 * Decode the EH information emitted by our modified LLVM compiler and construct a
1947 * MonoJitInfo structure from it.
1948 * LOCKING: Acquires the domain lock.
1951 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
1952 MonoMethod *method, guint8 *code,
1953 MonoJitExceptionInfo *clauses, int num_clauses,
1954 int extra_size, GSList **nesting,
1955 int *this_reg, int *this_offset)
1958 guint8 *fde, *cie, *code_start, *code_end;
1959 int version, fde_count;
1961 int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
1962 MonoJitExceptionInfo *ei;
1963 guint32 fde_len, ei_len, nested_len, nindex;
1964 gpointer *type_info;
1966 MonoLLVMFDEInfo info;
1968 g_assert (amodule->mono_eh_frame);
1970 p = amodule->mono_eh_frame;
1972 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
1976 g_assert (version == 1 || version == 2);
1982 func_encoding = DW_EH_PE_pcrel;
1984 p = ALIGN_PTR_TO (p, 4);
1986 fde_count = *(guint32*)p;
1990 /* There is +1 entry in the table */
1991 cie = p + ((fde_count + 1) * 8);
1993 /* Binary search in the table to find the entry for code */
1994 offset = code - amodule->mono_eh_frame;
1999 pos = (left + right) / 2;
2001 offset1 = table [(pos * 2)];
2002 if (pos + 1 == fde_count) {
2004 offset2 = amodule->code_end - amodule->code;
2006 /* Encoded as DW_EH_PE_pcrel, but relative to mono_eh_frame */
2007 offset2 = table [(pos + 1) * 2];
2010 if (func_encoding == DW_EH_PE_absptr) {
2012 * Encoded as DW_EH_PE_absptr, because the ios linker can move functions inside object files to make thumb work,
2013 * so the offsets between two symbols in the text segment are not assembler constant.
2015 g_assert (sizeof(gpointer) == 4);
2016 offset1 -= (gint32)(gsize)amodule->mono_eh_frame;
2017 offset2 -= (gint32)(gsize)amodule->mono_eh_frame;
2020 if (offset < offset1)
2022 else if (offset >= offset2)
2028 if (func_encoding == DW_EH_PE_absptr) {
2029 code_start = (gpointer)(gsize)table [(pos * 2)];
2030 code_end = (gpointer)(gsize)table [(pos * 2) + 2];
2032 code_start = amodule->mono_eh_frame + table [(pos * 2)];
2033 /* This won't overflow because there is +1 entry in the table */
2034 code_end = amodule->mono_eh_frame + table [(pos * 2) + 2];
2036 code_len = code_end - code_start;
2038 g_assert (code >= code_start && code < code_end);
2040 if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
2041 /* Clear thumb flag */
2042 code_start = (guint8*)(((mgreg_t)code_start) & ~1);
2044 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
2045 /* This won't overflow because there is +1 entry in the table */
2046 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2048 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
2050 ei_len = info.ex_info_len;
2051 type_info = info.type_info;
2052 *this_reg = info.this_reg;
2053 *this_offset = info.this_offset;
2055 /* Count number of nested clauses */
2057 for (i = 0; i < ei_len; ++i) {
2058 /* This might be unaligned */
2059 gint32 cindex1 = read32 (type_info [i]);
2062 for (l = nesting [cindex1]; l; l = l->next) {
2063 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2065 for (j = 0; j < ei_len; ++j) {
2066 gint32 cindex2 = read32 (type_info [j]);
2068 if (cindex2 == nesting_cindex)
2075 * LLVM might represent one IL region with multiple regions, so have to
2076 * allocate a new JI.
2079 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2081 jinfo->code_size = code_len;
2082 jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2083 jinfo->method = method;
2084 jinfo->code_start = code;
2085 jinfo->domain_neutral = 0;
2086 /* This signals that used_regs points to a normal cached unwind info */
2087 jinfo->from_aot = 0;
2088 jinfo->num_clauses = ei_len + nested_len;
2090 for (i = 0; i < ei_len; ++i) {
2092 * orig_jinfo contains the original IL exception info saved by the AOT
2093 * compiler, we have to combine that with the information produced by LLVM
2095 /* The type_info entries contain IL clause indexes */
2096 int clause_index = read32 (type_info [i]);
2097 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2098 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2100 g_assert (clause_index < num_clauses);
2101 jei->flags = orig_jei->flags;
2102 jei->data.catch_class = orig_jei->data.catch_class;
2104 jei->try_start = ei [i].try_start;
2105 jei->try_end = ei [i].try_end;
2106 jei->handler_start = ei [i].handler_start;
2108 /* Make sure we transition to thumb when a handler starts */
2109 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2110 jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2113 /* See exception_cb () in mini-llvm.c as to why this is needed */
2115 for (i = 0; i < ei_len; ++i) {
2116 gint32 cindex1 = read32 (type_info [i]);
2119 for (l = nesting [cindex1]; l; l = l->next) {
2120 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2122 for (j = 0; j < ei_len; ++j) {
2123 gint32 cindex2 = read32 (type_info [j]);
2125 if (cindex2 == nesting_cindex) {
2127 * The try interval comes from the nested clause, everything else from the
2130 memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2131 jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2132 jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2138 g_assert (nindex == ei_len + nested_len);
2144 * LOCKING: Acquires the domain lock.
2147 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
2148 MonoMethod *method, guint8* ex_info, guint8 *addr,
2149 guint8 *code, guint32 code_len)
2151 int i, buf_len, num_clauses;
2153 guint used_int_regs, flags;
2154 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2155 gboolean from_llvm, has_gc_map;
2157 int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2158 int this_reg = 0, this_offset = 0;
2160 /* Load the method info from the AOT file */
2163 flags = decode_value (p, &p);
2164 has_generic_jit_info = (flags & 1) != 0;
2165 has_dwarf_unwind_info = (flags & 2) != 0;
2166 has_clauses = (flags & 4) != 0;
2167 has_seq_points = (flags & 8) != 0;
2168 from_llvm = (flags & 16) != 0;
2169 has_try_block_holes = (flags & 32) != 0;
2170 has_gc_map = (flags & 64) != 0;
2171 has_arch_eh_jit_info = (flags & 128) != 0;
2173 if (has_dwarf_unwind_info) {
2176 offset = decode_value (p, &p);
2177 g_assert (offset < (1 << 30));
2178 used_int_regs = offset;
2180 used_int_regs = decode_value (p, &p);
2182 if (has_generic_jit_info)
2183 generic_info_size = sizeof (MonoGenericJitInfo);
2185 generic_info_size = 0;
2187 if (has_try_block_holes) {
2188 num_holes = decode_value (p, &p);
2189 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2191 num_holes = try_holes_info_size = 0;
2193 /* Exception table */
2195 num_clauses = decode_value (p, &p);
2198 if (has_arch_eh_jit_info)
2199 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2201 arch_eh_jit_info_size = 0;
2204 MonoJitExceptionInfo *clauses;
2208 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2211 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2212 nesting = g_new0 (GSList*, num_clauses);
2214 for (i = 0; i < num_clauses; ++i) {
2215 MonoJitExceptionInfo *ei = &clauses [i];
2217 ei->flags = decode_value (p, &p);
2219 if (decode_value (p, &p))
2220 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2222 /* Read the list of nesting clauses */
2224 int nesting_index = decode_value (p, &p);
2225 if (nesting_index == -1)
2227 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2231 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);
2232 jinfo->from_llvm = 1;
2235 for (i = 0; i < num_clauses; ++i)
2236 g_slist_free (nesting [i]);
2240 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size);
2241 jinfo->num_clauses = num_clauses;
2243 for (i = 0; i < jinfo->num_clauses; ++i) {
2244 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2246 ei->flags = decode_value (p, &p);
2248 ei->exvar_offset = decode_value (p, &p);
2250 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2251 ei->data.filter = code + decode_value (p, &p);
2253 if (decode_value (p, &p))
2254 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2257 ei->try_start = code + decode_value (p, &p);
2258 ei->try_end = code + decode_value (p, &p);
2259 ei->handler_start = code + decode_value (p, &p);
2262 jinfo->code_size = code_len;
2263 jinfo->used_regs = used_int_regs;
2264 jinfo->method = method;
2265 jinfo->code_start = code;
2266 jinfo->domain_neutral = 0;
2267 jinfo->from_aot = 1;
2270 if (has_generic_jit_info) {
2271 MonoGenericJitInfo *gi;
2273 jinfo->has_generic_jit_info = 1;
2275 gi = mono_jit_info_get_generic_jit_info (jinfo);
2278 gi->nlocs = decode_value (p, &p);
2280 gi->locations = mono_domain_alloc0 (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2281 for (i = 0; i < gi->nlocs; ++i) {
2282 MonoDwarfLocListEntry *entry = &gi->locations [i];
2284 entry->is_reg = decode_value (p, &p);
2285 entry->reg = decode_value (p, &p);
2287 entry->offset = decode_value (p, &p);
2289 entry->from = decode_value (p, &p);
2290 entry->to = decode_value (p, &p);
2294 gi->has_this = this_reg != -1;
2295 gi->this_reg = this_reg;
2296 gi->this_offset = this_offset;
2298 gi->has_this = decode_value (p, &p);
2299 gi->this_reg = decode_value (p, &p);
2300 gi->this_offset = decode_value (p, &p);
2304 /* This currently contains no data */
2305 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2307 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
2310 if (has_try_block_holes) {
2311 MonoTryBlockHoleTableJitInfo *table;
2313 jinfo->has_try_block_holes = 1;
2315 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2318 table->num_holes = (guint16)num_holes;
2319 for (i = 0; i < num_holes; ++i) {
2320 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2321 hole->clause = decode_value (p, &p);
2322 hole->length = decode_value (p, &p);
2323 hole->offset = decode_value (p, &p);
2327 if (has_arch_eh_jit_info) {
2328 MonoArchEHJitInfo *eh_info;
2330 jinfo->has_arch_eh_info = 1;
2332 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2333 eh_info->stack_size = decode_value (p, &p);
2336 if (has_seq_points) {
2337 MonoSeqPointInfo *seq_points;
2338 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2340 int len = decode_value (p, &p);
2342 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2343 seq_points->len = len;
2344 last_il_offset = last_native_offset = 0;
2345 for (i = 0; i < len; ++i) {
2346 SeqPoint *sp = &seq_points->seq_points [i];
2347 il_offset = last_il_offset + decode_value (p, &p);
2348 native_offset = last_native_offset + decode_value (p, &p);
2350 sp->il_offset = il_offset;
2351 sp->native_offset = native_offset;
2353 sp->next_len = decode_value (p, &p);
2354 sp->next = g_new (int, sp->next_len);
2355 for (j = 0; j < sp->next_len; ++j)
2356 sp->next [j] = decode_value (p, &p);
2358 last_il_offset = il_offset;
2359 last_native_offset = native_offset;
2362 mono_domain_lock (domain);
2363 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2364 mono_domain_unlock (domain);
2367 /* Load debug info */
2368 buf_len = decode_value (p, &p);
2369 mono_debug_add_aot_method (domain, method, code, p, buf_len);
2373 int map_size = decode_value (p, &p);
2374 /* The GC map requires 4 bytes of alignment */
2375 while ((guint64)(gsize)p % 4)
2381 if (amodule != jinfo->method->klass->image->aot_module) {
2384 ji_to_amodule = g_hash_table_new (NULL, NULL);
2385 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2393 * mono_aot_get_unwind_info:
2395 * Return a pointer to the DWARF unwind info belonging to JI.
2398 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2400 MonoAotModule *amodule = ji->method->klass->image->aot_module;
2402 guint8 *code = ji->code_start;
2405 g_assert (ji->from_aot);
2407 if (!(code >= amodule->code && code <= amodule->code_end)) {
2408 /* ji belongs to a different aot module than amodule */
2410 g_assert (ji_to_amodule);
2411 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2413 g_assert (code >= amodule->code && code <= amodule->code_end);
2417 p = amodule->unwind_info + ji->used_regs;
2418 *unwind_info_len = decode_value (p, &p);
2422 static G_GNUC_UNUSED int
2423 compare_ints (const void *a, const void *b)
2425 return *(gint32*)a - *(gint32*)b;
2429 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2431 int mid = (lo + hi) / 2;
2438 for (i = lo; i < hi; ++i)
2439 if (array [(i * 2)] > array [(i * 2) + 2])
2442 /* Already sorted */
2446 msort_code_offsets_internal (array, lo, mid, scratch);
2447 msort_code_offsets_internal (array, mid + 1, hi, scratch);
2449 if (array [mid * 2] < array [(mid + 1) * 2])
2455 for (i = lo; i <= hi; i ++) {
2456 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2457 scratch [(i * 2)] = array [t_lo * 2];
2458 scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2461 scratch [(i * 2)] = array [t_hi * 2];
2462 scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2466 for (i = lo; i <= hi; ++i) {
2467 array [(i * 2)] = scratch [i * 2];
2468 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2473 msort_code_offsets (gint32 *array, int len)
2477 scratch = g_new (gint32, len * 2);
2478 msort_code_offsets_internal (array, 0, len - 1, scratch);
2483 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2485 int pos, left, right, offset, offset1, offset2, code_len;
2486 int method_index, table_len, is_wrapper;
2488 MonoAotModule *amodule = image->aot_module;
2491 guint8 *code, *ex_info, *p;
2493 int nmethods = amodule->info.nmethods;
2494 gint32 *code_offsets;
2500 if (domain != mono_get_root_domain ())
2504 offset = (guint8*)addr - amodule->code;
2506 /* Compute a sorted table mapping code offsets to method indexes. */
2507 if (!amodule->sorted_code_offsets) {
2508 code_offsets = g_new0 (gint32, nmethods * 2);
2510 for (i = 0; i < nmethods; ++i) {
2511 /* Skip the -1 entries to speed up sorting */
2512 if (amodule->code_offsets [i] == 0xffffffff)
2514 code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2515 code_offsets [(offsets_len *2) + 1] = i;
2518 /* Use a merge sort as this is mostly sorted */
2519 msort_code_offsets (code_offsets, offsets_len);
2520 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2521 for (i = 0; i < offsets_len -1; ++i)
2522 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2524 amodule->sorted_code_offsets_len = offsets_len;
2525 mono_memory_barrier ();
2526 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2527 /* Somebody got in before us */
2528 g_free (code_offsets);
2531 code_offsets = amodule->sorted_code_offsets;
2532 offsets_len = amodule->sorted_code_offsets_len;
2534 if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
2537 /* Binary search in the sorted_code_offsets table */
2539 right = offsets_len;
2541 pos = (left + right) / 2;
2543 offset1 = code_offsets [(pos * 2)];
2544 if (pos + 1 == offsets_len)
2545 offset2 = amodule->code_end - amodule->code;
2547 offset2 = code_offsets [(pos + 1) * 2];
2549 if (offset < offset1)
2551 else if (offset >= offset2)
2557 g_assert (offset >= code_offsets [(pos * 2)]);
2558 if (pos + 1 < offsets_len)
2559 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2560 method_index = code_offsets [(pos * 2) + 1];
2562 code = &amodule->code [amodule->code_offsets [method_index]];
2563 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2565 if (pos == offsets_len - 1)
2566 code_len = amodule->code_end - code;
2568 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2570 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2572 /* Might be a wrapper/extra method */
2573 if (amodule->extra_methods) {
2575 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2582 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2584 * This is hit for extra methods which are called directly, so they are
2585 * not in amodule->extra_methods.
2587 table_len = amodule->extra_method_info_offsets [0];
2588 table = amodule->extra_method_info_offsets + 1;
2595 pos = ((left + right) / 2);
2597 g_assert (pos < table_len);
2599 if (table [pos * 2] < method_index)
2601 else if (table [pos * 2] > method_index)
2607 p = amodule->blob + table [(pos * 2) + 1];
2608 is_wrapper = decode_value (p, &p);
2610 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
2612 g_assert (!is_wrapper);
2613 method = decode_resolve_method_ref (amodule, p, &p);
2618 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2619 method = mono_get_method (image, token, NULL);
2626 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2628 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2630 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2631 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2633 /* Add it to the normal JitInfo tables */
2634 mono_jit_info_table_add (domain, jinfo);
2640 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2648 case MONO_PATCH_INFO_METHOD:
2649 case MONO_PATCH_INFO_METHOD_JUMP:
2650 case MONO_PATCH_INFO_ICALL_ADDR:
2651 case MONO_PATCH_INFO_METHOD_RGCTX: {
2655 res = decode_method_ref (aot_module, &ref, p, &p);
2659 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)) {
2660 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2661 ji->type = MONO_PATCH_INFO_ABS;
2665 ji->data.method = ref.method;
2667 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2668 g_assert (ji->data.method);
2669 mono_class_init (ji->data.method->klass);
2673 case MONO_PATCH_INFO_INTERNAL_METHOD:
2674 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2675 guint32 len = decode_value (p, &p);
2677 ji->data.name = (char*)p;
2681 case MONO_PATCH_INFO_METHODCONST:
2683 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2684 if (!ji->data.method)
2687 case MONO_PATCH_INFO_VTABLE:
2688 case MONO_PATCH_INFO_CLASS:
2689 case MONO_PATCH_INFO_IID:
2690 case MONO_PATCH_INFO_ADJUSTED_IID:
2692 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2693 if (!ji->data.klass)
2696 case MONO_PATCH_INFO_CLASS_INIT:
2697 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2698 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2699 if (!ji->data.klass)
2702 case MONO_PATCH_INFO_IMAGE:
2703 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2704 if (!ji->data.image)
2707 case MONO_PATCH_INFO_FIELD:
2708 case MONO_PATCH_INFO_SFLDA:
2710 ji->data.field = decode_field_info (aot_module, p, &p);
2711 if (!ji->data.field)
2714 case MONO_PATCH_INFO_SWITCH:
2715 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2716 ji->data.table->table_size = decode_value (p, &p);
2717 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2718 ji->data.table->table = (MonoBasicBlock**)table;
2719 for (i = 0; i < ji->data.table->table_size; i++)
2720 table [i] = (gpointer)(gssize)decode_value (p, &p);
2722 case MONO_PATCH_INFO_R4: {
2725 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2726 val = decode_value (p, &p);
2727 *(float*)ji->data.target = *(float*)&val;
2730 case MONO_PATCH_INFO_R8: {
2734 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2736 val [0] = decode_value (p, &p);
2737 val [1] = decode_value (p, &p);
2738 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2739 *(double*)ji->data.target = *(double*)&v;
2742 case MONO_PATCH_INFO_LDSTR:
2743 image = load_image (aot_module, decode_value (p, &p), TRUE);
2746 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2748 case MONO_PATCH_INFO_RVA:
2749 case MONO_PATCH_INFO_DECLSEC:
2750 case MONO_PATCH_INFO_LDTOKEN:
2751 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2753 image = load_image (aot_module, decode_value (p, &p), TRUE);
2756 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2758 ji->data.token->has_context = decode_value (p, &p);
2759 if (ji->data.token->has_context) {
2760 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2765 case MONO_PATCH_INFO_EXC_NAME:
2766 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2767 if (!ji->data.klass)
2769 ji->data.name = ji->data.klass->name;
2771 case MONO_PATCH_INFO_METHOD_REL:
2772 ji->data.offset = decode_value (p, &p);
2774 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2775 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2776 case MONO_PATCH_INFO_MONITOR_ENTER:
2777 case MONO_PATCH_INFO_MONITOR_EXIT:
2778 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
2779 case MONO_PATCH_INFO_CASTCLASS_CACHE:
2781 case MONO_PATCH_INFO_RGCTX_FETCH: {
2783 MonoJumpInfoRgctxEntry *entry;
2784 guint32 offset, val;
2787 offset = decode_value (p, &p);
2788 val = decode_value (p, &p);
2790 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2791 p2 = aot_module->blob + offset;
2792 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
2793 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
2794 entry->info_type = (val >> 1) & 0xff;
2795 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2796 entry->data->type = (val >> 9) & 0xff;
2798 res = decode_patch (aot_module, mp, entry->data, p, &p);
2801 ji->data.rgctx_entry = entry;
2804 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2806 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2807 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2809 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2810 imt_tramp->vt_offset = decode_value (p, &p);
2812 ji->data.imt_tramp = imt_tramp;
2815 case MONO_PATCH_INFO_SIGNATURE:
2816 ji->data.target = decode_signature (aot_module, p, &p);
2819 g_warning ("unhandled type %d", ji->type);
2820 g_assert_not_reached ();
2831 static MonoJumpInfo*
2832 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
2833 guint32 **got_slots,
2834 guint8 *buf, guint8 **endbuf)
2836 MonoJumpInfo *patches;
2842 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2844 *got_slots = g_malloc (sizeof (guint32) * n_patches);
2846 for (pindex = 0; pindex < n_patches; ++pindex) {
2847 MonoJumpInfo *ji = &patches [pindex];
2852 got_offset = decode_value (p, &p);
2854 if (aot_module->got [got_offset]) {
2855 /* Already loaded */
2856 //printf ("HIT!\n");
2858 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2860 ji->type = decode_value (shared_p, &shared_p);
2862 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2867 (*got_slots) [pindex] = got_offset;
2874 g_free (*got_slots);
2881 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2884 * Jump addresses cannot be patched by the trampoline code since it
2885 * does not have access to the caller's address. Instead, we collect
2886 * the addresses of the GOT slots pointing to a method, and patch
2887 * them after the method has been compiled.
2889 MonoJitDomainInfo *info = domain_jit_info (domain);
2892 mono_domain_lock (domain);
2893 if (!info->jump_target_got_slot_hash)
2894 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2895 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2896 list = g_slist_prepend (list, got_slot);
2897 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2898 mono_domain_unlock (domain);
2904 * Load the method identified by METHOD_INDEX from the AOT image. Return a
2905 * pointer to the native code of the method, or NULL if not found.
2906 * METHOD might not be set if the caller only has the image/token info.
2909 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2912 gboolean from_plt = method == NULL;
2914 int i, pindex, n_patches, used_strings;
2915 gboolean keep_patches = TRUE;
2917 MonoJitInfo *jinfo = NULL;
2918 guint8 *code, *info;
2920 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2923 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2924 /* Non shared AOT code can't be used in other appdomains */
2927 if (amodule->out_of_date)
2930 if (amodule->code_offsets [method_index] == 0xffffffff) {
2931 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2935 method = mono_get_method (image, token, NULL);
2936 full_name = mono_method_full_name (method, TRUE);
2937 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2943 code = &amodule->code [amodule->code_offsets [method_index]];
2945 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2947 if (amodule->thumb_end && code < amodule->thumb_end) {
2948 /* Convert this into a thumb address */
2949 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
2950 code = &amodule->code [amodule->code_offsets [method_index] + 1];
2954 if (!amodule->methods_loaded)
2955 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
2958 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2961 if (mono_last_aot_method != -1) {
2962 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2964 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2966 method = mono_get_method (image, token, NULL);
2968 char *name = mono_method_full_name (method, TRUE);
2969 printf ("LAST AOT METHOD: %s.\n", name);
2972 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2980 klass = method->klass;
2981 decode_klass_ref (amodule, p, &p);
2983 klass = decode_klass_ref (amodule, p, &p);
2986 if (amodule->info.opts & MONO_OPT_SHARED)
2987 used_strings = decode_value (p, &p);
2991 for (i = 0; i < used_strings; i++) {
2992 guint token = decode_value (p, &p);
2993 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2996 if (amodule->info.opts & MONO_OPT_SHARED)
2997 keep_patches = FALSE;
2999 n_patches = decode_value (p, &p);
3001 keep_patches = FALSE;
3004 MonoJumpInfo *patches;
3010 mp = mono_mempool_new ();
3012 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3013 if (patches == NULL)
3016 for (pindex = 0; pindex < n_patches; ++pindex) {
3017 MonoJumpInfo *ji = &patches [pindex];
3019 if (!amodule->got [got_slots [pindex]]) {
3020 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
3021 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3022 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
3023 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3024 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
3026 ji->type = MONO_PATCH_INFO_NONE;
3032 mono_mempool_destroy (mp);
3035 if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
3036 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3038 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3042 method = mono_get_method (image, token, NULL);
3044 full_name = mono_method_full_name (method, TRUE);
3047 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3049 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]\n", full_name, code, code + jinfo->code_size, info);
3055 InterlockedIncrement (&mono_jit_stats.methods_aot);
3057 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
3061 if (method && method->wrapper_type)
3062 g_hash_table_insert (amodule->method_to_code, method, code);
3066 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3070 method = mono_get_method (image, token, NULL);
3073 mono_profiler_method_jit (method);
3074 jinfo = mono_jit_info_table_find (domain, (char*)code);
3076 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3079 if (from_plt && klass && !klass->generic_container)
3080 mono_runtime_class_init (mono_class_vtable (domain, klass));
3085 /* FIXME: The space in domain->mp is wasted */
3086 if (amodule->info.opts & MONO_OPT_SHARED)
3087 /* No need to cache patches */
3088 mono_mempool_destroy (mp);
3097 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name)
3099 guint32 table_size, entry_size, hash;
3100 guint32 *table, *entry;
3102 static guint32 n_extra_decodes;
3104 if (!amodule || amodule->out_of_date)
3107 table_size = amodule->extra_method_table [0];
3108 table = amodule->extra_method_table + 1;
3111 hash = mono_aot_method_hash (method) % table_size;
3113 entry = &table [hash * entry_size];
3120 guint32 key = entry [0];
3121 guint32 value = entry [1];
3122 guint32 next = entry [entry_size - 1];
3126 p = amodule->blob + key;
3130 if (!amodule->method_ref_to_method)
3131 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3132 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3135 m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3138 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3147 /* Special case: wrappers of shared generic methods */
3148 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3149 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3150 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3151 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3153 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3159 /* Methods decoded needlessly */
3161 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3166 entry = &table [next * entry_size];
3175 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3177 g_ptr_array_add ((GPtrArray*)user_data, value);
3181 * find_extra_method:
3183 * Try finding METHOD in the extra_method table in all AOT images.
3184 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3185 * module where the method was found.
3188 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3195 if (method->wrapper_type)
3196 name = mono_aot_wrapper_name (method);
3198 /* Try the method's module first */
3199 *out_amodule = method->klass->image->aot_module;
3200 index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name);
3201 if (index != 0xffffff) {
3207 * Try all other modules.
3208 * This is needed because generic instances klass->image points to the image
3209 * containing the generic definition, but the native code is generated to the
3210 * AOT image which contains the reference.
3213 /* Make a copy to avoid doing the search inside the aot lock */
3214 modules = g_ptr_array_new ();
3216 g_hash_table_foreach (aot_modules, add_module_cb, modules);
3220 for (i = 0; i < modules->len; ++i) {
3221 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3223 if (amodule != method->klass->image->aot_module)
3224 index = find_extra_method_in_amodule (amodule, method, name);
3225 if (index != 0xffffff) {
3226 *out_amodule = amodule;
3231 g_ptr_array_free (modules, TRUE);
3238 * mono_aot_get_method:
3240 * Return a pointer to the AOTed native code for METHOD if it can be found,
3242 * On platforms with function pointers, this doesn't return a function pointer.
3245 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3247 MonoClass *klass = method->klass;
3248 guint32 method_index;
3249 MonoAotModule *amodule = klass->image->aot_module;
3255 if (amodule->out_of_date)
3258 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3259 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3260 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3261 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3265 * Use the original method instead of its invoke-with-check wrapper.
3266 * This is not a problem when using full-aot, since it doesn't support
3269 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3270 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3272 g_assert (klass->inited);
3274 /* Find method index */
3275 if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
3277 * For generic methods, we store the fully shared instance in place of the
3280 method = mono_method_get_declaring_generic_method (method);
3281 method_index = mono_metadata_token_index (method->token) - 1;
3282 } else if (method->is_inflated || !method->token) {
3283 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3285 code = g_hash_table_lookup (amodule->method_to_code, method);
3290 method_index = find_extra_method (method, &amodule);
3292 * Special case the ICollection<T> wrappers for arrays, as they cannot
3293 * be statically enumerated, and each wrapper ends up calling the same
3296 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3297 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3299 code = mono_aot_get_method (domain, m);
3301 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
3302 code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
3303 /* The call above returns an ftnptr */
3304 code = mono_get_addr_from_ftnptr (code);
3312 * Special case Array.GetGenericValueImpl which is a generic icall.
3313 * Generic sharing currently can't handle it, but the icall returns data using
3314 * an out parameter, so the managed-to-native wrappers can share the same code.
3316 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3318 MonoGenericContext ctx;
3319 MonoType *args [16];
3321 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3322 /* Avoid recursion */
3325 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3328 memset (&ctx, 0, sizeof (ctx));
3329 args [0] = &mono_defaults.object_class->byval_arg;
3330 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3332 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3335 * Get the code for the <object> instantiation which should be emitted into
3336 * the mscorlib aot image by the AOT compiler.
3338 code = mono_aot_get_method (domain, m);
3343 /* Same for CompareExchange<T> and Exchange<T> */
3344 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !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])) {
3346 MonoGenericContext ctx;
3347 MonoType *args [16];
3348 gpointer iter = NULL;
3350 while ((m = mono_class_get_methods (method->klass, &iter))) {
3351 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3356 memset (&ctx, 0, sizeof (ctx));
3357 args [0] = &mono_defaults.object_class->byval_arg;
3358 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3360 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3362 /* Avoid recursion */
3367 * Get the code for the <object> instantiation which should be emitted into
3368 * the mscorlib aot image by the AOT compiler.
3370 code = mono_aot_get_method (domain, m);
3375 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
3376 /* Partial sharing */
3377 method_index = find_extra_method (mini_get_shared_method (method), &amodule);
3380 if (method_index == 0xffffff) {
3381 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3384 full_name = mono_method_full_name (method, TRUE);
3385 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
3391 if (method_index == 0xffffff)
3394 /* Needed by find_jit_info */
3396 if (!amodule->extra_methods)
3397 amodule->extra_methods = g_hash_table_new (NULL, NULL);
3398 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3402 method_index = mono_metadata_token_index (method->token) - 1;
3405 return load_method (domain, amodule, klass->image, method, method->token, method_index);
3409 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3413 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3415 MonoAotModule *aot_module = image->aot_module;
3421 method_index = mono_metadata_token_index (token) - 1;
3423 return load_method (domain, aot_module, image, NULL, token, method_index);
3429 } IsGotEntryUserData;
3432 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3434 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3435 MonoAotModule *aot_module = (MonoAotModule*)value;
3437 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3442 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3444 IsGotEntryUserData user_data;
3449 user_data.addr = addr;
3450 user_data.res = FALSE;
3452 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3455 return user_data.res;
3460 MonoAotModule *module;
3461 } FindAotModuleUserData;
3464 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3466 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3467 MonoAotModule *aot_module = (MonoAotModule*)value;
3469 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3470 data->module = aot_module;
3473 static inline MonoAotModule*
3474 find_aot_module (guint8 *code)
3476 FindAotModuleUserData user_data;
3481 /* Reading these need no locking */
3482 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3485 user_data.addr = code;
3486 user_data.module = NULL;
3489 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3492 return user_data.module;
3496 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3499 * Since AOT code is only used in the root domain,
3500 * mono_domain_get () != mono_get_root_domain () means the calling method
3501 * is AppDomain:InvokeInDomain, so this is the same check as in
3502 * mono_method_same_domain () but without loading the metadata for the method.
3504 if (mono_domain_get () == mono_get_root_domain ())
3505 mono_arch_patch_plt_entry (code, got, regs, addr);
3509 * mono_aot_plt_resolve:
3511 * This function is called by the entries in the PLT to resolve the actual method that
3512 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3513 * Returns NULL if the something cannot be loaded.
3516 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3518 #ifdef MONO_ARCH_AOT_SUPPORTED
3519 guint8 *p, *target, *plt_entry;
3521 MonoAotModule *module = (MonoAotModule*)aot_module;
3522 gboolean res, no_ftnptr = FALSE;
3525 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3527 p = &module->blob [plt_info_offset];
3529 ji.type = decode_value (p, &p);
3531 mp = mono_mempool_new_size (512);
3532 res = decode_patch (module, mp, &ji, p, &p);
3535 mono_mempool_destroy (mp);
3540 * Avoid calling resolve_patch_target in the full-aot case if possible, since
3541 * it would create a trampoline, and we don't need that.
3542 * We could do this only if the method does not need the special handling
3543 * in mono_magic_trampoline ().
3545 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) &&
3546 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
3547 target = mono_jit_compile_method (ji.data.method);
3550 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3554 * The trampoline expects us to return a function descriptor on platforms which use
3555 * it, but resolve_patch_target returns a direct function pointer for some type of
3556 * patches, so have to translate between the two.
3557 * FIXME: Clean this up, but how ?
3559 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) {
3560 /* These should already have a function descriptor */
3561 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3562 /* Our function descriptors have a 0 environment, gcc created ones don't */
3563 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3564 g_assert (((gpointer*)target) [2] == 0);
3567 } else if (!no_ftnptr) {
3568 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3569 g_assert (((gpointer*)target) [2] != 0);
3571 target = mono_create_ftnptr (mono_domain_get (), target);
3574 mono_mempool_destroy (mp);
3576 /* Patch the PLT entry with target which might be the actual method not a trampoline */
3577 plt_entry = mono_aot_get_plt_entry (code);
3578 g_assert (plt_entry);
3579 mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3583 g_assert_not_reached ();
3591 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
3592 * method in the module is loaded to avoid committing memory by writing to it.
3593 * LOCKING: Assumes the AOT lock is held.
3596 init_plt (MonoAotModule *amodule)
3601 if (amodule->plt_inited)
3604 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3607 * Initialize the PLT entries in the GOT to point to the default targets.
3610 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3611 for (i = 1; i < amodule->info.plt_size; ++i)
3612 /* All the default entries point to the AOT trampoline */
3613 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3615 amodule->plt_inited = TRUE;
3619 * mono_aot_get_plt_entry:
3621 * Return the address of the PLT entry called by the code at CODE if exists.
3624 mono_aot_get_plt_entry (guint8 *code)
3626 MonoAotModule *amodule = find_aot_module (code);
3627 guint8 *target = NULL;
3633 if (amodule->thumb_end && code < amodule->thumb_end) {
3634 return mono_arm_get_thumb_plt_entry (code);
3638 #ifdef MONO_ARCH_AOT_SUPPORTED
3639 target = mono_arch_get_call_target (code);
3641 g_assert_not_reached ();
3644 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3651 * mono_aot_get_plt_info_offset:
3653 * Return the PLT info offset belonging to the plt entry called by CODE.
3656 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3658 guint8 *plt_entry = mono_aot_get_plt_entry (code);
3660 g_assert (plt_entry);
3662 /* The offset is embedded inside the code after the plt entry */
3663 #ifdef MONO_ARCH_AOT_SUPPORTED
3664 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3666 g_assert_not_reached ();
3672 mono_create_ftnptr_malloc (guint8 *code)
3674 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3675 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3677 ftnptr->code = code;
3688 * mono_aot_register_jit_icall:
3690 * Register a JIT icall which is called by trampolines in full-aot mode. This should
3691 * be called from mono_arch_init () during startup.
3694 mono_aot_register_jit_icall (const char *name, gpointer addr)
3696 /* No need for locking */
3697 if (!aot_jit_icall_hash)
3698 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3699 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3705 * Load the function named NAME from the aot image.
3708 load_function (MonoAotModule *amodule, const char *name)
3712 int n_patches, pindex;
3718 symbol = g_strdup_printf ("%s", name);
3719 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3722 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3724 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
3728 symbol = g_strdup_printf ("%s_p", name);
3729 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3732 /* Nothing to patch */
3735 p = amodule->blob + *(guint32*)p;
3737 /* Similar to mono_aot_load_method () */
3739 n_patches = decode_value (p, &p);
3742 MonoJumpInfo *patches;
3745 mp = mono_mempool_new ();
3747 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3750 for (pindex = 0; pindex < n_patches; ++pindex) {
3751 MonoJumpInfo *ji = &patches [pindex];
3754 if (amodule->got [got_slots [pindex]])
3758 * When this code is executed, the runtime may not be initalized yet, so
3759 * resolve the patch info by hand.
3761 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3762 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3763 target = mono_get_lmf_addr;
3764 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3765 target = mono_thread_force_interruption_checkpoint;
3766 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3767 target = mono_exception_from_token;
3768 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3769 target = mono_get_throw_exception ();
3770 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3771 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3772 target = (gpointer)mono_get_trampoline_func (tramp_type2);
3773 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3774 /* atoll is needed because the the offset is unsigned */
3778 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3779 g_assert (res == 1);
3780 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3781 target = mono_create_ftnptr_malloc (target);
3782 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3783 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3784 target = mono_create_ftnptr_malloc (target);
3785 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3786 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3787 target = mono_create_ftnptr_malloc (target);
3788 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3789 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3790 target = mono_create_ftnptr_malloc (target);
3791 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3792 target = mono_thread_get_and_clear_pending_exception;
3793 } else if (strstr (ji->data.name, "generic_trampoline_")) {
3794 target = mono_aot_get_trampoline (ji->data.name);
3795 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3796 /* Registered by mono_arch_init () */
3797 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3799 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3800 g_assert_not_reached ();
3804 /* Hopefully the code doesn't have patches which need method or
3807 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3811 amodule->got [got_slots [pindex]] = target;
3816 mono_mempool_destroy (mp);
3823 * Return the trampoline identified by NAME from the mscorlib AOT file.
3824 * On ppc64, this returns a function descriptor.
3827 mono_aot_get_trampoline (const char *name)
3830 MonoAotModule *amodule;
3832 image = mono_defaults.corlib;
3835 amodule = image->aot_module;
3838 return mono_create_ftnptr_malloc (load_function (amodule, name));
3841 /* Return a given kind of trampoline */
3843 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3845 MonoAotModule *amodule;
3846 int index, tramp_size;
3849 /* Currently, we keep all trampolines in the mscorlib AOT image */
3850 image = mono_defaults.corlib;
3855 amodule = image->aot_module;
3858 *out_amodule = amodule;
3860 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3861 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3863 index = amodule->trampoline_index [tramp_type] ++;
3867 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3869 tramp_size = amodule->info.trampoline_size [tramp_type];
3872 *out_tramp_size = tramp_size;
3874 return amodule->trampolines [tramp_type] + (index * tramp_size);
3878 * Return a specific trampoline from the AOT file.
3881 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3883 MonoAotModule *amodule;
3884 guint32 got_offset, tramp_size;
3885 guint8 *code, *tramp;
3886 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3887 static gboolean inited;
3888 static guint32 num_trampolines;
3894 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3903 if (!generic_trampolines [tramp_type]) {
3906 symbol = mono_get_generic_trampoline_name (tramp_type);
3907 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
3911 tramp = generic_trampolines [tramp_type];
3914 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3916 amodule->got [got_offset] = tramp;
3917 amodule->got [got_offset + 1] = arg1;
3920 *code_len = tramp_size;
3926 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3928 MonoAotModule *amodule;
3932 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3934 amodule->got [got_offset] = ctx;
3935 amodule->got [got_offset + 1] = addr;
3937 /* The caller expects an ftnptr */
3938 return mono_create_ftnptr (mono_domain_get (), code);
3942 mono_aot_get_unbox_trampoline (MonoMethod *method)
3944 guint32 method_index = mono_metadata_token_index (method->token) - 1;
3945 MonoAotModule *amodule;
3947 guint32 *ut, *ut_end, *entry;
3948 int low, high, entry_index;
3950 if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3951 method_index = find_extra_method (method, &amodule);
3952 g_assert (method_index != 0xffffff);
3954 amodule = method->klass->image->aot_module;
3958 ut = amodule->unbox_trampolines;
3959 ut_end = amodule->unbox_trampolines_end;
3961 /* Do a binary search in the sorted table */
3964 high = (ut_end - ut) / 2;
3965 while (low < high) {
3966 entry_index = (low + high) / 2;
3967 entry = &ut [(entry_index * 2)];
3968 if (entry [0] < method_index) {
3969 low = entry_index + 1;
3970 } else if (entry [0] > method_index) {
3973 code = amodule->code + entry [1];
3979 /* The caller expects an ftnptr */
3980 return mono_create_ftnptr (mono_domain_get (), code);
3984 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3989 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
3990 code = load_function (mono_defaults.corlib->aot_module, symbol);
3992 /* The caller expects an ftnptr */
3993 return mono_create_ftnptr (mono_domain_get (), code);
3997 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4002 int i, index, real_count;
4003 MonoAotModule *amodule;
4005 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
4008 for (i = 0; i < count; ++i) {
4009 MonoIMTCheckItem *item = imt_entries [i];
4011 if (item->is_equals)
4015 /* Save the entries into an array */
4016 buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
4018 for (i = 0; i < count; ++i) {
4019 MonoIMTCheckItem *item = imt_entries [i];
4021 if (!item->is_equals)
4024 g_assert (item->key);
4026 buf [(index * 2)] = item->key;
4027 if (item->has_target_code) {
4028 gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
4029 *p = item->value.target_code;
4030 buf [(index * 2) + 1] = p;
4032 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
4036 buf [(index * 2)] = NULL;
4037 buf [(index * 2) + 1] = fail_tramp;
4039 amodule->got [got_offset] = buf;
4045 * mono_aot_set_make_unreadable:
4047 * Set whenever to make all mmaped memory unreadable. In conjuction with a
4048 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
4051 mono_aot_set_make_unreadable (gboolean unreadable)
4055 make_unreadable = unreadable;
4057 if (make_unreadable && !inited) {
4058 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
4063 MonoAotModule *module;
4068 find_map (gpointer key, gpointer value, gpointer user_data)
4070 MonoAotModule *module = (MonoAotModule*)value;
4071 FindMapUserData *data = (FindMapUserData*)user_data;
4074 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4075 data->module = module;
4078 static MonoAotModule*
4079 find_module_for_addr (void *ptr)
4081 FindMapUserData data;
4083 if (!make_unreadable)
4087 data.ptr = (guint8*)ptr;
4090 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4097 * mono_aot_is_pagefault:
4099 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4100 * within memory allocated by this module.
4103 mono_aot_is_pagefault (void *ptr)
4105 if (!make_unreadable)
4109 * Not signal safe, but SIGSEGV's are synchronous, and
4110 * this is only turned on by a MONO_DEBUG option.
4112 return find_module_for_addr (ptr) != NULL;
4116 * mono_aot_handle_pagefault:
4118 * Handle a pagefault caused by an unreadable page by making it readable again.
4121 mono_aot_handle_pagefault (void *ptr)
4123 #ifndef PLATFORM_WIN32
4124 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
4128 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
4129 g_assert (res == 0);
4140 mono_aot_init (void)
4145 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
4151 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4157 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4163 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
4169 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
4175 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
4181 mono_aot_get_plt_entry (guint8 *code)
4187 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4193 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
4198 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
4204 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4206 g_assert_not_reached ();
4212 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4214 g_assert_not_reached ();
4219 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4221 g_assert_not_reached ();
4226 mono_aot_get_trampoline (const char *name)
4228 g_assert_not_reached ();
4233 mono_aot_get_unbox_trampoline (MonoMethod *method)
4235 g_assert_not_reached ();
4240 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4242 g_assert_not_reached ();
4247 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4249 g_assert_not_reached ();
4254 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
4256 g_assert_not_reached ();
4261 mono_aot_register_jit_icall (const char *name, gpointer addr)