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.
12 #include <sys/types.h>
18 #ifdef HAVE_SYS_MMAN_H
27 #ifdef HAVE_EXECINFO_H
34 #ifdef HAVE_SYS_WAIT_H
35 #include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
38 #ifdef HAVE_DL_ITERATE_PHDR
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/class.h>
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/metadata/assembly.h>
49 #include <mono/metadata/metadata-internals.h>
50 #include <mono/metadata/marshal.h>
51 #include <mono/metadata/gc-internal.h>
52 #include <mono/metadata/monitor.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/utils/mono-logger.h>
55 #include <mono/utils/mono-mmap.h>
56 #include "mono/utils/mono-compiler.h"
57 #include <mono/utils/mono-counters.h>
65 #define SHARED_EXT ".dll"
66 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
67 #define SHARED_EXT ".dylib"
69 #define SHARED_EXT ".so"
72 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
73 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
75 typedef struct MonoAotModule {
77 /* Pointer to the Global Offset Table */
79 GHashTable *name_cache;
80 GHashTable *extra_methods;
81 /* Maps methods to their code */
82 GHashTable *method_to_code;
83 /* Maps pointers into the method info to the methods themselves */
84 GHashTable *method_ref_to_method;
85 MonoAssemblyName *image_names;
87 MonoAssembly *assembly;
88 MonoImage **image_table;
89 guint32 image_table_len;
100 /* This contains <offset, index> pairs sorted by offset */
101 /* This is needed because LLVM emitted methods can be in any order */
102 gint32 *sorted_code_offsets;
103 guint32 *method_info_offsets;
104 guint32 *got_info_offsets;
105 guint32 *ex_info_offsets;
106 guint32 *class_info_offsets;
107 guint32 *methods_loaded;
108 guint16 *class_name_table;
109 guint32 *extra_method_table;
110 guint32 *extra_method_info_offsets;
113 /* Points to the the GNU .eh_frame_hdr section, if it exists */
114 guint8 *eh_frame_hdr;
116 /* Points to the trampolines */
117 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
118 /* The first unused trampoline of each kind */
119 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
121 MonoAotFileInfo info;
127 static GHashTable *aot_modules;
128 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
129 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
130 static CRITICAL_SECTION aot_mutex;
133 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
134 * AOT modules registered by mono_aot_register_module ().
136 static GHashTable *static_aot_modules;
139 * Maps MonoJitInfo* to the aot module they belong to, this can be different
140 * from ji->method->klass->image's aot module for generic instances.
142 static GHashTable *ji_to_amodule;
145 * Whenever to AOT compile loaded assemblies on demand and store them in
146 * a cache under $HOME/.mono/aot-cache.
148 static gboolean use_aot_cache = FALSE;
151 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
152 * use_aot_cache is TRUE.
154 static gboolean spawn_compiler = TRUE;
157 static gint32 mono_last_aot_method = -1;
159 static gboolean make_unreadable = FALSE;
160 static guint32 name_table_accesses = 0;
162 /* Used to speed-up find_aot_module () */
163 static gsize aot_code_low_addr = (gssize)-1;
164 static gsize aot_code_high_addr = 0;
167 init_plt (MonoAotModule *info);
169 /*****************************************************/
171 /*****************************************************/
174 load_image (MonoAotModule *module, int index)
176 MonoAssembly *assembly;
177 MonoImageOpenStatus status;
179 g_assert (index < module->image_table_len);
181 if (module->image_table [index])
182 return module->image_table [index];
183 if (module->out_of_date)
186 assembly = mono_assembly_load (&module->image_names [index], NULL, &status);
188 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable because dependency %s is not found.\n", module->aot_name, module->image_names [index].name);
189 module->out_of_date = TRUE;
193 if (strcmp (assembly->image->guid, module->image_guids [index])) {
194 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date (Older than dependency %s).\n", module->aot_name, module->image_names [index].name);
195 module->out_of_date = TRUE;
199 module->image_table [index] = assembly->image;
200 return assembly->image;
205 decode_value (guint8 *ptr, guint8 **rptr)
210 if ((b & 0x80) == 0){
213 } else if ((b & 0x40) == 0){
214 len = ((b & 0x3f) << 8 | ptr [1]);
216 } else if (b != 0xff) {
217 len = ((b & 0x1f) << 24) |
224 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
230 //printf ("DECODE: %d.\n", len);
235 * mono_aot_get_method:
237 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
241 mono_aot_get_offset (guint32 *table, int index)
243 int i, group, ngroups, index_entry_size;
244 int start_offset, offset, noffsets, group_size;
245 guint8 *data_start, *p;
246 guint32 *index32 = NULL;
247 guint16 *index16 = NULL;
249 noffsets = table [0];
250 group_size = table [1];
252 index_entry_size = table [3];
253 group = index / group_size;
255 if (index_entry_size == 2) {
256 index16 = (guint16*)&table [4];
257 data_start = (guint8*)&index16 [ngroups];
258 p = data_start + index16 [group];
260 index32 = (guint32*)&table [4];
261 data_start = (guint8*)&index32 [ngroups];
262 p = data_start + index32 [group];
265 /* offset will contain the value of offsets [group * group_size] */
266 offset = start_offset = decode_value (p, &p);
267 for (i = group * group_size + 1; i <= index; ++i) {
268 offset += decode_value (p, &p);
271 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
277 decode_method_ref_2 (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
280 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
282 static MonoGenericInst*
283 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
286 MonoType **type_argv;
287 MonoGenericInst *inst;
290 type_argc = decode_value (p, &p);
291 type_argv = g_new0 (MonoType*, type_argc);
293 for (i = 0; i < type_argc; ++i) {
294 MonoClass *pclass = decode_klass_ref (module, p, &p);
299 type_argv [i] = &pclass->byval_arg;
302 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
311 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
313 gboolean has_class_inst, has_method_inst;
316 has_class_inst = decode_value (p, &p);
317 if (has_class_inst) {
318 ctx->class_inst = decode_generic_inst (module, p, &p);
319 if (!ctx->class_inst)
322 has_method_inst = decode_value (p, &p);
323 if (has_method_inst) {
324 ctx->method_inst = decode_generic_inst (module, p, &p);
325 if (!ctx->method_inst)
334 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
337 MonoClass *klass, *eklass;
341 token = decode_value (p, &p);
346 if (mono_metadata_token_table (token) == 0) {
347 image = load_image (module, decode_value (p, &p));
350 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token);
351 } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
352 if (token == MONO_TOKEN_TYPE_SPEC) {
353 MonoTypeEnum type = decode_value (p, &p);
355 if (type == MONO_TYPE_GENERICINST) {
357 MonoGenericContext ctx;
360 gclass = decode_klass_ref (module, p, &p);
361 g_assert (gclass->generic_container);
363 memset (&ctx, 0, sizeof (ctx));
364 ctx.class_inst = decode_generic_inst (module, p, &p);
367 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
368 klass = mono_class_from_mono_type (type);
369 mono_metadata_free_type (type);
370 } else if ((type == MONO_TYPE_VAR) || (type == MONO_TYPE_MVAR)) {
372 MonoGenericContainer *container;
374 int num = decode_value (p, &p);
375 gboolean is_method = decode_value (p, &p);
378 MonoMethod *method_def;
379 g_assert (type == MONO_TYPE_MVAR);
380 method_def = decode_method_ref_2 (module, p, &p);
384 container = mono_method_get_generic_container (method_def);
386 MonoClass *class_def;
387 g_assert (type == MONO_TYPE_VAR);
388 class_def = decode_klass_ref (module, p, &p);
392 container = class_def->generic_container;
395 g_assert (container);
397 // FIXME: Memory management
398 t = g_new0 (MonoType, 1);
400 t->data.generic_param = mono_generic_container_get_param (container, num);
402 // FIXME: Maybe use types directly to avoid
403 // the overhead of creating MonoClass-es
404 klass = mono_class_from_mono_type (t);
408 g_assert_not_reached ();
411 image = load_image (module, decode_value (p, &p));
414 klass = mono_class_get (image, token);
416 } else if (token == MONO_TOKEN_TYPE_DEF) {
418 image = load_image (module, decode_value (p, &p));
421 rank = decode_value (p, &p);
422 eklass = decode_klass_ref (module, p, &p);
423 klass = mono_array_class_get (eklass, rank);
425 g_assert_not_reached ();
428 mono_class_init (klass);
434 static MonoClassField*
435 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
437 MonoClass *klass = decode_klass_ref (module, buf, &buf);
444 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
448 return mono_class_get_field (klass, token);
452 * can_method_ref_match_method:
454 * Determine if calling decode_method_ref_2 on P could return the same method as
455 * METHOD. This is an optimization to avoid calling decode_method_ref_2 () which
456 * would create MonoMethods which are not needed etc.
459 can_method_ref_match_method (MonoAotModule *module, guint8 *buf, MonoMethod *method)
462 guint32 image_index, value;
464 /* Keep this in sync with decode_method_ref () */
465 value = decode_value (p, &p);
466 image_index = value >> 24;
468 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
469 guint32 wrapper_type;
471 if (!method->wrapper_type)
474 wrapper_type = decode_value (p, &p);
476 if (method->wrapper_type != wrapper_type)
478 } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) {
480 } else if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
481 if (method->wrapper_type)
491 * Decode a method reference, and return its image and token. This avoids loading
492 * metadata for the method if the caller does not need it. If the method has no token,
493 * then it is loaded from metadata and METHOD is set to the method instance.
496 decode_method_ref (MonoAotModule *module, guint32 *token, MonoMethod **method, gboolean *no_aot_trampoline, guint8 *buf, guint8 **endbuf)
498 guint32 image_index, value;
499 MonoImage *image = NULL;
504 if (no_aot_trampoline)
505 *no_aot_trampoline = FALSE;
507 value = decode_value (p, &p);
508 image_index = value >> 24;
510 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
511 if (no_aot_trampoline)
512 *no_aot_trampoline = TRUE;
513 value = decode_value (p, &p);
514 image_index = value >> 24;
517 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
518 guint32 wrapper_type;
520 wrapper_type = decode_value (p, &p);
523 image = mono_defaults.corlib;
525 switch (wrapper_type) {
526 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
527 MonoMethod *m = decode_method_ref_2 (module, p, &p);
531 mono_class_init (m->klass);
532 *method = mono_marshal_get_remoting_invoke_with_check (m);
535 case MONO_WRAPPER_PROXY_ISINST: {
536 MonoClass *klass = decode_klass_ref (module, p, &p);
539 *method = mono_marshal_get_proxy_cancast (klass);
542 case MONO_WRAPPER_LDFLD:
543 case MONO_WRAPPER_LDFLDA:
544 case MONO_WRAPPER_STFLD:
545 case MONO_WRAPPER_ISINST: {
546 MonoClass *klass = decode_klass_ref (module, p, &p);
549 if (wrapper_type == MONO_WRAPPER_LDFLD)
550 *method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
551 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
552 *method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
553 else if (wrapper_type == MONO_WRAPPER_STFLD)
554 *method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
555 else if (wrapper_type == MONO_WRAPPER_ISINST)
556 *method = mono_marshal_get_isinst (klass);
558 g_assert_not_reached ();
561 case MONO_WRAPPER_LDFLD_REMOTE:
562 *method = mono_marshal_get_ldfld_remote_wrapper (NULL);
564 case MONO_WRAPPER_STFLD_REMOTE:
565 *method = mono_marshal_get_stfld_remote_wrapper (NULL);
567 case MONO_WRAPPER_ALLOC: {
568 int atype = decode_value (p, &p);
570 *method = mono_gc_get_managed_allocator_by_type (atype);
573 case MONO_WRAPPER_STELEMREF:
574 *method = mono_marshal_get_stelemref ();
576 case MONO_WRAPPER_SYNCHRONIZED: {
577 MonoMethod *m = decode_method_ref_2 (module, p, &p);
581 *method = mono_marshal_get_synchronized_wrapper (m);
584 case MONO_WRAPPER_UNKNOWN: {
585 MonoMethodDesc *desc;
586 MonoMethod *orig_method;
587 int subtype = decode_value (p, &p);
589 if (subtype == MONO_AOT_WRAPPER_MONO_ENTER)
590 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
591 else if (subtype == MONO_AOT_WRAPPER_MONO_EXIT)
592 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
594 g_assert_not_reached ();
595 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
596 g_assert (orig_method);
597 mono_method_desc_free (desc);
598 *method = mono_monitor_get_fast_path (orig_method);
601 case MONO_WRAPPER_RUNTIME_INVOKE: {
603 MonoMethod *m = decode_method_ref_2 (module, p, &p);
607 *method = mono_marshal_get_runtime_invoke (m, FALSE);
611 g_assert_not_reached ();
613 } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) {
614 /* Can't decode these */
615 g_assert_not_reached ();
616 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
617 image_index = decode_value (p, &p);
618 *token = decode_value (p, &p);
620 image = load_image (module, image_index);
623 } else if (image_index == MONO_AOT_METHODREF_GINST) {
625 MonoGenericContext ctx;
628 * These methods do not have a token which resolves them, so we
629 * resolve them immediately.
631 klass = decode_klass_ref (module, p, &p);
635 image_index = decode_value (p, &p);
636 *token = decode_value (p, &p);
638 image = load_image (module, image_index);
642 *method = mono_get_method_full (image, *token, NULL, NULL);
646 memset (&ctx, 0, sizeof (ctx));
648 if (FALSE && klass->generic_class) {
649 ctx.class_inst = klass->generic_class->context.class_inst;
650 ctx.method_inst = NULL;
652 *method = mono_class_inflate_generic_method_full (*method, klass, &ctx);
655 memset (&ctx, 0, sizeof (ctx));
657 if (!decode_generic_context (module, &ctx, p, &p))
660 *method = mono_class_inflate_generic_method_full (*method, klass, &ctx);
661 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
665 klass = decode_klass_ref (module, p, &p);
668 method_type = decode_value (p, &p);
670 switch (method_type) {
672 *method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
675 *method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
678 *method = mono_class_get_method_from_name (klass, "Get", -1);
681 *method = mono_class_get_method_from_name (klass, "Address", -1);
684 *method = mono_class_get_method_from_name (klass, "Set", -1);
687 g_assert_not_reached ();
690 g_assert (image_index < MONO_AOT_METHODREF_MIN);
691 *token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
693 image = load_image (module, image_index);
704 * decode_method_ref_2:
706 * Similar to decode_method_ref, but resolve and return the method itself.
709 decode_method_ref_2 (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
713 MonoImage *image = decode_method_ref (module, &token, &method, NULL, buf, endbuf);
719 method = mono_get_method (image, token, NULL);
725 make_writable (guint8* addr, guint32 len)
731 g_error ("Attempt to make AOT memory writable while running in aot-only mode.\n");
733 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1));
734 pages = (addr + len - page_start + mono_pagesize () - 1) / mono_pagesize ();
736 err = mono_mprotect (page_start, pages * mono_pagesize (), MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_EXEC);
741 create_cache_structure (void)
747 home = g_get_home_dir ();
751 tmp = g_build_filename (home, ".mono", NULL);
752 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
753 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
757 err = mkdir (tmp, 0777);
760 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
766 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
767 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
768 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
772 err = mkdir (tmp, 0777);
775 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
784 * load_aot_module_from_cache:
786 * Experimental code to AOT compile loaded assemblies on demand.
789 * - Add environment variable MONO_AOT_CACHE_OPTIONS
790 * - Add options for controlling the cache size
791 * - Handle full cache by deleting old assemblies lru style
792 * - Add options for excluding assemblies during development
793 * - Maybe add a threshold after an assembly is AOT compiled
794 * - invoking a new mono process is a security risk
795 * - recompile the AOT module if one of its dependencies changes
798 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
800 char *fname, *cmd, *tmp2, *aot_options;
809 if (assembly->image->dynamic)
812 create_cache_structure ();
814 home = g_get_home_dir ();
816 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
817 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
821 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
822 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
825 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
827 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
829 aot_options = g_strdup_printf ("outfile=%s", fname);
831 if (spawn_compiler) {
832 /* FIXME: security */
833 /* FIXME: Has to pass the assembly loading path to the child process */
834 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
836 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
838 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
840 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
841 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
843 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
850 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
852 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
854 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
858 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
860 g_free (aot_options);
867 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
871 guint16 *table, *entry;
875 /* The first entry points to the hash */
879 table_size = table [0];
882 hash = mono_aot_str_hash (name) % table_size;
884 entry = &table [hash * 2];
886 /* Search the hash for the index into the globals table */
888 while (entry [0] != 0) {
889 guint32 index = entry [0] - 1;
890 guint32 next = entry [1];
892 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
894 if (!strcmp (globals [index * 2], name)) {
895 global_index = index;
900 entry = &table [next * 2];
906 if (global_index != -1)
907 *value = globals [global_index * 2 + 1];
911 mono_dl_symbol (module, name, value);
915 #ifdef HAVE_DL_ITERATE_PHDR
917 dl_callback (struct dl_phdr_info *info, size_t size, void *data)
920 MonoAotModule *amodule = data;
922 if (!strcmp (amodule->aot_name, info->dlpi_name)) {
923 for (j = 0; j < info->dlpi_phnum; j++) {
924 if (info->dlpi_phdr [j].p_type == PT_GNU_EH_FRAME)
925 amodule->eh_frame_hdr = (guint8*)(info->dlpi_addr + info->dlpi_phdr [j].p_vaddr);
935 load_aot_module (MonoAssembly *assembly, gpointer user_data)
938 MonoAotModule *amodule;
940 gboolean usable = TRUE;
941 char *saved_guid = NULL;
942 char *aot_version = NULL;
943 char *runtime_version, *build_info;
944 char *opt_flags = NULL;
946 gboolean full_aot = FALSE;
947 MonoAotFileInfo *file_info = NULL;
951 if (mono_compile_aot)
954 if (assembly->image->aot_module)
956 * Already loaded. This can happen because the assembly loading code might invoke
957 * the assembly load hooks multiple times for the same assembly.
961 if (assembly->image->dynamic)
964 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
968 if (static_aot_modules)
969 globals = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
975 /* Statically linked AOT module */
977 aot_name = g_strdup_printf ("%s", assembly->aname.name);
978 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
981 sofile = load_aot_module_from_cache (assembly, &aot_name);
984 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
986 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
989 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
995 if (!sofile && !globals) {
997 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1004 find_symbol (sofile, globals, "mono_assembly_guid", (gpointer *) &saved_guid);
1005 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &aot_version);
1006 find_symbol (sofile, globals, "mono_aot_opt_flags", (gpointer *)&opt_flags);
1007 find_symbol (sofile, globals, "mono_runtime_version", (gpointer *)&runtime_version);
1008 find_symbol (sofile, globals, "mono_aot_got_addr", (gpointer *)&got_addr);
1010 if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
1011 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s has wrong file format version (expected %s got %s)\n", aot_name, MONO_AOT_FILE_VERSION, aot_version);
1015 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
1016 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
1021 build_info = mono_get_runtime_build_info ();
1022 if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, build_info)))) {
1023 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled against runtime version '%s' while this runtime has version '%s'.\n", aot_name, runtime_version, build_info);
1026 g_free (build_info);
1028 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&file_info);
1029 g_assert (file_info);
1031 full_aot = ((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1033 if (mono_aot_only && !full_aot) {
1034 fprintf (stderr, "Can't use AOT image '%s' in aot-only mode because it is not compiled with --aot=full.\n", aot_name);
1037 if (!mono_aot_only && full_aot) {
1038 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with --aot=full.\n", aot_name);
1042 if ((((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1043 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with LLVM.\n", aot_name);
1048 if (mono_aot_only) {
1049 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode.\n", aot_name);
1054 mono_dl_close (sofile);
1055 assembly->image->aot_module = NULL;
1059 amodule = g_new0 (MonoAotModule, 1);
1060 amodule->aot_name = aot_name;
1061 amodule->assembly = assembly;
1063 memcpy (&amodule->info, file_info, sizeof (*file_info));
1065 amodule->got = *got_addr;
1066 amodule->got [0] = assembly->image;
1067 amodule->globals = globals;
1068 amodule->sofile = sofile;
1069 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1071 /* Read image table */
1073 guint32 table_len, i;
1076 find_symbol (sofile, globals, "mono_image_table", (gpointer *)&table);
1079 table_len = *(guint32*)table;
1080 table += sizeof (guint32);
1081 amodule->image_table = g_new0 (MonoImage*, table_len);
1082 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1083 amodule->image_guids = g_new0 (char*, table_len);
1084 amodule->image_table_len = table_len;
1085 for (i = 0; i < table_len; ++i) {
1086 MonoAssemblyName *aname = &(amodule->image_names [i]);
1088 aname->name = g_strdup (table);
1089 table += strlen (table) + 1;
1090 amodule->image_guids [i] = g_strdup (table);
1091 table += strlen (table) + 1;
1093 aname->culture = g_strdup (table);
1094 table += strlen (table) + 1;
1095 memcpy (aname->public_key_token, table, strlen (table) + 1);
1096 table += strlen (table) + 1;
1098 table = ALIGN_PTR_TO (table, 8);
1099 aname->flags = *(guint32*)table;
1101 aname->major = *(guint32*)table;
1103 aname->minor = *(guint32*)table;
1105 aname->build = *(guint32*)table;
1107 aname->revision = *(guint32*)table;
1112 /* Read method and method_info tables */
1113 find_symbol (sofile, globals, "code_offsets", (gpointer*)&amodule->code_offsets);
1114 find_symbol (sofile, globals, "methods", (gpointer*)&amodule->code);
1115 find_symbol (sofile, globals, "methods_end", (gpointer*)&amodule->code_end);
1116 find_symbol (sofile, globals, "method_info_offsets", (gpointer*)&amodule->method_info_offsets);
1117 find_symbol (sofile, globals, "ex_info_offsets", (gpointer*)&amodule->ex_info_offsets);
1118 find_symbol (sofile, globals, "blob", (gpointer*)&amodule->blob);
1119 find_symbol (sofile, globals, "class_info_offsets", (gpointer*)&amodule->class_info_offsets);
1120 find_symbol (sofile, globals, "class_name_table", (gpointer *)&amodule->class_name_table);
1121 find_symbol (sofile, globals, "extra_method_table", (gpointer *)&amodule->extra_method_table);
1122 find_symbol (sofile, globals, "extra_method_info_offsets", (gpointer *)&amodule->extra_method_info_offsets);
1123 find_symbol (sofile, globals, "got_info_offsets", (gpointer*)&amodule->got_info_offsets);
1124 find_symbol (sofile, globals, "specific_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC]));
1125 find_symbol (sofile, globals, "static_rgctx_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX]));
1126 find_symbol (sofile, globals, "imt_thunks", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK]));
1127 find_symbol (sofile, globals, "unwind_info", (gpointer)&amodule->unwind_info);
1128 find_symbol (sofile, globals, "mem_end", (gpointer*)&amodule->mem_end);
1130 amodule->mem_begin = amodule->code;
1132 find_symbol (sofile, globals, "plt", (gpointer*)&amodule->plt);
1133 find_symbol (sofile, globals, "plt_end", (gpointer*)&amodule->plt_end);
1135 if (make_unreadable) {
1136 #ifndef TARGET_WIN32
1139 int pages, err, len;
1141 addr = amodule->mem_begin;
1142 len = amodule->mem_end - amodule->mem_begin;
1144 /* Round down in both directions to avoid modifying data which is not ours */
1145 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1146 pages = ((addr + len - page_start + mono_pagesize () - 1) / mono_pagesize ()) - 1;
1147 err = mono_mprotect (page_start, pages * mono_pagesize (), MONO_MMAP_NONE);
1148 g_assert (err == 0);
1154 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1155 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1157 g_hash_table_insert (aot_modules, assembly, amodule);
1160 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1162 assembly->image->aot_module = amodule;
1164 #ifdef HAVE_DL_ITERATE_PHDR
1165 /* Lookup the address of the .eh_frame_hdr () section if available */
1166 dl_iterate_phdr (dl_callback, amodule);
1169 if (mono_aot_only) {
1170 if (mono_defaults.corlib) {
1171 /* The second got slot contains the mscorlib got addr */
1172 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1174 amodule->got [1] = mscorlib_amodule->got;
1176 amodule->got [1] = amodule->got;
1181 * Since we store methoddef and classdef tokens when referring to methods/classes in
1182 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1183 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1184 * non-lazily, since we can't handle out-of-date errors later.
1186 for (i = 0; i < amodule->image_table_len; ++i)
1187 load_image (amodule, i);
1189 if (amodule->out_of_date) {
1190 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);
1191 if (mono_aot_only) {
1192 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);
1197 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1201 * mono_aot_register_globals:
1203 * This is called by the ctor function in AOT images compiled with the
1204 * 'no-dlsym' option.
1207 mono_aot_register_globals (gpointer *globals)
1209 g_assert_not_reached ();
1213 * mono_aot_register_module:
1215 * This should be called by embedding code to register AOT modules statically linked
1216 * into the executable. AOT_INFO should be the value of the
1217 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1220 mono_aot_register_module (gpointer *aot_info)
1228 /* Determine the assembly name */
1229 find_symbol (NULL, globals, "mono_aot_assembly_name", (gpointer*)&aname);
1232 /* This could be called before startup */
1236 if (!static_aot_modules)
1237 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1239 g_hash_table_insert (static_aot_modules, aname, globals);
1246 mono_aot_init (void)
1248 InitializeCriticalSection (&aot_mutex);
1249 aot_modules = g_hash_table_new (NULL, NULL);
1251 mono_install_assembly_load_hook (load_aot_module, NULL);
1253 if (g_getenv ("MONO_LASTAOT"))
1254 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1255 if (g_getenv ("MONO_AOT_CACHE"))
1256 use_aot_cache = TRUE;
1260 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1264 info->vtable_size = decode_value (buf, &buf);
1265 if (info->vtable_size == -1)
1268 flags = decode_value (buf, &buf);
1269 info->ghcimpl = (flags >> 0) & 0x1;
1270 info->has_finalize = (flags >> 1) & 0x1;
1271 info->has_cctor = (flags >> 2) & 0x1;
1272 info->has_nested_classes = (flags >> 3) & 0x1;
1273 info->blittable = (flags >> 4) & 0x1;
1274 info->has_references = (flags >> 5) & 0x1;
1275 info->has_static_refs = (flags >> 6) & 0x1;
1276 info->no_special_static_fields = (flags >> 7) & 0x1;
1277 info->is_generic_container = (flags >> 8) & 0x1;
1279 if (info->has_cctor) {
1280 MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, NULL, NULL, buf, &buf);
1284 if (info->has_finalize) {
1285 info->finalize_image = decode_method_ref (module, &info->finalize_token, NULL, NULL, buf, &buf);
1286 if (!info->finalize_image)
1290 info->instance_size = decode_value (buf, &buf);
1291 info->class_size = decode_value (buf, &buf);
1292 info->packing_size = decode_value (buf, &buf);
1293 info->min_align = decode_value (buf, &buf);
1301 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1304 MonoClass *klass = vtable->klass;
1305 MonoAotModule *aot_module = klass->image->aot_module;
1307 MonoCachedClassInfo class_info;
1311 gboolean no_aot_trampoline;
1313 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !aot_module)
1316 info = &aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1319 err = decode_cached_class_info (aot_module, &class_info, p, &p);
1323 for (i = 0; i < slot; ++i)
1324 decode_method_ref (aot_module, &token, NULL, NULL, p, &p);
1326 image = decode_method_ref (aot_module, &token, NULL, &no_aot_trampoline, p, &p);
1329 if (no_aot_trampoline)
1332 if (mono_metadata_token_index (token) == 0)
1335 return mono_aot_get_method_from_token (domain, image, token);
1339 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1341 MonoAotModule *aot_module = klass->image->aot_module;
1345 if (klass->rank || !aot_module)
1348 p = (guint8*)&aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1350 err = decode_cached_class_info (aot_module, res, p, &p);
1358 * mono_aot_get_class_from_name:
1360 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1361 * using a cache stored in the AOT file.
1362 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1364 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
1368 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1370 MonoAotModule *aot_module = image->aot_module;
1371 guint16 *table, *entry;
1374 char full_name_buf [1024];
1376 const char *name2, *name_space2;
1378 guint32 cols [MONO_TYPEDEF_SIZE];
1379 GHashTable *nspace_table;
1381 if (!aot_module || !aot_module->class_name_table)
1388 /* First look in the cache */
1389 if (!aot_module->name_cache)
1390 aot_module->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1391 nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
1393 *klass = g_hash_table_lookup (nspace_table, name);
1400 table_size = aot_module->class_name_table [0];
1401 table = aot_module->class_name_table + 1;
1403 if (name_space [0] == '\0')
1404 full_name = g_strdup_printf ("%s", name);
1406 if (strlen (name_space) + strlen (name) < 1000) {
1407 sprintf (full_name_buf, "%s.%s", name_space, name);
1408 full_name = full_name_buf;
1410 full_name = g_strdup_printf ("%s.%s", name_space, name);
1413 hash = mono_aot_str_hash (full_name) % table_size;
1414 if (full_name != full_name_buf)
1417 entry = &table [hash * 2];
1419 if (entry [0] != 0) {
1420 t = &image->tables [MONO_TABLE_TYPEDEF];
1423 guint32 index = entry [0];
1424 guint32 next = entry [1];
1425 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1427 name_table_accesses ++;
1429 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1431 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1432 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1434 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1436 *klass = mono_class_get (image, token);
1441 nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
1442 if (!nspace_table) {
1443 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1444 g_hash_table_insert (aot_module->name_cache, (char*)name_space2, nspace_table);
1446 g_hash_table_insert (nspace_table, (char*)name2, *klass);
1453 entry = &table [next * 2];
1465 #define DW_EH_PE_omit 0xff
1466 #define DW_EH_PE_uleb128 0x01
1467 #define DW_EH_PE_udata2 0x02
1468 #define DW_EH_PE_udata4 0x03
1469 #define DW_EH_PE_udata8 0x04
1470 #define DW_EH_PE_sleb128 0x09
1471 #define DW_EH_PE_sdata2 0x0A
1472 #define DW_EH_PE_sdata4 0x0B
1473 #define DW_EH_PE_sdata8 0x0C
1475 #define DW_EH_PE_absptr 0x00
1476 #define DW_EH_PE_pcrel 0x10
1477 #define DW_EH_PE_datarel 0x30
1478 #define DW_EH_PE_omit 0xff
1483 guint8 eh_frame_ptr_enc;
1484 guint8 fde_count_enc;
1492 * Decode the exception handling information in the .eh_frame section of the AOT
1493 * file belong to CODE, and construct a MonoJitInfo structure from it.
1494 * LOCKING: Acquires the domain lock.
1497 decode_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
1498 MonoMethod *method, guint8 *code, MonoJitInfo *jinfo)
1502 guint8 *eh_frame, *unwind_info;
1503 guint32 eh_frame_ptr;
1506 int pos, left, right, offset, offset1, offset2;
1507 guint32 unw_len, code_len;
1509 g_assert (amodule->eh_frame_hdr);
1511 // http://refspecs.freestandards.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html
1512 hdr = (eh_frame_hdr*)amodule->eh_frame_hdr;
1513 g_assert (hdr->version == 1);
1514 g_assert (hdr->eh_frame_ptr_enc == (DW_EH_PE_pcrel | DW_EH_PE_sdata4));
1515 g_assert (hdr->fde_count_enc == DW_EH_PE_udata4);
1516 g_assert (hdr->table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4));
1519 eh_frame_ptr = *(guint32*)p;
1521 fde_count = *(guint32*)p;
1525 /* Binary search in the table to find the entry for code */
1526 offset = code - amodule->eh_frame_hdr;
1531 pos = (left + right) / 2;
1533 offset1 = table [(pos * 2)];
1534 if (pos + 1 == fde_count)
1536 offset2 = amodule->code_end - amodule->code;
1538 offset2 = table [(pos + 1) * 2];
1540 if (offset < offset1)
1542 else if (offset >= offset2)
1548 g_assert (code >= amodule->eh_frame_hdr + table [(pos * 2)]);
1549 if (pos < fde_count)
1550 g_assert (code < amodule->eh_frame_hdr + table [(pos * 2) + 2]);
1552 eh_frame = amodule->eh_frame_hdr + table [(pos * 2) + 1];
1554 unwind_info = mono_unwind_get_ops_from_fde (eh_frame, &unw_len, &code_len);
1556 jinfo->code_size = code_len;
1557 jinfo->used_regs = mono_cache_unwind_info (unwind_info, unw_len);
1558 jinfo->method = method;
1559 jinfo->code_start = code;
1560 jinfo->domain_neutral = 0;
1561 /* This signals that used_regs points to a normal cached unwind info */
1562 jinfo->from_aot = 0;
1566 * LOCKING: Acquires the domain lock.
1569 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
1570 MonoMethod *method, guint8* ex_info, guint8 *addr,
1571 guint8 *code, guint32 code_len)
1575 guint used_int_regs, flags;
1576 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points;
1579 int generic_info_size;
1581 /* Load the method info from the AOT file */
1584 flags = decode_value (p, &p);
1585 has_generic_jit_info = (flags & 1) != 0;
1586 has_dwarf_unwind_info = (flags & 2) != 0;
1587 has_clauses = (flags & 4) != 0;
1588 has_seq_points = (flags & 8) != 0;
1589 from_llvm = (flags & 16) != 0;
1590 if (has_dwarf_unwind_info) {
1593 offset = decode_value (p, &p);
1594 g_assert (offset < (1 << 30));
1595 used_int_regs = offset;
1597 used_int_regs = decode_value (p, &p);
1599 if (has_generic_jit_info)
1600 generic_info_size = sizeof (MonoGenericJitInfo);
1602 generic_info_size = 0;
1604 /* Exception table */
1606 int num_clauses = decode_value (p, &p);
1609 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size);
1610 jinfo->num_clauses = num_clauses;
1612 for (i = 0; i < num_clauses; ++i) {
1613 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
1615 ei->flags = decode_value (p, &p);
1616 ei->exvar_offset = decode_value (p, &p);
1618 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
1619 ei->data.filter = code + decode_value (p, &p);
1621 if (decode_value (p, &p))
1622 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1625 ei->try_start = code + decode_value (p, &p);
1626 ei->try_end = code + decode_value (p, &p);
1627 ei->handler_start = code + decode_value (p, &p);
1631 jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + generic_info_size);
1635 /* LLVM compiled method */
1636 /* The info is in the .eh_frame section */
1637 decode_eh_frame (amodule, domain, method, code, jinfo);
1639 jinfo->code_size = code_len;
1640 jinfo->used_regs = used_int_regs;
1641 jinfo->method = method;
1642 jinfo->code_start = code;
1643 jinfo->domain_neutral = 0;
1644 jinfo->from_aot = 1;
1647 if (has_generic_jit_info) {
1648 MonoGenericJitInfo *gi;
1650 jinfo->has_generic_jit_info = 1;
1652 gi = mono_jit_info_get_generic_jit_info (jinfo);
1655 gi->has_this = decode_value (p, &p);
1656 gi->this_reg = decode_value (p, &p);
1657 gi->this_offset = decode_value (p, &p);
1659 /* This currently contains no data */
1660 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
1662 jinfo->method = decode_method_ref_2 (amodule, p, &p);
1665 if (has_seq_points) {
1666 GPtrArray *seq_points;
1667 int il_offset, native_offset, last_il_offset, last_native_offset;
1669 int len = decode_value (p, &p);
1671 seq_points = g_ptr_array_new ();
1672 last_il_offset = last_native_offset = 0;
1673 for (i = 0; i < len; i += 2) {
1674 il_offset = last_il_offset + decode_value (p, &p);
1675 native_offset = last_native_offset + decode_value (p, &p);
1677 g_ptr_array_add (seq_points, GINT_TO_POINTER (il_offset));
1678 g_ptr_array_add (seq_points, GINT_TO_POINTER (native_offset));
1680 last_il_offset = il_offset;
1681 last_native_offset = native_offset;
1684 mono_domain_lock (domain);
1685 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
1686 mono_domain_unlock (domain);
1689 /* Load debug info */
1690 buf_len = decode_value (p, &p);
1691 mono_debug_add_aot_method (domain, method, code, p, buf_len);
1693 if (amodule != jinfo->method->klass->image->aot_module) {
1696 ji_to_amodule = g_hash_table_new (NULL, NULL);
1697 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
1705 * mono_aot_get_unwind_info:
1707 * Return a pointer to the DWARF unwind info belonging to JI.
1710 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
1712 MonoAotModule *amodule = ji->method->klass->image->aot_module;
1714 guint8 *code = ji->code_start;
1717 g_assert (ji->from_aot);
1719 if (!(code >= amodule->code && code <= amodule->code_end)) {
1720 /* ji belongs to a different aot module than amodule */
1722 g_assert (ji_to_amodule);
1723 amodule = g_hash_table_lookup (ji_to_amodule, ji);
1725 g_assert (code >= amodule->code && code <= amodule->code_end);
1728 p = amodule->unwind_info + ji->used_regs;
1729 *unwind_info_len = decode_value (p, &p);
1734 compare_ints (const void *a, const void *b)
1736 return *(gint32*)a - *(gint32*)b;
1740 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
1742 int pos, left, right, offset, offset1, offset2, code_len;
1743 int method_index, table_len, is_wrapper;
1745 MonoAotModule *amodule = image->aot_module;
1748 guint8 *code, *ex_info, *p;
1750 int nmethods = amodule->info.nmethods;
1751 gint32 *code_offsets;
1757 if (domain != mono_get_root_domain ())
1761 offset = (guint8*)addr - amodule->code;
1763 /* Compute a sorted table mapping code offsets to method indexes. */
1764 if (!amodule->sorted_code_offsets) {
1765 code_offsets = g_new0 (gint32, nmethods * 2);
1766 for (i = 0; i < nmethods; ++i) {
1767 code_offsets [(i * 2)] = amodule->code_offsets [i];
1768 code_offsets [(i *2) + 1] = i;
1770 /* FIXME: Use a merge sort as this is mostly sorted */
1771 qsort (code_offsets, nmethods, sizeof (gint32) * 2, compare_ints);
1772 for (i = 0; i < nmethods -1; ++i)
1773 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
1775 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
1776 /* Somebody got in before us */
1777 g_free (code_offsets);
1780 code_offsets = amodule->sorted_code_offsets;
1782 /* Binary search in the sorted_code_offsets table */
1786 pos = (left + right) / 2;
1788 offset1 = code_offsets [(pos * 2)];
1789 if (pos + 1 == nmethods)
1790 offset2 = amodule->code_end - amodule->code;
1792 offset2 = code_offsets [(pos + 1) * 2];
1794 if (offset < offset1)
1796 else if (offset >= offset2)
1802 g_assert (offset >= code_offsets [(pos * 2)]);
1803 if (pos + 1 < nmethods)
1804 g_assert (offset < code_offsets [((pos + 1) * 2)]);
1805 method_index = code_offsets [(pos * 2) + 1];
1807 code = &amodule->code [amodule->code_offsets [method_index]];
1808 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
1810 if (pos == nmethods - 1)
1811 code_len = amodule->code_end - code;
1813 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
1815 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
1817 /* Might be a wrapper/extra method */
1818 if (amodule->extra_methods) {
1820 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
1827 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
1829 * This is hit for extra methods which are called directly, so they are
1830 * not in amodule->extra_methods.
1832 table_len = amodule->extra_method_info_offsets [0];
1833 table = amodule->extra_method_info_offsets + 1;
1840 pos = ((left + right) / 2);
1842 g_assert (pos < table_len);
1844 if (table [pos * 2] < method_index)
1846 else if (table [pos * 2] > method_index)
1852 p = amodule->blob + table [(pos * 2) + 1];
1853 is_wrapper = decode_value (p, &p);
1854 g_assert (!is_wrapper);
1855 method = decode_method_ref_2 (amodule, p, &p);
1858 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
1859 method = mono_get_method (image, token, NULL);
1866 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
1868 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
1870 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
1871 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
1873 /* Add it to the normal JitInfo tables */
1874 mono_jit_info_table_add (domain, jinfo);
1880 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
1888 case MONO_PATCH_INFO_METHOD:
1889 case MONO_PATCH_INFO_METHOD_JUMP:
1890 case MONO_PATCH_INFO_ICALL_ADDR:
1891 case MONO_PATCH_INFO_METHOD_RGCTX: {
1894 gboolean no_aot_trampoline;
1896 image = decode_method_ref (aot_module, &token, &method, &no_aot_trampoline, p, &p);
1900 if (!method && !mono_aot_only && !no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) {
1901 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (image, token));
1902 ji->type = MONO_PATCH_INFO_ABS;
1906 ji->data.method = method;
1908 ji->data.method = mono_get_method (image, token, NULL);
1909 g_assert (ji->data.method);
1910 mono_class_init (ji->data.method->klass);
1914 case MONO_PATCH_INFO_INTERNAL_METHOD:
1915 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1916 guint32 len = decode_value (p, &p);
1918 ji->data.name = (char*)p;
1922 case MONO_PATCH_INFO_METHODCONST:
1924 ji->data.method = decode_method_ref_2 (aot_module, p, &p);
1925 if (!ji->data.method)
1928 case MONO_PATCH_INFO_VTABLE:
1929 case MONO_PATCH_INFO_CLASS:
1930 case MONO_PATCH_INFO_IID:
1931 case MONO_PATCH_INFO_ADJUSTED_IID:
1933 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1934 if (!ji->data.klass)
1937 case MONO_PATCH_INFO_CLASS_INIT:
1938 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1939 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1940 if (!ji->data.klass)
1943 case MONO_PATCH_INFO_IMAGE:
1944 ji->data.image = load_image (aot_module, decode_value (p, &p));
1945 if (!ji->data.image)
1948 case MONO_PATCH_INFO_FIELD:
1949 case MONO_PATCH_INFO_SFLDA:
1951 ji->data.field = decode_field_info (aot_module, p, &p);
1952 if (!ji->data.field)
1955 case MONO_PATCH_INFO_SWITCH:
1956 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
1957 ji->data.table->table_size = decode_value (p, &p);
1958 table = g_new (gpointer, ji->data.table->table_size);
1959 ji->data.table->table = (MonoBasicBlock**)table;
1960 for (i = 0; i < ji->data.table->table_size; i++)
1961 table [i] = (gpointer)(gssize)decode_value (p, &p);
1963 case MONO_PATCH_INFO_R4: {
1966 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
1967 val = decode_value (p, &p);
1968 *(float*)ji->data.target = *(float*)&val;
1971 case MONO_PATCH_INFO_R8: {
1975 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
1977 val [0] = decode_value (p, &p);
1978 val [1] = decode_value (p, &p);
1979 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
1980 *(double*)ji->data.target = *(double*)&v;
1983 case MONO_PATCH_INFO_LDSTR:
1984 image = load_image (aot_module, decode_value (p, &p));
1987 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
1989 case MONO_PATCH_INFO_RVA:
1990 case MONO_PATCH_INFO_DECLSEC:
1991 case MONO_PATCH_INFO_LDTOKEN:
1992 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1994 image = load_image (aot_module, decode_value (p, &p));
1997 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
1999 ji->data.token->has_context = decode_value (p, &p);
2000 if (ji->data.token->has_context) {
2001 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2006 case MONO_PATCH_INFO_EXC_NAME:
2007 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2008 if (!ji->data.klass)
2010 ji->data.name = ji->data.klass->name;
2012 case MONO_PATCH_INFO_METHOD_REL:
2013 ji->data.offset = decode_value (p, &p);
2015 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2016 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2017 case MONO_PATCH_INFO_MONITOR_ENTER:
2018 case MONO_PATCH_INFO_MONITOR_EXIT:
2020 case MONO_PATCH_INFO_RGCTX_FETCH: {
2022 MonoJumpInfoRgctxEntry *entry;
2024 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2025 entry->method = decode_method_ref_2 (aot_module, p, &p);
2026 entry->in_mrgctx = decode_value (p, &p);
2027 entry->info_type = decode_value (p, &p);
2028 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2029 entry->data->type = decode_value (p, &p);
2031 res = decode_patch (aot_module, mp, entry->data, p, &p);
2034 ji->data.rgctx_entry = entry;
2037 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2039 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2040 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2042 imt_tramp->method = decode_method_ref_2 (aot_module, p, &p);
2043 imt_tramp->vt_offset = decode_value (p, &p);
2045 ji->data.imt_tramp = imt_tramp;
2049 g_warning ("unhandled type %d", ji->type);
2050 g_assert_not_reached ();
2061 static MonoJumpInfo*
2062 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
2063 guint32 **got_slots,
2064 guint8 *buf, guint8 **endbuf)
2066 MonoJumpInfo *patches;
2072 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2074 *got_slots = g_malloc (sizeof (guint32) * n_patches);
2076 for (pindex = 0; pindex < n_patches; ++pindex) {
2077 MonoJumpInfo *ji = &patches [pindex];
2082 got_offset = decode_value (p, &p);
2084 if (aot_module->got [got_offset]) {
2085 /* Already loaded */
2086 //printf ("HIT!\n");
2088 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2090 ji->type = decode_value (shared_p, &shared_p);
2092 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2097 (*got_slots) [pindex] = got_offset;
2104 g_free (*got_slots);
2111 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2114 * Jump addresses cannot be patched by the trampoline code since it
2115 * does not have access to the caller's address. Instead, we collect
2116 * the addresses of the GOT slots pointing to a method, and patch
2117 * them after the method has been compiled.
2119 MonoJitDomainInfo *info = domain_jit_info (domain);
2122 mono_domain_lock (domain);
2123 if (!info->jump_target_got_slot_hash)
2124 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2125 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2126 list = g_slist_prepend (list, got_slot);
2127 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2128 mono_domain_unlock (domain);
2134 * Load the method identified by METHOD_INDEX from the AOT image. Return a
2135 * pointer to the native code of the method, or NULL if not found.
2136 * METHOD might not be set if the caller only has the image/token info.
2139 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2142 gboolean from_plt = method == NULL;
2144 int i, pindex, n_patches, used_strings;
2145 gboolean keep_patches = TRUE;
2147 MonoJitInfo *jinfo = NULL;
2148 guint8 *code, *info;
2150 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2153 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2154 /* Non shared AOT code can't be used in other appdomains */
2157 if (amodule->out_of_date)
2160 if (amodule->code_offsets [method_index] == 0xffffffff) {
2161 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2165 method = mono_get_method (image, token, NULL);
2166 full_name = mono_method_full_name (method, TRUE);
2167 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2173 code = &amodule->code [amodule->code_offsets [method_index]];
2175 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2178 if (!amodule->methods_loaded)
2179 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods + 1);
2182 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2185 if (mono_last_aot_method != -1) {
2186 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2188 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2190 printf ("LAST AOT METHOD: %s%s%s.%s.\n", method->klass->name_space, method->klass->name_space [0] ? "." : "", method->klass->name, method->name);
2192 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2199 klass = method->klass;
2200 decode_klass_ref (amodule, p, &p);
2202 klass = decode_klass_ref (amodule, p, &p);
2205 if (amodule->info.opts & MONO_OPT_SHARED)
2206 used_strings = decode_value (p, &p);
2210 for (i = 0; i < used_strings; i++) {
2211 guint token = decode_value (p, &p);
2212 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2215 if (amodule->info.opts & MONO_OPT_SHARED)
2216 keep_patches = FALSE;
2218 n_patches = decode_value (p, &p);
2220 keep_patches = FALSE;
2223 MonoJumpInfo *patches;
2229 mp = mono_mempool_new ();
2231 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2232 if (patches == NULL)
2235 for (pindex = 0; pindex < n_patches; ++pindex) {
2236 MonoJumpInfo *ji = &patches [pindex];
2238 if (!amodule->got [got_slots [pindex]]) {
2239 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
2240 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2241 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
2242 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2243 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
2245 ji->type = MONO_PATCH_INFO_NONE;
2251 mono_mempool_destroy (mp);
2254 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2258 method = mono_get_method (image, token, NULL);
2260 full_name = mono_method_full_name (method, TRUE);
2263 jinfo = mono_aot_find_jit_info (domain, method->klass->image, code);
2265 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p - %p %p\n", full_name, code, code + jinfo->code_size, info);
2271 mono_jit_stats.methods_aot++;
2273 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
2277 if (method && method->wrapper_type)
2278 g_hash_table_insert (amodule->method_to_code, method, code);
2282 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
2286 method = mono_get_method (image, token, NULL);
2289 mono_profiler_method_jit (method);
2290 jinfo = mono_jit_info_table_find (domain, (char*)code);
2292 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
2295 if (from_plt && klass && !klass->generic_container)
2296 mono_runtime_class_init (mono_class_vtable (domain, klass));
2301 /* FIXME: The space in domain->mp is wasted */
2302 if (amodule->info.opts & MONO_OPT_SHARED)
2303 /* No need to cache patches */
2304 mono_mempool_destroy (mp);
2313 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
2315 guint32 table_size, entry_size, hash;
2316 guint32 *table, *entry;
2319 static guint32 n_extra_decodes;
2324 table_size = amodule->extra_method_table [0];
2325 table = amodule->extra_method_table + 1;
2328 if (method->wrapper_type) {
2329 name = mono_aot_wrapper_name (method);
2332 hash = mono_aot_method_hash (method) % table_size;
2334 entry = &table [hash * entry_size];
2341 guint32 key = entry [0];
2342 guint32 value = entry [1];
2343 guint32 next = entry [entry_size - 1];
2346 int is_wrapper_name;
2348 p = amodule->blob + key;
2349 is_wrapper_name = decode_value (p, &p);
2350 if (is_wrapper_name) {
2351 int wrapper_type = decode_value (p, &p);
2352 if (wrapper_type == method->wrapper_type && !strcmp (name, (char*)p)) {
2356 } else if (can_method_ref_match_method (amodule, p, method)) {
2358 if (!amodule->method_ref_to_method)
2359 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
2360 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
2364 m = decode_method_ref_2 (amodule, p, &p);
2367 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
2376 /* Special case: wrappers of shared generic methods */
2377 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
2378 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
2379 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
2380 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
2382 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
2388 /* Methods decoded needlessly */
2391 printf ("%d %s %s\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE));
2397 entry = &table [next * entry_size];
2407 add_module_cb (gpointer key, gpointer value, gpointer user_data)
2409 g_ptr_array_add ((GPtrArray*)user_data, value);
2413 * find_extra_method:
2415 * Try finding METHOD in the extra_method table in all AOT images.
2416 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
2417 * module where the method was found.
2420 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
2426 /* Try the method's module first */
2427 *out_amodule = method->klass->image->aot_module;
2428 index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
2429 if (index != 0xffffff)
2433 * Try all other modules.
2434 * This is needed because generic instances klass->image points to the image
2435 * containing the generic definition, but the native code is generated to the
2436 * AOT image which contains the reference.
2439 /* Make a copy to avoid doing the search inside the aot lock */
2440 modules = g_ptr_array_new ();
2442 g_hash_table_foreach (aot_modules, add_module_cb, modules);
2446 for (i = 0; i < modules->len; ++i) {
2447 MonoAotModule *amodule = g_ptr_array_index (modules, i);
2449 if (amodule != method->klass->image->aot_module)
2450 index = find_extra_method_in_amodule (amodule, method);
2451 if (index != 0xffffff) {
2452 *out_amodule = amodule;
2457 g_ptr_array_free (modules, TRUE);
2463 * mono_aot_get_method:
2465 * Return a pointer to the AOTed native code for METHOD if it can be found,
2467 * On platforms with function pointers, this doesn't return a function pointer.
2470 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2472 MonoClass *klass = method->klass;
2473 guint32 method_index;
2474 MonoAotModule *amodule = klass->image->aot_module;
2480 if (amodule->out_of_date)
2483 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2484 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2485 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2486 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2490 * Use the original method instead of its invoke-with-check wrapper.
2491 * This is not a problem when using full-aot, since it doesn't support
2494 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
2495 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
2497 g_assert (klass->inited);
2499 /* Find method index */
2500 if (method->is_inflated && mono_method_is_generic_sharable_impl (method, FALSE)) {
2501 method = mono_method_get_declaring_generic_method (method);
2502 method_index = mono_metadata_token_index (method->token) - 1;
2503 } else if (method->is_inflated || !method->token) {
2504 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
2506 code = g_hash_table_lookup (amodule->method_to_code, method);
2511 method_index = find_extra_method (method, &amodule);
2513 * Special case the ICollection<T> wrappers for arrays, as they cannot
2514 * be statically enumerated, and each wrapper ends up calling the same
2517 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
2518 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2520 code = mono_aot_get_method (domain, m);
2522 if (mono_method_needs_static_rgctx_invoke (m, FALSE))
2523 code = mono_create_static_rgctx_trampoline (m, code);
2530 * Special case Array.GetGenericValueImpl which is a generic icall.
2531 * Generic sharing currently can't handle it, but the icall returns data using
2532 * an out parameter, so the managed-to-native wrappers can share the same code.
2534 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
2536 MonoGenericContext ctx;
2537 MonoType *args [16];
2539 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
2540 /* Avoid recursion */
2543 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
2546 memset (&ctx, 0, sizeof (ctx));
2547 args [0] = &mono_defaults.object_class->byval_arg;
2548 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2550 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
2553 * Get the code for the <object> instantiation which should be emitted into
2554 * the mscorlib aot image by the AOT compiler.
2556 code = mono_aot_get_method (domain, m);
2561 if (method_index == 0xffffff) {
2562 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2565 full_name = mono_method_full_name (method, TRUE);
2566 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2572 if (method_index == 0xffffff)
2575 /* Needed by find_jit_info */
2577 if (!amodule->extra_methods)
2578 amodule->extra_methods = g_hash_table_new (NULL, NULL);
2579 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
2583 method_index = mono_metadata_token_index (method->token) - 1;
2586 return load_method (domain, amodule, klass->image, method, method->token, method_index);
2590 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
2594 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
2596 MonoAotModule *aot_module = image->aot_module;
2602 method_index = mono_metadata_token_index (token) - 1;
2604 return load_method (domain, aot_module, image, NULL, token, method_index);
2610 } IsGotEntryUserData;
2613 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
2615 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
2616 MonoAotModule *aot_module = (MonoAotModule*)value;
2618 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
2623 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
2625 IsGotEntryUserData user_data;
2630 user_data.addr = addr;
2631 user_data.res = FALSE;
2633 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
2636 return user_data.res;
2641 MonoAotModule *module;
2642 } FindAotModuleUserData;
2645 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
2647 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
2648 MonoAotModule *aot_module = (MonoAotModule*)value;
2650 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
2651 data->module = aot_module;
2654 static inline MonoAotModule*
2655 find_aot_module (guint8 *code)
2657 FindAotModuleUserData user_data;
2662 /* Reading these need no locking */
2663 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
2666 user_data.addr = code;
2667 user_data.module = NULL;
2670 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
2673 return user_data.module;
2677 * mono_aot_plt_resolve:
2679 * This function is called by the entries in the PLT to resolve the actual method that
2680 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
2683 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
2685 #ifdef MONO_ARCH_AOT_SUPPORTED
2686 guint8 *p, *target, *plt_entry;
2688 MonoAotModule *module = (MonoAotModule*)aot_module;
2689 gboolean res, no_ftnptr = FALSE;
2692 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
2694 p = &module->blob [plt_info_offset];
2696 ji.type = decode_value (p, &p);
2698 mp = mono_mempool_new_size (512);
2699 res = decode_patch (module, mp, &ji, p, &p);
2700 // FIXME: Error handling (how ?)
2704 * Avoid calling resolve_patch_target in the full-aot case if possible, since
2705 * it would create a trampoline, and we don't need that.
2706 * We could do this only if the method does not need the special handling
2707 * in mono_magic_trampoline ().
2709 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) &&
2710 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
2711 target = mono_jit_compile_method (ji.data.method);
2714 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
2718 * The trampoline expects us to return a function descriptor on platforms which use
2719 * it, but resolve_patch_target returns a direct function pointer for some type of
2720 * patches, so have to translate between the two.
2721 * FIXME: Clean this up, but how ?
2723 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) {
2724 /* These should already have a function descriptor */
2725 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2726 g_assert (((gpointer*)target) [2] == 0);
2728 } else if (!no_ftnptr) {
2729 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2730 g_assert (((gpointer*)target) [2] != 0);
2732 target = mono_create_ftnptr (mono_domain_get (), target);
2735 mono_mempool_destroy (mp);
2737 /* Patch the PLT entry with target which might be the actual method not a trampoline */
2738 plt_entry = mono_aot_get_plt_entry (code);
2739 g_assert (plt_entry);
2740 mono_arch_patch_plt_entry (plt_entry, module->got, NULL, target);
2744 g_assert_not_reached ();
2752 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
2753 * method in the module is loaded to avoid committing memory by writing to it.
2754 * LOCKING: Assumes the AOT lock is held.
2757 init_plt (MonoAotModule *amodule)
2759 #ifndef MONO_CROSS_COMPILE
2761 #ifdef MONO_ARCH_AOT_SUPPORTED
2763 guint8 *buf = amodule->plt;
2764 #elif defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__)
2770 if (amodule->plt_inited)
2773 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
2776 /* Initialize the first PLT entry */
2777 make_writable (amodule->plt, amodule->plt_end - amodule->plt);
2778 x86_jump_code (buf, tramp);
2779 #elif defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__)
2781 * Initialize the PLT entries in the GOT to point to the default targets.
2784 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
2785 plt_0 = mono_create_ftnptr (mono_domain_get (), amodule->plt);
2786 /* The first entry points to the AOT trampoline */
2787 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base] = tramp;
2788 for (i = 1; i < amodule->info.plt_size; ++i)
2789 /* All the default entries point to the first entry */
2790 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = plt_0;
2792 g_assert_not_reached ();
2795 amodule->plt_inited = TRUE;
2798 #endif /* MONO_CROSS_COMPILE */
2802 * mono_aot_get_plt_entry:
2804 * Return the address of the PLT entry called by the code at CODE if exists.
2807 mono_aot_get_plt_entry (guint8 *code)
2809 MonoAotModule *aot_module = find_aot_module (code);
2810 #if defined(__arm__) || defined(__mono_ppc__)
2817 #if defined(__i386__) || defined(__x86_64__)
2818 if (code [-5] == 0xe8) {
2819 guint32 disp = *(guint32*)(code - 4);
2820 guint8 *target = code + disp;
2822 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2825 #elif defined(__arm__)
2826 ins = ((guint32*)(gpointer)code) [-1];
2828 /* Should be a 'bl' */
2829 if ((((ins >> 25) & 0x7) == 0x5) && (((ins >> 24) & 0x1) == 0x1)) {
2830 gint32 disp = ((gint32)ins) & 0xffffff;
2831 guint8 *target = code - 4 + 8 + (disp * 4);
2833 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2836 #elif defined(__mono_ppc__)
2837 /* Should be a bl */
2838 ins = ((guint32*)(gpointer)code) [-1];
2840 if ((ins >> 26 == 18) && ((ins & 1) == 1) && ((ins & 2) == 0)) {
2841 gint32 disp = (((gint32)ins) >> 2) & 0xffffff;
2842 guint8 *target = code - 4 + (disp * 4);
2844 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2848 g_assert_not_reached ();
2855 * mono_aot_get_plt_info_offset:
2857 * Return the PLT info offset belonging to the plt entry called by CODE.
2860 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
2862 guint8 *plt_entry = mono_aot_get_plt_entry (code);
2864 g_assert (plt_entry);
2866 /* The offset is embedded inside the code after the plt entry */
2867 #if defined(__i386__)
2868 return *(guint32*)(plt_entry + 5);
2869 #elif defined(__x86_64__)
2870 return *(guint32*)(plt_entry + 6);
2871 #elif defined(__arm__)
2872 /* The offset is stored as the 4th word of the plt entry */
2873 return ((guint32*)plt_entry) [3];
2874 #elif defined(__mono_ppc__)
2875 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2876 return ((guint32*)plt_entry) [8];
2878 return ((guint32*)plt_entry) [6];
2881 g_assert_not_reached ();
2887 mono_create_ftnptr_malloc (guint8 *code)
2889 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2890 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
2892 ftnptr->code = code;
2905 * Load the function named NAME from the aot image.
2908 load_function (MonoAotModule *amodule, const char *name)
2912 int n_patches, pindex;
2918 symbol = g_strdup_printf ("%s", name);
2919 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
2922 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
2924 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
2928 symbol = g_strdup_printf ("%s_p", name);
2929 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
2932 /* Nothing to patch */
2935 /* Similar to mono_aot_load_method () */
2937 n_patches = decode_value (p, &p);
2940 MonoJumpInfo *patches;
2943 mp = mono_mempool_new ();
2945 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2948 for (pindex = 0; pindex < n_patches; ++pindex) {
2949 MonoJumpInfo *ji = &patches [pindex];
2952 if (amodule->got [got_slots [pindex]])
2956 * When this code is executed, the runtime may not be initalized yet, so
2957 * resolve the patch info by hand.
2959 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
2960 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
2961 target = mono_get_lmf_addr;
2962 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
2963 target = mono_thread_force_interruption_checkpoint;
2964 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
2965 target = mono_exception_from_token;
2966 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
2967 target = mono_get_throw_exception ();
2969 } else if (!strcmp (ji->data.name, "mono_amd64_throw_exception")) {
2970 target = mono_amd64_throw_exception;
2973 } else if (!strcmp (ji->data.name, "mono_amd64_get_original_ip")) {
2974 target = mono_amd64_get_original_ip;
2977 } else if (!strcmp (ji->data.name, "mono_arm_throw_exception")) {
2978 target = mono_arm_throw_exception;
2979 } else if (!strcmp (ji->data.name, "mono_arm_throw_exception_by_token")) {
2980 target = mono_arm_throw_exception_by_token;
2983 } else if (!strcmp (ji->data.name, "mono_ppc_throw_exception")) {
2984 target = mono_ppc_throw_exception;
2986 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
2987 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
2988 target = (gpointer)mono_get_trampoline_func (tramp_type2);
2989 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
2990 /* atoll is needed because the the offset is unsigned */
2994 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
2995 g_assert (res == 1);
2996 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
2997 target = mono_create_ftnptr_malloc (target);
2998 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
2999 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3000 target = mono_create_ftnptr_malloc (target);
3001 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3002 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3003 target = mono_create_ftnptr_malloc (target);
3004 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3005 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3006 target = mono_create_ftnptr_malloc (target);
3007 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3008 target = mono_thread_get_and_clear_pending_exception;
3010 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3011 g_assert_not_reached ();
3015 /* Hopefully the code doesn't have patches which need method or
3018 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3022 amodule->got [got_slots [pindex]] = target;
3027 mono_mempool_destroy (mp);
3034 * Return the piece of code identified by NAME from the mscorlib AOT file.
3035 * On ppc64, this returns a function descriptor.
3038 mono_aot_get_named_code (const char *name)
3041 MonoAotModule *amodule;
3043 image = mono_defaults.corlib;
3046 amodule = image->aot_module;
3049 return mono_create_ftnptr_malloc (load_function (amodule, name));
3052 /* Return a given kind of trampoline */
3054 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3056 MonoAotModule *amodule;
3057 int index, tramp_size;
3060 /* Currently, we keep all trampolines in the mscorlib AOT image */
3061 image = mono_defaults.corlib;
3066 amodule = image->aot_module;
3069 *out_amodule = amodule;
3071 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3072 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3074 index = amodule->trampoline_index [tramp_type] ++;
3078 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3080 tramp_size = amodule->info.trampoline_size [tramp_type];
3083 *out_tramp_size = tramp_size;
3085 return amodule->trampolines [tramp_type] + (index * tramp_size);
3089 * Return a specific trampoline from the AOT file.
3092 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3094 MonoAotModule *amodule;
3095 guint32 got_offset, tramp_size;
3096 guint8 *code, *tramp;
3097 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3098 static gboolean inited;
3099 static guint32 num_trampolines;
3105 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3114 if (!generic_trampolines [tramp_type]) {
3117 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
3118 generic_trampolines [tramp_type] = mono_aot_get_named_code (symbol);
3122 tramp = generic_trampolines [tramp_type];
3125 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3127 amodule->got [got_offset] = tramp;
3128 amodule->got [got_offset + 1] = arg1;
3131 *code_len = tramp_size;
3137 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3139 MonoAotModule *amodule;
3143 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3145 amodule->got [got_offset] = ctx;
3146 amodule->got [got_offset + 1] = addr;
3148 /* The caller expects an ftnptr */
3149 return mono_create_ftnptr (mono_domain_get (), code);
3153 mono_aot_get_unbox_trampoline (MonoMethod *method)
3155 guint32 method_index = mono_metadata_token_index (method->token) - 1;
3156 MonoAotModule *amodule;
3160 if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3161 guint32 index = find_extra_method (method, &amodule);
3162 g_assert (index != 0xffffff);
3164 symbol = g_strdup_printf ("ut_e_%d", index);
3166 amodule = method->klass->image->aot_module;
3169 symbol = g_strdup_printf ("ut_%d", method_index);
3171 code = load_function (amodule, symbol);
3174 /* The caller expects an ftnptr */
3175 return mono_create_ftnptr (mono_domain_get (), code);
3179 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3184 symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", slot);
3185 code = load_function (mono_defaults.corlib->aot_module, symbol);
3191 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3197 MonoAotModule *amodule;
3199 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
3201 /* Save the entries into an array */
3202 buf = mono_domain_alloc (domain, (count + 1) * 2 * sizeof (gpointer));
3203 for (i = 0; i < count; ++i) {
3204 MonoIMTCheckItem *item = imt_entries [i];
3206 g_assert (item->key);
3208 g_assert (!item->has_target_code);
3210 buf [(i * 2)] = item->key;
3211 buf [(i * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
3213 buf [(count * 2)] = NULL;
3214 buf [(count * 2) + 1] = fail_tramp;
3216 amodule->got [got_offset] = buf;
3225 mono_aot_init (void)
3230 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3236 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3242 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
3248 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
3254 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3260 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3266 mono_aot_get_plt_entry (guint8 *code)
3272 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3278 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
3284 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3286 g_assert_not_reached ();
3292 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3294 g_assert_not_reached ();
3299 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3301 g_assert_not_reached ();
3306 mono_aot_get_named_code (const char *name)
3308 g_assert_not_reached ();
3313 mono_aot_get_unbox_trampoline (MonoMethod *method)
3315 g_assert_not_reached ();
3320 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3322 g_assert_not_reached ();
3327 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3329 g_assert_not_reached ();
3334 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3336 g_assert_not_reached ();