2 * aot.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 #ifndef PLATFORM_WIN32
25 #ifdef HAVE_EXECINFO_H
31 #include <limits.h> /* for PAGESIZE */
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/utils/mono-logger.h>
51 #include "mono/utils/mono-compiler.h"
59 #define SHARED_EXT ".dll"
60 #elif (defined(__ppc__) || defined(__ppc64__)) && defined(__MACH__)
61 #define SHARED_EXT ".dylib"
63 #define SHARED_EXT ".so"
66 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
67 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
69 typedef struct MonoAotModule {
71 /* Optimization flags used to compile the module */
73 /* Pointer to the Global Offset Table */
76 GHashTable *name_cache;
78 MonoAssemblyName *image_names;
80 MonoImage **image_table;
81 guint32 image_table_len;
91 guint8 *plt_jump_table;
92 guint32 plt_jump_table_size;
93 guint32 *code_offsets;
95 guint32 *method_info_offsets;
97 guint32 *got_info_offsets;
99 guint32 *ex_info_offsets;
100 guint32 *method_order;
101 guint32 *method_order_end;
103 guint32 *class_info_offsets;
104 guint32 *methods_loaded;
105 guint16 *class_name_table;
106 guint8 *wrapper_info;
108 guint32 num_trampolines, first_trampoline_got_offset, trampoline_index;
111 static GHashTable *aot_modules;
112 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
113 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
114 static CRITICAL_SECTION aot_mutex;
117 * Disabling this will make a copy of the loaded code and use the copy instead
118 * of the original. This will place the caller and the callee close to each
119 * other in memory, possibly improving cache behavior. Since the original
120 * code is in copy-on-write memory, this will not increase the memory usage
123 static gboolean use_loaded_code = TRUE;
126 * Whenever to AOT compile loaded assemblies on demand and store them in
127 * a cache under $HOME/.mono/aot-cache.
129 static gboolean use_aot_cache = FALSE;
132 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
133 * use_aot_cache is TRUE.
135 static gboolean spawn_compiler = TRUE;
138 static gint32 mono_last_aot_method = -1;
140 static gboolean make_unreadable = FALSE;
141 static guint32 n_pagefaults = 0;
142 static guint32 name_table_accesses = 0;
144 /* Used to speed-up find_aot_module () */
145 static gsize aot_code_low_addr = (gssize)-1;
146 static gsize aot_code_high_addr = 0;
149 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info, int method_index);
152 init_plt (MonoAotModule *info);
155 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
156 guint32 got_index, guint32 **got_slots,
157 guint8 *buf, guint8 **endbuf);
159 static inline gboolean
160 is_got_patch (MonoJumpInfoType patch_type)
165 /*****************************************************/
167 /*****************************************************/
170 load_image (MonoAotModule *module, int index)
172 MonoAssembly *assembly;
173 MonoImageOpenStatus status;
175 g_assert (index < module->image_table_len);
177 if (module->image_table [index])
178 return module->image_table [index];
179 if (module->out_of_date)
182 assembly = mono_assembly_load (&module->image_names [index], NULL, &status);
184 module->out_of_date = TRUE;
188 if (strcmp (assembly->image->guid, module->image_guids [index])) {
189 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);
190 module->out_of_date = TRUE;
194 module->image_table [index] = assembly->image;
195 return assembly->image;
200 decode_value (guint8 *ptr, guint8 **rptr)
205 if ((b & 0x80) == 0){
208 } else if ((b & 0x40) == 0){
209 len = ((b & 0x3f) << 8 | ptr [1]);
211 } else if (b != 0xff) {
212 len = ((b & 0x1f) << 24) |
219 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
225 //printf ("DECODE: %d.\n", len);
230 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
233 MonoClass *klass, *eklass;
236 token = decode_value (buf, &buf);
241 if (mono_metadata_token_table (token) == 0) {
242 image = load_image (module, decode_value (buf, &buf));
245 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token);
246 } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
247 if (token == MONO_TOKEN_TYPE_SPEC) {
250 MonoGenericContext ctx;
251 MonoGenericInst inst;
253 gclass = decode_klass_ref (module, buf, &buf);
254 g_assert (gclass->generic_container);
256 memset (&ctx, 0, sizeof (ctx));
257 memset (&inst, 0, sizeof (inst));
258 ctx.class_inst = &inst;
259 inst.type_argc = decode_value (buf, &buf);
260 inst.type_argv = g_new0 (MonoType*, inst.type_argc);
261 for (i = 0; i < inst.type_argc; ++i) {
262 MonoClass *pclass = decode_klass_ref (module, buf, &buf);
264 g_free (inst.type_argv);
267 inst.type_argv [i] = &pclass->byval_arg;
269 klass = mono_class_from_mono_type (mono_class_inflate_generic_type (&gclass->byval_arg, &ctx));
271 image = load_image (module, decode_value (buf, &buf));
274 klass = mono_class_get (image, token);
276 } else if (token == MONO_TOKEN_TYPE_DEF) {
278 image = load_image (module, decode_value (buf, &buf));
281 rank = decode_value (buf, &buf);
282 eklass = decode_klass_ref (module, buf, &buf);
283 klass = mono_array_class_get (eklass, rank);
285 g_assert_not_reached ();
288 mono_class_init (klass);
294 static MonoClassField*
295 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
297 MonoClass *klass = decode_klass_ref (module, buf, &buf);
303 token = MONO_TOKEN_FIELD_DEF + decode_value (buf, &buf);
307 return mono_class_get_field (klass, token);
310 static inline MonoImage*
311 decode_method_ref (MonoAotModule *module, guint32 *token, guint8 *buf, guint8 **endbuf)
313 guint32 image_index, value;
316 value = decode_value (buf, &buf);
317 image_index = value >> 24;
318 *token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
320 if (image_index == 255) {
322 image_index = decode_value (buf, &buf);
323 *token = decode_value (buf, &buf);
328 image = load_image (module, image_index);
337 make_writable (guint8* addr, guint32 len)
339 #ifndef PLATFORM_WIN32
344 g_error ("Attempt to make AOT memory writable while running with --aot-only.\n");
346 page_start = (guint8 *) (((gssize) (addr)) & ~ (PAGESIZE - 1));
347 pages = (addr + len - page_start + PAGESIZE - 1) / PAGESIZE;
348 err = mprotect (page_start, pages * PAGESIZE, PROT_READ | PROT_WRITE | PROT_EXEC);
353 g_assert (VirtualProtect (addr, len, PAGE_EXECUTE_READWRITE, &oldp) != 0);
359 create_cache_structure (void)
365 home = g_get_home_dir ();
369 tmp = g_build_filename (home, ".mono", NULL);
370 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
371 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
372 #ifdef PLATFORM_WIN32
375 err = mkdir (tmp, 0777);
378 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
384 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
385 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
386 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
387 #ifdef PLATFORM_WIN32
390 err = mkdir (tmp, 0777);
393 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
402 * load_aot_module_from_cache:
404 * Experimental code to AOT compile loaded assemblies on demand.
407 * - Add environment variable MONO_AOT_CACHE_OPTIONS
408 * - Add options for controlling the cache size
409 * - Handle full cache by deleting old assemblies lru style
410 * - Add options for excluding assemblies during development
411 * - Maybe add a threshold after an assembly is AOT compiled
412 * - invoking a new mono process is a security risk
413 * - recompile the AOT module if one of its dependencies changes
416 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
418 char *fname, *cmd, *tmp2, *aot_options;
427 if (assembly->image->dynamic)
430 create_cache_structure ();
432 home = g_get_home_dir ();
434 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
435 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
439 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
440 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
443 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
445 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
447 aot_options = g_strdup_printf ("outfile=%s", fname);
449 if (spawn_compiler) {
450 /* FIXME: security */
451 /* FIXME: Has to pass the assembly loading path to the child process */
452 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
454 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
456 #if !defined(PLATFORM_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
458 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
459 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
461 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
468 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
470 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
472 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
476 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
478 g_free (aot_options);
485 load_aot_module (MonoAssembly *assembly, gpointer user_data)
489 gboolean usable = TRUE;
490 char *saved_guid = NULL;
491 char *aot_version = NULL;
492 char *runtime_version;
493 char *opt_flags = NULL;
494 gpointer *plt_jump_table_addr = NULL;
495 guint32 *plt_jump_table_size = NULL;
496 guint32 *trampolines_info = NULL;
497 gpointer *got_addr = NULL;
498 gpointer *got = NULL;
499 guint32 *got_size_ptr = NULL;
502 if (mono_compile_aot)
505 if (assembly->aot_module)
507 * Already loaded. This can happen because the assembly loading code might invoke
508 * the assembly load hooks multiple times for the same assembly.
512 if (assembly->image->dynamic)
516 assembly->aot_module = load_aot_module_from_cache (assembly, &aot_name);
519 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
521 assembly->aot_module = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
523 if (!assembly->aot_module) {
524 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
529 if (!assembly->aot_module) {
531 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
538 mono_dl_symbol (assembly->aot_module, "mono_assembly_guid", (gpointer *) &saved_guid);
539 mono_dl_symbol (assembly->aot_module, "mono_aot_version", (gpointer *) &aot_version);
540 mono_dl_symbol (assembly->aot_module, "mono_aot_opt_flags", (gpointer *)&opt_flags);
541 mono_dl_symbol (assembly->aot_module, "mono_runtime_version", (gpointer *)&runtime_version);
543 if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
544 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);
548 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
549 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
554 if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, FULL_VERSION)))) {
555 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, FULL_VERSION);
561 g_error ("Failed to load AOT module '%s' while running with --aot-only.\n", aot_name);
563 mono_dl_close (assembly->aot_module);
564 assembly->aot_module = NULL;
568 mono_dl_symbol (assembly->aot_module, "got_addr", (gpointer *)&got_addr);
570 got = (gpointer*)*got_addr;
572 mono_dl_symbol (assembly->aot_module, "got_size", (gpointer *)&got_size_ptr);
573 g_assert (got_size_ptr);
575 info = g_new0 (MonoAotModule, 1);
576 info->aot_name = aot_name;
578 info->got_size = *got_size_ptr;
579 info->got [0] = assembly->image;
581 sscanf (opt_flags, "%d", &info->opts);
583 /* Read image table */
585 guint32 table_len, i;
588 mono_dl_symbol (assembly->aot_module, "mono_image_table", (gpointer *)&table);
591 table_len = *(guint32*)table;
592 table += sizeof (guint32);
593 info->image_table = g_new0 (MonoImage*, table_len);
594 info->image_names = g_new0 (MonoAssemblyName, table_len);
595 info->image_guids = g_new0 (char*, table_len);
596 info->image_table_len = table_len;
597 for (i = 0; i < table_len; ++i) {
598 MonoAssemblyName *aname = &(info->image_names [i]);
600 aname->name = g_strdup (table);
601 table += strlen (table) + 1;
602 info->image_guids [i] = g_strdup (table);
603 table += strlen (table) + 1;
605 aname->culture = g_strdup (table);
606 table += strlen (table) + 1;
607 memcpy (aname->public_key_token, table, strlen (table) + 1);
608 table += strlen (table) + 1;
610 table = ALIGN_PTR_TO (table, 8);
611 aname->flags = *(guint32*)table;
613 aname->major = *(guint32*)table;
615 aname->minor = *(guint32*)table;
617 aname->build = *(guint32*)table;
619 aname->revision = *(guint32*)table;
624 /* Read method and method_info tables */
625 mono_dl_symbol (assembly->aot_module, "method_offsets", (gpointer*)&info->code_offsets);
626 mono_dl_symbol (assembly->aot_module, "methods", (gpointer*)&info->code);
627 mono_dl_symbol (assembly->aot_module, "methods_end", (gpointer*)&info->code_end);
628 mono_dl_symbol (assembly->aot_module, "method_info_offsets", (gpointer*)&info->method_info_offsets);
629 mono_dl_symbol (assembly->aot_module, "method_info", (gpointer*)&info->method_info);
630 mono_dl_symbol (assembly->aot_module, "ex_info_offsets", (gpointer*)&info->ex_info_offsets);
631 mono_dl_symbol (assembly->aot_module, "ex_info", (gpointer*)&info->ex_info);
632 mono_dl_symbol (assembly->aot_module, "method_order", (gpointer*)&info->method_order);
633 mono_dl_symbol (assembly->aot_module, "method_order_end", (gpointer*)&info->method_order_end);
634 mono_dl_symbol (assembly->aot_module, "class_info", (gpointer*)&info->class_info);
635 mono_dl_symbol (assembly->aot_module, "class_info_offsets", (gpointer*)&info->class_info_offsets);
636 mono_dl_symbol (assembly->aot_module, "class_name_table", (gpointer *)&info->class_name_table);
637 mono_dl_symbol (assembly->aot_module, "got_info", (gpointer*)&info->got_info);
638 mono_dl_symbol (assembly->aot_module, "got_info_offsets", (gpointer*)&info->got_info_offsets);
639 mono_dl_symbol (assembly->aot_module, "wrapper_info", (gpointer*)&info->wrapper_info);
640 mono_dl_symbol (assembly->aot_module, "trampolines", (gpointer*)&info->trampolines);
641 mono_dl_symbol (assembly->aot_module, "mem_end", (gpointer*)&info->mem_end);
643 info->mem_begin = info->code;
645 mono_dl_symbol (assembly->aot_module, "plt", (gpointer*)&info->plt);
646 mono_dl_symbol (assembly->aot_module, "plt_end", (gpointer*)&info->plt_end);
647 mono_dl_symbol (assembly->aot_module, "plt_info", (gpointer*)&info->plt_info);
649 mono_dl_symbol (assembly->aot_module, "plt_jump_table_addr", (gpointer *)&plt_jump_table_addr);
650 g_assert (plt_jump_table_addr);
651 info->plt_jump_table = (guint8*)*plt_jump_table_addr;
652 g_assert (info->plt_jump_table);
654 mono_dl_symbol (assembly->aot_module, "plt_jump_table_size", (gpointer *)&plt_jump_table_size);
655 g_assert (plt_jump_table_size);
656 info->plt_jump_table_size = *plt_jump_table_size;
658 mono_dl_symbol (assembly->aot_module, "trampolines_info", (gpointer *)&trampolines_info);
659 if (trampolines_info) {
660 info->num_trampolines = trampolines_info [0];
661 info->first_trampoline_got_offset = trampolines_info [1];
667 mono_dl_symbol (assembly->aot_module, "mono_aot_full_aot", (gpointer *)&full_aot);
669 if (!full_aot || strcmp (full_aot, "TRUE") != 0) {
670 fprintf (stderr, "Can't use AOT image '%s' in aot-only mode because it is not compiled with --aot=full.\n", info->aot_name);
675 if (make_unreadable) {
676 #ifndef PLATFORM_WIN32
681 addr = info->mem_begin;
682 len = info->mem_end - info->mem_begin;
684 /* Round down in both directions to avoid modifying data which is not ours */
685 page_start = (guint8 *) (((gssize) (addr)) & ~ (PAGESIZE - 1)) + PAGESIZE;
686 pages = ((addr + len - page_start + PAGESIZE - 1) / PAGESIZE) - 1;
687 err = mprotect (page_start, pages * PAGESIZE, 0);
694 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)info->code);
695 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)info->code_end);
697 g_hash_table_insert (aot_modules, assembly, info);
700 mono_jit_info_add_aot_module (assembly->image, info->code, info->code_end);
703 * Since we store methoddef and classdef tokens when referring to methods/classes in
704 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
705 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
706 * non-lazily, since we can't handle out-of-date errors later.
708 for (i = 0; i < info->image_table_len; ++i)
709 load_image (info, i);
711 if (info->out_of_date)
712 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);
714 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
720 InitializeCriticalSection (&aot_mutex);
721 aot_modules = g_hash_table_new (NULL, NULL);
723 mono_install_assembly_load_hook (load_aot_module, NULL);
725 if (getenv ("MONO_LASTAOT"))
726 mono_last_aot_method = atoi (getenv ("MONO_LASTAOT"));
727 if (getenv ("MONO_AOT_CACHE"))
728 use_aot_cache = TRUE;
732 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
736 info->vtable_size = decode_value (buf, &buf);
737 if (info->vtable_size == -1)
740 flags = decode_value (buf, &buf);
741 info->ghcimpl = (flags >> 0) & 0x1;
742 info->has_finalize = (flags >> 1) & 0x1;
743 info->has_cctor = (flags >> 2) & 0x1;
744 info->has_nested_classes = (flags >> 3) & 0x1;
745 info->blittable = (flags >> 4) & 0x1;
746 info->has_references = (flags >> 5) & 0x1;
747 info->has_static_refs = (flags >> 6) & 0x1;
748 info->no_special_static_fields = (flags >> 7) & 0x1;
750 if (info->has_cctor) {
751 MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, buf, &buf);
755 if (info->has_finalize) {
756 info->finalize_image = decode_method_ref (module, &info->finalize_token, buf, &buf);
757 if (!info->finalize_image)
761 info->instance_size = decode_value (buf, &buf);
762 info->class_size = decode_value (buf, &buf);
763 info->packing_size = decode_value (buf, &buf);
764 info->min_align = decode_value (buf, &buf);
772 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
775 MonoAotModule *aot_module;
776 MonoClass *klass = vtable->klass;
778 MonoCachedClassInfo class_info;
783 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !klass->image->assembly->aot_module)
788 aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
794 info = &aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
797 err = decode_cached_class_info (aot_module, &class_info, p, &p);
803 for (i = 0; i < slot; ++i)
804 decode_method_ref (aot_module, &token, p, &p);
806 image = decode_method_ref (aot_module, &token, p, &p);
814 return mono_aot_get_method_from_token (domain, image, token);
818 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
820 MonoAotModule *aot_module;
824 if (klass->rank || !klass->image->assembly->aot_module)
829 aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
835 p = (guint8*)&aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
837 err = decode_cached_class_info (aot_module, res, p, &p);
849 * mono_aot_get_class_from_name:
851 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
852 * using a cache stored in the AOT file.
853 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
855 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
859 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
861 MonoAotModule *aot_module;
862 guint16 *table, *entry;
865 char full_name_buf [1024];
867 const char *name2, *name_space2;
869 guint32 cols [MONO_TYPEDEF_SIZE];
870 GHashTable *nspace_table;
877 aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, image->assembly);
878 if (!aot_module || !aot_module->class_name_table) {
885 /* First look in the cache */
886 if (!aot_module->name_cache)
887 aot_module->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
888 nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
890 *klass = g_hash_table_lookup (nspace_table, name);
897 table_size = aot_module->class_name_table [0];
898 table = aot_module->class_name_table + 1;
900 if (name_space [0] == '\0')
901 full_name = g_strdup_printf ("%s", name);
903 if (strlen (name_space) + strlen (name) < 1000) {
904 sprintf (full_name_buf, "%s.%s", name_space, name);
905 full_name = full_name_buf;
907 full_name = g_strdup_printf ("%s.%s", name_space, name);
910 hash = g_str_hash (full_name) % table_size;
911 if (full_name != full_name_buf)
914 entry = &table [hash * 2];
916 if (entry [0] != 0) {
917 t = &image->tables [MONO_TABLE_TYPEDEF];
920 guint32 index = entry [0];
921 guint32 next = entry [1];
922 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
924 name_table_accesses ++;
926 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
928 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
929 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
931 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
933 *klass = mono_class_get (image, token);
938 nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
940 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
941 g_hash_table_insert (aot_module->name_cache, (char*)name_space2, nspace_table);
943 g_hash_table_insert (nspace_table, (char*)name2, *klass);
950 entry = &table [next * 2];
963 decode_exception_debug_info (MonoAotModule *aot_module, MonoDomain *domain,
964 MonoMethod *method, guint8* ex_info, guint8 *code)
968 guint code_len, used_int_regs;
970 MonoMethodHeader *header;
972 header = mono_method_get_header (method);
974 /* Load the method info from the AOT file */
977 code_len = decode_value (p, &p);
978 used_int_regs = decode_value (p, &p);
980 /* Exception table */
981 if (header && header->num_clauses) {
983 mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo) + (sizeof (MonoJitExceptionInfo) * header->num_clauses));
984 jinfo->num_clauses = header->num_clauses;
986 for (i = 0; i < header->num_clauses; ++i) {
987 MonoExceptionClause *ec = &header->clauses [i];
988 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
990 ei->flags = ec->flags;
991 ei->exvar_offset = decode_value (p, &p);
993 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
994 ei->data.filter = code + decode_value (p, &p);
996 ei->data.catch_class = ec->data.catch_class;
998 ei->try_start = code + decode_value (p, &p);
999 ei->try_end = code + decode_value (p, &p);
1000 ei->handler_start = code + decode_value (p, &p);
1004 jinfo = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
1006 jinfo->code_size = code_len;
1007 jinfo->used_regs = used_int_regs;
1008 jinfo->method = method;
1009 jinfo->code_start = code;
1010 jinfo->domain_neutral = 0;
1012 /* Load debug info */
1013 buf_len = decode_value (p, &p);
1014 mono_debug_add_aot_method (domain, method, code, p, buf_len);
1020 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
1022 MonoAssembly *ass = image->assembly;
1023 MonoDl *module = ass->aot_module;
1024 int pos, left, right, offset, offset1, offset2, last_offset, new_offset, page_index, method_index, table_len;
1026 MonoAotModule *aot_module;
1029 guint8 *code, *ex_info;
1030 guint32 *table, *ptr;
1036 aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1038 if (domain != mono_get_root_domain ())
1042 offset = (guint8*)addr - aot_module->code;
1044 /* First search through the index */
1045 ptr = aot_module->method_order;
1050 if (*ptr == 0xffffff)
1054 while (*ptr != 0xffffff) {
1055 guint32 method_index = ptr [0];
1056 new_offset = aot_module->code_offsets [method_index];
1058 if (offset >= last_offset && offset < new_offset) {
1064 last_offset = new_offset;
1068 /* Skip rest of index */
1069 while (*ptr != 0xffffff)
1074 table_len = aot_module->method_order_end - table;
1076 g_assert (table <= aot_module->method_order_end);
1079 left = (page_index * 1024);
1080 right = left + 1024;
1082 if (right > table_len)
1085 offset1 = aot_module->code_offsets [table [left]];
1086 g_assert (offset1 <= offset);
1088 //printf ("Found in index: 0x%x 0x%x 0x%x\n", offset, last_offset, new_offset);
1091 //printf ("Not found in index: 0x%x\n", offset);
1096 /* Binary search inside the method_order table to find the method */
1098 pos = (left + right) / 2;
1100 g_assert (table + pos <= aot_module->method_order_end);
1102 //printf ("Pos: %5d < %5d < %5d Offset: 0x%05x < 0x%05x < 0x%05x\n", left, pos, right, aot_module->code_offsets [table [left]], offset, aot_module->code_offsets [table [right]]);
1104 offset1 = aot_module->code_offsets [table [pos]];
1105 if (table + pos + 1 >= aot_module->method_order_end)
1106 offset2 = aot_module->code_end - aot_module->code;
1108 offset2 = aot_module->code_offsets [table [pos + 1]];
1110 if (offset < offset1)
1112 else if (offset >= offset2)
1118 method_index = table [pos];
1120 /* Might be a wrapper */
1121 if (aot_module->wrappers) {
1123 method = g_hash_table_lookup (aot_module->wrappers, GUINT_TO_POINTER (method_index));
1130 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
1131 method = mono_get_method (image, token, NULL);
1137 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
1139 code = &aot_module->code [aot_module->code_offsets [method_index]];
1140 ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [method_index]];
1142 jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1144 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
1145 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
1147 /* Add it to the normal JitInfo tables */
1148 mono_jit_info_table_add (domain, jinfo);
1154 decode_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf, guint32 *got_offset)
1162 case MONO_PATCH_INFO_METHOD:
1163 case MONO_PATCH_INFO_METHODCONST:
1164 case MONO_PATCH_INFO_METHOD_JUMP:
1165 case MONO_PATCH_INFO_ICALL_ADDR: {
1168 image = decode_method_ref (aot_module, &token, p, &p);
1172 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
1173 if (!mono_aot_only && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) {
1174 ji->data.target = mono_create_jit_trampoline_from_token (image, token);
1175 ji->type = MONO_PATCH_INFO_ABS;
1178 ji->data.method = mono_get_method (image, token, NULL);
1179 g_assert (ji->data.method);
1180 mono_class_init (ji->data.method->klass);
1183 ji->data.method = mono_get_method (image, token, NULL);
1184 g_assert (ji->data.method);
1185 mono_class_init (ji->data.method->klass);
1190 case MONO_PATCH_INFO_WRAPPER: {
1191 guint32 wrapper_type;
1193 wrapper_type = decode_value (p, &p);
1195 ji->type = MONO_PATCH_INFO_METHOD;
1197 switch (wrapper_type) {
1198 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
1199 guint32 image_index, token, value;
1201 value = decode_value (p, &p);
1202 image_index = value >> 24;
1203 token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1205 image = load_image (aot_module, image_index);
1208 ji->data.method = mono_get_method (image, token, NULL);
1209 g_assert (ji->data.method);
1210 mono_class_init (ji->data.method->klass);
1212 ji->data.method = mono_marshal_get_remoting_invoke_with_check (ji->data.method);
1215 case MONO_WRAPPER_PROXY_ISINST: {
1216 MonoClass *klass = decode_klass_ref (aot_module, p, &p);
1219 ji->data.method = mono_marshal_get_proxy_cancast (klass);
1222 case MONO_WRAPPER_LDFLD:
1223 case MONO_WRAPPER_LDFLDA:
1224 case MONO_WRAPPER_STFLD:
1225 case MONO_WRAPPER_ISINST: {
1226 MonoClass *klass = decode_klass_ref (aot_module, p, &p);
1229 if (wrapper_type == MONO_WRAPPER_LDFLD)
1230 ji->data.method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
1231 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
1232 ji->data.method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
1233 else if (wrapper_type == MONO_WRAPPER_STFLD)
1234 ji->data.method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
1235 else if (wrapper_type == MONO_WRAPPER_ISINST)
1236 ji->data.method = mono_marshal_get_isinst (klass);
1238 g_assert_not_reached ();
1241 case MONO_WRAPPER_LDFLD_REMOTE:
1242 ji->data.method = mono_marshal_get_ldfld_remote_wrapper (NULL);
1244 case MONO_WRAPPER_STFLD_REMOTE:
1245 ji->data.method = mono_marshal_get_stfld_remote_wrapper (NULL);
1247 case MONO_WRAPPER_ALLOC: {
1248 int atype = decode_value (p, &p);
1250 ji->data.method = mono_gc_get_managed_allocator_by_type (atype);
1253 case MONO_WRAPPER_STELEMREF:
1254 ji->data.method = mono_marshal_get_stelemref ();
1257 g_assert_not_reached ();
1261 case MONO_PATCH_INFO_INTERNAL_METHOD:
1262 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1263 guint32 len = decode_value (p, &p);
1265 ji->data.name = (char*)p;
1269 case MONO_PATCH_INFO_VTABLE:
1270 case MONO_PATCH_INFO_CLASS:
1271 case MONO_PATCH_INFO_IID:
1272 case MONO_PATCH_INFO_ADJUSTED_IID:
1273 *got_offset = decode_value (p, &p);
1275 if (aot_module->got [*got_offset]) {
1276 /* Already loaded */
1277 //printf ("HIT!\n");
1279 guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1280 ji->data.klass = decode_klass_ref (aot_module, tmp, &tmp);
1281 if (!ji->data.klass)
1285 case MONO_PATCH_INFO_CLASS_INIT:
1286 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1287 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1288 if (!ji->data.klass)
1291 case MONO_PATCH_INFO_IMAGE:
1292 ji->data.image = load_image (aot_module, decode_value (p, &p));
1293 if (!ji->data.image)
1296 case MONO_PATCH_INFO_FIELD:
1297 case MONO_PATCH_INFO_SFLDA:
1298 *got_offset = decode_value (p, &p);
1300 if (aot_module->got [*got_offset]) {
1301 /* Already loaded */
1302 //printf ("HIT2!\n");
1304 guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1305 ji->data.field = decode_field_info (aot_module, tmp, &tmp);
1306 if (!ji->data.field)
1310 case MONO_PATCH_INFO_SWITCH:
1311 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
1312 ji->data.table->table_size = decode_value (p, &p);
1313 table = g_new (gpointer, ji->data.table->table_size);
1314 ji->data.table->table = (MonoBasicBlock**)table;
1315 for (i = 0; i < ji->data.table->table_size; i++)
1316 table [i] = (gpointer)(gssize)decode_value (p, &p);
1318 case MONO_PATCH_INFO_R4: {
1321 ji->data.target = mono_mempool_alloc0 (mp, sizeof (float));
1322 val = decode_value (p, &p);
1323 *(float*)ji->data.target = *(float*)&val;
1326 case MONO_PATCH_INFO_R8: {
1329 ji->data.target = mono_mempool_alloc0 (mp, sizeof (double));
1331 val [0] = decode_value (p, &p);
1332 val [1] = decode_value (p, &p);
1333 *(double*)ji->data.target = *(double*)val;
1336 case MONO_PATCH_INFO_LDSTR:
1337 image = load_image (aot_module, decode_value (p, &p));
1340 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
1342 case MONO_PATCH_INFO_RVA:
1343 case MONO_PATCH_INFO_DECLSEC:
1344 case MONO_PATCH_INFO_LDTOKEN:
1345 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1346 *got_offset = decode_value (p, &p);
1348 if (aot_module->got [*got_offset]) {
1349 /* Already loaded */
1351 guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1352 image = load_image (aot_module, decode_value (tmp, &tmp));
1355 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (tmp, &tmp));
1358 case MONO_PATCH_INFO_EXC_NAME:
1359 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1360 if (!ji->data.klass)
1362 ji->data.name = ji->data.klass->name;
1364 case MONO_PATCH_INFO_METHOD_REL:
1365 ji->data.offset = decode_value (p, &p);
1367 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1370 g_warning ("unhandled type %d", ji->type);
1371 g_assert_not_reached ();
1382 static MonoJumpInfo*
1383 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
1384 guint32 got_index, guint32 **got_slots,
1385 guint8 *buf, guint8 **endbuf)
1387 MonoJumpInfo *patches;
1388 MonoJumpInfo *patch_info = NULL;
1390 guint32 last_offset;
1395 /* First load the type + offset table */
1397 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
1399 for (pindex = 0; pindex < n_patches; ++pindex) {
1400 MonoJumpInfo *ji = &patches [pindex];
1405 //printf ("T: %d O: %d.\n", ji->type, ji->ip.i);
1406 ji->next = patch_info;
1410 *got_slots = g_malloc (sizeof (guint32) * n_patches);
1411 memset (*got_slots, 0xff, sizeof (guint32) * n_patches);
1413 /* Then load the other data */
1414 for (pindex = 0; pindex < n_patches; ++pindex) {
1415 MonoJumpInfo *ji = &patches [pindex];
1417 if (!decode_patch_info (aot_module, mp, ji, p, &p, (*got_slots) + pindex))
1420 if ((*got_slots) [pindex] == 0xffffffff)
1421 (*got_slots) [pindex] = got_index ++;
1428 g_free (*got_slots);
1435 mono_aot_get_method_inner (MonoDomain *domain, MonoMethod *method)
1437 MonoClass *klass = method->klass;
1438 MonoAssembly *ass = klass->image->assembly;
1439 MonoDl *module = ass->aot_module;
1440 guint32 method_index = mono_metadata_token_index (method->token) - 1;
1441 guint8 *code, *info;
1442 MonoAotModule *aot_module;
1447 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1450 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1451 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1452 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1453 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1456 aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1458 g_assert (klass->inited);
1460 if ((domain != mono_get_root_domain ()) && (!(aot_module->opts & MONO_OPT_SHARED)))
1461 /* Non shared AOT code can't be used in other appdomains */
1464 if (aot_module->out_of_date)
1467 if (method->is_inflated) {
1468 if (!mono_method_is_generic_sharable_impl (method, FALSE))
1470 method = mono_method_get_declaring_generic_method (method);
1473 if (!method->token) {
1477 if (!method->wrapper_type || !aot_module->wrapper_info)
1480 /* Try to find the wrapper among the wrapper info */
1481 full_name = mono_method_full_name (method, TRUE);
1482 p = (char*)aot_module->wrapper_info;
1486 end = p + strlen (p) + 1;
1487 end = ALIGN_PTR_TO (end, 4);
1488 method_index = *(guint32*)end;
1490 if (strcmp (full_name, p) == 0)
1500 /* Needed by find_jit_info */
1502 if (!aot_module->wrappers)
1503 aot_module->wrappers = g_hash_table_new (NULL, NULL);
1504 g_hash_table_insert (aot_module->wrappers, GUINT_TO_POINTER (method_index), method);
1508 if (aot_module->code_offsets [method_index] == 0xffffffff) {
1509 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1510 char *full_name = mono_method_full_name (method, TRUE);
1511 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
1517 code = &aot_module->code [aot_module->code_offsets [method_index]];
1518 info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1520 if (!aot_module->methods_loaded)
1521 aot_module->methods_loaded = g_new0 (guint32, klass->image->tables [MONO_TABLE_METHOD].rows + 1);
1523 if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1526 if (mono_last_aot_method != -1) {
1527 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1530 if (mono_jit_stats.methods_aot == mono_last_aot_method)
1531 printf ("LAST AOT METHOD: %s.%s.%s.\n", klass->name_space, klass->name, method->name);
1534 return mono_aot_load_method (domain, aot_module, method, code, info, method_index);
1538 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info, int method_index)
1540 MonoClass *klass = method->klass;
1541 MonoJumpInfo *patch_info = NULL;
1543 int i, pindex, got_index = 0, n_patches, used_strings;
1544 gboolean non_got_patches, keep_patches = TRUE;
1545 guint8 *p, *ex_info;
1546 MonoJitInfo *jinfo = NULL;
1549 decode_klass_ref (aot_module, p, &p);
1551 if (!use_loaded_code) {
1555 ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1556 jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1559 code2 = mono_code_manager_reserve (domain->code_mp, jinfo->code_size);
1560 memcpy (code2, code, jinfo->code_size);
1561 mono_arch_flush_icache (code2, jinfo->code_size);
1565 if (aot_module->opts & MONO_OPT_SHARED)
1566 used_strings = decode_value (p, &p);
1570 for (i = 0; i < used_strings; i++) {
1571 guint token = decode_value (p, &p);
1572 mono_ldstr (mono_get_root_domain (), klass->image, mono_metadata_token_index (token));
1575 if (aot_module->opts & MONO_OPT_SHARED)
1576 keep_patches = FALSE;
1578 n_patches = decode_value (p, &p);
1580 keep_patches = FALSE;
1583 MonoJumpInfo *patches;
1589 mp = mono_mempool_new ();
1591 got_index = decode_value (p, &p);
1593 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1594 if (patches == NULL)
1597 /* Do this outside the lock to avoid deadlocks */
1599 non_got_patches = FALSE;
1600 for (pindex = 0; pindex < n_patches; ++pindex) {
1601 MonoJumpInfo *ji = &patches [pindex];
1603 if (is_got_patch (ji->type)) {
1604 if (!aot_module->got [got_slots [pindex]])
1605 aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
1606 ji->type = MONO_PATCH_INFO_NONE;
1609 non_got_patches = TRUE;
1611 if (non_got_patches) {
1613 ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1614 jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1617 mono_arch_flush_icache (code, jinfo->code_size);
1618 make_writable (code, jinfo->code_size);
1619 mono_arch_patch_code (method, domain, code, patch_info, TRUE);
1626 mono_mempool_destroy (mp);
1629 mono_jit_stats.methods_aot++;
1631 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1632 char *full_name = mono_method_full_name (method, TRUE);
1635 ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [method_index]];
1636 jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1639 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);
1643 aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1645 init_plt (aot_module);
1650 /* FIXME: The space in domain->mp is wasted */
1651 if (aot_module->opts & MONO_OPT_SHARED)
1652 /* No need to cache patches */
1653 mono_mempool_destroy (mp);
1662 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
1667 code = mono_aot_get_method_inner (domain, method);
1674 mono_aot_get_method_from_token_inner (MonoDomain *domain, MonoImage *image, guint32 token, MonoClass **klass)
1676 MonoAssembly *ass = image->assembly;
1678 int i, method_index, pindex, got_index, n_patches, used_strings;
1679 gboolean keep_patches = TRUE;
1681 MonoDl *module = ass->aot_module;
1682 guint8 *code = NULL;
1684 MonoAotModule *aot_module;
1691 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1694 aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1696 if (domain != mono_get_root_domain ())
1699 if (aot_module->out_of_date)
1702 if (aot_module->code_offsets [mono_metadata_token_index (token) - 1] == 0xffffffff) {
1706 method_index = mono_metadata_token_index (token) - 1;
1707 code = &aot_module->code [aot_module->code_offsets [method_index]];
1708 info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1710 if (!aot_module->methods_loaded)
1711 aot_module->methods_loaded = g_new0 (guint32, image->tables [MONO_TABLE_METHOD].rows + 1);
1713 if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1716 if (mono_last_aot_method != -1) {
1717 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1720 if (mono_jit_stats.methods_aot == mono_last_aot_method) {
1721 MonoMethod *method = mono_get_method (image, token, NULL);
1722 printf ("LAST AOT METHOD: %s.%s.%s.\n", method->klass->name_space, method->klass->name, method->name);
1727 *klass = decode_klass_ref (aot_module, p, &p);
1729 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1730 MonoMethod *method = mono_get_method (image, token, NULL);
1731 char *full_name = mono_method_full_name (method, TRUE);
1732 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p %p\n", full_name, code, info);
1736 if (aot_module->opts & MONO_OPT_SHARED)
1737 used_strings = decode_value (p, &p);
1741 for (i = 0; i < used_strings; i++) {
1742 guint string_token = decode_value (p, &p);
1743 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (string_token));
1746 if (aot_module->opts & MONO_OPT_SHARED)
1747 keep_patches = FALSE;
1749 keep_patches = FALSE;
1751 n_patches = decode_value (p, &p);
1754 MonoJumpInfo *patches;
1760 mp = mono_mempool_new ();
1762 got_index = decode_value (p, &p);
1764 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1765 if (patches == NULL)
1768 /* Do this outside the lock to avoid deadlocks */
1771 for (pindex = 0; pindex < n_patches; ++pindex) {
1772 MonoJumpInfo *ji = &patches [pindex];
1774 if (is_got_patch (ji->type)) {
1775 if (!aot_module->got [got_slots [pindex]])
1776 aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (NULL, domain, code, ji, TRUE);
1777 ji->type = MONO_PATCH_INFO_NONE;
1786 mono_mempool_destroy (mp);
1789 mono_jit_stats.methods_aot++;
1791 aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1793 init_plt (aot_module);
1798 /* FIXME: The space in domain->mp is wasted */
1799 if (aot_module->opts & MONO_OPT_SHARED)
1800 /* No need to cache patches */
1801 mono_mempool_destroy (mp);
1807 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
1811 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
1817 res = mono_aot_get_method_from_token_inner (domain, image, token, &klass);
1824 mono_runtime_class_init (mono_class_vtable (domain, klass));
1832 } IsGotEntryUserData;
1835 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
1837 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
1838 MonoAotModule *aot_module = (MonoAotModule*)value;
1840 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->got_size)))
1845 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
1847 IsGotEntryUserData user_data;
1852 user_data.addr = addr;
1853 user_data.res = FALSE;
1855 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
1858 return user_data.res;
1863 MonoAotModule *module;
1864 } FindAotModuleUserData;
1867 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
1869 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
1870 MonoAotModule *aot_module = (MonoAotModule*)value;
1872 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
1873 data->module = aot_module;
1876 static inline MonoAotModule*
1877 find_aot_module (guint8 *code)
1879 FindAotModuleUserData user_data;
1884 /* Reading these need no locking */
1885 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
1888 user_data.addr = code;
1889 user_data.module = NULL;
1892 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
1895 return user_data.module;
1899 * mono_aot_set_make_unreadable:
1901 * Set whenever to make all mmaped memory unreadable. In conjuction with a
1902 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
1905 mono_aot_set_make_unreadable (gboolean unreadable)
1907 make_unreadable = unreadable;
1911 MonoAotModule *module;
1916 find_map (gpointer key, gpointer value, gpointer user_data)
1918 MonoAotModule *module = (MonoAotModule*)value;
1919 FindMapUserData *data = (FindMapUserData*)user_data;
1922 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
1923 data->module = module;
1926 static MonoAotModule*
1927 find_module_for_addr (void *ptr)
1929 FindMapUserData data;
1931 if (!make_unreadable)
1935 data.ptr = (guint8*)ptr;
1938 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
1945 * mono_aot_is_pagefault:
1947 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
1948 * within memory allocated by this module.
1951 mono_aot_is_pagefault (void *ptr)
1953 if (!make_unreadable)
1956 return find_module_for_addr (ptr) != NULL;
1960 * mono_aot_handle_pagefault:
1962 * Handle a pagefault caused by an unreadable page by making it readable again.
1965 mono_aot_handle_pagefault (void *ptr)
1967 #ifndef PLATFORM_WIN32
1968 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), PAGESIZE);
1972 res = mprotect (start, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
1973 g_assert (res == 0);
1984 printf ("\nNative stacktrace:\n\n");
1986 size = backtrace (array, 256);
1987 names = backtrace_symbols (array, size);
1988 for (i =0; i < size; ++i) {
1989 printf ("\t%s\n", names [i]);
1999 * mono_aot_plt_resolve:
2001 * This function is called by the entries in the PLT to resolve the actual method that
2002 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
2005 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
2007 #ifdef MONO_ARCH_AOT_SUPPORTED
2008 guint8 *p, *target, *plt_entry;
2010 MonoAotModule *module = (MonoAotModule*)aot_module;
2013 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
2015 p = &module->plt_info [plt_info_offset];
2017 ji.type = decode_value (p, &p);
2019 res = decode_patch_info (module, NULL, &ji, p, &p, NULL);
2020 // FIXME: Error handling (how ?)
2023 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
2025 /* Patch the PLT entry with target which might be the actual method not a trampoline */
2026 plt_entry = mono_aot_get_plt_entry (code);
2027 g_assert (plt_entry);
2028 mono_arch_patch_plt_entry (plt_entry, target);
2032 g_assert_not_reached ();
2040 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
2041 * method in the module is loaded to avoid committing memory by writing to it.
2042 * LOCKING: Assumes the AOT lock is held.
2045 init_plt (MonoAotModule *info)
2047 #ifdef MONO_ARCH_AOT_SUPPORTED
2049 guint8 *buf = info->plt;
2050 #elif defined(__x86_64__)
2052 #elif defined(__arm__)
2057 if (info->plt_inited)
2060 tramp = mono_create_specific_trampoline (info, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
2063 /* Initialize the first PLT entry */
2064 make_writable (info->plt, info->plt_end - info->plt);
2065 x86_jump_code (buf, tramp);
2066 #elif defined(__x86_64__)
2068 * Initialize the entries in the plt_jump_table to point to the default targets.
2070 n_entries = info->plt_jump_table_size / sizeof (gpointer);
2072 /* The first entry points to the AOT trampoline */
2073 ((gpointer*)info->plt_jump_table)[0] = tramp;
2074 for (i = 1; i < n_entries; ++i)
2075 /* Each PLT entry is 16 bytes long, the default entry begins at offset 6 */
2076 ((gpointer*)info->plt_jump_table)[i] = info->plt + (i * 16) + 6;
2077 #elif defined(__arm__)
2078 /* Initialize the first PLT entry */
2079 make_writable (info->plt, info->plt_end - info->plt);
2080 ((guint32*)info->plt)[1] = (guint32)tramp;
2082 n_entries = ((guint8*)info->plt_end - (guint8*)info->plt) / 8;
2085 * Initialize the jump targets embedded inside the PLT entries to the default
2088 for (i = 1; i < n_entries; ++i)
2089 /* Each PLT entry is 8 bytes long, the jump target is at offset 4 */
2090 /* Each default PLT target is 12 bytes long */
2091 ((guint32*)info->plt)[(i * 2) + 1] = (guint8*)info->plt_end + ((i - 1) * 12);
2093 g_assert_not_reached ();
2096 info->plt_inited = TRUE;
2101 * mono_aot_get_plt_entry:
2103 * Return the address of the PLT entry called by the code at CODE if exists.
2106 mono_aot_get_plt_entry (guint8 *code)
2108 MonoAotModule *aot_module = find_aot_module (code);
2109 #if defined(__arm__)
2116 #if defined(__i386__) || defined(__x86_64__)
2117 if (code [-5] == 0xe8) {
2118 guint32 disp = *(guint32*)(code - 4);
2119 guint8 *target = code + disp;
2121 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2124 #elif defined(__arm__)
2125 ins = ((guint32*)(gpointer)code) [-1];
2127 /* Should be a 'bl' */
2128 if ((((ins >> 25) & 0x7) == 0x5) && (((ins >> 24) & 0x1) == 0x1)) {
2129 gint32 disp = ((gint32)ins) & 0xffffff;
2130 guint8 *target = code - 4 + 8 + (disp * 4);
2132 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2136 g_assert_not_reached ();
2143 * Return the piece of code identified by NAME from the AOT file.
2146 mono_aot_get_named_code (MonoAssembly *assembly, MonoAotModule *aot_module, char *name)
2150 int n_patches, got_index, pindex;
2156 symbol = g_strdup_printf ("%s", name);
2157 mono_dl_symbol (assembly->aot_module, symbol, (gpointer *)&code);
2163 symbol = g_strdup_printf ("%s_p", name);
2164 mono_dl_symbol (assembly->aot_module, symbol, (gpointer *)&p);
2168 /* Similar to mono_aot_load_method () */
2170 n_patches = decode_value (p, &p);
2173 MonoJumpInfo *patches;
2176 mp = mono_mempool_new ();
2178 got_index = decode_value (p, &p);
2180 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
2183 for (pindex = 0; pindex < n_patches; ++pindex) {
2184 MonoJumpInfo *ji = &patches [pindex];
2187 g_assert (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR);
2190 * When this code is executed, the runtime may not yet initalized, so
2191 * resolve the patch info by hand.
2193 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
2194 target = mono_get_lmf_addr;
2195 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
2196 target = mono_thread_force_interruption_checkpoint;
2197 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
2198 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
2199 target = (gpointer)mono_get_trampoline_func (tramp_type2);
2201 fprintf (stderr, "%s\n", ji->data.name);
2202 g_assert_not_reached ();
2206 aot_module->got [got_slots [pindex]] = target;
2211 mono_mempool_destroy (mp);
2218 * Return a specific trampoline from the AOT file.
2221 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
2223 MonoAotModule *amodule;
2225 guint8 *code, *tramp;
2226 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
2228 /* Currently, we keep all trampolines in the mscorlib AOT image */
2229 image = mono_defaults.corlib;
2234 g_assert (image->assembly);
2235 amodule = (MonoAotModule*) g_hash_table_lookup (aot_modules, image->assembly);
2238 if (amodule->trampoline_index == amodule->num_trampolines)
2239 g_error ("Ran out of trampolines in '%s' (%d)\n", image->name, amodule->num_trampolines);
2241 index = amodule->trampoline_index ++;
2245 if (!generic_trampolines [tramp_type]) {
2248 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
2249 generic_trampolines [tramp_type] = mono_aot_get_named_code (image->assembly, amodule, symbol);
2253 tramp = generic_trampolines [tramp_type];
2256 amodule->got [amodule->first_trampoline_got_offset + (index *2)] = tramp;
2257 amodule->got [amodule->first_trampoline_got_offset + (index *2) + 1] = arg1;
2260 code = amodule->trampolines + (index * 16);
2262 g_assert_not_reached ();
2269 * mono_aot_get_n_pagefaults:
2271 * Return the number of times handle_pagefault is called.
2274 mono_aot_get_n_pagefaults (void)
2276 return n_pagefaults;
2283 mono_aot_init (void)
2288 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2294 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
2300 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2306 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2312 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2318 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
2324 mono_aot_is_pagefault (void *ptr)
2330 mono_aot_set_make_unreadable (gboolean unreadable)
2335 mono_aot_get_n_pagefaults (void)
2341 mono_aot_handle_pagefault (void *ptr)
2346 mono_aot_get_plt_entry (guint8 *code)
2352 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
2358 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
2363 gpointer mono_aot_create_specific_trampolines (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
2365 g_assert_not_reached ();