Significant disambiguation between host and target. (#10969)
[mono-project.git] / mono / mini / aot-runtime.c
blobd14f2f881ad89844b97b108e3697c92c37ab7c39
1 /**
2 * \file
3 * mono Ahead of Time compiler
5 * Author:
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
9 * (C) 2002 Ximian, Inc.
10 * Copyright 2003-2011 Novell, Inc.
11 * Copyright 2011 Xamarin, Inc.
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include "config.h"
16 #include <sys/types.h>
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #include <fcntl.h>
21 #include <string.h>
22 #ifdef HAVE_SYS_MMAN_H
23 #include <sys/mman.h>
24 #endif
26 #if HOST_WIN32
27 #include <winsock2.h>
28 #include <windows.h>
29 #endif
31 #ifdef HAVE_EXECINFO_H
32 #include <execinfo.h>
33 #endif
35 #include <errno.h>
36 #include <sys/stat.h>
38 #ifdef HAVE_SYS_WAIT_H
39 #include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
40 #endif
42 #include <mono/metadata/abi-details.h>
43 #include <mono/metadata/tabledefs.h>
44 #include <mono/metadata/class.h>
45 #include <mono/metadata/object.h>
46 #include <mono/metadata/tokentype.h>
47 #include <mono/metadata/appdomain.h>
48 #include <mono/metadata/debug-helpers.h>
49 #include <mono/metadata/assembly.h>
50 #include <mono/metadata/assembly-internals.h>
51 #include <mono/metadata/metadata-internals.h>
52 #include <mono/metadata/exception-internals.h>
53 #include <mono/metadata/marshal.h>
54 #include <mono/metadata/gc-internals.h>
55 #include <mono/metadata/threads-types.h>
56 #include <mono/metadata/mono-endian.h>
57 #include <mono/utils/mono-logger-internals.h>
58 #include <mono/utils/mono-mmap.h>
59 #include <mono/utils/mono-compiler.h>
60 #include <mono/utils/mono-counters.h>
61 #include <mono/utils/mono-digest.h>
62 #include <mono/utils/mono-threads-coop.h>
64 #include "mini.h"
65 #include "seq-points.h"
66 #include "version.h"
67 #include "debugger-agent.h"
68 #include "aot-compiler.h"
69 #include "aot-runtime.h"
70 #include "jit-icalls.h"
71 #include "mini-runtime.h"
73 #ifndef DISABLE_AOT
75 #ifdef TARGET_OSX
76 #define ENABLE_AOT_CACHE
77 #endif
79 /* Number of got entries shared between the JIT and LLVM GOT */
80 #define N_COMMON_GOT_ENTRIES 10
82 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
84 typedef struct {
85 int method_index;
86 MonoJitInfo *jinfo;
87 } JitInfoMap;
89 typedef struct MonoAotModule {
90 char *aot_name;
91 /* Pointer to the Global Offset Table */
92 gpointer *got;
93 gpointer *llvm_got;
94 gpointer *shared_got;
95 GHashTable *name_cache;
96 GHashTable *extra_methods;
97 /* Maps methods to their code */
98 GHashTable *method_to_code;
99 /* Maps pointers into the method info to the methods themselves */
100 GHashTable *method_ref_to_method;
101 MonoAssemblyName *image_names;
102 char **image_guids;
103 MonoAssembly *assembly;
104 MonoImage **image_table;
105 guint32 image_table_len;
106 gboolean out_of_date;
107 gboolean plt_inited;
108 gboolean got_initializing;
109 guint8 *mem_begin;
110 guint8 *mem_end;
111 guint8 *jit_code_start;
112 guint8 *jit_code_end;
113 guint8 *llvm_code_start;
114 guint8 *llvm_code_end;
115 guint8 *plt;
116 guint8 *plt_end;
117 guint8 *blob;
118 gpointer weak_field_indexes;
119 /* Maps method indexes to their code */
120 gpointer *methods;
121 /* Sorted array of method addresses */
122 gpointer *sorted_methods;
123 /* Method indexes for each method in sorted_methods */
124 int *sorted_method_indexes;
125 /* The length of the two tables above */
126 int sorted_methods_len;
127 guint32 *method_info_offsets;
128 guint32 *ex_info_offsets;
129 guint32 *class_info_offsets;
130 guint32 *got_info_offsets;
131 guint32 *llvm_got_info_offsets;
132 guint32 *methods_loaded;
133 guint16 *class_name_table;
134 guint32 *extra_method_table;
135 guint32 *extra_method_info_offsets;
136 guint32 *unbox_trampolines;
137 guint32 *unbox_trampolines_end;
138 guint32 *unbox_trampoline_addresses;
139 guint8 *unwind_info;
141 /* Points to the mono EH data created by LLVM */
142 guint8 *mono_eh_frame;
144 /* Points to the data tables if MONO_AOT_FILE_FLAG_SEPARATE_DATA is set */
145 gpointer tables [MONO_AOT_TABLE_NUM];
146 /* Points to the trampolines */
147 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
148 /* The first unused trampoline of each kind */
149 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
151 gboolean use_page_trampolines;
153 MonoAotFileInfo info;
155 gpointer *globals;
156 MonoDl *sofile;
158 JitInfoMap *async_jit_info_table;
159 mono_mutex_t mutex;
160 } MonoAotModule;
162 typedef struct {
163 void *next;
164 unsigned char *trampolines;
165 unsigned char *trampolines_end;
166 } TrampolinePage;
168 static GHashTable *aot_modules;
169 #define mono_aot_lock() mono_os_mutex_lock (&aot_mutex)
170 #define mono_aot_unlock() mono_os_mutex_unlock (&aot_mutex)
171 static mono_mutex_t aot_mutex;
174 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
175 * AOT modules registered by mono_aot_register_module ().
177 static GHashTable *static_aot_modules;
179 * Same as above, but tracks module that must be loaded before others are
180 * This allows us to have a "container" module which contains resources for
181 * other modules. Since it doesn't provide methods for a managed assembly,
182 * and it needs to be fully loaded by the time the other code needs it, it
183 * must be eagerly loaded before other modules.
185 static char *container_assm_name = NULL;
186 static MonoAotModule *container_amodule = NULL;
189 * Maps MonoJitInfo* to the aot module they belong to, this can be different
190 * from ji->method->klass->image's aot module for generic instances.
192 static GHashTable *ji_to_amodule;
195 * Whenever to AOT compile loaded assemblies on demand and store them in
196 * a cache.
198 static gboolean enable_aot_cache = FALSE;
200 static gboolean mscorlib_aot_loaded;
202 /* For debugging */
203 static gint32 mono_last_aot_method = -1;
205 static gboolean make_unreadable = FALSE;
206 static guint32 name_table_accesses = 0;
207 static guint32 n_pagefaults = 0;
209 /* Used to speed-up find_aot_module () */
210 static gsize aot_code_low_addr = (gssize)-1;
211 static gsize aot_code_high_addr = 0;
213 /* Stats */
214 static gint32 async_jit_info_size;
216 static GHashTable *aot_jit_icall_hash;
218 #ifdef MONOTOUCH
219 #define USE_PAGE_TRAMPOLINES (mono_defaults.corlib->aot_module->use_page_trampolines)
220 #else
221 #define USE_PAGE_TRAMPOLINES 0
222 #endif
224 #define mono_aot_page_lock() mono_os_mutex_lock (&aot_page_mutex)
225 #define mono_aot_page_unlock() mono_os_mutex_unlock (&aot_page_mutex)
226 static mono_mutex_t aot_page_mutex;
228 static MonoAotModule *mscorlib_aot_module;
230 /* Embedding API hooks to load the AOT data for AOT images compiled with MONO_AOT_FILE_FLAG_SEPARATE_DATA */
231 static MonoLoadAotDataFunc aot_data_load_func;
232 static MonoFreeAotDataFunc aot_data_free_func;
233 static gpointer aot_data_func_user_data;
235 static void
236 init_plt (MonoAotModule *info);
238 static void
239 compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end);
241 static gboolean
242 init_method (MonoAotModule *amodule, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoGenericContext *context, MonoError *error);
244 static MonoJumpInfo*
245 decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets);
247 static inline void
248 amodule_lock (MonoAotModule *amodule)
250 mono_os_mutex_lock (&amodule->mutex);
253 static inline void
254 amodule_unlock (MonoAotModule *amodule)
256 mono_os_mutex_unlock (&amodule->mutex);
260 * load_image:
262 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
263 * found, and sets @error for what happened
265 static MonoImage *
266 load_image (MonoAotModule *amodule, int index, MonoError *error)
268 MonoAssembly *assembly;
269 MonoImageOpenStatus status;
271 g_assert (index < amodule->image_table_len);
273 error_init (error);
275 if (amodule->image_table [index])
276 return amodule->image_table [index];
277 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s wants to load image %d: %s", amodule->aot_name, index, amodule->image_names[index].name);
278 if (amodule->out_of_date) {
279 mono_error_set_bad_image_by_name (error, amodule->aot_name, "Image out of date");
280 return NULL;
284 * LoadFile allows loading more than one assembly with the same name.
285 * That means that just calling mono_assembly_load is unlikely to find
286 * the correct assembly (it'll just return the first one loaded). But
287 * we shouldn't hardcode the full assembly filepath into the AOT image,
288 * so it's not obvious that we can call mono_assembly_open_predicate.
290 * In the JIT, an assembly opened with LoadFile is supposed to only
291 * refer to already-loaded assemblies (or to GAC & MONO_PATH)
292 * assemblies - so nothing new should be loading. And for the
293 * LoadFile'd assembly itself, we can check if the name and guid of the
294 * current AOT module matches the wanted name and guid and just return
295 * the AOT module's assembly.
297 if (mono_asmctx_get_kind (&amodule->assembly->context) == MONO_ASMCTX_INDIVIDUAL &&
298 !strcmp (amodule->assembly->image->guid, amodule->image_guids [index]) &&
299 mono_assembly_names_equal (&amodule->image_names [index], &amodule->assembly->aname))
300 assembly = amodule->assembly;
301 else
302 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
303 if (!assembly) {
304 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable because dependency %s is not found.", amodule->aot_name, amodule->image_names [index].name);
305 mono_error_set_bad_image_by_name (error, amodule->aot_name, "module is unusable because dependency %s is not found (error %d).\n", amodule->image_names [index].name, status);
306 amodule->out_of_date = TRUE;
307 return NULL;
310 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
311 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s').", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
312 mono_error_set_bad_image_by_name (error, amodule->aot_name, "module is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s').", amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
313 amodule->out_of_date = TRUE;
314 return NULL;
317 amodule->image_table [index] = assembly->image;
318 return assembly->image;
321 static inline gint32
322 decode_value (guint8 *ptr, guint8 **rptr)
324 guint8 b = *ptr;
325 gint32 len;
327 if ((b & 0x80) == 0){
328 len = b;
329 ++ptr;
330 } else if ((b & 0x40) == 0){
331 len = ((b & 0x3f) << 8 | ptr [1]);
332 ptr += 2;
333 } else if (b != 0xff) {
334 len = ((b & 0x1f) << 24) |
335 (ptr [1] << 16) |
336 (ptr [2] << 8) |
337 ptr [3];
338 ptr += 4;
340 else {
341 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
342 ptr += 5;
344 if (rptr)
345 *rptr = ptr;
347 //printf ("DECODE: %d.\n", len);
348 return len;
352 * mono_aot_get_offset:
354 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
355 * entry.
357 static guint32
358 mono_aot_get_offset (guint32 *table, int index)
360 int i, group, ngroups, index_entry_size;
361 int start_offset, offset, group_size;
362 guint8 *data_start, *p;
363 guint32 *index32 = NULL;
364 guint16 *index16 = NULL;
366 /* noffsets = table [0]; */
367 group_size = table [1];
368 ngroups = table [2];
369 index_entry_size = table [3];
370 group = index / group_size;
372 if (index_entry_size == 2) {
373 index16 = (guint16*)&table [4];
374 data_start = (guint8*)&index16 [ngroups];
375 p = data_start + index16 [group];
376 } else {
377 index32 = (guint32*)&table [4];
378 data_start = (guint8*)&index32 [ngroups];
379 p = data_start + index32 [group];
382 /* offset will contain the value of offsets [group * group_size] */
383 offset = start_offset = decode_value (p, &p);
384 for (i = group * group_size + 1; i <= index; ++i) {
385 offset += decode_value (p, &p);
388 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
390 return offset;
393 static MonoMethod*
394 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
396 static MonoClass*
397 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
399 static MonoType*
400 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
402 static MonoGenericInst*
403 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
405 int type_argc, i;
406 MonoType **type_argv;
407 MonoGenericInst *inst;
408 guint8 *p = buf;
410 error_init (error);
411 type_argc = decode_value (p, &p);
412 type_argv = g_new0 (MonoType*, type_argc);
414 for (i = 0; i < type_argc; ++i) {
415 MonoClass *pclass = decode_klass_ref (module, p, &p, error);
416 if (!pclass) {
417 g_free (type_argv);
418 return NULL;
420 type_argv [i] = m_class_get_byval_arg (pclass);
423 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
424 g_free (type_argv);
426 *endbuf = p;
428 return inst;
431 static gboolean
432 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf, MonoError *error)
434 guint8 *p = buf;
435 guint8 *p2;
436 int argc;
437 error_init (error);
439 p2 = p;
440 argc = decode_value (p, &p);
441 if (argc) {
442 p = p2;
443 ctx->class_inst = decode_generic_inst (module, p, &p, error);
444 if (!ctx->class_inst)
445 return FALSE;
447 p2 = p;
448 argc = decode_value (p, &p);
449 if (argc) {
450 p = p2;
451 ctx->method_inst = decode_generic_inst (module, p, &p, error);
452 if (!ctx->method_inst)
453 return FALSE;
456 *endbuf = p;
457 return TRUE;
460 static MonoClass*
461 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
463 MonoImage *image;
464 MonoClass *klass = NULL, *eklass;
465 guint32 token, rank, idx;
466 guint8 *p = buf;
467 int reftype;
469 error_init (error);
470 reftype = decode_value (p, &p);
471 if (reftype == 0) {
472 *endbuf = p;
473 mono_error_set_bad_image_by_name (error, module->aot_name, "Decoding a null class ref");
474 return NULL;
477 switch (reftype) {
478 case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
479 idx = decode_value (p, &p);
480 image = load_image (module, 0, error);
481 if (!image)
482 return NULL;
483 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
484 break;
485 case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
486 idx = decode_value (p, &p);
487 image = load_image (module, decode_value (p, &p), error);
488 if (!image)
489 return NULL;
490 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
491 break;
492 case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
493 token = decode_value (p, &p);
494 image = module->assembly->image;
495 if (!image) {
496 mono_error_set_bad_image_by_name (error, module->aot_name, "No image associated with the aot module");
497 return NULL;
499 klass = mono_class_get_checked (image, token, error);
500 break;
501 case MONO_AOT_TYPEREF_GINST: {
502 MonoClass *gclass;
503 MonoGenericContext ctx;
504 MonoType *type;
506 gclass = decode_klass_ref (module, p, &p, error);
507 if (!gclass)
508 return NULL;
509 g_assert (mono_class_is_gtd (gclass));
511 memset (&ctx, 0, sizeof (ctx));
512 ctx.class_inst = decode_generic_inst (module, p, &p, error);
513 if (!ctx.class_inst)
514 return NULL;
515 type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
516 if (!type)
517 return NULL;
518 klass = mono_class_from_mono_type (type);
519 mono_metadata_free_type (type);
520 break;
522 case MONO_AOT_TYPEREF_VAR: {
523 MonoType *t = NULL;
524 MonoGenericContainer *container = NULL;
525 gboolean has_constraint = decode_value (p, &p);
527 if (has_constraint) {
528 MonoClass *par_klass;
529 MonoType *gshared_constraint;
531 gshared_constraint = decode_type (module, p, &p, error);
532 if (!gshared_constraint)
533 return NULL;
535 par_klass = decode_klass_ref (module, p, &p, error);
536 if (!par_klass)
537 return NULL;
539 t = mini_get_shared_gparam (m_class_get_byval_arg (par_klass), gshared_constraint);
540 mono_metadata_free_type (gshared_constraint);
541 klass = mono_class_from_mono_type (t);
542 } else {
543 int type = decode_value (p, &p);
544 int num = decode_value (p, &p);
545 gboolean is_not_anonymous = decode_value (p, &p);
547 if (is_not_anonymous) {
548 gboolean is_method = decode_value (p, &p);
550 if (is_method) {
551 MonoMethod *method_def;
552 g_assert (type == MONO_TYPE_MVAR);
553 method_def = decode_resolve_method_ref (module, p, &p, error);
554 if (!method_def)
555 return NULL;
557 container = mono_method_get_generic_container (method_def);
558 } else {
559 MonoClass *class_def;
560 g_assert (type == MONO_TYPE_VAR);
561 class_def = decode_klass_ref (module, p, &p, error);
562 if (!class_def)
563 return NULL;
565 container = mono_class_try_get_generic_container (class_def); //FIXME is this a case for a try_get?
567 } else {
568 // We didn't decode is_method, so we have to infer it from type enum.
569 container = mono_get_anonymous_container_for_image (module->assembly->image, type == MONO_TYPE_MVAR);
572 t = g_new0 (MonoType, 1);
573 t->type = (MonoTypeEnum)type;
574 if (is_not_anonymous) {
575 t->data.generic_param = mono_generic_container_get_param (container, num);
576 } else {
577 /* Anonymous */
578 MonoGenericParam *par = mono_metadata_create_anon_gparam (module->assembly->image, num, type == MONO_TYPE_MVAR);
579 t->data.generic_param = par;
580 // FIXME: maybe do this for all anon gparams?
581 ((MonoGenericParamFull*)par)->info.name = mono_make_generic_name_string (module->assembly->image, num);
583 // FIXME: Maybe use types directly to avoid
584 // the overhead of creating MonoClass-es
585 klass = mono_class_from_mono_type (t);
587 g_free (t);
589 break;
591 case MONO_AOT_TYPEREF_ARRAY:
592 /* Array */
593 rank = decode_value (p, &p);
594 eklass = decode_klass_ref (module, p, &p, error);
595 if (!eklass)
596 return NULL;
597 klass = mono_class_create_array (eklass, rank);
598 break;
599 case MONO_AOT_TYPEREF_PTR: {
600 MonoType *t;
602 t = decode_type (module, p, &p, error);
603 if (!t)
604 return NULL;
605 klass = mono_class_from_mono_type (t);
606 g_free (t);
607 break;
609 case MONO_AOT_TYPEREF_BLOB_INDEX: {
610 guint32 offset = decode_value (p, &p);
611 guint8 *p2;
613 p2 = module->blob + offset;
614 klass = decode_klass_ref (module, p2, &p2, error);
615 break;
617 default:
618 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid klass reftype %d", reftype);
620 //g_assert (klass);
621 //printf ("BLA: %s\n", mono_type_full_name (m_class_get_byval_arg (klass)));
622 *endbuf = p;
623 return klass;
626 static MonoClassField*
627 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
629 ERROR_DECL (error);
630 MonoClass *klass = decode_klass_ref (module, buf, &buf, error);
631 guint32 token;
632 guint8 *p = buf;
634 if (!klass) {
635 mono_error_cleanup (error); /* FIXME don't swallow the error */
636 return NULL;
639 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
641 *endbuf = p;
643 return mono_class_get_field (klass, token);
647 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
648 * memory.
650 static MonoType*
651 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
653 guint8 *p = buf;
654 MonoType *t;
656 if (*p == MONO_TYPE_CMOD_REQD) {
657 ++p;
659 int count = decode_value (p, &p);
661 t = (MonoType*)g_malloc0 (mono_sizeof_type_with_mods (count));
662 t->has_cmods = TRUE;
664 MonoCustomModContainer *cm = mono_type_get_cmods (t);
665 int iindex = decode_value (p, &p);
666 cm->image = load_image (module, iindex, error);
667 if (!cm->image) {
668 g_free (t);
669 return NULL;
671 cm->count = count;
672 for (int i = 0; i < cm->count; ++i) {
673 cm->modifiers [i].required = decode_value (p, &p);
674 cm->modifiers [i].token = decode_value (p, &p);
676 } else {
677 t = (MonoType *) g_malloc0 (sizeof (MonoType));
680 while (TRUE) {
681 if (*p == MONO_TYPE_PINNED) {
682 t->pinned = TRUE;
683 ++p;
684 } else if (*p == MONO_TYPE_BYREF) {
685 t->byref = TRUE;
686 ++p;
687 } else {
688 break;
692 t->type = (MonoTypeEnum)*p;
693 ++p;
695 switch (t->type) {
696 case MONO_TYPE_VOID:
697 case MONO_TYPE_BOOLEAN:
698 case MONO_TYPE_CHAR:
699 case MONO_TYPE_I1:
700 case MONO_TYPE_U1:
701 case MONO_TYPE_I2:
702 case MONO_TYPE_U2:
703 case MONO_TYPE_I4:
704 case MONO_TYPE_U4:
705 case MONO_TYPE_I8:
706 case MONO_TYPE_U8:
707 case MONO_TYPE_R4:
708 case MONO_TYPE_R8:
709 case MONO_TYPE_I:
710 case MONO_TYPE_U:
711 case MONO_TYPE_STRING:
712 case MONO_TYPE_OBJECT:
713 case MONO_TYPE_TYPEDBYREF:
714 break;
715 case MONO_TYPE_VALUETYPE:
716 case MONO_TYPE_CLASS:
717 t->data.klass = decode_klass_ref (module, p, &p, error);
718 if (!t->data.klass)
719 goto fail;
720 break;
721 case MONO_TYPE_SZARRAY:
722 t->data.klass = decode_klass_ref (module, p, &p, error);
724 if (!t->data.klass)
725 goto fail;
726 break;
727 case MONO_TYPE_PTR:
728 t->data.type = decode_type (module, p, &p, error);
729 if (!t->data.type)
730 goto fail;
731 break;
732 case MONO_TYPE_GENERICINST: {
733 MonoClass *gclass;
734 MonoGenericContext ctx;
735 MonoType *type;
736 MonoClass *klass;
738 gclass = decode_klass_ref (module, p, &p, error);
739 if (!gclass)
740 goto fail;
741 g_assert (mono_class_is_gtd (gclass));
743 memset (&ctx, 0, sizeof (ctx));
744 ctx.class_inst = decode_generic_inst (module, p, &p, error);
745 if (!ctx.class_inst)
746 goto fail;
747 type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
748 if (!type)
749 goto fail;
750 klass = mono_class_from_mono_type (type);
751 t->data.generic_class = mono_class_get_generic_class (klass);
752 break;
754 case MONO_TYPE_ARRAY: {
755 MonoArrayType *array;
756 int i;
758 // FIXME: memory management
759 array = g_new0 (MonoArrayType, 1);
760 array->eklass = decode_klass_ref (module, p, &p, error);
761 if (!array->eklass)
762 goto fail;
763 array->rank = decode_value (p, &p);
764 array->numsizes = decode_value (p, &p);
766 if (array->numsizes)
767 array->sizes = (int *)g_malloc0 (sizeof (int) * array->numsizes);
768 for (i = 0; i < array->numsizes; ++i)
769 array->sizes [i] = decode_value (p, &p);
771 array->numlobounds = decode_value (p, &p);
772 if (array->numlobounds)
773 array->lobounds = (int *)g_malloc0 (sizeof (int) * array->numlobounds);
774 for (i = 0; i < array->numlobounds; ++i)
775 array->lobounds [i] = decode_value (p, &p);
776 t->data.array = array;
777 break;
779 case MONO_TYPE_VAR:
780 case MONO_TYPE_MVAR: {
781 MonoClass *klass = decode_klass_ref (module, p, &p, error);
782 if (!klass)
783 goto fail;
784 t->data.generic_param = m_class_get_byval_arg (klass)->data.generic_param;
785 break;
787 default:
788 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid encoded type %d", t->type);
789 goto fail;
792 *endbuf = p;
794 return t;
795 fail:
796 g_free (t);
797 return NULL;
800 // FIXME: Error handling, memory management
802 static MonoMethodSignature*
803 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
805 ERROR_DECL (error);
806 MonoMethodSignature *sig;
807 guint32 flags;
808 int i, gen_param_count = 0, param_count, call_conv;
809 guint8 *p = buf;
810 gboolean hasthis, explicit_this, has_gen_params;
812 flags = *p;
813 p ++;
814 has_gen_params = (flags & 0x10) != 0;
815 hasthis = (flags & 0x20) != 0;
816 explicit_this = (flags & 0x40) != 0;
817 call_conv = flags & 0x0F;
819 if (has_gen_params)
820 gen_param_count = decode_value (p, &p);
821 param_count = decode_value (p, &p);
822 if (target && param_count != target->param_count)
823 return NULL;
824 sig = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
825 sig->param_count = param_count;
826 sig->sentinelpos = -1;
827 sig->hasthis = hasthis;
828 sig->explicit_this = explicit_this;
829 sig->call_convention = call_conv;
830 sig->generic_param_count = gen_param_count;
831 sig->ret = decode_type (module, p, &p, error);
832 if (!sig->ret)
833 goto fail;
834 for (i = 0; i < param_count; ++i) {
835 if (*p == MONO_TYPE_SENTINEL) {
836 g_assert (sig->call_convention == MONO_CALL_VARARG);
837 sig->sentinelpos = i;
838 p ++;
840 sig->params [i] = decode_type (module, p, &p, error);
841 if (!sig->params [i])
842 goto fail;
845 if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
846 sig->sentinelpos = sig->param_count;
848 *endbuf = p;
850 return sig;
851 fail:
852 mono_error_cleanup (error); /* FIXME don't swallow the error */
853 g_free (sig);
854 return NULL;
857 static MonoMethodSignature*
858 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
860 return decode_signature_with_target (module, NULL, buf, endbuf);
863 static gboolean
864 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
866 MonoMethodSignature *sig;
867 gboolean res;
868 guint8 *p = buf;
870 sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
871 res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
872 g_free (sig);
873 *endbuf = p;
874 return res;
877 /* Stores information returned by decode_method_ref () */
878 typedef struct {
879 MonoImage *image;
880 guint32 token;
881 MonoMethod *method;
882 gboolean no_aot_trampoline;
883 } MethodRef;
886 * decode_method_ref_with_target:
888 * Decode a method reference, storing the image/token into a MethodRef structure.
889 * This avoids loading metadata for the method if the caller does not need it. If the method has
890 * no token, then it is loaded from metadata and ref->method is set to the method instance.
891 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
892 * couldn't resolve to TARGET, and return FALSE.
893 * There are some kinds of method references which only support a non-null TARGET.
894 * This means that its not possible to decode this into a method, only to check
895 * that the method reference matches a given method. This is normally not a problem
896 * as these wrappers only occur in the extra_methods table, where we already have
897 * a method we want to lookup.
899 * If there was a decoding error, we return FALSE and set @error
901 static gboolean
902 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
904 guint32 image_index, value;
905 MonoImage *image = NULL;
906 guint8 *p = buf;
908 memset (ref, 0, sizeof (MethodRef));
909 error_init (error);
911 value = decode_value (p, &p);
912 image_index = value >> 24;
914 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
915 ref->no_aot_trampoline = TRUE;
916 value = decode_value (p, &p);
917 image_index = value >> 24;
920 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
921 if (target && target->wrapper_type) {
922 return FALSE;
926 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
927 WrapperInfo *info;
928 guint32 wrapper_type;
930 wrapper_type = decode_value (p, &p);
932 if (target && target->wrapper_type != wrapper_type)
933 return FALSE;
935 /* Doesn't matter */
936 image = mono_defaults.corlib;
938 switch (wrapper_type) {
939 #ifndef DISABLE_REMOTING
940 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
941 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
942 if (!m)
943 return FALSE;
944 mono_class_init (m->klass);
945 if (mono_aot_only)
946 ref->method = m;
947 else {
948 ref->method = mono_marshal_get_remoting_invoke_with_check (m, error);
949 return_val_if_nok (error, FALSE);
951 break;
953 case MONO_WRAPPER_PROXY_ISINST: {
954 MonoClass *klass = decode_klass_ref (module, p, &p, error);
955 if (!klass)
956 return FALSE;
957 ref->method = mono_marshal_get_proxy_cancast (klass);
958 break;
960 case MONO_WRAPPER_LDFLD:
961 case MONO_WRAPPER_LDFLDA:
962 case MONO_WRAPPER_STFLD: {
963 MonoClass *klass = decode_klass_ref (module, p, &p, error);
964 if (!klass)
965 return FALSE;
966 MonoType *type = m_class_get_byval_arg (klass);
967 if (wrapper_type == MONO_WRAPPER_LDFLD)
968 ref->method = mono_marshal_get_ldfld_wrapper (type);
969 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
970 ref->method = mono_marshal_get_ldflda_wrapper (type);
971 else if (wrapper_type == MONO_WRAPPER_STFLD)
972 ref->method = mono_marshal_get_stfld_wrapper (type);
973 else {
974 mono_error_set_bad_image_by_name (error, module->aot_name, "Unknown AOT wrapper type %d", wrapper_type);
975 return FALSE;
977 break;
979 #endif
980 case MONO_WRAPPER_ALLOC: {
981 int atype = decode_value (p, &p);
982 ManagedAllocatorVariant variant =
983 mono_profiler_allocations_enabled () ?
984 MANAGED_ALLOCATOR_PROFILER : MANAGED_ALLOCATOR_REGULAR;
986 ref->method = mono_gc_get_managed_allocator_by_type (atype, variant);
987 /* Try to fallback to the slow path version */
988 if (!ref->method)
989 ref->method = mono_gc_get_managed_allocator_by_type (atype, MANAGED_ALLOCATOR_SLOW_PATH);
990 if (!ref->method) {
991 mono_error_set_bad_image_by_name (error, module->aot_name, "Error: No managed allocator, but we need one for AOT.\nAre you using non-standard GC options?\n");
992 return FALSE;
994 break;
996 case MONO_WRAPPER_WRITE_BARRIER: {
997 ref->method = mono_gc_get_write_barrier ();
998 break;
1000 case MONO_WRAPPER_STELEMREF: {
1001 int subtype = decode_value (p, &p);
1003 if (subtype == WRAPPER_SUBTYPE_NONE) {
1004 ref->method = mono_marshal_get_stelemref ();
1005 } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
1006 int kind;
1008 kind = decode_value (p, &p);
1010 /* Can't decode this */
1011 if (!target)
1012 return FALSE;
1013 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
1014 info = mono_marshal_get_wrapper_info (target);
1016 g_assert (info);
1017 if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
1018 ref->method = target;
1019 else
1020 return FALSE;
1021 } else {
1022 return FALSE;
1024 } else {
1025 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid STELEMREF subtype %d", subtype);
1026 return FALSE;
1028 break;
1030 case MONO_WRAPPER_SYNCHRONIZED: {
1031 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1032 if (!m)
1033 return FALSE;
1034 ref->method = mono_marshal_get_synchronized_wrapper (m);
1035 break;
1037 case MONO_WRAPPER_UNKNOWN: {
1038 int subtype = decode_value (p, &p);
1040 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
1041 MonoClass *klass = decode_klass_ref (module, p, &p, error);
1042 if (!klass)
1043 return FALSE;
1045 if (!target)
1046 return FALSE;
1047 if (klass != target->klass)
1048 return FALSE;
1050 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
1051 if (strcmp (target->name, "PtrToStructure"))
1052 return FALSE;
1053 ref->method = mono_marshal_get_ptr_to_struct (klass);
1054 } else {
1055 if (strcmp (target->name, "StructureToPtr"))
1056 return FALSE;
1057 ref->method = mono_marshal_get_struct_to_ptr (klass);
1059 } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
1060 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1061 if (!m)
1062 return FALSE;
1063 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
1064 } else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
1065 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1066 if (!m)
1067 return FALSE;
1068 ref->method = mono_marshal_get_array_accessor_wrapper (m);
1069 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
1070 ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
1071 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
1072 ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
1073 } else if (subtype == WRAPPER_SUBTYPE_INTERP_IN) {
1074 MonoMethodSignature *sig = decode_signature (module, p, &p);
1075 if (!sig)
1076 return FALSE;
1077 ref->method = mini_get_interp_in_wrapper (sig);
1078 } else if (subtype == WRAPPER_SUBTYPE_INTERP_LMF) {
1079 ref->method = mini_get_interp_lmf_wrapper ();
1080 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
1081 MonoMethodSignature *sig = decode_signature (module, p, &p);
1082 if (!sig)
1083 return FALSE;
1084 ref->method = mini_get_gsharedvt_in_sig_wrapper (sig);
1085 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
1086 MonoMethodSignature *sig = decode_signature (module, p, &p);
1087 if (!sig)
1088 return FALSE;
1089 ref->method = mini_get_gsharedvt_out_sig_wrapper (sig);
1090 } else {
1091 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid UNKNOWN wrapper subtype %d", subtype);
1092 return FALSE;
1094 break;
1096 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
1097 int subtype = decode_value (p, &p);
1099 if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
1100 int rank = decode_value (p, &p);
1101 int elem_size = decode_value (p, &p);
1103 ref->method = mono_marshal_get_array_address (rank, elem_size);
1104 } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
1105 MonoMethod *m;
1107 m = decode_resolve_method_ref (module, p, &p, error);
1108 if (!m)
1109 return FALSE;
1111 if (!target)
1112 return FALSE;
1113 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
1115 info = mono_marshal_get_wrapper_info (target);
1116 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
1117 ref->method = target;
1118 else
1119 return FALSE;
1121 break;
1123 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
1124 MonoMethod *m;
1125 int subtype = decode_value (p, &p);
1126 char *name;
1128 if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
1129 if (!target)
1130 return FALSE;
1132 name = (char*)p;
1133 if (strcmp (target->name, name) != 0)
1134 return FALSE;
1135 ref->method = target;
1136 } else {
1137 m = decode_resolve_method_ref (module, p, &p, error);
1138 if (!m)
1139 return FALSE;
1141 /* This should only happen when looking for an extra method */
1142 if (!target)
1143 return FALSE;
1144 if (mono_marshal_method_from_wrapper (target) == m)
1145 ref->method = target;
1146 else
1147 return FALSE;
1149 break;
1151 case MONO_WRAPPER_CASTCLASS: {
1152 int subtype = decode_value (p, &p);
1154 if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
1155 ref->method = mono_marshal_get_castclass_with_cache ();
1156 else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
1157 ref->method = mono_marshal_get_isinst_with_cache ();
1158 else {
1159 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid CASTCLASS wrapper subtype %d", subtype);
1160 return FALSE;
1162 break;
1164 case MONO_WRAPPER_RUNTIME_INVOKE: {
1165 int subtype = decode_value (p, &p);
1167 if (!target)
1168 return FALSE;
1170 if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
1171 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
1172 return FALSE;
1173 ref->method = target;
1174 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
1175 /* Direct wrapper */
1176 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1177 if (!m)
1178 return FALSE;
1179 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
1180 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
1181 /* Virtual direct wrapper */
1182 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1183 if (!m)
1184 return FALSE;
1185 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
1186 } else {
1187 MonoMethodSignature *sig;
1189 sig = decode_signature_with_target (module, NULL, p, &p);
1190 info = mono_marshal_get_wrapper_info (target);
1191 g_assert (info);
1193 if (info->subtype != subtype)
1194 return FALSE;
1195 g_assert (info->d.runtime_invoke.sig);
1196 if (mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig))
1197 ref->method = target;
1198 else
1199 return FALSE;
1201 break;
1203 case MONO_WRAPPER_DELEGATE_INVOKE:
1204 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1205 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
1206 gboolean is_inflated = decode_value (p, &p);
1207 WrapperSubtype subtype;
1209 if (is_inflated) {
1210 MonoClass *klass;
1211 MonoMethod *invoke, *wrapper;
1213 klass = decode_klass_ref (module, p, &p, error);
1214 if (!klass)
1215 return FALSE;
1217 switch (wrapper_type) {
1218 case MONO_WRAPPER_DELEGATE_INVOKE:
1219 invoke = mono_get_delegate_invoke (klass);
1220 wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
1221 break;
1222 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1223 invoke = mono_get_delegate_begin_invoke (klass);
1224 wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
1225 break;
1226 case MONO_WRAPPER_DELEGATE_END_INVOKE:
1227 invoke = mono_get_delegate_end_invoke (klass);
1228 wrapper = mono_marshal_get_delegate_end_invoke (invoke);
1229 break;
1230 default:
1231 g_assert_not_reached ();
1232 break;
1234 if (target) {
1236 * Due to the way mini_get_shared_method_full () works, we could end up with
1237 * multiple copies of the same wrapper.
1239 if (wrapper->klass != target->klass)
1240 return FALSE;
1241 ref->method = target;
1242 } else {
1243 ref->method = wrapper;
1245 } else {
1247 * These wrappers are associated with a signature, not with a method.
1248 * Since we can't decode them into methods, they need a target method.
1250 if (!target)
1251 return FALSE;
1253 if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1254 subtype = (WrapperSubtype)decode_value (p, &p);
1255 info = mono_marshal_get_wrapper_info (target);
1256 if (info) {
1257 if (info->subtype != subtype)
1258 return FALSE;
1259 } else {
1260 if (subtype != WRAPPER_SUBTYPE_NONE)
1261 return FALSE;
1264 if (sig_matches_target (module, target, p, &p))
1265 ref->method = target;
1266 else
1267 return FALSE;
1269 break;
1271 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1272 MonoMethod *m;
1273 MonoClass *klass;
1275 m = decode_resolve_method_ref (module, p, &p, error);
1276 if (!m)
1277 return FALSE;
1278 klass = decode_klass_ref (module, p, &p, error);
1279 if (!klass)
1280 return FALSE;
1281 ref->method = mono_marshal_get_managed_wrapper (m, klass, 0, error);
1282 if (!mono_error_ok (error))
1283 return FALSE;
1284 break;
1286 default:
1287 g_assert_not_reached ();
1289 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1290 image_index = decode_value (p, &p);
1291 ref->token = decode_value (p, &p);
1293 image = load_image (module, image_index, error);
1294 if (!image)
1295 return FALSE;
1296 } else if (image_index == MONO_AOT_METHODREF_GINST) {
1297 MonoClass *klass;
1298 MonoGenericContext ctx;
1301 * These methods do not have a token which resolves them, so we
1302 * resolve them immediately.
1304 klass = decode_klass_ref (module, p, &p, error);
1305 if (!klass)
1306 return FALSE;
1308 if (target && target->klass != klass)
1309 return FALSE;
1311 image_index = decode_value (p, &p);
1312 ref->token = decode_value (p, &p);
1314 image = load_image (module, image_index, error);
1315 if (!image)
1316 return FALSE;
1318 ref->method = mono_get_method_checked (image, ref->token, NULL, NULL, error);
1319 if (!ref->method)
1320 return FALSE;
1323 memset (&ctx, 0, sizeof (ctx));
1325 if (FALSE && mono_class_is_ginst (klass)) {
1326 ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
1327 ctx.method_inst = NULL;
1329 ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
1330 if (!ref->method)
1331 return FALSE;
1334 memset (&ctx, 0, sizeof (ctx));
1336 if (!decode_generic_context (module, &ctx, p, &p, error))
1337 return FALSE;
1339 ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
1340 if (!ref->method)
1341 return FALSE;
1343 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1344 MonoClass *klass;
1345 int method_type;
1347 klass = decode_klass_ref (module, p, &p, error);
1348 if (!klass)
1349 return FALSE;
1350 method_type = decode_value (p, &p);
1351 switch (method_type) {
1352 case 0:
1353 ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass), 0, error);
1354 return_val_if_nok (error, FALSE);
1355 break;
1356 case 1:
1357 ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass) * 2, 0, error);
1358 return_val_if_nok (error, FALSE);
1359 break;
1360 case 2:
1361 ref->method = mono_class_get_method_from_name_checked (klass, "Get", -1, 0, error);
1362 return_val_if_nok (error, FALSE);
1363 break;
1364 case 3:
1365 ref->method = mono_class_get_method_from_name_checked (klass, "Address", -1, 0, error);
1366 return_val_if_nok (error, FALSE);
1367 break;
1368 case 4:
1369 ref->method = mono_class_get_method_from_name_checked (klass, "Set", -1, 0, error);
1370 return_val_if_nok (error, FALSE);
1371 break;
1372 default:
1373 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid METHODREF_ARRAY method type %d", method_type);
1374 return FALSE;
1376 } else {
1377 if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
1378 image_index = decode_value (p, &p);
1379 value = decode_value (p, &p);
1382 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1384 image = load_image (module, image_index, error);
1385 if (!image)
1386 return FALSE;
1389 *endbuf = p;
1391 ref->image = image;
1393 return TRUE;
1396 static gboolean
1397 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf, MonoError *error)
1399 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf, error);
1403 * decode_resolve_method_ref_with_target:
1405 * Similar to decode_method_ref, but resolve and return the method itself.
1407 static MonoMethod*
1408 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
1410 MethodRef ref;
1412 error_init (error);
1414 if (!decode_method_ref_with_target (module, &ref, target, buf, endbuf, error))
1415 return NULL;
1416 if (ref.method)
1417 return ref.method;
1418 if (!ref.image) {
1419 mono_error_set_bad_image_by_name (error, module->aot_name, "No image found for methodref with target");
1420 return NULL;
1422 return mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
1425 static MonoMethod*
1426 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
1428 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf, error);
1431 #ifdef ENABLE_AOT_CACHE
1433 /* AOT CACHE */
1436 * FIXME:
1437 * - Add options for controlling the cache size
1438 * - Handle full cache by deleting old assemblies lru style
1439 * - Maybe add a threshold after an assembly is AOT compiled
1440 * - Add options for enabling this for specific main assemblies
1443 /* The cache directory */
1444 static char *cache_dir;
1446 /* The number of assemblies AOTed in this run */
1447 static int cache_count;
1449 /* Whenever to AOT in-process */
1450 static gboolean in_process;
1452 static void
1453 collect_assemblies (gpointer data, gpointer user_data)
1455 MonoAssembly *ass = (MonoAssembly*)data;
1456 GSList **l = (GSList**)user_data;
1458 *l = g_slist_prepend (*l, ass);
1461 #define SHA1_DIGEST_LENGTH 20
1464 * get_aot_config_hash:
1466 * Return a hash for all the version information an AOT module depends on.
1468 static G_GNUC_UNUSED char*
1469 get_aot_config_hash (MonoAssembly *assembly)
1471 char *build_info;
1472 GSList *l, *assembly_list = NULL;
1473 GString *s;
1474 int i;
1475 guint8 digest [SHA1_DIGEST_LENGTH];
1476 char *digest_str;
1478 build_info = mono_get_runtime_build_info ();
1480 s = g_string_new (build_info);
1482 mono_assembly_foreach (collect_assemblies, &assembly_list);
1485 * The assembly list includes the current assembly as well, no need
1486 * to add it.
1488 for (l = assembly_list; l; l = l->next) {
1489 MonoAssembly *ass = (MonoAssembly*)l->data;
1491 g_string_append (s, "_");
1492 g_string_append (s, ass->aname.name);
1493 g_string_append (s, "_");
1494 g_string_append (s, ass->image->guid);
1497 for (i = 0; i < s->len; ++i) {
1498 if (!isalnum (s->str [i]) && s->str [i] != '-')
1499 s->str [i] = '_';
1502 mono_sha1_get_digest ((guint8*)s->str, s->len, digest);
1504 digest_str = g_malloc0 ((SHA1_DIGEST_LENGTH * 2) + 1);
1505 for (i = 0; i < SHA1_DIGEST_LENGTH; ++i)
1506 sprintf (digest_str + (i * 2), "%02x", digest [i]);
1508 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: file dependencies: %s, hash %s", s->str, digest_str);
1510 g_string_free (s, TRUE);
1512 return digest_str;
1515 static void
1516 aot_cache_init (void)
1518 if (mono_aot_only)
1519 return;
1520 enable_aot_cache = TRUE;
1521 in_process = TRUE;
1525 * aot_cache_load_module:
1527 * Load the AOT image corresponding to ASSEMBLY from the aot cache, AOTing it if neccessary.
1529 static MonoDl*
1530 aot_cache_load_module (MonoAssembly *assembly, char **aot_name)
1532 MonoAotCacheConfig *config;
1533 GSList *l;
1534 char *fname, *tmp2, *aot_options, *failure_fname;
1535 const char *home;
1536 MonoDl *module;
1537 gboolean res;
1538 gint exit_status;
1539 char *hash;
1540 int pid;
1541 gboolean enabled;
1542 FILE *failure_file;
1544 *aot_name = NULL;
1546 if (image_is_dynamic (assembly->image))
1547 return NULL;
1549 /* Check in the list of assemblies enabled for aot caching */
1550 config = mono_get_aot_cache_config ();
1552 enabled = FALSE;
1553 if (config->apps) {
1554 MonoDomain *domain = mono_domain_get ();
1555 MonoAssembly *entry_assembly = domain->entry_assembly;
1557 // FIXME: This cannot be used for mscorlib during startup, since entry_assembly is not set yet
1558 for (l = config->apps; l; l = l->next) {
1559 char *n = (char*)l->data;
1561 if ((entry_assembly && !strcmp (entry_assembly->aname.name, n)) || (!entry_assembly && !strcmp (assembly->aname.name, n)))
1562 break;
1564 if (l)
1565 enabled = TRUE;
1568 if (!enabled) {
1569 for (l = config->assemblies; l; l = l->next) {
1570 char *n = (char*)l->data;
1572 if (!strcmp (assembly->aname.name, n))
1573 break;
1575 if (l)
1576 enabled = TRUE;
1578 if (!enabled)
1579 return NULL;
1581 if (!cache_dir) {
1582 home = g_get_home_dir ();
1583 if (!home)
1584 return NULL;
1585 cache_dir = g_strdup_printf ("%s/Library/Caches/mono/aot-cache", home);
1586 if (!g_file_test (cache_dir, (GFileTest)(G_FILE_TEST_EXISTS|G_FILE_TEST_IS_DIR)))
1587 g_mkdir_with_parents (cache_dir, 0777);
1591 * The same assembly can be used in multiple configurations, i.e. multiple
1592 * versions of the runtime, with multiple versions of dependent assemblies etc.
1593 * To handle this, we compute a version string containing all this information, hash it,
1594 * and use the hash as a filename suffix.
1596 hash = get_aot_config_hash (assembly);
1598 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, hash, MONO_SOLIB_EXT);
1599 fname = g_build_filename (cache_dir, tmp2, NULL);
1600 *aot_name = fname;
1601 g_free (tmp2);
1603 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: loading from cache: '%s'.", fname);
1604 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1606 if (module) {
1607 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: found in cache: '%s'.", fname);
1608 return module;
1611 if (!strcmp (assembly->aname.name, "mscorlib") && !mscorlib_aot_loaded)
1613 * Can't AOT this during startup, so we AOT it when called later from
1614 * mono_aot_get_method ().
1616 return NULL;
1618 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: not found.");
1620 /* Only AOT one assembly per run to avoid slowing down execution too much */
1621 if (cache_count > 0)
1622 return NULL;
1623 cache_count ++;
1625 /* Check for previous failure */
1626 failure_fname = g_strdup_printf ("%s.failure", fname);
1627 failure_file = fopen (failure_fname, "r");
1628 if (failure_file) {
1629 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: assembly '%s' previously failed to compile '%s' ('%s')... ", assembly->image->name, fname, failure_fname);
1630 g_free (failure_fname);
1631 return NULL;
1632 } else {
1633 g_free (failure_fname);
1634 fclose (failure_file);
1637 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compiling assembly '%s', logfile: '%s.log'... ", assembly->image->name, fname);
1640 * We need to invoke the AOT compiler here. There are multiple approaches:
1641 * - spawn a new runtime process. This can be hard when running with mkbundle, and
1642 * its hard to make the new process load the same set of assemblies.
1643 * - doing it in-process. This exposes the current process to bugs/leaks/side effects of
1644 * the AOT compiler.
1645 * - fork a new process and do the work there.
1647 if (in_process) {
1648 aot_options = g_strdup_printf ("outfile=%s,internal-logfile=%s.log%s%s", fname, fname, config->aot_options ? "," : "", config->aot_options ? config->aot_options : "");
1649 /* Maybe due this in another thread ? */
1650 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options, NULL);
1651 if (res) {
1652 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compilation failed.");
1653 failure_fname = g_strdup_printf ("%s.failure", fname);
1654 failure_file = fopen (failure_fname, "a+");
1655 fclose (failure_file);
1656 g_free (failure_fname);
1657 } else {
1658 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compilation succeeded.");
1660 } else {
1662 * - Avoid waiting for the aot process to finish ?
1663 * (less overhead, but multiple processes could aot the same assembly at the same time)
1665 pid = fork ();
1666 if (pid == 0) {
1667 FILE *logfile;
1668 char *logfile_name;
1670 /* Child */
1672 logfile_name = g_strdup_printf ("%s/aot.log", cache_dir);
1673 logfile = fopen (logfile_name, "a+");
1674 g_free (logfile_name);
1676 dup2 (fileno (logfile), 1);
1677 dup2 (fileno (logfile), 2);
1679 aot_options = g_strdup_printf ("outfile=%s", fname);
1680 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options, NULL);
1681 if (!res) {
1682 exit (1);
1683 } else {
1684 exit (0);
1686 } else {
1687 /* Parent */
1688 waitpid (pid, &exit_status, 0);
1689 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1690 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: failed.");
1691 else
1692 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: succeeded.");
1696 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1698 return module;
1701 #else
1703 static void
1704 aot_cache_init (void)
1708 static MonoDl*
1709 aot_cache_load_module (MonoAssembly *assembly, char **aot_name)
1711 return NULL;
1714 #endif
1716 static void
1717 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1719 if (globals) {
1720 int global_index;
1721 guint16 *table, *entry;
1722 guint16 table_size;
1723 guint32 hash;
1724 char *symbol = (char*)name;
1726 #ifdef TARGET_MACH
1727 symbol = g_strdup_printf ("_%s", name);
1728 #endif
1730 /* The first entry points to the hash */
1731 table = (guint16 *)globals [0];
1732 globals ++;
1734 table_size = table [0];
1735 table ++;
1737 hash = mono_metadata_str_hash (symbol) % table_size;
1739 entry = &table [hash * 2];
1741 /* Search the hash for the index into the globals table */
1742 global_index = -1;
1743 while (entry [0] != 0) {
1744 guint32 index = entry [0] - 1;
1745 guint32 next = entry [1];
1747 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1749 if (!strcmp ((const char*)globals [index * 2], symbol)) {
1750 global_index = index;
1751 break;
1754 if (next != 0) {
1755 entry = &table [next * 2];
1756 } else {
1757 break;
1761 if (global_index != -1)
1762 *value = globals [global_index * 2 + 1];
1763 else
1764 *value = NULL;
1766 if (symbol != name)
1767 g_free (symbol);
1768 } else {
1769 char *err = mono_dl_symbol (module, name, value);
1771 if (err)
1772 g_free (err);
1776 static void
1777 find_amodule_symbol (MonoAotModule *amodule, const char *name, gpointer *value)
1779 g_assert (!(amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY));
1781 find_symbol (amodule->sofile, amodule->globals, name, value);
1784 void
1785 mono_install_load_aot_data_hook (MonoLoadAotDataFunc load_func, MonoFreeAotDataFunc free_func, gpointer user_data)
1787 aot_data_load_func = load_func;
1788 aot_data_free_func = free_func;
1789 aot_data_func_user_data = user_data;
1792 /* Load the separate aot data file for ASSEMBLY */
1793 static guint8*
1794 open_aot_data (MonoAssembly *assembly, MonoAotFileInfo *info, void **ret_handle)
1796 MonoFileMap *map;
1797 char *filename;
1798 guint8 *data;
1800 if (aot_data_load_func) {
1801 data = aot_data_load_func (assembly, info->datafile_size, aot_data_func_user_data, ret_handle);
1802 g_assert (data);
1803 return data;
1807 * Use <assembly name>.aotdata as the default implementation if no callback is given
1809 filename = g_strdup_printf ("%s.aotdata", assembly->image->name);
1810 map = mono_file_map_open (filename);
1811 g_assert (map);
1812 data = (guint8*)mono_file_map (info->datafile_size, MONO_MMAP_READ, mono_file_map_fd (map), 0, ret_handle);
1813 g_assert (data);
1815 return data;
1818 static gboolean
1819 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, guint8 *blob, char **out_msg)
1821 char *build_info;
1822 char *msg = NULL;
1823 gboolean usable = TRUE;
1824 gboolean full_aot, interp, safepoints;
1825 guint32 excluded_cpu_optimizations;
1827 if (strcmp (assembly->image->guid, (const char*)info->assembly_guid)) {
1828 msg = g_strdup_printf ("doesn't match assembly");
1829 usable = FALSE;
1832 build_info = mono_get_runtime_build_info ();
1833 if (strlen ((const char *)info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1834 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1835 usable = FALSE;
1837 g_free (build_info);
1839 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1840 interp = info->flags & MONO_AOT_FILE_FLAG_INTERP;
1842 if (mono_aot_only && !full_aot) {
1843 if (!interp) {
1844 msg = g_strdup_printf ("not compiled with --aot=full");
1845 usable = FALSE;
1848 if (!mono_aot_only && full_aot) {
1849 msg = g_strdup_printf ("compiled with --aot=full");
1850 usable = FALSE;
1852 if (mono_use_interpreter && !interp) {
1853 msg = g_strdup_printf ("not compiled with --aot=interp");
1854 usable = FALSE;
1856 if (mono_llvm_only && !(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
1857 msg = g_strdup_printf ("not compiled with --aot=llvmonly");
1858 usable = FALSE;
1860 if (mono_use_llvm && !(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)) {
1861 /* Prefer LLVM JITted code when using --llvm */
1862 msg = g_strdup_printf ("not compiled with --aot=llvm");
1863 usable = FALSE;
1865 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1866 msg = g_strdup_printf ("not compiled for debugging");
1867 usable = FALSE;
1870 mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1871 if (info->opts & excluded_cpu_optimizations) {
1872 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1873 usable = FALSE;
1876 if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
1877 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1878 usable = FALSE;
1881 if (info->gc_name_index != -1) {
1882 char *gc_name = (char*)&blob [info->gc_name_index];
1883 const char *current_gc_name = mono_gc_get_gc_name ();
1885 if (strcmp (current_gc_name, gc_name) != 0) {
1886 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1887 usable = FALSE;
1891 safepoints = info->flags & MONO_AOT_FILE_FLAG_SAFEPOINTS;
1893 if (!safepoints && mono_threads_are_safepoints_enabled ()) {
1894 msg = g_strdup_printf ("not compiled with safepoints");
1895 usable = FALSE;
1898 *out_msg = msg;
1899 return usable;
1903 * TABLE should point to a table of call instructions. Return the address called by the INDEXth entry.
1905 static void*
1906 get_call_table_entry (void *table, int index)
1908 #if defined(TARGET_ARM)
1909 guint32 *ins_addr;
1910 guint32 ins;
1911 gint32 offset;
1913 ins_addr = (guint32*)table + index;
1914 ins = *ins_addr;
1915 if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
1916 /* blx */
1917 offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
1918 return (char*)ins_addr + (offset * 2) + 8 + 1;
1919 } else {
1920 offset = (((int)ins & 0xffffff) << 8) >> 8;
1921 return (char*)ins_addr + (offset * 4) + 8;
1923 #elif defined(TARGET_ARM64)
1924 return mono_arch_get_call_target ((guint8*)table + (index * 4) + 4);
1925 #elif defined(TARGET_X86) || defined(TARGET_AMD64)
1926 /* The callee expects an ip which points after the call */
1927 return mono_arch_get_call_target ((guint8*)table + (index * 5) + 5);
1928 #else
1929 g_assert_not_reached ();
1930 return NULL;
1931 #endif
1935 * init_amodule_got:
1937 * Initialize the shared got entries for AMODULE.
1939 static void
1940 init_amodule_got (MonoAotModule *amodule)
1942 MonoJumpInfo *ji;
1943 MonoMemPool *mp;
1944 MonoJumpInfo *patches;
1945 guint32 got_offsets [128];
1946 ERROR_DECL (error);
1947 int i, npatches;
1949 /* These can't be initialized in load_aot_module () */
1950 if (amodule->shared_got [0] || amodule->got_initializing)
1951 return;
1953 amodule->got_initializing = TRUE;
1955 mp = mono_mempool_new ();
1956 npatches = amodule->info.nshared_got_entries;
1957 for (i = 0; i < npatches; ++i)
1958 got_offsets [i] = i;
1959 patches = decode_patches (amodule, mp, npatches, FALSE, got_offsets);
1960 g_assert (patches);
1961 for (i = 0; i < npatches; ++i) {
1962 ji = &patches [i];
1964 if (ji->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR && !mono_gc_is_moving ()) {
1965 amodule->shared_got [i] = NULL;
1966 } else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_START && !mono_gc_is_moving ()) {
1967 amodule->shared_got [i] = NULL;
1968 } else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_BITS && !mono_gc_is_moving ()) {
1969 amodule->shared_got [i] = NULL;
1970 } else if (ji->type == MONO_PATCH_INFO_IMAGE) {
1971 amodule->shared_got [i] = amodule->assembly->image;
1972 } else if (ji->type == MONO_PATCH_INFO_MSCORLIB_GOT_ADDR) {
1973 if (mono_defaults.corlib) {
1974 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1976 if (mscorlib_amodule)
1977 amodule->shared_got [i] = mscorlib_amodule->got;
1978 } else {
1979 amodule->shared_got [i] = amodule->got;
1981 } else if (ji->type == MONO_PATCH_INFO_AOT_MODULE) {
1982 amodule->shared_got [i] = amodule;
1983 } else {
1984 amodule->shared_got [i] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, ji, FALSE, error);
1985 mono_error_assert_ok (error);
1989 if (amodule->got) {
1990 for (i = 0; i < npatches; ++i)
1991 amodule->got [i] = amodule->shared_got [i];
1993 if (amodule->llvm_got) {
1994 for (i = 0; i < npatches; ++i)
1995 amodule->llvm_got [i] = amodule->shared_got [i];
1998 mono_mempool_destroy (mp);
2001 static void
2002 load_aot_module (MonoAssembly *assembly, gpointer user_data)
2004 char *aot_name, *found_aot_name;
2005 MonoAotModule *amodule;
2006 MonoDl *sofile;
2007 gboolean usable = TRUE;
2008 char *version_symbol = NULL;
2009 char *msg = NULL;
2010 gpointer *globals = NULL;
2011 MonoAotFileInfo *info = NULL;
2012 int i, version;
2013 gboolean do_load_image = TRUE;
2014 int align_double, align_int64;
2015 guint8 *aot_data = NULL;
2017 if (mono_compile_aot)
2018 return;
2020 if (assembly->image->aot_module)
2022 * Already loaded. This can happen because the assembly loading code might invoke
2023 * the assembly load hooks multiple times for the same assembly.
2025 return;
2027 if (image_is_dynamic (assembly->image) || mono_asmctx_get_kind (&assembly->context) == MONO_ASMCTX_REFONLY || mono_domain_get () != mono_get_root_domain ())
2028 return;
2030 mono_aot_lock ();
2032 if (container_assm_name && !container_amodule) {
2033 char *local_ref = container_assm_name;
2034 container_assm_name = NULL;
2035 MonoImageOpenStatus status = MONO_IMAGE_OK;
2036 gchar *dll = g_strdup_printf ( "%s.dll", local_ref);
2037 MonoAssembly *assm = mono_assembly_open_a_lot (dll, &status, MONO_ASMCTX_DEFAULT);
2038 if (!assm) {
2039 gchar *exe = g_strdup_printf ("%s.exe", local_ref);
2040 assm = mono_assembly_open_a_lot (exe, &status, MONO_ASMCTX_DEFAULT);
2042 g_assert (assm);
2043 load_aot_module (assm, NULL);
2044 container_amodule = assm->image->aot_module;
2047 if (static_aot_modules)
2048 info = (MonoAotFileInfo *)g_hash_table_lookup (static_aot_modules, assembly->aname.name);
2050 mono_aot_unlock ();
2052 sofile = NULL;
2054 found_aot_name = NULL;
2056 if (info) {
2057 /* Statically linked AOT module */
2058 aot_name = g_strdup_printf ("%s", assembly->aname.name);
2059 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.", aot_name);
2060 if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
2061 globals = (void **)info->globals;
2062 g_assert (globals);
2064 found_aot_name = g_strdup (aot_name);
2065 } else {
2066 char *err;
2068 if (enable_aot_cache)
2069 sofile = aot_cache_load_module (assembly, &aot_name);
2070 if (!sofile) {
2071 aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
2073 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
2074 if (sofile) {
2075 found_aot_name = g_strdup (aot_name);
2076 } else {
2077 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
2078 g_free (err);
2080 g_free (aot_name);
2082 if (!sofile) {
2083 char *basename = g_path_get_basename (assembly->image->name);
2084 aot_name = g_strdup_printf ("%s/mono/aot-cache/%s/%s%s", mono_assembly_getrootdir(), MONO_ARCHITECTURE, basename, MONO_SOLIB_EXT);
2085 g_free (basename);
2086 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
2087 if (!sofile) {
2088 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
2089 g_free (err);
2091 g_free (aot_name);
2093 if (!sofile) {
2094 GList *l;
2096 for (l = mono_aot_paths; l; l = l->next) {
2097 char *path = (char*)l->data;
2099 char *basename = g_path_get_basename (assembly->image->name);
2100 aot_name = g_strdup_printf ("%s/%s%s", path, basename, MONO_SOLIB_EXT);
2101 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
2102 if (sofile) {
2103 found_aot_name = g_strdup (aot_name);
2104 } else {
2105 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
2106 g_free (err);
2108 g_free (basename);
2109 g_free (aot_name);
2110 if (sofile)
2111 break;
2114 if (!sofile) {
2115 if (mono_aot_only && !mono_use_interpreter && assembly->image->tables [MONO_TABLE_METHOD].rows) {
2116 aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
2117 g_error ("Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
2118 g_free (aot_name);
2120 return;
2124 if (!info) {
2125 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
2126 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
2129 // Copy aotid to MonoImage
2130 memcpy(&assembly->image->aotid, info->aotid, 16);
2132 if (version_symbol) {
2133 /* Old file format */
2134 version = atoi (version_symbol);
2135 } else {
2136 g_assert (info);
2137 version = info->version;
2140 if (version != MONO_AOT_FILE_VERSION) {
2141 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
2142 usable = FALSE;
2143 } else {
2144 guint8 *blob;
2145 void *handle;
2147 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
2148 aot_data = open_aot_data (assembly, info, &handle);
2150 blob = aot_data + info->table_offsets [MONO_AOT_TABLE_BLOB];
2151 } else {
2152 blob = (guint8 *)info->blob;
2155 usable = check_usable (assembly, info, blob, &msg);
2158 if (!usable) {
2159 if (mono_aot_only) {
2160 g_error ("Failed to load AOT module '%s' while running in aot-only mode: %s.\n", found_aot_name, msg);
2161 } else {
2162 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable: %s.", found_aot_name, msg);
2164 g_free (msg);
2165 g_free (found_aot_name);
2166 if (sofile)
2167 mono_dl_close (sofile);
2168 assembly->image->aot_module = NULL;
2169 return;
2172 /* Sanity check */
2173 align_double = MONO_ABI_ALIGNOF (double);
2174 align_int64 = MONO_ABI_ALIGNOF (gint64);
2175 int card_table_shift_bits = 0;
2176 gpointer card_table_mask = NULL;
2177 mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2179 g_assert (info->double_align == align_double);
2180 g_assert (info->long_align == align_int64);
2181 g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
2182 g_assert (info->card_table_shift_bits == card_table_shift_bits);
2183 g_assert (info->card_table_mask == GPOINTER_TO_UINT (card_table_mask));
2185 amodule = g_new0 (MonoAotModule, 1);
2186 amodule->aot_name = found_aot_name;
2187 amodule->assembly = assembly;
2189 memcpy (&amodule->info, info, sizeof (*info));
2191 amodule->got = (void **)amodule->info.jit_got;
2192 amodule->llvm_got = (void **)amodule->info.llvm_got;
2193 amodule->globals = globals;
2194 amodule->sofile = sofile;
2195 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
2196 amodule->extra_methods = g_hash_table_new (NULL, NULL);
2197 amodule->shared_got = g_new0 (gpointer, info->nshared_got_entries);
2199 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
2200 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
2201 amodule->tables [i] = aot_data + info->table_offsets [i];
2204 mono_os_mutex_init_recursive (&amodule->mutex);
2206 /* Read image table */
2208 guint32 table_len, i;
2209 char *table = NULL;
2211 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA)
2212 table = (char *)amodule->tables [MONO_AOT_TABLE_IMAGE_TABLE];
2213 else
2214 table = (char *)info->image_table;
2215 g_assert (table);
2217 table_len = *(guint32*)table;
2218 table += sizeof (guint32);
2219 amodule->image_table = g_new0 (MonoImage*, table_len);
2220 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
2221 amodule->image_guids = g_new0 (char*, table_len);
2222 amodule->image_table_len = table_len;
2223 for (i = 0; i < table_len; ++i) {
2224 MonoAssemblyName *aname = &(amodule->image_names [i]);
2226 aname->name = g_strdup (table);
2227 table += strlen (table) + 1;
2228 amodule->image_guids [i] = g_strdup (table);
2229 table += strlen (table) + 1;
2230 if (table [0] != 0)
2231 aname->culture = g_strdup (table);
2232 table += strlen (table) + 1;
2233 memcpy (aname->public_key_token, table, strlen (table) + 1);
2234 table += strlen (table) + 1;
2236 table = (char *)ALIGN_PTR_TO (table, 8);
2237 aname->flags = *(guint32*)table;
2238 table += 4;
2239 aname->major = *(guint32*)table;
2240 table += 4;
2241 aname->minor = *(guint32*)table;
2242 table += 4;
2243 aname->build = *(guint32*)table;
2244 table += 4;
2245 aname->revision = *(guint32*)table;
2246 table += 4;
2250 amodule->jit_code_start = (guint8 *)info->jit_code_start;
2251 amodule->jit_code_end = (guint8 *)info->jit_code_end;
2252 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
2253 amodule->blob = (guint8*)amodule->tables [MONO_AOT_TABLE_BLOB];
2254 amodule->method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_METHOD_INFO_OFFSETS];
2255 amodule->ex_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EX_INFO_OFFSETS];
2256 amodule->class_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_CLASS_INFO_OFFSETS];
2257 amodule->class_name_table = (guint16*)amodule->tables [MONO_AOT_TABLE_CLASS_NAME];
2258 amodule->extra_method_table = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_TABLE];
2259 amodule->extra_method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS];
2260 amodule->got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_GOT_INFO_OFFSETS];
2261 amodule->llvm_got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS];
2262 amodule->weak_field_indexes = (guint32*)amodule->tables [MONO_AOT_TABLE_WEAK_FIELD_INDEXES];
2263 } else {
2264 amodule->blob = (guint8*)info->blob;
2265 amodule->method_info_offsets = (guint32 *)info->method_info_offsets;
2266 amodule->ex_info_offsets = (guint32 *)info->ex_info_offsets;
2267 amodule->class_info_offsets = (guint32 *)info->class_info_offsets;
2268 amodule->class_name_table = (guint16 *)info->class_name_table;
2269 amodule->extra_method_table = (guint32 *)info->extra_method_table;
2270 amodule->extra_method_info_offsets = (guint32 *)info->extra_method_info_offsets;
2271 amodule->got_info_offsets = (guint32*)info->got_info_offsets;
2272 amodule->llvm_got_info_offsets = (guint32*)info->llvm_got_info_offsets;
2273 amodule->weak_field_indexes = (guint32*)info->weak_field_indexes;
2275 amodule->unbox_trampolines = (guint32 *)info->unbox_trampolines;
2276 amodule->unbox_trampolines_end = (guint32 *)info->unbox_trampolines_end;
2277 amodule->unbox_trampoline_addresses = (guint32 *)info->unbox_trampoline_addresses;
2278 amodule->unwind_info = (guint8 *)info->unwind_info;
2279 amodule->mem_begin = (guint8*)amodule->jit_code_start;
2280 amodule->mem_end = (guint8 *)info->mem_end;
2281 amodule->plt = (guint8 *)info->plt;
2282 amodule->plt_end = (guint8 *)info->plt_end;
2283 amodule->mono_eh_frame = (guint8 *)info->mono_eh_frame;
2284 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = (guint8 *)info->specific_trampolines;
2285 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = (guint8 *)info->static_rgctx_trampolines;
2286 amodule->trampolines [MONO_AOT_TRAMP_IMT] = (guint8 *)info->imt_trampolines;
2287 amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = (guint8 *)info->gsharedvt_arg_trampolines;
2288 amodule->trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = (guint8 *)info->ftnptr_arg_trampolines;
2290 if (!strcmp (assembly->aname.name, "mscorlib"))
2291 mscorlib_aot_module = amodule;
2293 /* Compute method addresses */
2294 amodule->methods = (void **)g_malloc0 (amodule->info.nmethods * sizeof (gpointer));
2295 for (i = 0; i < amodule->info.nmethods; ++i) {
2296 void *addr = NULL;
2298 if (amodule->info.llvm_get_method) {
2299 gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
2301 addr = get_method (i);
2304 /* method_addresses () contains a table of branches, since the ios linker can update those correctly */
2305 if (!addr && amodule->info.method_addresses) {
2306 addr = get_call_table_entry (amodule->info.method_addresses, i);
2307 g_assert (addr);
2308 if (addr == amodule->info.method_addresses)
2309 addr = NULL;
2311 if (addr == NULL)
2312 amodule->methods [i] = GINT_TO_POINTER (-1);
2313 else
2314 amodule->methods [i] = addr;
2317 if (make_unreadable) {
2318 #ifndef TARGET_WIN32
2319 guint8 *addr;
2320 guint8 *page_start, *page_end;
2321 int err, len;
2323 addr = amodule->mem_begin;
2324 g_assert (addr);
2325 len = amodule->mem_end - amodule->mem_begin;
2327 /* Round down in both directions to avoid modifying data which is not ours */
2328 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
2329 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
2330 if (page_end > page_start) {
2331 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
2332 g_assert (err == 0);
2334 #endif
2337 /* Compute the boundaries of LLVM code */
2338 if (info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)
2339 compute_llvm_code_range (amodule, &amodule->llvm_code_start, &amodule->llvm_code_end);
2341 mono_aot_lock ();
2343 if (amodule->jit_code_start) {
2344 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->jit_code_start);
2345 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->jit_code_end);
2347 if (amodule->llvm_code_start) {
2348 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->llvm_code_start);
2349 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->llvm_code_end);
2352 g_hash_table_insert (aot_modules, assembly, amodule);
2353 mono_aot_unlock ();
2355 if (amodule->jit_code_start)
2356 mono_jit_info_add_aot_module (assembly->image, amodule->jit_code_start, amodule->jit_code_end);
2357 if (amodule->llvm_code_start)
2358 mono_jit_info_add_aot_module (assembly->image, amodule->llvm_code_start, amodule->llvm_code_end);
2360 assembly->image->aot_module = amodule;
2362 if (mono_aot_only && !mono_llvm_only) {
2363 char *code;
2364 find_amodule_symbol (amodule, "specific_trampolines_page", (gpointer *)&code);
2365 amodule->use_page_trampolines = code != NULL;
2366 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
2370 * Register the plt region as a single trampoline so we can unwind from this code
2372 mono_aot_tramp_info_register (
2373 mono_tramp_info_create (
2374 NULL,
2375 amodule->plt,
2376 amodule->plt_end - amodule->plt,
2377 NULL,
2378 mono_unwind_get_cie_program ()
2380 NULL
2384 * Since we store methoddef and classdef tokens when referring to methods/classes in
2385 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
2386 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
2387 * non-lazily, since we can't handle out-of-date errors later.
2388 * The cached class info also depends on the exact assemblies.
2390 if (do_load_image) {
2391 for (i = 0; i < amodule->image_table_len; ++i) {
2392 ERROR_DECL (error);
2393 load_image (amodule, i, error);
2394 mono_error_cleanup (error); /* FIXME don't swallow the error */
2398 if (amodule->out_of_date) {
2399 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: Module %s is unusable because a dependency is out-of-date.", assembly->image->name);
2400 if (mono_aot_only)
2401 g_error ("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", found_aot_name);
2402 } else {
2403 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' found.", found_aot_name);
2408 * mono_aot_register_module:
2410 * This should be called by embedding code to register normal AOT modules statically linked
2411 * into the executable.
2413 * \param aot_info the value of the 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
2415 void
2416 mono_aot_register_module (gpointer *aot_info)
2418 gpointer *globals;
2419 char *aname;
2420 MonoAotFileInfo *info = (MonoAotFileInfo *)aot_info;
2422 g_assert (info->version == MONO_AOT_FILE_VERSION);
2424 if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
2425 globals = (void **)info->globals;
2426 g_assert (globals);
2429 aname = (char *)info->assembly_name;
2431 /* This could be called before startup */
2432 if (aot_modules)
2433 mono_aot_lock ();
2435 if (!static_aot_modules)
2436 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
2438 g_hash_table_insert (static_aot_modules, aname, info);
2440 if (info->flags & MONO_AOT_FILE_FLAG_EAGER_LOAD) {
2441 g_assert (!container_assm_name);
2442 container_assm_name = aname;
2445 if (aot_modules)
2446 mono_aot_unlock ();
2449 void
2450 mono_aot_init (void)
2452 mono_os_mutex_init_recursive (&aot_mutex);
2453 mono_os_mutex_init_recursive (&aot_page_mutex);
2454 aot_modules = g_hash_table_new (NULL, NULL);
2456 mono_install_assembly_load_hook (load_aot_module, NULL);
2457 mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
2459 char *lastaot = g_getenv ("MONO_LASTAOT");
2460 if (lastaot) {
2461 mono_last_aot_method = atoi (lastaot);
2462 g_free (lastaot);
2464 aot_cache_init ();
2467 void
2468 mono_aot_cleanup (void)
2470 g_hash_table_destroy (aot_jit_icall_hash);
2471 g_hash_table_destroy (aot_modules);
2474 static gboolean
2475 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
2477 ERROR_DECL (error);
2478 guint32 flags;
2479 MethodRef ref;
2480 gboolean res;
2482 info->vtable_size = decode_value (buf, &buf);
2483 if (info->vtable_size == -1)
2484 /* Generic type */
2485 return FALSE;
2486 flags = decode_value (buf, &buf);
2487 info->ghcimpl = (flags >> 0) & 0x1;
2488 info->has_finalize = (flags >> 1) & 0x1;
2489 info->has_cctor = (flags >> 2) & 0x1;
2490 info->has_nested_classes = (flags >> 3) & 0x1;
2491 info->blittable = (flags >> 4) & 0x1;
2492 info->has_references = (flags >> 5) & 0x1;
2493 info->has_static_refs = (flags >> 6) & 0x1;
2494 info->no_special_static_fields = (flags >> 7) & 0x1;
2495 info->is_generic_container = (flags >> 8) & 0x1;
2496 info->has_weak_fields = (flags >> 9) & 0x1;
2498 if (info->has_cctor) {
2499 res = decode_method_ref (module, &ref, buf, &buf, error);
2500 mono_error_assert_ok (error); /* FIXME don't swallow the error */
2501 if (!res)
2502 return FALSE;
2503 info->cctor_token = ref.token;
2505 if (info->has_finalize) {
2506 res = decode_method_ref (module, &ref, buf, &buf, error);
2507 mono_error_assert_ok (error); /* FIXME don't swallow the error */
2508 if (!res)
2509 return FALSE;
2510 info->finalize_image = ref.image;
2511 info->finalize_token = ref.token;
2514 info->instance_size = decode_value (buf, &buf);
2515 info->class_size = decode_value (buf, &buf);
2516 info->packing_size = decode_value (buf, &buf);
2517 info->min_align = decode_value (buf, &buf);
2519 *endbuf = buf;
2521 return TRUE;
2524 gpointer
2525 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot, MonoError *error)
2527 int i;
2528 MonoClass *klass = vtable->klass;
2529 MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
2530 guint8 *info, *p;
2531 MonoCachedClassInfo class_info;
2532 gboolean err;
2533 MethodRef ref;
2534 gboolean res;
2535 gpointer addr;
2536 ERROR_DECL_VALUE (inner_error);
2538 error_init (error);
2540 if (MONO_CLASS_IS_INTERFACE (klass) || m_class_get_rank (klass) || !amodule)
2541 return NULL;
2543 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
2544 p = info;
2546 err = decode_cached_class_info (amodule, &class_info, p, &p);
2547 if (!err)
2548 return NULL;
2550 for (i = 0; i < slot; ++i) {
2551 decode_method_ref (amodule, &ref, p, &p, &inner_error);
2552 mono_error_cleanup (&inner_error); /* FIXME don't swallow the error */
2555 res = decode_method_ref (amodule, &ref, p, &p, &inner_error);
2556 mono_error_cleanup (&inner_error); /* FIXME don't swallow the error */
2557 if (!res)
2558 return NULL;
2559 if (ref.no_aot_trampoline)
2560 return NULL;
2562 if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
2563 return NULL;
2565 addr = mono_aot_get_method_from_token (domain, ref.image, ref.token, error);
2566 return addr;
2569 gboolean
2570 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2572 MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
2573 guint8 *p;
2574 gboolean err;
2576 if (m_class_get_rank (klass) || !m_class_get_type_token (klass) || !amodule)
2577 return FALSE;
2579 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
2581 err = decode_cached_class_info (amodule, res, p, &p);
2582 if (!err)
2583 return FALSE;
2585 return TRUE;
2589 * mono_aot_get_class_from_name:
2591 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
2592 * using a cache stored in the AOT file.
2593 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
2595 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
2596 * found.
2598 gboolean
2599 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2601 MonoAotModule *amodule = image->aot_module;
2602 guint16 *table, *entry;
2603 guint16 table_size;
2604 guint32 hash;
2605 char full_name_buf [1024];
2606 char *full_name;
2607 const char *name2, *name_space2;
2608 MonoTableInfo *t;
2609 guint32 cols [MONO_TYPEDEF_SIZE];
2610 GHashTable *nspace_table;
2612 if (!amodule || !amodule->class_name_table)
2613 return FALSE;
2615 amodule_lock (amodule);
2617 *klass = NULL;
2619 /* First look in the cache */
2620 if (!amodule->name_cache)
2621 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
2622 nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
2623 if (nspace_table) {
2624 *klass = (MonoClass *)g_hash_table_lookup (nspace_table, name);
2625 if (*klass) {
2626 amodule_unlock (amodule);
2627 return TRUE;
2631 table_size = amodule->class_name_table [0];
2632 table = amodule->class_name_table + 1;
2634 if (name_space [0] == '\0')
2635 full_name = g_strdup_printf ("%s", name);
2636 else {
2637 if (strlen (name_space) + strlen (name) < 1000) {
2638 sprintf (full_name_buf, "%s.%s", name_space, name);
2639 full_name = full_name_buf;
2640 } else {
2641 full_name = g_strdup_printf ("%s.%s", name_space, name);
2644 hash = mono_metadata_str_hash (full_name) % table_size;
2645 if (full_name != full_name_buf)
2646 g_free (full_name);
2648 entry = &table [hash * 2];
2650 if (entry [0] != 0) {
2651 t = &image->tables [MONO_TABLE_TYPEDEF];
2653 while (TRUE) {
2654 guint32 index = entry [0];
2655 guint32 next = entry [1];
2656 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2658 name_table_accesses ++;
2660 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2662 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2663 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2665 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2666 ERROR_DECL (error);
2667 amodule_unlock (amodule);
2668 *klass = mono_class_get_checked (image, token, error);
2669 if (!mono_error_ok (error))
2670 mono_error_cleanup (error); /* FIXME don't swallow the error */
2672 /* Add to cache */
2673 if (*klass) {
2674 amodule_lock (amodule);
2675 nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
2676 if (!nspace_table) {
2677 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2678 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2680 g_hash_table_insert (nspace_table, (char*)name2, *klass);
2681 amodule_unlock (amodule);
2683 return TRUE;
2686 if (next != 0) {
2687 entry = &table [next * 2];
2688 } else {
2689 break;
2694 amodule_unlock (amodule);
2696 return TRUE;
2699 GHashTable *
2700 mono_aot_get_weak_field_indexes (MonoImage *image)
2702 MonoAotModule *amodule = image->aot_module;
2704 if (!amodule)
2705 return NULL;
2707 /* Initialize weak field indexes from the cached copy */
2708 guint32 *indexes = (guint32*)amodule->weak_field_indexes;
2709 int len = indexes [0];
2710 GHashTable *indexes_hash = g_hash_table_new (NULL, NULL);
2711 for (int i = 0; i < len; ++i)
2712 g_hash_table_insert (indexes_hash, GUINT_TO_POINTER (indexes [i + 1]), GUINT_TO_POINTER (1));
2713 return indexes_hash;
2716 /* Compute the boundaries of the LLVM code for AMODULE. */
2717 static void
2718 compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end)
2720 guint8 *p;
2721 int version, fde_count;
2722 gint32 *table;
2724 if (amodule->info.llvm_get_method) {
2725 gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
2727 #ifdef HOST_WASM
2728 gsize min = 1 << 30, max = 0;
2729 gsize prev = 0;
2731 // FIXME: This depends on emscripten allocating ftnptr ids sequentially
2732 for (int i = 0; i < amodule->info.nmethods; ++i) {
2733 void *addr = NULL;
2735 addr = get_method (i);
2736 gsize val = (gsize)addr;
2737 if (val) {
2738 g_assert (val > prev);
2739 if (val < min)
2740 min = val;
2741 else if (val > max)
2742 max = val;
2743 prev = val;
2746 if (max) {
2747 *code_start = (guint8*)min;
2748 *code_end = (guint8*)(max + 1);
2749 } else {
2750 *code_start = NULL;
2751 *code_end = NULL;
2753 #else
2754 *code_start = (guint8 *)get_method (-1);
2755 *code_end = (guint8 *)get_method (-2);
2757 g_assert (*code_end > *code_start);
2758 #endif
2759 return;
2762 g_assert (amodule->mono_eh_frame);
2764 p = amodule->mono_eh_frame;
2766 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2768 /* Header */
2769 version = *p;
2770 g_assert (version == 3);
2771 p ++;
2772 p ++;
2773 p = (guint8 *)ALIGN_PTR_TO (p, 4);
2775 fde_count = *(guint32*)p;
2776 p += 4;
2777 table = (gint32*)p;
2779 if (fde_count > 0) {
2780 *code_start = (guint8 *)amodule->methods [table [0]];
2781 *code_end = (guint8*)amodule->methods [table [(fde_count - 1) * 2]] + table [fde_count * 2];
2782 } else {
2783 *code_start = NULL;
2784 *code_end = NULL;
2788 static gboolean
2789 is_llvm_code (MonoAotModule *amodule, guint8 *code)
2791 #if HOST_WASM
2792 return TRUE;
2793 #else
2794 if ((guint8*)code >= amodule->llvm_code_start && (guint8*)code < amodule->llvm_code_end)
2795 return TRUE;
2796 else
2797 return FALSE;
2798 #endif
2801 static gboolean
2802 is_thumb_code (MonoAotModule *amodule, guint8 *code)
2804 if (is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_THUMB))
2805 return TRUE;
2806 else
2807 return FALSE;
2811 * decode_llvm_mono_eh_frame:
2813 * Decode the EH information emitted by our modified LLVM compiler and construct a
2814 * MonoJitInfo structure from it.
2815 * If JINFO is NULL, set OUT_LLVM_CLAUSES to the number of llvm level clauses.
2816 * This function is async safe when called in async context.
2818 static void
2819 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, MonoJitInfo *jinfo,
2820 guint8 *code, guint32 code_len,
2821 MonoJitExceptionInfo *clauses, int num_clauses,
2822 GSList **nesting,
2823 int *this_reg, int *this_offset, int *out_llvm_clauses)
2825 guint8 *p, *code1, *code2;
2826 guint8 *fde, *cie, *code_start, *code_end;
2827 int version, fde_count;
2828 gint32 *table;
2829 int i, pos, left, right;
2830 MonoJitExceptionInfo *ei;
2831 guint32 fde_len, ei_len, nested_len, nindex;
2832 gpointer *type_info;
2833 MonoLLVMFDEInfo info;
2834 guint8 *unw_info;
2835 gboolean async;
2837 async = mono_thread_info_is_async_context ();
2839 if (!amodule->mono_eh_frame) {
2840 if (!jinfo) {
2841 *out_llvm_clauses = num_clauses;
2842 return;
2844 memcpy (jinfo->clauses, clauses, num_clauses * sizeof (MonoJitExceptionInfo));
2845 return;
2848 g_assert (amodule->mono_eh_frame && code);
2850 p = amodule->mono_eh_frame;
2852 /* p points to data emitted by LLVM in DwarfMonoException::EmitMonoEHFrame () */
2854 /* Header */
2855 version = *p;
2856 g_assert (version == 3);
2857 p ++;
2858 /* func_encoding = *p; */
2859 p ++;
2860 p = (guint8 *)ALIGN_PTR_TO (p, 4);
2862 fde_count = *(guint32*)p;
2863 p += 4;
2864 table = (gint32*)p;
2866 /* There is +1 entry in the table */
2867 cie = p + ((fde_count + 1) * 8);
2869 /* Binary search in the table to find the entry for code */
2870 left = 0;
2871 right = fde_count;
2872 while (TRUE) {
2873 pos = (left + right) / 2;
2875 /* The table contains method index/fde offset pairs */
2876 g_assert (table [(pos * 2)] != -1);
2877 code1 = (guint8 *)amodule->methods [table [(pos * 2)]];
2878 if (pos + 1 == fde_count) {
2879 code2 = amodule->llvm_code_end;
2880 } else {
2881 g_assert (table [(pos + 1) * 2] != -1);
2882 code2 = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
2885 if (code < code1)
2886 right = pos;
2887 else if (code >= code2)
2888 left = pos + 1;
2889 else
2890 break;
2893 code_start = (guint8 *)amodule->methods [table [(pos * 2)]];
2894 if (pos + 1 == fde_count) {
2895 /* The +1 entry in the table contains the length of the last method */
2896 int len = table [(pos + 1) * 2];
2897 code_end = code_start + len;
2898 } else {
2899 code_end = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
2901 if (!code_len)
2902 code_len = code_end - code_start;
2904 g_assert (code >= code_start && code < code_end);
2906 if (is_thumb_code (amodule, code_start))
2907 /* Clear thumb flag */
2908 code_start = (guint8*)(((gsize)code_start) & ~1);
2910 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
2911 /* This won't overflow because there is +1 entry in the table */
2912 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2914 /* Compute lengths */
2915 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, NULL, NULL, NULL);
2917 if (async) {
2918 /* These are leaked, but the leak is bounded */
2919 ei = mono_domain_alloc0_lock_free (domain, info.ex_info_len * sizeof (MonoJitExceptionInfo));
2920 type_info = mono_domain_alloc0_lock_free (domain, info.ex_info_len * sizeof (gpointer));
2921 unw_info = mono_domain_alloc0_lock_free (domain, info.unw_info_len);
2922 } else {
2923 ei = (MonoJitExceptionInfo *)g_malloc0 (info.ex_info_len * sizeof (MonoJitExceptionInfo));
2924 type_info = (gpointer *)g_malloc0 (info.ex_info_len * sizeof (gpointer));
2925 unw_info = (guint8*)g_malloc0 (info.unw_info_len);
2927 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, ei, type_info, unw_info);
2929 ei_len = info.ex_info_len;
2930 *this_reg = info.this_reg;
2931 *this_offset = info.this_offset;
2934 * LLVM might represent one IL region with multiple regions.
2937 /* Count number of nested clauses */
2938 nested_len = 0;
2939 for (i = 0; i < ei_len; ++i) {
2940 /* This might be unaligned */
2941 gint32 cindex1 = read32 (type_info [i]);
2942 GSList *l;
2944 for (l = nesting [cindex1]; l; l = l->next)
2945 nested_len ++;
2948 if (!jinfo) {
2949 *out_llvm_clauses = ei_len + nested_len;
2950 return;
2953 /* Store the unwind info addr/length in the MonoJitInfo structure itself so its async safe */
2954 MonoUnwindJitInfo *jinfo_unwind = mono_jit_info_get_unwind_info (jinfo);
2955 g_assert (jinfo_unwind);
2956 jinfo_unwind->unw_info = unw_info;
2957 jinfo_unwind->unw_info_len = info.unw_info_len;
2959 for (i = 0; i < ei_len; ++i) {
2961 * clauses contains the original IL exception info saved by the AOT
2962 * compiler, we have to combine that with the information produced by LLVM
2964 /* The type_info entries contain IL clause indexes */
2965 int clause_index = read32 (type_info [i]);
2966 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2967 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2969 g_assert (clause_index < num_clauses);
2970 jei->flags = orig_jei->flags;
2971 jei->data.catch_class = orig_jei->data.catch_class;
2973 jei->try_start = ei [i].try_start;
2974 jei->try_end = ei [i].try_end;
2975 jei->handler_start = ei [i].handler_start;
2976 jei->clause_index = clause_index;
2978 if (is_thumb_code (amodule, (guint8 *)jei->try_start)) {
2979 jei->try_start = (void*)((gsize)jei->try_start & ~1);
2980 jei->try_end = (void*)((gsize)jei->try_end & ~1);
2981 /* Make sure we transition to thumb when a handler starts */
2982 jei->handler_start = (void*)((gsize)jei->handler_start + 1);
2986 /* See exception_cb () in mini-llvm.c as to why this is needed */
2987 nindex = ei_len;
2988 for (i = 0; i < ei_len; ++i) {
2989 gint32 cindex1 = read32 (type_info [i]);
2990 GSList *l;
2992 for (l = nesting [cindex1]; l; l = l->next) {
2993 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2994 MonoJitExceptionInfo *nesting_ei;
2995 MonoJitExceptionInfo *nesting_clause = &clauses [nesting_cindex];
2997 nesting_ei = &jinfo->clauses [nindex];
2998 nindex ++;
3000 memcpy (nesting_ei, &jinfo->clauses [i], sizeof (MonoJitExceptionInfo));
3001 nesting_ei->flags = nesting_clause->flags;
3002 nesting_ei->data.catch_class = nesting_clause->data.catch_class;
3003 nesting_ei->clause_index = nesting_cindex;
3006 g_assert (nindex == ei_len + nested_len);
3009 static gpointer
3010 alloc0_jit_info_data (MonoDomain *domain, int size, gboolean async_context)
3012 #define alloc0_jit_info_data(domain, size, async_context) (g_cast (alloc0_jit_info_data ((domain), (size), (async_context))))
3015 gpointer res;
3017 if (async_context) {
3018 res = mono_domain_alloc0_lock_free (domain, size);
3019 mono_atomic_fetch_add_i32 (&async_jit_info_size, size);
3020 } else {
3021 res = mono_domain_alloc0 (domain, size);
3023 return res;
3027 * LOCKING: Acquires the domain lock.
3028 * In async context, this is async safe.
3030 static MonoJitInfo*
3031 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
3032 MonoMethod *method, guint8* ex_info,
3033 guint8 *code, guint32 code_len)
3035 ERROR_DECL (error);
3036 int i, buf_len, num_clauses, len;
3037 MonoJitInfo *jinfo;
3038 MonoJitInfoFlags flags = JIT_INFO_NONE;
3039 guint unwind_info, eflags;
3040 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
3041 gboolean from_llvm, has_gc_map;
3042 guint8 *p;
3043 int try_holes_info_size, num_holes;
3044 int this_reg = 0, this_offset = 0;
3045 gboolean async;
3047 /* Load the method info from the AOT file */
3048 async = mono_thread_info_is_async_context ();
3050 p = ex_info;
3051 eflags = decode_value (p, &p);
3052 has_generic_jit_info = (eflags & 1) != 0;
3053 has_dwarf_unwind_info = (eflags & 2) != 0;
3054 has_clauses = (eflags & 4) != 0;
3055 has_seq_points = (eflags & 8) != 0;
3056 from_llvm = (eflags & 16) != 0;
3057 has_try_block_holes = (eflags & 32) != 0;
3058 has_gc_map = (eflags & 64) != 0;
3059 has_arch_eh_jit_info = (eflags & 128) != 0;
3061 if (has_dwarf_unwind_info) {
3062 unwind_info = decode_value (p, &p);
3063 g_assert (unwind_info < (1 << 30));
3064 } else {
3065 unwind_info = decode_value (p, &p);
3067 if (has_generic_jit_info)
3068 flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
3070 if (has_try_block_holes) {
3071 num_holes = decode_value (p, &p);
3072 flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
3073 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
3074 } else {
3075 num_holes = try_holes_info_size = 0;
3078 if (has_arch_eh_jit_info) {
3079 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
3080 /* Overwrite the original code_len which includes alignment padding */
3081 code_len = decode_value (p, &p);
3084 /* Exception table */
3085 if (has_clauses)
3086 num_clauses = decode_value (p, &p);
3087 else
3088 num_clauses = 0;
3090 if (from_llvm) {
3091 MonoJitExceptionInfo *clauses;
3092 GSList **nesting;
3095 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
3096 * section.
3098 if (async) {
3099 if (num_clauses < 16) {
3100 clauses = g_newa (MonoJitExceptionInfo, num_clauses);
3101 nesting = g_newa (GSList*, num_clauses);
3102 } else {
3103 clauses = alloc0_jit_info_data (domain, sizeof (MonoJitExceptionInfo) * num_clauses, TRUE);
3104 nesting = alloc0_jit_info_data (domain, sizeof (GSList*) * num_clauses, TRUE);
3106 memset (clauses, 0, sizeof (MonoJitExceptionInfo) * num_clauses);
3107 memset (nesting, 0, sizeof (GSList*) * num_clauses);
3108 } else {
3109 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
3110 nesting = g_new0 (GSList*, num_clauses);
3113 for (i = 0; i < num_clauses; ++i) {
3114 MonoJitExceptionInfo *ei = &clauses [i];
3116 ei->flags = decode_value (p, &p);
3118 if (!(ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
3119 int len = decode_value (p, &p);
3121 if (len > 0) {
3122 if (async) {
3123 p += len;
3124 } else {
3125 ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
3126 mono_error_cleanup (error); /* FIXME don't swallow the error */
3131 ei->clause_index = i;
3133 ei->try_offset = decode_value (p, &p);
3134 ei->try_len = decode_value (p, &p);
3135 ei->handler_offset = decode_value (p, &p);
3136 ei->handler_len = decode_value (p, &p);
3138 /* Read the list of nesting clauses */
3139 while (TRUE) {
3140 int nesting_index = decode_value (p, &p);
3141 if (nesting_index == -1)
3142 break;
3143 // FIXME: async
3144 g_assert (!async);
3145 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
3149 flags |= JIT_INFO_HAS_UNWIND_INFO;
3151 int num_llvm_clauses;
3152 /* Get the length first */
3153 decode_llvm_mono_eh_frame (amodule, domain, NULL, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, &num_llvm_clauses);
3154 len = mono_jit_info_size (flags, num_llvm_clauses, num_holes);
3155 jinfo = (MonoJitInfo *)alloc0_jit_info_data (domain, len, async);
3156 mono_jit_info_init (jinfo, method, code, code_len, flags, num_llvm_clauses, num_holes);
3158 decode_llvm_mono_eh_frame (amodule, domain, jinfo, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, NULL);
3160 if (!async) {
3161 g_free (clauses);
3162 for (i = 0; i < num_clauses; ++i)
3163 g_slist_free (nesting [i]);
3164 g_free (nesting);
3166 jinfo->from_llvm = 1;
3167 } else {
3168 len = mono_jit_info_size (flags, num_clauses, num_holes);
3169 jinfo = (MonoJitInfo *)alloc0_jit_info_data (domain, len, async);
3170 mono_jit_info_init (jinfo, method, code, code_len, flags, num_clauses, num_holes);
3172 for (i = 0; i < jinfo->num_clauses; ++i) {
3173 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3175 ei->flags = decode_value (p, &p);
3177 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
3178 /* Not used for catch clauses */
3179 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
3180 ei->exvar_offset = decode_value (p, &p);
3181 #else
3182 ei->exvar_offset = decode_value (p, &p);
3183 #endif
3185 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3186 ei->data.filter = code + decode_value (p, &p);
3187 else {
3188 int len = decode_value (p, &p);
3190 if (len > 0) {
3191 if (async) {
3192 p += len;
3193 } else {
3194 ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
3195 mono_error_cleanup (error); /* FIXME don't swallow the error */
3200 ei->try_start = code + decode_value (p, &p);
3201 ei->try_end = code + decode_value (p, &p);
3202 ei->handler_start = code + decode_value (p, &p);
3205 jinfo->unwind_info = unwind_info;
3206 jinfo->domain_neutral = 0;
3207 jinfo->from_aot = 1;
3210 if (has_try_block_holes) {
3211 MonoTryBlockHoleTableJitInfo *table;
3213 g_assert (jinfo->has_try_block_holes);
3215 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3216 g_assert (table);
3218 table->num_holes = (guint16)num_holes;
3219 for (i = 0; i < num_holes; ++i) {
3220 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3221 hole->clause = decode_value (p, &p);
3222 hole->length = decode_value (p, &p);
3223 hole->offset = decode_value (p, &p);
3227 if (has_arch_eh_jit_info) {
3228 MonoArchEHJitInfo *eh_info;
3230 g_assert (jinfo->has_arch_eh_info);
3232 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
3233 eh_info->stack_size = decode_value (p, &p);
3234 eh_info->epilog_size = decode_value (p, &p);
3237 if (async) {
3238 /* The rest is not needed in async mode */
3239 jinfo->async = TRUE;
3240 jinfo->d.aot_info = amodule;
3241 // FIXME: Cache
3242 return jinfo;
3245 if (has_generic_jit_info) {
3246 MonoGenericJitInfo *gi;
3247 int len;
3249 g_assert (jinfo->has_generic_jit_info);
3251 gi = mono_jit_info_get_generic_jit_info (jinfo);
3252 g_assert (gi);
3254 gi->nlocs = decode_value (p, &p);
3255 if (gi->nlocs) {
3256 gi->locations = (MonoDwarfLocListEntry *)alloc0_jit_info_data (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
3257 for (i = 0; i < gi->nlocs; ++i) {
3258 MonoDwarfLocListEntry *entry = &gi->locations [i];
3260 entry->is_reg = decode_value (p, &p);
3261 entry->reg = decode_value (p, &p);
3262 if (!entry->is_reg)
3263 entry->offset = decode_value (p, &p);
3264 if (i > 0)
3265 entry->from = decode_value (p, &p);
3266 entry->to = decode_value (p, &p);
3268 gi->has_this = 1;
3269 } else {
3270 if (from_llvm) {
3271 gi->has_this = this_reg != -1;
3272 gi->this_reg = this_reg;
3273 gi->this_offset = this_offset;
3274 } else {
3275 gi->has_this = decode_value (p, &p);
3276 gi->this_reg = decode_value (p, &p);
3277 gi->this_offset = decode_value (p, &p);
3281 len = decode_value (p, &p);
3282 if (async) {
3283 p += len;
3284 } else {
3285 jinfo->d.method = decode_resolve_method_ref (amodule, p, &p, error);
3286 mono_error_cleanup (error); /* FIXME don't swallow the error */
3289 gi->generic_sharing_context = alloc0_jit_info_data (domain, sizeof (MonoGenericSharingContext), async);
3290 if (decode_value (p, &p)) {
3291 /* gsharedvt */
3292 MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
3294 gsctx->is_gsharedvt = TRUE;
3298 if (method && has_seq_points) {
3299 MonoSeqPointInfo *seq_points;
3301 p += mono_seq_point_info_read (&seq_points, p, FALSE);
3303 mono_domain_lock (domain);
3304 /* This could be set already since this function can be called more than once for the same method */
3305 if (!g_hash_table_lookup (domain_jit_info (domain)->seq_points, method))
3306 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
3307 else
3308 mono_seq_point_info_free (seq_points);
3309 mono_domain_unlock (domain);
3312 /* Load debug info */
3313 buf_len = decode_value (p, &p);
3314 if (!async)
3315 mono_debug_add_aot_method (domain, method, code, p, buf_len);
3316 p += buf_len;
3318 if (has_gc_map) {
3319 int map_size = decode_value (p, &p);
3320 /* The GC map requires 4 bytes of alignment */
3321 while ((guint64)(gsize)p % 4)
3322 p ++;
3323 jinfo->gc_info = p;
3324 p += map_size;
3327 if (amodule != m_class_get_image (jinfo->d.method->klass)->aot_module) {
3328 mono_aot_lock ();
3329 if (!ji_to_amodule)
3330 ji_to_amodule = g_hash_table_new (NULL, NULL);
3331 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
3332 mono_aot_unlock ();
3335 return jinfo;
3338 static gboolean
3339 amodule_contains_code_addr (MonoAotModule *amodule, guint8 *code)
3341 return (code >= amodule->jit_code_start && code <= amodule->jit_code_end) ||
3342 (code >= amodule->llvm_code_start && code <= amodule->llvm_code_end);
3346 * mono_aot_get_unwind_info:
3348 * Return a pointer to the DWARF unwind info belonging to JI.
3350 guint8*
3351 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3353 MonoAotModule *amodule;
3354 guint8 *p;
3355 guint8 *code = (guint8 *)ji->code_start;
3357 if (ji->async)
3358 amodule = ji->d.aot_info;
3359 else
3360 amodule = m_class_get_image (jinfo_get_method (ji)->klass)->aot_module;
3361 g_assert (amodule);
3362 g_assert (ji->from_aot);
3364 if (!amodule_contains_code_addr (amodule, code)) {
3365 /* ji belongs to a different aot module than amodule */
3366 mono_aot_lock ();
3367 g_assert (ji_to_amodule);
3368 amodule = (MonoAotModule *)g_hash_table_lookup (ji_to_amodule, ji);
3369 g_assert (amodule);
3370 g_assert (amodule_contains_code_addr (amodule, code));
3371 mono_aot_unlock ();
3374 p = amodule->unwind_info + ji->unwind_info;
3375 *unwind_info_len = decode_value (p, &p);
3376 return p;
3379 static void
3380 msort_method_addresses_internal (gpointer *array, int *indexes, int lo, int hi, gpointer *scratch, int *scratch_indexes)
3382 int mid = (lo + hi) / 2;
3383 int i, t_lo, t_hi;
3385 if (lo >= hi)
3386 return;
3388 if (hi - lo < 32) {
3389 for (i = lo; i < hi; ++i)
3390 if (array [i] > array [i + 1])
3391 break;
3392 if (i == hi)
3393 /* Already sorted */
3394 return;
3397 msort_method_addresses_internal (array, indexes, lo, mid, scratch, scratch_indexes);
3398 msort_method_addresses_internal (array, indexes, mid + 1, hi, scratch, scratch_indexes);
3400 if (array [mid] < array [mid + 1])
3401 return;
3403 /* Merge */
3404 t_lo = lo;
3405 t_hi = mid + 1;
3406 for (i = lo; i <= hi; i ++) {
3407 if (t_lo <= mid && ((t_hi > hi) || array [t_lo] < array [t_hi])) {
3408 scratch [i] = array [t_lo];
3409 scratch_indexes [i] = indexes [t_lo];
3410 t_lo ++;
3411 } else {
3412 scratch [i] = array [t_hi];
3413 scratch_indexes [i] = indexes [t_hi];
3414 t_hi ++;
3417 for (i = lo; i <= hi; ++i) {
3418 array [i] = scratch [i];
3419 indexes [i] = scratch_indexes [i];
3423 static void
3424 msort_method_addresses (gpointer *array, int *indexes, int len)
3426 gpointer *scratch;
3427 int *scratch_indexes;
3429 scratch = g_new (gpointer, len);
3430 scratch_indexes = g_new (int, len);
3431 msort_method_addresses_internal (array, indexes, 0, len - 1, scratch, scratch_indexes);
3432 g_free (scratch);
3433 g_free (scratch_indexes);
3437 * mono_aot_find_jit_info:
3439 * In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
3440 * to the jit info tables.
3441 * FIXME: Large sizes in the lock free allocator
3443 MonoJitInfo *
3444 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3446 ERROR_DECL (error);
3447 int pos, left, right, code_len;
3448 int method_index, table_len;
3449 guint32 token;
3450 MonoAotModule *amodule = image->aot_module;
3451 MonoMethod *method = NULL;
3452 MonoJitInfo *jinfo;
3453 guint8 *code, *ex_info, *p;
3454 guint32 *table;
3455 int nmethods;
3456 gpointer *methods;
3457 guint8 *code1, *code2;
3458 int methods_len, i;
3459 gboolean async;
3461 if (!amodule)
3462 return NULL;
3464 nmethods = amodule->info.nmethods;
3466 if (domain != mono_get_root_domain ())
3467 /* FIXME: */
3468 return NULL;
3470 if (!amodule_contains_code_addr (amodule, (guint8 *)addr))
3471 return NULL;
3473 async = mono_thread_info_is_async_context ();
3475 /* Compute a sorted table mapping code to method indexes. */
3476 if (!amodule->sorted_methods) {
3477 // FIXME: async
3478 gpointer *methods = g_new0 (gpointer, nmethods);
3479 int *method_indexes = g_new0 (int, nmethods);
3480 int methods_len = 0;
3482 for (i = 0; i < nmethods; ++i) {
3483 /* Skip the -1 entries to speed up sorting */
3484 if (amodule->methods [i] == GINT_TO_POINTER (-1))
3485 continue;
3486 methods [methods_len] = amodule->methods [i];
3487 method_indexes [methods_len] = i;
3488 methods_len ++;
3490 /* Use a merge sort as this is mostly sorted */
3491 msort_method_addresses (methods, method_indexes, methods_len);
3492 for (i = 0; i < methods_len -1; ++i)
3493 g_assert (methods [i] <= methods [i + 1]);
3494 amodule->sorted_methods_len = methods_len;
3495 if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_methods, methods, NULL) != NULL)
3496 /* Somebody got in before us */
3497 g_free (methods);
3498 if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_method_indexes, method_indexes, NULL) != NULL)
3499 /* Somebody got in before us */
3500 g_free (method_indexes);
3503 /* Binary search in the sorted_methods table */
3504 methods = amodule->sorted_methods;
3505 methods_len = amodule->sorted_methods_len;
3506 code = (guint8 *)addr;
3507 left = 0;
3508 right = methods_len;
3509 while (TRUE) {
3510 pos = (left + right) / 2;
3512 code1 = (guint8 *)methods [pos];
3513 if (pos + 1 == methods_len) {
3514 if (code1 >= amodule->jit_code_start && code1 < amodule->jit_code_end)
3515 code2 = amodule->jit_code_end;
3516 else
3517 code2 = amodule->llvm_code_end;
3518 } else {
3519 code2 = (guint8 *)methods [pos + 1];
3522 if (code < code1)
3523 right = pos;
3524 else if (code >= code2)
3525 left = pos + 1;
3526 else
3527 break;
3530 g_assert (addr >= methods [pos]);
3531 if (pos + 1 < methods_len)
3532 g_assert (addr < methods [pos + 1]);
3533 method_index = amodule->sorted_method_indexes [pos];
3535 /* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
3536 if (async) {
3537 JitInfoMap *table = amodule->async_jit_info_table;
3538 int len;
3540 if (table) {
3541 len = table [0].method_index;
3542 for (i = 1; i < len; ++i) {
3543 if (table [i].method_index == method_index)
3544 return table [i].jinfo;
3549 code = (guint8 *)amodule->methods [method_index];
3550 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
3552 if (pos == methods_len - 1) {
3553 if (code >= amodule->jit_code_start && code < amodule->jit_code_end)
3554 code_len = amodule->jit_code_end - code;
3555 else
3556 code_len = amodule->llvm_code_end - code;
3557 } else {
3558 code_len = (guint8*)methods [pos + 1] - (guint8*)methods [pos];
3561 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
3563 /* Might be a wrapper/extra method */
3564 if (!async) {
3565 if (amodule->extra_methods) {
3566 amodule_lock (amodule);
3567 method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
3568 amodule_unlock (amodule);
3569 } else {
3570 method = NULL;
3573 if (!method) {
3574 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
3576 * This is hit for extra methods which are called directly, so they are
3577 * not in amodule->extra_methods.
3579 table_len = amodule->extra_method_info_offsets [0];
3580 table = amodule->extra_method_info_offsets + 1;
3581 left = 0;
3582 right = table_len;
3583 pos = 0;
3585 /* Binary search */
3586 while (TRUE) {
3587 pos = ((left + right) / 2);
3589 g_assert (pos < table_len);
3591 if (table [pos * 2] < method_index)
3592 left = pos + 1;
3593 else if (table [pos * 2] > method_index)
3594 right = pos;
3595 else
3596 break;
3599 p = amodule->blob + table [(pos * 2) + 1];
3600 method = decode_resolve_method_ref (amodule, p, &p, error);
3601 mono_error_cleanup (error); /* FIXME don't swallow the error */
3602 if (!method)
3603 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
3604 return NULL;
3605 } else {
3606 ERROR_DECL (error);
3607 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
3608 method = mono_get_method_checked (image, token, NULL, NULL, error);
3609 if (!method)
3610 g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
3613 /* FIXME: */
3614 g_assert (method);
3617 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3619 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, code, code_len);
3621 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
3623 /* Add it to the normal JitInfo tables */
3624 if (async) {
3625 JitInfoMap *old_table, *new_table;
3626 int len;
3629 * Use a simple inmutable table with linear search to cache async jit info entries.
3630 * This assumes that the number of entries is small.
3632 while (TRUE) {
3633 /* Copy the table, adding a new entry at the end */
3634 old_table = amodule->async_jit_info_table;
3635 if (old_table)
3636 len = old_table[0].method_index;
3637 else
3638 len = 1;
3639 new_table = (JitInfoMap *)alloc0_jit_info_data (domain, (len + 1) * sizeof (JitInfoMap), async);
3640 if (old_table)
3641 memcpy (new_table, old_table, len * sizeof (JitInfoMap));
3642 new_table [0].method_index = len + 1;
3643 new_table [len].method_index = method_index;
3644 new_table [len].jinfo = jinfo;
3645 /* Publish it */
3646 mono_memory_barrier ();
3647 if (mono_atomic_cas_ptr ((volatile gpointer *)&amodule->async_jit_info_table, new_table, old_table) == old_table)
3648 break;
3650 } else {
3651 mono_jit_info_table_add (domain, jinfo);
3654 if ((guint8*)addr >= (guint8*)jinfo->code_start + jinfo->code_size)
3655 /* addr is in the padding between methods, see the adjustment of code_size in decode_exception_debug_info () */
3656 return NULL;
3658 return jinfo;
3661 static gboolean
3662 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
3664 ERROR_DECL (error);
3665 guint8 *p = buf;
3666 gpointer *table;
3667 MonoImage *image;
3668 int i;
3670 switch (ji->type) {
3671 case MONO_PATCH_INFO_METHOD:
3672 case MONO_PATCH_INFO_METHOD_JUMP:
3673 case MONO_PATCH_INFO_ICALL_ADDR:
3674 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3675 case MONO_PATCH_INFO_METHOD_RGCTX:
3676 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
3677 MethodRef ref;
3678 gboolean res;
3680 res = decode_method_ref (aot_module, &ref, p, &p, error);
3681 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3682 if (!res)
3683 goto cleanup;
3685 if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
3686 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
3687 ji->type = MONO_PATCH_INFO_ABS;
3689 else {
3690 if (ref.method) {
3691 ji->data.method = ref.method;
3692 }else {
3693 ERROR_DECL (error);
3694 ji->data.method = mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
3695 if (!ji->data.method)
3696 g_error ("AOT Runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
3698 g_assert (ji->data.method);
3699 mono_class_init (ji->data.method->klass);
3701 break;
3703 case MONO_PATCH_INFO_INTERNAL_METHOD:
3704 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3705 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
3706 guint32 len = decode_value (p, &p);
3708 ji->data.name = (char*)p;
3709 p += len + 1;
3710 break;
3712 case MONO_PATCH_INFO_METHODCONST:
3713 /* Shared */
3714 ji->data.method = decode_resolve_method_ref (aot_module, p, &p, error);
3715 mono_error_cleanup (error); /* FIXME don't swallow the error */
3716 if (!ji->data.method)
3717 goto cleanup;
3718 break;
3719 case MONO_PATCH_INFO_VTABLE:
3720 case MONO_PATCH_INFO_CLASS:
3721 case MONO_PATCH_INFO_IID:
3722 case MONO_PATCH_INFO_ADJUSTED_IID:
3723 /* Shared */
3724 ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
3725 mono_error_cleanup (error); /* FIXME don't swallow the error */
3726 if (!ji->data.klass)
3727 goto cleanup;
3728 break;
3729 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3730 ji->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
3731 ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p, error);
3732 mono_error_cleanup (error); /* FIXME don't swallow the error */
3733 if (!ji->data.del_tramp->klass)
3734 goto cleanup;
3735 if (decode_value (p, &p)) {
3736 ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p, error);
3737 mono_error_cleanup (error); /* FIXME don't swallow the error */
3738 if (!ji->data.del_tramp->method)
3739 goto cleanup;
3741 ji->data.del_tramp->is_virtual = decode_value (p, &p) ? TRUE : FALSE;
3742 break;
3743 case MONO_PATCH_INFO_IMAGE:
3744 ji->data.image = load_image (aot_module, decode_value (p, &p), error);
3745 mono_error_cleanup (error); /* FIXME don't swallow the error */
3746 if (!ji->data.image)
3747 goto cleanup;
3748 break;
3749 case MONO_PATCH_INFO_FIELD:
3750 case MONO_PATCH_INFO_SFLDA:
3751 /* Shared */
3752 ji->data.field = decode_field_info (aot_module, p, &p);
3753 if (!ji->data.field)
3754 goto cleanup;
3755 break;
3756 case MONO_PATCH_INFO_SWITCH:
3757 ji->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
3758 ji->data.table->table_size = decode_value (p, &p);
3759 table = (void **)mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
3760 ji->data.table->table = (MonoBasicBlock**)table;
3761 for (i = 0; i < ji->data.table->table_size; i++)
3762 table [i] = (gpointer)(gssize)decode_value (p, &p);
3763 break;
3764 case MONO_PATCH_INFO_R4: {
3765 guint32 val;
3767 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
3768 val = decode_value (p, &p);
3769 *(float*)ji->data.target = *(float*)&val;
3770 break;
3772 case MONO_PATCH_INFO_R8: {
3773 guint32 val [2];
3774 guint64 v;
3776 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
3778 val [0] = decode_value (p, &p);
3779 val [1] = decode_value (p, &p);
3780 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
3781 *(double*)ji->data.target = *(double*)&v;
3782 break;
3784 case MONO_PATCH_INFO_LDSTR:
3785 image = load_image (aot_module, decode_value (p, &p), error);
3786 mono_error_cleanup (error); /* FIXME don't swallow the error */
3787 if (!image)
3788 goto cleanup;
3789 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
3790 break;
3791 case MONO_PATCH_INFO_RVA:
3792 case MONO_PATCH_INFO_DECLSEC:
3793 case MONO_PATCH_INFO_LDTOKEN:
3794 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3795 /* Shared */
3796 image = load_image (aot_module, decode_value (p, &p), error);
3797 mono_error_cleanup (error); /* FIXME don't swallow the error */
3798 if (!image)
3799 goto cleanup;
3800 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
3802 ji->data.token->has_context = decode_value (p, &p);
3803 if (ji->data.token->has_context) {
3804 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p, error);
3805 mono_error_cleanup (error); /* FIXME don't swallow the error */
3806 if (!res)
3807 goto cleanup;
3809 break;
3810 case MONO_PATCH_INFO_EXC_NAME:
3811 ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
3812 mono_error_cleanup (error); /* FIXME don't swallow the error */
3813 if (!ji->data.klass)
3814 goto cleanup;
3815 ji->data.name = m_class_get_name (ji->data.klass);
3816 break;
3817 case MONO_PATCH_INFO_METHOD_REL:
3818 ji->data.offset = decode_value (p, &p);
3819 break;
3820 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3821 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3822 case MONO_PATCH_INFO_GC_NURSERY_START:
3823 case MONO_PATCH_INFO_GC_NURSERY_BITS:
3824 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
3825 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
3826 break;
3827 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3828 ji->data.index = decode_value (p, &p);
3829 break;
3830 case MONO_PATCH_INFO_RGCTX_FETCH:
3831 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
3832 gboolean res;
3833 MonoJumpInfoRgctxEntry *entry;
3834 guint32 offset, val;
3835 guint8 *p2;
3837 offset = decode_value (p, &p);
3838 val = decode_value (p, &p);
3840 entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3841 p2 = aot_module->blob + offset;
3842 entry->method = decode_resolve_method_ref (aot_module, p2, &p2, error);
3843 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
3844 entry->info_type = (MonoRgctxInfoType)((val >> 1) & 0xff);
3845 entry->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3846 entry->data->type = (MonoJumpInfoType)((val >> 9) & 0xff);
3847 mono_error_cleanup (error); /* FIXME don't swallow the error */
3849 res = decode_patch (aot_module, mp, entry->data, p, &p);
3850 if (!res)
3851 goto cleanup;
3852 ji->data.rgctx_entry = entry;
3853 break;
3855 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3856 case MONO_PATCH_INFO_AOT_MODULE:
3857 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3858 break;
3859 case MONO_PATCH_INFO_SIGNATURE:
3860 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
3861 ji->data.target = decode_signature (aot_module, p, &p);
3862 break;
3863 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
3864 MonoJumpInfoGSharedVtCall *info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
3865 info->sig = decode_signature (aot_module, p, &p);
3866 g_assert (info->sig);
3867 info->method = decode_resolve_method_ref (aot_module, p, &p, error);
3868 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3870 ji->data.target = info;
3871 break;
3873 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
3874 MonoGSharedVtMethodInfo *info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
3875 int i;
3877 info->method = decode_resolve_method_ref (aot_module, p, &p, error);
3878 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3880 info->num_entries = decode_value (p, &p);
3881 info->count_entries = info->num_entries;
3882 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
3883 for (i = 0; i < info->num_entries; ++i) {
3884 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
3886 template_->info_type = (MonoRgctxInfoType)decode_value (p, &p);
3887 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
3888 case MONO_PATCH_INFO_CLASS: {
3889 MonoClass *klass = decode_klass_ref (aot_module, p, &p, error);
3890 mono_error_cleanup (error); /* FIXME don't swallow the error */
3891 if (!klass)
3892 goto cleanup;
3893 template_->data = m_class_get_byval_arg (klass);
3894 break;
3896 case MONO_PATCH_INFO_FIELD:
3897 template_->data = decode_field_info (aot_module, p, &p);
3898 if (!template_->data)
3899 goto cleanup;
3900 break;
3901 default:
3902 g_assert_not_reached ();
3903 break;
3906 ji->data.target = info;
3907 break;
3909 case MONO_PATCH_INFO_LDSTR_LIT: {
3910 int len = decode_value (p, &p);
3911 char *s;
3913 s = (char *)mono_mempool_alloc0 (mp, len + 1);
3914 memcpy (s, p, len + 1);
3915 p += len + 1;
3917 ji->data.target = s;
3918 break;
3920 case MONO_PATCH_INFO_VIRT_METHOD: {
3921 MonoJumpInfoVirtMethod *info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
3923 info->klass = decode_klass_ref (aot_module, p, &p, error);
3924 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3926 info->method = decode_resolve_method_ref (aot_module, p, &p, error);
3927 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3929 ji->data.target = info;
3930 break;
3932 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
3933 break;
3934 case MONO_PATCH_INFO_GET_TLS_TRAMP:
3935 case MONO_PATCH_INFO_SET_TLS_TRAMP:
3936 case MONO_PATCH_INFO_AOT_JIT_INFO:
3937 ji->data.index = decode_value (p, &p);
3938 break;
3939 default:
3940 g_warning ("unhandled type %d", ji->type);
3941 g_assert_not_reached ();
3944 *endbuf = p;
3946 return TRUE;
3948 cleanup:
3949 return FALSE;
3953 * decode_patches:
3955 * Decode a list of patches identified by the got offsets in GOT_OFFSETS. Return an array of
3956 * MonoJumpInfo structures allocated from MP.
3958 static MonoJumpInfo*
3959 decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets)
3961 MonoJumpInfo *patches;
3962 MonoJumpInfo *ji;
3963 gpointer *got;
3964 guint32 *got_info_offsets;
3965 int i;
3966 gboolean res;
3968 if (llvm) {
3969 got = amodule->llvm_got;
3970 got_info_offsets = (guint32 *)amodule->llvm_got_info_offsets;
3971 } else {
3972 got = amodule->got;
3973 got_info_offsets = (guint32 *)amodule->got_info_offsets;
3976 patches = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
3977 for (i = 0; i < n_patches; ++i) {
3978 guint8 *p = amodule->blob + mono_aot_get_offset (got_info_offsets, got_offsets [i]);
3980 ji = &patches [i];
3981 ji->type = (MonoJumpInfoType)decode_value (p, &p);
3983 /* See load_method () for SFLDA */
3984 if (got && got [got_offsets [i]] && ji->type != MONO_PATCH_INFO_SFLDA) {
3985 /* Already loaded */
3986 } else {
3987 res = decode_patch (amodule, mp, ji, p, &p);
3988 if (!res)
3989 return NULL;
3993 return patches;
3996 static MonoJumpInfo*
3997 load_patch_info (MonoAotModule *amodule, MonoMemPool *mp, int n_patches,
3998 gboolean llvm, guint32 **got_slots,
3999 guint8 *buf, guint8 **endbuf)
4001 MonoJumpInfo *patches;
4002 int pindex;
4003 guint8 *p;
4005 p = buf;
4007 *got_slots = (guint32 *)g_malloc (sizeof (guint32) * n_patches);
4008 for (pindex = 0; pindex < n_patches; ++pindex) {
4009 (*got_slots)[pindex] = decode_value (p, &p);
4012 patches = decode_patches (amodule, mp, n_patches, llvm, *got_slots);
4013 if (!patches) {
4014 g_free (*got_slots);
4015 *got_slots = NULL;
4016 return NULL;
4019 *endbuf = p;
4020 return patches;
4023 static void
4024 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
4027 * Jump addresses cannot be patched by the trampoline code since it
4028 * does not have access to the caller's address. Instead, we collect
4029 * the addresses of the GOT slots pointing to a method, and patch
4030 * them after the method has been compiled.
4032 MonoJitDomainInfo *info = domain_jit_info (domain);
4033 GSList *list;
4034 MonoMethod *shared_method = mini_method_to_shared (method);
4035 method = shared_method ? shared_method : method;
4037 mono_domain_lock (domain);
4038 if (!info->jump_target_got_slot_hash)
4039 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
4040 list = (GSList *)g_hash_table_lookup (info->jump_target_got_slot_hash, method);
4041 list = g_slist_prepend (list, got_slot);
4042 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
4043 mono_domain_unlock (domain);
4047 * load_method:
4049 * Load the method identified by METHOD_INDEX from the AOT image. Return a
4050 * pointer to the native code of the method, or NULL if not found.
4051 * METHOD might not be set if the caller only has the image/token info.
4053 static gpointer
4054 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index,
4055 MonoError *error)
4057 MonoJitInfo *jinfo = NULL;
4058 guint8 *code = NULL, *info;
4059 gboolean res;
4061 error_init (error);
4063 init_amodule_got (amodule);
4065 if (domain != mono_get_root_domain ())
4066 /* Non shared AOT code can't be used in other appdomains */
4067 return NULL;
4069 if (amodule->out_of_date)
4070 return NULL;
4072 if (amodule->info.llvm_get_method) {
4074 * Obtain the method address by calling a generated function in the LLVM module.
4076 gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
4077 code = (guint8 *)get_method (method_index);
4080 if (!code) {
4081 /* JITted method */
4082 if (amodule->methods [method_index] == GINT_TO_POINTER (-1)) {
4083 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
4084 char *full_name;
4086 if (!method) {
4087 method = mono_get_method_checked (image, token, NULL, NULL, error);
4088 if (!method)
4089 return NULL;
4091 if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4092 full_name = mono_method_full_name (method, TRUE);
4093 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: NOT FOUND: %s.", full_name);
4094 g_free (full_name);
4097 return NULL;
4099 if (method_index < amodule->info.nmethods)
4100 code = (guint8 *)amodule->methods [method_index];
4103 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
4105 if (!amodule->methods_loaded) {
4106 amodule_lock (amodule);
4107 if (!amodule->methods_loaded) {
4108 guint32 *loaded;
4110 loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
4111 mono_memory_barrier ();
4112 amodule->methods_loaded = loaded;
4114 amodule_unlock (amodule);
4117 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
4118 return code;
4120 if (mini_debug_options.aot_skip_set && !(method && method->wrapper_type)) {
4121 gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
4122 if (methods_aot == mini_debug_options.aot_skip) {
4123 if (!method) {
4124 method = mono_get_method_checked (image, token, NULL, NULL, error);
4125 if (!method)
4126 return NULL;
4128 if (method) {
4129 char *name = mono_method_full_name (method, TRUE);
4130 g_print ("NON AOT METHOD: %s.\n", name);
4131 g_free (name);
4132 } else {
4133 g_print ("NON AOT METHOD: %p %d\n", code, method_index);
4135 mini_debug_options.aot_skip_set = FALSE;
4136 return NULL;
4140 if (mono_last_aot_method != -1) {
4141 gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
4142 if (methods_aot >= mono_last_aot_method)
4143 return NULL;
4144 else if (methods_aot == mono_last_aot_method - 1) {
4145 if (!method) {
4146 method = mono_get_method_checked (image, token, NULL, NULL, error);
4147 if (!method)
4148 return NULL;
4150 if (method) {
4151 char *name = mono_method_full_name (method, TRUE);
4152 g_print ("LAST AOT METHOD: %s.\n", name);
4153 g_free (name);
4154 } else {
4155 g_print ("LAST AOT METHOD: %p %d\n", code, method_index);
4160 if (!(is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) ||
4161 (mono_llvm_only && method && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)) {
4162 res = init_method (amodule, method_index, method, NULL, NULL, error);
4163 if (!res)
4164 goto cleanup;
4167 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
4168 char *full_name;
4170 if (!method) {
4171 method = mono_get_method_checked (image, token, NULL, NULL, error);
4172 if (!method)
4173 return NULL;
4176 full_name = mono_method_full_name (method, TRUE);
4178 if (!jinfo)
4179 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
4181 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
4182 g_free (full_name);
4185 amodule_lock (amodule);
4187 init_plt (amodule);
4189 mono_atomic_inc_i32 (&mono_jit_stats.methods_aot);
4191 if (method && method->wrapper_type)
4192 g_hash_table_insert (amodule->method_to_code, method, code);
4194 /* Commit changes since methods_loaded is accessed outside the lock */
4195 mono_memory_barrier ();
4197 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
4199 amodule_unlock (amodule);
4201 if (MONO_PROFILER_ENABLED (jit_begin) || MONO_PROFILER_ENABLED (jit_done)) {
4202 MonoJitInfo *jinfo;
4204 if (!method) {
4205 method = mono_get_method_checked (amodule->assembly->image, token, NULL, NULL, error);
4206 if (!method)
4207 return NULL;
4209 MONO_PROFILER_RAISE (jit_begin, (method));
4210 jinfo = mono_jit_info_table_find (domain, code);
4211 g_assert (jinfo);
4212 MONO_PROFILER_RAISE (jit_done, (method, jinfo));
4215 return code;
4217 cleanup:
4218 if (jinfo)
4219 g_free (jinfo);
4221 return NULL;
4224 /** find_aot_method_in_amodule
4226 * \param code_amodule The AOT module containing the code pointer
4227 * \param method The method to find the code index for
4228 * \param hash_full The hash for the method
4230 static guint32
4231 find_aot_method_in_amodule (MonoAotModule *code_amodule, MonoMethod *method, guint32 hash_full)
4233 ERROR_DECL (error);
4234 guint32 table_size, entry_size, hash;
4235 guint32 *table, *entry;
4236 guint32 index;
4237 static guint32 n_extra_decodes;
4239 // The AOT module containing the MonoMethod
4240 // The reference to the metadata amodule will differ among multiple dedup methods
4241 // which mangle to the same name but live in different assemblies. This leads to
4242 // the caching breaking. The solution seems to be to cache using the "metadata" amodule.
4243 MonoAotModule *metadata_amodule = m_class_get_image (method->klass)->aot_module;
4245 if (!metadata_amodule || metadata_amodule->out_of_date || !code_amodule || code_amodule->out_of_date)
4246 return 0xffffff;
4248 table_size = code_amodule->extra_method_table [0];
4249 hash = hash_full % table_size;
4250 table = code_amodule->extra_method_table + 1;
4251 entry_size = 3;
4253 entry = &table [hash * entry_size];
4255 if (entry [0] == 0)
4256 return 0xffffff;
4258 index = 0xffffff;
4259 while (TRUE) {
4260 guint32 key = entry [0];
4261 guint32 value = entry [1];
4262 guint32 next = entry [entry_size - 1];
4263 MonoMethod *m;
4264 guint8 *p, *orig_p;
4266 p = code_amodule->blob + key;
4267 orig_p = p;
4269 amodule_lock (metadata_amodule);
4270 if (!metadata_amodule->method_ref_to_method)
4271 metadata_amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
4272 m = (MonoMethod *)g_hash_table_lookup (metadata_amodule->method_ref_to_method, p);
4273 amodule_unlock (metadata_amodule);
4274 if (!m) {
4275 m = decode_resolve_method_ref_with_target (code_amodule, method, p, &p, error);
4276 mono_error_cleanup (error); /* FIXME don't swallow the error */
4278 * Can't catche runtime invoke wrappers since it would break
4279 * the check in decode_method_ref_with_target ().
4281 if (m && m->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
4282 amodule_lock (metadata_amodule);
4283 g_hash_table_insert (metadata_amodule->method_ref_to_method, orig_p, m);
4284 amodule_unlock (metadata_amodule);
4287 if (m == method) {
4288 index = value;
4289 break;
4292 /* Methods decoded needlessly */
4293 if (m) {
4294 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
4295 n_extra_decodes ++;
4298 if (next != 0)
4299 entry = &table [next * entry_size];
4300 else
4301 break;
4304 if (index != 0xffffff)
4305 g_assert (index < code_amodule->info.nmethods);
4307 return index;
4310 static void
4311 add_module_cb (gpointer key, gpointer value, gpointer user_data)
4313 g_ptr_array_add ((GPtrArray*)user_data, value);
4316 gboolean
4317 mono_aot_can_dedup (MonoMethod *method)
4319 gboolean not_normal_gshared = method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE);
4320 gboolean extra_method = (method->wrapper_type != MONO_WRAPPER_NONE) || not_normal_gshared;
4322 return extra_method;
4327 * find_aot_method:
4329 * Try finding METHOD in the extra_method table in all AOT images.
4330 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
4331 * module where the method was found.
4333 static guint32
4334 find_aot_method (MonoMethod *method, MonoAotModule **out_amodule)
4336 guint32 index;
4337 GPtrArray *modules;
4338 int i;
4339 guint32 hash = mono_aot_method_hash (method);
4341 /* Try the place we expect to have moved the method only
4342 * We don't probe, as that causes hard-to-debug issues when we fail
4343 * to find the method */
4344 if (container_amodule && mono_aot_can_dedup (method)) {
4345 *out_amodule = container_amodule;
4346 index = find_aot_method_in_amodule (container_amodule, method, hash);
4347 return index;
4350 /* Try the method's module first */
4351 *out_amodule = m_class_get_image (method->klass)->aot_module;
4352 index = find_aot_method_in_amodule (m_class_get_image (method->klass)->aot_module, method, hash);
4353 if (index != 0xffffff)
4354 return index;
4357 * Try all other modules.
4358 * This is needed because generic instances klass->image points to the image
4359 * containing the generic definition, but the native code is generated to the
4360 * AOT image which contains the reference.
4363 /* Make a copy to avoid doing the search inside the aot lock */
4364 modules = g_ptr_array_new ();
4365 mono_aot_lock ();
4366 g_hash_table_foreach (aot_modules, add_module_cb, modules);
4367 mono_aot_unlock ();
4369 index = 0xffffff;
4370 for (i = 0; i < modules->len; ++i) {
4371 MonoAotModule *amodule = (MonoAotModule *)g_ptr_array_index (modules, i);
4373 if (amodule != m_class_get_image (method->klass)->aot_module)
4374 index = find_aot_method_in_amodule (amodule, method, hash);
4375 if (index != 0xffffff) {
4376 *out_amodule = amodule;
4377 break;
4381 g_ptr_array_free (modules, TRUE);
4383 return index;
4386 guint32
4387 mono_aot_find_method_index (MonoMethod *method)
4389 MonoAotModule *out_amodule;
4390 return find_aot_method (method, &out_amodule);
4393 static gboolean
4394 init_method (MonoAotModule *amodule, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoGenericContext *context, MonoError *error)
4396 MonoDomain *domain = mono_domain_get ();
4397 MonoMemPool *mp;
4398 MonoClass *klass_to_run_ctor = NULL;
4399 gboolean from_plt = method == NULL;
4400 int pindex, n_patches;
4401 guint8 *p;
4402 MonoJitInfo *jinfo = NULL;
4403 guint8 *code, *info;
4405 error_init (error);
4407 code = (guint8 *)amodule->methods [method_index];
4408 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
4410 p = info;
4412 //does the method's class has a cctor?
4413 if (decode_value (p, &p) == 1)
4414 klass_to_run_ctor = decode_klass_ref (amodule, p, &p, error);
4415 if (!is_ok (error))
4416 return FALSE;
4418 //FIXME old code would use the class from @method if not null and ignore the one encoded. I don't know if we need to honor that -- @kumpera
4419 if (method)
4420 klass_to_run_ctor = method->klass;
4422 n_patches = decode_value (p, &p);
4424 if (n_patches) {
4425 MonoJumpInfo *patches;
4426 guint32 *got_slots;
4427 gboolean llvm;
4428 gpointer *got;
4430 mp = mono_mempool_new ();
4432 if ((gpointer)code >= amodule->info.jit_code_start && (gpointer)code <= amodule->info.jit_code_end) {
4433 llvm = FALSE;
4434 got = amodule->got;
4435 } else {
4436 llvm = TRUE;
4437 got = amodule->llvm_got;
4438 g_assert (got);
4441 patches = load_patch_info (amodule, mp, n_patches, llvm, &got_slots, p, &p);
4442 if (patches == NULL) {
4443 mono_mempool_destroy (mp);
4444 goto cleanup;
4447 for (pindex = 0; pindex < n_patches; ++pindex) {
4448 MonoJumpInfo *ji = &patches [pindex];
4449 gpointer addr;
4452 * For SFLDA, we need to call resolve_patch_target () since the GOT slot could have
4453 * been initialized by load_method () for a static cctor before the cctor has
4454 * finished executing (#23242).
4456 if (!got [got_slots [pindex]] || ji->type == MONO_PATCH_INFO_SFLDA) {
4457 /* In llvm-only made, we might encounter shared methods */
4458 if (mono_llvm_only && ji->type == MONO_PATCH_INFO_METHOD && mono_method_check_context_used (ji->data.method)) {
4459 g_assert (context);
4460 ji->data.method = mono_class_inflate_generic_method_checked (ji->data.method, context, error);
4461 if (!mono_error_ok (error)) {
4462 g_free (got_slots);
4463 mono_mempool_destroy (mp);
4464 return FALSE;
4467 /* This cannot be resolved in mono_resolve_patch_target () */
4468 if (ji->type == MONO_PATCH_INFO_AOT_JIT_INFO) {
4469 // FIXME: Lookup using the index
4470 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
4471 ji->type = MONO_PATCH_INFO_ABS;
4472 ji->data.target = jinfo;
4474 addr = mono_resolve_patch_target (method, domain, code, ji, TRUE, error);
4475 if (!mono_error_ok (error)) {
4476 g_free (got_slots);
4477 mono_mempool_destroy (mp);
4478 return FALSE;
4480 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
4481 addr = mono_create_ftnptr (domain, addr);
4482 mono_memory_barrier ();
4483 got [got_slots [pindex]] = addr;
4484 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
4485 register_jump_target_got_slot (domain, ji->data.method, &(got [got_slots [pindex]]));
4487 ji->type = MONO_PATCH_INFO_NONE;
4490 g_free (got_slots);
4492 mono_mempool_destroy (mp);
4495 if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
4496 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
4498 gboolean inited_ok;
4499 inited_ok = TRUE;
4500 if (init_class) {
4501 MonoVTable *vt = mono_class_vtable_checked (domain, init_class, error);
4502 if (!is_ok (error))
4503 inited_ok = FALSE;
4504 else
4505 inited_ok = mono_runtime_class_init_full (vt, error);
4506 } else if (from_plt && klass_to_run_ctor && !mono_class_is_gtd (klass_to_run_ctor)) {
4507 MonoVTable *vt = mono_class_vtable_checked (domain, klass_to_run_ctor, error);
4508 if (!is_ok (error))
4509 inited_ok = FALSE;
4510 else
4511 inited_ok = mono_runtime_class_init_full (vt, error);
4513 if (!inited_ok)
4514 return FALSE;
4516 return TRUE;
4518 cleanup:
4519 if (jinfo)
4520 g_free (jinfo);
4522 return FALSE;
4525 static void
4526 init_llvmonly_method (MonoAotModule *amodule, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoGenericContext *context)
4528 ERROR_DECL (error);
4530 init_method (amodule, method_index, method, init_class, context, error);
4531 if (!is_ok (error)) {
4532 MonoException *ex = mono_error_convert_to_exception (error);
4533 /* Its okay to raise in llvmonly mode */
4534 if (ex)
4535 mono_llvm_throw_exception ((MonoObject*)ex);
4539 void
4540 mono_aot_init_llvm_method (gpointer aot_module, guint32 method_index)
4542 MonoAotModule *amodule = (MonoAotModule *)aot_module;
4544 init_llvmonly_method (amodule, method_index, NULL, NULL, NULL);
4547 void
4548 mono_aot_init_gshared_method_this (gpointer aot_module, guint32 method_index, MonoObject *this_obj)
4550 MonoAotModule *amodule = (MonoAotModule *)aot_module;
4551 MonoClass *klass;
4552 MonoGenericContext *context;
4553 MonoMethod *method;
4555 // FIXME:
4556 g_assert (this_obj);
4557 klass = this_obj->vtable->klass;
4559 amodule_lock (amodule);
4560 method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
4561 amodule_unlock (amodule);
4563 g_assert (method);
4564 context = mono_method_get_context (method);
4565 g_assert (context);
4567 init_llvmonly_method (amodule, method_index, NULL, klass, context);
4570 void
4571 mono_aot_init_gshared_method_mrgctx (gpointer aot_module, guint32 method_index, MonoMethodRuntimeGenericContext *rgctx)
4573 MonoAotModule *amodule = (MonoAotModule *)aot_module;
4574 MonoGenericContext context = { NULL, NULL };
4575 MonoClass *klass = rgctx->class_vtable->klass;
4577 if (mono_class_is_ginst (klass))
4578 context.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
4579 else if (mono_class_is_gtd (klass))
4580 context.class_inst = mono_class_get_generic_container (klass)->context.class_inst;
4581 context.method_inst = rgctx->method_inst;
4583 init_llvmonly_method (amodule, method_index, NULL, rgctx->class_vtable->klass, &context);
4586 void
4587 mono_aot_init_gshared_method_vtable (gpointer aot_module, guint32 method_index, MonoVTable *vtable)
4589 MonoAotModule *amodule = (MonoAotModule *)aot_module;
4590 MonoClass *klass;
4591 MonoGenericContext *context;
4592 MonoMethod *method;
4594 klass = vtable->klass;
4596 amodule_lock (amodule);
4597 method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
4598 amodule_unlock (amodule);
4600 g_assert (method);
4601 context = mono_method_get_context (method);
4602 g_assert (context);
4604 init_llvmonly_method (amodule, method_index, NULL, klass, context);
4608 * mono_aot_get_method:
4610 * Return a pointer to the AOTed native code for METHOD if it can be found,
4611 * NULL otherwise.
4612 * On platforms with function pointers, this doesn't return a function pointer.
4614 gpointer
4615 mono_aot_get_method (MonoDomain *domain, MonoMethod *method, MonoError *error)
4617 MonoClass *klass = method->klass;
4618 MonoMethod *orig_method = method;
4619 guint32 method_index;
4620 MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
4621 guint8 *code;
4622 gboolean cache_result = FALSE;
4623 ERROR_DECL_VALUE (inner_error);
4625 error_init (error);
4627 if (domain != mono_get_root_domain ())
4628 /* Non shared AOT code can't be used in other appdomains */
4629 return NULL;
4631 if (enable_aot_cache && !amodule && domain->entry_assembly && m_class_get_image (klass) == mono_defaults.corlib) {
4632 /* This cannot be AOTed during startup, so do it now */
4633 if (!mscorlib_aot_loaded) {
4634 mscorlib_aot_loaded = TRUE;
4635 load_aot_module (m_class_get_image (klass)->assembly, NULL);
4636 amodule = m_class_get_image (klass)->aot_module;
4640 if (!amodule)
4641 return NULL;
4643 if (amodule->out_of_date)
4644 return NULL;
4646 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4647 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4648 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4649 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4650 return NULL;
4653 * Use the original method instead of its invoke-with-check wrapper.
4654 * This is not a problem when using full-aot, since it doesn't support
4655 * remoting.
4657 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4658 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method), error);
4660 g_assert (m_class_is_inited (klass));
4662 /* Find method index */
4663 method_index = 0xffffff;
4665 gboolean dedupable = mono_aot_can_dedup (method);
4667 if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) && !dedupable) {
4668 MonoMethod *orig_method = method;
4670 * For generic methods, we store the fully shared instance in place of the
4671 * original method.
4673 method = mono_method_get_declaring_generic_method (method);
4674 method_index = mono_metadata_token_index (method->token) - 1;
4676 if (mono_llvm_only) {
4677 /* Needed by mono_aot_init_gshared_method_this () */
4678 /* orig_method is a random instance but it is enough to make init_method () work */
4679 amodule_lock (amodule);
4680 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), orig_method);
4681 amodule_unlock (amodule);
4685 if (method_index == 0xffffff && (method->is_inflated || !method->token)) {
4686 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
4687 amodule_lock (amodule);
4688 code = (guint8 *)g_hash_table_lookup (amodule->method_to_code, method);
4689 amodule_unlock (amodule);
4690 if (code)
4691 return code;
4693 cache_result = TRUE;
4694 if (method_index == 0xffffff)
4695 method_index = find_aot_method (method, &amodule);
4698 * Special case the ICollection<T> wrappers for arrays, as they cannot
4699 * be statically enumerated, and each wrapper ends up calling the same
4700 * method in Array.
4702 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && m_class_get_rank (method->klass) && strstr (method->name, "System.Collections.Generic")) {
4703 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4705 code = (guint8 *)mono_aot_get_method (domain, m, &inner_error);
4706 mono_error_cleanup (&inner_error);
4707 if (code)
4708 return code;
4712 * Special case Array.GetGenericValueImpl which is a generic icall.
4713 * Generic sharing currently can't handle it, but the icall returns data using
4714 * an out parameter, so the managed-to-native wrappers can share the same code.
4716 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
4717 MonoMethod *m;
4718 MonoGenericContext ctx;
4719 MonoType *args [16];
4721 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
4722 /* Avoid recursion */
4723 return NULL;
4725 m = mono_class_get_method_from_name_checked (mono_defaults.array_class, "GetGenericValueImpl", 2, 0, error);
4726 mono_error_assert_ok (error);
4727 g_assert (m);
4729 memset (&ctx, 0, sizeof (ctx));
4730 args [0] = m_class_get_byval_arg (mono_defaults.object_class);
4731 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4733 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE);
4734 if (!m)
4735 g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
4738 * Get the code for the <object> instantiation which should be emitted into
4739 * the mscorlib aot image by the AOT compiler.
4741 code = (guint8 *)mono_aot_get_method (domain, m, &inner_error);
4742 mono_error_cleanup (&inner_error);
4743 if (code)
4744 return code;
4747 const char *klass_name_space = m_class_get_name_space (method->klass);
4748 const char *klass_name = m_class_get_name (method->klass);
4749 /* Same for CompareExchange<T> and Exchange<T> */
4750 /* Same for Volatile.Read<T>/Write<T> */
4751 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && m_class_get_image (method->klass) == mono_defaults.corlib &&
4752 ((!strcmp (klass_name_space, "System.Threading") && !strcmp (klass_name, "Interlocked") && (!strcmp (method->name, "CompareExchange") || !strcmp (method->name, "Exchange")) && MONO_TYPE_IS_REFERENCE (mini_type_get_underlying_type (mono_method_signature (method)->params [1]))) ||
4753 (!strcmp (klass_name_space, "System.Threading") && !strcmp (klass_name, "Volatile") && (!strcmp (method->name, "Read") && MONO_TYPE_IS_REFERENCE (mini_type_get_underlying_type (mono_method_signature (method)->ret)))) ||
4754 (!strcmp (klass_name_space, "System.Threading") && !strcmp (klass_name, "Volatile") && (!strcmp (method->name, "Write") && MONO_TYPE_IS_REFERENCE (mini_type_get_underlying_type (mono_method_signature (method)->params [1])))))) {
4755 MonoMethod *m;
4756 MonoGenericContext ctx;
4757 MonoType *args [16];
4758 gpointer iter = NULL;
4760 while ((m = mono_class_get_methods (method->klass, &iter))) {
4761 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
4762 break;
4764 g_assert (m);
4766 memset (&ctx, 0, sizeof (ctx));
4767 args [0] = mono_get_object_type ();
4768 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4770 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE);
4771 if (!m)
4772 g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
4774 /* Avoid recursion */
4775 if (method == m)
4776 return NULL;
4779 * Get the code for the <object> instantiation which should be emitted into
4780 * the mscorlib aot image by the AOT compiler.
4782 code = (guint8 *)mono_aot_get_method (domain, m, &inner_error);
4783 mono_error_cleanup (&inner_error);
4784 if (code)
4785 return code;
4788 /* For ARRAY_ACCESSOR wrappers with reference types, use the <object> instantiation saved in corlib */
4789 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
4790 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4792 if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
4793 MonoMethod *array_method = info->d.array_accessor.method;
4794 if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (m_class_get_element_class (array_method->klass)))) {
4795 int rank;
4797 if (!strcmp (array_method->name, "Set"))
4798 rank = mono_method_signature (array_method)->param_count - 1;
4799 else if (!strcmp (array_method->name, "Get") || !strcmp (array_method->name, "Address"))
4800 rank = mono_method_signature (array_method)->param_count;
4801 else
4802 g_assert_not_reached ();
4803 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, rank);
4804 MonoMethod *m = mono_class_get_method_from_name_checked (obj_array_class, array_method->name, mono_method_signature (array_method)->param_count, 0, error);
4805 mono_error_assert_ok (error);
4806 g_assert (m);
4808 m = mono_marshal_get_array_accessor_wrapper (m);
4809 if (m != method) {
4810 code = (guint8 *)mono_aot_get_method (domain, m, &inner_error);
4811 mono_error_cleanup (&inner_error);
4812 if (code)
4813 return code;
4819 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
4820 /* Partial sharing */
4821 MonoMethod *shared;
4823 shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4824 return_val_if_nok (error, NULL);
4826 method_index = find_aot_method (shared, &amodule);
4827 if (method_index != 0xffffff)
4828 method = shared;
4831 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4832 MonoMethod *shared;
4833 /* gsharedvt */
4834 /* Use the all-vt shared method since this is what was AOTed */
4835 shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4836 if (!shared)
4837 return NULL;
4839 method_index = find_aot_method (shared, &amodule);
4840 if (method_index != 0xffffff) {
4841 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4842 if (!method)
4843 return NULL;
4847 if (method_index == 0xffffff) {
4848 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
4849 char *full_name;
4851 full_name = mono_method_full_name (method, TRUE);
4852 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
4853 g_free (full_name);
4855 return NULL;
4858 if (method_index == 0xffffff)
4859 return NULL;
4861 /* Needed by find_jit_info */
4862 amodule_lock (amodule);
4863 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
4864 amodule_unlock (amodule);
4865 } else {
4866 /* Common case */
4867 method_index = mono_metadata_token_index (method->token) - 1;
4869 guint32 num_methods = amodule->info.nmethods - amodule->info.nextra_methods;
4870 if (method_index >= num_methods)
4871 /* method not available in AOT image */
4872 return NULL;
4875 code = (guint8 *)load_method (domain, amodule, m_class_get_image (klass), method, method->token, method_index, error);
4876 if (!is_ok (error))
4877 return NULL;
4878 if (code && cache_result) {
4879 amodule_lock (amodule);
4880 g_hash_table_insert (amodule->method_to_code, orig_method, code);
4881 amodule_unlock (amodule);
4883 return code;
4887 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
4888 * method.
4890 gpointer
4891 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token, MonoError *error)
4893 MonoAotModule *aot_module = image->aot_module;
4894 int method_index;
4895 gpointer res;
4897 error_init (error);
4899 if (!aot_module)
4900 return NULL;
4902 method_index = mono_metadata_token_index (token) - 1;
4904 res = load_method (domain, aot_module, image, NULL, token, method_index, error);
4905 return res;
4908 typedef struct {
4909 guint8 *addr;
4910 gboolean res;
4911 } IsGotEntryUserData;
4913 static void
4914 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
4916 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
4917 MonoAotModule *aot_module = (MonoAotModule*)value;
4919 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
4920 data->res = TRUE;
4923 gboolean
4924 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4926 IsGotEntryUserData user_data;
4928 if (!aot_modules)
4929 return FALSE;
4931 user_data.addr = addr;
4932 user_data.res = FALSE;
4933 mono_aot_lock ();
4934 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
4935 mono_aot_unlock ();
4937 return user_data.res;
4940 typedef struct {
4941 guint8 *addr;
4942 MonoAotModule *module;
4943 } FindAotModuleUserData;
4945 static void
4946 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
4948 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
4949 MonoAotModule *aot_module = (MonoAotModule*)value;
4951 if (amodule_contains_code_addr (aot_module, data->addr))
4952 data->module = aot_module;
4955 static inline MonoAotModule*
4956 find_aot_module (guint8 *code)
4958 FindAotModuleUserData user_data;
4960 if (!aot_modules)
4961 return NULL;
4963 /* Reading these need no locking */
4964 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
4965 return NULL;
4967 user_data.addr = code;
4968 user_data.module = NULL;
4970 mono_aot_lock ();
4971 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
4972 mono_aot_unlock ();
4974 return user_data.module;
4977 void
4978 mono_aot_patch_plt_entry (guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
4980 MonoAotModule *amodule;
4983 * Since AOT code is only used in the root domain,
4984 * mono_domain_get () != mono_get_root_domain () means the calling method
4985 * is AppDomain:InvokeInDomain, so this is the same check as in
4986 * mono_method_same_domain () but without loading the metadata for the method.
4988 if (mono_domain_get () == mono_get_root_domain ()) {
4989 if (!got) {
4990 amodule = find_aot_module (code);
4991 if (amodule)
4992 got = amodule->got;
4994 mono_arch_patch_plt_entry (plt_entry, got, regs, addr);
4999 * mono_aot_plt_resolve:
5001 * This function is called by the entries in the PLT to resolve the actual method that
5002 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
5003 * Returns NULL if the something cannot be loaded.
5005 gpointer
5006 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code, MonoError *error)
5008 #ifdef MONO_ARCH_AOT_SUPPORTED
5009 guint8 *p, *target, *plt_entry;
5010 MonoJumpInfo ji;
5011 MonoAotModule *module = (MonoAotModule*)aot_module;
5012 gboolean res, no_ftnptr = FALSE;
5013 MonoMemPool *mp;
5014 gboolean using_gsharedvt = FALSE;
5016 error_init (error);
5018 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
5020 p = &module->blob [plt_info_offset];
5022 ji.type = (MonoJumpInfoType)decode_value (p, &p);
5024 mp = mono_mempool_new ();
5025 res = decode_patch (module, mp, &ji, p, &p);
5027 if (!res) {
5028 mono_mempool_destroy (mp);
5029 return NULL;
5032 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5033 using_gsharedvt = TRUE;
5034 #endif
5037 * Avoid calling resolve_patch_target in the full-aot case if possible, since
5038 * it would create a trampoline, and we don't need that.
5039 * We could do this only if the method does not need the special handling
5040 * in mono_magic_trampoline ().
5042 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) &&
5043 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
5044 target = (guint8 *)mono_jit_compile_method (ji.data.method, error);
5045 if (!mono_error_ok (error)) {
5046 mono_mempool_destroy (mp);
5047 return NULL;
5049 no_ftnptr = TRUE;
5050 } else {
5051 target = (guint8 *)mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE, error);
5052 if (!mono_error_ok (error)) {
5053 mono_mempool_destroy (mp);
5054 return NULL;
5059 * The trampoline expects us to return a function descriptor on platforms which use
5060 * it, but resolve_patch_target returns a direct function pointer for some type of
5061 * patches, so have to translate between the two.
5062 * FIXME: Clean this up, but how ?
5064 if (ji.type == MONO_PATCH_INFO_ABS || ji.type == MONO_PATCH_INFO_INTERNAL_METHOD || ji.type == MONO_PATCH_INFO_ICALL_ADDR || ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR || ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
5065 /* These should already have a function descriptor */
5066 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5067 /* Our function descriptors have a 0 environment, gcc created ones don't */
5068 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
5069 g_assert (((gpointer*)target) [2] == 0);
5070 #endif
5071 /* Empty */
5072 } else if (!no_ftnptr) {
5073 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5074 g_assert (((gpointer*)target) [2] != 0);
5075 #endif
5076 target = (guint8 *)mono_create_ftnptr (mono_domain_get (), target);
5079 mono_mempool_destroy (mp);
5081 /* Patch the PLT entry with target which might be the actual method not a trampoline */
5082 plt_entry = mono_aot_get_plt_entry (code);
5083 g_assert (plt_entry);
5084 mono_aot_patch_plt_entry (code, plt_entry, module->got, NULL, target);
5086 return target;
5087 #else
5088 g_assert_not_reached ();
5089 return NULL;
5090 #endif
5094 * init_plt:
5096 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
5097 * method in the module is loaded to avoid committing memory by writing to it.
5098 * LOCKING: Assumes the AMODULE lock is held.
5100 static void
5101 init_plt (MonoAotModule *amodule)
5103 int i;
5104 gpointer tramp;
5106 if (amodule->plt_inited)
5107 return;
5109 if (amodule->info.plt_size <= 1) {
5110 amodule->plt_inited = TRUE;
5111 return;
5114 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
5117 * Initialize the PLT entries in the GOT to point to the default targets.
5120 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
5121 for (i = 1; i < amodule->info.plt_size; ++i)
5122 /* All the default entries point to the AOT trampoline */
5123 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
5125 amodule->plt_inited = TRUE;
5129 * mono_aot_get_plt_entry:
5131 * Return the address of the PLT entry called by the code at CODE if exists.
5133 guint8*
5134 mono_aot_get_plt_entry (guint8 *code)
5136 MonoAotModule *amodule = find_aot_module (code);
5137 guint8 *target = NULL;
5139 if (!amodule)
5140 return NULL;
5142 #ifdef TARGET_ARM
5143 if (is_thumb_code (amodule, code - 4))
5144 return mono_arm_get_thumb_plt_entry (code);
5145 #endif
5147 #ifdef MONO_ARCH_AOT_SUPPORTED
5148 target = mono_arch_get_call_target (code);
5149 #else
5150 g_assert_not_reached ();
5151 #endif
5153 #ifdef MONOTOUCH
5154 while (target != NULL) {
5155 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
5156 return target;
5158 // Add 4 since mono_arch_get_call_target assumes we're passing
5159 // the instruction after the actual branch instruction.
5160 target = mono_arch_get_call_target (target + 4);
5163 return NULL;
5164 #else
5165 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
5166 return target;
5167 else
5168 return NULL;
5169 #endif
5173 * mono_aot_get_plt_info_offset:
5175 * Return the PLT info offset belonging to the plt entry called by CODE.
5177 guint32
5178 mono_aot_get_plt_info_offset (host_mgreg_t *regs, guint8 *code)
5180 guint8 *plt_entry = mono_aot_get_plt_entry (code);
5182 g_assert (plt_entry);
5184 /* The offset is embedded inside the code after the plt entry */
5185 #ifdef MONO_ARCH_AOT_SUPPORTED
5186 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
5187 #else
5188 g_assert_not_reached ();
5189 return 0;
5190 #endif
5193 static gpointer
5194 mono_create_ftnptr_malloc (guint8 *code)
5196 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5197 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
5199 ftnptr->code = code;
5200 ftnptr->toc = NULL;
5201 ftnptr->env = NULL;
5203 return ftnptr;
5204 #else
5205 return code;
5206 #endif
5210 * mono_aot_register_jit_icall:
5212 * Register a JIT icall which is called by trampolines in full-aot mode. This should
5213 * be called from mono_arch_init () during startup.
5215 void
5216 mono_aot_register_jit_icall (const char *name, gpointer addr)
5218 /* No need for locking */
5219 if (!aot_jit_icall_hash)
5220 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
5221 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
5225 * load_function_full:
5227 * Load the function named NAME from the aot image.
5229 static gpointer
5230 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
5232 char *symbol;
5233 guint8 *p;
5234 int n_patches, pindex;
5235 MonoMemPool *mp;
5236 gpointer code;
5237 guint32 info_offset;
5239 /* Load the code */
5241 symbol = g_strdup_printf ("%s", name);
5242 find_amodule_symbol (amodule, symbol, (gpointer *)&code);
5243 g_free (symbol);
5244 if (!code)
5245 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
5247 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
5249 /* Load info */
5251 symbol = g_strdup_printf ("%s_p", name);
5252 find_amodule_symbol (amodule, symbol, (gpointer *)&p);
5253 g_free (symbol);
5254 if (!p)
5255 /* Nothing to patch */
5256 return code;
5258 info_offset = *(guint32*)p;
5259 if (out_tinfo) {
5260 MonoTrampInfo *tinfo;
5261 guint32 code_size, uw_info_len, uw_offset;
5262 guint8 *uw_info;
5263 /* Construct a MonoTrampInfo from the data in the AOT image */
5265 p += sizeof (guint32);
5266 code_size = *(guint32*)p;
5267 p += sizeof (guint32);
5268 uw_offset = *(guint32*)p;
5269 uw_info = amodule->unwind_info + uw_offset;
5270 uw_info_len = decode_value (uw_info, &uw_info);
5272 tinfo = g_new0 (MonoTrampInfo, 1);
5273 tinfo->code = (guint8 *)code;
5274 tinfo->code_size = code_size;
5275 tinfo->uw_info_len = uw_info_len;
5276 if (uw_info_len)
5277 tinfo->uw_info = uw_info;
5279 *out_tinfo = tinfo;
5282 p = amodule->blob + info_offset;
5284 /* Similar to mono_aot_load_method () */
5286 n_patches = decode_value (p, &p);
5288 if (n_patches) {
5289 MonoJumpInfo *patches;
5290 guint32 *got_slots;
5292 mp = mono_mempool_new ();
5294 patches = load_patch_info (amodule, mp, n_patches, FALSE, &got_slots, p, &p);
5295 g_assert (patches);
5297 for (pindex = 0; pindex < n_patches; ++pindex) {
5298 MonoJumpInfo *ji = &patches [pindex];
5299 ERROR_DECL (error);
5300 gpointer target;
5302 if (amodule->got [got_slots [pindex]])
5303 continue;
5306 * When this code is executed, the runtime may not be initalized yet, so
5307 * resolve the patch info by hand.
5309 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5310 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
5311 target = (gpointer)mono_get_lmf_addr;
5312 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint_noraise")) {
5313 target = (gpointer)mono_thread_force_interruption_checkpoint_noraise;
5314 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
5315 target = (gpointer)mono_exception_from_token;
5316 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
5317 target = (gpointer)mono_get_throw_exception ();
5318 } else if (!strcmp (ji->data.name, "mono_rethrow_preserve_exception")) {
5319 target = (gpointer)mono_get_rethrow_preserve_exception ();
5320 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
5321 MonoTrampolineType tramp_type2 = (MonoTrampolineType)atoi (ji->data.name + strlen ("trampoline_func_"));
5322 target = (gpointer)mono_get_trampoline_func (tramp_type2);
5323 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
5324 /* atoll is needed because the the offset is unsigned */
5325 guint32 slot;
5326 int res;
5328 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
5329 g_assert (res == 1);
5330 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
5331 target = mono_create_ftnptr_malloc ((guint8 *)target);
5332 } else if (!strcmp (ji->data.name, "debugger_agent_single_step_from_context")) {
5333 target = (gpointer)mini_get_dbg_callbacks ()->single_step_from_context;
5334 } else if (!strcmp (ji->data.name, "debugger_agent_breakpoint_from_context")) {
5335 target = (gpointer)mini_get_dbg_callbacks ()->breakpoint_from_context;
5336 } else if (!strcmp (ji->data.name, "throw_exception_addr")) {
5337 target = mono_get_throw_exception_addr ();
5338 } else if (!strcmp (ji->data.name, "rethrow_preserve_exception_addr")) {
5339 target = mono_get_rethrow_preserve_exception_addr ();
5340 } else if (strstr (ji->data.name, "generic_trampoline_")) {
5341 target = mono_aot_get_trampoline (ji->data.name);
5342 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
5343 /* Registered by mono_arch_init () */
5344 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
5345 } else {
5346 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
5347 g_assert_not_reached ();
5348 target = NULL;
5350 } else {
5351 /* Hopefully the code doesn't have patches which need method or
5352 * domain to be set.
5354 target = mono_resolve_patch_target (NULL, NULL, (guint8 *)code, ji, FALSE, error);
5355 mono_error_assert_ok (error);
5356 g_assert (target);
5359 amodule->got [got_slots [pindex]] = target;
5362 g_free (got_slots);
5364 mono_mempool_destroy (mp);
5367 return code;
5370 static gpointer
5371 load_function (MonoAotModule *amodule, const char *name)
5373 return load_function_full (amodule, name, NULL);
5376 static MonoAotModule*
5377 get_mscorlib_aot_module (void)
5379 MonoImage *image;
5380 MonoAotModule *amodule;
5382 image = mono_defaults.corlib;
5383 if (image)
5384 amodule = image->aot_module;
5385 else
5386 amodule = mscorlib_aot_module;
5387 g_assert (amodule);
5388 return amodule;
5391 static void
5392 no_trampolines (void)
5394 g_assert_not_reached ();
5398 * Return the trampoline identified by NAME from the mscorlib AOT file.
5399 * On ppc64, this returns a function descriptor.
5401 gpointer
5402 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
5404 MonoAotModule *amodule = get_mscorlib_aot_module ();
5406 if (mono_llvm_only) {
5407 *out_tinfo = NULL;
5408 return (gpointer)no_trampolines;
5411 return mono_create_ftnptr_malloc ((guint8 *)load_function_full (amodule, name, out_tinfo));
5414 gpointer
5415 (mono_aot_get_trampoline) (const char *name)
5417 MonoTrampInfo *out_tinfo;
5418 gpointer code;
5420 code = mono_aot_get_trampoline_full (name, &out_tinfo);
5421 mono_aot_tramp_info_register (out_tinfo, NULL);
5423 return code;
5426 static gpointer
5427 read_unwind_info (MonoAotModule *amodule, MonoTrampInfo *info, const char *symbol_name)
5429 gpointer symbol_addr;
5430 guint32 uw_offset, uw_info_len;
5431 guint8 *uw_info;
5433 find_amodule_symbol (amodule, symbol_name, &symbol_addr);
5435 if (!symbol_addr)
5436 return NULL;
5438 uw_offset = *(guint32*)symbol_addr;
5439 uw_info = amodule->unwind_info + uw_offset;
5440 uw_info_len = decode_value (uw_info, &uw_info);
5442 info->uw_info_len = uw_info_len;
5443 if (uw_info_len)
5444 info->uw_info = uw_info;
5445 else
5446 info->uw_info = NULL;
5448 /* If successful return the address of the following data */
5449 return (guint32*)symbol_addr + 1;
5452 #ifdef MONOTOUCH
5453 #include <mach/mach.h>
5455 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
5457 static void
5458 read_page_trampoline_uwinfo (MonoTrampInfo *info, int tramp_type, gboolean is_generic)
5460 char symbol_name [128];
5462 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
5463 sprintf (symbol_name, "specific_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5464 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
5465 sprintf (symbol_name, "rgctx_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5466 else if (tramp_type == MONO_AOT_TRAMP_IMT)
5467 sprintf (symbol_name, "imt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5468 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
5469 sprintf (symbol_name, "gsharedvt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5470 else
5471 g_assert_not_reached ();
5473 read_unwind_info (mono_defaults.corlib->aot_module, info, symbol_name);
5476 static unsigned char*
5477 get_new_trampoline_from_page (int tramp_type)
5479 MonoAotModule *amodule;
5480 MonoImage *image;
5481 TrampolinePage *page;
5482 int count;
5483 void *tpage;
5484 vm_address_t addr, taddr;
5485 kern_return_t ret;
5486 vm_prot_t prot, max_prot;
5487 int psize, specific_trampoline_size;
5488 unsigned char *code;
5490 specific_trampoline_size = 2 * sizeof (gpointer);
5492 mono_aot_page_lock ();
5493 page = trampoline_pages [tramp_type];
5494 if (page && page->trampolines < page->trampolines_end) {
5495 code = page->trampolines;
5496 page->trampolines += specific_trampoline_size;
5497 mono_aot_page_unlock ();
5498 return code;
5500 mono_aot_page_unlock ();
5501 /* the trampoline template page is in the mscorlib module */
5502 image = mono_defaults.corlib;
5503 g_assert (image);
5505 psize = MONO_AOT_TRAMP_PAGE_SIZE;
5507 amodule = image->aot_module;
5508 g_assert (amodule);
5510 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
5511 tpage = load_function (amodule, "specific_trampolines_page");
5512 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
5513 tpage = load_function (amodule, "rgctx_trampolines_page");
5514 else if (tramp_type == MONO_AOT_TRAMP_IMT)
5515 tpage = load_function (amodule, "imt_trampolines_page");
5516 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
5517 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
5518 else
5519 g_error ("Incorrect tramp type for trampolines page");
5520 g_assert (tpage);
5521 /*g_warning ("loaded trampolines page at %x", tpage);*/
5523 /* avoid the unlikely case of looping forever */
5524 count = 40;
5525 page = NULL;
5526 while (page == NULL && count-- > 0) {
5527 MonoTrampInfo *gen_info, *sp_info;
5529 addr = 0;
5530 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
5531 * while the second will contain the trampolines.
5533 do {
5534 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
5535 } while (ret == KERN_ABORTED);
5536 if (ret != KERN_SUCCESS) {
5537 g_error ("Cannot allocate memory for trampolines: %d", ret);
5538 break;
5540 /*g_warning ("allocated trampoline double page at %x", addr);*/
5541 /* replace the second page with a remapped trampoline page */
5542 taddr = addr + psize;
5543 vm_deallocate (mach_task_self (), taddr, psize);
5544 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
5545 if (ret != KERN_SUCCESS) {
5546 /* someone else got the page, try again */
5547 vm_deallocate (mach_task_self (), addr, psize);
5548 continue;
5550 /*g_warning ("remapped trampoline page at %x", taddr);*/
5552 mono_aot_page_lock ();
5553 page = trampoline_pages [tramp_type];
5554 /* some other thread already allocated, so use that to avoid wasting memory */
5555 if (page && page->trampolines < page->trampolines_end) {
5556 code = page->trampolines;
5557 page->trampolines += specific_trampoline_size;
5558 mono_aot_page_unlock ();
5559 vm_deallocate (mach_task_self (), addr, psize);
5560 vm_deallocate (mach_task_self (), taddr, psize);
5561 return code;
5563 page = (TrampolinePage*)addr;
5564 page->next = trampoline_pages [tramp_type];
5565 trampoline_pages [tramp_type] = page;
5566 page->trampolines = (guint8*)(taddr + amodule->info.tramp_page_code_offsets [tramp_type]);
5567 page->trampolines_end = (guint8*)(taddr + psize - 64);
5568 code = page->trampolines;
5569 page->trampolines += specific_trampoline_size;
5570 mono_aot_page_unlock ();
5572 /* Register the generic part at the beggining of the trampoline page */
5573 gen_info = mono_tramp_info_create (NULL, (guint8*)taddr, amodule->info.tramp_page_code_offsets [tramp_type], NULL, NULL);
5574 read_page_trampoline_uwinfo (gen_info, tramp_type, TRUE);
5575 mono_aot_tramp_info_register (gen_info, NULL);
5577 * FIXME
5578 * Registering each specific trampoline produces a lot of
5579 * MonoJitInfo structures. Jump trampolines are also registered
5580 * separately.
5582 if (tramp_type != MONO_AOT_TRAMP_SPECIFIC) {
5583 /* Register the rest of the page as a single trampoline */
5584 sp_info = mono_tramp_info_create (NULL, code, page->trampolines_end - code, NULL, NULL);
5585 read_page_trampoline_uwinfo (sp_info, tramp_type, FALSE);
5586 mono_aot_tramp_info_register (sp_info, NULL);
5588 return code;
5590 g_error ("Cannot allocate more trampoline pages: %d", ret);
5591 return NULL;
5594 #else
5595 static unsigned char*
5596 get_new_trampoline_from_page (int tramp_type)
5598 g_error ("Page trampolines not supported.");
5599 return NULL;
5601 #endif
5604 static gpointer
5605 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
5607 void *code;
5608 gpointer *data;
5610 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
5612 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5613 data [0] = arg;
5614 data [1] = tramp;
5615 /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
5616 return code;
5620 static gpointer
5621 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
5623 void *code;
5624 gpointer *data;
5626 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
5628 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5629 data [0] = arg;
5630 data [1] = tramp;
5631 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
5632 return code;
5636 static gpointer
5637 get_new_imt_trampoline_from_page (gpointer arg)
5639 void *code;
5640 gpointer *data;
5642 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT);
5644 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5645 data [0] = arg;
5646 /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
5647 return code;
5651 static gpointer
5652 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
5654 void *code;
5655 gpointer *data;
5657 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
5659 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5660 data [0] = arg;
5661 data [1] = tramp;
5662 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
5663 return code;
5666 /* Return a given kind of trampoline */
5667 /* FIXME set unwind info for these trampolines */
5668 static gpointer
5669 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
5671 MonoImage *image;
5672 MonoAotModule *amodule = get_mscorlib_aot_module ();
5673 int index, tramp_size;
5675 /* Currently, we keep all trampolines in the mscorlib AOT image */
5676 image = mono_defaults.corlib;
5678 *out_amodule = amodule;
5680 mono_aot_lock ();
5682 #ifdef MONOTOUCH
5683 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
5684 #else
5685 #define MONOTOUCH_TRAMPOLINES_ERROR ""
5686 #endif
5687 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
5688 g_error ("Ran out of trampolines of type %d in '%s' (limit %d)%s\n",
5689 tramp_type, image ? image->name : "mscorlib", amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
5691 index = amodule->trampoline_index [tramp_type] ++;
5693 mono_aot_unlock ();
5695 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
5697 tramp_size = amodule->info.trampoline_size [tramp_type];
5699 if (out_tramp_size)
5700 *out_tramp_size = tramp_size;
5702 return amodule->trampolines [tramp_type] + (index * tramp_size);
5705 static void
5706 no_specific_trampoline (void)
5708 g_assert_not_reached ();
5712 * Return a specific trampoline from the AOT file.
5714 gpointer
5715 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
5717 MonoAotModule *amodule;
5718 guint32 got_offset, tramp_size;
5719 guint8 *code, *tramp;
5720 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
5721 static gboolean inited;
5722 static guint32 num_trampolines;
5724 if (mono_llvm_only) {
5725 *code_len = 1;
5726 return (gpointer)no_specific_trampoline;
5729 if (!inited) {
5730 mono_aot_lock ();
5732 if (!inited) {
5733 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
5734 inited = TRUE;
5737 mono_aot_unlock ();
5740 num_trampolines ++;
5742 if (!generic_trampolines [tramp_type]) {
5743 char *symbol;
5745 symbol = mono_get_generic_trampoline_name (tramp_type);
5746 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
5747 g_free (symbol);
5750 tramp = (guint8 *)generic_trampolines [tramp_type];
5751 g_assert (tramp);
5753 if (USE_PAGE_TRAMPOLINES) {
5754 code = (guint8 *)get_new_specific_trampoline_from_page (tramp, arg1);
5755 tramp_size = 8;
5756 } else {
5757 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
5759 amodule->got [got_offset] = tramp;
5760 amodule->got [got_offset + 1] = arg1;
5763 if (code_len)
5764 *code_len = tramp_size;
5766 return code;
5769 gpointer
5770 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
5772 MonoAotModule *amodule;
5773 guint8 *code;
5774 guint32 got_offset;
5776 if (USE_PAGE_TRAMPOLINES) {
5777 code = (guint8 *)get_new_rgctx_trampoline_from_page (addr, ctx);
5778 } else {
5779 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
5781 amodule->got [got_offset] = ctx;
5782 amodule->got [got_offset + 1] = addr;
5785 /* The caller expects an ftnptr */
5786 return mono_create_ftnptr (mono_domain_get (), code);
5789 gpointer
5790 mono_aot_get_unbox_trampoline (MonoMethod *method)
5792 ERROR_DECL (error);
5793 guint32 method_index = mono_metadata_token_index (method->token) - 1;
5794 MonoAotModule *amodule;
5795 gpointer code;
5796 guint32 *ut, *ut_end, *entry;
5797 int low, high, entry_index = 0;
5798 MonoTrampInfo *tinfo;
5800 if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
5801 method_index = find_aot_method (method, &amodule);
5802 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
5803 MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
5804 mono_error_assert_ok (error);
5805 method_index = find_aot_method (shared, &amodule);
5807 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, TRUE)) {
5808 MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
5809 mono_error_assert_ok (error);
5811 method_index = find_aot_method (shared, &amodule);
5813 g_assert (method_index != 0xffffff);
5814 } else {
5815 amodule = m_class_get_image (method->klass)->aot_module;
5816 g_assert (amodule);
5819 if (amodule->info.llvm_get_unbox_tramp) {
5820 gpointer (*get_tramp) (int) = (gpointer (*)(int))amodule->info.llvm_get_unbox_tramp;
5821 code = get_tramp (method_index);
5823 if (code)
5824 return code;
5827 ut = amodule->unbox_trampolines;
5828 ut_end = amodule->unbox_trampolines_end;
5830 /* Do a binary search in the sorted table */
5831 code = NULL;
5832 low = 0;
5833 high = (ut_end - ut);
5834 while (low < high) {
5835 entry_index = (low + high) / 2;
5836 entry = &ut [entry_index];
5837 if (entry [0] < method_index) {
5838 low = entry_index + 1;
5839 } else if (entry [0] > method_index) {
5840 high = entry_index;
5841 } else {
5842 break;
5846 code = get_call_table_entry (amodule->unbox_trampoline_addresses, entry_index);
5847 g_assert (code);
5849 tinfo = mono_tramp_info_create (NULL, (guint8 *)code, 0, NULL, NULL);
5851 gpointer const symbol_addr = read_unwind_info (amodule, tinfo, "unbox_trampoline_p");
5852 if (!symbol_addr) {
5853 mono_tramp_info_free (tinfo);
5854 return FALSE;
5857 tinfo->code_size = *(guint32*)symbol_addr;
5858 mono_aot_tramp_info_register (tinfo, NULL);
5860 /* The caller expects an ftnptr */
5861 return mono_create_ftnptr (mono_domain_get (), code);
5864 gpointer
5865 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
5867 char *symbol;
5868 gpointer code;
5869 MonoAotModule *amodule = mono_defaults.corlib->aot_module;
5870 guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
5871 static int count = 0;
5873 count ++;
5874 if (index >= amodule->info.num_rgctx_fetch_trampolines) {
5875 static gpointer addr;
5876 gpointer *info;
5879 * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
5881 if (!addr)
5882 addr = load_function (amodule, "rgctx_fetch_trampoline_general");
5883 info = (void **)mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
5884 info [0] = GUINT_TO_POINTER (slot);
5885 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
5886 code = mono_aot_get_static_rgctx_trampoline (info, addr);
5887 return mono_create_ftnptr (mono_domain_get (), code);
5890 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
5891 code = load_function (mono_defaults.corlib->aot_module, symbol);
5892 g_free (symbol);
5893 /* The caller expects an ftnptr */
5894 return mono_create_ftnptr (mono_domain_get (), code);
5897 static void
5898 no_imt_trampoline (void)
5900 g_assert_not_reached ();
5903 gpointer
5904 mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
5906 guint32 got_offset;
5907 gpointer code;
5908 gpointer *buf;
5909 int i, index, real_count;
5910 MonoAotModule *amodule;
5912 if (mono_llvm_only)
5913 return (gpointer)no_imt_trampoline;
5915 real_count = 0;
5916 for (i = 0; i < count; ++i) {
5917 MonoIMTCheckItem *item = imt_entries [i];
5919 if (item->is_equals)
5920 real_count ++;
5923 /* Save the entries into an array */
5924 buf = (void **)mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
5925 index = 0;
5926 for (i = 0; i < count; ++i) {
5927 MonoIMTCheckItem *item = imt_entries [i];
5929 if (!item->is_equals)
5930 continue;
5932 g_assert (item->key);
5934 buf [(index * 2)] = item->key;
5935 if (item->has_target_code) {
5936 gpointer *p = (gpointer *)mono_domain_alloc (domain, sizeof (gpointer));
5937 *p = item->value.target_code;
5938 buf [(index * 2) + 1] = p;
5939 } else {
5940 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
5942 index ++;
5944 buf [(index * 2)] = NULL;
5945 buf [(index * 2) + 1] = fail_tramp;
5947 if (USE_PAGE_TRAMPOLINES) {
5948 code = get_new_imt_trampoline_from_page (buf);
5949 } else {
5950 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT, 1, &amodule, &got_offset, NULL);
5952 amodule->got [got_offset] = buf;
5955 return code;
5958 gpointer
5959 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
5961 MonoAotModule *amodule;
5962 guint8 *code;
5963 guint32 got_offset;
5965 if (USE_PAGE_TRAMPOLINES) {
5966 code = (guint8 *)get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
5967 } else {
5968 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
5970 amodule->got [got_offset] = arg;
5971 amodule->got [got_offset + 1] = addr;
5974 /* The caller expects an ftnptr */
5975 return mono_create_ftnptr (mono_domain_get (), code);
5978 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
5979 gpointer
5980 mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
5982 MonoAotModule *amodule;
5983 guint8 *code;
5984 guint32 got_offset;
5986 if (USE_PAGE_TRAMPOLINES) {
5987 g_error ("FIXME: ftnptr_arg page trampolines");
5988 } else {
5989 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_FTNPTR_ARG, 2, &amodule, &got_offset, NULL);
5991 amodule->got [got_offset] = arg;
5992 amodule->got [got_offset + 1] = addr;
5995 /* The caller expects an ftnptr */
5996 return mono_create_ftnptr (mono_domain_get (), code);
5998 #endif
6002 * mono_aot_set_make_unreadable:
6004 * Set whenever to make all mmaped memory unreadable. In conjuction with a
6005 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
6007 void
6008 mono_aot_set_make_unreadable (gboolean unreadable)
6010 static int inited;
6012 make_unreadable = unreadable;
6014 if (make_unreadable && !inited) {
6015 mono_counters_register ("AOT: pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
6019 typedef struct {
6020 MonoAotModule *module;
6021 guint8 *ptr;
6022 } FindMapUserData;
6024 static void
6025 find_map (gpointer key, gpointer value, gpointer user_data)
6027 MonoAotModule *module = (MonoAotModule*)value;
6028 FindMapUserData *data = (FindMapUserData*)user_data;
6030 if (!data->module)
6031 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
6032 data->module = module;
6035 static MonoAotModule*
6036 find_module_for_addr (void *ptr)
6038 FindMapUserData data;
6040 if (!make_unreadable)
6041 return NULL;
6043 data.module = NULL;
6044 data.ptr = (guint8*)ptr;
6046 mono_aot_lock ();
6047 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
6048 mono_aot_unlock ();
6050 return data.module;
6054 * mono_aot_is_pagefault:
6056 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
6057 * within memory allocated by this module.
6059 gboolean
6060 mono_aot_is_pagefault (void *ptr)
6062 if (!make_unreadable)
6063 return FALSE;
6066 * Not signal safe, but SIGSEGV's are synchronous, and
6067 * this is only turned on by a MONO_DEBUG option.
6069 return find_module_for_addr (ptr) != NULL;
6073 * mono_aot_handle_pagefault:
6075 * Handle a pagefault caused by an unreadable page by making it readable again.
6077 void
6078 mono_aot_handle_pagefault (void *ptr)
6080 #ifndef HOST_WIN32
6081 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
6082 int res;
6084 mono_aot_lock ();
6085 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
6086 g_assert (res == 0);
6088 n_pagefaults ++;
6089 mono_aot_unlock ();
6090 #endif
6093 #else
6094 /* AOT disabled */
6096 void
6097 mono_aot_init (void)
6101 void
6102 mono_aot_cleanup (void)
6106 guint32
6107 mono_aot_find_method_index (MonoMethod *method)
6109 g_assert_not_reached ();
6110 return 0;
6113 void
6114 mono_aot_init_llvm_method (gpointer aot_module, guint32 method_index)
6118 void
6119 mono_aot_init_gshared_method_this (gpointer aot_module, guint32 method_index, MonoObject *this)
6123 void
6124 mono_aot_init_gshared_method_mrgctx (gpointer aot_module, guint32 method_index, MonoMethodRuntimeGenericContext *rgctx)
6128 void
6129 mono_aot_init_gshared_method_vtable (gpointer aot_module, guint32 method_index, MonoVTable *vtable)
6133 gpointer
6134 mono_aot_get_method (MonoDomain *domain,
6135 MonoMethod *method, MonoError *error)
6137 error_init (error);
6138 return NULL;
6141 gboolean
6142 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
6144 return FALSE;
6147 gboolean
6148 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6150 return FALSE;
6153 gboolean
6154 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
6156 return FALSE;
6159 MonoJitInfo *
6160 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
6162 return NULL;
6165 gpointer
6166 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token, MonoError *error)
6168 error_init (error);
6169 return NULL;
6172 guint8*
6173 mono_aot_get_plt_entry (guint8 *code)
6175 return NULL;
6178 gpointer
6179 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code, MonoError *error)
6181 return NULL;
6184 void
6185 mono_aot_patch_plt_entry (guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
6189 gpointer
6190 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot, MonoError *error)
6192 error_init (error);
6194 return NULL;
6197 guint32
6198 mono_aot_get_plt_info_offset (host_mgreg_t *regs, guint8 *code)
6200 g_assert_not_reached ();
6202 return 0;
6205 gpointer
6206 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
6208 g_assert_not_reached ();
6209 return NULL;
6212 gpointer
6213 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
6215 g_assert_not_reached ();
6216 return NULL;
6219 gpointer
6220 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
6222 g_assert_not_reached ();
6223 return NULL;
6226 gpointer
6227 mono_aot_get_trampoline (const char *name)
6229 g_assert_not_reached ();
6230 return NULL;
6233 gpointer
6234 mono_aot_get_unbox_trampoline (MonoMethod *method)
6236 g_assert_not_reached ();
6237 return NULL;
6240 gpointer
6241 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
6243 g_assert_not_reached ();
6244 return NULL;
6247 gpointer
6248 mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
6250 g_assert_not_reached ();
6251 return NULL;
6254 gpointer
6255 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
6257 g_assert_not_reached ();
6258 return NULL;
6261 void
6262 mono_aot_set_make_unreadable (gboolean unreadable)
6266 gboolean
6267 mono_aot_is_pagefault (void *ptr)
6269 return FALSE;
6272 void
6273 mono_aot_handle_pagefault (void *ptr)
6277 guint8*
6278 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
6280 g_assert_not_reached ();
6281 return NULL;
6284 void
6285 mono_aot_register_jit_icall (const char *name, gpointer addr)
6289 GHashTable *
6290 mono_aot_get_weak_field_indexes (MonoImage *image)
6292 return NULL;
6295 #endif