/* * aot-runtime.c: mono Ahead of Time compiler * * Author: * Dietmar Maurer (dietmar@ximian.com) * Zoltan Varga (vargaz@gmail.com) * * (C) 2002 Ximian, Inc. */ #include "config.h" #include #ifdef HAVE_UNISTD_H #include #endif #include #include #ifdef HAVE_SYS_MMAN_H #include #endif #if HOST_WIN32 #include #include #endif #ifdef HAVE_EXECINFO_H #include #endif #include #include #ifdef HAVE_SYS_WAIT_H #include /* for WIFEXITED, WEXITSTATUS */ #endif #ifdef HAVE_DL_ITERATE_PHDR #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mono/utils/mono-compiler.h" #include #include "mini.h" #include "version.h" #ifndef DISABLE_AOT #ifdef TARGET_WIN32 #define SHARED_EXT ".dll" #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__) #define SHARED_EXT ".dylib" #else #define SHARED_EXT ".so" #endif #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1))) #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1)) typedef struct MonoAotModule { char *aot_name; /* Pointer to the Global Offset Table */ gpointer *got; GHashTable *name_cache; GHashTable *extra_methods; /* Maps methods to their code */ GHashTable *method_to_code; /* Maps pointers into the method info to the methods themselves */ GHashTable *method_ref_to_method; MonoAssemblyName *image_names; char **image_guids; MonoAssembly *assembly; MonoImage **image_table; guint32 image_table_len; gboolean out_of_date; gboolean plt_inited; guint8 *mem_begin; guint8 *mem_end; guint8 *code; guint8 *code_end; guint8 *plt; guint8 *plt_end; guint8 *blob; gint32 *code_offsets; /* This contains pairs sorted by offset */ /* This is needed because LLVM emitted methods can be in any order */ gint32 *sorted_code_offsets; gint32 sorted_code_offsets_len; guint32 *method_info_offsets; guint32 *got_info_offsets; guint32 *ex_info_offsets; guint32 *class_info_offsets; guint32 *methods_loaded; guint16 *class_name_table; guint32 *extra_method_table; guint32 *extra_method_info_offsets; guint8 *unwind_info; /* Points to the GNU .eh_frame_hdr section, if it exists */ guint8 *eh_frame_hdr; /* Points to the .ARM.exidx section, if it exists */ guint8 *arm_exidx; guint32 arm_exidx_size; /* Points to the trampolines */ guint8 *trampolines [MONO_AOT_TRAMP_NUM]; /* The first unused trampoline of each kind */ guint32 trampoline_index [MONO_AOT_TRAMP_NUM]; MonoAotFileInfo info; gpointer *globals; MonoDl *sofile; } MonoAotModule; static GHashTable *aot_modules; #define mono_aot_lock() EnterCriticalSection (&aot_mutex) #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex) static CRITICAL_SECTION aot_mutex; /* * Maps assembly names to the mono_aot_module__info symbols in the * AOT modules registered by mono_aot_register_module (). */ static GHashTable *static_aot_modules; /* * Maps MonoJitInfo* to the aot module they belong to, this can be different * from ji->method->klass->image's aot module for generic instances. */ static GHashTable *ji_to_amodule; /* * Whenever to AOT compile loaded assemblies on demand and store them in * a cache under $HOME/.mono/aot-cache. */ static gboolean use_aot_cache = FALSE; /* * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if * use_aot_cache is TRUE. */ static gboolean spawn_compiler = TRUE; /* For debugging */ static gint32 mono_last_aot_method = -1; static gboolean make_unreadable = FALSE; static guint32 name_table_accesses = 0; static guint32 n_pagefaults = 0; /* Used to speed-up find_aot_module () */ static gsize aot_code_low_addr = (gssize)-1; static gsize aot_code_high_addr = 0; static void init_plt (MonoAotModule *info); /*****************************************************/ /* AOT RUNTIME */ /*****************************************************/ /* * load_image: * * Load one of the images referenced by AMODULE. Returns NULL if the image is not * found, and sets the loader error if SET_ERROR is TRUE. */ static MonoImage * load_image (MonoAotModule *amodule, int index, gboolean set_error) { MonoAssembly *assembly; MonoImageOpenStatus status; g_assert (index < amodule->image_table_len); if (amodule->image_table [index]) return amodule->image_table [index]; if (amodule->out_of_date) return NULL; assembly = mono_assembly_load (&amodule->image_names [index], NULL, &status); if (!assembly) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable because dependency %s is not found.\n", amodule->aot_name, amodule->image_names [index].name); amodule->out_of_date = TRUE; if (set_error) { char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]); mono_loader_set_error_assembly_load (full_name, FALSE); g_free (full_name); } return NULL; } if (strcmp (assembly->image->guid, amodule->image_guids [index])) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date (Older than dependency %s).\n", amodule->aot_name, amodule->image_names [index].name); amodule->out_of_date = TRUE; return NULL; } amodule->image_table [index] = assembly->image; return assembly->image; } static inline gint32 decode_value (guint8 *ptr, guint8 **rptr) { guint8 b = *ptr; gint32 len; if ((b & 0x80) == 0){ len = b; ++ptr; } else if ((b & 0x40) == 0){ len = ((b & 0x3f) << 8 | ptr [1]); ptr += 2; } else if (b != 0xff) { len = ((b & 0x1f) << 24) | (ptr [1] << 16) | (ptr [2] << 8) | ptr [3]; ptr += 4; } else { len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4]; ptr += 5; } if (rptr) *rptr = ptr; //printf ("DECODE: %d.\n", len); return len; } /* * mono_aot_get_method: * * Decode an offset table emitted by emit_offset_table (), returning the INDEXth * entry. */ static guint32 mono_aot_get_offset (guint32 *table, int index) { int i, group, ngroups, index_entry_size; int start_offset, offset, noffsets, group_size; guint8 *data_start, *p; guint32 *index32 = NULL; guint16 *index16 = NULL; noffsets = table [0]; group_size = table [1]; ngroups = table [2]; index_entry_size = table [3]; group = index / group_size; if (index_entry_size == 2) { index16 = (guint16*)&table [4]; data_start = (guint8*)&index16 [ngroups]; p = data_start + index16 [group]; } else { index32 = (guint32*)&table [4]; data_start = (guint8*)&index32 [ngroups]; p = data_start + index32 [group]; } /* offset will contain the value of offsets [group * group_size] */ offset = start_offset = decode_value (p, &p); for (i = group * group_size + 1; i <= index; ++i) { offset += decode_value (p, &p); } //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]); return offset; } static MonoMethod* decode_method_ref_2 (MonoAotModule *module, guint8 *buf, guint8 **endbuf); static MonoClass* decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf); static MonoGenericInst* decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf) { int type_argc, i; MonoType **type_argv; MonoGenericInst *inst; guint8 *p = buf; type_argc = decode_value (p, &p); type_argv = g_new0 (MonoType*, type_argc); for (i = 0; i < type_argc; ++i) { MonoClass *pclass = decode_klass_ref (module, p, &p); if (!pclass) { g_free (type_argv); return NULL; } type_argv [i] = &pclass->byval_arg; } inst = mono_metadata_get_generic_inst (type_argc, type_argv); g_free (type_argv); *endbuf = p; return inst; } static gboolean decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf) { gboolean has_class_inst, has_method_inst; guint8 *p = buf; has_class_inst = decode_value (p, &p); if (has_class_inst) { ctx->class_inst = decode_generic_inst (module, p, &p); if (!ctx->class_inst) return FALSE; } has_method_inst = decode_value (p, &p); if (has_method_inst) { ctx->method_inst = decode_generic_inst (module, p, &p); if (!ctx->method_inst) return FALSE; } *endbuf = p; return TRUE; } static MonoClass* decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf) { MonoImage *image; MonoClass *klass, *eklass; guint32 token, rank; guint8 *p = buf; token = decode_value (p, &p); if (token == 0) { *endbuf = p; return NULL; } if (mono_metadata_token_table (token) == 0) { image = load_image (module, decode_value (p, &p), TRUE); if (!image) return NULL; klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token); } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) { if (token == MONO_TOKEN_TYPE_SPEC) { MonoTypeEnum type = decode_value (p, &p); if (type == MONO_TYPE_GENERICINST) { MonoClass *gclass; MonoGenericContext ctx; MonoType *type; gclass = decode_klass_ref (module, p, &p); if (!gclass) return NULL; g_assert (gclass->generic_container); memset (&ctx, 0, sizeof (ctx)); ctx.class_inst = decode_generic_inst (module, p, &p); if (!ctx.class_inst) return NULL; type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx); klass = mono_class_from_mono_type (type); mono_metadata_free_type (type); } else if ((type == MONO_TYPE_VAR) || (type == MONO_TYPE_MVAR)) { MonoType *t; MonoGenericContainer *container; int num = decode_value (p, &p); gboolean is_method = decode_value (p, &p); if (is_method) { MonoMethod *method_def; g_assert (type == MONO_TYPE_MVAR); method_def = decode_method_ref_2 (module, p, &p); if (!method_def) return NULL; container = mono_method_get_generic_container (method_def); } else { MonoClass *class_def; g_assert (type == MONO_TYPE_VAR); class_def = decode_klass_ref (module, p, &p); if (!class_def) return NULL; container = class_def->generic_container; } g_assert (container); // FIXME: Memory management t = g_new0 (MonoType, 1); t->type = type; t->data.generic_param = mono_generic_container_get_param (container, num); // FIXME: Maybe use types directly to avoid // the overhead of creating MonoClass-es klass = mono_class_from_mono_type (t); g_free (t); } else { g_assert_not_reached (); } } else { image = load_image (module, decode_value (p, &p), TRUE); if (!image) return NULL; klass = mono_class_get (image, token); } } else if (token == MONO_TOKEN_TYPE_DEF) { /* Array */ image = load_image (module, decode_value (p, &p), TRUE); if (!image) return NULL; rank = decode_value (p, &p); eklass = decode_klass_ref (module, p, &p); klass = mono_array_class_get (eklass, rank); } else { g_assert_not_reached (); } g_assert (klass); *endbuf = p; return klass; } static MonoClassField* decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf) { MonoClass *klass = decode_klass_ref (module, buf, &buf); guint32 token; guint8 *p = buf; if (!klass) return NULL; token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p); *endbuf = p; return mono_class_get_field (klass, token); } /* * can_method_ref_match_method: * * Determine if calling decode_method_ref_2 on P could return the same method as * METHOD. This is an optimization to avoid calling decode_method_ref_2 () which * would create MonoMethods which are not needed etc. */ static gboolean can_method_ref_match_method (MonoAotModule *module, guint8 *buf, MonoMethod *method) { guint8 *p = buf; guint32 image_index, value; /* Keep this in sync with decode_method_ref () */ value = decode_value (p, &p); image_index = value >> 24; if (image_index == MONO_AOT_METHODREF_WRAPPER) { guint32 wrapper_type; if (!method->wrapper_type) return FALSE; wrapper_type = decode_value (p, &p); if (method->wrapper_type != wrapper_type) return FALSE; } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) { return FALSE; } else if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) { if (method->wrapper_type) return FALSE; } return TRUE; } /* * decode_method_ref: * * Decode a method reference, and return its image and token. This avoids loading * metadata for the method if the caller does not need it. If the method has no token, * then it is loaded from metadata and METHOD is set to the method instance. */ static MonoImage* decode_method_ref (MonoAotModule *module, guint32 *token, MonoMethod **method, gboolean *no_aot_trampoline, guint8 *buf, guint8 **endbuf) { guint32 image_index, value; MonoImage *image = NULL; guint8 *p = buf; if (method) *method = NULL; if (no_aot_trampoline) *no_aot_trampoline = FALSE; value = decode_value (p, &p); image_index = value >> 24; if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) { if (no_aot_trampoline) *no_aot_trampoline = TRUE; value = decode_value (p, &p); image_index = value >> 24; } if (image_index == MONO_AOT_METHODREF_WRAPPER) { guint32 wrapper_type; wrapper_type = decode_value (p, &p); /* Doesn't matter */ image = mono_defaults.corlib; switch (wrapper_type) { case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: { MonoMethod *m = decode_method_ref_2 (module, p, &p); if (!m) return NULL; mono_class_init (m->klass); *method = mono_marshal_get_remoting_invoke_with_check (m); break; } case MONO_WRAPPER_PROXY_ISINST: { MonoClass *klass = decode_klass_ref (module, p, &p); if (!klass) return NULL; *method = mono_marshal_get_proxy_cancast (klass); break; } case MONO_WRAPPER_LDFLD: case MONO_WRAPPER_LDFLDA: case MONO_WRAPPER_STFLD: case MONO_WRAPPER_ISINST: { MonoClass *klass = decode_klass_ref (module, p, &p); if (!klass) return NULL; if (wrapper_type == MONO_WRAPPER_LDFLD) *method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg); else if (wrapper_type == MONO_WRAPPER_LDFLDA) *method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg); else if (wrapper_type == MONO_WRAPPER_STFLD) *method = mono_marshal_get_stfld_wrapper (&klass->byval_arg); else if (wrapper_type == MONO_WRAPPER_ISINST) *method = mono_marshal_get_isinst (klass); else g_assert_not_reached (); break; } case MONO_WRAPPER_LDFLD_REMOTE: *method = mono_marshal_get_ldfld_remote_wrapper (NULL); break; case MONO_WRAPPER_STFLD_REMOTE: *method = mono_marshal_get_stfld_remote_wrapper (NULL); break; case MONO_WRAPPER_ALLOC: { int atype = decode_value (p, &p); *method = mono_gc_get_managed_allocator_by_type (atype); break; } case MONO_WRAPPER_WRITE_BARRIER: *method = mono_gc_get_write_barrier (); break; case MONO_WRAPPER_STELEMREF: *method = mono_marshal_get_stelemref (); break; case MONO_WRAPPER_SYNCHRONIZED: { MonoMethod *m = decode_method_ref_2 (module, p, &p); if (!m) return NULL; *method = mono_marshal_get_synchronized_wrapper (m); break; } case MONO_WRAPPER_UNKNOWN: { MonoMethodDesc *desc; MonoMethod *orig_method; int subtype = decode_value (p, &p); if (subtype == MONO_AOT_WRAPPER_MONO_ENTER) desc = mono_method_desc_new ("Monitor:Enter", FALSE); else if (subtype == MONO_AOT_WRAPPER_MONO_EXIT) desc = mono_method_desc_new ("Monitor:Exit", FALSE); else g_assert_not_reached (); orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class); g_assert (orig_method); mono_method_desc_free (desc); *method = mono_monitor_get_fast_path (orig_method); break; } case MONO_WRAPPER_RUNTIME_INVOKE: { /* Direct wrapper */ MonoMethod *m = decode_method_ref_2 (module, p, &p); if (!m) return NULL; *method = mono_marshal_get_runtime_invoke (m, FALSE); break; } case MONO_WRAPPER_MANAGED_TO_MANAGED: { int subtype = decode_value (p, &p); if (subtype == MONO_AOT_WRAPPER_ELEMENT_ADDR) { int rank = decode_value (p, &p); int elem_size = decode_value (p, &p); *method = mono_marshal_get_array_address (rank, elem_size); } else { g_assert_not_reached (); } break; } default: g_assert_not_reached (); } } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) { /* Can't decode these */ g_assert_not_reached (); } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) { image_index = decode_value (p, &p); *token = decode_value (p, &p); image = load_image (module, image_index, TRUE); if (!image) return NULL; } else if (image_index == MONO_AOT_METHODREF_GINST) { MonoClass *klass; MonoGenericContext ctx; /* * These methods do not have a token which resolves them, so we * resolve them immediately. */ klass = decode_klass_ref (module, p, &p); if (!klass) return NULL; image_index = decode_value (p, &p); *token = decode_value (p, &p); image = load_image (module, image_index, TRUE); if (!image) return NULL; *method = mono_get_method_full (image, *token, NULL, NULL); if (!(*method)) return NULL; memset (&ctx, 0, sizeof (ctx)); if (FALSE && klass->generic_class) { ctx.class_inst = klass->generic_class->context.class_inst; ctx.method_inst = NULL; *method = mono_class_inflate_generic_method_full (*method, klass, &ctx); } memset (&ctx, 0, sizeof (ctx)); if (!decode_generic_context (module, &ctx, p, &p)) return NULL; *method = mono_class_inflate_generic_method_full (*method, klass, &ctx); } else if (image_index == MONO_AOT_METHODREF_ARRAY) { MonoClass *klass; int method_type; klass = decode_klass_ref (module, p, &p); if (!klass) return NULL; method_type = decode_value (p, &p); *token = 0; switch (method_type) { case 0: *method = mono_class_get_method_from_name (klass, ".ctor", klass->rank); break; case 1: *method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2); break; case 2: *method = mono_class_get_method_from_name (klass, "Get", -1); break; case 3: *method = mono_class_get_method_from_name (klass, "Address", -1); break; case 4: *method = mono_class_get_method_from_name (klass, "Set", -1); break; default: g_assert_not_reached (); } } else { g_assert (image_index < MONO_AOT_METHODREF_MIN); *token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff); image = load_image (module, image_index, TRUE); if (!image) return NULL; } *endbuf = p; return image; } /* * decode_method_ref_2: * * Similar to decode_method_ref, but resolve and return the method itself. */ static MonoMethod* decode_method_ref_2 (MonoAotModule *module, guint8 *buf, guint8 **endbuf) { MonoMethod *method; guint32 token; MonoImage *image = decode_method_ref (module, &token, &method, NULL, buf, endbuf); if (method) return method; if (!image) return NULL; method = mono_get_method (image, token, NULL); return method; } G_GNUC_UNUSED static void make_writable (guint8* addr, guint32 len) { guint8 *page_start; int pages, err; if (mono_aot_only) g_error ("Attempt to make AOT memory writable while running in aot-only mode.\n"); page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)); pages = (addr + len - page_start + mono_pagesize () - 1) / mono_pagesize (); err = mono_mprotect (page_start, pages * mono_pagesize (), MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_EXEC); g_assert (err == 0); } static void create_cache_structure (void) { const char *home; char *tmp; int err; home = g_get_home_dir (); if (!home) return; tmp = g_build_filename (home, ".mono", NULL); if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp); #ifdef HOST_WIN32 err = mkdir (tmp); #else err = mkdir (tmp, 0777); #endif if (err) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno)); g_free (tmp); return; } } g_free (tmp); tmp = g_build_filename (home, ".mono", "aot-cache", NULL); if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp); #ifdef HOST_WIN32 err = mkdir (tmp); #else err = mkdir (tmp, 0777); #endif if (err) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno)); g_free (tmp); return; } } g_free (tmp); } /* * load_aot_module_from_cache: * * Experimental code to AOT compile loaded assemblies on demand. * * FIXME: * - Add environment variable MONO_AOT_CACHE_OPTIONS * - Add options for controlling the cache size * - Handle full cache by deleting old assemblies lru style * - Add options for excluding assemblies during development * - Maybe add a threshold after an assembly is AOT compiled * - invoking a new mono process is a security risk * - recompile the AOT module if one of its dependencies changes */ static MonoDl* load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name) { char *fname, *cmd, *tmp2, *aot_options; const char *home; MonoDl *module; gboolean res; gchar *out, *err; gint exit_status; *aot_name = NULL; if (assembly->image->dynamic) return NULL; create_cache_structure (); home = g_get_home_dir (); tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT); fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL); *aot_name = fname; g_free (tmp2); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname); module = mono_dl_open (fname, MONO_DL_LAZY, NULL); if (!module) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found."); mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name); aot_options = g_strdup_printf ("outfile=%s", fname); if (spawn_compiler) { /* FIXME: security */ /* FIXME: Has to pass the assembly loading path to the child process */ cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name); res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL); #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__) if (res) { if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0)) mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err); else mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded."); g_free (out); g_free (err); } #endif g_free (cmd); } else { res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options); if (!res) { mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed."); } else { mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded."); } } module = mono_dl_open (fname, MONO_DL_LAZY, NULL); g_free (aot_options); } return module; } static void find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value) { if (globals) { int global_index; guint16 *table, *entry; guint16 table_size; guint32 hash; /* The first entry points to the hash */ table = globals [0]; globals ++; table_size = table [0]; table ++; hash = mono_metadata_str_hash (name) % table_size; entry = &table [hash * 2]; /* Search the hash for the index into the globals table */ global_index = -1; while (entry [0] != 0) { guint32 index = entry [0] - 1; guint32 next = entry [1]; //printf ("X: %s %s\n", (char*)globals [index * 2], name); if (!strcmp (globals [index * 2], name)) { global_index = index; break; } if (next != 0) { entry = &table [next * 2]; } else { break; } } if (global_index != -1) *value = globals [global_index * 2 + 1]; else *value = NULL; } else { char *err = mono_dl_symbol (module, name, value); if (err) g_free (err); } } #ifndef SHT_ARM_EXIDX #define SHT_ARM_EXIDX 0x70000001 #endif #if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME) static int dl_callback (struct dl_phdr_info *info, size_t size, void *data) { int j; MonoAotModule *amodule = data; if (!strcmp (amodule->aot_name, info->dlpi_name)) { for (j = 0; j < info->dlpi_phnum; j++) { if (info->dlpi_phdr [j].p_type == PT_GNU_EH_FRAME) amodule->eh_frame_hdr = (guint8*)(info->dlpi_addr + info->dlpi_phdr [j].p_vaddr); if (info->dlpi_phdr [j].p_type == SHT_ARM_EXIDX) { amodule->arm_exidx = (guint8*)(info->dlpi_addr + info->dlpi_phdr [j].p_vaddr); amodule->arm_exidx_size = info->dlpi_phdr [j].p_filesz; } } return 1; } else { return 0; } } #endif static void load_aot_module (MonoAssembly *assembly, gpointer user_data) { char *aot_name; MonoAotModule *amodule; MonoDl *sofile; gboolean usable = TRUE; char *saved_guid = NULL; char *aot_version = NULL; char *runtime_version, *build_info; char *opt_flags = NULL; gpointer *globals; gboolean full_aot = FALSE; MonoAotFileInfo *file_info = NULL; int i; gpointer *got_addr; if (mono_compile_aot) return; if (assembly->image->aot_module) /* * Already loaded. This can happen because the assembly loading code might invoke * the assembly load hooks multiple times for the same assembly. */ return; if (assembly->image->dynamic) return; if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) return; mono_aot_lock (); if (static_aot_modules) globals = g_hash_table_lookup (static_aot_modules, assembly->aname.name); else globals = NULL; mono_aot_unlock (); if (globals) { /* Statically linked AOT module */ sofile = NULL; aot_name = g_strdup_printf ("%s", assembly->aname.name); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name); } else { if (use_aot_cache) sofile = load_aot_module_from_cache (assembly, &aot_name); else { char *err; aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT); sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err); if (!sofile) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err); g_free (err); } } } if (!sofile && !globals) { if (mono_aot_only) { fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name); exit (1); } g_free (aot_name); return; } find_symbol (sofile, globals, "mono_assembly_guid", (gpointer *) &saved_guid); find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &aot_version); find_symbol (sofile, globals, "mono_aot_opt_flags", (gpointer *)&opt_flags); find_symbol (sofile, globals, "mono_runtime_version", (gpointer *)&runtime_version); find_symbol (sofile, globals, "mono_aot_got_addr", (gpointer *)&got_addr); if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) { 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); usable = FALSE; } else { if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name); usable = FALSE; } } build_info = mono_get_runtime_build_info (); if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, build_info)))) { 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); usable = FALSE; } g_free (build_info); find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&file_info); g_assert (file_info); full_aot = ((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_FULL_AOT; if (mono_aot_only && !full_aot) { fprintf (stderr, "Can't use AOT image '%s' in aot-only mode because it is not compiled with --aot=full.\n", aot_name); exit (1); } if (!mono_aot_only && full_aot) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with --aot=full.\n", aot_name); usable = FALSE; } if ((((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with LLVM.\n", aot_name); usable = FALSE; } if (!usable) { if (mono_aot_only) { fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode.\n", aot_name); exit (1); } g_free (aot_name); if (sofile) mono_dl_close (sofile); assembly->image->aot_module = NULL; return; } amodule = g_new0 (MonoAotModule, 1); amodule->aot_name = aot_name; amodule->assembly = assembly; memcpy (&amodule->info, file_info, sizeof (*file_info)); amodule->got = *got_addr; amodule->got [0] = assembly->image; amodule->globals = globals; amodule->sofile = sofile; amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL); /* Read image table */ { guint32 table_len, i; char *table = NULL; find_symbol (sofile, globals, "mono_image_table", (gpointer *)&table); g_assert (table); table_len = *(guint32*)table; table += sizeof (guint32); amodule->image_table = g_new0 (MonoImage*, table_len); amodule->image_names = g_new0 (MonoAssemblyName, table_len); amodule->image_guids = g_new0 (char*, table_len); amodule->image_table_len = table_len; for (i = 0; i < table_len; ++i) { MonoAssemblyName *aname = &(amodule->image_names [i]); aname->name = g_strdup (table); table += strlen (table) + 1; amodule->image_guids [i] = g_strdup (table); table += strlen (table) + 1; if (table [0] != 0) aname->culture = g_strdup (table); table += strlen (table) + 1; memcpy (aname->public_key_token, table, strlen (table) + 1); table += strlen (table) + 1; table = ALIGN_PTR_TO (table, 8); aname->flags = *(guint32*)table; table += 4; aname->major = *(guint32*)table; table += 4; aname->minor = *(guint32*)table; table += 4; aname->build = *(guint32*)table; table += 4; aname->revision = *(guint32*)table; table += 4; } } /* Read method and method_info tables */ find_symbol (sofile, globals, "code_offsets", (gpointer*)&amodule->code_offsets); find_symbol (sofile, globals, "methods", (gpointer*)&amodule->code); find_symbol (sofile, globals, "methods_end", (gpointer*)&amodule->code_end); find_symbol (sofile, globals, "method_info_offsets", (gpointer*)&amodule->method_info_offsets); find_symbol (sofile, globals, "ex_info_offsets", (gpointer*)&amodule->ex_info_offsets); find_symbol (sofile, globals, "blob", (gpointer*)&amodule->blob); find_symbol (sofile, globals, "class_info_offsets", (gpointer*)&amodule->class_info_offsets); find_symbol (sofile, globals, "class_name_table", (gpointer *)&amodule->class_name_table); find_symbol (sofile, globals, "extra_method_table", (gpointer *)&amodule->extra_method_table); find_symbol (sofile, globals, "extra_method_info_offsets", (gpointer *)&amodule->extra_method_info_offsets); find_symbol (sofile, globals, "got_info_offsets", (gpointer*)&amodule->got_info_offsets); find_symbol (sofile, globals, "specific_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC])); find_symbol (sofile, globals, "static_rgctx_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX])); find_symbol (sofile, globals, "imt_thunks", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK])); find_symbol (sofile, globals, "unwind_info", (gpointer)&amodule->unwind_info); find_symbol (sofile, globals, "mem_end", (gpointer*)&amodule->mem_end); amodule->mem_begin = amodule->code; find_symbol (sofile, globals, "plt", (gpointer*)&amodule->plt); find_symbol (sofile, globals, "plt_end", (gpointer*)&amodule->plt_end); if (make_unreadable) { #ifndef TARGET_WIN32 guint8 *addr; guint8 *page_start, *page_end; int err, len; addr = amodule->mem_begin; len = amodule->mem_end - amodule->mem_begin; /* Round down in both directions to avoid modifying data which is not ours */ page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize (); page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1)); if (page_end > page_start) { err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE); g_assert (err == 0); } #endif } mono_aot_lock (); aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code); aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end); g_hash_table_insert (aot_modules, assembly, amodule); mono_aot_unlock (); mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end); assembly->image->aot_module = amodule; #if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME) /* Lookup the address of the .eh_frame_hdr () section if available */ dl_iterate_phdr (dl_callback, amodule); #endif if (mono_aot_only) { if (mono_defaults.corlib) { /* The second got slot contains the mscorlib got addr */ MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module; amodule->got [1] = mscorlib_amodule->got; } else { amodule->got [1] = amodule->got; } } /* * Since we store methoddef and classdef tokens when referring to methods/classes in * referenced assemblies, we depend on the exact versions of the referenced assemblies. * MS calls this 'hard binding'. This means we have to load all referenced assemblies * non-lazily, since we can't handle out-of-date errors later. * The cached class info also depends on the exact assemblies. */ for (i = 0; i < amodule->image_table_len; ++i) load_image (amodule, i, FALSE); if (amodule->out_of_date) { 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); if (mono_aot_only) { 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); exit (1); } } else mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name); } /* * mono_aot_register_globals: * * This is called by the ctor function in AOT images compiled with the * 'no-dlsym' option. */ void mono_aot_register_globals (gpointer *globals) { g_assert_not_reached (); } /* * mono_aot_register_module: * * This should be called by embedding code to register AOT modules statically linked * into the executable. AOT_INFO should be the value of the * 'mono_aot_module__info' global symbol from the AOT module. */ void mono_aot_register_module (gpointer *aot_info) { gpointer *globals; char *aname; globals = aot_info; g_assert (globals); /* Determine the assembly name */ find_symbol (NULL, globals, "mono_aot_assembly_name", (gpointer*)&aname); g_assert (aname); /* This could be called before startup */ if (aot_modules) mono_aot_lock (); if (!static_aot_modules) static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (static_aot_modules, aname, globals); if (aot_modules) mono_aot_unlock (); } void mono_aot_init (void) { InitializeCriticalSection (&aot_mutex); aot_modules = g_hash_table_new (NULL, NULL); mono_install_assembly_load_hook (load_aot_module, NULL); if (g_getenv ("MONO_LASTAOT")) mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT")); if (g_getenv ("MONO_AOT_CACHE")) use_aot_cache = TRUE; } static gboolean decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf) { guint32 flags; info->vtable_size = decode_value (buf, &buf); if (info->vtable_size == -1) /* Generic type */ return FALSE; flags = decode_value (buf, &buf); info->ghcimpl = (flags >> 0) & 0x1; info->has_finalize = (flags >> 1) & 0x1; info->has_cctor = (flags >> 2) & 0x1; info->has_nested_classes = (flags >> 3) & 0x1; info->blittable = (flags >> 4) & 0x1; info->has_references = (flags >> 5) & 0x1; info->has_static_refs = (flags >> 6) & 0x1; info->no_special_static_fields = (flags >> 7) & 0x1; info->is_generic_container = (flags >> 8) & 0x1; if (info->has_cctor) { MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, NULL, NULL, buf, &buf); if (!cctor_image) return FALSE; } if (info->has_finalize) { info->finalize_image = decode_method_ref (module, &info->finalize_token, NULL, NULL, buf, &buf); if (!info->finalize_image) return FALSE; } info->instance_size = decode_value (buf, &buf); info->class_size = decode_value (buf, &buf); info->packing_size = decode_value (buf, &buf); info->min_align = decode_value (buf, &buf); *endbuf = buf; return TRUE; } gpointer mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot) { int i; MonoClass *klass = vtable->klass; MonoAotModule *aot_module = klass->image->aot_module; guint8 *info, *p; MonoCachedClassInfo class_info; gboolean err; guint32 token; MonoImage *image; gboolean no_aot_trampoline; if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !aot_module) return NULL; info = &aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)]; p = info; err = decode_cached_class_info (aot_module, &class_info, p, &p); if (!err) return NULL; for (i = 0; i < slot; ++i) decode_method_ref (aot_module, &token, NULL, NULL, p, &p); image = decode_method_ref (aot_module, &token, NULL, &no_aot_trampoline, p, &p); if (!image) return NULL; if (no_aot_trampoline) return NULL; if (mono_metadata_token_index (token) == 0) return NULL; return mono_aot_get_method_from_token (domain, image, token); } gboolean mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res) { MonoAotModule *aot_module = klass->image->aot_module; guint8 *p; gboolean err; if (klass->rank || !aot_module) return FALSE; p = (guint8*)&aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)]; err = decode_cached_class_info (aot_module, res, p, &p); if (!err) return FALSE; return TRUE; } /** * mono_aot_get_class_from_name: * * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE, * using a cache stored in the AOT file. * Stores the resulting class in *KLASS if found, stores NULL otherwise. * * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was * found. */ gboolean mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass) { MonoAotModule *aot_module = image->aot_module; guint16 *table, *entry; guint16 table_size; guint32 hash; char full_name_buf [1024]; char *full_name; const char *name2, *name_space2; MonoTableInfo *t; guint32 cols [MONO_TYPEDEF_SIZE]; GHashTable *nspace_table; if (!aot_module || !aot_module->class_name_table) return FALSE; mono_aot_lock (); *klass = NULL; /* First look in the cache */ if (!aot_module->name_cache) aot_module->name_cache = g_hash_table_new (g_str_hash, g_str_equal); nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space); if (nspace_table) { *klass = g_hash_table_lookup (nspace_table, name); if (*klass) { mono_aot_unlock (); return TRUE; } } table_size = aot_module->class_name_table [0]; table = aot_module->class_name_table + 1; if (name_space [0] == '\0') full_name = g_strdup_printf ("%s", name); else { if (strlen (name_space) + strlen (name) < 1000) { sprintf (full_name_buf, "%s.%s", name_space, name); full_name = full_name_buf; } else { full_name = g_strdup_printf ("%s.%s", name_space, name); } } hash = mono_metadata_str_hash (full_name) % table_size; if (full_name != full_name_buf) g_free (full_name); entry = &table [hash * 2]; if (entry [0] != 0) { t = &image->tables [MONO_TABLE_TYPEDEF]; while (TRUE) { guint32 index = entry [0]; guint32 next = entry [1]; guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index); name_table_accesses ++; mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE); name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]); name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]); if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) { mono_aot_unlock (); *klass = mono_class_get (image, token); /* Add to cache */ if (*klass) { mono_aot_lock (); nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space); if (!nspace_table) { nspace_table = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (aot_module->name_cache, (char*)name_space2, nspace_table); } g_hash_table_insert (nspace_table, (char*)name2, *klass); mono_aot_unlock (); } return TRUE; } if (next != 0) { entry = &table [next * 2]; } else { break; } } } mono_aot_unlock (); return TRUE; } #define DW_EH_PE_omit 0xff #define DW_EH_PE_uleb128 0x01 #define DW_EH_PE_udata2 0x02 #define DW_EH_PE_udata4 0x03 #define DW_EH_PE_udata8 0x04 #define DW_EH_PE_sleb128 0x09 #define DW_EH_PE_sdata2 0x0A #define DW_EH_PE_sdata4 0x0B #define DW_EH_PE_sdata8 0x0C #define DW_EH_PE_absptr 0x00 #define DW_EH_PE_pcrel 0x10 #define DW_EH_PE_datarel 0x30 #define DW_EH_PE_omit 0xff typedef struct { guint8 version; guint8 eh_frame_ptr_enc; guint8 fde_count_enc; guint8 table_enc; guint8 rest; } eh_frame_hdr; /* * decode_eh_frame: * * Decode the exception handling information in the .eh_frame section of the AOT * file belong to CODE, and construct a MonoJitInfo structure from it. * LOCKING: Acquires the domain lock. */ static G_GNUC_UNUSED MonoJitInfo* decode_eh_frame (MonoAotModule *amodule, MonoDomain *domain, MonoMethod *method, guint8 *code, MonoJitInfo *orig_jinfo, int extra_size) { eh_frame_hdr *hdr; guint8 *p; guint8 *eh_frame, *unwind_info; guint32 eh_frame_ptr; int fde_count; gint32 *table; int i, pos, left, right, offset, offset1, offset2; guint32 unw_len, code_len; MonoJitExceptionInfo *ei; guint32 ei_len; gpointer *type_info; MonoJitInfo *jinfo; g_assert (amodule->eh_frame_hdr); // http://refspecs.freestandards.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html hdr = (eh_frame_hdr*)amodule->eh_frame_hdr; g_assert (hdr->version == 1); g_assert (hdr->eh_frame_ptr_enc == (DW_EH_PE_pcrel | DW_EH_PE_sdata4)); g_assert (hdr->fde_count_enc == DW_EH_PE_udata4); g_assert (hdr->table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4)); p = &(hdr->rest); eh_frame_ptr = *(guint32*)p; p += 4; fde_count = *(guint32*)p; p += 4; table = (gint32*)p; /* Binary search in the table to find the entry for code */ offset = code - amodule->eh_frame_hdr; left = 0; right = fde_count; while (TRUE) { pos = (left + right) / 2; offset1 = table [(pos * 2)]; if (pos + 1 == fde_count) /* FIXME: */ offset2 = amodule->code_end - amodule->code; else offset2 = table [(pos + 1) * 2]; if (offset < offset1) right = pos; else if (offset >= offset2) left = pos + 1; else break; } g_assert (code >= amodule->eh_frame_hdr + table [(pos * 2)]); if (pos < fde_count) g_assert (code < amodule->eh_frame_hdr + table [(pos * 2) + 2]); eh_frame = amodule->eh_frame_hdr + table [(pos * 2) + 1]; unwind_info = mono_unwind_decode_fde (eh_frame, &unw_len, &code_len, &ei, &ei_len, &type_info); /* * LLVM might represent one IL region with multiple regions, so have to * allocate a new JI. */ if (ei_len) { jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * ei_len) + extra_size); } else { jinfo = orig_jinfo; } jinfo->code_size = code_len; jinfo->used_regs = mono_cache_unwind_info (unwind_info, unw_len); jinfo->method = method; jinfo->code_start = code; jinfo->domain_neutral = 0; /* This signals that used_regs points to a normal cached unwind info */ jinfo->from_aot = 0; jinfo->num_clauses = ei_len; for (i = 0; i < ei_len; ++i) { /* * orig_jinfo contains the original IL exception info saved by the AOT * compiler, we have to combine that with the information produced by LLVM */ /* The type_info entries contain IL clause indexes */ int clause_index = *(gint32*)type_info [i]; MonoJitExceptionInfo *jei = &jinfo->clauses [i]; MonoJitExceptionInfo *orig_jei = &orig_jinfo->clauses [clause_index]; g_assert (clause_index < orig_jinfo->num_clauses); jei->flags = orig_jei->flags; jei->data.catch_class = orig_jei->data.catch_class; jei->try_start = ei [i].try_start; jei->try_end = ei [i].try_end; jei->handler_start = ei [i].handler_start; } return jinfo; } #ifdef TARGET_ARM /* The offsets in the table are 31 bits long, have to extend them to 32 */ #define EXTEND_PREL31(val) ((((gint32)(val)) << 1) >> 1) static inline guint32 decode_uleb128 (guint8 *buf, guint8 **endbuf) { guint8 *p = buf; guint32 res = 0; int shift = 0; while (TRUE) { guint8 b = *p; p ++; res = res | (((int)(b & 0x7f)) << shift); if (!(b & 0x80)) break; shift += 7; } *endbuf = p; return res; } static GSList* decode_arm_eh_ops (guint8 *unwind_ops, int nops) { int i, vsp_reg, vsp_offset; GSList *ops; gint32 *reg_offsets; /* * Have to convert the ARM unwind info into DWARF unwind info. * The ARM unwind info specifies a simple set of instructions which need to be * executed during unwinding. It manipulates a virtual stack pointer (vsp). The * connection with DWARF unwind info is the following: after all ARM unwind * opcodes have been executed, the stack should be completely unwound, i.e. * vsp == DWARF CFA. This allows us to construct the DWARF opcodes corresponding * to the ARM opcodes. * The ARM unwind info is not instruction precise, i. e. it can't handle * async exceptions etc. */ /* The reg used to compute the initial value of vsp */ vsp_reg = ARMREG_SP; /* The offset between vsp_reg and the CFA */ vsp_offset = 0; /* The register save offsets from the initial value of vsp */ reg_offsets = g_new0 (gint32, 16); for (i = 0; i < 16; ++i) reg_offsets [i] = -1; /* section 9.3 in the ehabi doc */ for (i = 0; i < nops; ++i) { guint8 op = unwind_ops [i]; if ((op >> 6) == 0) { /* vsp = vsp + (xxxxxx << 2) + 4. */ vsp_offset += ((op & 0x3f) << 2) + 4; } else if ((op >> 6) == 1) { /* vsp = vsp - (xxxxxx << 2) - 4. */ vsp_offset -= ((op & 0x3f) << 2) + 4; } else if (op == 0xb2) { /* vsp = vsp = vsp + 0x204 + (uleb128 << 2) */ guint8 *p = unwind_ops + i + 1; guint32 v = decode_uleb128 (p, &p); vsp_offset += 0x204 + (v << 2); i = (p - unwind_ops) - 1; } else if (op >= 0x80 && op <= 0x8f) { /* pop registers */ guint8 op2; GSList *regs; int j; g_assert (i + 1 < nops); op2 = unwind_ops [i + 1]; regs = NULL; for (j = 0; j < 8; ++j) if (op2 & (0x1 << j)) regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R4 + j)); for (j = 0; j < 4; ++j) if (op & (0x1 << j)) regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R12 + j)); g_assert (regs); for (j = 0; j < g_slist_length (regs); ++j) reg_offsets [GPOINTER_TO_UINT (g_slist_nth (regs, j)->data)] = vsp_offset + (j * 4); vsp_offset += g_slist_length (regs) * 4; g_slist_free (regs); i ++; } else if (op >= 0xa8 && op <= 0xaf) { GSList *regs; int j; /* pop r4-r[4 + nnn], r14 */ regs = NULL; for (j = 0; j <= (op & 0x7); ++j) regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R4 + j)); regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R14)); for (j = 0; j < g_slist_length (regs); ++j) reg_offsets [GPOINTER_TO_UINT (g_slist_nth (regs, j)->data)] = vsp_offset + (j * 4); vsp_offset += g_slist_length (regs) * 4; g_slist_free (regs); } else if (op == 0xb0) { /* finish */ break; } else if (op >= 0x90 && op <= 0x9f && op != 0x9d && op != 0x9f) { /* vsp = */ vsp_reg = op & 0xf; vsp_offset = 0; } else { int j; for (j = 0; j < nops; ++j) printf ("%x ", unwind_ops [j]); printf (" / %d\n", i); g_assert_not_reached (); } } ops = NULL; /* vsp_reg + vsp_offset = CFA */ mono_add_unwind_op_def_cfa (ops, (guint8*)NULL, (guint8*)NULL, vsp_reg, vsp_offset); for (i = 0; i < 16; ++i) { if (reg_offsets [i] != -1) /* The reg is saved at vsp_reg + reg_offset [i] == CFA - (vsp_offset - reg_offset [i]) */ mono_add_unwind_op_offset (ops, (guint8*)NULL, (guint8*)NULL, i, - (vsp_offset - reg_offsets [i])); } return ops; } /* * decode_arm_exidx: * * Decode the exception handling information in the .ARM.exidx section of the AOT * file belong to CODE, and construct a MonoJitInfo structure from it. * LOCKING: Acquires the domain lock. */ static void decode_arm_exidx (MonoAotModule *amodule, MonoDomain *domain, MonoMethod *method, guint8 *code, guint32 code_len, MonoJitInfo *jinfo) { guint32 *table; guint8 *base, *code1, *code2; int i, pos, left, right, offset, offset1, offset2, count, nwords, nops; guint32 entry; guint8 unwind_ops [64]; GSList *ops; guint8 *unwind_info; guint32 unw_len; g_assert (amodule->arm_exidx); table = (guint32*)amodule->arm_exidx; /* * The table format is described in: * infocenter.arm.com/help/topic/com.arm.doc.../IHI0038A_ehabi.pdf */ base = amodule->arm_exidx; count = amodule->arm_exidx_size / 8; /* Binary search in the table to find the entry for code */ offset = code - base; left = 0; right = count; while (TRUE) { pos = (left + right) / 2; if (left == right) break; offset1 = EXTEND_PREL31 (table [(pos * 2)]); code1 = (guint8*)&(table [pos * 2]) + offset1; if (pos + 1 == count) /* FIXME: */ offset2 = amodule->code_end - amodule->code; else offset2 = EXTEND_PREL31 (table [(pos + 1) * 2]); code2 = (guint8*)&(table [(pos + 1) * 2]) + offset2; if (code < code1) right = pos; else if (code >= code2) left = pos + 1; else break; } if (code >= code1) { /* * The linker might merge duplicate unwind table entries, so * offset1 and offset2 might point to another method, but this is not a problem. */ code1 = (guint8*)&(table [pos * 2]) + offset1; code2 = (guint8*)&(table [(pos + 1) * 2]) + offset2; g_assert (code >= code1); if (pos < count) g_assert (code < code2); entry = table [(pos * 2) + 1]; /* inline entry, compact model, personality routine 0 */ if ((entry & 0xff000000) == 0x80000000) { nops = 3; unwind_ops [0] = (entry & 0x00ff0000) >> 16; unwind_ops [1] = (entry & 0x0000ff00) >> 8; unwind_ops [2] = (entry & 0x000000ff) >> 0; ops = decode_arm_eh_ops (unwind_ops, nops); } else if ((entry & 0x80000000) == 0) { /* non-inline entry */ guint8 *data = (guint8*)&table [(pos * 2) + 1] + EXTEND_PREL31 (entry); entry = ((guint32*)data) [0]; /* compact model, personality routine 1 */ g_assert ((entry & 0xff000000) == 0x81000000); nwords = (entry & 0x00ff0000) >> 16; nops = nwords * 4 + 2; g_assert (nops < 64); unwind_ops [0] = (entry & 0x0000ff00) >> 8; unwind_ops [1] = (entry & 0x000000ff) >> 0; for (i = 0; i < nwords; ++i) { entry = ((guint32*)data) [1 + i]; unwind_ops [(i * 4) + 2] = (entry & 0xff000000) >> 24; unwind_ops [(i * 4) + 2 + 1] = (entry & 0x00ff0000) >> 16; unwind_ops [(i * 4) + 2 + 2] = (entry & 0x0000ff00) >> 8; unwind_ops [(i * 4) + 2 + 3] = (entry & 0x000000ff) >> 0; } ops = decode_arm_eh_ops (unwind_ops, nops); } else { NOT_IMPLEMENTED; } unwind_info = mono_unwind_ops_encode (ops, &unw_len); } else { /* The method has no unwind info */ unwind_info = NULL; unw_len = 0; } jinfo->code_size = code_len; jinfo->used_regs = mono_cache_unwind_info (unwind_info, unw_len); jinfo->method = method; jinfo->code_start = code; jinfo->domain_neutral = 0; /* This signals that used_regs points to a normal cached unwind info */ jinfo->from_aot = 0; } #endif /* * LOCKING: Acquires the domain lock. */ static MonoJitInfo* decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, MonoMethod *method, guint8* ex_info, guint8 *addr, guint8 *code, guint32 code_len) { int i, buf_len; MonoJitInfo *jinfo; guint used_int_regs, flags; gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes; gboolean from_llvm; guint8 *p; int generic_info_size, try_holes_info_size, num_holes; /* Load the method info from the AOT file */ p = ex_info; flags = decode_value (p, &p); has_generic_jit_info = (flags & 1) != 0; has_dwarf_unwind_info = (flags & 2) != 0; has_clauses = (flags & 4) != 0; has_seq_points = (flags & 8) != 0; from_llvm = (flags & 16) != 0; has_try_block_holes = (flags & 32) != 0; if (has_dwarf_unwind_info) { guint32 offset; offset = decode_value (p, &p); g_assert (offset < (1 << 30)); used_int_regs = offset; } else { used_int_regs = decode_value (p, &p); } if (has_generic_jit_info) generic_info_size = sizeof (MonoGenericJitInfo); else generic_info_size = 0; if (has_try_block_holes) { num_holes = decode_value (p, &p); try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo); } else { num_holes = try_holes_info_size = 0; } /* Exception table */ if (has_clauses) { int num_clauses = decode_value (p, &p); jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size); jinfo->num_clauses = num_clauses; for (i = 0; i < num_clauses; ++i) { MonoJitExceptionInfo *ei = &jinfo->clauses [i]; ei->flags = decode_value (p, &p); if (from_llvm) { if (decode_value (p, &p)) ei->data.catch_class = decode_klass_ref (amodule, p, &p); /* The rest of the info is in the DWARF EH section */ continue; } ei->exvar_offset = decode_value (p, &p); if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) ei->data.filter = code + decode_value (p, &p); else { if (decode_value (p, &p)) ei->data.catch_class = decode_klass_ref (amodule, p, &p); } ei->try_start = code + decode_value (p, &p); ei->try_end = code + decode_value (p, &p); ei->handler_start = code + decode_value (p, &p); } } else { jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + generic_info_size + try_holes_info_size); } if (from_llvm) { /* LLVM compiled method */ /* The info is in the .eh_frame section */ #ifdef TARGET_ARM decode_arm_exidx (amodule, domain, method, code, code_len, jinfo); #else jinfo = decode_eh_frame (amodule, domain, method, code, jinfo, generic_info_size); #endif jinfo->from_llvm = 1; } else { jinfo->code_size = code_len; jinfo->used_regs = used_int_regs; jinfo->method = method; jinfo->code_start = code; jinfo->domain_neutral = 0; jinfo->from_aot = 1; } if (has_generic_jit_info) { MonoGenericJitInfo *gi; jinfo->has_generic_jit_info = 1; gi = mono_jit_info_get_generic_jit_info (jinfo); g_assert (gi); gi->has_this = decode_value (p, &p); gi->this_reg = decode_value (p, &p); gi->this_offset = decode_value (p, &p); /* This currently contains no data */ gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1); jinfo->method = decode_method_ref_2 (amodule, p, &p); } if (has_try_block_holes) { MonoTryBlockHoleTableJitInfo *table; jinfo->has_try_block_holes = 1; table = mono_jit_info_get_try_block_hole_table_info (jinfo); g_assert (table); table->num_holes = (guint16)num_holes; for (i = 0; i < num_holes; ++i) { MonoTryBlockHoleJitInfo *hole = &table->holes [i]; hole->clause = decode_value (p, &p); hole->length = decode_value (p, &p); hole->offset = decode_value (p, &p); } } if (has_seq_points) { MonoSeqPointInfo *seq_points; int il_offset, native_offset, last_il_offset, last_native_offset, j; int len = decode_value (p, &p); seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint)); seq_points->len = len; last_il_offset = last_native_offset = 0; for (i = 0; i < len; ++i) { SeqPoint *sp = &seq_points->seq_points [i]; il_offset = last_il_offset + decode_value (p, &p); native_offset = last_native_offset + decode_value (p, &p); sp->il_offset = il_offset; sp->native_offset = native_offset; sp->next_len = decode_value (p, &p); sp->next = g_new (int, sp->next_len); for (j = 0; j < sp->next_len; ++j) sp->next [j] = decode_value (p, &p); last_il_offset = il_offset; last_native_offset = native_offset; } mono_domain_lock (domain); g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points); mono_domain_unlock (domain); } /* Load debug info */ buf_len = decode_value (p, &p); mono_debug_add_aot_method (domain, method, code, p, buf_len); if (amodule != jinfo->method->klass->image->aot_module) { mono_aot_lock (); if (!ji_to_amodule) ji_to_amodule = g_hash_table_new (NULL, NULL); g_hash_table_insert (ji_to_amodule, jinfo, amodule); mono_aot_unlock (); } return jinfo; } /* * mono_aot_get_unwind_info: * * Return a pointer to the DWARF unwind info belonging to JI. */ guint8* mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len) { MonoAotModule *amodule = ji->method->klass->image->aot_module; guint8 *p; guint8 *code = ji->code_start; g_assert (amodule); g_assert (ji->from_aot); if (!(code >= amodule->code && code <= amodule->code_end)) { /* ji belongs to a different aot module than amodule */ mono_aot_lock (); g_assert (ji_to_amodule); amodule = g_hash_table_lookup (ji_to_amodule, ji); g_assert (amodule); g_assert (code >= amodule->code && code <= amodule->code_end); mono_aot_unlock (); } p = amodule->unwind_info + ji->used_regs; *unwind_info_len = decode_value (p, &p); return p; } static G_GNUC_UNUSED int compare_ints (const void *a, const void *b) { return *(gint32*)a - *(gint32*)b; } static void msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch) { int mid = (lo + hi) / 2; int i, t_lo, t_hi; if (lo >= hi) return; if (hi - lo < 32) { for (i = lo; i < hi; ++i) if (array [(i * 2)] > array [(i * 2) + 2]) break; if (i == hi) /* Already sorted */ return; } msort_code_offsets_internal (array, lo, mid, scratch); msort_code_offsets_internal (array, mid + 1, hi, scratch); if (array [mid * 2] < array [(mid + 1) * 2]) return; /* Merge */ t_lo = lo; t_hi = mid + 1; for (i = lo; i <= hi; i ++) { if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) { scratch [(i * 2)] = array [t_lo * 2]; scratch [(i * 2) + 1] = array [(t_lo *2) + 1]; t_lo ++; } else { scratch [(i * 2)] = array [t_hi * 2]; scratch [(i * 2) + 1] = array [(t_hi *2) + 1]; t_hi ++; } } for (i = lo; i <= hi; ++i) { array [(i * 2)] = scratch [i * 2]; array [(i * 2) + 1] = scratch [(i * 2) + 1]; } } static void msort_code_offsets (gint32 *array, int len) { gint32 *scratch; scratch = g_new (gint32, len * 2); msort_code_offsets_internal (array, 0, len - 1, scratch); g_free (scratch); } MonoJitInfo * mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr) { int pos, left, right, offset, offset1, offset2, code_len; int method_index, table_len, is_wrapper; guint32 token; MonoAotModule *amodule = image->aot_module; MonoMethod *method; MonoJitInfo *jinfo; guint8 *code, *ex_info, *p; guint32 *table; int nmethods = amodule->info.nmethods; gint32 *code_offsets; int offsets_len, i; if (!amodule) return NULL; if (domain != mono_get_root_domain ()) /* FIXME: */ return NULL; offset = (guint8*)addr - amodule->code; /* Compute a sorted table mapping code offsets to method indexes. */ if (!amodule->sorted_code_offsets) { code_offsets = g_new0 (gint32, nmethods * 2); offsets_len = 0; for (i = 0; i < nmethods; ++i) { /* Skip the -1 entries to speed up sorting */ if (amodule->code_offsets [i] == 0xffffffff) continue; code_offsets [(offsets_len * 2)] = amodule->code_offsets [i]; code_offsets [(offsets_len *2) + 1] = i; offsets_len ++; } /* Use a merge sort as this is mostly sorted */ msort_code_offsets (code_offsets, offsets_len); //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints); for (i = 0; i < offsets_len -1; ++i) g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]); if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL) /* Somebody got in before us */ g_free (code_offsets); amodule->sorted_code_offsets_len = offsets_len; } code_offsets = amodule->sorted_code_offsets; offsets_len = amodule->sorted_code_offsets_len; /* Binary search in the sorted_code_offsets table */ left = 0; right = offsets_len; while (TRUE) { pos = (left + right) / 2; offset1 = code_offsets [(pos * 2)]; if (pos + 1 == offsets_len) offset2 = amodule->code_end - amodule->code; else offset2 = code_offsets [(pos + 1) * 2]; if (offset < offset1) right = pos; else if (offset >= offset2) left = pos + 1; else break; } g_assert (offset >= code_offsets [(pos * 2)]); if (pos + 1 < offsets_len) g_assert (offset < code_offsets [((pos + 1) * 2)]); method_index = code_offsets [(pos * 2) + 1]; code = &amodule->code [amodule->code_offsets [method_index]]; ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)]; if (pos == offsets_len - 1) code_len = amodule->code_end - code; else code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2]; g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len); /* Might be a wrapper/extra method */ if (amodule->extra_methods) { mono_aot_lock (); method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index)); mono_aot_unlock (); } else { method = NULL; } if (!method) { if (method_index >= image->tables [MONO_TABLE_METHOD].rows) { /* * This is hit for extra methods which are called directly, so they are * not in amodule->extra_methods. */ table_len = amodule->extra_method_info_offsets [0]; table = amodule->extra_method_info_offsets + 1; left = 0; right = table_len; pos = 0; /* Binary search */ while (TRUE) { pos = ((left + right) / 2); g_assert (pos < table_len); if (table [pos * 2] < method_index) left = pos + 1; else if (table [pos * 2] > method_index) right = pos; else break; } p = amodule->blob + table [(pos * 2) + 1]; is_wrapper = decode_value (p, &p); g_assert (!is_wrapper); method = decode_method_ref_2 (amodule, p, &p); g_assert (method); } else { token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1); method = mono_get_method (image, token, NULL); } } /* FIXME: */ g_assert (method); //printf ("F: %s\n", mono_method_full_name (method, TRUE)); jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len); g_assert ((guint8*)addr >= (guint8*)jinfo->code_start); g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size); /* Add it to the normal JitInfo tables */ mono_jit_info_table_add (domain, jinfo); return jinfo; } static gboolean decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf) { guint8 *p = buf; gpointer *table; MonoImage *image; int i; switch (ji->type) { case MONO_PATCH_INFO_METHOD: case MONO_PATCH_INFO_METHOD_JUMP: case MONO_PATCH_INFO_ICALL_ADDR: case MONO_PATCH_INFO_METHOD_RGCTX: { guint32 token; MonoMethod *method; gboolean no_aot_trampoline; image = decode_method_ref (aot_module, &token, &method, &no_aot_trampoline, p, &p); if (!image) goto cleanup; if (!method && !mono_aot_only && !no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) { ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (image, token)); ji->type = MONO_PATCH_INFO_ABS; } else { if (method) ji->data.method = method; else ji->data.method = mono_get_method (image, token, NULL); g_assert (ji->data.method); mono_class_init (ji->data.method->klass); } break; } case MONO_PATCH_INFO_INTERNAL_METHOD: case MONO_PATCH_INFO_JIT_ICALL_ADDR: { guint32 len = decode_value (p, &p); ji->data.name = (char*)p; p += len + 1; break; } case MONO_PATCH_INFO_METHODCONST: /* Shared */ ji->data.method = decode_method_ref_2 (aot_module, p, &p); if (!ji->data.method) goto cleanup; break; case MONO_PATCH_INFO_VTABLE: case MONO_PATCH_INFO_CLASS: case MONO_PATCH_INFO_IID: case MONO_PATCH_INFO_ADJUSTED_IID: /* Shared */ ji->data.klass = decode_klass_ref (aot_module, p, &p); if (!ji->data.klass) goto cleanup; break; case MONO_PATCH_INFO_CLASS_INIT: case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: ji->data.klass = decode_klass_ref (aot_module, p, &p); if (!ji->data.klass) goto cleanup; break; case MONO_PATCH_INFO_IMAGE: ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE); if (!ji->data.image) goto cleanup; break; case MONO_PATCH_INFO_FIELD: case MONO_PATCH_INFO_SFLDA: /* Shared */ ji->data.field = decode_field_info (aot_module, p, &p); if (!ji->data.field) goto cleanup; break; case MONO_PATCH_INFO_SWITCH: ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable)); ji->data.table->table_size = decode_value (p, &p); table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size); ji->data.table->table = (MonoBasicBlock**)table; for (i = 0; i < ji->data.table->table_size; i++) table [i] = (gpointer)(gssize)decode_value (p, &p); break; case MONO_PATCH_INFO_R4: { guint32 val; ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float)); val = decode_value (p, &p); *(float*)ji->data.target = *(float*)&val; break; } case MONO_PATCH_INFO_R8: { guint32 val [2]; guint64 v; ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double)); val [0] = decode_value (p, &p); val [1] = decode_value (p, &p); v = ((guint64)val [1] << 32) | ((guint64)val [0]); *(double*)ji->data.target = *(double*)&v; break; } case MONO_PATCH_INFO_LDSTR: image = load_image (aot_module, decode_value (p, &p), TRUE); if (!image) goto cleanup; ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p)); break; case MONO_PATCH_INFO_RVA: case MONO_PATCH_INFO_DECLSEC: case MONO_PATCH_INFO_LDTOKEN: case MONO_PATCH_INFO_TYPE_FROM_HANDLE: /* Shared */ image = load_image (aot_module, decode_value (p, &p), TRUE); if (!image) goto cleanup; ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p)); ji->data.token->has_context = decode_value (p, &p); if (ji->data.token->has_context) { gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p); if (!res) goto cleanup; } break; case MONO_PATCH_INFO_EXC_NAME: ji->data.klass = decode_klass_ref (aot_module, p, &p); if (!ji->data.klass) goto cleanup; ji->data.name = ji->data.klass->name; break; case MONO_PATCH_INFO_METHOD_REL: ji->data.offset = decode_value (p, &p); break; case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG: case MONO_PATCH_INFO_GENERIC_CLASS_INIT: case MONO_PATCH_INFO_MONITOR_ENTER: case MONO_PATCH_INFO_MONITOR_EXIT: break; case MONO_PATCH_INFO_RGCTX_FETCH: { gboolean res; MonoJumpInfoRgctxEntry *entry; entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry)); entry->method = decode_method_ref_2 (aot_module, p, &p); entry->in_mrgctx = decode_value (p, &p); entry->info_type = decode_value (p, &p); entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo)); entry->data->type = decode_value (p, &p); res = decode_patch (aot_module, mp, entry->data, p, &p); if (!res) goto cleanup; ji->data.rgctx_entry = entry; break; } case MONO_PATCH_INFO_SEQ_POINT_INFO: break; case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: { MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp)); imt_tramp->method = decode_method_ref_2 (aot_module, p, &p); imt_tramp->vt_offset = decode_value (p, &p); ji->data.imt_tramp = imt_tramp; break; } default: g_warning ("unhandled type %d", ji->type); g_assert_not_reached (); } *endbuf = p; return TRUE; cleanup: return FALSE; } static MonoJumpInfo* load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, guint32 **got_slots, guint8 *buf, guint8 **endbuf) { MonoJumpInfo *patches; int pindex; guint8 *p; p = buf; patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches); *got_slots = g_malloc (sizeof (guint32) * n_patches); for (pindex = 0; pindex < n_patches; ++pindex) { MonoJumpInfo *ji = &patches [pindex]; guint8 *shared_p; gboolean res; guint32 got_offset; got_offset = decode_value (p, &p); if (aot_module->got [got_offset]) { /* Already loaded */ //printf ("HIT!\n"); } else { shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset); ji->type = decode_value (shared_p, &shared_p); res = decode_patch (aot_module, mp, ji, shared_p, &shared_p); if (!res) goto cleanup; } (*got_slots) [pindex] = got_offset; } *endbuf = p; return patches; cleanup: g_free (*got_slots); *got_slots = NULL; return NULL; } static void register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot) { /* * Jump addresses cannot be patched by the trampoline code since it * does not have access to the caller's address. Instead, we collect * the addresses of the GOT slots pointing to a method, and patch * them after the method has been compiled. */ MonoJitDomainInfo *info = domain_jit_info (domain); GSList *list; mono_domain_lock (domain); if (!info->jump_target_got_slot_hash) info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL); list = g_hash_table_lookup (info->jump_target_got_slot_hash, method); list = g_slist_prepend (list, got_slot); g_hash_table_insert (info->jump_target_got_slot_hash, method, list); mono_domain_unlock (domain); } /* * load_method: * * Load the method identified by METHOD_INDEX from the AOT image. Return a * pointer to the native code of the method, or NULL if not found. * METHOD might not be set if the caller only has the image/token info. */ static gpointer load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index) { MonoClass *klass; gboolean from_plt = method == NULL; MonoMemPool *mp; int i, pindex, n_patches, used_strings; gboolean keep_patches = TRUE; guint8 *p; MonoJitInfo *jinfo = NULL; guint8 *code, *info; if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE) return NULL; if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED))) /* Non shared AOT code can't be used in other appdomains */ return NULL; if (amodule->out_of_date) return NULL; if (amodule->code_offsets [method_index] == 0xffffffff) { if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) { char *full_name; if (!method) method = mono_get_method (image, token, NULL); full_name = mono_method_full_name (method, TRUE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name); g_free (full_name); } return NULL; } code = &amodule->code [amodule->code_offsets [method_index]]; info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)]; mono_aot_lock (); if (!amodule->methods_loaded) amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods + 1); mono_aot_unlock (); if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1) return code; if (mono_last_aot_method != -1) { if (mono_jit_stats.methods_aot >= mono_last_aot_method) return NULL; else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) { if (!method) method = mono_get_method (image, token, NULL); if (method) { char *name = mono_method_full_name (method, TRUE); printf ("LAST AOT METHOD: %s.\n", name); g_free (name); } else { printf ("LAST AOT METHOD: %p %d\n", code, method_index); } } } p = info; if (method) { klass = method->klass; decode_klass_ref (amodule, p, &p); } else { klass = decode_klass_ref (amodule, p, &p); } if (amodule->info.opts & MONO_OPT_SHARED) used_strings = decode_value (p, &p); else used_strings = 0; for (i = 0; i < used_strings; i++) { guint token = decode_value (p, &p); mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token)); } if (amodule->info.opts & MONO_OPT_SHARED) keep_patches = FALSE; n_patches = decode_value (p, &p); keep_patches = FALSE; if (n_patches) { MonoJumpInfo *patches; guint32 *got_slots; if (keep_patches) mp = domain->mp; else mp = mono_mempool_new (); patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p); if (patches == NULL) goto cleanup; for (pindex = 0; pindex < n_patches; ++pindex) { MonoJumpInfo *ji = &patches [pindex]; if (!amodule->got [got_slots [pindex]]) { amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE); if (ji->type == MONO_PATCH_INFO_METHOD_JUMP) amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]); if (ji->type == MONO_PATCH_INFO_METHOD_JUMP) register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]])); } ji->type = MONO_PATCH_INFO_NONE; } g_free (got_slots); if (!keep_patches) mono_mempool_destroy (mp); } if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) { char *full_name; if (!method) method = mono_get_method (image, token, NULL); full_name = mono_method_full_name (method, TRUE); if (!jinfo) jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code); 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); g_free (full_name); } mono_aot_lock (); mono_jit_stats.methods_aot++; amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32); init_plt (amodule); if (method && method->wrapper_type) g_hash_table_insert (amodule->method_to_code, method, code); mono_aot_unlock (); if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) { MonoJitInfo *jinfo; if (!method) { method = mono_get_method (image, token, NULL); g_assert (method); } mono_profiler_method_jit (method); jinfo = mono_jit_info_table_find (domain, (char*)code); g_assert (jinfo); mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK); } if (from_plt && klass && !klass->generic_container) mono_runtime_class_init (mono_class_vtable (domain, klass)); return code; cleanup: /* FIXME: The space in domain->mp is wasted */ if (amodule->info.opts & MONO_OPT_SHARED) /* No need to cache patches */ mono_mempool_destroy (mp); if (jinfo) g_free (jinfo); return NULL; } static guint32 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name) { guint32 table_size, entry_size, hash; guint32 *table, *entry; guint32 index; static guint32 n_extra_decodes; if (!amodule) return 0xffffff; table_size = amodule->extra_method_table [0]; table = amodule->extra_method_table + 1; entry_size = 3; hash = mono_aot_method_hash (method) % table_size; entry = &table [hash * entry_size]; if (entry [0] == 0) return 0xffffff; index = 0xffffff; while (TRUE) { guint32 key = entry [0]; guint32 value = entry [1]; guint32 next = entry [entry_size - 1]; MonoMethod *m; guint8 *p; int is_wrapper_name; p = amodule->blob + key; is_wrapper_name = decode_value (p, &p); if (is_wrapper_name) { int wrapper_type = decode_value (p, &p); if (wrapper_type == method->wrapper_type && !strcmp (name, (char*)p)) { index = value; break; } } else if (can_method_ref_match_method (amodule, p, method)) { mono_aot_lock (); if (!amodule->method_ref_to_method) amodule->method_ref_to_method = g_hash_table_new (NULL, NULL); m = g_hash_table_lookup (amodule->method_ref_to_method, p); mono_aot_unlock (); if (!m) { guint8 *orig_p = p; m = decode_method_ref_2 (amodule, p, &p); if (m) { mono_aot_lock (); g_hash_table_insert (amodule->method_ref_to_method, orig_p, m); mono_aot_unlock (); } } if (m == method) { index = value; break; } /* Special case: wrappers of shared generic methods */ if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type && method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) { MonoMethod *w1 = mono_marshal_method_from_wrapper (method); MonoMethod *w2 = mono_marshal_method_from_wrapper (m); if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) { index = value; break; } } /* Methods decoded needlessly */ /* if (m) printf ("%d %s %s\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE)); */ n_extra_decodes ++; } if (next != 0) entry = &table [next * entry_size]; else break; } return index; } static void add_module_cb (gpointer key, gpointer value, gpointer user_data) { g_ptr_array_add ((GPtrArray*)user_data, value); } /* * find_extra_method: * * Try finding METHOD in the extra_method table in all AOT images. * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT * module where the method was found. */ static guint32 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule) { guint32 index; GPtrArray *modules; int i; char *name = NULL; if (method->wrapper_type) name = mono_aot_wrapper_name (method); /* Try the method's module first */ *out_amodule = method->klass->image->aot_module; index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name); if (index != 0xffffff) { g_free (name); return index; } /* * Try all other modules. * This is needed because generic instances klass->image points to the image * containing the generic definition, but the native code is generated to the * AOT image which contains the reference. */ /* Make a copy to avoid doing the search inside the aot lock */ modules = g_ptr_array_new (); mono_aot_lock (); g_hash_table_foreach (aot_modules, add_module_cb, modules); mono_aot_unlock (); index = 0xffffff; for (i = 0; i < modules->len; ++i) { MonoAotModule *amodule = g_ptr_array_index (modules, i); if (amodule != method->klass->image->aot_module) index = find_extra_method_in_amodule (amodule, method, name); if (index != 0xffffff) { *out_amodule = amodule; break; } } g_ptr_array_free (modules, TRUE); g_free (name); return index; } /* * mono_aot_get_method: * * Return a pointer to the AOTed native code for METHOD if it can be found, * NULL otherwise. * On platforms with function pointers, this doesn't return a function pointer. */ gpointer mono_aot_get_method (MonoDomain *domain, MonoMethod *method) { MonoClass *klass = method->klass; guint32 method_index; MonoAotModule *amodule = klass->image->aot_module; guint8 *code; if (!amodule) return NULL; if (amodule->out_of_date) return NULL; if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) return NULL; /* * Use the original method instead of its invoke-with-check wrapper. * This is not a problem when using full-aot, since it doesn't support * remoting. */ if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method)); g_assert (klass->inited); /* Find method index */ if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) { /* * For generic methods, we store the fully shared instance in place of the * original method. */ method = mono_method_get_declaring_generic_method (method); method_index = mono_metadata_token_index (method->token) - 1; } else if (method->is_inflated || !method->token) { /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */ mono_aot_lock (); code = g_hash_table_lookup (amodule->method_to_code, method); mono_aot_unlock (); if (code) return code; method_index = find_extra_method (method, &amodule); /* * Special case the ICollection wrappers for arrays, as they cannot * be statically enumerated, and each wrapper ends up calling the same * method in Array. */ if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) { MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method); code = mono_aot_get_method (domain, m); if (code) { if (mono_method_needs_static_rgctx_invoke (m, FALSE)) { code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code)); /* The call above returns an ftnptr */ code = mono_get_addr_from_ftnptr (code); } return code; } } /* * Special case Array.GetGenericValueImpl which is a generic icall. * Generic sharing currently can't handle it, but the icall returns data using * an out parameter, so the managed-to-native wrappers can share the same code. */ if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) { MonoMethod *m; MonoGenericContext ctx; MonoType *args [16]; if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT) /* Avoid recursion */ return NULL; m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2); g_assert (m); memset (&ctx, 0, sizeof (ctx)); args [0] = &mono_defaults.object_class->byval_arg; ctx.method_inst = mono_metadata_get_generic_inst (1, args); m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE); /* * Get the code for the instantiation which should be emitted into * the mscorlib aot image by the AOT compiler. */ code = mono_aot_get_method (domain, m); if (code) return code; } if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) { /* Partial sharing */ method_index = find_extra_method (mini_get_shared_method (method), &amodule); } if (method_index == 0xffffff) { if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) { char *full_name; full_name = mono_method_full_name (method, TRUE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name); g_free (full_name); } return NULL; } if (method_index == 0xffffff) return NULL; /* Needed by find_jit_info */ mono_aot_lock (); if (!amodule->extra_methods) amodule->extra_methods = g_hash_table_new (NULL, NULL); g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method); mono_aot_unlock (); } else { /* Common case */ method_index = mono_metadata_token_index (method->token) - 1; } return load_method (domain, amodule, klass->image, method, method->token, method_index); } /** * Same as mono_aot_get_method, but we try to avoid loading any metadata from the * method. */ gpointer mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token) { MonoAotModule *aot_module = image->aot_module; int method_index; if (!aot_module) return NULL; method_index = mono_metadata_token_index (token) - 1; return load_method (domain, aot_module, image, NULL, token, method_index); } typedef struct { guint8 *addr; gboolean res; } IsGotEntryUserData; static void check_is_got_entry (gpointer key, gpointer value, gpointer user_data) { IsGotEntryUserData *data = (IsGotEntryUserData*)user_data; MonoAotModule *aot_module = (MonoAotModule*)value; if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size))) data->res = TRUE; } gboolean mono_aot_is_got_entry (guint8 *code, guint8 *addr) { IsGotEntryUserData user_data; if (!aot_modules) return FALSE; user_data.addr = addr; user_data.res = FALSE; mono_aot_lock (); g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data); mono_aot_unlock (); return user_data.res; } typedef struct { guint8 *addr; MonoAotModule *module; } FindAotModuleUserData; static void find_aot_module_cb (gpointer key, gpointer value, gpointer user_data) { FindAotModuleUserData *data = (FindAotModuleUserData*)user_data; MonoAotModule *aot_module = (MonoAotModule*)value; if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end))) data->module = aot_module; } static inline MonoAotModule* find_aot_module (guint8 *code) { FindAotModuleUserData user_data; if (!aot_modules) return NULL; /* Reading these need no locking */ if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr)) return NULL; user_data.addr = code; user_data.module = NULL; mono_aot_lock (); g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data); mono_aot_unlock (); return user_data.module; } void mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr) { /* * Since AOT code is only used in the root domain, * mono_domain_get () != mono_get_root_domain () means the calling method * is AppDomain:InvokeInDomain, so this is the same check as in * mono_method_same_domain () but without loading the metadata for the method. */ if (mono_domain_get () == mono_get_root_domain ()) mono_arch_patch_plt_entry (code, got, regs, addr); } /* * mono_aot_plt_resolve: * * This function is called by the entries in the PLT to resolve the actual method that * needs to be called. It returns a trampoline to the method and patches the PLT entry. * Returns NULL if the something cannot be loaded. */ gpointer mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code) { #ifdef MONO_ARCH_AOT_SUPPORTED guint8 *p, *target, *plt_entry; MonoJumpInfo ji; MonoAotModule *module = (MonoAotModule*)aot_module; gboolean res, no_ftnptr = FALSE; MonoMemPool *mp; //printf ("DYN: %p %d\n", aot_module, plt_info_offset); p = &module->blob [plt_info_offset]; ji.type = decode_value (p, &p); mp = mono_mempool_new_size (512); res = decode_patch (module, mp, &ji, p, &p); if (!res) { mono_mempool_destroy (mp); return NULL; } /* * Avoid calling resolve_patch_target in the full-aot case if possible, since * it would create a trampoline, and we don't need that. * We could do this only if the method does not need the special handling * in mono_magic_trampoline (). */ 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) && !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) { target = mono_jit_compile_method (ji.data.method); no_ftnptr = TRUE; } else { target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE); } /* * The trampoline expects us to return a function descriptor on platforms which use * it, but resolve_patch_target returns a direct function pointer for some type of * patches, so have to translate between the two. * FIXME: Clean this up, but how ? */ 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) { /* These should already have a function descriptor */ #ifdef PPC_USES_FUNCTION_DESCRIPTOR /* Our function descriptors have a 0 environment, gcc created ones don't */ if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR) g_assert (((gpointer*)target) [2] == 0); #endif /* Empty */ } else if (!no_ftnptr) { #ifdef PPC_USES_FUNCTION_DESCRIPTOR g_assert (((gpointer*)target) [2] != 0); #endif target = mono_create_ftnptr (mono_domain_get (), target); } mono_mempool_destroy (mp); /* Patch the PLT entry with target which might be the actual method not a trampoline */ plt_entry = mono_aot_get_plt_entry (code); g_assert (plt_entry); mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target); return target; #else g_assert_not_reached (); return NULL; #endif } /** * init_plt: * * Initialize the PLT table of the AOT module. Called lazily when the first AOT * method in the module is loaded to avoid committing memory by writing to it. * LOCKING: Assumes the AOT lock is held. */ static void init_plt (MonoAotModule *amodule) { #ifndef MONO_CROSS_COMPILE #ifdef MONO_ARCH_AOT_SUPPORTED #ifdef __i386__ guint8 *buf = amodule->plt; #elif defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__) int i; gpointer plt_0; #endif gpointer tramp; if (amodule->plt_inited) return; tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL); #ifdef __i386__ /* Initialize the first PLT entry */ make_writable (amodule->plt, amodule->plt_end - amodule->plt); x86_jump_code (buf, tramp); #elif defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__) /* * Initialize the PLT entries in the GOT to point to the default targets. */ tramp = mono_create_ftnptr (mono_domain_get (), tramp); plt_0 = mono_create_ftnptr (mono_domain_get (), amodule->plt); /* The first entry points to the AOT trampoline */ ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base] = tramp; for (i = 1; i < amodule->info.plt_size; ++i) /* All the default entries point to the first entry */ ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = plt_0; #else g_assert_not_reached (); #endif amodule->plt_inited = TRUE; #endif #endif /* MONO_CROSS_COMPILE */ } /* * mono_aot_get_plt_entry: * * Return the address of the PLT entry called by the code at CODE if exists. */ guint8* mono_aot_get_plt_entry (guint8 *code) { MonoAotModule *aot_module = find_aot_module (code); #if defined(__arm__) || defined(__mono_ppc__) guint32 ins; #endif if (!aot_module) return NULL; #if defined(__i386__) || defined(__x86_64__) if (code [-5] == 0xe8) { guint32 disp = *(guint32*)(code - 4); guint8 *target = code + disp; if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end))) return target; } #elif defined(__arm__) ins = ((guint32*)(gpointer)code) [-1]; /* Should be a 'bl' */ if ((((ins >> 25) & 0x7) == 0x5) && (((ins >> 24) & 0x1) == 0x1)) { gint32 disp = ((gint32)ins) & 0xffffff; guint8 *target = code - 4 + 8 + (disp * 4); if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end))) return target; } #elif defined(__mono_ppc__) /* Should be a bl */ ins = ((guint32*)(gpointer)code) [-1]; if ((ins >> 26 == 18) && ((ins & 1) == 1) && ((ins & 2) == 0)) { gint32 disp = (((gint32)ins) >> 2) & 0xffffff; guint8 *target = code - 4 + (disp * 4); if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end))) return target; } #else g_assert_not_reached (); #endif return NULL; } /* * mono_aot_get_plt_info_offset: * * Return the PLT info offset belonging to the plt entry called by CODE. */ guint32 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code) { guint8 *plt_entry = mono_aot_get_plt_entry (code); g_assert (plt_entry); /* The offset is embedded inside the code after the plt entry */ #if defined(__i386__) return *(guint32*)(plt_entry + 5); #elif defined(__x86_64__) return *(guint32*)(plt_entry + 6); #elif defined(__arm__) /* The offset is stored as the 4th word of the plt entry */ return ((guint32*)plt_entry) [3]; #elif defined(__mono_ppc__) #ifdef PPC_USES_FUNCTION_DESCRIPTOR return ((guint32*)plt_entry) [8]; #else return ((guint32*)plt_entry) [6]; #endif #else g_assert_not_reached (); return 0; #endif } static gpointer mono_create_ftnptr_malloc (guint8 *code) { #ifdef PPC_USES_FUNCTION_DESCRIPTOR MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor)); ftnptr->code = code; ftnptr->toc = NULL; ftnptr->env = NULL; return ftnptr; #else return code; #endif } /* * load_function: * * Load the function named NAME from the aot image. */ static gpointer load_function (MonoAotModule *amodule, const char *name) { char *symbol; guint8 *p; int n_patches, pindex; MonoMemPool *mp; gpointer code; /* Load the code */ symbol = g_strdup_printf ("%s", name); find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code); g_free (symbol); if (!code) g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name); /* Load info */ symbol = g_strdup_printf ("%s_p", name); find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p); g_free (symbol); if (!p) /* Nothing to patch */ return code; p = amodule->blob + *(guint32*)p; /* Similar to mono_aot_load_method () */ n_patches = decode_value (p, &p); if (n_patches) { MonoJumpInfo *patches; guint32 *got_slots; mp = mono_mempool_new (); patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p); g_assert (patches); for (pindex = 0; pindex < n_patches; ++pindex) { MonoJumpInfo *ji = &patches [pindex]; gpointer target; if (amodule->got [got_slots [pindex]]) continue; /* * When this code is executed, the runtime may not be initalized yet, so * resolve the patch info by hand. */ if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) { if (!strcmp (ji->data.name, "mono_get_lmf_addr")) { target = mono_get_lmf_addr; } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) { target = mono_thread_force_interruption_checkpoint; } else if (!strcmp (ji->data.name, "mono_exception_from_token")) { target = mono_exception_from_token; } else if (!strcmp (ji->data.name, "mono_throw_exception")) { target = mono_get_throw_exception (); #ifdef __x86_64__ } else if (!strcmp (ji->data.name, "mono_amd64_throw_exception")) { target = mono_amd64_throw_exception; #endif #ifdef __x86_64__ } else if (!strcmp (ji->data.name, "mono_amd64_get_original_ip")) { target = mono_amd64_get_original_ip; #endif #ifdef __arm__ } else if (!strcmp (ji->data.name, "mono_arm_throw_exception")) { target = mono_arm_throw_exception; } else if (!strcmp (ji->data.name, "mono_arm_throw_exception_by_token")) { target = mono_arm_throw_exception_by_token; #endif #ifdef __mono_ppc__ } else if (!strcmp (ji->data.name, "mono_ppc_throw_exception")) { target = mono_ppc_throw_exception; #endif } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) { int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_")); target = (gpointer)mono_get_trampoline_func (tramp_type2); } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) { /* atoll is needed because the the offset is unsigned */ guint32 slot; int res; res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot); g_assert (res == 1); target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL); target = mono_create_ftnptr_malloc (target); } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) { target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL); target = mono_create_ftnptr_malloc (target); } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) { target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL); target = mono_create_ftnptr_malloc (target); } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) { target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL); target = mono_create_ftnptr_malloc (target); } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) { target = mono_thread_get_and_clear_pending_exception; } else { fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name); g_assert_not_reached (); target = NULL; } } else { /* Hopefully the code doesn't have patches which need method or * domain to be set. */ target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE); g_assert (target); } amodule->got [got_slots [pindex]] = target; } g_free (got_slots); mono_mempool_destroy (mp); } return code; } /* * Return the piece of code identified by NAME from the mscorlib AOT file. * On ppc64, this returns a function descriptor. */ gpointer mono_aot_get_named_code (const char *name) { MonoImage *image; MonoAotModule *amodule; image = mono_defaults.corlib; g_assert (image); amodule = image->aot_module; g_assert (amodule); return mono_create_ftnptr_malloc (load_function (amodule, name)); } /* Return a given kind of trampoline */ static gpointer get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size) { MonoAotModule *amodule; int index, tramp_size; MonoImage *image; /* Currently, we keep all trampolines in the mscorlib AOT image */ image = mono_defaults.corlib; g_assert (image); mono_aot_lock (); amodule = image->aot_module; g_assert (amodule); *out_amodule = amodule; if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]); index = amodule->trampoline_index [tramp_type] ++; mono_aot_unlock (); *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots); tramp_size = amodule->info.trampoline_size [tramp_type]; if (out_tramp_size) *out_tramp_size = tramp_size; return amodule->trampolines [tramp_type] + (index * tramp_size); } /* * Return a specific trampoline from the AOT file. */ gpointer mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len) { MonoAotModule *amodule; guint32 got_offset, tramp_size; guint8 *code, *tramp; static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM]; static gboolean inited; static guint32 num_trampolines; if (!inited) { mono_aot_lock (); if (!inited) { mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines); inited = TRUE; } mono_aot_unlock (); } num_trampolines ++; if (!generic_trampolines [tramp_type]) { char *symbol; symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type); generic_trampolines [tramp_type] = mono_aot_get_named_code (symbol); g_free (symbol); } tramp = generic_trampolines [tramp_type]; g_assert (tramp); code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size); amodule->got [got_offset] = tramp; amodule->got [got_offset + 1] = arg1; if (code_len) *code_len = tramp_size; return code; } gpointer mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr) { MonoAotModule *amodule; guint8 *code; guint32 got_offset; code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL); amodule->got [got_offset] = ctx; amodule->got [got_offset + 1] = addr; /* The caller expects an ftnptr */ return mono_create_ftnptr (mono_domain_get (), code); } gpointer mono_aot_get_unbox_trampoline (MonoMethod *method) { guint32 method_index = mono_metadata_token_index (method->token) - 1; MonoAotModule *amodule; char *symbol; gpointer code; if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) { guint32 index = find_extra_method (method, &amodule); g_assert (index != 0xffffff); symbol = g_strdup_printf ("ut_e_%d", index); } else { amodule = method->klass->image->aot_module; g_assert (amodule); symbol = g_strdup_printf ("ut_%d", method_index); } code = load_function (amodule, symbol); g_free (symbol); /* The caller expects an ftnptr */ return mono_create_ftnptr (mono_domain_get (), code); } gpointer mono_aot_get_lazy_fetch_trampoline (guint32 slot) { char *symbol; gpointer code; symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", slot); code = load_function (mono_defaults.corlib->aot_module, symbol); g_free (symbol); /* The caller expects an ftnptr */ return mono_create_ftnptr (mono_domain_get (), code); } gpointer mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp) { guint32 got_offset; gpointer code; gpointer *buf; int i; MonoAotModule *amodule; code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL); /* Save the entries into an array */ buf = mono_domain_alloc (domain, (count + 1) * 2 * sizeof (gpointer)); for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; g_assert (item->key); /* FIXME: */ g_assert (!item->has_target_code); buf [(i * 2)] = item->key; buf [(i * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]); } buf [(count * 2)] = NULL; buf [(count * 2) + 1] = fail_tramp; amodule->got [got_offset] = buf; return code; } /* * mono_aot_set_make_unreadable: * * Set whenever to make all mmaped memory unreadable. In conjuction with a * SIGSEGV handler, this is useful to find out which pages the runtime tries to read. */ void mono_aot_set_make_unreadable (gboolean unreadable) { static int inited; make_unreadable = unreadable; if (make_unreadable && !inited) { mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults); } } typedef struct { MonoAotModule *module; guint8 *ptr; } FindMapUserData; static void find_map (gpointer key, gpointer value, gpointer user_data) { MonoAotModule *module = (MonoAotModule*)value; FindMapUserData *data = (FindMapUserData*)user_data; if (!data->module) if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end)) data->module = module; } static MonoAotModule* find_module_for_addr (void *ptr) { FindMapUserData data; if (!make_unreadable) return NULL; data.module = NULL; data.ptr = (guint8*)ptr; mono_aot_lock (); g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data); mono_aot_unlock (); return data.module; } /* * mono_aot_is_pagefault: * * Should be called from a SIGSEGV signal handler to find out whenever @ptr is * within memory allocated by this module. */ gboolean mono_aot_is_pagefault (void *ptr) { if (!make_unreadable) return FALSE; /* * Not signal safe, but SIGSEGV's are synchronous, and * this is only turned on by a MONO_DEBUG option. */ return find_module_for_addr (ptr) != NULL; } /* * mono_aot_handle_pagefault: * * Handle a pagefault caused by an unreadable page by making it readable again. */ void mono_aot_handle_pagefault (void *ptr) { #ifndef PLATFORM_WIN32 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ()); int res; mono_aot_lock (); res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC); g_assert (res == 0); n_pagefaults ++; mono_aot_unlock (); #endif } #else /* AOT disabled */ void mono_aot_init (void) { } gpointer mono_aot_get_method (MonoDomain *domain, MonoMethod *method) { return NULL; } gboolean mono_aot_is_got_entry (guint8 *code, guint8 *addr) { return FALSE; } gboolean mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res) { return FALSE; } gboolean mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass) { return FALSE; } MonoJitInfo * mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr) { return NULL; } gpointer mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token) { return NULL; } guint8* mono_aot_get_plt_entry (guint8 *code) { return NULL; } gpointer mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code) { return NULL; } void mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr) { } gpointer mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot) { return NULL; } guint32 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code) { g_assert_not_reached (); return 0; } gpointer mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len) { g_assert_not_reached (); return NULL; } gpointer mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr) { g_assert_not_reached (); return NULL; } gpointer mono_aot_get_named_code (const char *name) { g_assert_not_reached (); return NULL; } gpointer mono_aot_get_unbox_trampoline (MonoMethod *method) { g_assert_not_reached (); return NULL; } gpointer mono_aot_get_lazy_fetch_trampoline (guint32 slot) { g_assert_not_reached (); return NULL; } gpointer mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp) { g_assert_not_reached (); return NULL; } guint8* mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len) { g_assert_not_reached (); return NULL; } #endif