PPC JIT optimizations (System.Math instruction inlining) (#11964)
[mono-project.git] / mono / mini / aot-runtime.c
blob66cd7b5ed2f6a19db0867491f5fe6dde7f27740c
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>
63 #include <mono/utils/bsearch.h>
65 #include "mini.h"
66 #include "seq-points.h"
67 #include "version.h"
68 #include "debugger-agent.h"
69 #include "aot-compiler.h"
70 #include "aot-runtime.h"
71 #include "jit-icalls.h"
72 #include "mini-runtime.h"
74 #ifndef DISABLE_AOT
76 #ifdef TARGET_OSX
77 #define ENABLE_AOT_CACHE
78 #endif
80 /* Number of got entries shared between the JIT and LLVM GOT */
81 #define N_COMMON_GOT_ENTRIES 10
83 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
85 typedef struct {
86 int method_index;
87 MonoJitInfo *jinfo;
88 } JitInfoMap;
90 #define GOT_INITIALIZING 1
91 #define GOT_INITIALIZED 2
93 struct MonoAotModule {
94 char *aot_name;
95 /* Pointer to the Global Offset Table */
96 gpointer *got;
97 gpointer *llvm_got;
98 gpointer *shared_got;
99 GHashTable *name_cache;
100 GHashTable *extra_methods;
101 /* Maps methods to their code */
102 GHashTable *method_to_code;
103 /* Maps pointers into the method info to the methods themselves */
104 GHashTable *method_ref_to_method;
105 MonoAssemblyName *image_names;
106 char **image_guids;
107 MonoAssembly *assembly;
108 MonoImage **image_table;
109 guint32 image_table_len;
110 gboolean out_of_date;
111 gboolean plt_inited;
112 int got_initialized;
113 guint8 *mem_begin;
114 guint8 *mem_end;
115 guint8 *jit_code_start;
116 guint8 *jit_code_end;
117 guint8 *llvm_code_start;
118 guint8 *llvm_code_end;
119 guint8 *plt;
120 guint8 *plt_end;
121 guint8 *blob;
122 gpointer weak_field_indexes;
123 /* Maps method indexes to their code */
124 gpointer *methods;
125 /* Sorted array of method addresses */
126 gpointer *sorted_methods;
127 /* Method indexes for each method in sorted_methods */
128 int *sorted_method_indexes;
129 /* The length of the two tables above */
130 int sorted_methods_len;
131 guint32 *method_info_offsets;
132 guint32 *ex_info_offsets;
133 guint32 *class_info_offsets;
134 guint32 *got_info_offsets;
135 guint32 *llvm_got_info_offsets;
136 guint32 *methods_loaded;
137 guint16 *class_name_table;
138 guint32 *extra_method_table;
139 guint32 *extra_method_info_offsets;
140 guint32 *unbox_trampolines;
141 guint32 *unbox_trampolines_end;
142 guint32 *unbox_trampoline_addresses;
143 guint8 *unwind_info;
145 /* Points to the mono EH data created by LLVM */
146 guint8 *mono_eh_frame;
148 /* Points to the data tables if MONO_AOT_FILE_FLAG_SEPARATE_DATA is set */
149 gpointer tables [MONO_AOT_TABLE_NUM];
150 /* Points to the trampolines */
151 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
152 /* The first unused trampoline of each kind */
153 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
155 gboolean use_page_trampolines;
157 MonoAotFileInfo info;
159 gpointer *globals;
160 MonoDl *sofile;
162 JitInfoMap *async_jit_info_table;
163 mono_mutex_t mutex;
166 typedef struct {
167 void *next;
168 unsigned char *trampolines;
169 unsigned char *trampolines_end;
170 } TrampolinePage;
172 static GHashTable *aot_modules;
173 #define mono_aot_lock() mono_os_mutex_lock (&aot_mutex)
174 #define mono_aot_unlock() mono_os_mutex_unlock (&aot_mutex)
175 static mono_mutex_t aot_mutex;
178 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
179 * AOT modules registered by mono_aot_register_module ().
181 static GHashTable *static_aot_modules;
183 * Same as above, but tracks module that must be loaded before others are
184 * This allows us to have a "container" module which contains resources for
185 * other modules. Since it doesn't provide methods for a managed assembly,
186 * and it needs to be fully loaded by the time the other code needs it, it
187 * must be eagerly loaded before other modules.
189 static char *container_assm_name = NULL;
190 static MonoAotModule *container_amodule = NULL;
193 * Maps MonoJitInfo* to the aot module they belong to, this can be different
194 * from ji->method->klass->image's aot module for generic instances.
196 static GHashTable *ji_to_amodule;
198 /* Maps method addresses to MonoAotMethodFlags */
199 static GHashTable *code_to_method_flags;
202 * Whenever to AOT compile loaded assemblies on demand and store them in
203 * a cache.
205 static gboolean enable_aot_cache = FALSE;
207 static gboolean mscorlib_aot_loaded;
209 /* For debugging */
210 static gint32 mono_last_aot_method = -1;
212 static gboolean make_unreadable = FALSE;
213 static guint32 name_table_accesses = 0;
214 static guint32 n_pagefaults = 0;
216 /* Used to speed-up find_aot_module () */
217 static gsize aot_code_low_addr = (gssize)-1;
218 static gsize aot_code_high_addr = 0;
220 /* Stats */
221 static gint32 async_jit_info_size;
223 static GHashTable *aot_jit_icall_hash;
225 #ifdef MONOTOUCH
226 #define USE_PAGE_TRAMPOLINES (mono_defaults.corlib->aot_module->use_page_trampolines)
227 #else
228 #define USE_PAGE_TRAMPOLINES 0
229 #endif
231 #define mono_aot_page_lock() mono_os_mutex_lock (&aot_page_mutex)
232 #define mono_aot_page_unlock() mono_os_mutex_unlock (&aot_page_mutex)
233 static mono_mutex_t aot_page_mutex;
235 static MonoAotModule *mscorlib_aot_module;
237 /* Embedding API hooks to load the AOT data for AOT images compiled with MONO_AOT_FILE_FLAG_SEPARATE_DATA */
238 static MonoLoadAotDataFunc aot_data_load_func;
239 static MonoFreeAotDataFunc aot_data_free_func;
240 static gpointer aot_data_func_user_data;
242 static void
243 init_plt (MonoAotModule *info);
245 static void
246 compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end);
248 static gboolean
249 init_method (MonoAotModule *amodule, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoGenericContext *context, MonoError *error);
251 static MonoJumpInfo*
252 decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets);
254 static inline void
255 amodule_lock (MonoAotModule *amodule)
257 mono_os_mutex_lock (&amodule->mutex);
260 static inline void
261 amodule_unlock (MonoAotModule *amodule)
263 mono_os_mutex_unlock (&amodule->mutex);
267 * load_image:
269 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
270 * found, and sets @error for what happened
272 static MonoImage *
273 load_image (MonoAotModule *amodule, int index, MonoError *error)
275 MonoAssembly *assembly;
276 MonoImageOpenStatus status;
278 g_assert (index < amodule->image_table_len);
280 error_init (error);
282 if (amodule->image_table [index])
283 return amodule->image_table [index];
284 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);
285 if (amodule->out_of_date) {
286 mono_error_set_bad_image_by_name (error, amodule->aot_name, "Image out of date");
287 return NULL;
291 * LoadFile allows loading more than one assembly with the same name.
292 * That means that just calling mono_assembly_load is unlikely to find
293 * the correct assembly (it'll just return the first one loaded). But
294 * we shouldn't hardcode the full assembly filepath into the AOT image,
295 * so it's not obvious that we can call mono_assembly_open_predicate.
297 * In the JIT, an assembly opened with LoadFile is supposed to only
298 * refer to already-loaded assemblies (or to GAC & MONO_PATH)
299 * assemblies - so nothing new should be loading. And for the
300 * LoadFile'd assembly itself, we can check if the name and guid of the
301 * current AOT module matches the wanted name and guid and just return
302 * the AOT module's assembly.
304 if (mono_asmctx_get_kind (&amodule->assembly->context) == MONO_ASMCTX_INDIVIDUAL &&
305 !strcmp (amodule->assembly->image->guid, amodule->image_guids [index]) &&
306 mono_assembly_names_equal (&amodule->image_names [index], &amodule->assembly->aname))
307 assembly = amodule->assembly;
308 else
309 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
310 if (!assembly) {
311 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);
312 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);
313 amodule->out_of_date = TRUE;
314 return NULL;
317 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
318 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);
319 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);
320 amodule->out_of_date = TRUE;
321 return NULL;
324 amodule->image_table [index] = assembly->image;
325 return assembly->image;
328 static inline gint32
329 decode_value (guint8 *ptr, guint8 **rptr)
331 guint8 b = *ptr;
332 gint32 len;
334 if ((b & 0x80) == 0){
335 len = b;
336 ++ptr;
337 } else if ((b & 0x40) == 0){
338 len = ((b & 0x3f) << 8 | ptr [1]);
339 ptr += 2;
340 } else if (b != 0xff) {
341 len = ((b & 0x1f) << 24) |
342 (ptr [1] << 16) |
343 (ptr [2] << 8) |
344 ptr [3];
345 ptr += 4;
347 else {
348 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
349 ptr += 5;
351 if (rptr)
352 *rptr = ptr;
354 //printf ("DECODE: %d.\n", len);
355 return len;
359 * mono_aot_get_offset:
361 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
362 * entry.
364 static guint32
365 mono_aot_get_offset (guint32 *table, int index)
367 int i, group, ngroups, index_entry_size;
368 int start_offset, offset, group_size;
369 guint8 *data_start, *p;
370 guint32 *index32 = NULL;
371 guint16 *index16 = NULL;
373 /* noffsets = table [0]; */
374 group_size = table [1];
375 ngroups = table [2];
376 index_entry_size = table [3];
377 group = index / group_size;
379 if (index_entry_size == 2) {
380 index16 = (guint16*)&table [4];
381 data_start = (guint8*)&index16 [ngroups];
382 p = data_start + index16 [group];
383 } else {
384 index32 = (guint32*)&table [4];
385 data_start = (guint8*)&index32 [ngroups];
386 p = data_start + index32 [group];
389 /* offset will contain the value of offsets [group * group_size] */
390 offset = start_offset = decode_value (p, &p);
391 for (i = group * group_size + 1; i <= index; ++i) {
392 offset += decode_value (p, &p);
395 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
397 return offset;
400 static MonoMethod*
401 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
403 static MonoClass*
404 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
406 static MonoType*
407 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
409 static MonoGenericInst*
410 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
412 int type_argc, i;
413 MonoType **type_argv;
414 MonoGenericInst *inst;
415 guint8 *p = buf;
417 error_init (error);
418 type_argc = decode_value (p, &p);
419 type_argv = g_new0 (MonoType*, type_argc);
421 for (i = 0; i < type_argc; ++i) {
422 MonoClass *pclass = decode_klass_ref (module, p, &p, error);
423 if (!pclass) {
424 g_free (type_argv);
425 return NULL;
427 type_argv [i] = m_class_get_byval_arg (pclass);
430 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
431 g_free (type_argv);
433 *endbuf = p;
435 return inst;
438 static gboolean
439 decode_generic_context (MonoAotModule *amodule, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf, MonoError *error)
441 guint8 *p = buf;
442 guint8 *p2;
443 guint32 offset, flags;
445 /* Either the class_inst or method_inst offset */
446 flags = decode_value (p, &p);
448 if (flags & 1) {
449 offset = decode_value (p, &p);
450 p2 = amodule->blob + offset;
451 ctx->class_inst = decode_generic_inst (amodule, p2, &p2, error);
452 if (!ctx->class_inst)
453 return FALSE;
455 if (flags & 2) {
456 offset = decode_value (p, &p);
457 p2 = amodule->blob + offset;
458 ctx->method_inst = decode_generic_inst (amodule, p2, &p2, error);
459 if (!ctx->method_inst)
460 return FALSE;
463 *endbuf = p;
464 return TRUE;
467 static MonoClass*
468 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
470 MonoImage *image;
471 MonoClass *klass = NULL, *eklass;
472 guint32 token, rank, idx;
473 guint8 *p = buf;
474 int reftype;
476 error_init (error);
477 reftype = decode_value (p, &p);
478 if (reftype == 0) {
479 *endbuf = p;
480 mono_error_set_bad_image_by_name (error, module->aot_name, "Decoding a null class ref");
481 return NULL;
484 switch (reftype) {
485 case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
486 idx = decode_value (p, &p);
487 image = load_image (module, 0, 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_TYPEDEF_INDEX_IMAGE:
493 idx = decode_value (p, &p);
494 image = load_image (module, decode_value (p, &p), error);
495 if (!image)
496 return NULL;
497 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
498 break;
499 case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
500 token = decode_value (p, &p);
501 image = module->assembly->image;
502 if (!image) {
503 mono_error_set_bad_image_by_name (error, module->aot_name, "No image associated with the aot module");
504 return NULL;
506 klass = mono_class_get_checked (image, token, error);
507 break;
508 case MONO_AOT_TYPEREF_GINST: {
509 MonoClass *gclass;
510 MonoGenericContext ctx;
511 MonoType *type;
513 gclass = decode_klass_ref (module, p, &p, error);
514 if (!gclass)
515 return NULL;
516 g_assert (mono_class_is_gtd (gclass));
518 memset (&ctx, 0, sizeof (ctx));
519 guint32 offset = decode_value (p, &p);
520 guint8 *p2 = module->blob + offset;
521 ctx.class_inst = decode_generic_inst (module, p2, &p2, error);
522 if (!ctx.class_inst)
523 return NULL;
524 type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
525 if (!type)
526 return NULL;
527 klass = mono_class_from_mono_type_internal (type);
528 mono_metadata_free_type (type);
529 break;
531 case MONO_AOT_TYPEREF_VAR: {
532 MonoType *t = NULL;
533 MonoGenericContainer *container = NULL;
534 gboolean has_constraint = decode_value (p, &p);
536 if (has_constraint) {
537 MonoClass *par_klass;
538 MonoType *gshared_constraint;
540 gshared_constraint = decode_type (module, p, &p, error);
541 if (!gshared_constraint)
542 return NULL;
544 par_klass = decode_klass_ref (module, p, &p, error);
545 if (!par_klass)
546 return NULL;
548 t = mini_get_shared_gparam (m_class_get_byval_arg (par_klass), gshared_constraint);
549 mono_metadata_free_type (gshared_constraint);
550 klass = mono_class_from_mono_type_internal (t);
551 } else {
552 int type = decode_value (p, &p);
553 int num = decode_value (p, &p);
554 gboolean is_not_anonymous = decode_value (p, &p);
556 if (is_not_anonymous) {
557 gboolean is_method = decode_value (p, &p);
559 if (is_method) {
560 MonoMethod *method_def;
561 g_assert (type == MONO_TYPE_MVAR);
562 method_def = decode_resolve_method_ref (module, p, &p, error);
563 if (!method_def)
564 return NULL;
566 container = mono_method_get_generic_container (method_def);
567 } else {
568 MonoClass *class_def;
569 g_assert (type == MONO_TYPE_VAR);
570 class_def = decode_klass_ref (module, p, &p, error);
571 if (!class_def)
572 return NULL;
574 container = mono_class_try_get_generic_container (class_def); //FIXME is this a case for a try_get?
576 } else {
577 // We didn't decode is_method, so we have to infer it from type enum.
578 container = mono_get_anonymous_container_for_image (module->assembly->image, type == MONO_TYPE_MVAR);
581 t = g_new0 (MonoType, 1);
582 t->type = (MonoTypeEnum)type;
583 if (is_not_anonymous) {
584 t->data.generic_param = mono_generic_container_get_param (container, num);
585 } else {
586 /* Anonymous */
587 MonoGenericParam *par = mono_metadata_create_anon_gparam (module->assembly->image, num, type == MONO_TYPE_MVAR);
588 t->data.generic_param = par;
589 // FIXME: maybe do this for all anon gparams?
590 ((MonoGenericParamFull*)par)->info.name = mono_make_generic_name_string (module->assembly->image, num);
592 // FIXME: Maybe use types directly to avoid
593 // the overhead of creating MonoClass-es
594 klass = mono_class_from_mono_type_internal (t);
596 g_free (t);
598 break;
600 case MONO_AOT_TYPEREF_ARRAY:
601 /* Array */
602 rank = decode_value (p, &p);
603 eklass = decode_klass_ref (module, p, &p, error);
604 if (!eklass)
605 return NULL;
606 klass = mono_class_create_array (eklass, rank);
607 break;
608 case MONO_AOT_TYPEREF_PTR: {
609 MonoType *t;
611 t = decode_type (module, p, &p, error);
612 if (!t)
613 return NULL;
614 klass = mono_class_from_mono_type_internal (t);
615 g_free (t);
616 break;
618 case MONO_AOT_TYPEREF_BLOB_INDEX: {
619 guint32 offset = decode_value (p, &p);
620 guint8 *p2;
622 p2 = module->blob + offset;
623 klass = decode_klass_ref (module, p2, &p2, error);
624 break;
626 default:
627 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid klass reftype %d", reftype);
629 //g_assert (klass);
630 //printf ("BLA: %s\n", mono_type_full_name (m_class_get_byval_arg (klass)));
631 *endbuf = p;
632 return klass;
635 static MonoClassField*
636 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
638 ERROR_DECL (error);
639 MonoClass *klass = decode_klass_ref (module, buf, &buf, error);
640 guint32 token;
641 guint8 *p = buf;
643 if (!klass) {
644 mono_error_cleanup (error); /* FIXME don't swallow the error */
645 return NULL;
648 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
650 *endbuf = p;
652 return mono_class_get_field (klass, token);
656 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
657 * memory.
659 static MonoType*
660 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
662 guint8 *p = buf;
663 MonoType *t;
665 if (*p == MONO_TYPE_CMOD_REQD) {
666 ++p;
668 int count = decode_value (p, &p);
670 t = (MonoType*)g_malloc0 (mono_sizeof_type_with_mods (count));
671 t->has_cmods = TRUE;
673 MonoCustomModContainer *cm = mono_type_get_cmods (t);
674 int iindex = decode_value (p, &p);
675 cm->image = load_image (module, iindex, error);
676 if (!cm->image) {
677 g_free (t);
678 return NULL;
680 cm->count = count;
681 for (int i = 0; i < cm->count; ++i) {
682 cm->modifiers [i].required = decode_value (p, &p);
683 cm->modifiers [i].token = decode_value (p, &p);
685 } else {
686 t = (MonoType *) g_malloc0 (sizeof (MonoType));
689 while (TRUE) {
690 if (*p == MONO_TYPE_PINNED) {
691 t->pinned = TRUE;
692 ++p;
693 } else if (*p == MONO_TYPE_BYREF) {
694 t->byref = TRUE;
695 ++p;
696 } else {
697 break;
701 t->type = (MonoTypeEnum)*p;
702 ++p;
704 switch (t->type) {
705 case MONO_TYPE_VOID:
706 case MONO_TYPE_BOOLEAN:
707 case MONO_TYPE_CHAR:
708 case MONO_TYPE_I1:
709 case MONO_TYPE_U1:
710 case MONO_TYPE_I2:
711 case MONO_TYPE_U2:
712 case MONO_TYPE_I4:
713 case MONO_TYPE_U4:
714 case MONO_TYPE_I8:
715 case MONO_TYPE_U8:
716 case MONO_TYPE_R4:
717 case MONO_TYPE_R8:
718 case MONO_TYPE_I:
719 case MONO_TYPE_U:
720 case MONO_TYPE_STRING:
721 case MONO_TYPE_OBJECT:
722 case MONO_TYPE_TYPEDBYREF:
723 break;
724 case MONO_TYPE_VALUETYPE:
725 case MONO_TYPE_CLASS:
726 t->data.klass = decode_klass_ref (module, p, &p, error);
727 if (!t->data.klass)
728 goto fail;
729 break;
730 case MONO_TYPE_SZARRAY:
731 t->data.klass = decode_klass_ref (module, p, &p, error);
733 if (!t->data.klass)
734 goto fail;
735 break;
736 case MONO_TYPE_PTR:
737 t->data.type = decode_type (module, p, &p, error);
738 if (!t->data.type)
739 goto fail;
740 break;
741 case MONO_TYPE_GENERICINST: {
742 MonoClass *gclass;
743 MonoGenericContext ctx;
744 MonoType *type;
745 MonoClass *klass;
747 gclass = decode_klass_ref (module, p, &p, error);
748 if (!gclass)
749 goto fail;
750 g_assert (mono_class_is_gtd (gclass));
752 memset (&ctx, 0, sizeof (ctx));
753 ctx.class_inst = decode_generic_inst (module, p, &p, error);
754 if (!ctx.class_inst)
755 goto fail;
756 type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
757 if (!type)
758 goto fail;
759 klass = mono_class_from_mono_type_internal (type);
760 t->data.generic_class = mono_class_get_generic_class (klass);
761 break;
763 case MONO_TYPE_ARRAY: {
764 MonoArrayType *array;
765 int i;
767 // FIXME: memory management
768 array = g_new0 (MonoArrayType, 1);
769 array->eklass = decode_klass_ref (module, p, &p, error);
770 if (!array->eklass)
771 goto fail;
772 array->rank = decode_value (p, &p);
773 array->numsizes = decode_value (p, &p);
775 if (array->numsizes)
776 array->sizes = (int *)g_malloc0 (sizeof (int) * array->numsizes);
777 for (i = 0; i < array->numsizes; ++i)
778 array->sizes [i] = decode_value (p, &p);
780 array->numlobounds = decode_value (p, &p);
781 if (array->numlobounds)
782 array->lobounds = (int *)g_malloc0 (sizeof (int) * array->numlobounds);
783 for (i = 0; i < array->numlobounds; ++i)
784 array->lobounds [i] = decode_value (p, &p);
785 t->data.array = array;
786 break;
788 case MONO_TYPE_VAR:
789 case MONO_TYPE_MVAR: {
790 MonoClass *klass = decode_klass_ref (module, p, &p, error);
791 if (!klass)
792 goto fail;
793 t->data.generic_param = m_class_get_byval_arg (klass)->data.generic_param;
794 break;
796 default:
797 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid encoded type %d", t->type);
798 goto fail;
801 *endbuf = p;
803 return t;
804 fail:
805 g_free (t);
806 return NULL;
809 // FIXME: Error handling, memory management
811 static MonoMethodSignature*
812 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
814 ERROR_DECL (error);
815 MonoMethodSignature *sig;
816 guint32 flags;
817 int i, gen_param_count = 0, param_count, call_conv;
818 guint8 *p = buf;
819 gboolean hasthis, explicit_this, has_gen_params;
821 flags = *p;
822 p ++;
823 has_gen_params = (flags & 0x10) != 0;
824 hasthis = (flags & 0x20) != 0;
825 explicit_this = (flags & 0x40) != 0;
826 call_conv = flags & 0x0F;
828 if (has_gen_params)
829 gen_param_count = decode_value (p, &p);
830 param_count = decode_value (p, &p);
831 if (target && param_count != target->param_count)
832 return NULL;
833 sig = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
834 sig->param_count = param_count;
835 sig->sentinelpos = -1;
836 sig->hasthis = hasthis;
837 sig->explicit_this = explicit_this;
838 sig->call_convention = call_conv;
839 sig->generic_param_count = gen_param_count;
840 sig->ret = decode_type (module, p, &p, error);
841 if (!sig->ret)
842 goto fail;
843 for (i = 0; i < param_count; ++i) {
844 if (*p == MONO_TYPE_SENTINEL) {
845 g_assert (sig->call_convention == MONO_CALL_VARARG);
846 sig->sentinelpos = i;
847 p ++;
849 sig->params [i] = decode_type (module, p, &p, error);
850 if (!sig->params [i])
851 goto fail;
854 if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
855 sig->sentinelpos = sig->param_count;
857 *endbuf = p;
859 return sig;
860 fail:
861 mono_error_cleanup (error); /* FIXME don't swallow the error */
862 g_free (sig);
863 return NULL;
866 static MonoMethodSignature*
867 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
869 return decode_signature_with_target (module, NULL, buf, endbuf);
872 static gboolean
873 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
875 MonoMethodSignature *sig;
876 gboolean res;
877 guint8 *p = buf;
879 sig = decode_signature_with_target (module, mono_method_signature_internal (target), p, &p);
880 res = sig && mono_metadata_signature_equal (mono_method_signature_internal (target), sig);
881 g_free (sig);
882 *endbuf = p;
883 return res;
886 /* Stores information returned by decode_method_ref () */
887 typedef struct {
888 MonoImage *image;
889 guint32 token;
890 MonoMethod *method;
891 gboolean no_aot_trampoline;
892 } MethodRef;
895 * decode_method_ref_with_target:
897 * Decode a method reference, storing the image/token into a MethodRef structure.
898 * This avoids loading metadata for the method if the caller does not need it. If the method has
899 * no token, then it is loaded from metadata and ref->method is set to the method instance.
900 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
901 * couldn't resolve to TARGET, and return FALSE.
902 * There are some kinds of method references which only support a non-null TARGET.
903 * This means that its not possible to decode this into a method, only to check
904 * that the method reference matches a given method. This is normally not a problem
905 * as these wrappers only occur in the extra_methods table, where we already have
906 * a method we want to lookup.
908 * If there was a decoding error, we return FALSE and set @error
910 static gboolean
911 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
913 guint32 image_index, value;
914 MonoImage *image = NULL;
915 guint8 *p = buf;
917 memset (ref, 0, sizeof (MethodRef));
918 error_init (error);
920 value = decode_value (p, &p);
921 image_index = value >> 24;
923 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
924 ref->no_aot_trampoline = TRUE;
925 value = decode_value (p, &p);
926 image_index = value >> 24;
929 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC ||
930 image_index == MONO_AOT_METHODREF_GINST || image_index == MONO_AOT_METHODREF_BLOB_INDEX) {
931 if (target && target->wrapper_type) {
932 return FALSE;
936 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
937 WrapperInfo *info;
938 guint32 wrapper_type;
940 wrapper_type = decode_value (p, &p);
942 if (target && target->wrapper_type != wrapper_type)
943 return FALSE;
945 /* Doesn't matter */
946 image = mono_defaults.corlib;
948 switch (wrapper_type) {
949 #ifndef DISABLE_REMOTING
950 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
951 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
952 if (!m)
953 return FALSE;
954 mono_class_init_internal (m->klass);
955 if (mono_aot_only)
956 ref->method = m;
957 else {
958 ref->method = mono_marshal_get_remoting_invoke_with_check (m, error);
959 return_val_if_nok (error, FALSE);
961 break;
963 case MONO_WRAPPER_PROXY_ISINST: {
964 MonoClass *klass = decode_klass_ref (module, p, &p, error);
965 if (!klass)
966 return FALSE;
967 ref->method = mono_marshal_get_proxy_cancast (klass);
968 break;
970 case MONO_WRAPPER_LDFLD:
971 case MONO_WRAPPER_LDFLDA:
972 case MONO_WRAPPER_STFLD: {
973 MonoClass *klass = decode_klass_ref (module, p, &p, error);
974 if (!klass)
975 return FALSE;
976 MonoType *type = m_class_get_byval_arg (klass);
977 if (wrapper_type == MONO_WRAPPER_LDFLD)
978 ref->method = mono_marshal_get_ldfld_wrapper (type);
979 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
980 ref->method = mono_marshal_get_ldflda_wrapper (type);
981 else if (wrapper_type == MONO_WRAPPER_STFLD)
982 ref->method = mono_marshal_get_stfld_wrapper (type);
983 else {
984 mono_error_set_bad_image_by_name (error, module->aot_name, "Unknown AOT wrapper type %d", wrapper_type);
985 return FALSE;
987 break;
989 #endif
990 case MONO_WRAPPER_ALLOC: {
991 int atype = decode_value (p, &p);
992 ManagedAllocatorVariant variant =
993 mono_profiler_allocations_enabled () ?
994 MANAGED_ALLOCATOR_PROFILER : MANAGED_ALLOCATOR_REGULAR;
996 ref->method = mono_gc_get_managed_allocator_by_type (atype, variant);
997 /* Try to fallback to the slow path version */
998 if (!ref->method)
999 ref->method = mono_gc_get_managed_allocator_by_type (atype, MANAGED_ALLOCATOR_SLOW_PATH);
1000 if (!ref->method) {
1001 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");
1002 return FALSE;
1004 break;
1006 case MONO_WRAPPER_WRITE_BARRIER: {
1007 ref->method = mono_gc_get_write_barrier ();
1008 break;
1010 case MONO_WRAPPER_STELEMREF: {
1011 int subtype = decode_value (p, &p);
1013 if (subtype == WRAPPER_SUBTYPE_NONE) {
1014 ref->method = mono_marshal_get_stelemref ();
1015 } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
1016 int kind;
1018 kind = decode_value (p, &p);
1020 /* Can't decode this */
1021 if (!target)
1022 return FALSE;
1023 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
1024 info = mono_marshal_get_wrapper_info (target);
1026 g_assert (info);
1027 if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
1028 ref->method = target;
1029 else
1030 return FALSE;
1031 } else {
1032 return FALSE;
1034 } else {
1035 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid STELEMREF subtype %d", subtype);
1036 return FALSE;
1038 break;
1040 case MONO_WRAPPER_SYNCHRONIZED: {
1041 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1042 if (!m)
1043 return FALSE;
1044 ref->method = mono_marshal_get_synchronized_wrapper (m);
1045 break;
1047 case MONO_WRAPPER_OTHER: {
1048 int subtype = decode_value (p, &p);
1050 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
1051 MonoClass *klass = decode_klass_ref (module, p, &p, error);
1052 if (!klass)
1053 return FALSE;
1055 if (!target)
1056 return FALSE;
1057 if (klass != target->klass)
1058 return FALSE;
1060 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
1061 if (strcmp (target->name, "PtrToStructure"))
1062 return FALSE;
1063 ref->method = mono_marshal_get_ptr_to_struct (klass);
1064 } else {
1065 if (strcmp (target->name, "StructureToPtr"))
1066 return FALSE;
1067 ref->method = mono_marshal_get_struct_to_ptr (klass);
1069 } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
1070 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1071 if (!m)
1072 return FALSE;
1073 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
1074 } else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
1075 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1076 if (!m)
1077 return FALSE;
1078 ref->method = mono_marshal_get_array_accessor_wrapper (m);
1079 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
1080 ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
1081 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
1082 ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
1083 } else if (subtype == WRAPPER_SUBTYPE_INTERP_IN) {
1084 MonoMethodSignature *sig = decode_signature (module, p, &p);
1085 if (!sig)
1086 return FALSE;
1087 ref->method = mini_get_interp_in_wrapper (sig);
1088 } else if (subtype == WRAPPER_SUBTYPE_INTERP_LMF) {
1089 MonoJitICallInfo *info = mono_find_jit_icall_by_name ((char *) p);
1090 g_assert (info);
1091 ref->method = mini_get_interp_lmf_wrapper (info->name, (gpointer) info->func);
1092 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
1093 MonoMethodSignature *sig = decode_signature (module, p, &p);
1094 if (!sig)
1095 return FALSE;
1096 ref->method = mini_get_gsharedvt_in_sig_wrapper (sig);
1097 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
1098 MonoMethodSignature *sig = decode_signature (module, p, &p);
1099 if (!sig)
1100 return FALSE;
1101 ref->method = mini_get_gsharedvt_out_sig_wrapper (sig);
1102 } else {
1103 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid UNKNOWN wrapper subtype %d", subtype);
1104 return FALSE;
1106 break;
1108 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
1109 int subtype = decode_value (p, &p);
1111 if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
1112 int rank = decode_value (p, &p);
1113 int elem_size = decode_value (p, &p);
1115 ref->method = mono_marshal_get_array_address (rank, elem_size);
1116 } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
1117 MonoMethod *m;
1119 m = decode_resolve_method_ref (module, p, &p, error);
1120 if (!m)
1121 return FALSE;
1123 if (!target)
1124 return FALSE;
1125 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
1127 info = mono_marshal_get_wrapper_info (target);
1128 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
1129 ref->method = target;
1130 else
1131 return FALSE;
1133 break;
1135 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
1136 MonoMethod *m;
1137 int subtype = decode_value (p, &p);
1138 char *name;
1140 if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
1141 name = (char*)p;
1143 MonoJitICallInfo *info = mono_find_jit_icall_by_name (name);
1144 g_assert (info);
1145 ref->method = mono_icall_get_wrapper_method (info);
1146 } else {
1147 m = decode_resolve_method_ref (module, p, &p, error);
1148 if (!m)
1149 return FALSE;
1151 /* This should only happen when looking for an extra method */
1152 if (!target)
1153 return FALSE;
1154 if (mono_marshal_method_from_wrapper (target) == m)
1155 ref->method = target;
1156 else
1157 return FALSE;
1159 break;
1161 case MONO_WRAPPER_CASTCLASS: {
1162 int subtype = decode_value (p, &p);
1164 if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
1165 ref->method = mono_marshal_get_castclass_with_cache ();
1166 else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
1167 ref->method = mono_marshal_get_isinst_with_cache ();
1168 else {
1169 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid CASTCLASS wrapper subtype %d", subtype);
1170 return FALSE;
1172 break;
1174 case MONO_WRAPPER_RUNTIME_INVOKE: {
1175 int subtype = decode_value (p, &p);
1177 if (!target)
1178 return FALSE;
1180 if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
1181 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
1182 return FALSE;
1183 ref->method = target;
1184 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
1185 /* Direct wrapper */
1186 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1187 if (!m)
1188 return FALSE;
1189 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
1190 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
1191 /* Virtual direct wrapper */
1192 MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
1193 if (!m)
1194 return FALSE;
1195 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
1196 } else {
1197 MonoMethodSignature *sig;
1199 sig = decode_signature_with_target (module, NULL, p, &p);
1200 info = mono_marshal_get_wrapper_info (target);
1201 g_assert (info);
1203 if (info->subtype != subtype)
1204 return FALSE;
1205 g_assert (info->d.runtime_invoke.sig);
1206 if (mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig))
1207 ref->method = target;
1208 else
1209 return FALSE;
1211 break;
1213 case MONO_WRAPPER_DELEGATE_INVOKE:
1214 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1215 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
1216 gboolean is_inflated = decode_value (p, &p);
1217 WrapperSubtype subtype;
1219 if (is_inflated) {
1220 MonoClass *klass;
1221 MonoMethod *invoke, *wrapper;
1223 klass = decode_klass_ref (module, p, &p, error);
1224 if (!klass)
1225 return FALSE;
1227 switch (wrapper_type) {
1228 case MONO_WRAPPER_DELEGATE_INVOKE:
1229 invoke = mono_get_delegate_invoke_internal (klass);
1230 wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
1231 break;
1232 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1233 invoke = mono_get_delegate_begin_invoke_internal (klass);
1234 wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
1235 break;
1236 case MONO_WRAPPER_DELEGATE_END_INVOKE:
1237 invoke = mono_get_delegate_end_invoke_internal (klass);
1238 wrapper = mono_marshal_get_delegate_end_invoke (invoke);
1239 break;
1240 default:
1241 g_assert_not_reached ();
1242 break;
1244 if (target) {
1246 * Due to the way mini_get_shared_method_full () works, we could end up with
1247 * multiple copies of the same wrapper.
1249 if (wrapper->klass != target->klass)
1250 return FALSE;
1251 ref->method = target;
1252 } else {
1253 ref->method = wrapper;
1255 } else {
1257 * These wrappers are associated with a signature, not with a method.
1258 * Since we can't decode them into methods, they need a target method.
1260 if (!target)
1261 return FALSE;
1263 if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1264 subtype = (WrapperSubtype)decode_value (p, &p);
1265 info = mono_marshal_get_wrapper_info (target);
1266 if (info) {
1267 if (info->subtype != subtype)
1268 return FALSE;
1269 } else {
1270 if (subtype != WRAPPER_SUBTYPE_NONE)
1271 return FALSE;
1274 if (sig_matches_target (module, target, p, &p))
1275 ref->method = target;
1276 else
1277 return FALSE;
1279 break;
1281 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1282 MonoMethod *m;
1283 MonoClass *klass;
1285 m = decode_resolve_method_ref (module, p, &p, error);
1286 if (!m)
1287 return FALSE;
1288 klass = decode_klass_ref (module, p, &p, error);
1289 if (!klass)
1290 return FALSE;
1291 ref->method = mono_marshal_get_managed_wrapper (m, klass, 0, error);
1292 if (!mono_error_ok (error))
1293 return FALSE;
1294 break;
1296 default:
1297 g_assert_not_reached ();
1299 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1300 image_index = decode_value (p, &p);
1301 ref->token = decode_value (p, &p);
1303 image = load_image (module, image_index, error);
1304 if (!image)
1305 return FALSE;
1306 } else if (image_index == MONO_AOT_METHODREF_BLOB_INDEX) {
1307 guint32 offset = decode_value (p, &p);
1309 guint8 *p2;
1311 p2 = module->blob + offset;
1312 if (!decode_method_ref_with_target (module, ref, target, p2, &p2, error))
1313 return FALSE;
1314 image = ref->image;
1315 if (!image)
1316 return FALSE;
1317 } else if (image_index == MONO_AOT_METHODREF_GINST) {
1318 MonoClass *klass;
1319 MonoGenericContext ctx;
1320 guint32 token_index;
1323 * These methods do not have a token which resolves them, so we
1324 * resolve them immediately.
1326 klass = decode_klass_ref (module, p, &p, error);
1327 if (!klass)
1328 return FALSE;
1330 if (target && target->klass != klass)
1331 return FALSE;
1333 image_index = decode_value (p, &p);
1334 token_index = decode_value (p, &p);
1335 ref->token = mono_metadata_make_token (MONO_TABLE_METHOD, token_index);
1337 image = load_image (module, image_index, error);
1338 if (!image)
1339 return FALSE;
1341 ref->method = mono_get_method_checked (image, ref->token, NULL, NULL, error);
1342 if (!ref->method)
1343 return FALSE;
1345 memset (&ctx, 0, sizeof (ctx));
1347 if (FALSE && mono_class_is_ginst (klass)) {
1348 ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
1349 ctx.method_inst = NULL;
1351 ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
1352 if (!ref->method)
1353 return FALSE;
1356 memset (&ctx, 0, sizeof (ctx));
1358 if (!decode_generic_context (module, &ctx, p, &p, error))
1359 return FALSE;
1361 ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
1362 if (!ref->method)
1363 return FALSE;
1365 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1366 MonoClass *klass;
1367 int method_type;
1369 klass = decode_klass_ref (module, p, &p, error);
1370 if (!klass)
1371 return FALSE;
1372 method_type = decode_value (p, &p);
1373 switch (method_type) {
1374 case 0:
1375 ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass), 0, error);
1376 return_val_if_nok (error, FALSE);
1377 break;
1378 case 1:
1379 ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass) * 2, 0, error);
1380 return_val_if_nok (error, FALSE);
1381 break;
1382 case 2:
1383 ref->method = mono_class_get_method_from_name_checked (klass, "Get", -1, 0, error);
1384 return_val_if_nok (error, FALSE);
1385 break;
1386 case 3:
1387 ref->method = mono_class_get_method_from_name_checked (klass, "Address", -1, 0, error);
1388 return_val_if_nok (error, FALSE);
1389 break;
1390 case 4:
1391 ref->method = mono_class_get_method_from_name_checked (klass, "Set", -1, 0, error);
1392 return_val_if_nok (error, FALSE);
1393 break;
1394 default:
1395 mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid METHODREF_ARRAY method type %d", method_type);
1396 return FALSE;
1398 } else {
1399 if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
1400 image_index = decode_value (p, &p);
1401 value = decode_value (p, &p);
1404 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1406 image = load_image (module, image_index, error);
1407 if (!image)
1408 return FALSE;
1411 *endbuf = p;
1413 ref->image = image;
1415 return TRUE;
1418 static gboolean
1419 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf, MonoError *error)
1421 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf, error);
1425 * decode_resolve_method_ref_with_target:
1427 * Similar to decode_method_ref, but resolve and return the method itself.
1429 static MonoMethod*
1430 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
1432 MethodRef ref;
1434 error_init (error);
1436 if (!decode_method_ref_with_target (module, &ref, target, buf, endbuf, error))
1437 return NULL;
1438 if (ref.method)
1439 return ref.method;
1440 if (!ref.image) {
1441 mono_error_set_bad_image_by_name (error, module->aot_name, "No image found for methodref with target");
1442 return NULL;
1444 return mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
1447 static MonoMethod*
1448 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
1450 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf, error);
1453 #ifdef ENABLE_AOT_CACHE
1455 /* AOT CACHE */
1458 * FIXME:
1459 * - Add options for controlling the cache size
1460 * - Handle full cache by deleting old assemblies lru style
1461 * - Maybe add a threshold after an assembly is AOT compiled
1462 * - Add options for enabling this for specific main assemblies
1465 /* The cache directory */
1466 static char *cache_dir;
1468 /* The number of assemblies AOTed in this run */
1469 static int cache_count;
1471 /* Whenever to AOT in-process */
1472 static gboolean in_process;
1474 static void
1475 collect_assemblies (gpointer data, gpointer user_data)
1477 MonoAssembly *ass = (MonoAssembly*)data;
1478 GSList **l = (GSList**)user_data;
1480 *l = g_slist_prepend (*l, ass);
1483 #define SHA1_DIGEST_LENGTH 20
1486 * get_aot_config_hash:
1488 * Return a hash for all the version information an AOT module depends on.
1490 static G_GNUC_UNUSED char*
1491 get_aot_config_hash (MonoAssembly *assembly)
1493 char *build_info;
1494 GSList *l, *assembly_list = NULL;
1495 GString *s;
1496 int i;
1497 guint8 digest [SHA1_DIGEST_LENGTH];
1498 char *digest_str;
1500 build_info = mono_get_runtime_build_info ();
1502 s = g_string_new (build_info);
1504 mono_assembly_foreach (collect_assemblies, &assembly_list);
1507 * The assembly list includes the current assembly as well, no need
1508 * to add it.
1510 for (l = assembly_list; l; l = l->next) {
1511 MonoAssembly *ass = (MonoAssembly*)l->data;
1513 g_string_append (s, "_");
1514 g_string_append (s, ass->aname.name);
1515 g_string_append (s, "_");
1516 g_string_append (s, ass->image->guid);
1519 for (i = 0; i < s->len; ++i) {
1520 if (!isalnum (s->str [i]) && s->str [i] != '-')
1521 s->str [i] = '_';
1524 mono_sha1_get_digest ((guint8*)s->str, s->len, digest);
1526 digest_str = g_malloc0 ((SHA1_DIGEST_LENGTH * 2) + 1);
1527 for (i = 0; i < SHA1_DIGEST_LENGTH; ++i)
1528 sprintf (digest_str + (i * 2), "%02x", digest [i]);
1530 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: file dependencies: %s, hash %s", s->str, digest_str);
1532 g_string_free (s, TRUE);
1534 return digest_str;
1537 static void
1538 aot_cache_init (void)
1540 if (mono_aot_only)
1541 return;
1542 enable_aot_cache = TRUE;
1543 in_process = TRUE;
1547 * aot_cache_load_module:
1549 * Load the AOT image corresponding to ASSEMBLY from the aot cache, AOTing it if neccessary.
1551 static MonoDl*
1552 aot_cache_load_module (MonoAssembly *assembly, char **aot_name)
1554 MonoAotCacheConfig *config;
1555 GSList *l;
1556 char *fname, *tmp2, *aot_options, *failure_fname;
1557 const char *home;
1558 MonoDl *module;
1559 gboolean res;
1560 gint exit_status;
1561 char *hash;
1562 int pid;
1563 gboolean enabled;
1564 FILE *failure_file;
1566 *aot_name = NULL;
1568 if (image_is_dynamic (assembly->image))
1569 return NULL;
1571 /* Check in the list of assemblies enabled for aot caching */
1572 config = mono_get_aot_cache_config ();
1574 enabled = FALSE;
1575 if (config->apps) {
1576 MonoDomain *domain = mono_domain_get ();
1577 MonoAssembly *entry_assembly = domain->entry_assembly;
1579 // FIXME: This cannot be used for mscorlib during startup, since entry_assembly is not set yet
1580 for (l = config->apps; l; l = l->next) {
1581 char *n = (char*)l->data;
1583 if ((entry_assembly && !strcmp (entry_assembly->aname.name, n)) || (!entry_assembly && !strcmp (assembly->aname.name, n)))
1584 break;
1586 if (l)
1587 enabled = TRUE;
1590 if (!enabled) {
1591 for (l = config->assemblies; l; l = l->next) {
1592 char *n = (char*)l->data;
1594 if (!strcmp (assembly->aname.name, n))
1595 break;
1597 if (l)
1598 enabled = TRUE;
1600 if (!enabled)
1601 return NULL;
1603 if (!cache_dir) {
1604 home = g_get_home_dir ();
1605 if (!home)
1606 return NULL;
1607 cache_dir = g_strdup_printf ("%s/Library/Caches/mono/aot-cache", home);
1608 if (!g_file_test (cache_dir, (GFileTest)(G_FILE_TEST_EXISTS|G_FILE_TEST_IS_DIR)))
1609 g_mkdir_with_parents (cache_dir, 0777);
1613 * The same assembly can be used in multiple configurations, i.e. multiple
1614 * versions of the runtime, with multiple versions of dependent assemblies etc.
1615 * To handle this, we compute a version string containing all this information, hash it,
1616 * and use the hash as a filename suffix.
1618 hash = get_aot_config_hash (assembly);
1620 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, hash, MONO_SOLIB_EXT);
1621 fname = g_build_filename (cache_dir, tmp2, NULL);
1622 *aot_name = fname;
1623 g_free (tmp2);
1625 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: loading from cache: '%s'.", fname);
1626 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1628 if (module) {
1629 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: found in cache: '%s'.", fname);
1630 return module;
1633 if (mono_is_corlib_image (assembly->image) && !mscorlib_aot_loaded)
1635 * Can't AOT this during startup, so we AOT it when called later from
1636 * mono_aot_get_method ().
1638 return NULL;
1640 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: not found.");
1642 /* Only AOT one assembly per run to avoid slowing down execution too much */
1643 if (cache_count > 0)
1644 return NULL;
1645 cache_count ++;
1647 /* Check for previous failure */
1648 failure_fname = g_strdup_printf ("%s.failure", fname);
1649 failure_file = fopen (failure_fname, "r");
1650 if (failure_file) {
1651 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: assembly '%s' previously failed to compile '%s' ('%s')... ", assembly->image->name, fname, failure_fname);
1652 g_free (failure_fname);
1653 return NULL;
1654 } else {
1655 g_free (failure_fname);
1656 fclose (failure_file);
1659 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compiling assembly '%s', logfile: '%s.log'... ", assembly->image->name, fname);
1662 * We need to invoke the AOT compiler here. There are multiple approaches:
1663 * - spawn a new runtime process. This can be hard when running with mkbundle, and
1664 * its hard to make the new process load the same set of assemblies.
1665 * - doing it in-process. This exposes the current process to bugs/leaks/side effects of
1666 * the AOT compiler.
1667 * - fork a new process and do the work there.
1669 if (in_process) {
1670 aot_options = g_strdup_printf ("outfile=%s,internal-logfile=%s.log%s%s", fname, fname, config->aot_options ? "," : "", config->aot_options ? config->aot_options : "");
1671 /* Maybe due this in another thread ? */
1672 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options, NULL);
1673 if (res) {
1674 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compilation failed.");
1675 failure_fname = g_strdup_printf ("%s.failure", fname);
1676 failure_file = fopen (failure_fname, "a+");
1677 fclose (failure_file);
1678 g_free (failure_fname);
1679 } else {
1680 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compilation succeeded.");
1682 } else {
1684 * - Avoid waiting for the aot process to finish ?
1685 * (less overhead, but multiple processes could aot the same assembly at the same time)
1687 pid = fork ();
1688 if (pid == 0) {
1689 FILE *logfile;
1690 char *logfile_name;
1692 /* Child */
1694 logfile_name = g_strdup_printf ("%s/aot.log", cache_dir);
1695 logfile = fopen (logfile_name, "a+");
1696 g_free (logfile_name);
1698 dup2 (fileno (logfile), 1);
1699 dup2 (fileno (logfile), 2);
1701 aot_options = g_strdup_printf ("outfile=%s", fname);
1702 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options, NULL);
1703 if (!res) {
1704 exit (1);
1705 } else {
1706 exit (0);
1708 } else {
1709 /* Parent */
1710 waitpid (pid, &exit_status, 0);
1711 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1712 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: failed.");
1713 else
1714 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: succeeded.");
1718 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1720 return module;
1723 #else
1725 static void
1726 aot_cache_init (void)
1730 static MonoDl*
1731 aot_cache_load_module (MonoAssembly *assembly, char **aot_name)
1733 return NULL;
1736 #endif
1738 static void
1739 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1741 if (globals) {
1742 int global_index;
1743 guint16 *table, *entry;
1744 guint16 table_size;
1745 guint32 hash;
1746 char *symbol = (char*)name;
1748 #ifdef TARGET_MACH
1749 symbol = g_strdup_printf ("_%s", name);
1750 #endif
1752 /* The first entry points to the hash */
1753 table = (guint16 *)globals [0];
1754 globals ++;
1756 table_size = table [0];
1757 table ++;
1759 hash = mono_metadata_str_hash (symbol) % table_size;
1761 entry = &table [hash * 2];
1763 /* Search the hash for the index into the globals table */
1764 global_index = -1;
1765 while (entry [0] != 0) {
1766 guint32 index = entry [0] - 1;
1767 guint32 next = entry [1];
1769 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1771 if (!strcmp ((const char*)globals [index * 2], symbol)) {
1772 global_index = index;
1773 break;
1776 if (next != 0) {
1777 entry = &table [next * 2];
1778 } else {
1779 break;
1783 if (global_index != -1)
1784 *value = globals [global_index * 2 + 1];
1785 else
1786 *value = NULL;
1788 if (symbol != name)
1789 g_free (symbol);
1790 } else {
1791 char *err = mono_dl_symbol (module, name, value);
1793 if (err)
1794 g_free (err);
1798 static void
1799 find_amodule_symbol (MonoAotModule *amodule, const char *name, gpointer *value)
1801 g_assert (!(amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY));
1803 find_symbol (amodule->sofile, amodule->globals, name, value);
1806 void
1807 mono_install_load_aot_data_hook (MonoLoadAotDataFunc load_func, MonoFreeAotDataFunc free_func, gpointer user_data)
1809 aot_data_load_func = load_func;
1810 aot_data_free_func = free_func;
1811 aot_data_func_user_data = user_data;
1814 /* Load the separate aot data file for ASSEMBLY */
1815 static guint8*
1816 open_aot_data (MonoAssembly *assembly, MonoAotFileInfo *info, void **ret_handle)
1818 MonoFileMap *map;
1819 char *filename;
1820 guint8 *data;
1822 if (aot_data_load_func) {
1823 data = aot_data_load_func (assembly, info->datafile_size, aot_data_func_user_data, ret_handle);
1824 g_assert (data);
1825 return data;
1829 * Use <assembly name>.aotdata as the default implementation if no callback is given
1831 filename = g_strdup_printf ("%s.aotdata", assembly->image->name);
1832 map = mono_file_map_open (filename);
1833 g_assert (map);
1834 data = (guint8*)mono_file_map (info->datafile_size, MONO_MMAP_READ, mono_file_map_fd (map), 0, ret_handle);
1835 g_assert (data);
1837 return data;
1840 static gboolean
1841 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, guint8 *blob, char **out_msg)
1843 char *build_info;
1844 char *msg = NULL;
1845 gboolean usable = TRUE;
1846 gboolean full_aot, interp, safepoints;
1847 guint32 excluded_cpu_optimizations;
1849 if (strcmp (assembly->image->guid, (const char*)info->assembly_guid)) {
1850 msg = g_strdup_printf ("doesn't match assembly");
1851 usable = FALSE;
1854 build_info = mono_get_runtime_build_info ();
1855 if (strlen ((const char *)info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1856 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1857 usable = FALSE;
1859 g_free (build_info);
1861 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1862 interp = info->flags & MONO_AOT_FILE_FLAG_INTERP;
1864 if (mono_aot_only && !full_aot) {
1865 if (!interp) {
1866 msg = g_strdup_printf ("not compiled with --aot=full");
1867 usable = FALSE;
1870 if (!mono_aot_only && full_aot) {
1871 msg = g_strdup_printf ("compiled with --aot=full");
1872 usable = FALSE;
1874 if (mono_use_interpreter && !interp && !strcmp (assembly->aname.name, "mscorlib")) {
1875 /* mscorlib contains necessary interpreter trampolines */
1876 msg = g_strdup_printf ("not compiled with --aot=interp");
1877 usable = FALSE;
1879 if (mono_llvm_only && !(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
1880 msg = g_strdup_printf ("not compiled with --aot=llvmonly");
1881 usable = FALSE;
1883 if (mono_use_llvm && !(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)) {
1884 /* Prefer LLVM JITted code when using --llvm */
1885 msg = g_strdup_printf ("not compiled with --aot=llvm");
1886 usable = FALSE;
1888 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot && !interp) {
1889 msg = g_strdup_printf ("not compiled for debugging");
1890 usable = FALSE;
1893 mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1894 if (info->opts & excluded_cpu_optimizations) {
1895 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1896 usable = FALSE;
1899 if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
1900 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1901 usable = FALSE;
1904 if (info->gc_name_index != -1) {
1905 char *gc_name = (char*)&blob [info->gc_name_index];
1906 const char *current_gc_name = mono_gc_get_gc_name ();
1908 if (strcmp (current_gc_name, gc_name) != 0) {
1909 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1910 usable = FALSE;
1914 safepoints = info->flags & MONO_AOT_FILE_FLAG_SAFEPOINTS;
1916 if (!safepoints && mono_threads_are_safepoints_enabled ()) {
1917 msg = g_strdup_printf ("not compiled with safepoints");
1918 usable = FALSE;
1921 *out_msg = msg;
1922 return usable;
1926 * TABLE should point to a table of call instructions. Return the address called by the INDEXth entry.
1928 static void*
1929 get_call_table_entry (void *table, int index)
1931 #if defined(TARGET_ARM)
1932 guint32 *ins_addr;
1933 guint32 ins;
1934 gint32 offset;
1936 ins_addr = (guint32*)table + index;
1937 ins = *ins_addr;
1938 if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
1939 /* blx */
1940 offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
1941 return (char*)ins_addr + (offset * 2) + 8 + 1;
1942 } else {
1943 offset = (((int)ins & 0xffffff) << 8) >> 8;
1944 return (char*)ins_addr + (offset * 4) + 8;
1946 #elif defined(TARGET_ARM64)
1947 return mono_arch_get_call_target ((guint8*)table + (index * 4) + 4);
1948 #elif defined(TARGET_X86) || defined(TARGET_AMD64)
1949 /* The callee expects an ip which points after the call */
1950 return mono_arch_get_call_target ((guint8*)table + (index * 5) + 5);
1951 #else
1952 g_assert_not_reached ();
1953 return NULL;
1954 #endif
1958 * init_amodule_got:
1960 * Initialize the shared got entries for AMODULE.
1962 static void
1963 init_amodule_got (MonoAotModule *amodule)
1965 MonoJumpInfo *ji;
1966 MonoMemPool *mp;
1967 MonoJumpInfo *patches;
1968 guint32 got_offsets [128];
1969 ERROR_DECL (error);
1970 int i, npatches;
1972 /* These can't be initialized in load_aot_module () */
1973 if (amodule->got_initialized == GOT_INITIALIZED)
1974 return;
1976 mono_loader_lock ();
1979 * If it is initialized some other thread did it in the meantime. If it is
1980 * initializing it means the current thread is initializing it since we are
1981 * holding the loader lock, skip it.
1983 if (amodule->got_initialized) {
1984 mono_loader_unlock ();
1985 return;
1988 amodule->got_initialized = GOT_INITIALIZING;
1990 mp = mono_mempool_new ();
1991 npatches = amodule->info.nshared_got_entries;
1992 for (i = 0; i < npatches; ++i)
1993 got_offsets [i] = i;
1994 if (amodule->got)
1995 patches = decode_patches (amodule, mp, npatches, FALSE, got_offsets);
1996 else
1997 patches = decode_patches (amodule, mp, npatches, TRUE, got_offsets);
1998 g_assert (patches);
1999 for (i = 0; i < npatches; ++i) {
2000 ji = &patches [i];
2002 if (ji->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR && !mono_gc_is_moving ()) {
2003 amodule->shared_got [i] = NULL;
2004 } else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_START && !mono_gc_is_moving ()) {
2005 amodule->shared_got [i] = NULL;
2006 } else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_BITS && !mono_gc_is_moving ()) {
2007 amodule->shared_got [i] = NULL;
2008 } else if (ji->type == MONO_PATCH_INFO_IMAGE) {
2009 amodule->shared_got [i] = amodule->assembly->image;
2010 } else if (ji->type == MONO_PATCH_INFO_MSCORLIB_GOT_ADDR) {
2011 if (mono_defaults.corlib) {
2012 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
2014 if (mscorlib_amodule)
2015 amodule->shared_got [i] = mscorlib_amodule->got;
2016 } else {
2017 amodule->shared_got [i] = amodule->got;
2019 } else if (ji->type == MONO_PATCH_INFO_AOT_MODULE) {
2020 amodule->shared_got [i] = amodule;
2021 } else {
2022 amodule->shared_got [i] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, ji, FALSE, error);
2023 mono_error_assert_ok (error);
2027 if (amodule->got) {
2028 for (i = 0; i < npatches; ++i)
2029 amodule->got [i] = amodule->shared_got [i];
2031 if (amodule->llvm_got) {
2032 for (i = 0; i < npatches; ++i)
2033 amodule->llvm_got [i] = amodule->shared_got [i];
2036 mono_mempool_destroy (mp);
2038 mono_memory_barrier ();
2039 amodule->got_initialized = GOT_INITIALIZED;
2040 mono_loader_unlock ();
2043 static void
2044 load_aot_module (MonoAssembly *assembly, gpointer user_data)
2046 char *aot_name, *found_aot_name;
2047 MonoAotModule *amodule;
2048 MonoDl *sofile;
2049 gboolean usable = TRUE;
2050 char *version_symbol = NULL;
2051 char *msg = NULL;
2052 gpointer *globals = NULL;
2053 MonoAotFileInfo *info = NULL;
2054 int i, version;
2055 gboolean do_load_image = TRUE;
2056 int align_double, align_int64;
2057 guint8 *aot_data = NULL;
2059 if (mono_compile_aot)
2060 return;
2062 if (mono_aot_mode == MONO_AOT_MODE_NONE)
2063 return;
2065 if (assembly->image->aot_module)
2067 * Already loaded. This can happen because the assembly loading code might invoke
2068 * the assembly load hooks multiple times for the same assembly.
2070 return;
2072 if (image_is_dynamic (assembly->image) || mono_asmctx_get_kind (&assembly->context) == MONO_ASMCTX_REFONLY || mono_domain_get () != mono_get_root_domain ())
2073 return;
2075 mono_aot_lock ();
2077 if (container_assm_name && !container_amodule) {
2078 char *local_ref = container_assm_name;
2079 container_assm_name = NULL;
2080 MonoImageOpenStatus status = MONO_IMAGE_OK;
2081 MonoAssemblyOpenRequest req;
2082 gchar *dll = g_strdup_printf ( "%s.dll", local_ref);
2083 mono_assembly_request_prepare (&req.request, sizeof (req), MONO_ASMCTX_DEFAULT);
2084 MonoAssembly *assm = mono_assembly_request_open (dll, &req, &status);
2085 if (!assm) {
2086 gchar *exe = g_strdup_printf ("%s.exe", local_ref);
2087 assm = mono_assembly_request_open (exe, &req, &status);
2089 g_assert (assm);
2090 load_aot_module (assm, NULL);
2091 container_amodule = assm->image->aot_module;
2094 if (static_aot_modules)
2095 info = (MonoAotFileInfo *)g_hash_table_lookup (static_aot_modules, assembly->aname.name);
2097 mono_aot_unlock ();
2099 sofile = NULL;
2101 found_aot_name = NULL;
2103 if (info) {
2104 /* Statically linked AOT module */
2105 aot_name = g_strdup_printf ("%s", assembly->aname.name);
2106 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.", aot_name);
2107 if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
2108 globals = (void **)info->globals;
2109 g_assert (globals);
2111 found_aot_name = g_strdup (aot_name);
2112 } else {
2113 char *err;
2115 if (enable_aot_cache)
2116 sofile = aot_cache_load_module (assembly, &aot_name);
2117 if (!sofile) {
2118 aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
2120 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
2121 if (sofile) {
2122 found_aot_name = g_strdup (aot_name);
2123 } else {
2124 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
2125 g_free (err);
2127 g_free (aot_name);
2129 #ifndef PLATFORM_ANDROID
2130 if (!sofile) {
2131 char *basename = g_path_get_basename (assembly->image->name);
2132 aot_name = g_strdup_printf ("%s/mono/aot-cache/%s/%s%s", mono_assembly_getrootdir(), MONO_ARCHITECTURE, basename, MONO_SOLIB_EXT);
2133 g_free (basename);
2134 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
2135 if (!sofile) {
2136 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
2137 g_free (err);
2139 g_free (aot_name);
2141 #endif
2142 if (!sofile) {
2143 GList *l;
2145 for (l = mono_aot_paths; l; l = l->next) {
2146 char *path = (char*)l->data;
2148 char *basename = g_path_get_basename (assembly->image->name);
2149 aot_name = g_strdup_printf ("%s/%s%s", path, basename, MONO_SOLIB_EXT);
2150 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
2151 if (sofile) {
2152 found_aot_name = g_strdup (aot_name);
2153 } else {
2154 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
2155 g_free (err);
2157 g_free (basename);
2158 g_free (aot_name);
2159 if (sofile)
2160 break;
2163 if (!sofile) {
2164 if (mono_aot_only && !mono_use_interpreter && assembly->image->tables [MONO_TABLE_METHOD].rows) {
2165 aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
2166 g_error ("Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
2167 g_free (aot_name);
2169 return;
2173 if (!info) {
2174 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
2175 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
2178 // Copy aotid to MonoImage
2179 memcpy(&assembly->image->aotid, info->aotid, 16);
2181 if (version_symbol) {
2182 /* Old file format */
2183 version = atoi (version_symbol);
2184 } else {
2185 g_assert (info);
2186 version = info->version;
2189 if (version != MONO_AOT_FILE_VERSION) {
2190 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
2191 usable = FALSE;
2192 } else {
2193 guint8 *blob;
2194 void *handle;
2196 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
2197 aot_data = open_aot_data (assembly, info, &handle);
2199 blob = aot_data + info->table_offsets [MONO_AOT_TABLE_BLOB];
2200 } else {
2201 blob = (guint8 *)info->blob;
2204 usable = check_usable (assembly, info, blob, &msg);
2207 if (!usable) {
2208 if (mono_aot_only) {
2209 g_error ("Failed to load AOT module '%s' while running in aot-only mode: %s.\n", found_aot_name, msg);
2210 } else {
2211 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable: %s.", found_aot_name, msg);
2213 g_free (msg);
2214 g_free (found_aot_name);
2215 if (sofile)
2216 mono_dl_close (sofile);
2217 assembly->image->aot_module = NULL;
2218 return;
2221 /* Sanity check */
2222 align_double = MONO_ABI_ALIGNOF (double);
2223 align_int64 = MONO_ABI_ALIGNOF (gint64);
2224 int card_table_shift_bits = 0;
2225 gpointer card_table_mask = NULL;
2226 mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2228 g_assert (info->double_align == align_double);
2229 g_assert (info->long_align == align_int64);
2230 g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
2231 g_assert (info->card_table_shift_bits == card_table_shift_bits);
2232 g_assert (info->card_table_mask == GPOINTER_TO_UINT (card_table_mask));
2234 amodule = g_new0 (MonoAotModule, 1);
2235 amodule->aot_name = found_aot_name;
2236 amodule->assembly = assembly;
2238 memcpy (&amodule->info, info, sizeof (*info));
2240 amodule->got = (void **)amodule->info.jit_got;
2241 amodule->llvm_got = (void **)amodule->info.llvm_got;
2242 amodule->globals = globals;
2243 amodule->sofile = sofile;
2244 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
2245 amodule->extra_methods = g_hash_table_new (NULL, NULL);
2246 amodule->shared_got = g_new0 (gpointer, info->nshared_got_entries);
2248 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
2249 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
2250 amodule->tables [i] = aot_data + info->table_offsets [i];
2253 mono_os_mutex_init_recursive (&amodule->mutex);
2255 /* Read image table */
2257 guint32 table_len, i;
2258 char *table = NULL;
2260 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA)
2261 table = (char *)amodule->tables [MONO_AOT_TABLE_IMAGE_TABLE];
2262 else
2263 table = (char *)info->image_table;
2264 g_assert (table);
2266 table_len = *(guint32*)table;
2267 table += sizeof (guint32);
2268 amodule->image_table = g_new0 (MonoImage*, table_len);
2269 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
2270 amodule->image_guids = g_new0 (char*, table_len);
2271 amodule->image_table_len = table_len;
2272 for (i = 0; i < table_len; ++i) {
2273 MonoAssemblyName *aname = &(amodule->image_names [i]);
2275 aname->name = g_strdup (table);
2276 table += strlen (table) + 1;
2277 amodule->image_guids [i] = g_strdup (table);
2278 table += strlen (table) + 1;
2279 if (table [0] != 0)
2280 aname->culture = g_strdup (table);
2281 table += strlen (table) + 1;
2282 memcpy (aname->public_key_token, table, strlen (table) + 1);
2283 table += strlen (table) + 1;
2285 table = (char *)ALIGN_PTR_TO (table, 8);
2286 aname->flags = *(guint32*)table;
2287 table += 4;
2288 aname->major = *(guint32*)table;
2289 table += 4;
2290 aname->minor = *(guint32*)table;
2291 table += 4;
2292 aname->build = *(guint32*)table;
2293 table += 4;
2294 aname->revision = *(guint32*)table;
2295 table += 4;
2299 amodule->jit_code_start = (guint8 *)info->jit_code_start;
2300 amodule->jit_code_end = (guint8 *)info->jit_code_end;
2301 if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
2302 amodule->blob = (guint8*)amodule->tables [MONO_AOT_TABLE_BLOB];
2303 amodule->method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_METHOD_INFO_OFFSETS];
2304 amodule->ex_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EX_INFO_OFFSETS];
2305 amodule->class_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_CLASS_INFO_OFFSETS];
2306 amodule->class_name_table = (guint16*)amodule->tables [MONO_AOT_TABLE_CLASS_NAME];
2307 amodule->extra_method_table = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_TABLE];
2308 amodule->extra_method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS];
2309 amodule->got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_GOT_INFO_OFFSETS];
2310 amodule->llvm_got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS];
2311 amodule->weak_field_indexes = (guint32*)amodule->tables [MONO_AOT_TABLE_WEAK_FIELD_INDEXES];
2312 } else {
2313 amodule->blob = (guint8*)info->blob;
2314 amodule->method_info_offsets = (guint32 *)info->method_info_offsets;
2315 amodule->ex_info_offsets = (guint32 *)info->ex_info_offsets;
2316 amodule->class_info_offsets = (guint32 *)info->class_info_offsets;
2317 amodule->class_name_table = (guint16 *)info->class_name_table;
2318 amodule->extra_method_table = (guint32 *)info->extra_method_table;
2319 amodule->extra_method_info_offsets = (guint32 *)info->extra_method_info_offsets;
2320 amodule->got_info_offsets = (guint32*)info->got_info_offsets;
2321 amodule->llvm_got_info_offsets = (guint32*)info->llvm_got_info_offsets;
2322 amodule->weak_field_indexes = (guint32*)info->weak_field_indexes;
2324 amodule->unbox_trampolines = (guint32 *)info->unbox_trampolines;
2325 amodule->unbox_trampolines_end = (guint32 *)info->unbox_trampolines_end;
2326 amodule->unbox_trampoline_addresses = (guint32 *)info->unbox_trampoline_addresses;
2327 amodule->unwind_info = (guint8 *)info->unwind_info;
2328 amodule->mem_begin = (guint8*)amodule->jit_code_start;
2329 amodule->mem_end = (guint8 *)info->mem_end;
2330 amodule->plt = (guint8 *)info->plt;
2331 amodule->plt_end = (guint8 *)info->plt_end;
2332 amodule->mono_eh_frame = (guint8 *)info->mono_eh_frame;
2333 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = (guint8 *)info->specific_trampolines;
2334 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = (guint8 *)info->static_rgctx_trampolines;
2335 amodule->trampolines [MONO_AOT_TRAMP_IMT] = (guint8 *)info->imt_trampolines;
2336 amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = (guint8 *)info->gsharedvt_arg_trampolines;
2337 amodule->trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = (guint8 *)info->ftnptr_arg_trampolines;
2338 amodule->trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = (guint8 *)info->unbox_arbitrary_trampolines;
2340 if (mono_is_corlib_image (assembly->image))
2341 mscorlib_aot_module = amodule;
2343 /* Compute method addresses */
2344 amodule->methods = (void **)g_malloc0 (amodule->info.nmethods * sizeof (gpointer));
2345 for (i = 0; i < amodule->info.nmethods; ++i) {
2346 void *addr = NULL;
2348 if (amodule->info.llvm_get_method) {
2349 gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
2351 addr = get_method (i);
2354 /* method_addresses () contains a table of branches, since the ios linker can update those correctly */
2355 if (!addr && amodule->info.method_addresses) {
2356 addr = get_call_table_entry (amodule->info.method_addresses, i);
2357 g_assert (addr);
2358 if (addr == amodule->info.method_addresses)
2359 addr = NULL;
2361 if (addr == NULL)
2362 amodule->methods [i] = GINT_TO_POINTER (-1);
2363 else
2364 amodule->methods [i] = addr;
2367 if (make_unreadable) {
2368 #ifndef TARGET_WIN32
2369 guint8 *addr;
2370 guint8 *page_start, *page_end;
2371 int err, len;
2373 addr = amodule->mem_begin;
2374 g_assert (addr);
2375 len = amodule->mem_end - amodule->mem_begin;
2377 /* Round down in both directions to avoid modifying data which is not ours */
2378 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
2379 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
2380 if (page_end > page_start) {
2381 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
2382 g_assert (err == 0);
2384 #endif
2387 /* Compute the boundaries of LLVM code */
2388 if (info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)
2389 compute_llvm_code_range (amodule, &amodule->llvm_code_start, &amodule->llvm_code_end);
2391 mono_aot_lock ();
2393 if (amodule->jit_code_start) {
2394 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->jit_code_start);
2395 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->jit_code_end);
2397 if (amodule->llvm_code_start) {
2398 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->llvm_code_start);
2399 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->llvm_code_end);
2402 g_hash_table_insert (aot_modules, assembly, amodule);
2403 mono_aot_unlock ();
2405 if (amodule->jit_code_start)
2406 mono_jit_info_add_aot_module (assembly->image, amodule->jit_code_start, amodule->jit_code_end);
2407 if (amodule->llvm_code_start)
2408 mono_jit_info_add_aot_module (assembly->image, amodule->llvm_code_start, amodule->llvm_code_end);
2410 assembly->image->aot_module = amodule;
2412 if (mono_aot_only && !mono_llvm_only) {
2413 char *code;
2414 find_amodule_symbol (amodule, "specific_trampolines_page", (gpointer *)&code);
2415 amodule->use_page_trampolines = code != NULL;
2416 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
2420 * Register the plt region as a single trampoline so we can unwind from this code
2422 mono_aot_tramp_info_register (
2423 mono_tramp_info_create (
2424 NULL,
2425 amodule->plt,
2426 amodule->plt_end - amodule->plt,
2427 NULL,
2428 mono_unwind_get_cie_program ()
2430 NULL
2434 * Since we store methoddef and classdef tokens when referring to methods/classes in
2435 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
2436 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
2437 * non-lazily, since we can't handle out-of-date errors later.
2438 * The cached class info also depends on the exact assemblies.
2440 if (do_load_image) {
2441 for (i = 0; i < amodule->image_table_len; ++i) {
2442 ERROR_DECL (error);
2443 load_image (amodule, i, error);
2444 mono_error_cleanup (error); /* FIXME don't swallow the error */
2448 if (amodule->out_of_date) {
2449 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: Module %s is unusable because a dependency is out-of-date.", assembly->image->name);
2450 if (mono_aot_only)
2451 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);
2452 } else {
2453 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: image '%s' found.", found_aot_name);
2458 * mono_aot_register_module:
2460 * This should be called by embedding code to register normal AOT modules statically linked
2461 * into the executable.
2463 * \param aot_info the value of the 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
2465 void
2466 mono_aot_register_module (gpointer *aot_info)
2468 gpointer *globals;
2469 char *aname;
2470 MonoAotFileInfo *info = (MonoAotFileInfo *)aot_info;
2472 g_assert (info->version == MONO_AOT_FILE_VERSION);
2474 if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
2475 globals = (void **)info->globals;
2476 g_assert (globals);
2479 aname = (char *)info->assembly_name;
2481 /* This could be called before startup */
2482 if (aot_modules)
2483 mono_aot_lock ();
2485 if (!static_aot_modules)
2486 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
2488 g_hash_table_insert (static_aot_modules, aname, info);
2490 if (info->flags & MONO_AOT_FILE_FLAG_EAGER_LOAD) {
2491 g_assert (!container_assm_name);
2492 container_assm_name = aname;
2495 if (aot_modules)
2496 mono_aot_unlock ();
2499 void
2500 mono_aot_init (void)
2502 mono_os_mutex_init_recursive (&aot_mutex);
2503 mono_os_mutex_init_recursive (&aot_page_mutex);
2504 aot_modules = g_hash_table_new (NULL, NULL);
2506 mono_install_assembly_load_hook (load_aot_module, NULL);
2507 mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
2509 char *lastaot = g_getenv ("MONO_LASTAOT");
2510 if (lastaot) {
2511 mono_last_aot_method = atoi (lastaot);
2512 g_free (lastaot);
2514 aot_cache_init ();
2517 void
2518 mono_aot_cleanup (void)
2520 g_hash_table_destroy (aot_jit_icall_hash);
2521 g_hash_table_destroy (aot_modules);
2524 static gboolean
2525 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
2527 ERROR_DECL (error);
2528 guint32 flags;
2529 MethodRef ref;
2530 gboolean res;
2532 info->vtable_size = decode_value (buf, &buf);
2533 if (info->vtable_size == -1)
2534 /* Generic type */
2535 return FALSE;
2536 flags = decode_value (buf, &buf);
2537 info->ghcimpl = (flags >> 0) & 0x1;
2538 info->has_finalize = (flags >> 1) & 0x1;
2539 info->has_cctor = (flags >> 2) & 0x1;
2540 info->has_nested_classes = (flags >> 3) & 0x1;
2541 info->blittable = (flags >> 4) & 0x1;
2542 info->has_references = (flags >> 5) & 0x1;
2543 info->has_static_refs = (flags >> 6) & 0x1;
2544 info->no_special_static_fields = (flags >> 7) & 0x1;
2545 info->is_generic_container = (flags >> 8) & 0x1;
2546 info->has_weak_fields = (flags >> 9) & 0x1;
2548 if (info->has_cctor) {
2549 res = decode_method_ref (module, &ref, buf, &buf, error);
2550 mono_error_assert_ok (error); /* FIXME don't swallow the error */
2551 if (!res)
2552 return FALSE;
2553 info->cctor_token = ref.token;
2555 if (info->has_finalize) {
2556 res = decode_method_ref (module, &ref, buf, &buf, error);
2557 mono_error_assert_ok (error); /* FIXME don't swallow the error */
2558 if (!res)
2559 return FALSE;
2560 info->finalize_image = ref.image;
2561 info->finalize_token = ref.token;
2564 info->instance_size = decode_value (buf, &buf);
2565 info->class_size = decode_value (buf, &buf);
2566 info->packing_size = decode_value (buf, &buf);
2567 info->min_align = decode_value (buf, &buf);
2569 *endbuf = buf;
2571 return TRUE;
2574 gpointer
2575 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot, MonoError *error)
2577 int i;
2578 MonoClass *klass = vtable->klass;
2579 MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
2580 guint8 *info, *p;
2581 MonoCachedClassInfo class_info;
2582 gboolean err;
2583 MethodRef ref;
2584 gboolean res;
2585 gpointer addr;
2586 ERROR_DECL (inner_error);
2588 error_init (error);
2590 if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || m_class_get_rank (klass) || !amodule)
2591 return NULL;
2593 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
2594 p = info;
2596 err = decode_cached_class_info (amodule, &class_info, p, &p);
2597 if (!err)
2598 return NULL;
2600 for (i = 0; i < slot; ++i) {
2601 decode_method_ref (amodule, &ref, p, &p, inner_error);
2602 mono_error_cleanup (inner_error); /* FIXME don't swallow the error */
2605 res = decode_method_ref (amodule, &ref, p, &p, inner_error);
2606 mono_error_cleanup (inner_error); /* FIXME don't swallow the error */
2607 if (!res)
2608 return NULL;
2609 if (ref.no_aot_trampoline)
2610 return NULL;
2612 if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
2613 return NULL;
2615 addr = mono_aot_get_method_from_token (domain, ref.image, ref.token, error);
2616 return addr;
2619 gboolean
2620 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2622 MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
2623 guint8 *p;
2624 gboolean err;
2626 if (m_class_get_rank (klass) || !m_class_get_type_token (klass) || !amodule)
2627 return FALSE;
2629 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
2631 err = decode_cached_class_info (amodule, res, p, &p);
2632 if (!err)
2633 return FALSE;
2635 return TRUE;
2639 * mono_aot_get_class_from_name:
2641 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
2642 * using a cache stored in the AOT file.
2643 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
2645 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
2646 * found.
2648 gboolean
2649 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2651 MonoAotModule *amodule = image->aot_module;
2652 guint16 *table, *entry;
2653 guint16 table_size;
2654 guint32 hash;
2655 char full_name_buf [1024];
2656 char *full_name;
2657 const char *name2, *name_space2;
2658 MonoTableInfo *t;
2659 guint32 cols [MONO_TYPEDEF_SIZE];
2660 GHashTable *nspace_table;
2662 if (!amodule || !amodule->class_name_table)
2663 return FALSE;
2665 amodule_lock (amodule);
2667 *klass = NULL;
2669 /* First look in the cache */
2670 if (!amodule->name_cache)
2671 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
2672 nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
2673 if (nspace_table) {
2674 *klass = (MonoClass *)g_hash_table_lookup (nspace_table, name);
2675 if (*klass) {
2676 amodule_unlock (amodule);
2677 return TRUE;
2681 table_size = amodule->class_name_table [0];
2682 table = amodule->class_name_table + 1;
2684 if (name_space [0] == '\0')
2685 full_name = g_strdup_printf ("%s", name);
2686 else {
2687 if (strlen (name_space) + strlen (name) < 1000) {
2688 sprintf (full_name_buf, "%s.%s", name_space, name);
2689 full_name = full_name_buf;
2690 } else {
2691 full_name = g_strdup_printf ("%s.%s", name_space, name);
2694 hash = mono_metadata_str_hash (full_name) % table_size;
2695 if (full_name != full_name_buf)
2696 g_free (full_name);
2698 entry = &table [hash * 2];
2700 if (entry [0] != 0) {
2701 t = &image->tables [MONO_TABLE_TYPEDEF];
2703 while (TRUE) {
2704 guint32 index = entry [0];
2705 guint32 next = entry [1];
2706 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2708 name_table_accesses ++;
2710 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2712 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2713 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2715 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2716 ERROR_DECL (error);
2717 amodule_unlock (amodule);
2718 *klass = mono_class_get_checked (image, token, error);
2719 if (!mono_error_ok (error))
2720 mono_error_cleanup (error); /* FIXME don't swallow the error */
2722 /* Add to cache */
2723 if (*klass) {
2724 amodule_lock (amodule);
2725 nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
2726 if (!nspace_table) {
2727 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2728 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2730 g_hash_table_insert (nspace_table, (char*)name2, *klass);
2731 amodule_unlock (amodule);
2733 return TRUE;
2736 if (next != 0) {
2737 entry = &table [next * 2];
2738 } else {
2739 break;
2744 amodule_unlock (amodule);
2746 return TRUE;
2749 GHashTable *
2750 mono_aot_get_weak_field_indexes (MonoImage *image)
2752 MonoAotModule *amodule = image->aot_module;
2754 if (!amodule)
2755 return NULL;
2757 /* Initialize weak field indexes from the cached copy */
2758 guint32 *indexes = (guint32*)amodule->weak_field_indexes;
2759 int len = indexes [0];
2760 GHashTable *indexes_hash = g_hash_table_new (NULL, NULL);
2761 for (int i = 0; i < len; ++i)
2762 g_hash_table_insert (indexes_hash, GUINT_TO_POINTER (indexes [i + 1]), GUINT_TO_POINTER (1));
2763 return indexes_hash;
2766 /* Compute the boundaries of the LLVM code for AMODULE. */
2767 static void
2768 compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end)
2770 guint8 *p;
2771 int version, fde_count;
2772 gint32 *table;
2774 if (amodule->info.llvm_get_method) {
2775 gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
2777 #ifdef HOST_WASM
2778 gsize min = 1 << 30, max = 0;
2779 gsize prev = 0;
2781 // FIXME: This depends on emscripten allocating ftnptr ids sequentially
2782 for (int i = 0; i < amodule->info.nmethods; ++i) {
2783 void *addr = NULL;
2785 addr = get_method (i);
2786 gsize val = (gsize)addr;
2787 if (val) {
2788 g_assert (val > prev);
2789 if (val < min)
2790 min = val;
2791 else if (val > max)
2792 max = val;
2793 prev = val;
2796 if (max) {
2797 *code_start = (guint8*)min;
2798 *code_end = (guint8*)(max + 1);
2799 } else {
2800 *code_start = NULL;
2801 *code_end = NULL;
2803 #else
2804 *code_start = (guint8 *)get_method (-1);
2805 *code_end = (guint8 *)get_method (-2);
2807 g_assert (*code_end > *code_start);
2808 #endif
2809 return;
2812 g_assert (amodule->mono_eh_frame);
2814 p = amodule->mono_eh_frame;
2816 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2818 /* Header */
2819 version = *p;
2820 g_assert (version == 3);
2821 p ++;
2822 p ++;
2823 p = (guint8 *)ALIGN_PTR_TO (p, 4);
2825 fde_count = *(guint32*)p;
2826 p += 4;
2827 table = (gint32*)p;
2829 if (fde_count > 0) {
2830 *code_start = (guint8 *)amodule->methods [table [0]];
2831 *code_end = (guint8*)amodule->methods [table [(fde_count - 1) * 2]] + table [fde_count * 2];
2832 } else {
2833 *code_start = NULL;
2834 *code_end = NULL;
2838 static gboolean
2839 is_llvm_code (MonoAotModule *amodule, guint8 *code)
2841 #if HOST_WASM
2842 return TRUE;
2843 #else
2844 if ((guint8*)code >= amodule->llvm_code_start && (guint8*)code < amodule->llvm_code_end)
2845 return TRUE;
2846 else
2847 return FALSE;
2848 #endif
2851 static gboolean
2852 is_thumb_code (MonoAotModule *amodule, guint8 *code)
2854 if (is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_THUMB))
2855 return TRUE;
2856 else
2857 return FALSE;
2861 * decode_llvm_mono_eh_frame:
2863 * Decode the EH information emitted by our modified LLVM compiler and construct a
2864 * MonoJitInfo structure from it.
2865 * If JINFO is NULL, set OUT_LLVM_CLAUSES to the number of llvm level clauses.
2866 * This function is async safe when called in async context.
2868 static void
2869 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, MonoJitInfo *jinfo,
2870 guint8 *code, guint32 code_len,
2871 MonoJitExceptionInfo *clauses, int num_clauses,
2872 GSList **nesting,
2873 int *this_reg, int *this_offset, int *out_llvm_clauses)
2875 guint8 *p, *code1, *code2;
2876 guint8 *fde, *cie, *code_start, *code_end;
2877 int version, fde_count;
2878 gint32 *table;
2879 int i, pos, left, right;
2880 MonoJitExceptionInfo *ei;
2881 guint32 fde_len, ei_len, nested_len, nindex;
2882 gpointer *type_info;
2883 MonoLLVMFDEInfo info;
2884 guint8 *unw_info;
2885 gboolean async;
2887 async = mono_thread_info_is_async_context ();
2889 if (!amodule->mono_eh_frame) {
2890 if (!jinfo) {
2891 *out_llvm_clauses = num_clauses;
2892 return;
2894 memcpy (jinfo->clauses, clauses, num_clauses * sizeof (MonoJitExceptionInfo));
2895 return;
2898 g_assert (amodule->mono_eh_frame && code);
2900 p = amodule->mono_eh_frame;
2902 /* p points to data emitted by LLVM in DwarfMonoException::EmitMonoEHFrame () */
2904 /* Header */
2905 version = *p;
2906 g_assert (version == 3);
2907 p ++;
2908 /* func_encoding = *p; */
2909 p ++;
2910 p = (guint8 *)ALIGN_PTR_TO (p, 4);
2912 fde_count = *(guint32*)p;
2913 p += 4;
2914 table = (gint32*)p;
2916 /* There is +1 entry in the table */
2917 cie = p + ((fde_count + 1) * 8);
2919 /* Binary search in the table to find the entry for code */
2920 left = 0;
2921 right = fde_count;
2922 while (TRUE) {
2923 pos = (left + right) / 2;
2925 /* The table contains method index/fde offset pairs */
2926 g_assert (table [(pos * 2)] != -1);
2927 code1 = (guint8 *)amodule->methods [table [(pos * 2)]];
2928 if (pos + 1 == fde_count) {
2929 code2 = amodule->llvm_code_end;
2930 } else {
2931 g_assert (table [(pos + 1) * 2] != -1);
2932 code2 = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
2935 if (code < code1)
2936 right = pos;
2937 else if (code >= code2)
2938 left = pos + 1;
2939 else
2940 break;
2943 code_start = (guint8 *)amodule->methods [table [(pos * 2)]];
2944 if (pos + 1 == fde_count) {
2945 /* The +1 entry in the table contains the length of the last method */
2946 int len = table [(pos + 1) * 2];
2947 code_end = code_start + len;
2948 } else {
2949 code_end = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
2951 if (!code_len)
2952 code_len = code_end - code_start;
2954 g_assert (code >= code_start && code < code_end);
2956 if (is_thumb_code (amodule, code_start))
2957 /* Clear thumb flag */
2958 code_start = (guint8*)(((gsize)code_start) & ~1);
2960 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
2961 /* This won't overflow because there is +1 entry in the table */
2962 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2964 /* Compute lengths */
2965 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, NULL, NULL, NULL);
2967 if (async) {
2968 /* These are leaked, but the leak is bounded */
2969 ei = mono_domain_alloc0_lock_free (domain, info.ex_info_len * sizeof (MonoJitExceptionInfo));
2970 type_info = mono_domain_alloc0_lock_free (domain, info.ex_info_len * sizeof (gpointer));
2971 unw_info = mono_domain_alloc0_lock_free (domain, info.unw_info_len);
2972 } else {
2973 ei = (MonoJitExceptionInfo *)g_malloc0 (info.ex_info_len * sizeof (MonoJitExceptionInfo));
2974 type_info = (gpointer *)g_malloc0 (info.ex_info_len * sizeof (gpointer));
2975 unw_info = (guint8*)g_malloc0 (info.unw_info_len);
2977 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, ei, type_info, unw_info);
2979 ei_len = info.ex_info_len;
2980 *this_reg = info.this_reg;
2981 *this_offset = info.this_offset;
2984 * LLVM might represent one IL region with multiple regions.
2987 /* Count number of nested clauses */
2988 nested_len = 0;
2989 for (i = 0; i < ei_len; ++i) {
2990 /* This might be unaligned */
2991 gint32 cindex1 = read32 (type_info [i]);
2992 GSList *l;
2994 for (l = nesting [cindex1]; l; l = l->next)
2995 nested_len ++;
2998 if (!jinfo) {
2999 *out_llvm_clauses = ei_len + nested_len;
3000 return;
3003 /* Store the unwind info addr/length in the MonoJitInfo structure itself so its async safe */
3004 MonoUnwindJitInfo *jinfo_unwind = mono_jit_info_get_unwind_info (jinfo);
3005 g_assert (jinfo_unwind);
3006 jinfo_unwind->unw_info = unw_info;
3007 jinfo_unwind->unw_info_len = info.unw_info_len;
3009 for (i = 0; i < ei_len; ++i) {
3011 * clauses contains the original IL exception info saved by the AOT
3012 * compiler, we have to combine that with the information produced by LLVM
3014 /* The type_info entries contain IL clause indexes */
3015 int clause_index = read32 (type_info [i]);
3016 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
3017 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
3019 g_assert (clause_index < num_clauses);
3020 jei->flags = orig_jei->flags;
3021 jei->data.catch_class = orig_jei->data.catch_class;
3023 jei->try_start = ei [i].try_start;
3024 jei->try_end = ei [i].try_end;
3025 jei->handler_start = ei [i].handler_start;
3026 jei->clause_index = clause_index;
3028 if (is_thumb_code (amodule, (guint8 *)jei->try_start)) {
3029 jei->try_start = (void*)((gsize)jei->try_start & ~1);
3030 jei->try_end = (void*)((gsize)jei->try_end & ~1);
3031 /* Make sure we transition to thumb when a handler starts */
3032 jei->handler_start = (void*)((gsize)jei->handler_start + 1);
3036 /* See exception_cb () in mini-llvm.c as to why this is needed */
3037 nindex = ei_len;
3038 for (i = 0; i < ei_len; ++i) {
3039 gint32 cindex1 = read32 (type_info [i]);
3040 GSList *l;
3042 for (l = nesting [cindex1]; l; l = l->next) {
3043 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
3044 MonoJitExceptionInfo *nesting_ei;
3045 MonoJitExceptionInfo *nesting_clause = &clauses [nesting_cindex];
3047 nesting_ei = &jinfo->clauses [nindex];
3048 nindex ++;
3050 memcpy (nesting_ei, &jinfo->clauses [i], sizeof (MonoJitExceptionInfo));
3051 nesting_ei->flags = nesting_clause->flags;
3052 nesting_ei->data.catch_class = nesting_clause->data.catch_class;
3053 nesting_ei->clause_index = nesting_cindex;
3056 g_assert (nindex == ei_len + nested_len);
3059 static gpointer
3060 alloc0_jit_info_data (MonoDomain *domain, int size, gboolean async_context)
3062 #define alloc0_jit_info_data(domain, size, async_context) (g_cast (alloc0_jit_info_data ((domain), (size), (async_context))))
3065 gpointer res;
3067 if (async_context) {
3068 res = mono_domain_alloc0_lock_free (domain, size);
3069 mono_atomic_fetch_add_i32 (&async_jit_info_size, size);
3070 } else {
3071 res = mono_domain_alloc0 (domain, size);
3073 return res;
3077 * LOCKING: Acquires the domain lock.
3078 * In async context, this is async safe.
3080 static MonoJitInfo*
3081 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
3082 MonoMethod *method, guint8* ex_info,
3083 guint8 *code, guint32 code_len)
3085 ERROR_DECL (error);
3086 int i, buf_len, num_clauses, len;
3087 MonoJitInfo *jinfo;
3088 MonoJitInfoFlags flags = JIT_INFO_NONE;
3089 guint unwind_info, eflags;
3090 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
3091 gboolean from_llvm, has_gc_map;
3092 guint8 *p;
3093 int try_holes_info_size, num_holes;
3094 int this_reg = 0, this_offset = 0;
3095 gboolean async;
3097 /* Load the method info from the AOT file */
3098 async = mono_thread_info_is_async_context ();
3100 p = ex_info;
3101 eflags = decode_value (p, &p);
3102 has_generic_jit_info = (eflags & 1) != 0;
3103 has_dwarf_unwind_info = (eflags & 2) != 0;
3104 has_clauses = (eflags & 4) != 0;
3105 has_seq_points = (eflags & 8) != 0;
3106 from_llvm = (eflags & 16) != 0;
3107 has_try_block_holes = (eflags & 32) != 0;
3108 has_gc_map = (eflags & 64) != 0;
3109 has_arch_eh_jit_info = (eflags & 128) != 0;
3111 if (has_dwarf_unwind_info) {
3112 unwind_info = decode_value (p, &p);
3113 g_assert (unwind_info < (1 << 30));
3114 } else {
3115 unwind_info = decode_value (p, &p);
3117 if (has_generic_jit_info)
3118 flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
3120 if (has_try_block_holes) {
3121 num_holes = decode_value (p, &p);
3122 flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
3123 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
3124 } else {
3125 num_holes = try_holes_info_size = 0;
3128 if (has_arch_eh_jit_info) {
3129 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
3130 /* Overwrite the original code_len which includes alignment padding */
3131 code_len = decode_value (p, &p);
3134 /* Exception table */
3135 if (has_clauses)
3136 num_clauses = decode_value (p, &p);
3137 else
3138 num_clauses = 0;
3140 if (from_llvm) {
3141 MonoJitExceptionInfo *clauses;
3142 GSList **nesting;
3145 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
3146 * section.
3148 if (async) {
3149 if (num_clauses < 16) {
3150 clauses = g_newa (MonoJitExceptionInfo, num_clauses);
3151 nesting = g_newa (GSList*, num_clauses);
3152 } else {
3153 clauses = alloc0_jit_info_data (domain, sizeof (MonoJitExceptionInfo) * num_clauses, TRUE);
3154 nesting = alloc0_jit_info_data (domain, sizeof (GSList*) * num_clauses, TRUE);
3156 memset (clauses, 0, sizeof (MonoJitExceptionInfo) * num_clauses);
3157 memset (nesting, 0, sizeof (GSList*) * num_clauses);
3158 } else {
3159 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
3160 nesting = g_new0 (GSList*, num_clauses);
3163 for (i = 0; i < num_clauses; ++i) {
3164 MonoJitExceptionInfo *ei = &clauses [i];
3166 ei->flags = decode_value (p, &p);
3168 if (!(ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
3169 int len = decode_value (p, &p);
3171 if (len > 0) {
3172 if (async) {
3173 p += len;
3174 } else {
3175 ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
3176 mono_error_cleanup (error); /* FIXME don't swallow the error */
3181 ei->clause_index = i;
3183 ei->try_offset = decode_value (p, &p);
3184 ei->try_len = decode_value (p, &p);
3185 ei->handler_offset = decode_value (p, &p);
3186 ei->handler_len = decode_value (p, &p);
3188 /* Read the list of nesting clauses */
3189 while (TRUE) {
3190 int nesting_index = decode_value (p, &p);
3191 if (nesting_index == -1)
3192 break;
3193 // FIXME: async
3194 g_assert (!async);
3195 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
3199 flags |= JIT_INFO_HAS_UNWIND_INFO;
3201 int num_llvm_clauses;
3202 /* Get the length first */
3203 decode_llvm_mono_eh_frame (amodule, domain, NULL, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, &num_llvm_clauses);
3204 len = mono_jit_info_size (flags, num_llvm_clauses, num_holes);
3205 jinfo = (MonoJitInfo *)alloc0_jit_info_data (domain, len, async);
3206 mono_jit_info_init (jinfo, method, code, code_len, flags, num_llvm_clauses, num_holes);
3208 decode_llvm_mono_eh_frame (amodule, domain, jinfo, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, NULL);
3210 if (!async) {
3211 g_free (clauses);
3212 for (i = 0; i < num_clauses; ++i)
3213 g_slist_free (nesting [i]);
3214 g_free (nesting);
3216 jinfo->from_llvm = 1;
3217 } else {
3218 len = mono_jit_info_size (flags, num_clauses, num_holes);
3219 jinfo = (MonoJitInfo *)alloc0_jit_info_data (domain, len, async);
3220 mono_jit_info_init (jinfo, method, code, code_len, flags, num_clauses, num_holes);
3222 for (i = 0; i < jinfo->num_clauses; ++i) {
3223 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3225 ei->flags = decode_value (p, &p);
3227 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
3228 /* Not used for catch clauses */
3229 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
3230 ei->exvar_offset = decode_value (p, &p);
3231 #else
3232 ei->exvar_offset = decode_value (p, &p);
3233 #endif
3235 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3236 ei->data.filter = code + decode_value (p, &p);
3237 else {
3238 int len = decode_value (p, &p);
3240 if (len > 0) {
3241 if (async) {
3242 p += len;
3243 } else {
3244 ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
3245 mono_error_cleanup (error); /* FIXME don't swallow the error */
3250 ei->try_start = code + decode_value (p, &p);
3251 ei->try_end = code + decode_value (p, &p);
3252 ei->handler_start = code + decode_value (p, &p);
3255 jinfo->unwind_info = unwind_info;
3256 jinfo->domain_neutral = 0;
3257 jinfo->from_aot = 1;
3260 if (has_try_block_holes) {
3261 MonoTryBlockHoleTableJitInfo *table;
3263 g_assert (jinfo->has_try_block_holes);
3265 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3266 g_assert (table);
3268 table->num_holes = (guint16)num_holes;
3269 for (i = 0; i < num_holes; ++i) {
3270 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3271 hole->clause = decode_value (p, &p);
3272 hole->length = decode_value (p, &p);
3273 hole->offset = decode_value (p, &p);
3277 if (has_arch_eh_jit_info) {
3278 MonoArchEHJitInfo *eh_info;
3280 g_assert (jinfo->has_arch_eh_info);
3282 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
3283 eh_info->stack_size = decode_value (p, &p);
3284 eh_info->epilog_size = decode_value (p, &p);
3287 if (async) {
3288 /* The rest is not needed in async mode */
3289 jinfo->async = TRUE;
3290 jinfo->d.aot_info = amodule;
3291 // FIXME: Cache
3292 return jinfo;
3295 if (has_generic_jit_info) {
3296 MonoGenericJitInfo *gi;
3297 int len;
3299 g_assert (jinfo->has_generic_jit_info);
3301 gi = mono_jit_info_get_generic_jit_info (jinfo);
3302 g_assert (gi);
3304 gi->nlocs = decode_value (p, &p);
3305 if (gi->nlocs) {
3306 gi->locations = (MonoDwarfLocListEntry *)alloc0_jit_info_data (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
3307 for (i = 0; i < gi->nlocs; ++i) {
3308 MonoDwarfLocListEntry *entry = &gi->locations [i];
3310 entry->is_reg = decode_value (p, &p);
3311 entry->reg = decode_value (p, &p);
3312 if (!entry->is_reg)
3313 entry->offset = decode_value (p, &p);
3314 if (i > 0)
3315 entry->from = decode_value (p, &p);
3316 entry->to = decode_value (p, &p);
3318 gi->has_this = 1;
3319 } else {
3320 if (from_llvm) {
3321 gi->has_this = this_reg != -1;
3322 gi->this_reg = this_reg;
3323 gi->this_offset = this_offset;
3324 } else {
3325 gi->has_this = decode_value (p, &p);
3326 gi->this_reg = decode_value (p, &p);
3327 gi->this_offset = decode_value (p, &p);
3331 len = decode_value (p, &p);
3332 if (async) {
3333 p += len;
3334 } else {
3335 jinfo->d.method = decode_resolve_method_ref (amodule, p, &p, error);
3336 mono_error_cleanup (error); /* FIXME don't swallow the error */
3339 gi->generic_sharing_context = alloc0_jit_info_data (domain, sizeof (MonoGenericSharingContext), async);
3340 if (decode_value (p, &p)) {
3341 /* gsharedvt */
3342 MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
3344 gsctx->is_gsharedvt = TRUE;
3348 if (method && has_seq_points) {
3349 MonoSeqPointInfo *seq_points;
3351 p += mono_seq_point_info_read (&seq_points, p, FALSE);
3353 mono_domain_lock (domain);
3354 /* This could be set already since this function can be called more than once for the same method */
3355 if (!g_hash_table_lookup (domain_jit_info (domain)->seq_points, method))
3356 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
3357 else
3358 mono_seq_point_info_free (seq_points);
3359 mono_domain_unlock (domain);
3361 jinfo->seq_points = seq_points;
3364 /* Load debug info */
3365 buf_len = decode_value (p, &p);
3366 if (!async)
3367 mono_debug_add_aot_method (domain, method, code, p, buf_len);
3368 p += buf_len;
3370 if (has_gc_map) {
3371 int map_size = decode_value (p, &p);
3372 /* The GC map requires 4 bytes of alignment */
3373 while ((guint64)(gsize)p % 4)
3374 p ++;
3375 jinfo->gc_info = p;
3376 p += map_size;
3379 if (amodule != m_class_get_image (jinfo->d.method->klass)->aot_module) {
3380 mono_aot_lock ();
3381 if (!ji_to_amodule)
3382 ji_to_amodule = g_hash_table_new (NULL, NULL);
3383 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
3384 mono_aot_unlock ();
3387 return jinfo;
3390 static gboolean
3391 amodule_contains_code_addr (MonoAotModule *amodule, guint8 *code)
3393 return (code >= amodule->jit_code_start && code <= amodule->jit_code_end) ||
3394 (code >= amodule->llvm_code_start && code <= amodule->llvm_code_end);
3398 * mono_aot_get_unwind_info:
3400 * Return a pointer to the DWARF unwind info belonging to JI.
3402 guint8*
3403 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3405 MonoAotModule *amodule;
3406 guint8 *p;
3407 guint8 *code = (guint8 *)ji->code_start;
3409 if (ji->async)
3410 amodule = ji->d.aot_info;
3411 else
3412 amodule = m_class_get_image (jinfo_get_method (ji)->klass)->aot_module;
3413 g_assert (amodule);
3414 g_assert (ji->from_aot);
3416 if (!amodule_contains_code_addr (amodule, code)) {
3417 /* ji belongs to a different aot module than amodule */
3418 mono_aot_lock ();
3419 g_assert (ji_to_amodule);
3420 amodule = (MonoAotModule *)g_hash_table_lookup (ji_to_amodule, ji);
3421 g_assert (amodule);
3422 g_assert (amodule_contains_code_addr (amodule, code));
3423 mono_aot_unlock ();
3426 p = amodule->unwind_info + ji->unwind_info;
3427 *unwind_info_len = decode_value (p, &p);
3428 return p;
3431 static void
3432 msort_method_addresses_internal (gpointer *array, int *indexes, int lo, int hi, gpointer *scratch, int *scratch_indexes)
3434 int mid = (lo + hi) / 2;
3435 int i, t_lo, t_hi;
3437 if (lo >= hi)
3438 return;
3440 if (hi - lo < 32) {
3441 for (i = lo; i < hi; ++i)
3442 if (array [i] > array [i + 1])
3443 break;
3444 if (i == hi)
3445 /* Already sorted */
3446 return;
3449 msort_method_addresses_internal (array, indexes, lo, mid, scratch, scratch_indexes);
3450 msort_method_addresses_internal (array, indexes, mid + 1, hi, scratch, scratch_indexes);
3452 if (array [mid] < array [mid + 1])
3453 return;
3455 /* Merge */
3456 t_lo = lo;
3457 t_hi = mid + 1;
3458 for (i = lo; i <= hi; i ++) {
3459 if (t_lo <= mid && ((t_hi > hi) || array [t_lo] < array [t_hi])) {
3460 scratch [i] = array [t_lo];
3461 scratch_indexes [i] = indexes [t_lo];
3462 t_lo ++;
3463 } else {
3464 scratch [i] = array [t_hi];
3465 scratch_indexes [i] = indexes [t_hi];
3466 t_hi ++;
3469 for (i = lo; i <= hi; ++i) {
3470 array [i] = scratch [i];
3471 indexes [i] = scratch_indexes [i];
3475 static void
3476 msort_method_addresses (gpointer *array, int *indexes, int len)
3478 gpointer *scratch;
3479 int *scratch_indexes;
3481 scratch = g_new (gpointer, len);
3482 scratch_indexes = g_new (int, len);
3483 msort_method_addresses_internal (array, indexes, 0, len - 1, scratch, scratch_indexes);
3484 g_free (scratch);
3485 g_free (scratch_indexes);
3489 * mono_aot_find_jit_info:
3491 * In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
3492 * to the jit info tables.
3493 * FIXME: Large sizes in the lock free allocator
3495 MonoJitInfo *
3496 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3498 ERROR_DECL (error);
3499 int pos, left, right, code_len;
3500 int method_index, table_len;
3501 guint32 token;
3502 MonoAotModule *amodule = image->aot_module;
3503 MonoMethod *method = NULL;
3504 MonoJitInfo *jinfo;
3505 guint8 *code, *ex_info, *p;
3506 guint32 *table;
3507 int nmethods;
3508 gpointer *methods;
3509 guint8 *code1, *code2;
3510 int methods_len, i;
3511 gboolean async;
3513 if (!amodule)
3514 return NULL;
3516 nmethods = amodule->info.nmethods;
3518 if (domain != mono_get_root_domain ())
3519 /* FIXME: */
3520 return NULL;
3522 if (!amodule_contains_code_addr (amodule, (guint8 *)addr))
3523 return NULL;
3525 async = mono_thread_info_is_async_context ();
3527 /* Compute a sorted table mapping code to method indexes. */
3528 if (!amodule->sorted_methods) {
3529 // FIXME: async
3530 gpointer *methods = g_new0 (gpointer, nmethods);
3531 int *method_indexes = g_new0 (int, nmethods);
3532 int methods_len = 0;
3534 for (i = 0; i < nmethods; ++i) {
3535 /* Skip the -1 entries to speed up sorting */
3536 if (amodule->methods [i] == GINT_TO_POINTER (-1))
3537 continue;
3538 methods [methods_len] = amodule->methods [i];
3539 method_indexes [methods_len] = i;
3540 methods_len ++;
3542 /* Use a merge sort as this is mostly sorted */
3543 msort_method_addresses (methods, method_indexes, methods_len);
3544 for (i = 0; i < methods_len -1; ++i)
3545 g_assert (methods [i] <= methods [i + 1]);
3546 amodule->sorted_methods_len = methods_len;
3547 if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_methods, methods, NULL) != NULL)
3548 /* Somebody got in before us */
3549 g_free (methods);
3550 if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_method_indexes, method_indexes, NULL) != NULL)
3551 /* Somebody got in before us */
3552 g_free (method_indexes);
3555 /* Binary search in the sorted_methods table */
3556 methods = amodule->sorted_methods;
3557 methods_len = amodule->sorted_methods_len;
3558 code = (guint8 *)addr;
3559 left = 0;
3560 right = methods_len;
3561 while (TRUE) {
3562 pos = (left + right) / 2;
3564 code1 = (guint8 *)methods [pos];
3565 if (pos + 1 == methods_len) {
3566 if (code1 >= amodule->jit_code_start && code1 < amodule->jit_code_end)
3567 code2 = amodule->jit_code_end;
3568 else
3569 code2 = amodule->llvm_code_end;
3570 } else {
3571 code2 = (guint8 *)methods [pos + 1];
3574 if (code < code1)
3575 right = pos;
3576 else if (code >= code2)
3577 left = pos + 1;
3578 else
3579 break;
3582 g_assert (addr >= methods [pos]);
3583 if (pos + 1 < methods_len)
3584 g_assert (addr < methods [pos + 1]);
3585 method_index = amodule->sorted_method_indexes [pos];
3587 /* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
3588 if (async) {
3589 JitInfoMap *table = amodule->async_jit_info_table;
3590 int len;
3592 if (table) {
3593 len = table [0].method_index;
3594 for (i = 1; i < len; ++i) {
3595 if (table [i].method_index == method_index)
3596 return table [i].jinfo;
3601 code = (guint8 *)amodule->methods [method_index];
3602 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
3604 if (pos == methods_len - 1) {
3605 if (code >= amodule->jit_code_start && code < amodule->jit_code_end)
3606 code_len = amodule->jit_code_end - code;
3607 else
3608 code_len = amodule->llvm_code_end - code;
3609 } else {
3610 code_len = (guint8*)methods [pos + 1] - (guint8*)methods [pos];
3613 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
3615 /* Might be a wrapper/extra method */
3616 if (!async) {
3617 if (amodule->extra_methods) {
3618 amodule_lock (amodule);
3619 method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
3620 amodule_unlock (amodule);
3621 } else {
3622 method = NULL;
3625 if (!method) {
3626 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
3628 * This is hit for extra methods which are called directly, so they are
3629 * not in amodule->extra_methods.
3631 table_len = amodule->extra_method_info_offsets [0];
3632 table = amodule->extra_method_info_offsets + 1;
3633 left = 0;
3634 right = table_len;
3635 pos = 0;
3637 /* Binary search */
3638 while (TRUE) {
3639 pos = ((left + right) / 2);
3641 g_assert (pos < table_len);
3643 if (table [pos * 2] < method_index)
3644 left = pos + 1;
3645 else if (table [pos * 2] > method_index)
3646 right = pos;
3647 else
3648 break;
3651 p = amodule->blob + table [(pos * 2) + 1];
3652 method = decode_resolve_method_ref (amodule, p, &p, error);
3653 mono_error_cleanup (error); /* FIXME don't swallow the error */
3654 if (!method)
3655 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
3656 return NULL;
3657 } else {
3658 ERROR_DECL (error);
3659 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
3660 method = mono_get_method_checked (image, token, NULL, NULL, error);
3661 if (!method)
3662 g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
3665 /* FIXME: */
3666 g_assert (method);
3669 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3671 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, code, code_len);
3673 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
3675 /* Add it to the normal JitInfo tables */
3676 if (async) {
3677 JitInfoMap *old_table, *new_table;
3678 int len;
3681 * Use a simple inmutable table with linear search to cache async jit info entries.
3682 * This assumes that the number of entries is small.
3684 while (TRUE) {
3685 /* Copy the table, adding a new entry at the end */
3686 old_table = amodule->async_jit_info_table;
3687 if (old_table)
3688 len = old_table[0].method_index;
3689 else
3690 len = 1;
3691 new_table = (JitInfoMap *)alloc0_jit_info_data (domain, (len + 1) * sizeof (JitInfoMap), async);
3692 if (old_table)
3693 memcpy (new_table, old_table, len * sizeof (JitInfoMap));
3694 new_table [0].method_index = len + 1;
3695 new_table [len].method_index = method_index;
3696 new_table [len].jinfo = jinfo;
3697 /* Publish it */
3698 mono_memory_barrier ();
3699 if (mono_atomic_cas_ptr ((volatile gpointer *)&amodule->async_jit_info_table, new_table, old_table) == old_table)
3700 break;
3702 } else {
3703 mono_jit_info_table_add (domain, jinfo);
3706 if ((guint8*)addr >= (guint8*)jinfo->code_start + jinfo->code_size)
3707 /* addr is in the padding between methods, see the adjustment of code_size in decode_exception_debug_info () */
3708 return NULL;
3710 return jinfo;
3713 static gboolean
3714 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
3716 ERROR_DECL (error);
3717 guint8 *p = buf;
3718 gpointer *table;
3719 MonoImage *image;
3720 int i;
3722 switch (ji->type) {
3723 case MONO_PATCH_INFO_METHOD:
3724 case MONO_PATCH_INFO_METHOD_JUMP:
3725 case MONO_PATCH_INFO_METHOD_FTNDESC:
3726 case MONO_PATCH_INFO_ICALL_ADDR:
3727 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3728 case MONO_PATCH_INFO_METHOD_RGCTX:
3729 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
3730 MethodRef ref;
3731 gboolean res;
3733 res = decode_method_ref (aot_module, &ref, p, &p, error);
3734 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3735 if (!res)
3736 goto cleanup;
3738 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)) {
3739 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
3740 ji->type = MONO_PATCH_INFO_ABS;
3742 else {
3743 if (ref.method) {
3744 ji->data.method = ref.method;
3745 }else {
3746 ERROR_DECL (error);
3747 ji->data.method = mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
3748 if (!ji->data.method)
3749 g_error ("AOT Runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
3751 g_assert (ji->data.method);
3752 mono_class_init_internal (ji->data.method->klass);
3754 break;
3756 case MONO_PATCH_INFO_JIT_ICALL:
3757 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3758 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
3759 guint32 len = decode_value (p, &p);
3761 ji->data.name = (char*)p;
3762 p += len + 1;
3763 break;
3765 case MONO_PATCH_INFO_METHODCONST:
3766 /* Shared */
3767 ji->data.method = decode_resolve_method_ref (aot_module, p, &p, error);
3768 mono_error_cleanup (error); /* FIXME don't swallow the error */
3769 if (!ji->data.method)
3770 goto cleanup;
3771 break;
3772 case MONO_PATCH_INFO_VTABLE:
3773 case MONO_PATCH_INFO_CLASS:
3774 case MONO_PATCH_INFO_IID:
3775 case MONO_PATCH_INFO_ADJUSTED_IID:
3776 /* Shared */
3777 ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
3778 mono_error_cleanup (error); /* FIXME don't swallow the error */
3779 if (!ji->data.klass)
3780 goto cleanup;
3781 break;
3782 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3783 ji->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
3784 ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p, error);
3785 mono_error_cleanup (error); /* FIXME don't swallow the error */
3786 if (!ji->data.del_tramp->klass)
3787 goto cleanup;
3788 if (decode_value (p, &p)) {
3789 ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p, error);
3790 mono_error_cleanup (error); /* FIXME don't swallow the error */
3791 if (!ji->data.del_tramp->method)
3792 goto cleanup;
3794 ji->data.del_tramp->is_virtual = decode_value (p, &p) ? TRUE : FALSE;
3795 break;
3796 case MONO_PATCH_INFO_IMAGE:
3797 ji->data.image = load_image (aot_module, decode_value (p, &p), error);
3798 mono_error_cleanup (error); /* FIXME don't swallow the error */
3799 if (!ji->data.image)
3800 goto cleanup;
3801 break;
3802 case MONO_PATCH_INFO_FIELD:
3803 case MONO_PATCH_INFO_SFLDA:
3804 /* Shared */
3805 ji->data.field = decode_field_info (aot_module, p, &p);
3806 if (!ji->data.field)
3807 goto cleanup;
3808 break;
3809 case MONO_PATCH_INFO_SWITCH:
3810 ji->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
3811 ji->data.table->table_size = decode_value (p, &p);
3812 table = (void **)mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
3813 ji->data.table->table = (MonoBasicBlock**)table;
3814 for (i = 0; i < ji->data.table->table_size; i++)
3815 table [i] = (gpointer)(gssize)decode_value (p, &p);
3816 break;
3817 case MONO_PATCH_INFO_R4: {
3818 guint32 val;
3820 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
3821 val = decode_value (p, &p);
3822 *(float*)ji->data.target = *(float*)&val;
3823 break;
3825 case MONO_PATCH_INFO_R8: {
3826 guint32 val [2];
3827 guint64 v;
3829 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
3831 val [0] = decode_value (p, &p);
3832 val [1] = decode_value (p, &p);
3833 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
3834 *(double*)ji->data.target = *(double*)&v;
3835 break;
3837 case MONO_PATCH_INFO_LDSTR:
3838 image = load_image (aot_module, decode_value (p, &p), error);
3839 mono_error_cleanup (error); /* FIXME don't swallow the error */
3840 if (!image)
3841 goto cleanup;
3842 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
3843 break;
3844 case MONO_PATCH_INFO_RVA:
3845 case MONO_PATCH_INFO_DECLSEC:
3846 case MONO_PATCH_INFO_LDTOKEN:
3847 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3848 /* Shared */
3849 image = load_image (aot_module, decode_value (p, &p), error);
3850 mono_error_cleanup (error); /* FIXME don't swallow the error */
3851 if (!image)
3852 goto cleanup;
3853 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
3855 ji->data.token->has_context = decode_value (p, &p);
3856 if (ji->data.token->has_context) {
3857 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p, error);
3858 mono_error_cleanup (error); /* FIXME don't swallow the error */
3859 if (!res)
3860 goto cleanup;
3862 break;
3863 case MONO_PATCH_INFO_EXC_NAME:
3864 ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
3865 mono_error_cleanup (error); /* FIXME don't swallow the error */
3866 if (!ji->data.klass)
3867 goto cleanup;
3868 ji->data.name = m_class_get_name (ji->data.klass);
3869 break;
3870 case MONO_PATCH_INFO_METHOD_REL:
3871 ji->data.offset = decode_value (p, &p);
3872 break;
3873 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3874 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3875 case MONO_PATCH_INFO_GC_NURSERY_START:
3876 case MONO_PATCH_INFO_GC_NURSERY_BITS:
3877 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
3878 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
3879 break;
3880 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3881 ji->data.index = decode_value (p, &p);
3882 break;
3883 case MONO_PATCH_INFO_RGCTX_FETCH:
3884 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
3885 gboolean res;
3886 MonoJumpInfoRgctxEntry *entry;
3887 guint32 offset, val;
3888 guint8 *p2;
3890 offset = decode_value (p, &p);
3891 val = decode_value (p, &p);
3893 entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3894 p2 = aot_module->blob + offset;
3895 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
3896 if (entry->in_mrgctx)
3897 entry->d.method = decode_resolve_method_ref (aot_module, p2, &p2, error);
3898 else
3899 entry->d.klass = decode_klass_ref (aot_module, p2, &p2, error);
3900 entry->info_type = (MonoRgctxInfoType)((val >> 1) & 0xff);
3901 entry->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3902 entry->data->type = (MonoJumpInfoType)((val >> 9) & 0xff);
3903 mono_error_cleanup (error); /* FIXME don't swallow the error */
3905 res = decode_patch (aot_module, mp, entry->data, p, &p);
3906 if (!res)
3907 goto cleanup;
3908 ji->data.rgctx_entry = entry;
3909 break;
3911 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3912 case MONO_PATCH_INFO_AOT_MODULE:
3913 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3914 break;
3915 case MONO_PATCH_INFO_SIGNATURE:
3916 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
3917 ji->data.target = decode_signature (aot_module, p, &p);
3918 break;
3919 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
3920 MonoJumpInfoGSharedVtCall *info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
3921 info->sig = decode_signature (aot_module, p, &p);
3922 g_assert (info->sig);
3923 info->method = decode_resolve_method_ref (aot_module, p, &p, error);
3924 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3926 ji->data.target = info;
3927 break;
3929 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
3930 MonoGSharedVtMethodInfo *info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
3931 int i;
3933 info->method = decode_resolve_method_ref (aot_module, p, &p, error);
3934 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3936 info->num_entries = decode_value (p, &p);
3937 info->count_entries = info->num_entries;
3938 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
3939 for (i = 0; i < info->num_entries; ++i) {
3940 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
3942 template_->info_type = (MonoRgctxInfoType)decode_value (p, &p);
3943 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
3944 case MONO_PATCH_INFO_CLASS: {
3945 MonoClass *klass = decode_klass_ref (aot_module, p, &p, error);
3946 mono_error_cleanup (error); /* FIXME don't swallow the error */
3947 if (!klass)
3948 goto cleanup;
3949 template_->data = m_class_get_byval_arg (klass);
3950 break;
3952 case MONO_PATCH_INFO_FIELD:
3953 template_->data = decode_field_info (aot_module, p, &p);
3954 if (!template_->data)
3955 goto cleanup;
3956 break;
3957 default:
3958 g_assert_not_reached ();
3959 break;
3962 ji->data.target = info;
3963 break;
3965 case MONO_PATCH_INFO_LDSTR_LIT: {
3966 int len = decode_value (p, &p);
3967 char *s;
3969 s = (char *)mono_mempool_alloc0 (mp, len + 1);
3970 memcpy (s, p, len + 1);
3971 p += len + 1;
3973 ji->data.target = s;
3974 break;
3976 case MONO_PATCH_INFO_VIRT_METHOD: {
3977 MonoJumpInfoVirtMethod *info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
3979 info->klass = decode_klass_ref (aot_module, p, &p, error);
3980 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3982 info->method = decode_resolve_method_ref (aot_module, p, &p, error);
3983 mono_error_assert_ok (error); /* FIXME don't swallow the error */
3985 ji->data.target = info;
3986 break;
3988 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
3989 break;
3990 case MONO_PATCH_INFO_GET_TLS_TRAMP:
3991 case MONO_PATCH_INFO_SET_TLS_TRAMP:
3992 case MONO_PATCH_INFO_AOT_JIT_INFO:
3993 ji->data.index = decode_value (p, &p);
3994 break;
3995 default:
3996 g_warning ("unhandled type %d", ji->type);
3997 g_assert_not_reached ();
4000 *endbuf = p;
4002 return TRUE;
4004 cleanup:
4005 return FALSE;
4009 * decode_patches:
4011 * Decode a list of patches identified by the got offsets in GOT_OFFSETS. Return an array of
4012 * MonoJumpInfo structures allocated from MP.
4014 static MonoJumpInfo*
4015 decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets)
4017 MonoJumpInfo *patches;
4018 MonoJumpInfo *ji;
4019 gpointer *got;
4020 guint32 *got_info_offsets;
4021 int i;
4022 gboolean res;
4024 if (llvm) {
4025 got = amodule->llvm_got;
4026 got_info_offsets = (guint32 *)amodule->llvm_got_info_offsets;
4027 } else {
4028 got = amodule->got;
4029 got_info_offsets = (guint32 *)amodule->got_info_offsets;
4032 patches = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
4033 for (i = 0; i < n_patches; ++i) {
4034 guint8 *p = amodule->blob + mono_aot_get_offset (got_info_offsets, got_offsets [i]);
4036 ji = &patches [i];
4037 ji->type = (MonoJumpInfoType)decode_value (p, &p);
4039 /* See load_method () for SFLDA */
4040 if (got && got [got_offsets [i]] && ji->type != MONO_PATCH_INFO_SFLDA) {
4041 /* Already loaded */
4042 } else {
4043 res = decode_patch (amodule, mp, ji, p, &p);
4044 if (!res)
4045 return NULL;
4049 return patches;
4052 static MonoJumpInfo*
4053 load_patch_info (MonoAotModule *amodule, MonoMemPool *mp, int n_patches,
4054 gboolean llvm, guint32 **got_slots,
4055 guint8 *buf, guint8 **endbuf)
4057 MonoJumpInfo *patches;
4058 int pindex;
4059 guint8 *p;
4061 p = buf;
4063 *got_slots = (guint32 *)g_malloc (sizeof (guint32) * n_patches);
4064 for (pindex = 0; pindex < n_patches; ++pindex) {
4065 (*got_slots)[pindex] = decode_value (p, &p);
4068 patches = decode_patches (amodule, mp, n_patches, llvm, *got_slots);
4069 if (!patches) {
4070 g_free (*got_slots);
4071 *got_slots = NULL;
4072 return NULL;
4075 *endbuf = p;
4076 return patches;
4079 static void
4080 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
4083 * Jump addresses cannot be patched by the trampoline code since it
4084 * does not have access to the caller's address. Instead, we collect
4085 * the addresses of the GOT slots pointing to a method, and patch
4086 * them after the method has been compiled.
4088 MonoJitDomainInfo *info = domain_jit_info (domain);
4089 GSList *list;
4090 MonoMethod *shared_method = mini_method_to_shared (method);
4091 method = shared_method ? shared_method : method;
4093 mono_domain_lock (domain);
4094 if (!info->jump_target_got_slot_hash)
4095 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
4096 list = (GSList *)g_hash_table_lookup (info->jump_target_got_slot_hash, method);
4097 list = g_slist_prepend (list, got_slot);
4098 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
4099 mono_domain_unlock (domain);
4103 * load_method:
4105 * Load the method identified by METHOD_INDEX from the AOT image. Return a
4106 * pointer to the native code of the method, or NULL if not found.
4107 * METHOD might not be set if the caller only has the image/token info.
4109 static gpointer
4110 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index,
4111 MonoError *error)
4113 MonoJitInfo *jinfo = NULL;
4114 guint8 *code = NULL, *info;
4115 gboolean res;
4117 error_init (error);
4119 init_amodule_got (amodule);
4121 if (domain != mono_get_root_domain ())
4122 /* Non shared AOT code can't be used in other appdomains */
4123 return NULL;
4125 if (amodule->out_of_date)
4126 return NULL;
4128 if (amodule->info.llvm_get_method) {
4130 * Obtain the method address by calling a generated function in the LLVM module.
4132 gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
4133 code = (guint8 *)get_method (method_index);
4136 if (!code) {
4137 if (method_index < amodule->info.nmethods)
4138 code = (guint8 *)amodule->methods [method_index];
4139 else
4140 return NULL;
4142 /* JITted method */
4143 if (amodule->methods [method_index] == GINT_TO_POINTER (-1)) {
4144 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
4145 char *full_name;
4147 if (!method) {
4148 method = mono_get_method_checked (image, token, NULL, NULL, error);
4149 if (!method)
4150 return NULL;
4152 if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4153 full_name = mono_method_full_name (method, TRUE);
4154 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: NOT FOUND: %s.", full_name);
4155 g_free (full_name);
4158 return NULL;
4162 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
4164 if (!amodule->methods_loaded) {
4165 amodule_lock (amodule);
4166 if (!amodule->methods_loaded) {
4167 guint32 *loaded;
4169 loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
4170 mono_memory_barrier ();
4171 amodule->methods_loaded = loaded;
4173 amodule_unlock (amodule);
4176 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
4177 return code;
4179 if (mini_debug_options.aot_skip_set && !(method && method->wrapper_type)) {
4180 gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
4181 if (methods_aot == mini_debug_options.aot_skip) {
4182 if (!method) {
4183 method = mono_get_method_checked (image, token, NULL, NULL, error);
4184 if (!method)
4185 return NULL;
4187 if (method) {
4188 char *name = mono_method_full_name (method, TRUE);
4189 g_print ("NON AOT METHOD: %s.\n", name);
4190 g_free (name);
4191 } else {
4192 g_print ("NON AOT METHOD: %p %d\n", code, method_index);
4194 mini_debug_options.aot_skip_set = FALSE;
4195 return NULL;
4199 if (mono_last_aot_method != -1) {
4200 gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
4201 if (methods_aot >= mono_last_aot_method)
4202 return NULL;
4203 else if (methods_aot == mono_last_aot_method - 1) {
4204 if (!method) {
4205 method = mono_get_method_checked (image, token, NULL, NULL, error);
4206 if (!method)
4207 return NULL;
4209 if (method) {
4210 char *name = mono_method_full_name (method, TRUE);
4211 g_print ("LAST AOT METHOD: %s.\n", name);
4212 g_free (name);
4213 } else {
4214 g_print ("LAST AOT METHOD: %p %d\n", code, method_index);
4219 if (!(is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) ||
4220 (mono_llvm_only && method && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)) {
4221 res = init_method (amodule, method_index, method, NULL, NULL, error);
4222 if (!res)
4223 goto cleanup;
4226 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
4227 char *full_name;
4229 if (!method) {
4230 method = mono_get_method_checked (image, token, NULL, NULL, error);
4231 if (!method)
4232 return NULL;
4235 full_name = mono_method_full_name (method, TRUE);
4237 if (!jinfo)
4238 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
4240 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
4241 g_free (full_name);
4244 if (mono_llvm_only) {
4245 guint8 *info, *p;
4247 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
4248 p = info;
4249 guint8 flags = decode_value (p, &p);
4250 /* The caller needs to looks this up, but its hard to do without constructing the full MonoJitInfo, so save it here */
4251 if (flags & MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE) {
4252 mono_aot_lock ();
4253 if (!code_to_method_flags)
4254 code_to_method_flags = g_hash_table_new (NULL, NULL);
4255 g_hash_table_insert (code_to_method_flags, code, GUINT_TO_POINTER (flags));
4256 mono_aot_unlock ();
4260 amodule_lock (amodule);
4262 init_plt (amodule);
4264 mono_atomic_inc_i32 (&mono_jit_stats.methods_aot);
4266 if (method && method->wrapper_type)
4267 g_hash_table_insert (amodule->method_to_code, method, code);
4269 /* Commit changes since methods_loaded is accessed outside the lock */
4270 mono_memory_barrier ();
4272 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
4274 amodule_unlock (amodule);
4276 if (MONO_PROFILER_ENABLED (jit_begin) || MONO_PROFILER_ENABLED (jit_done)) {
4277 MonoJitInfo *jinfo;
4279 if (!method) {
4280 method = mono_get_method_checked (amodule->assembly->image, token, NULL, NULL, error);
4281 if (!method)
4282 return NULL;
4284 MONO_PROFILER_RAISE (jit_begin, (method));
4285 jinfo = mono_jit_info_table_find (domain, code);
4286 g_assert (jinfo);
4287 MONO_PROFILER_RAISE (jit_done, (method, jinfo));
4290 return code;
4292 cleanup:
4293 if (jinfo)
4294 g_free (jinfo);
4296 return NULL;
4299 /** find_aot_method_in_amodule
4301 * \param code_amodule The AOT module containing the code pointer
4302 * \param method The method to find the code index for
4303 * \param hash_full The hash for the method
4305 static guint32
4306 find_aot_method_in_amodule (MonoAotModule *code_amodule, MonoMethod *method, guint32 hash_full)
4308 ERROR_DECL (error);
4309 guint32 table_size, entry_size, hash;
4310 guint32 *table, *entry;
4311 guint32 index;
4312 static guint32 n_extra_decodes;
4314 // The AOT module containing the MonoMethod
4315 // The reference to the metadata amodule will differ among multiple dedup methods
4316 // which mangle to the same name but live in different assemblies. This leads to
4317 // the caching breaking. The solution seems to be to cache using the "metadata" amodule.
4318 MonoAotModule *metadata_amodule = m_class_get_image (method->klass)->aot_module;
4320 if (!metadata_amodule || metadata_amodule->out_of_date || !code_amodule || code_amodule->out_of_date)
4321 return 0xffffff;
4323 table_size = code_amodule->extra_method_table [0];
4324 hash = hash_full % table_size;
4325 table = code_amodule->extra_method_table + 1;
4326 entry_size = 3;
4328 entry = &table [hash * entry_size];
4330 if (entry [0] == 0)
4331 return 0xffffff;
4333 index = 0xffffff;
4334 while (TRUE) {
4335 guint32 key = entry [0];
4336 guint32 value = entry [1];
4337 guint32 next = entry [entry_size - 1];
4338 MonoMethod *m;
4339 guint8 *p, *orig_p;
4341 p = code_amodule->blob + key;
4342 orig_p = p;
4344 amodule_lock (metadata_amodule);
4345 if (!metadata_amodule->method_ref_to_method)
4346 metadata_amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
4347 m = (MonoMethod *)g_hash_table_lookup (metadata_amodule->method_ref_to_method, p);
4348 amodule_unlock (metadata_amodule);
4349 if (!m) {
4350 m = decode_resolve_method_ref_with_target (code_amodule, method, p, &p, error);
4351 mono_error_cleanup (error); /* FIXME don't swallow the error */
4353 * Can't catche runtime invoke wrappers since it would break
4354 * the check in decode_method_ref_with_target ().
4356 if (m && m->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
4357 amodule_lock (metadata_amodule);
4358 g_hash_table_insert (metadata_amodule->method_ref_to_method, orig_p, m);
4359 amodule_unlock (metadata_amodule);
4362 if (m == method) {
4363 index = value;
4364 break;
4367 /* Methods decoded needlessly */
4368 if (m) {
4369 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
4370 n_extra_decodes ++;
4373 if (next != 0)
4374 entry = &table [next * entry_size];
4375 else
4376 break;
4379 if (index != 0xffffff)
4380 g_assert (index < code_amodule->info.nmethods);
4382 return index;
4385 static void
4386 add_module_cb (gpointer key, gpointer value, gpointer user_data)
4388 g_ptr_array_add ((GPtrArray*)user_data, value);
4391 gboolean
4392 mono_aot_can_dedup (MonoMethod *method)
4394 #ifdef TARGET_WASM
4395 /* Use a set of wrappers/instances which work and useful */
4396 switch (method->wrapper_type) {
4397 case MONO_WRAPPER_RUNTIME_INVOKE:
4398 return TRUE;
4399 break;
4400 case MONO_WRAPPER_OTHER: {
4401 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4403 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
4404 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR ||
4405 info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
4406 return FALSE;
4407 return TRUE;
4409 default:
4410 break;
4413 if (method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) &&
4414 !mini_is_gsharedvt_signature (mono_method_signature_internal (method)) &&
4415 !mini_is_gsharedvt_klass (method->klass))
4416 return TRUE;
4418 return FALSE;
4419 #else
4420 gboolean not_normal_gshared = method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE);
4421 gboolean extra_method = (method->wrapper_type != MONO_WRAPPER_NONE) || not_normal_gshared;
4423 return extra_method;
4424 #endif
4429 * find_aot_method:
4431 * Try finding METHOD in the extra_method table in all AOT images.
4432 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
4433 * module where the method was found.
4435 static guint32
4436 find_aot_method (MonoMethod *method, MonoAotModule **out_amodule)
4438 guint32 index;
4439 GPtrArray *modules;
4440 int i;
4441 guint32 hash = mono_aot_method_hash (method);
4443 /* Try the place we expect to have moved the method only
4444 * We don't probe, as that causes hard-to-debug issues when we fail
4445 * to find the method */
4446 if (container_amodule && mono_aot_can_dedup (method)) {
4447 *out_amodule = container_amodule;
4448 index = find_aot_method_in_amodule (container_amodule, method, hash);
4449 return index;
4452 /* Try the method's module first */
4453 *out_amodule = m_class_get_image (method->klass)->aot_module;
4454 index = find_aot_method_in_amodule (m_class_get_image (method->klass)->aot_module, method, hash);
4455 if (index != 0xffffff)
4456 return index;
4459 * Try all other modules.
4460 * This is needed because generic instances klass->image points to the image
4461 * containing the generic definition, but the native code is generated to the
4462 * AOT image which contains the reference.
4465 /* Make a copy to avoid doing the search inside the aot lock */
4466 modules = g_ptr_array_new ();
4467 mono_aot_lock ();
4468 g_hash_table_foreach (aot_modules, add_module_cb, modules);
4469 mono_aot_unlock ();
4471 index = 0xffffff;
4472 for (i = 0; i < modules->len; ++i) {
4473 MonoAotModule *amodule = (MonoAotModule *)g_ptr_array_index (modules, i);
4475 if (amodule != m_class_get_image (method->klass)->aot_module)
4476 index = find_aot_method_in_amodule (amodule, method, hash);
4477 if (index != 0xffffff) {
4478 *out_amodule = amodule;
4479 break;
4483 g_ptr_array_free (modules, TRUE);
4485 return index;
4488 guint32
4489 mono_aot_find_method_index (MonoMethod *method)
4491 MonoAotModule *out_amodule;
4492 return find_aot_method (method, &out_amodule);
4495 static gboolean
4496 init_method (MonoAotModule *amodule, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoGenericContext *context, MonoError *error)
4498 MonoDomain *domain = mono_domain_get ();
4499 MonoMemPool *mp;
4500 MonoClass *klass_to_run_ctor = NULL;
4501 gboolean from_plt = method == NULL;
4502 int pindex, n_patches;
4503 guint8 *p;
4504 MonoJitInfo *jinfo = NULL;
4505 guint8 *code, *info;
4507 error_init (error);
4509 code = (guint8 *)amodule->methods [method_index];
4510 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
4512 p = info;
4514 guint8 flags = decode_value (p, &p);
4515 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
4516 klass_to_run_ctor = decode_klass_ref (amodule, p, &p, error);
4517 if (!is_ok (error))
4518 return FALSE;
4520 //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
4521 if (method)
4522 klass_to_run_ctor = method->klass;
4524 if (flags & MONO_AOT_METHOD_FLAG_HAS_PATCHES)
4525 n_patches = decode_value (p, &p);
4526 else
4527 n_patches = 0;
4529 if (n_patches) {
4530 MonoJumpInfo *patches;
4531 guint32 *got_slots;
4532 gboolean llvm;
4533 gpointer *got;
4535 mp = mono_mempool_new ();
4537 if ((gpointer)code >= amodule->info.jit_code_start && (gpointer)code <= amodule->info.jit_code_end) {
4538 llvm = FALSE;
4539 got = amodule->got;
4540 } else {
4541 llvm = TRUE;
4542 got = amodule->llvm_got;
4543 g_assert (got);
4546 patches = load_patch_info (amodule, mp, n_patches, llvm, &got_slots, p, &p);
4547 if (patches == NULL) {
4548 mono_mempool_destroy (mp);
4549 goto cleanup;
4552 for (pindex = 0; pindex < n_patches; ++pindex) {
4553 MonoJumpInfo *ji = &patches [pindex];
4554 gpointer addr;
4557 * For SFLDA, we need to call resolve_patch_target () since the GOT slot could have
4558 * been initialized by load_method () for a static cctor before the cctor has
4559 * finished executing (#23242).
4561 if (!got [got_slots [pindex]] || ji->type == MONO_PATCH_INFO_SFLDA) {
4562 /* In llvm-only made, we might encounter shared methods */
4563 if (mono_llvm_only && ji->type == MONO_PATCH_INFO_METHOD && mono_method_check_context_used (ji->data.method)) {
4564 g_assert (context);
4565 ji->data.method = mono_class_inflate_generic_method_checked (ji->data.method, context, error);
4566 if (!mono_error_ok (error)) {
4567 g_free (got_slots);
4568 mono_mempool_destroy (mp);
4569 return FALSE;
4572 /* This cannot be resolved in mono_resolve_patch_target () */
4573 if (ji->type == MONO_PATCH_INFO_AOT_JIT_INFO) {
4574 // FIXME: Lookup using the index
4575 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
4576 ji->type = MONO_PATCH_INFO_ABS;
4577 ji->data.target = jinfo;
4579 addr = mono_resolve_patch_target (method, domain, code, ji, TRUE, error);
4580 if (!mono_error_ok (error)) {
4581 g_free (got_slots);
4582 mono_mempool_destroy (mp);
4583 return FALSE;
4585 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
4586 addr = mono_create_ftnptr (domain, addr);
4587 mono_memory_barrier ();
4588 got [got_slots [pindex]] = addr;
4589 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
4590 register_jump_target_got_slot (domain, ji->data.method, &(got [got_slots [pindex]]));
4592 ji->type = MONO_PATCH_INFO_NONE;
4595 g_free (got_slots);
4597 mono_mempool_destroy (mp);
4600 if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
4601 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
4603 gboolean inited_ok;
4604 inited_ok = TRUE;
4605 if (init_class) {
4606 MonoVTable *vt = mono_class_vtable_checked (domain, init_class, error);
4607 if (!is_ok (error))
4608 inited_ok = FALSE;
4609 else
4610 inited_ok = mono_runtime_class_init_full (vt, error);
4611 } else if (from_plt && klass_to_run_ctor && !mono_class_is_gtd (klass_to_run_ctor)) {
4612 MonoVTable *vt = mono_class_vtable_checked (domain, klass_to_run_ctor, error);
4613 if (!is_ok (error))
4614 inited_ok = FALSE;
4615 else
4616 inited_ok = mono_runtime_class_init_full (vt, error);
4618 if (!inited_ok)
4619 return FALSE;
4621 return TRUE;
4623 cleanup:
4624 if (jinfo)
4625 g_free (jinfo);
4627 return FALSE;
4631 * mono_aot_init_llvmonly_method:
4633 * Initialize the method identified by METHOD_INDEX in llvmonly mode.
4634 * If LOOKUP_CONTEXT is TRUE, assume the method is in extra_methods, and load the context from there.
4636 gboolean
4637 mono_aot_init_llvmonly_method (gpointer aot_module, guint32 method_index, MonoClass *init_class, MonoGenericContext *context,
4638 gboolean lookup_context, MonoError *error)
4640 MonoAotModule *amodule = (MonoAotModule*)aot_module;
4641 MonoMethod *method = NULL;
4643 if (lookup_context) {
4644 amodule_lock (amodule);
4645 method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
4646 amodule_unlock (amodule);
4648 g_assert (method);
4649 context = mono_method_get_context (method);
4650 g_assert (context);
4652 return init_method (amodule, method_index, method, init_class, context, error);
4656 * mono_aot_get_method:
4658 * Return a pointer to the AOTed native code for METHOD if it can be found,
4659 * NULL otherwise.
4660 * On platforms with function pointers, this doesn't return a function pointer.
4662 gpointer
4663 mono_aot_get_method (MonoDomain *domain, MonoMethod *method, MonoError *error)
4665 MonoClass *klass = method->klass;
4666 MonoMethod *orig_method = method;
4667 guint32 method_index;
4668 MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
4669 guint8 *code;
4670 gboolean cache_result = FALSE;
4671 ERROR_DECL (inner_error);
4673 error_init (error);
4675 if (domain != mono_get_root_domain ())
4676 /* Non shared AOT code can't be used in other appdomains */
4677 return NULL;
4679 if (enable_aot_cache && !amodule && domain->entry_assembly && mono_is_corlib_image (m_class_get_image (klass))) {
4680 /* This cannot be AOTed during startup, so do it now */
4681 if (!mscorlib_aot_loaded) {
4682 mscorlib_aot_loaded = TRUE;
4683 load_aot_module (m_class_get_image (klass)->assembly, NULL);
4684 amodule = m_class_get_image (klass)->aot_module;
4688 if (!amodule)
4689 return NULL;
4691 if (amodule->out_of_date)
4692 return NULL;
4694 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4695 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4696 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4697 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4698 return NULL;
4701 * Use the original method instead of its invoke-with-check wrapper.
4702 * This is not a problem when using full-aot, since it doesn't support
4703 * remoting.
4705 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4706 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method), error);
4708 g_assert (m_class_is_inited (klass));
4710 /* Find method index */
4711 method_index = 0xffffff;
4713 gboolean dedupable = mono_aot_can_dedup (method);
4715 if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) && !dedupable) {
4716 MonoMethod *orig_method = method;
4718 * For generic methods, we store the fully shared instance in place of the
4719 * original method.
4721 method = mono_method_get_declaring_generic_method (method);
4722 method_index = mono_metadata_token_index (method->token) - 1;
4724 if (mono_llvm_only) {
4725 /* Needed by mono_aot_init_gshared_method_this () */
4726 /* orig_method is a random instance but it is enough to make init_method () work */
4727 amodule_lock (amodule);
4728 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), orig_method);
4729 amodule_unlock (amodule);
4733 if (method_index == 0xffffff && (method->is_inflated || !method->token)) {
4734 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
4735 amodule_lock (amodule);
4736 code = (guint8 *)g_hash_table_lookup (amodule->method_to_code, method);
4737 amodule_unlock (amodule);
4738 if (code)
4739 return code;
4741 cache_result = TRUE;
4742 if (method_index == 0xffffff)
4743 method_index = find_aot_method (method, &amodule);
4746 * Special case the ICollection<T> wrappers for arrays, as they cannot
4747 * be statically enumerated, and each wrapper ends up calling the same
4748 * method in Array.
4750 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && m_class_get_rank (method->klass) && strstr (method->name, "System.Collections.Generic")) {
4751 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4753 code = (guint8 *)mono_aot_get_method (domain, m, inner_error);
4754 mono_error_cleanup (inner_error);
4755 if (code)
4756 return code;
4760 * Special case Array.GetGenericValueImpl which is a generic icall.
4761 * Generic sharing currently can't handle it, but the icall returns data using
4762 * an out parameter, so the managed-to-native wrappers can share the same code.
4764 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
4765 MonoMethod *m;
4766 MonoGenericContext ctx;
4767 MonoType *args [16];
4769 if (mono_method_signature_internal (method)->params [1]->type == MONO_TYPE_OBJECT)
4770 /* Avoid recursion */
4771 return NULL;
4773 m = mono_class_get_method_from_name_checked (mono_defaults.array_class, "GetGenericValueImpl", 2, 0, error);
4774 mono_error_assert_ok (error);
4775 g_assert (m);
4777 memset (&ctx, 0, sizeof (ctx));
4778 args [0] = m_class_get_byval_arg (mono_defaults.object_class);
4779 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4781 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE);
4782 if (!m)
4783 g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
4786 * Get the code for the <object> instantiation which should be emitted into
4787 * the mscorlib aot image by the AOT compiler.
4789 code = (guint8 *)mono_aot_get_method (domain, m, inner_error);
4790 mono_error_cleanup (inner_error);
4791 if (code)
4792 return code;
4795 const char *klass_name_space = m_class_get_name_space (method->klass);
4796 const char *klass_name = m_class_get_name (method->klass);
4797 /* Same for CompareExchange<T> and Exchange<T> */
4798 /* Same for Volatile.Read<T>/Write<T> */
4799 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && m_class_get_image (method->klass) == mono_defaults.corlib &&
4800 ((!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_internal (method)->params [1]))) ||
4801 (!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_internal (method)->ret)))) ||
4802 (!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_internal (method)->params [1])))))) {
4803 MonoMethod *m;
4804 MonoGenericContext ctx;
4805 MonoType *args [16];
4806 gpointer iter = NULL;
4808 while ((m = mono_class_get_methods (method->klass, &iter))) {
4809 if (mono_method_signature_internal (m)->generic_param_count && !strcmp (m->name, method->name))
4810 break;
4812 g_assert (m);
4814 memset (&ctx, 0, sizeof (ctx));
4815 args [0] = mono_get_object_type ();
4816 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4818 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE);
4819 if (!m)
4820 g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
4822 /* Avoid recursion */
4823 if (method == m)
4824 return NULL;
4827 * Get the code for the <object> instantiation which should be emitted into
4828 * the mscorlib aot image by the AOT compiler.
4830 code = (guint8 *)mono_aot_get_method (domain, m, inner_error);
4831 mono_error_cleanup (inner_error);
4832 if (code)
4833 return code;
4836 /* For ARRAY_ACCESSOR wrappers with reference types, use the <object> instantiation saved in corlib */
4837 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_OTHER) {
4838 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4840 if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
4841 MonoMethod *array_method = info->d.array_accessor.method;
4842 if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (m_class_get_element_class (array_method->klass)))) {
4843 int rank;
4845 if (!strcmp (array_method->name, "Set"))
4846 rank = mono_method_signature_internal (array_method)->param_count - 1;
4847 else if (!strcmp (array_method->name, "Get") || !strcmp (array_method->name, "Address"))
4848 rank = mono_method_signature_internal (array_method)->param_count;
4849 else
4850 g_assert_not_reached ();
4851 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, rank);
4852 MonoMethod *m = mono_class_get_method_from_name_checked (obj_array_class, array_method->name, mono_method_signature_internal (array_method)->param_count, 0, error);
4853 mono_error_assert_ok (error);
4854 g_assert (m);
4856 m = mono_marshal_get_array_accessor_wrapper (m);
4857 if (m != method) {
4858 code = (guint8 *)mono_aot_get_method (domain, m, inner_error);
4859 mono_error_cleanup (inner_error);
4860 if (code)
4861 return code;
4867 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
4868 /* Partial sharing */
4869 MonoMethod *shared;
4871 shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4872 return_val_if_nok (error, NULL);
4874 method_index = find_aot_method (shared, &amodule);
4875 if (method_index != 0xffffff)
4876 method = shared;
4879 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4880 MonoMethod *shared;
4881 /* gsharedvt */
4882 /* Use the all-vt shared method since this is what was AOTed */
4883 shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4884 if (!shared)
4885 return NULL;
4887 method_index = find_aot_method (shared, &amodule);
4888 if (method_index != 0xffffff) {
4889 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4890 if (!method)
4891 return NULL;
4895 if (method_index == 0xffffff) {
4896 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
4897 char *full_name;
4899 full_name = mono_method_full_name (method, TRUE);
4900 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
4901 g_free (full_name);
4903 return NULL;
4906 if (method_index == 0xffffff)
4907 return NULL;
4909 /* Needed by find_jit_info */
4910 amodule_lock (amodule);
4911 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
4912 amodule_unlock (amodule);
4913 } else {
4914 /* Common case */
4915 method_index = mono_metadata_token_index (method->token) - 1;
4917 guint32 num_methods = amodule->info.nmethods - amodule->info.nextra_methods;
4918 if (method_index >= num_methods)
4919 /* method not available in AOT image */
4920 return NULL;
4923 code = (guint8 *)load_method (domain, amodule, m_class_get_image (klass), method, method->token, method_index, error);
4924 if (!is_ok (error))
4925 return NULL;
4926 if (code && cache_result) {
4927 amodule_lock (amodule);
4928 g_hash_table_insert (amodule->method_to_code, orig_method, code);
4929 amodule_unlock (amodule);
4931 return code;
4935 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
4936 * method.
4938 gpointer
4939 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token, MonoError *error)
4941 MonoAotModule *aot_module = image->aot_module;
4942 int method_index;
4943 gpointer res;
4945 error_init (error);
4947 if (!aot_module)
4948 return NULL;
4950 method_index = mono_metadata_token_index (token) - 1;
4952 res = load_method (domain, aot_module, image, NULL, token, method_index, error);
4953 return res;
4956 typedef struct {
4957 guint8 *addr;
4958 gboolean res;
4959 } IsGotEntryUserData;
4961 static void
4962 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
4964 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
4965 MonoAotModule *aot_module = (MonoAotModule*)value;
4967 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
4968 data->res = TRUE;
4971 gboolean
4972 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4974 IsGotEntryUserData user_data;
4976 if (!aot_modules)
4977 return FALSE;
4979 user_data.addr = addr;
4980 user_data.res = FALSE;
4981 mono_aot_lock ();
4982 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
4983 mono_aot_unlock ();
4985 return user_data.res;
4988 typedef struct {
4989 guint8 *addr;
4990 MonoAotModule *module;
4991 } FindAotModuleUserData;
4993 static void
4994 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
4996 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
4997 MonoAotModule *aot_module = (MonoAotModule*)value;
4999 if (amodule_contains_code_addr (aot_module, data->addr))
5000 data->module = aot_module;
5003 static inline MonoAotModule*
5004 find_aot_module (guint8 *code)
5006 FindAotModuleUserData user_data;
5008 if (!aot_modules)
5009 return NULL;
5011 /* Reading these need no locking */
5012 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
5013 return NULL;
5015 user_data.addr = code;
5016 user_data.module = NULL;
5018 mono_aot_lock ();
5019 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
5020 mono_aot_unlock ();
5022 return user_data.module;
5025 void
5026 mono_aot_patch_plt_entry (guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
5028 MonoAotModule *amodule;
5031 * Since AOT code is only used in the root domain,
5032 * mono_domain_get () != mono_get_root_domain () means the calling method
5033 * is AppDomain:InvokeInDomain, so this is the same check as in
5034 * mono_method_same_domain () but without loading the metadata for the method.
5036 if (mono_domain_get () == mono_get_root_domain ()) {
5037 if (!got) {
5038 amodule = find_aot_module (code);
5039 if (amodule)
5040 got = amodule->got;
5042 mono_arch_patch_plt_entry (plt_entry, got, regs, addr);
5047 * mono_aot_plt_resolve:
5049 * This function is called by the entries in the PLT to resolve the actual method that
5050 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
5051 * Returns NULL if the something cannot be loaded.
5053 gpointer
5054 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code, MonoError *error)
5056 #ifdef MONO_ARCH_AOT_SUPPORTED
5057 guint8 *p, *target, *plt_entry;
5058 MonoJumpInfo ji;
5059 MonoAotModule *module = (MonoAotModule*)aot_module;
5060 gboolean res, no_ftnptr = FALSE;
5061 MonoMemPool *mp;
5062 gboolean using_gsharedvt = FALSE;
5064 error_init (error);
5066 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
5068 p = &module->blob [plt_info_offset];
5070 ji.type = (MonoJumpInfoType)decode_value (p, &p);
5072 mp = mono_mempool_new ();
5073 res = decode_patch (module, mp, &ji, p, &p);
5075 if (!res) {
5076 mono_mempool_destroy (mp);
5077 return NULL;
5080 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5081 using_gsharedvt = TRUE;
5082 #endif
5085 * Avoid calling resolve_patch_target in the full-aot case if possible, since
5086 * it would create a trampoline, and we don't need that.
5087 * We could do this only if the method does not need the special handling
5088 * in mono_magic_trampoline ().
5090 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) &&
5091 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
5092 target = (guint8 *)mono_jit_compile_method (ji.data.method, error);
5093 if (!mono_error_ok (error)) {
5094 mono_mempool_destroy (mp);
5095 return NULL;
5097 no_ftnptr = TRUE;
5098 } else {
5099 target = (guint8 *)mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE, error);
5100 if (!mono_error_ok (error)) {
5101 mono_mempool_destroy (mp);
5102 return NULL;
5107 * The trampoline expects us to return a function descriptor on platforms which use
5108 * it, but resolve_patch_target returns a direct function pointer for some type of
5109 * patches, so have to translate between the two.
5110 * FIXME: Clean this up, but how ?
5112 if (ji.type == MONO_PATCH_INFO_ABS || ji.type == MONO_PATCH_INFO_JIT_ICALL || ji.type == MONO_PATCH_INFO_ICALL_ADDR || ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR || ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
5113 /* These should already have a function descriptor */
5114 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5115 /* Our function descriptors have a 0 environment, gcc created ones don't */
5116 if (ji.type != MONO_PATCH_INFO_JIT_ICALL && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
5117 g_assert (((gpointer*)target) [2] == 0);
5118 #endif
5119 /* Empty */
5120 } else if (!no_ftnptr) {
5121 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5122 g_assert (((gpointer*)target) [2] != 0);
5123 #endif
5124 target = (guint8 *)mono_create_ftnptr (mono_domain_get (), target);
5127 mono_mempool_destroy (mp);
5129 /* Patch the PLT entry with target which might be the actual method not a trampoline */
5130 plt_entry = mono_aot_get_plt_entry (code);
5131 g_assert (plt_entry);
5132 mono_aot_patch_plt_entry (code, plt_entry, module->got, NULL, target);
5134 return target;
5135 #else
5136 g_assert_not_reached ();
5137 return NULL;
5138 #endif
5142 * init_plt:
5144 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
5145 * method in the module is loaded to avoid committing memory by writing to it.
5146 * LOCKING: Assumes the AMODULE lock is held.
5148 static void
5149 init_plt (MonoAotModule *amodule)
5151 int i;
5152 gpointer tramp;
5154 if (amodule->plt_inited)
5155 return;
5157 if (amodule->info.plt_size <= 1) {
5158 amodule->plt_inited = TRUE;
5159 return;
5162 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
5165 * Initialize the PLT entries in the GOT to point to the default targets.
5168 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
5169 for (i = 1; i < amodule->info.plt_size; ++i)
5170 /* All the default entries point to the AOT trampoline */
5171 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
5173 amodule->plt_inited = TRUE;
5177 * mono_aot_get_plt_entry:
5179 * Return the address of the PLT entry called by the code at CODE if exists.
5181 guint8*
5182 mono_aot_get_plt_entry (guint8 *code)
5184 MonoAotModule *amodule = find_aot_module (code);
5185 guint8 *target = NULL;
5187 if (!amodule)
5188 return NULL;
5190 #ifdef TARGET_ARM
5191 if (is_thumb_code (amodule, code - 4))
5192 return mono_arm_get_thumb_plt_entry (code);
5193 #endif
5195 #ifdef MONO_ARCH_AOT_SUPPORTED
5196 target = mono_arch_get_call_target (code);
5197 #else
5198 g_assert_not_reached ();
5199 #endif
5201 #ifdef MONOTOUCH
5202 while (target != NULL) {
5203 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
5204 return target;
5206 // Add 4 since mono_arch_get_call_target assumes we're passing
5207 // the instruction after the actual branch instruction.
5208 target = mono_arch_get_call_target (target + 4);
5211 return NULL;
5212 #else
5213 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
5214 return target;
5215 else
5216 return NULL;
5217 #endif
5221 * mono_aot_get_plt_info_offset:
5223 * Return the PLT info offset belonging to the plt entry called by CODE.
5225 guint32
5226 mono_aot_get_plt_info_offset (host_mgreg_t *regs, guint8 *code)
5228 guint8 *plt_entry = mono_aot_get_plt_entry (code);
5230 g_assert (plt_entry);
5232 /* The offset is embedded inside the code after the plt entry */
5233 #ifdef MONO_ARCH_AOT_SUPPORTED
5234 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
5235 #else
5236 g_assert_not_reached ();
5237 return 0;
5238 #endif
5241 static gpointer
5242 mono_create_ftnptr_malloc (guint8 *code)
5244 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5245 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
5247 ftnptr->code = code;
5248 ftnptr->toc = NULL;
5249 ftnptr->env = NULL;
5251 return ftnptr;
5252 #else
5253 return code;
5254 #endif
5258 * mono_aot_register_jit_icall:
5260 * Register a JIT icall which is called by trampolines in full-aot mode. This should
5261 * be called from mono_arch_init () during startup.
5263 void
5264 mono_aot_register_jit_icall (const char *name, gpointer addr)
5266 /* No need for locking */
5267 if (!aot_jit_icall_hash)
5268 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
5269 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
5273 * load_function_full:
5275 * Load the function named NAME from the aot image.
5277 static gpointer
5278 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
5280 char *symbol;
5281 guint8 *p;
5282 int n_patches, pindex;
5283 MonoMemPool *mp;
5284 gpointer code;
5285 guint32 info_offset;
5287 /* Load the code */
5289 symbol = g_strdup_printf ("%s", name);
5290 find_amodule_symbol (amodule, symbol, (gpointer *)&code);
5291 g_free (symbol);
5292 if (!code)
5293 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
5295 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
5297 /* Load info */
5299 symbol = g_strdup_printf ("%s_p", name);
5300 find_amodule_symbol (amodule, symbol, (gpointer *)&p);
5301 g_free (symbol);
5302 if (!p)
5303 /* Nothing to patch */
5304 return code;
5306 info_offset = *(guint32*)p;
5307 if (out_tinfo) {
5308 MonoTrampInfo *tinfo;
5309 guint32 code_size, uw_info_len, uw_offset;
5310 guint8 *uw_info;
5311 /* Construct a MonoTrampInfo from the data in the AOT image */
5313 p += sizeof (guint32);
5314 code_size = *(guint32*)p;
5315 p += sizeof (guint32);
5316 uw_offset = *(guint32*)p;
5317 uw_info = amodule->unwind_info + uw_offset;
5318 uw_info_len = decode_value (uw_info, &uw_info);
5320 tinfo = g_new0 (MonoTrampInfo, 1);
5321 tinfo->code = (guint8 *)code;
5322 tinfo->code_size = code_size;
5323 tinfo->uw_info_len = uw_info_len;
5324 if (uw_info_len)
5325 tinfo->uw_info = uw_info;
5327 *out_tinfo = tinfo;
5330 p = amodule->blob + info_offset;
5332 /* Similar to mono_aot_load_method () */
5334 n_patches = decode_value (p, &p);
5336 if (n_patches) {
5337 MonoJumpInfo *patches;
5338 guint32 *got_slots;
5340 mp = mono_mempool_new ();
5342 patches = load_patch_info (amodule, mp, n_patches, FALSE, &got_slots, p, &p);
5343 g_assert (patches);
5345 for (pindex = 0; pindex < n_patches; ++pindex) {
5346 MonoJumpInfo *ji = &patches [pindex];
5347 ERROR_DECL (error);
5348 gpointer target;
5350 if (amodule->got [got_slots [pindex]])
5351 continue;
5354 * When this code is executed, the runtime may not be initalized yet, so
5355 * resolve the patch info by hand.
5357 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5358 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
5359 target = (gpointer)mono_get_lmf_addr;
5360 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint_noraise")) {
5361 target = (gpointer)mono_thread_force_interruption_checkpoint_noraise;
5362 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
5363 target = (gpointer)mono_exception_from_token;
5364 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
5365 target = (gpointer)mono_get_throw_exception ();
5366 } else if (!strcmp (ji->data.name, "mono_rethrow_preserve_exception")) {
5367 target = (gpointer)mono_get_rethrow_preserve_exception ();
5368 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
5369 MonoTrampolineType tramp_type2 = (MonoTrampolineType)atoi (ji->data.name + strlen ("trampoline_func_"));
5370 target = (gpointer)mono_get_trampoline_func (tramp_type2);
5371 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
5372 /* atoll is needed because the the offset is unsigned */
5373 guint32 slot;
5374 int res;
5376 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
5377 g_assert (res == 1);
5378 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
5379 target = mono_create_ftnptr_malloc ((guint8 *)target);
5380 } else if (!strcmp (ji->data.name, "debugger_agent_single_step_from_context")) {
5381 target = (gpointer)mini_get_dbg_callbacks ()->single_step_from_context;
5382 } else if (!strcmp (ji->data.name, "debugger_agent_breakpoint_from_context")) {
5383 target = (gpointer)mini_get_dbg_callbacks ()->breakpoint_from_context;
5384 } else if (!strcmp (ji->data.name, "throw_exception_addr")) {
5385 target = mono_get_throw_exception_addr ();
5386 } else if (!strcmp (ji->data.name, "rethrow_preserve_exception_addr")) {
5387 target = mono_get_rethrow_preserve_exception_addr ();
5388 } else if (strstr (ji->data.name, "generic_trampoline_")) {
5389 target = mono_aot_get_trampoline (ji->data.name);
5390 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
5391 /* Registered by mono_arch_init () */
5392 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
5393 } else {
5394 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
5395 g_assert_not_reached ();
5396 target = NULL;
5398 } else {
5399 /* Hopefully the code doesn't have patches which need method or
5400 * domain to be set.
5402 target = mono_resolve_patch_target (NULL, NULL, (guint8 *)code, ji, FALSE, error);
5403 mono_error_assert_ok (error);
5404 g_assert (target);
5407 amodule->got [got_slots [pindex]] = target;
5410 g_free (got_slots);
5412 mono_mempool_destroy (mp);
5415 return code;
5418 static gpointer
5419 load_function (MonoAotModule *amodule, const char *name)
5421 return load_function_full (amodule, name, NULL);
5424 static MonoAotModule*
5425 get_mscorlib_aot_module (void)
5427 MonoImage *image;
5428 MonoAotModule *amodule;
5430 image = mono_defaults.corlib;
5431 if (image)
5432 amodule = image->aot_module;
5433 else
5434 amodule = mscorlib_aot_module;
5435 g_assert (amodule);
5436 return amodule;
5439 static void
5440 no_trampolines (void)
5442 g_assert_not_reached ();
5446 * Return the trampoline identified by NAME from the mscorlib AOT file.
5447 * On ppc64, this returns a function descriptor.
5449 gpointer
5450 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
5452 MonoAotModule *amodule = get_mscorlib_aot_module ();
5454 if (mono_llvm_only) {
5455 *out_tinfo = NULL;
5456 return (gpointer)no_trampolines;
5459 return mono_create_ftnptr_malloc ((guint8 *)load_function_full (amodule, name, out_tinfo));
5462 gpointer
5463 (mono_aot_get_trampoline) (const char *name)
5465 MonoTrampInfo *out_tinfo;
5466 gpointer code;
5468 code = mono_aot_get_trampoline_full (name, &out_tinfo);
5469 mono_aot_tramp_info_register (out_tinfo, NULL);
5471 return code;
5474 static gpointer
5475 read_unwind_info (MonoAotModule *amodule, MonoTrampInfo *info, const char *symbol_name)
5477 gpointer symbol_addr;
5478 guint32 uw_offset, uw_info_len;
5479 guint8 *uw_info;
5481 find_amodule_symbol (amodule, symbol_name, &symbol_addr);
5483 if (!symbol_addr)
5484 return NULL;
5486 uw_offset = *(guint32*)symbol_addr;
5487 uw_info = amodule->unwind_info + uw_offset;
5488 uw_info_len = decode_value (uw_info, &uw_info);
5490 info->uw_info_len = uw_info_len;
5491 if (uw_info_len)
5492 info->uw_info = uw_info;
5493 else
5494 info->uw_info = NULL;
5496 /* If successful return the address of the following data */
5497 return (guint32*)symbol_addr + 1;
5500 #ifdef MONOTOUCH
5501 #include <mach/mach.h>
5503 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
5505 static void
5506 read_page_trampoline_uwinfo (MonoTrampInfo *info, int tramp_type, gboolean is_generic)
5508 char symbol_name [128];
5510 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
5511 sprintf (symbol_name, "specific_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5512 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
5513 sprintf (symbol_name, "rgctx_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5514 else if (tramp_type == MONO_AOT_TRAMP_IMT)
5515 sprintf (symbol_name, "imt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5516 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
5517 sprintf (symbol_name, "gsharedvt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5518 else if (tramp_type == MONO_AOT_TRAMP_UNBOX_ARBITRARY)
5519 sprintf (symbol_name, "unbox_arbitrary_trampolines_page_%s_p", is_generic ? "gen" : "sp");
5520 else
5521 g_assert_not_reached ();
5523 read_unwind_info (mono_defaults.corlib->aot_module, info, symbol_name);
5526 static unsigned char*
5527 get_new_trampoline_from_page (int tramp_type)
5529 MonoAotModule *amodule;
5530 MonoImage *image;
5531 TrampolinePage *page;
5532 int count;
5533 void *tpage;
5534 vm_address_t addr, taddr;
5535 kern_return_t ret;
5536 vm_prot_t prot, max_prot;
5537 int psize, specific_trampoline_size;
5538 unsigned char *code;
5540 specific_trampoline_size = 2 * sizeof (gpointer);
5542 mono_aot_page_lock ();
5543 page = trampoline_pages [tramp_type];
5544 if (page && page->trampolines < page->trampolines_end) {
5545 code = page->trampolines;
5546 page->trampolines += specific_trampoline_size;
5547 mono_aot_page_unlock ();
5548 return code;
5550 mono_aot_page_unlock ();
5551 /* the trampoline template page is in the mscorlib module */
5552 image = mono_defaults.corlib;
5553 g_assert (image);
5555 psize = MONO_AOT_TRAMP_PAGE_SIZE;
5557 amodule = image->aot_module;
5558 g_assert (amodule);
5560 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
5561 tpage = load_function (amodule, "specific_trampolines_page");
5562 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
5563 tpage = load_function (amodule, "rgctx_trampolines_page");
5564 else if (tramp_type == MONO_AOT_TRAMP_IMT)
5565 tpage = load_function (amodule, "imt_trampolines_page");
5566 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
5567 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
5568 else if (tramp_type == MONO_AOT_TRAMP_UNBOX_ARBITRARY)
5569 tpage = load_function (amodule, "unbox_arbitrary_trampolines_page");
5570 else
5571 g_error ("Incorrect tramp type for trampolines page");
5572 g_assert (tpage);
5573 /*g_warning ("loaded trampolines page at %x", tpage);*/
5575 /* avoid the unlikely case of looping forever */
5576 count = 40;
5577 page = NULL;
5578 while (page == NULL && count-- > 0) {
5579 MonoTrampInfo *gen_info, *sp_info;
5581 addr = 0;
5582 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
5583 * while the second will contain the trampolines.
5585 do {
5586 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
5587 } while (ret == KERN_ABORTED);
5588 if (ret != KERN_SUCCESS) {
5589 g_error ("Cannot allocate memory for trampolines: %d", ret);
5590 break;
5592 /*g_warning ("allocated trampoline double page at %x", addr);*/
5593 /* replace the second page with a remapped trampoline page */
5594 taddr = addr + psize;
5595 vm_deallocate (mach_task_self (), taddr, psize);
5596 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
5597 if (ret != KERN_SUCCESS) {
5598 /* someone else got the page, try again */
5599 vm_deallocate (mach_task_self (), addr, psize);
5600 continue;
5602 /*g_warning ("remapped trampoline page at %x", taddr);*/
5604 mono_aot_page_lock ();
5605 page = trampoline_pages [tramp_type];
5606 /* some other thread already allocated, so use that to avoid wasting memory */
5607 if (page && page->trampolines < page->trampolines_end) {
5608 code = page->trampolines;
5609 page->trampolines += specific_trampoline_size;
5610 mono_aot_page_unlock ();
5611 vm_deallocate (mach_task_self (), addr, psize);
5612 vm_deallocate (mach_task_self (), taddr, psize);
5613 return code;
5615 page = (TrampolinePage*)addr;
5616 page->next = trampoline_pages [tramp_type];
5617 trampoline_pages [tramp_type] = page;
5618 page->trampolines = (guint8*)(taddr + amodule->info.tramp_page_code_offsets [tramp_type]);
5619 page->trampolines_end = (guint8*)(taddr + psize - 64);
5620 code = page->trampolines;
5621 page->trampolines += specific_trampoline_size;
5622 mono_aot_page_unlock ();
5624 /* Register the generic part at the beggining of the trampoline page */
5625 gen_info = mono_tramp_info_create (NULL, (guint8*)taddr, amodule->info.tramp_page_code_offsets [tramp_type], NULL, NULL);
5626 read_page_trampoline_uwinfo (gen_info, tramp_type, TRUE);
5627 mono_aot_tramp_info_register (gen_info, NULL);
5629 * FIXME
5630 * Registering each specific trampoline produces a lot of
5631 * MonoJitInfo structures. Jump trampolines are also registered
5632 * separately.
5634 if (tramp_type != MONO_AOT_TRAMP_SPECIFIC) {
5635 /* Register the rest of the page as a single trampoline */
5636 sp_info = mono_tramp_info_create (NULL, code, page->trampolines_end - code, NULL, NULL);
5637 read_page_trampoline_uwinfo (sp_info, tramp_type, FALSE);
5638 mono_aot_tramp_info_register (sp_info, NULL);
5640 return code;
5642 g_error ("Cannot allocate more trampoline pages: %d", ret);
5643 return NULL;
5646 #else
5647 static unsigned char*
5648 get_new_trampoline_from_page (int tramp_type)
5650 g_error ("Page trampolines not supported.");
5651 return NULL;
5653 #endif
5656 static gpointer
5657 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
5659 void *code;
5660 gpointer *data;
5662 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
5664 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5665 data [0] = arg;
5666 data [1] = tramp;
5667 /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
5668 return code;
5672 static gpointer
5673 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
5675 void *code;
5676 gpointer *data;
5678 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
5680 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5681 data [0] = arg;
5682 data [1] = tramp;
5683 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
5684 return code;
5688 static gpointer
5689 get_new_imt_trampoline_from_page (gpointer arg)
5691 void *code;
5692 gpointer *data;
5694 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT);
5696 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5697 data [0] = arg;
5698 /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
5699 return code;
5703 static gpointer
5704 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
5706 void *code;
5707 gpointer *data;
5709 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
5711 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5712 data [0] = arg;
5713 data [1] = tramp;
5714 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
5715 return code;
5718 static gpointer
5719 get_new_unbox_arbitrary_trampoline_frome_page (gpointer addr)
5721 void *code;
5722 gpointer *data;
5724 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_UNBOX_ARBITRARY);
5726 data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
5727 data [0] = addr;
5729 return code;
5732 /* Return a given kind of trampoline */
5733 /* FIXME set unwind info for these trampolines */
5734 static gpointer
5735 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
5737 MonoImage *image;
5738 MonoAotModule *amodule = get_mscorlib_aot_module ();
5739 int index, tramp_size;
5741 /* Currently, we keep all trampolines in the mscorlib AOT image */
5742 image = mono_defaults.corlib;
5744 *out_amodule = amodule;
5746 mono_aot_lock ();
5748 #ifdef MONOTOUCH
5749 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
5750 #else
5751 #define MONOTOUCH_TRAMPOLINES_ERROR ""
5752 #endif
5753 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
5754 g_error ("Ran out of trampolines of type %d in '%s' (limit %d)%s\n",
5755 tramp_type, image ? image->name : MONO_ASSEMBLY_CORLIB_NAME, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
5757 index = amodule->trampoline_index [tramp_type] ++;
5759 mono_aot_unlock ();
5761 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
5763 tramp_size = amodule->info.trampoline_size [tramp_type];
5765 if (out_tramp_size)
5766 *out_tramp_size = tramp_size;
5768 return amodule->trampolines [tramp_type] + (index * tramp_size);
5771 static void
5772 no_specific_trampoline (void)
5774 g_assert_not_reached ();
5778 * Return a specific trampoline from the AOT file.
5780 gpointer
5781 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
5783 MonoAotModule *amodule;
5784 guint32 got_offset, tramp_size;
5785 guint8 *code, *tramp;
5786 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
5787 static gboolean inited;
5788 static guint32 num_trampolines;
5790 if (mono_llvm_only) {
5791 *code_len = 1;
5792 return (gpointer)no_specific_trampoline;
5795 if (!inited) {
5796 mono_aot_lock ();
5798 if (!inited) {
5799 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
5800 inited = TRUE;
5803 mono_aot_unlock ();
5806 num_trampolines ++;
5808 if (!generic_trampolines [tramp_type]) {
5809 char *symbol;
5811 symbol = mono_get_generic_trampoline_name (tramp_type);
5812 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
5813 g_free (symbol);
5816 tramp = (guint8 *)generic_trampolines [tramp_type];
5817 g_assert (tramp);
5819 if (USE_PAGE_TRAMPOLINES) {
5820 code = (guint8 *)get_new_specific_trampoline_from_page (tramp, arg1);
5821 tramp_size = 8;
5822 } else {
5823 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
5825 amodule->got [got_offset] = tramp;
5826 amodule->got [got_offset + 1] = arg1;
5829 if (code_len)
5830 *code_len = tramp_size;
5832 return code;
5835 gpointer
5836 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
5838 MonoAotModule *amodule;
5839 guint8 *code;
5840 guint32 got_offset;
5842 if (USE_PAGE_TRAMPOLINES) {
5843 code = (guint8 *)get_new_rgctx_trampoline_from_page (addr, ctx);
5844 } else {
5845 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
5847 amodule->got [got_offset] = ctx;
5848 amodule->got [got_offset + 1] = addr;
5851 /* The caller expects an ftnptr */
5852 return mono_create_ftnptr (mono_domain_get (), code);
5855 gpointer
5856 mono_aot_get_unbox_arbitrary_trampoline (gpointer addr)
5858 MonoAotModule *amodule;
5859 guint8 *code;
5860 guint32 got_offset;
5862 if (USE_PAGE_TRAMPOLINES) {
5863 code = (guint8 *)get_new_unbox_arbitrary_trampoline_frome_page (addr);
5864 } else {
5865 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_UNBOX_ARBITRARY, 1, &amodule, &got_offset, NULL);
5866 amodule->got [got_offset] = addr;
5869 /* The caller expects an ftnptr */
5870 return mono_create_ftnptr (mono_domain_get (), code);
5873 static int
5874 i32_idx_comparer (const void *key, const void *member)
5876 gint32 idx1 = GPOINTER_TO_INT (key);
5877 gint32 idx2 = *(gint32*)member;
5878 return idx1 - idx2;
5881 static int
5882 i16_idx_comparer (const void *key, const void *member)
5884 int idx1 = GPOINTER_TO_INT (key);
5885 int idx2 = *(gint16*)member;
5886 return idx1 - idx2;
5889 static gboolean
5890 aot_is_slim_amodule (MonoAotModule *amodule)
5892 if (!amodule)
5893 return FALSE;
5895 /* "slim" only applies to mscorlib.dll */
5896 if (strcmp (amodule->aot_name, "mscorlib"))
5897 return FALSE;
5899 guint32 f = amodule->info.flags;
5900 return (f & MONO_AOT_FILE_FLAG_INTERP) && !(f & MONO_AOT_FILE_FLAG_FULL_AOT);
5903 gpointer
5904 mono_aot_get_unbox_trampoline (MonoMethod *method, gpointer addr)
5906 ERROR_DECL (error);
5907 guint32 method_index = mono_metadata_token_index (method->token) - 1;
5908 MonoAotModule *amodule;
5909 gpointer code;
5910 guint32 *ut, *ut_end, *entry;
5911 int low, high, entry_index = 0;
5912 MonoTrampInfo *tinfo;
5914 if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
5915 method_index = find_aot_method (method, &amodule);
5916 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
5917 MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
5918 mono_error_assert_ok (error);
5919 method_index = find_aot_method (shared, &amodule);
5921 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, TRUE)) {
5922 MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
5923 mono_error_assert_ok (error);
5925 method_index = find_aot_method (shared, &amodule);
5927 } else
5928 amodule = m_class_get_image (method->klass)->aot_module;
5930 if (amodule == NULL || method_index == 0xffffff || aot_is_slim_amodule (amodule)) {
5931 /* couldn't find unbox trampoline specifically generated for that
5932 * method. this should only happen when an unbox trampoline is needed
5933 * for `fullAOT code -> native-to-interp -> interp` transition if
5934 * (1) it's a virtual call
5935 * (2) the receiver is a value type, thus needs unboxing */
5936 g_assert (mono_use_interpreter);
5937 return mono_aot_get_unbox_arbitrary_trampoline (addr);
5940 if (amodule->info.llvm_unbox_tramp_indexes) {
5941 int unbox_tramp_idx;
5943 /* Search the llvm_unbox_tramp_indexes table using a binary search */
5944 if (amodule->info.llvm_unbox_tramp_elemsize == sizeof (guint32)) {
5945 void *ptr = mono_binary_search (GINT_TO_POINTER (method_index), amodule->info.llvm_unbox_tramp_indexes, amodule->info.llvm_unbox_tramp_num, amodule->info.llvm_unbox_tramp_elemsize, i32_idx_comparer);
5946 g_assert (ptr);
5947 g_assert (*(int*)ptr == method_index);
5948 unbox_tramp_idx = (guint32*)ptr - (guint32*)amodule->info.llvm_unbox_tramp_indexes;
5949 } else {
5950 void *ptr = mono_binary_search (GINT_TO_POINTER (method_index), amodule->info.llvm_unbox_tramp_indexes, amodule->info.llvm_unbox_tramp_num, amodule->info.llvm_unbox_tramp_elemsize, i16_idx_comparer);
5951 g_assert (ptr);
5952 g_assert (*(gint16*)ptr == method_index);
5953 unbox_tramp_idx = (guint16*)ptr - (guint16*)amodule->info.llvm_unbox_tramp_indexes;
5955 g_assert (unbox_tramp_idx < amodule->info.llvm_unbox_tramp_num);
5956 code = ((gpointer*)(amodule->info.llvm_unbox_trampolines))[unbox_tramp_idx];
5957 g_assert (code);
5958 return code;
5961 if (amodule->info.llvm_get_unbox_tramp) {
5962 gpointer (*get_tramp) (int) = (gpointer (*)(int))amodule->info.llvm_get_unbox_tramp;
5963 code = get_tramp (method_index);
5965 if (code)
5966 return code;
5969 ut = amodule->unbox_trampolines;
5970 ut_end = amodule->unbox_trampolines_end;
5972 /* Do a binary search in the sorted table */
5973 code = NULL;
5974 low = 0;
5975 high = (ut_end - ut);
5976 while (low < high) {
5977 entry_index = (low + high) / 2;
5978 entry = &ut [entry_index];
5979 if (entry [0] < method_index) {
5980 low = entry_index + 1;
5981 } else if (entry [0] > method_index) {
5982 high = entry_index;
5983 } else {
5984 break;
5988 code = get_call_table_entry (amodule->unbox_trampoline_addresses, entry_index);
5989 g_assert (code);
5991 tinfo = mono_tramp_info_create (NULL, (guint8 *)code, 0, NULL, NULL);
5993 gpointer const symbol_addr = read_unwind_info (amodule, tinfo, "unbox_trampoline_p");
5994 if (!symbol_addr) {
5995 mono_tramp_info_free (tinfo);
5996 return FALSE;
5999 tinfo->code_size = *(guint32*)symbol_addr;
6000 mono_aot_tramp_info_register (tinfo, NULL);
6002 /* The caller expects an ftnptr */
6003 return mono_create_ftnptr (mono_domain_get (), code);
6006 gpointer
6007 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
6009 char *symbol;
6010 gpointer code;
6011 MonoAotModule *amodule = mono_defaults.corlib->aot_module;
6012 guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
6013 static int count = 0;
6015 count ++;
6016 if (index >= amodule->info.num_rgctx_fetch_trampolines) {
6017 static gpointer addr;
6018 gpointer *info;
6021 * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
6023 if (!addr)
6024 addr = load_function (amodule, "rgctx_fetch_trampoline_general");
6025 info = (void **)mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
6026 info [0] = GUINT_TO_POINTER (slot);
6027 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
6028 code = mono_aot_get_static_rgctx_trampoline (info, addr);
6029 return mono_create_ftnptr (mono_domain_get (), code);
6032 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
6033 code = load_function (mono_defaults.corlib->aot_module, symbol);
6034 g_free (symbol);
6035 /* The caller expects an ftnptr */
6036 return mono_create_ftnptr (mono_domain_get (), code);
6039 static void
6040 no_imt_trampoline (void)
6042 g_assert_not_reached ();
6045 gpointer
6046 mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
6048 guint32 got_offset;
6049 gpointer code;
6050 gpointer *buf;
6051 int i, index, real_count;
6052 MonoAotModule *amodule;
6054 if (mono_llvm_only)
6055 return (gpointer)no_imt_trampoline;
6057 real_count = 0;
6058 for (i = 0; i < count; ++i) {
6059 MonoIMTCheckItem *item = imt_entries [i];
6061 if (item->is_equals)
6062 real_count ++;
6065 /* Save the entries into an array */
6066 buf = (void **)mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
6067 index = 0;
6068 for (i = 0; i < count; ++i) {
6069 MonoIMTCheckItem *item = imt_entries [i];
6071 if (!item->is_equals)
6072 continue;
6074 g_assert (item->key);
6076 buf [(index * 2)] = item->key;
6077 if (item->has_target_code) {
6078 gpointer *p = (gpointer *)mono_domain_alloc (domain, sizeof (gpointer));
6079 *p = item->value.target_code;
6080 buf [(index * 2) + 1] = p;
6081 } else {
6082 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
6084 index ++;
6086 buf [(index * 2)] = NULL;
6087 buf [(index * 2) + 1] = fail_tramp;
6089 if (USE_PAGE_TRAMPOLINES) {
6090 code = get_new_imt_trampoline_from_page (buf);
6091 } else {
6092 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT, 1, &amodule, &got_offset, NULL);
6094 amodule->got [got_offset] = buf;
6097 return code;
6100 gpointer
6101 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
6103 MonoAotModule *amodule;
6104 guint8 *code;
6105 guint32 got_offset;
6107 if (USE_PAGE_TRAMPOLINES) {
6108 code = (guint8 *)get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
6109 } else {
6110 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
6112 amodule->got [got_offset] = arg;
6113 amodule->got [got_offset + 1] = addr;
6116 /* The caller expects an ftnptr */
6117 return mono_create_ftnptr (mono_domain_get (), code);
6120 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
6121 gpointer
6122 mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
6124 MonoAotModule *amodule;
6125 guint8 *code;
6126 guint32 got_offset;
6128 if (USE_PAGE_TRAMPOLINES) {
6129 g_error ("FIXME: ftnptr_arg page trampolines");
6130 } else {
6131 code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_FTNPTR_ARG, 2, &amodule, &got_offset, NULL);
6133 amodule->got [got_offset] = arg;
6134 amodule->got [got_offset + 1] = addr;
6137 /* The caller expects an ftnptr */
6138 return mono_create_ftnptr (mono_domain_get (), code);
6140 #endif
6144 * mono_aot_set_make_unreadable:
6146 * Set whenever to make all mmaped memory unreadable. In conjuction with a
6147 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
6149 void
6150 mono_aot_set_make_unreadable (gboolean unreadable)
6152 static int inited;
6154 make_unreadable = unreadable;
6156 if (make_unreadable && !inited) {
6157 mono_counters_register ("AOT: pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
6161 typedef struct {
6162 MonoAotModule *module;
6163 guint8 *ptr;
6164 } FindMapUserData;
6166 static void
6167 find_map (gpointer key, gpointer value, gpointer user_data)
6169 MonoAotModule *module = (MonoAotModule*)value;
6170 FindMapUserData *data = (FindMapUserData*)user_data;
6172 if (!data->module)
6173 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
6174 data->module = module;
6177 static MonoAotModule*
6178 find_module_for_addr (void *ptr)
6180 FindMapUserData data;
6182 if (!make_unreadable)
6183 return NULL;
6185 data.module = NULL;
6186 data.ptr = (guint8*)ptr;
6188 mono_aot_lock ();
6189 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
6190 mono_aot_unlock ();
6192 return data.module;
6196 * mono_aot_is_pagefault:
6198 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
6199 * within memory allocated by this module.
6201 gboolean
6202 mono_aot_is_pagefault (void *ptr)
6204 if (!make_unreadable)
6205 return FALSE;
6208 * Not signal safe, but SIGSEGV's are synchronous, and
6209 * this is only turned on by a MONO_DEBUG option.
6211 return find_module_for_addr (ptr) != NULL;
6215 * mono_aot_handle_pagefault:
6217 * Handle a pagefault caused by an unreadable page by making it readable again.
6219 void
6220 mono_aot_handle_pagefault (void *ptr)
6222 #ifndef HOST_WIN32
6223 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
6224 int res;
6226 mono_aot_lock ();
6227 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
6228 g_assert (res == 0);
6230 n_pagefaults ++;
6231 mono_aot_unlock ();
6232 #endif
6235 MonoAotMethodFlags
6236 mono_aot_get_method_flags (guint8 *code)
6238 guint32 flags;
6240 if (!code_to_method_flags)
6241 return MONO_AOT_METHOD_FLAG_NONE;
6242 mono_aot_lock ();
6243 /* Not found and no FLAG_NONE are the same, but its not a problem */
6244 flags = GPOINTER_TO_UINT (g_hash_table_lookup (code_to_method_flags, code));
6245 mono_aot_unlock ();
6246 return (MonoAotMethodFlags)flags;
6249 #else
6250 /* AOT disabled */
6252 void
6253 mono_aot_init (void)
6257 void
6258 mono_aot_cleanup (void)
6262 guint32
6263 mono_aot_find_method_index (MonoMethod *method)
6265 g_assert_not_reached ();
6266 return 0;
6269 void
6270 mono_aot_init_llvm_method (gpointer aot_module, guint32 method_index)
6274 void
6275 mono_aot_init_gshared_method_this (gpointer aot_module, guint32 method_index, MonoObject *this)
6279 void
6280 mono_aot_init_gshared_method_mrgctx (gpointer aot_module, guint32 method_index, MonoMethodRuntimeGenericContext *rgctx)
6284 void
6285 mono_aot_init_gshared_method_vtable (gpointer aot_module, guint32 method_index, MonoVTable *vtable)
6289 gpointer
6290 mono_aot_get_method (MonoDomain *domain,
6291 MonoMethod *method, MonoError *error)
6293 error_init (error);
6294 return NULL;
6297 gboolean
6298 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
6300 return FALSE;
6303 gboolean
6304 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
6306 return FALSE;
6309 gboolean
6310 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
6312 return FALSE;
6315 MonoJitInfo *
6316 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
6318 return NULL;
6321 gpointer
6322 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token, MonoError *error)
6324 error_init (error);
6325 return NULL;
6328 guint8*
6329 mono_aot_get_plt_entry (guint8 *code)
6331 return NULL;
6334 gpointer
6335 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code, MonoError *error)
6337 return NULL;
6340 void
6341 mono_aot_patch_plt_entry (guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
6345 gpointer
6346 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot, MonoError *error)
6348 error_init (error);
6350 return NULL;
6353 guint32
6354 mono_aot_get_plt_info_offset (host_mgreg_t *regs, guint8 *code)
6356 g_assert_not_reached ();
6358 return 0;
6361 gpointer
6362 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
6364 g_assert_not_reached ();
6365 return NULL;
6368 gpointer
6369 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
6371 g_assert_not_reached ();
6372 return NULL;
6375 gpointer
6376 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
6378 g_assert_not_reached ();
6379 return NULL;
6382 gpointer
6383 mono_aot_get_trampoline (const char *name)
6385 g_assert_not_reached ();
6386 return NULL;
6389 gpointer
6390 mono_aot_get_unbox_arbitrary_trampoline (gpointer addr)
6392 g_assert_not_reached ();
6393 return NULL;
6396 gpointer
6397 mono_aot_get_unbox_trampoline (MonoMethod *method, gpointer addr)
6399 g_assert_not_reached ();
6400 return NULL;
6403 gpointer
6404 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
6406 g_assert_not_reached ();
6407 return NULL;
6410 gpointer
6411 mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
6413 g_assert_not_reached ();
6414 return NULL;
6417 gpointer
6418 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
6420 g_assert_not_reached ();
6421 return NULL;
6424 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
6425 gpointer
6426 mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
6428 g_assert_not_reached ();
6429 return NULL;
6431 #endif
6433 void
6434 mono_aot_set_make_unreadable (gboolean unreadable)
6438 gboolean
6439 mono_aot_is_pagefault (void *ptr)
6441 return FALSE;
6444 void
6445 mono_aot_handle_pagefault (void *ptr)
6449 guint8*
6450 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
6452 g_assert_not_reached ();
6453 return NULL;
6456 void
6457 mono_aot_register_jit_icall (const char *name, gpointer addr)
6461 GHashTable *
6462 mono_aot_get_weak_field_indexes (MonoImage *image)
6464 return NULL;
6467 MonoAotMethodFlags
6468 mono_aot_get_method_flags (guint8 *code)
6470 return MONO_AOT_METHOD_FLAG_NONE;
6473 #endif