[jit] Fix error handling in a few places in the jit.
[mono-project.git] / mono / mini / aot-runtime.c
blob98361554a3ecb552c2297b72e55b04adcf1a86a1
1 /*
2 * aot-runtime.c: mono Ahead of Time compiler
4 * Author:
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc.
10 * Copyright 2011 Xamarin, Inc.
13 #include "config.h"
14 #include <sys/types.h>
15 #ifdef HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18 #include <fcntl.h>
19 #include <string.h>
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
24 #if HOST_WIN32
25 #include <winsock2.h>
26 #include <windows.h>
27 #endif
29 #ifdef HAVE_EXECINFO_H
30 #include <execinfo.h>
31 #endif
33 #include <errno.h>
34 #include <sys/stat.h>
36 #ifdef HAVE_SYS_WAIT_H
37 #include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
38 #endif
40 #include <mono/metadata/abi-details.h>
41 #include <mono/metadata/tabledefs.h>
42 #include <mono/metadata/class.h>
43 #include <mono/metadata/object.h>
44 #include <mono/metadata/tokentype.h>
45 #include <mono/metadata/appdomain.h>
46 #include <mono/metadata/debug-helpers.h>
47 #include <mono/metadata/assembly.h>
48 #include <mono/metadata/metadata-internals.h>
49 #include <mono/metadata/marshal.h>
50 #include <mono/metadata/gc-internal.h>
51 #include <mono/metadata/monitor.h>
52 #include <mono/metadata/threads-types.h>
53 #include <mono/metadata/mono-endian.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include "mono/utils/mono-compiler.h"
57 #include <mono/utils/mono-counters.h>
58 #include <mono/utils/mono-digest.h>
60 #include "mini.h"
61 #include "version.h"
63 #ifndef DISABLE_AOT
65 #ifdef TARGET_OSX
66 #define ENABLE_AOT_CACHE
67 #endif
69 #ifdef TARGET_WIN32
70 #define SHARED_EXT ".dll"
71 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
72 #define SHARED_EXT ".dylib"
73 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
74 #define SHARED_EXT ".dylib"
75 #else
76 #define SHARED_EXT ".so"
77 #endif
79 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
80 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
81 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
83 typedef struct {
84 int method_index;
85 MonoJitInfo *jinfo;
86 } JitInfoMap;
88 typedef struct MonoAotModule {
89 char *aot_name;
90 /* Pointer to the Global Offset Table */
91 gpointer *got;
92 GHashTable *name_cache;
93 GHashTable *extra_methods;
94 /* Maps methods to their code */
95 GHashTable *method_to_code;
96 /* Maps pointers into the method info to the methods themselves */
97 GHashTable *method_ref_to_method;
98 MonoAssemblyName *image_names;
99 char **image_guids;
100 MonoAssembly *assembly;
101 MonoImage **image_table;
102 guint32 image_table_len;
103 gboolean out_of_date;
104 gboolean plt_inited;
105 guint8 *mem_begin;
106 guint8 *mem_end;
107 guint8 *code;
108 guint8 *code_end;
109 guint8 *plt;
110 guint8 *plt_end;
111 guint8 *blob;
112 gint32 *code_offsets;
113 gpointer *method_addresses;
114 /* This contains <offset, index> pairs sorted by offset */
115 /* This is needed because LLVM emitted methods can be in any order */
116 gint32 *sorted_code_offsets;
117 gint32 sorted_code_offsets_len;
118 guint32 *method_info_offsets;
119 guint32 *got_info_offsets;
120 guint32 *ex_info_offsets;
121 guint32 *class_info_offsets;
122 guint32 *methods_loaded;
123 guint16 *class_name_table;
124 guint32 *extra_method_table;
125 guint32 *extra_method_info_offsets;
126 guint32 *unbox_trampolines;
127 guint32 *unbox_trampolines_end;
128 guint8 *unwind_info;
129 guint8 *thumb_end;
131 /* Points to the mono EH data created by LLVM */
132 guint8 *mono_eh_frame;
134 /* Points to the trampolines */
135 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
136 /* The first unused trampoline of each kind */
137 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
139 gboolean use_page_trampolines;
141 MonoAotFileInfo info;
143 gpointer *globals;
144 MonoDl *sofile;
146 JitInfoMap *async_jit_info_table;
147 mono_mutex_t mutex;
148 } MonoAotModule;
150 typedef struct {
151 void *next;
152 unsigned char *trampolines;
153 unsigned char *trampolines_end;
154 } TrampolinePage;
156 static GHashTable *aot_modules;
157 #define mono_aot_lock() mono_mutex_lock (&aot_mutex)
158 #define mono_aot_unlock() mono_mutex_unlock (&aot_mutex)
159 static mono_mutex_t aot_mutex;
162 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
163 * AOT modules registered by mono_aot_register_module ().
165 static GHashTable *static_aot_modules;
168 * Maps MonoJitInfo* to the aot module they belong to, this can be different
169 * from ji->method->klass->image's aot module for generic instances.
171 static GHashTable *ji_to_amodule;
174 * Whenever to AOT compile loaded assemblies on demand and store them in
175 * a cache.
177 static gboolean enable_aot_cache = FALSE;
179 static gboolean mscorlib_aot_loaded;
181 /* For debugging */
182 static gint32 mono_last_aot_method = -1;
184 static gboolean make_unreadable = FALSE;
185 static guint32 name_table_accesses = 0;
186 static guint32 n_pagefaults = 0;
188 /* Used to speed-up find_aot_module () */
189 static gsize aot_code_low_addr = (gssize)-1;
190 static gsize aot_code_high_addr = 0;
192 /* Stats */
193 static gint32 async_jit_info_size;
195 static GHashTable *aot_jit_icall_hash;
197 #ifdef MONOTOUCH
198 #define USE_PAGE_TRAMPOLINES ((MonoAotModule*)mono_defaults.corlib->aot_module)->use_page_trampolines
199 #else
200 #define USE_PAGE_TRAMPOLINES 0
201 #endif
203 #define mono_aot_page_lock() mono_mutex_lock (&aot_page_mutex)
204 #define mono_aot_page_unlock() mono_mutex_unlock (&aot_page_mutex)
205 static mono_mutex_t aot_page_mutex;
207 static void
208 init_plt (MonoAotModule *info);
210 /*****************************************************/
211 /* AOT RUNTIME */
212 /*****************************************************/
214 static inline void
215 amodule_lock (MonoAotModule *amodule)
217 mono_mutex_lock (&amodule->mutex);
220 static inline void
221 amodule_unlock (MonoAotModule *amodule)
223 mono_mutex_unlock (&amodule->mutex);
227 * load_image:
229 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
230 * found, and sets the loader error if SET_ERROR is TRUE.
232 static MonoImage *
233 load_image (MonoAotModule *amodule, int index, gboolean set_error)
235 MonoAssembly *assembly;
236 MonoImageOpenStatus status;
238 g_assert (index < amodule->image_table_len);
240 if (amodule->image_table [index])
241 return amodule->image_table [index];
242 if (amodule->out_of_date)
243 return NULL;
245 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
246 if (!assembly) {
247 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable because dependency %s is not found.\n", amodule->aot_name, amodule->image_names [index].name);
248 amodule->out_of_date = TRUE;
250 if (set_error) {
251 char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
252 mono_loader_set_error_assembly_load (full_name, FALSE);
253 g_free (full_name);
255 return NULL;
258 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
259 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').\n", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
260 amodule->out_of_date = TRUE;
261 return NULL;
264 amodule->image_table [index] = assembly->image;
265 return assembly->image;
268 static inline gint32
269 decode_value (guint8 *ptr, guint8 **rptr)
271 guint8 b = *ptr;
272 gint32 len;
274 if ((b & 0x80) == 0){
275 len = b;
276 ++ptr;
277 } else if ((b & 0x40) == 0){
278 len = ((b & 0x3f) << 8 | ptr [1]);
279 ptr += 2;
280 } else if (b != 0xff) {
281 len = ((b & 0x1f) << 24) |
282 (ptr [1] << 16) |
283 (ptr [2] << 8) |
284 ptr [3];
285 ptr += 4;
287 else {
288 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
289 ptr += 5;
291 if (rptr)
292 *rptr = ptr;
294 //printf ("DECODE: %d.\n", len);
295 return len;
299 * mono_aot_get_offset:
301 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
302 * entry.
304 static guint32
305 mono_aot_get_offset (guint32 *table, int index)
307 int i, group, ngroups, index_entry_size;
308 int start_offset, offset, noffsets, group_size;
309 guint8 *data_start, *p;
310 guint32 *index32 = NULL;
311 guint16 *index16 = NULL;
313 noffsets = table [0];
314 group_size = table [1];
315 ngroups = table [2];
316 index_entry_size = table [3];
317 group = index / group_size;
319 if (index_entry_size == 2) {
320 index16 = (guint16*)&table [4];
321 data_start = (guint8*)&index16 [ngroups];
322 p = data_start + index16 [group];
323 } else {
324 index32 = (guint32*)&table [4];
325 data_start = (guint8*)&index32 [ngroups];
326 p = data_start + index32 [group];
329 /* offset will contain the value of offsets [group * group_size] */
330 offset = start_offset = decode_value (p, &p);
331 for (i = group * group_size + 1; i <= index; ++i) {
332 offset += decode_value (p, &p);
335 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
337 return offset;
340 static MonoMethod*
341 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
343 static MonoClass*
344 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
346 static MonoType*
347 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
349 static MonoGenericInst*
350 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
352 int type_argc, i;
353 MonoType **type_argv;
354 MonoGenericInst *inst;
355 guint8 *p = buf;
357 type_argc = decode_value (p, &p);
358 type_argv = g_new0 (MonoType*, type_argc);
360 for (i = 0; i < type_argc; ++i) {
361 MonoClass *pclass = decode_klass_ref (module, p, &p);
362 if (!pclass) {
363 g_free (type_argv);
364 return NULL;
366 type_argv [i] = &pclass->byval_arg;
369 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
370 g_free (type_argv);
372 *endbuf = p;
374 return inst;
377 static gboolean
378 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
380 guint8 *p = buf;
381 guint8 *p2;
382 int argc;
384 p2 = p;
385 argc = decode_value (p, &p);
386 if (argc) {
387 p = p2;
388 ctx->class_inst = decode_generic_inst (module, p, &p);
389 if (!ctx->class_inst)
390 return FALSE;
392 p2 = p;
393 argc = decode_value (p, &p);
394 if (argc) {
395 p = p2;
396 ctx->method_inst = decode_generic_inst (module, p, &p);
397 if (!ctx->method_inst)
398 return FALSE;
401 *endbuf = p;
402 return TRUE;
405 static MonoClass*
406 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
408 MonoError error;
409 MonoImage *image;
410 MonoClass *klass = NULL, *eklass;
411 guint32 token, rank, idx;
412 guint8 *p = buf;
413 int reftype;
415 reftype = decode_value (p, &p);
416 if (reftype == 0) {
417 *endbuf = p;
418 return NULL;
421 switch (reftype) {
422 case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
423 idx = decode_value (p, &p);
424 image = load_image (module, 0, TRUE);
425 if (!image)
426 return NULL;
427 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, &error);
428 g_assert (mono_error_ok (&error));
429 break;
430 case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
431 idx = decode_value (p, &p);
432 image = load_image (module, decode_value (p, &p), TRUE);
433 if (!image)
434 return NULL;
435 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, &error);
436 g_assert (mono_error_ok (&error));
437 break;
438 case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
439 token = decode_value (p, &p);
440 image = module->assembly->image;
441 if (!image)
442 return NULL;
443 klass = mono_class_get_checked (image, token, &error);
444 g_assert (mono_error_ok (&error));
445 break;
446 case MONO_AOT_TYPEREF_GINST: {
447 MonoClass *gclass;
448 MonoGenericContext ctx;
449 MonoType *type;
451 gclass = decode_klass_ref (module, p, &p);
452 if (!gclass)
453 return NULL;
454 g_assert (gclass->generic_container);
456 memset (&ctx, 0, sizeof (ctx));
457 ctx.class_inst = decode_generic_inst (module, p, &p);
458 if (!ctx.class_inst)
459 return NULL;
460 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
461 klass = mono_class_from_mono_type (type);
462 mono_metadata_free_type (type);
463 break;
465 case MONO_AOT_TYPEREF_VAR: {
466 MonoType *t;
467 MonoGenericContainer *container = NULL;
468 int type = decode_value (p, &p);
469 int num = decode_value (p, &p);
470 gboolean has_container = decode_value (p, &p);
471 int serial = 0;
473 if (has_container) {
474 gboolean is_method = decode_value (p, &p);
476 if (is_method) {
477 MonoMethod *method_def;
478 g_assert (type == MONO_TYPE_MVAR);
479 method_def = decode_resolve_method_ref (module, p, &p);
480 if (!method_def)
481 return NULL;
483 container = mono_method_get_generic_container (method_def);
484 } else {
485 MonoClass *class_def;
486 g_assert (type == MONO_TYPE_VAR);
487 class_def = decode_klass_ref (module, p, &p);
488 if (!class_def)
489 return NULL;
491 container = class_def->generic_container;
493 } else {
494 serial = decode_value (p, &p);
497 t = g_new0 (MonoType, 1);
498 t->type = type;
499 if (container) {
500 t->data.generic_param = mono_generic_container_get_param (container, num);
501 g_assert (serial == 0);
502 } else {
503 /* Anonymous */
504 MonoGenericParam *par = (MonoGenericParam*)mono_image_alloc0 (module->assembly->image, sizeof (MonoGenericParamFull));
505 par->num = num;
506 par->serial = serial;
507 // FIXME:
508 par->image = mono_defaults.corlib;
509 t->data.generic_param = par;
512 // FIXME: Maybe use types directly to avoid
513 // the overhead of creating MonoClass-es
514 klass = mono_class_from_mono_type (t);
516 g_free (t);
517 break;
519 case MONO_AOT_TYPEREF_ARRAY:
520 /* Array */
521 rank = decode_value (p, &p);
522 eklass = decode_klass_ref (module, p, &p);
523 klass = mono_array_class_get (eklass, rank);
524 break;
525 case MONO_AOT_TYPEREF_PTR: {
526 MonoType *t;
528 t = decode_type (module, p, &p);
529 if (!t)
530 return NULL;
531 klass = mono_class_from_mono_type (t);
532 g_free (t);
533 break;
535 case MONO_AOT_TYPEREF_BLOB_INDEX: {
536 guint32 offset = decode_value (p, &p);
537 guint8 *p2;
539 p2 = module->blob + offset;
540 klass = decode_klass_ref (module, p2, &p2);
541 break;
543 default:
544 g_assert_not_reached ();
546 g_assert (klass);
547 //printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
548 *endbuf = p;
549 return klass;
552 static MonoClassField*
553 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
555 MonoClass *klass = decode_klass_ref (module, buf, &buf);
556 guint32 token;
557 guint8 *p = buf;
559 if (!klass)
560 return NULL;
562 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
564 *endbuf = p;
566 return mono_class_get_field (klass, token);
570 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
571 * memory.
573 static MonoType*
574 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
576 guint8 *p = buf;
577 MonoType *t;
579 t = g_malloc0 (sizeof (MonoType));
581 while (TRUE) {
582 if (*p == MONO_TYPE_PINNED) {
583 t->pinned = TRUE;
584 ++p;
585 } else if (*p == MONO_TYPE_BYREF) {
586 t->byref = TRUE;
587 ++p;
588 } else {
589 break;
593 t->type = *p;
594 ++p;
596 switch (t->type) {
597 case MONO_TYPE_VOID:
598 case MONO_TYPE_BOOLEAN:
599 case MONO_TYPE_CHAR:
600 case MONO_TYPE_I1:
601 case MONO_TYPE_U1:
602 case MONO_TYPE_I2:
603 case MONO_TYPE_U2:
604 case MONO_TYPE_I4:
605 case MONO_TYPE_U4:
606 case MONO_TYPE_I8:
607 case MONO_TYPE_U8:
608 case MONO_TYPE_R4:
609 case MONO_TYPE_R8:
610 case MONO_TYPE_I:
611 case MONO_TYPE_U:
612 case MONO_TYPE_STRING:
613 case MONO_TYPE_OBJECT:
614 case MONO_TYPE_TYPEDBYREF:
615 break;
616 case MONO_TYPE_VALUETYPE:
617 case MONO_TYPE_CLASS:
618 t->data.klass = decode_klass_ref (module, p, &p);
619 break;
620 case MONO_TYPE_SZARRAY:
621 t->data.klass = decode_klass_ref (module, p, &p);
623 if (!t->data.klass)
624 return NULL;
625 break;
626 case MONO_TYPE_PTR:
627 t->data.type = decode_type (module, p, &p);
628 break;
629 case MONO_TYPE_GENERICINST: {
630 MonoClass *gclass;
631 MonoGenericContext ctx;
632 MonoType *type;
633 MonoClass *klass;
635 gclass = decode_klass_ref (module, p, &p);
636 if (!gclass)
637 return NULL;
638 g_assert (gclass->generic_container);
640 memset (&ctx, 0, sizeof (ctx));
641 ctx.class_inst = decode_generic_inst (module, p, &p);
642 if (!ctx.class_inst)
643 return NULL;
644 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
645 klass = mono_class_from_mono_type (type);
646 t->data.generic_class = klass->generic_class;
647 break;
649 case MONO_TYPE_ARRAY: {
650 MonoArrayType *array;
651 int i;
653 // FIXME: memory management
654 array = g_new0 (MonoArrayType, 1);
655 array->eklass = decode_klass_ref (module, p, &p);
656 if (!array->eklass)
657 return NULL;
658 array->rank = decode_value (p, &p);
659 array->numsizes = decode_value (p, &p);
661 if (array->numsizes)
662 array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
663 for (i = 0; i < array->numsizes; ++i)
664 array->sizes [i] = decode_value (p, &p);
666 array->numlobounds = decode_value (p, &p);
667 if (array->numlobounds)
668 array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
669 for (i = 0; i < array->numlobounds; ++i)
670 array->lobounds [i] = decode_value (p, &p);
671 t->data.array = array;
672 break;
674 case MONO_TYPE_VAR:
675 case MONO_TYPE_MVAR: {
676 MonoClass *klass = decode_klass_ref (module, p, &p);
677 if (!klass)
678 return NULL;
679 t->data.generic_param = klass->byval_arg.data.generic_param;
680 break;
682 default:
683 g_assert_not_reached ();
686 *endbuf = p;
688 return t;
691 // FIXME: Error handling, memory management
693 static MonoMethodSignature*
694 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
696 MonoMethodSignature *sig;
697 guint32 flags;
698 int i, param_count, call_conv, gen_param_count = 0;
699 guint8 *p = buf;
700 gboolean hasthis, explicit_this, has_gen_params;
702 flags = *p;
703 p ++;
704 has_gen_params = (flags & 0x10) != 0;
705 hasthis = (flags & 0x20) != 0;
706 explicit_this = (flags & 0x40) != 0;
707 call_conv = flags & 0x0F;
709 if (has_gen_params)
710 gen_param_count = decode_value (p, &p);
711 param_count = decode_value (p, &p);
712 if (target && param_count != target->param_count)
713 return NULL;
714 sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
715 sig->param_count = param_count;
716 sig->sentinelpos = -1;
717 sig->hasthis = hasthis;
718 sig->explicit_this = explicit_this;
719 sig->call_convention = call_conv;
720 sig->param_count = param_count;
721 sig->ret = decode_type (module, p, &p);
722 for (i = 0; i < param_count; ++i) {
723 if (*p == MONO_TYPE_SENTINEL) {
724 g_assert (sig->call_convention == MONO_CALL_VARARG);
725 sig->sentinelpos = i;
726 p ++;
728 sig->params [i] = decode_type (module, p, &p);
731 if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
732 sig->sentinelpos = sig->param_count;
734 *endbuf = p;
736 return sig;
739 static MonoMethodSignature*
740 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
742 return decode_signature_with_target (module, NULL, buf, endbuf);
745 static gboolean
746 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
748 MonoMethodSignature *sig;
749 gboolean res;
750 guint8 *p = buf;
752 sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
753 res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
754 g_free (sig);
755 *endbuf = p;
756 return res;
759 /* Stores information returned by decode_method_ref () */
760 typedef struct {
761 MonoImage *image;
762 guint32 token;
763 MonoMethod *method;
764 gboolean no_aot_trampoline;
765 } MethodRef;
768 * decode_method_ref_with_target:
770 * Decode a method reference, storing the image/token into a MethodRef structure.
771 * This avoids loading metadata for the method if the caller does not need it. If the method has
772 * no token, then it is loaded from metadata and ref->method is set to the method instance.
773 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
774 * couldn't resolve to TARGET, and return FALSE.
775 * There are some kinds of method references which only support a non-null TARGET.
776 * This means that its not possible to decode this into a method, only to check
777 * that the method reference matches a given method. This is normally not a problem
778 * as these wrappers only occur in the extra_methods table, where we already have
779 * a method we want to lookup.
781 static gboolean
782 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
784 guint32 image_index, value;
785 MonoImage *image = NULL;
786 guint8 *p = buf;
788 memset (ref, 0, sizeof (MethodRef));
790 value = decode_value (p, &p);
791 image_index = value >> 24;
793 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
794 ref->no_aot_trampoline = TRUE;
795 value = decode_value (p, &p);
796 image_index = value >> 24;
799 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
800 if (target && target->wrapper_type)
801 return FALSE;
804 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
805 guint32 wrapper_type;
807 wrapper_type = decode_value (p, &p);
809 if (target && target->wrapper_type != wrapper_type)
810 return FALSE;
812 /* Doesn't matter */
813 image = mono_defaults.corlib;
815 switch (wrapper_type) {
816 #ifndef DISABLE_REMOTING
817 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
818 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
820 if (!m)
821 return FALSE;
822 mono_class_init (m->klass);
823 ref->method = mono_marshal_get_remoting_invoke_with_check (m);
824 break;
826 case MONO_WRAPPER_PROXY_ISINST: {
827 MonoClass *klass = decode_klass_ref (module, p, &p);
828 if (!klass)
829 return FALSE;
830 ref->method = mono_marshal_get_proxy_cancast (klass);
831 break;
833 case MONO_WRAPPER_LDFLD:
834 case MONO_WRAPPER_LDFLDA:
835 case MONO_WRAPPER_STFLD:
836 case MONO_WRAPPER_ISINST: {
837 MonoClass *klass = decode_klass_ref (module, p, &p);
838 if (!klass)
839 return FALSE;
840 if (wrapper_type == MONO_WRAPPER_LDFLD)
841 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
842 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
843 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
844 else if (wrapper_type == MONO_WRAPPER_STFLD)
845 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
846 else if (wrapper_type == MONO_WRAPPER_ISINST)
847 ref->method = mono_marshal_get_isinst (klass);
848 else
849 g_assert_not_reached ();
850 break;
852 case MONO_WRAPPER_LDFLD_REMOTE:
853 ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
854 break;
855 case MONO_WRAPPER_STFLD_REMOTE:
856 ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
857 break;
858 #endif
859 case MONO_WRAPPER_ALLOC: {
860 int atype = decode_value (p, &p);
862 ref->method = mono_gc_get_managed_allocator_by_type (atype);
863 g_assert (ref->method);
864 break;
866 case MONO_WRAPPER_WRITE_BARRIER:
867 ref->method = mono_gc_get_write_barrier ();
868 break;
869 case MONO_WRAPPER_STELEMREF: {
870 int subtype = decode_value (p, &p);
872 if (subtype == WRAPPER_SUBTYPE_NONE) {
873 ref->method = mono_marshal_get_stelemref ();
874 } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
875 int kind;
876 WrapperInfo *info;
878 kind = decode_value (p, &p);
880 /* Can't decode this */
881 if (!target)
882 return FALSE;
883 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
884 info = mono_marshal_get_wrapper_info (target);
886 g_assert (info);
887 if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
888 ref->method = target;
889 else
890 return FALSE;
891 } else {
892 return FALSE;
894 } else {
895 g_assert_not_reached ();
897 break;
899 case MONO_WRAPPER_SYNCHRONIZED: {
900 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
902 if (!m)
903 return FALSE;
904 ref->method = mono_marshal_get_synchronized_wrapper (m);
905 break;
907 case MONO_WRAPPER_UNKNOWN: {
908 MonoMethodDesc *desc;
909 MonoMethod *orig_method;
910 int subtype = decode_value (p, &p);
912 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
913 MonoClass *klass = decode_klass_ref (module, p, &p);
915 if (!klass)
916 return FALSE;
918 if (!target)
919 return FALSE;
920 if (klass != target->klass)
921 return FALSE;
923 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
924 if (strcmp (target->name, "PtrToStructure"))
925 return FALSE;
926 ref->method = mono_marshal_get_ptr_to_struct (klass);
927 } else {
928 if (strcmp (target->name, "StructureToPtr"))
929 return FALSE;
930 ref->method = mono_marshal_get_struct_to_ptr (klass);
932 } else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
933 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
935 if (!m)
936 return FALSE;
937 ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
938 } else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
939 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
941 if (!m)
942 return FALSE;
943 ref->method = mono_marshal_get_array_accessor_wrapper (m);
944 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
945 ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
946 } else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
947 ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
948 } else {
949 if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
950 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
951 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
952 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
953 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
954 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
955 else
956 g_assert_not_reached ();
957 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
958 g_assert (orig_method);
959 mono_method_desc_free (desc);
960 ref->method = mono_monitor_get_fast_path (orig_method);
962 break;
964 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
965 int subtype = decode_value (p, &p);
967 if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
968 int rank = decode_value (p, &p);
969 int elem_size = decode_value (p, &p);
971 ref->method = mono_marshal_get_array_address (rank, elem_size);
972 } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
973 WrapperInfo *info;
974 MonoMethod *m;
976 m = decode_resolve_method_ref (module, p, &p);
977 if (!m)
978 return FALSE;
980 if (!target)
981 return FALSE;
982 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
984 info = mono_marshal_get_wrapper_info (target);
985 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
986 ref->method = target;
987 else
988 return FALSE;
990 break;
992 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
993 MonoMethod *m;
994 int subtype = decode_value (p, &p);
995 char *name;
997 if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
998 if (!target)
999 return FALSE;
1001 name = (char*)p;
1002 if (strcmp (target->name, name) != 0)
1003 return FALSE;
1004 ref->method = target;
1005 } else {
1006 m = decode_resolve_method_ref (module, p, &p);
1008 if (!m)
1009 return FALSE;
1011 /* This should only happen when looking for an extra method */
1012 if (!target)
1013 return FALSE;
1014 if (mono_marshal_method_from_wrapper (target) == m)
1015 ref->method = target;
1016 else
1017 return FALSE;
1019 break;
1021 case MONO_WRAPPER_CASTCLASS: {
1022 int subtype = decode_value (p, &p);
1024 if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
1025 ref->method = mono_marshal_get_castclass_with_cache ();
1026 else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
1027 ref->method = mono_marshal_get_isinst_with_cache ();
1028 else
1029 g_assert_not_reached ();
1030 break;
1032 case MONO_WRAPPER_RUNTIME_INVOKE: {
1033 int subtype = decode_value (p, &p);
1035 if (!target)
1036 return FALSE;
1038 if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
1039 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
1040 return FALSE;
1041 ref->method = target;
1042 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
1043 /* Direct wrapper */
1044 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1046 if (!m)
1047 return FALSE;
1048 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
1049 } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
1050 /* Virtual direct wrapper */
1051 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
1053 if (!m)
1054 return FALSE;
1055 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
1056 } else {
1057 MonoMethodSignature *sig;
1058 WrapperInfo *info;
1060 sig = decode_signature_with_target (module, NULL, p, &p);
1061 info = mono_marshal_get_wrapper_info (target);
1062 g_assert (info);
1064 if (info->subtype != subtype)
1065 return FALSE;
1066 g_assert (info->d.runtime_invoke.sig);
1067 if (mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig))
1068 ref->method = target;
1069 else
1070 return FALSE;
1072 break;
1074 case MONO_WRAPPER_DELEGATE_INVOKE:
1075 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1076 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
1077 gboolean is_inflated = decode_value (p, &p);
1078 WrapperSubtype subtype;
1080 if (is_inflated) {
1081 MonoClass *klass;
1082 MonoMethod *invoke, *wrapper;
1084 klass = decode_klass_ref (module, p, &p);
1085 if (!klass)
1086 return FALSE;
1088 switch (wrapper_type) {
1089 case MONO_WRAPPER_DELEGATE_INVOKE:
1090 invoke = mono_get_delegate_invoke (klass);
1091 wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
1092 break;
1093 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
1094 invoke = mono_get_delegate_begin_invoke (klass);
1095 wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
1096 break;
1097 case MONO_WRAPPER_DELEGATE_END_INVOKE:
1098 invoke = mono_get_delegate_end_invoke (klass);
1099 wrapper = mono_marshal_get_delegate_end_invoke (invoke);
1100 break;
1101 default:
1102 g_assert_not_reached ();
1103 break;
1105 if (target && wrapper != target)
1106 return FALSE;
1107 ref->method = wrapper;
1108 } else {
1110 * These wrappers are associated with a signature, not with a method.
1111 * Since we can't decode them into methods, they need a target method.
1113 if (!target)
1114 return FALSE;
1116 if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1117 WrapperInfo *info;
1119 subtype = decode_value (p, &p);
1120 info = mono_marshal_get_wrapper_info (target);
1121 if (info) {
1122 if (info->subtype != subtype)
1123 return FALSE;
1124 } else {
1125 if (subtype != WRAPPER_SUBTYPE_NONE)
1126 return FALSE;
1129 if (sig_matches_target (module, target, p, &p))
1130 ref->method = target;
1131 else
1132 return FALSE;
1134 break;
1136 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
1137 MonoMethod *m;
1138 MonoClass *klass;
1140 m = decode_resolve_method_ref (module, p, &p);
1141 if (!m)
1142 return FALSE;
1143 klass = decode_klass_ref (module, p, &p);
1144 if (!klass)
1145 return FALSE;
1146 ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
1147 break;
1149 default:
1150 g_assert_not_reached ();
1152 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1153 image_index = decode_value (p, &p);
1154 ref->token = decode_value (p, &p);
1156 image = load_image (module, image_index, TRUE);
1157 if (!image)
1158 return FALSE;
1159 } else if (image_index == MONO_AOT_METHODREF_GINST) {
1160 MonoClass *klass;
1161 MonoGenericContext ctx;
1164 * These methods do not have a token which resolves them, so we
1165 * resolve them immediately.
1167 klass = decode_klass_ref (module, p, &p);
1168 if (!klass)
1169 return FALSE;
1171 if (target && target->klass != klass)
1172 return FALSE;
1174 image_index = decode_value (p, &p);
1175 ref->token = decode_value (p, &p);
1177 image = load_image (module, image_index, TRUE);
1178 if (!image)
1179 return FALSE;
1181 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
1182 if (!ref->method)
1183 return FALSE;
1185 memset (&ctx, 0, sizeof (ctx));
1187 if (FALSE && klass->generic_class) {
1188 ctx.class_inst = klass->generic_class->context.class_inst;
1189 ctx.method_inst = NULL;
1191 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1194 memset (&ctx, 0, sizeof (ctx));
1196 if (!decode_generic_context (module, &ctx, p, &p))
1197 return FALSE;
1199 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1200 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1201 MonoClass *klass;
1202 int method_type;
1204 klass = decode_klass_ref (module, p, &p);
1205 if (!klass)
1206 return FALSE;
1207 method_type = decode_value (p, &p);
1208 switch (method_type) {
1209 case 0:
1210 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
1211 break;
1212 case 1:
1213 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
1214 break;
1215 case 2:
1216 ref->method = mono_class_get_method_from_name (klass, "Get", -1);
1217 break;
1218 case 3:
1219 ref->method = mono_class_get_method_from_name (klass, "Address", -1);
1220 break;
1221 case 4:
1222 ref->method = mono_class_get_method_from_name (klass, "Set", -1);
1223 break;
1224 default:
1225 g_assert_not_reached ();
1227 } else {
1228 if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
1229 image_index = decode_value (p, &p);
1230 value = decode_value (p, &p);
1233 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1235 image = load_image (module, image_index, TRUE);
1236 if (!image)
1237 return FALSE;
1240 *endbuf = p;
1242 ref->image = image;
1244 return TRUE;
1247 static gboolean
1248 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
1250 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
1254 * decode_resolve_method_ref_with_target:
1256 * Similar to decode_method_ref, but resolve and return the method itself.
1258 static MonoMethod*
1259 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
1261 MethodRef ref;
1262 gboolean res;
1264 res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
1265 if (!res)
1266 return NULL;
1267 if (ref.method)
1268 return ref.method;
1269 if (!ref.image)
1270 return NULL;
1271 return mono_get_method (ref.image, ref.token, NULL);
1274 static MonoMethod*
1275 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
1277 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
1280 #ifdef ENABLE_AOT_CACHE
1282 /* AOT CACHE */
1285 * FIXME:
1286 * - Add options for controlling the cache size
1287 * - Handle full cache by deleting old assemblies lru style
1288 * - Maybe add a threshold after an assembly is AOT compiled
1289 * - Add options for enabling this for specific main assemblies
1292 /* The cache directory */
1293 static char *cache_dir;
1295 /* The number of assemblies AOTed in this run */
1296 static int cache_count;
1298 /* Whenever to AOT in-process */
1299 static gboolean in_process;
1301 static void
1302 collect_assemblies (gpointer data, gpointer user_data)
1304 MonoAssembly *ass = data;
1305 GSList **l = user_data;
1307 *l = g_slist_prepend (*l, ass);
1310 #define SHA1_DIGEST_LENGTH 20
1313 * get_aot_config_hash:
1315 * Return a hash for all the version information an AOT module depends on.
1317 static G_GNUC_UNUSED char*
1318 get_aot_config_hash (MonoAssembly *assembly)
1320 char *build_info;
1321 GSList *l, *assembly_list = NULL;
1322 GString *s;
1323 int i;
1324 guint8 digest [SHA1_DIGEST_LENGTH];
1325 char *digest_str;
1327 build_info = mono_get_runtime_build_info ();
1329 s = g_string_new (build_info);
1331 mono_assembly_foreach (collect_assemblies, &assembly_list);
1334 * The assembly list includes the current assembly as well, no need
1335 * to add it.
1337 for (l = assembly_list; l; l = l->next) {
1338 MonoAssembly *ass = l->data;
1340 g_string_append (s, "_");
1341 g_string_append (s, ass->aname.name);
1342 g_string_append (s, "_");
1343 g_string_append (s, ass->image->guid);
1346 for (i = 0; i < s->len; ++i) {
1347 if (!isalnum (s->str [i]) && s->str [i] != '-')
1348 s->str [i] = '_';
1351 mono_sha1_get_digest ((guint8*)s->str, s->len, digest);
1353 digest_str = g_malloc0 ((SHA1_DIGEST_LENGTH * 2) + 1);
1354 for (i = 0; i < SHA1_DIGEST_LENGTH; ++i)
1355 sprintf (digest_str + (i * 2), "%02x", digest [i]);
1357 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: file dependencies: %s, hash %s", s->str, digest_str);
1359 g_string_free (s, TRUE);
1361 return digest_str;
1364 static void
1365 aot_cache_init (void)
1367 if (mono_aot_only)
1368 return;
1369 enable_aot_cache = TRUE;
1370 in_process = TRUE;
1374 * aot_cache_load_module:
1376 * Load the AOT image corresponding to ASSEMBLY from the aot cache, AOTing it if neccessary.
1378 static MonoDl*
1379 aot_cache_load_module (MonoAssembly *assembly, char **aot_name)
1381 MonoAotCacheConfig *config;
1382 GSList *l;
1383 char *fname, *tmp2, *aot_options, *failure_fname;
1384 const char *home;
1385 MonoDl *module;
1386 gboolean res;
1387 gint exit_status;
1388 char *hash;
1389 int pid;
1390 gboolean enabled;
1391 FILE *failure_file;
1393 *aot_name = NULL;
1395 if (image_is_dynamic (assembly->image))
1396 return NULL;
1398 /* Check in the list of assemblies enabled for aot caching */
1399 config = mono_get_aot_cache_config ();
1401 enabled = FALSE;
1402 if (config->apps) {
1403 MonoDomain *domain = mono_domain_get ();
1404 MonoAssembly *entry_assembly = domain->entry_assembly;
1406 // FIXME: This cannot be used for mscorlib during startup, since entry_assembly is not set yet
1407 for (l = config->apps; l; l = l->next) {
1408 char *n = l->data;
1410 if ((entry_assembly && !strcmp (entry_assembly->aname.name, n)) || (!entry_assembly && !strcmp (assembly->aname.name, n)))
1411 break;
1413 if (l)
1414 enabled = TRUE;
1417 if (!enabled) {
1418 for (l = config->assemblies; l; l = l->next) {
1419 char *n = l->data;
1421 if (!strcmp (assembly->aname.name, n))
1422 break;
1424 if (l)
1425 enabled = TRUE;
1427 if (!enabled)
1428 return NULL;
1430 if (!cache_dir) {
1431 home = g_get_home_dir ();
1432 if (!home)
1433 return NULL;
1434 cache_dir = g_strdup_printf ("%s/Library/Caches/mono/aot-cache", home);
1435 if (!g_file_test (cache_dir, G_FILE_TEST_EXISTS|G_FILE_TEST_IS_DIR))
1436 g_mkdir_with_parents (cache_dir, 0777);
1440 * The same assembly can be used in multiple configurations, i.e. multiple
1441 * versions of the runtime, with multiple versions of dependent assemblies etc.
1442 * To handle this, we compute a version string containing all this information, hash it,
1443 * and use the hash as a filename suffix.
1445 hash = get_aot_config_hash (assembly);
1447 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, hash, SHARED_EXT);
1448 fname = g_build_filename (cache_dir, tmp2, NULL);
1449 *aot_name = fname;
1450 g_free (tmp2);
1452 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: loading from cache: '%s'.", fname);
1453 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1455 if (module)
1456 return module;
1458 if (!strcmp (assembly->aname.name, "mscorlib") && !mscorlib_aot_loaded)
1460 * Can't AOT this during startup, so we AOT it when called later from
1461 * mono_aot_get_method ().
1463 return NULL;
1465 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: not found.");
1467 /* Only AOT one assembly per run to avoid slowing down execution too much */
1468 if (cache_count > 0)
1469 return NULL;
1470 cache_count ++;
1472 /* Check for previous failure */
1473 failure_fname = g_strdup_printf ("%s.failure", fname);
1474 failure_file = fopen (failure_fname, "r");
1475 if (failure_file) {
1476 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: assembly '%s' previously failed to compile '%s' ('%s')... ", assembly->image->name, fname, failure_fname);
1477 g_free (failure_fname);
1478 return NULL;
1479 } else {
1480 g_free (failure_fname);
1481 fclose (failure_file);
1484 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: compiling assembly '%s'... ", assembly->image->name);
1487 * We need to invoke the AOT compiler here. There are multiple approaches:
1488 * - spawn a new runtime process. This can be hard when running with mkbundle, and
1489 * its hard to make the new process load the same set of assemblies.
1490 * - doing it in-process. This exposes the current process to bugs/leaks/side effects of
1491 * the AOT compiler.
1492 * - fork a new process and do the work there.
1494 if (in_process) {
1495 aot_options = g_strdup_printf ("outfile=%s,internal-logfile=%s.log", fname, fname);
1496 /* Maybe due this in another thread ? */
1497 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1498 if (!res) {
1499 failure_fname = g_strdup_printf ("%s.failure", fname);
1500 failure_file = fopen (failure_fname, "a+");
1501 fclose (failure_file);
1502 g_free (failure_fname);
1504 } else {
1506 * - Avoid waiting for the aot process to finish ?
1507 * (less overhead, but multiple processes could aot the same assembly at the same time)
1509 pid = fork ();
1510 if (pid == 0) {
1511 FILE *logfile;
1512 char *logfile_name;
1514 /* Child */
1516 logfile_name = g_strdup_printf ("%s/aot.log", cache_dir);
1517 logfile = fopen (logfile_name, "a+");
1518 g_free (logfile_name);
1520 dup2 (fileno (logfile), 1);
1521 dup2 (fileno (logfile), 2);
1523 aot_options = g_strdup_printf ("outfile=%s", fname);
1524 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1525 if (!res) {
1526 exit (1);
1527 } else {
1528 exit (0);
1530 } else {
1531 /* Parent */
1532 waitpid (pid, &exit_status, 0);
1533 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1534 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: failed.");
1535 else
1536 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT: succeeded.");
1540 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1542 return module;
1545 #else
1547 static void
1548 aot_cache_init (void)
1552 static MonoDl*
1553 aot_cache_load_module (MonoAssembly *assembly, char **aot_name)
1555 return NULL;
1558 #endif
1560 static void
1561 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1563 if (globals) {
1564 int global_index;
1565 guint16 *table, *entry;
1566 guint16 table_size;
1567 guint32 hash;
1568 char *symbol = (char*)name;
1570 #ifdef TARGET_MACH
1571 symbol = g_strdup_printf ("_%s", name);
1572 #endif
1574 /* The first entry points to the hash */
1575 table = globals [0];
1576 globals ++;
1578 table_size = table [0];
1579 table ++;
1581 hash = mono_metadata_str_hash (symbol) % table_size;
1583 entry = &table [hash * 2];
1585 /* Search the hash for the index into the globals table */
1586 global_index = -1;
1587 while (entry [0] != 0) {
1588 guint32 index = entry [0] - 1;
1589 guint32 next = entry [1];
1591 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1593 if (!strcmp (globals [index * 2], symbol)) {
1594 global_index = index;
1595 break;
1598 if (next != 0) {
1599 entry = &table [next * 2];
1600 } else {
1601 break;
1605 if (global_index != -1)
1606 *value = globals [global_index * 2 + 1];
1607 else
1608 *value = NULL;
1610 if (symbol != name)
1611 g_free (symbol);
1612 } else {
1613 char *err = mono_dl_symbol (module, name, value);
1615 if (err)
1616 g_free (err);
1620 static gboolean
1621 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
1623 char *build_info;
1624 char *msg = NULL;
1625 gboolean usable = TRUE;
1626 gboolean full_aot;
1627 guint8 *blob;
1628 guint32 excluded_cpu_optimizations;
1630 if (strcmp (assembly->image->guid, info->assembly_guid)) {
1631 msg = g_strdup_printf ("doesn't match assembly");
1632 usable = FALSE;
1635 build_info = mono_get_runtime_build_info ();
1636 if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1637 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1638 usable = FALSE;
1640 g_free (build_info);
1642 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1644 if (mono_aot_only && !full_aot) {
1645 msg = g_strdup_printf ("not compiled with --aot=full");
1646 usable = FALSE;
1648 if (!mono_aot_only && full_aot) {
1649 msg = g_strdup_printf ("compiled with --aot=full");
1650 usable = FALSE;
1652 #ifdef TARGET_ARM
1653 /* mono_arch_find_imt_method () requires this */
1654 if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1655 msg = g_strdup_printf ("compiled against LLVM");
1656 usable = FALSE;
1658 if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1659 msg = g_strdup_printf ("not compiled against LLVM");
1660 usable = FALSE;
1662 #endif
1663 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1664 msg = g_strdup_printf ("not compiled for debugging");
1665 usable = FALSE;
1668 mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
1669 if (info->opts & excluded_cpu_optimizations) {
1670 msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
1671 usable = FALSE;
1674 if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
1675 msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
1676 usable = FALSE;
1679 blob = info->blob;
1681 if (info->gc_name_index != -1) {
1682 char *gc_name = (char*)&blob [info->gc_name_index];
1683 const char *current_gc_name = mono_gc_get_gc_name ();
1685 if (strcmp (current_gc_name, gc_name) != 0) {
1686 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1687 usable = FALSE;
1691 *out_msg = msg;
1692 return usable;
1695 /* This returns an interop address */
1696 static void*
1697 get_arm_bl_target (guint32 *ins_addr)
1699 #ifdef TARGET_ARM
1700 guint32 ins = *ins_addr;
1701 gint32 offset;
1703 if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
1704 /* blx */
1705 offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
1706 return (char*)ins_addr + (offset * 2) + 8 + 1;
1707 } else {
1708 offset = (((int)ins & 0xffffff) << 8) >> 8;
1709 return (char*)ins_addr + (offset * 4) + 8;
1711 #elif defined(TARGET_ARM64)
1712 return mono_arch_get_call_target (((guint8*)ins_addr) + 4);
1713 #else
1714 g_assert_not_reached ();
1715 return NULL;
1716 #endif
1719 static void
1720 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1722 char *aot_name;
1723 MonoAotModule *amodule;
1724 MonoDl *sofile;
1725 gboolean usable = TRUE;
1726 char *version_symbol = NULL;
1727 char *msg = NULL;
1728 gpointer *globals = NULL;
1729 MonoAotFileInfo *info = NULL;
1730 int i, version;
1731 guint8 *blob;
1732 gboolean do_load_image = TRUE;
1733 int align_double, align_int64;
1735 if (mono_compile_aot)
1736 return;
1738 if (assembly->image->aot_module)
1740 * Already loaded. This can happen because the assembly loading code might invoke
1741 * the assembly load hooks multiple times for the same assembly.
1743 return;
1745 if (image_is_dynamic (assembly->image) || assembly->ref_only)
1746 return;
1748 if (mono_security_cas_enabled ())
1749 return;
1751 mono_aot_lock ();
1752 if (static_aot_modules)
1753 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1754 else
1755 info = NULL;
1756 mono_aot_unlock ();
1758 sofile = NULL;
1760 if (info) {
1761 /* Statically linked AOT module */
1762 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1763 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1764 globals = info->globals;
1765 } else {
1766 if (enable_aot_cache)
1767 sofile = aot_cache_load_module (assembly, &aot_name);
1768 if (!sofile) {
1769 char *err;
1770 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1772 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1774 if (!sofile) {
1775 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module '%s' not found: %s\n", aot_name, err);
1776 g_free (err);
1781 if (!sofile && !globals) {
1782 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1783 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1784 exit (1);
1786 g_free (aot_name);
1787 return;
1790 if (!info) {
1791 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1792 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1795 if (version_symbol) {
1796 /* Old file format */
1797 version = atoi (version_symbol);
1798 } else {
1799 g_assert (info);
1800 version = info->version;
1803 if (version != MONO_AOT_FILE_VERSION) {
1804 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1805 usable = FALSE;
1806 } else {
1807 usable = check_usable (assembly, info, &msg);
1810 if (!usable) {
1811 if (mono_aot_only) {
1812 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1813 exit (1);
1814 } else {
1815 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable: %s.\n", aot_name, msg);
1817 g_free (msg);
1818 g_free (aot_name);
1819 if (sofile)
1820 mono_dl_close (sofile);
1821 assembly->image->aot_module = NULL;
1822 return;
1825 #if defined (TARGET_ARM) && defined (TARGET_MACH)
1827 MonoType t;
1828 int align = 0;
1830 memset (&t, 0, sizeof (MonoType));
1831 t.type = MONO_TYPE_R8;
1832 mono_type_size (&t, &align);
1833 align_double = align;
1835 memset (&t, 0, sizeof (MonoType));
1836 t.type = MONO_TYPE_I8;
1837 align_int64 = align;
1839 #else
1840 align_double = MONO_ABI_ALIGNOF (double);
1841 align_int64 = MONO_ABI_ALIGNOF (gint64);
1842 #endif
1844 /* Sanity check */
1845 g_assert (info->double_align == align_double);
1846 g_assert (info->long_align == align_int64);
1847 g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
1849 blob = info->blob;
1851 amodule = g_new0 (MonoAotModule, 1);
1852 amodule->aot_name = aot_name;
1853 amodule->assembly = assembly;
1855 memcpy (&amodule->info, info, sizeof (*info));
1857 amodule->got = amodule->info.got;
1858 amodule->got [0] = assembly->image;
1859 amodule->globals = globals;
1860 amodule->sofile = sofile;
1861 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1862 amodule->blob = blob;
1864 mono_mutex_init_recursive (&amodule->mutex);
1866 /* Read image table */
1868 guint32 table_len, i;
1869 char *table = NULL;
1871 table = info->image_table;
1872 g_assert (table);
1874 table_len = *(guint32*)table;
1875 table += sizeof (guint32);
1876 amodule->image_table = g_new0 (MonoImage*, table_len);
1877 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1878 amodule->image_guids = g_new0 (char*, table_len);
1879 amodule->image_table_len = table_len;
1880 for (i = 0; i < table_len; ++i) {
1881 MonoAssemblyName *aname = &(amodule->image_names [i]);
1883 aname->name = g_strdup (table);
1884 table += strlen (table) + 1;
1885 amodule->image_guids [i] = g_strdup (table);
1886 table += strlen (table) + 1;
1887 if (table [0] != 0)
1888 aname->culture = g_strdup (table);
1889 table += strlen (table) + 1;
1890 memcpy (aname->public_key_token, table, strlen (table) + 1);
1891 table += strlen (table) + 1;
1893 table = ALIGN_PTR_TO (table, 8);
1894 aname->flags = *(guint32*)table;
1895 table += 4;
1896 aname->major = *(guint32*)table;
1897 table += 4;
1898 aname->minor = *(guint32*)table;
1899 table += 4;
1900 aname->build = *(guint32*)table;
1901 table += 4;
1902 aname->revision = *(guint32*)table;
1903 table += 4;
1907 amodule->code_offsets = info->code_offsets;
1908 amodule->method_addresses = info->method_addresses;
1909 amodule->code = info->methods;
1910 #ifdef TARGET_ARM
1911 /* Mask out thumb interop bit */
1912 amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1913 #endif
1914 amodule->code_end = info->methods_end;
1915 amodule->method_info_offsets = info->method_info_offsets;
1916 amodule->ex_info_offsets = info->ex_info_offsets;
1917 amodule->class_info_offsets = info->class_info_offsets;
1918 amodule->class_name_table = info->class_name_table;
1919 amodule->extra_method_table = info->extra_method_table;
1920 amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1921 amodule->unbox_trampolines = info->unbox_trampolines;
1922 amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1923 amodule->got_info_offsets = info->got_info_offsets;
1924 amodule->unwind_info = info->unwind_info;
1925 amodule->mem_end = info->mem_end;
1926 amodule->mem_begin = amodule->code;
1927 amodule->plt = info->plt;
1928 amodule->plt_end = info->plt_end;
1929 amodule->mono_eh_frame = info->mono_eh_frame;
1930 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1931 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1932 amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1933 amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = info->gsharedvt_arg_trampolines;
1934 amodule->thumb_end = info->thumb_end;
1936 if (info->flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) {
1937 /* Compute code_offsets from the method addresses */
1938 amodule->code_offsets = g_malloc0 (amodule->info.nmethods * sizeof (gint32));
1939 for (i = 0; i < amodule->info.nmethods; ++i) {
1940 /* method_addresses () contains a table of branches, since the ios linker can update those correctly */
1941 void *addr = NULL;
1943 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
1944 addr = get_arm_bl_target ((guint32*)amodule->method_addresses + i);
1945 #elif defined(TARGET_X86) || defined(TARGET_AMD64)
1946 addr = mono_arch_get_call_target ((guint8*)amodule->method_addresses + (i * 5) + 5);
1947 #else
1948 g_assert_not_reached ();
1949 #endif
1950 g_assert (addr);
1951 if (addr == amodule->method_addresses)
1952 amodule->code_offsets [i] = 0xffffffff;
1953 else
1954 amodule->code_offsets [i] = (char*)addr - (char*)amodule->code;
1958 if (make_unreadable) {
1959 #ifndef TARGET_WIN32
1960 guint8 *addr;
1961 guint8 *page_start, *page_end;
1962 int err, len;
1964 addr = amodule->mem_begin;
1965 len = amodule->mem_end - amodule->mem_begin;
1967 /* Round down in both directions to avoid modifying data which is not ours */
1968 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1969 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1970 if (page_end > page_start) {
1971 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1972 g_assert (err == 0);
1974 #endif
1977 mono_aot_lock ();
1979 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1980 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1982 g_hash_table_insert (aot_modules, assembly, amodule);
1983 mono_aot_unlock ();
1985 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1987 assembly->image->aot_module = amodule;
1989 if (mono_aot_only) {
1990 char *code;
1991 find_symbol (amodule->sofile, amodule->globals, "specific_trampolines_page", (gpointer *)&code);
1992 amodule->use_page_trampolines = code != NULL;
1993 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
1994 if (mono_defaults.corlib) {
1995 /* The second got slot contains the mscorlib got addr */
1996 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1998 amodule->got [1] = mscorlib_amodule->got;
1999 } else {
2000 amodule->got [1] = amodule->got;
2004 if (mono_gc_is_moving ()) {
2005 MonoJumpInfo ji;
2007 memset (&ji, 0, sizeof (ji));
2008 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
2010 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
2014 * Since we store methoddef and classdef tokens when referring to methods/classes in
2015 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
2016 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
2017 * non-lazily, since we can't handle out-of-date errors later.
2018 * The cached class info also depends on the exact assemblies.
2020 #if defined(__native_client__)
2021 /* TODO: Don't 'load_image' on mscorlib due to a */
2022 /* recursive loading problem. This should be */
2023 /* removed if mscorlib is loaded from disk. */
2024 if (strncmp(assembly->aname.name, "mscorlib", 8)) {
2025 do_load_image = TRUE;
2026 } else {
2027 do_load_image = FALSE;
2029 #endif
2030 if (do_load_image) {
2031 for (i = 0; i < amodule->image_table_len; ++i)
2032 load_image (amodule, i, FALSE);
2035 if (amodule->out_of_date) {
2036 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: Module %s is unusable because a dependency is out-of-date.\n", assembly->image->name);
2037 if (mono_aot_only) {
2038 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode because a dependency cannot be found or it is out of date.\n", aot_name);
2039 exit (1);
2042 else
2043 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: loaded AOT Module for %s.\n", assembly->image->name);
2047 * mono_aot_register_globals:
2049 * This is called by the ctor function in AOT images compiled with the
2050 * 'no-dlsym' option.
2052 void
2053 mono_aot_register_globals (gpointer *globals)
2055 g_assert_not_reached ();
2059 * mono_aot_register_module:
2061 * This should be called by embedding code to register AOT modules statically linked
2062 * into the executable. AOT_INFO should be the value of the
2063 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
2065 void
2066 mono_aot_register_module (gpointer *aot_info)
2068 gpointer *globals;
2069 char *aname;
2070 MonoAotFileInfo *info = (gpointer)aot_info;
2072 g_assert (info->version == MONO_AOT_FILE_VERSION);
2074 globals = info->globals;
2075 g_assert (globals);
2077 aname = info->assembly_name;
2079 /* This could be called before startup */
2080 if (aot_modules)
2081 mono_aot_lock ();
2083 if (!static_aot_modules)
2084 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
2086 g_hash_table_insert (static_aot_modules, aname, info);
2088 if (aot_modules)
2089 mono_aot_unlock ();
2092 void
2093 mono_aot_init (void)
2095 mono_mutex_init_recursive (&aot_mutex);
2096 mono_mutex_init_recursive (&aot_page_mutex);
2097 aot_modules = g_hash_table_new (NULL, NULL);
2099 #ifndef __native_client__
2100 mono_install_assembly_load_hook (load_aot_module, NULL);
2101 #endif
2102 mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
2104 if (g_getenv ("MONO_LASTAOT"))
2105 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
2106 aot_cache_init ();
2109 void
2110 mono_aot_cleanup (void)
2112 if (aot_jit_icall_hash)
2113 g_hash_table_destroy (aot_jit_icall_hash);
2114 if (aot_modules)
2115 g_hash_table_destroy (aot_modules);
2118 static gboolean
2119 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
2121 guint32 flags;
2122 MethodRef ref;
2123 gboolean res;
2125 info->vtable_size = decode_value (buf, &buf);
2126 if (info->vtable_size == -1)
2127 /* Generic type */
2128 return FALSE;
2129 flags = decode_value (buf, &buf);
2130 info->ghcimpl = (flags >> 0) & 0x1;
2131 info->has_finalize = (flags >> 1) & 0x1;
2132 info->has_cctor = (flags >> 2) & 0x1;
2133 info->has_nested_classes = (flags >> 3) & 0x1;
2134 info->blittable = (flags >> 4) & 0x1;
2135 info->has_references = (flags >> 5) & 0x1;
2136 info->has_static_refs = (flags >> 6) & 0x1;
2137 info->no_special_static_fields = (flags >> 7) & 0x1;
2138 info->is_generic_container = (flags >> 8) & 0x1;
2140 if (info->has_cctor) {
2141 res = decode_method_ref (module, &ref, buf, &buf);
2142 if (!res)
2143 return FALSE;
2144 info->cctor_token = ref.token;
2146 if (info->has_finalize) {
2147 res = decode_method_ref (module, &ref, buf, &buf);
2148 if (!res)
2149 return FALSE;
2150 info->finalize_image = ref.image;
2151 info->finalize_token = ref.token;
2154 info->instance_size = decode_value (buf, &buf);
2155 info->class_size = decode_value (buf, &buf);
2156 info->packing_size = decode_value (buf, &buf);
2157 info->min_align = decode_value (buf, &buf);
2159 *endbuf = buf;
2161 return TRUE;
2164 gpointer
2165 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
2167 int i;
2168 MonoClass *klass = vtable->klass;
2169 MonoAotModule *amodule = klass->image->aot_module;
2170 guint8 *info, *p;
2171 MonoCachedClassInfo class_info;
2172 gboolean err;
2173 MethodRef ref;
2174 gboolean res;
2176 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
2177 return NULL;
2179 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
2180 p = info;
2182 err = decode_cached_class_info (amodule, &class_info, p, &p);
2183 if (!err)
2184 return NULL;
2186 for (i = 0; i < slot; ++i)
2187 decode_method_ref (amodule, &ref, p, &p);
2189 res = decode_method_ref (amodule, &ref, p, &p);
2190 if (!res)
2191 return NULL;
2192 if (ref.no_aot_trampoline)
2193 return NULL;
2195 if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
2196 return NULL;
2198 return mono_aot_get_method_from_token (domain, ref.image, ref.token);
2201 gboolean
2202 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2204 MonoAotModule *amodule = klass->image->aot_module;
2205 guint8 *p;
2206 gboolean err;
2208 if (klass->rank || !amodule)
2209 return FALSE;
2211 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
2213 err = decode_cached_class_info (amodule, res, p, &p);
2214 if (!err)
2215 return FALSE;
2217 return TRUE;
2221 * mono_aot_get_class_from_name:
2223 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
2224 * using a cache stored in the AOT file.
2225 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
2227 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
2228 * found.
2230 gboolean
2231 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2233 MonoAotModule *amodule = image->aot_module;
2234 guint16 *table, *entry;
2235 guint16 table_size;
2236 guint32 hash;
2237 char full_name_buf [1024];
2238 char *full_name;
2239 const char *name2, *name_space2;
2240 MonoTableInfo *t;
2241 guint32 cols [MONO_TYPEDEF_SIZE];
2242 GHashTable *nspace_table;
2244 if (!amodule || !amodule->class_name_table)
2245 return FALSE;
2247 amodule_lock (amodule);
2249 *klass = NULL;
2251 /* First look in the cache */
2252 if (!amodule->name_cache)
2253 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
2254 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2255 if (nspace_table) {
2256 *klass = g_hash_table_lookup (nspace_table, name);
2257 if (*klass) {
2258 amodule_unlock (amodule);
2259 return TRUE;
2263 table_size = amodule->class_name_table [0];
2264 table = amodule->class_name_table + 1;
2266 if (name_space [0] == '\0')
2267 full_name = g_strdup_printf ("%s", name);
2268 else {
2269 if (strlen (name_space) + strlen (name) < 1000) {
2270 sprintf (full_name_buf, "%s.%s", name_space, name);
2271 full_name = full_name_buf;
2272 } else {
2273 full_name = g_strdup_printf ("%s.%s", name_space, name);
2276 hash = mono_metadata_str_hash (full_name) % table_size;
2277 if (full_name != full_name_buf)
2278 g_free (full_name);
2280 entry = &table [hash * 2];
2282 if (entry [0] != 0) {
2283 t = &image->tables [MONO_TABLE_TYPEDEF];
2285 while (TRUE) {
2286 guint32 index = entry [0];
2287 guint32 next = entry [1];
2288 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2290 name_table_accesses ++;
2292 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2294 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2295 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2297 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2298 MonoError error;
2299 amodule_unlock (amodule);
2300 *klass = mono_class_get_checked (image, token, &error);
2301 if (!mono_error_ok (&error))
2302 mono_error_cleanup (&error); /* FIXME don't swallow the error */
2304 /* Add to cache */
2305 if (*klass) {
2306 amodule_lock (amodule);
2307 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2308 if (!nspace_table) {
2309 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2310 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2312 g_hash_table_insert (nspace_table, (char*)name2, *klass);
2313 amodule_unlock (amodule);
2315 return TRUE;
2318 if (next != 0) {
2319 entry = &table [next * 2];
2320 } else {
2321 break;
2326 amodule_unlock (amodule);
2328 return TRUE;
2332 * decode_mono_eh_frame:
2334 * Decode the EH information emitted by our modified LLVM compiler and construct a
2335 * MonoJitInfo structure from it.
2336 * LOCKING: Acquires the domain lock.
2338 static MonoJitInfo*
2339 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
2340 MonoMethod *method, guint8 *code,
2341 MonoJitExceptionInfo *clauses, int num_clauses,
2342 int extra_size, GSList **nesting,
2343 int *this_reg, int *this_offset)
2345 guint8 *p;
2346 guint8 *fde, *cie, *code_start, *code_end;
2347 int version, fde_count;
2348 gint32 *table;
2349 int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
2350 MonoJitExceptionInfo *ei;
2351 guint32 fde_len, ei_len, nested_len, nindex;
2352 gpointer *type_info;
2353 MonoJitInfo *jinfo;
2354 MonoLLVMFDEInfo info;
2356 g_assert (amodule->mono_eh_frame);
2358 p = amodule->mono_eh_frame;
2360 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2362 /* Header */
2363 version = *p;
2364 g_assert (version == 3);
2365 p ++;
2366 func_encoding = *p;
2367 p ++;
2368 p = ALIGN_PTR_TO (p, 4);
2370 fde_count = *(guint32*)p;
2371 p += 4;
2372 table = (gint32*)p;
2374 /* There is +1 entry in the table */
2375 cie = p + ((fde_count + 1) * 8);
2377 /* Binary search in the table to find the entry for code */
2378 offset = code - amodule->code;
2379 left = 0;
2380 right = fde_count;
2381 while (TRUE) {
2382 pos = (left + right) / 2;
2384 /* The table contains method index/fde offset pairs */
2385 g_assert (table [(pos * 2)] != -1);
2386 offset1 = amodule->code_offsets [table [(pos * 2)]];
2387 if (pos + 1 == fde_count) {
2388 offset2 = amodule->code_end - amodule->code;
2389 } else {
2390 g_assert (table [(pos + 1) * 2] != -1);
2391 offset2 = amodule->code_offsets [table [(pos + 1) * 2]];
2394 if (offset < offset1)
2395 right = pos;
2396 else if (offset >= offset2)
2397 left = pos + 1;
2398 else
2399 break;
2402 code_start = amodule->code + amodule->code_offsets [table [(pos * 2)]];
2403 if (pos + 1 == fde_count) {
2404 /* The +1 entry in the table contains the length of the last method */
2405 int len = table [(pos + 1) * 2];
2406 code_end = code_start + len;
2407 } else {
2408 code_end = amodule->code + amodule->code_offsets [table [(pos + 1) * 2]];
2410 code_len = code_end - code_start;
2412 g_assert (code >= code_start && code < code_end);
2414 if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
2415 /* Clear thumb flag */
2416 code_start = (guint8*)(((mgreg_t)code_start) & ~1);
2418 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
2419 /* This won't overflow because there is +1 entry in the table */
2420 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2422 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
2423 ei = info.ex_info;
2424 ei_len = info.ex_info_len;
2425 type_info = info.type_info;
2426 *this_reg = info.this_reg;
2427 *this_offset = info.this_offset;
2429 /* Count number of nested clauses */
2430 nested_len = 0;
2431 for (i = 0; i < ei_len; ++i) {
2432 /* This might be unaligned */
2433 gint32 cindex1 = read32 (type_info [i]);
2434 GSList *l;
2436 for (l = nesting [cindex1]; l; l = l->next) {
2437 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2439 for (j = 0; j < ei_len; ++j) {
2440 gint32 cindex2 = read32 (type_info [j]);
2442 if (cindex2 == nesting_cindex)
2443 nested_len ++;
2449 * LLVM might represent one IL region with multiple regions, so have to
2450 * allocate a new JI.
2452 jinfo =
2453 mono_domain_alloc0_lock_free (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2455 jinfo->code_size = code_len;
2456 jinfo->unwind_info = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2457 jinfo->d.method = method;
2458 jinfo->code_start = code;
2459 jinfo->domain_neutral = 0;
2460 /* This signals that unwind_info points to a normal cached unwind info */
2461 jinfo->from_aot = 0;
2462 jinfo->num_clauses = ei_len + nested_len;
2464 for (i = 0; i < ei_len; ++i) {
2466 * orig_jinfo contains the original IL exception info saved by the AOT
2467 * compiler, we have to combine that with the information produced by LLVM
2469 /* The type_info entries contain IL clause indexes */
2470 int clause_index = read32 (type_info [i]);
2471 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2472 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2474 g_assert (clause_index < num_clauses);
2475 jei->flags = orig_jei->flags;
2476 jei->data.catch_class = orig_jei->data.catch_class;
2478 jei->try_start = ei [i].try_start;
2479 jei->try_end = ei [i].try_end;
2480 jei->handler_start = ei [i].handler_start;
2482 /* Make sure we transition to thumb when a handler starts */
2483 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2484 jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2487 /* See exception_cb () in mini-llvm.c as to why this is needed */
2488 nindex = ei_len;
2489 for (i = 0; i < ei_len; ++i) {
2490 gint32 cindex1 = read32 (type_info [i]);
2491 GSList *l;
2493 for (l = nesting [cindex1]; l; l = l->next) {
2494 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2496 for (j = 0; j < ei_len; ++j) {
2497 gint32 cindex2 = read32 (type_info [j]);
2499 if (cindex2 == nesting_cindex) {
2501 * The try interval comes from the nested clause, everything else from the
2502 * nesting clause.
2504 memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2505 jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2506 jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2507 nindex ++;
2512 g_assert (nindex == ei_len + nested_len);
2514 return jinfo;
2517 static gpointer
2518 alloc0_jit_info_data (MonoDomain *domain, int size, gboolean async_context)
2520 gpointer res;
2522 if (async_context) {
2523 res = mono_domain_alloc0_lock_free (domain, size);
2524 InterlockedExchangeAdd (&async_jit_info_size, size);
2525 } else {
2526 res = mono_domain_alloc0 (domain, size);
2528 return res;
2532 * LOCKING: Acquires the domain lock.
2533 * In async context, this is async safe.
2535 static MonoJitInfo*
2536 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
2537 MonoMethod *method, guint8* ex_info, guint8 *addr,
2538 guint8 *code, guint32 code_len)
2540 int i, buf_len, num_clauses, len;
2541 MonoJitInfo *jinfo;
2542 guint unwind_info, flags;
2543 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2544 gboolean from_llvm, has_gc_map;
2545 guint8 *p;
2546 int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2547 int this_reg = 0, this_offset = 0;
2548 gboolean async;
2550 /* Load the method info from the AOT file */
2551 async = mono_thread_info_is_async_context ();
2553 p = ex_info;
2554 flags = decode_value (p, &p);
2555 has_generic_jit_info = (flags & 1) != 0;
2556 has_dwarf_unwind_info = (flags & 2) != 0;
2557 has_clauses = (flags & 4) != 0;
2558 has_seq_points = (flags & 8) != 0;
2559 from_llvm = (flags & 16) != 0;
2560 has_try_block_holes = (flags & 32) != 0;
2561 has_gc_map = (flags & 64) != 0;
2562 has_arch_eh_jit_info = (flags & 128) != 0;
2564 if (has_dwarf_unwind_info) {
2565 unwind_info = decode_value (p, &p);
2566 g_assert (unwind_info < (1 << 30));
2567 } else {
2568 unwind_info = decode_value (p, &p);
2570 if (has_generic_jit_info)
2571 generic_info_size = sizeof (MonoGenericJitInfo);
2572 else
2573 generic_info_size = 0;
2575 if (has_try_block_holes) {
2576 num_holes = decode_value (p, &p);
2577 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2578 } else {
2579 num_holes = try_holes_info_size = 0;
2581 /* Exception table */
2582 if (has_clauses)
2583 num_clauses = decode_value (p, &p);
2584 else
2585 num_clauses = 0;
2586 if (has_arch_eh_jit_info)
2587 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2588 else
2589 arch_eh_jit_info_size = 0;
2591 if (from_llvm) {
2592 MonoJitExceptionInfo *clauses;
2593 GSList **nesting;
2595 // FIXME: async
2596 g_assert (!async);
2599 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2600 * section.
2602 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2603 nesting = g_new0 (GSList*, num_clauses);
2605 for (i = 0; i < num_clauses; ++i) {
2606 MonoJitExceptionInfo *ei = &clauses [i];
2608 ei->flags = decode_value (p, &p);
2610 if (decode_value (p, &p))
2611 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2613 /* Read the list of nesting clauses */
2614 while (TRUE) {
2615 int nesting_index = decode_value (p, &p);
2616 if (nesting_index == -1)
2617 break;
2618 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2622 jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size + arch_eh_jit_info_size, nesting, &this_reg, &this_offset);
2623 jinfo->from_llvm = 1;
2625 g_free (clauses);
2626 for (i = 0; i < num_clauses; ++i)
2627 g_slist_free (nesting [i]);
2628 g_free (nesting);
2629 } else {
2630 len = MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size;
2631 jinfo = alloc0_jit_info_data (domain, len, async);
2632 jinfo->num_clauses = num_clauses;
2634 for (i = 0; i < jinfo->num_clauses; ++i) {
2635 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2637 ei->flags = decode_value (p, &p);
2639 ei->exvar_offset = decode_value (p, &p);
2641 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2642 ei->data.filter = code + decode_value (p, &p);
2643 else {
2644 int len = decode_value (p, &p);
2646 if (len > 0) {
2647 if (async)
2648 p += len;
2649 else
2650 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2654 ei->try_start = code + decode_value (p, &p);
2655 ei->try_end = code + decode_value (p, &p);
2656 ei->handler_start = code + decode_value (p, &p);
2659 jinfo->code_size = code_len;
2660 jinfo->unwind_info = unwind_info;
2661 jinfo->d.method = method;
2662 jinfo->code_start = code;
2663 jinfo->domain_neutral = 0;
2664 jinfo->from_aot = 1;
2668 * Set all the 'has' flags, the mono_jit_info_get () functions depends on this to
2669 * compute the addresses of data blocks.
2671 if (has_generic_jit_info)
2672 jinfo->has_generic_jit_info = 1;
2673 if (has_arch_eh_jit_info)
2674 jinfo->has_arch_eh_info = 1;
2675 if (has_try_block_holes)
2676 jinfo->has_try_block_holes = 1;
2678 if (has_try_block_holes) {
2679 MonoTryBlockHoleTableJitInfo *table;
2681 g_assert (jinfo->has_try_block_holes);
2683 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2684 g_assert (table);
2686 table->num_holes = (guint16)num_holes;
2687 for (i = 0; i < num_holes; ++i) {
2688 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2689 hole->clause = decode_value (p, &p);
2690 hole->length = decode_value (p, &p);
2691 hole->offset = decode_value (p, &p);
2695 if (has_arch_eh_jit_info) {
2696 MonoArchEHJitInfo *eh_info;
2698 g_assert (jinfo->has_arch_eh_info);
2700 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2701 eh_info->stack_size = decode_value (p, &p);
2702 eh_info->epilog_size = decode_value (p, &p);
2705 if (async) {
2706 /* The rest is not needed in async mode */
2707 jinfo->async = TRUE;
2708 jinfo->d.aot_info = amodule;
2709 // FIXME: Cache
2710 return jinfo;
2713 if (has_generic_jit_info) {
2714 MonoGenericJitInfo *gi;
2715 int len;
2717 g_assert (jinfo->has_generic_jit_info);
2719 gi = mono_jit_info_get_generic_jit_info (jinfo);
2720 g_assert (gi);
2722 gi->nlocs = decode_value (p, &p);
2723 if (gi->nlocs) {
2724 gi->locations = alloc0_jit_info_data (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
2725 for (i = 0; i < gi->nlocs; ++i) {
2726 MonoDwarfLocListEntry *entry = &gi->locations [i];
2728 entry->is_reg = decode_value (p, &p);
2729 entry->reg = decode_value (p, &p);
2730 if (!entry->is_reg)
2731 entry->offset = decode_value (p, &p);
2732 if (i > 0)
2733 entry->from = decode_value (p, &p);
2734 entry->to = decode_value (p, &p);
2736 } else {
2737 if (from_llvm) {
2738 gi->has_this = this_reg != -1;
2739 gi->this_reg = this_reg;
2740 gi->this_offset = this_offset;
2741 } else {
2742 gi->has_this = decode_value (p, &p);
2743 gi->this_reg = decode_value (p, &p);
2744 gi->this_offset = decode_value (p, &p);
2748 len = decode_value (p, &p);
2749 if (async)
2750 p += len;
2751 else
2752 jinfo->d.method = decode_resolve_method_ref (amodule, p, &p);
2754 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2755 if (decode_value (p, &p)) {
2756 /* gsharedvt */
2757 int i, n;
2758 MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
2760 n = decode_value (p, &p);
2761 if (n) {
2762 gsctx->var_is_vt = alloc0_jit_info_data (domain, sizeof (gboolean) * n, async);
2763 for (i = 0; i < n; ++i)
2764 gsctx->var_is_vt [i] = decode_value (p, &p);
2766 n = decode_value (p, &p);
2767 if (n) {
2768 gsctx->mvar_is_vt = alloc0_jit_info_data (domain, sizeof (gboolean) * n, async);
2769 for (i = 0; i < n; ++i)
2770 gsctx->mvar_is_vt [i] = decode_value (p, &p);
2775 if (method && has_seq_points) {
2776 MonoSeqPointInfo *seq_points;
2777 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2779 int len = decode_value (p, &p);
2781 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2782 seq_points->len = len;
2783 last_il_offset = last_native_offset = 0;
2784 for (i = 0; i < len; ++i) {
2785 SeqPoint *sp = &seq_points->seq_points [i];
2786 il_offset = last_il_offset + decode_value (p, &p);
2787 native_offset = last_native_offset + decode_value (p, &p);
2789 sp->il_offset = il_offset;
2790 sp->native_offset = native_offset;
2792 sp->flags = decode_value (p, &p);
2793 sp->next_len = decode_value (p, &p);
2794 sp->next = g_new (int, sp->next_len);
2795 for (j = 0; j < sp->next_len; ++j)
2796 sp->next [j] = decode_value (p, &p);
2798 last_il_offset = il_offset;
2799 last_native_offset = native_offset;
2802 mono_domain_lock (domain);
2803 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2804 mono_domain_unlock (domain);
2807 /* Load debug info */
2808 buf_len = decode_value (p, &p);
2809 if (!async)
2810 mono_debug_add_aot_method (domain, method, code, p, buf_len);
2811 p += buf_len;
2813 if (has_gc_map) {
2814 int map_size = decode_value (p, &p);
2815 /* The GC map requires 4 bytes of alignment */
2816 while ((guint64)(gsize)p % 4)
2817 p ++;
2818 jinfo->gc_info = p;
2819 p += map_size;
2822 if (amodule != jinfo->d.method->klass->image->aot_module) {
2823 mono_aot_lock ();
2824 if (!ji_to_amodule)
2825 ji_to_amodule = g_hash_table_new (NULL, NULL);
2826 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2827 mono_aot_unlock ();
2830 return jinfo;
2834 * mono_aot_get_unwind_info:
2836 * Return a pointer to the DWARF unwind info belonging to JI.
2838 guint8*
2839 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2841 MonoAotModule *amodule;
2842 guint8 *p;
2843 guint8 *code = ji->code_start;
2845 if (ji->async)
2846 amodule = ji->d.aot_info;
2847 else
2848 amodule = jinfo_get_method (ji)->klass->image->aot_module;
2849 g_assert (amodule);
2850 g_assert (ji->from_aot);
2852 if (!(code >= amodule->code && code <= amodule->code_end)) {
2853 /* ji belongs to a different aot module than amodule */
2854 mono_aot_lock ();
2855 g_assert (ji_to_amodule);
2856 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2857 g_assert (amodule);
2858 g_assert (code >= amodule->code && code <= amodule->code_end);
2859 mono_aot_unlock ();
2862 p = amodule->unwind_info + ji->unwind_info;
2863 *unwind_info_len = decode_value (p, &p);
2864 return p;
2867 static G_GNUC_UNUSED int
2868 compare_ints (const void *a, const void *b)
2870 return *(gint32*)a - *(gint32*)b;
2873 static void
2874 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2876 int mid = (lo + hi) / 2;
2877 int i, t_lo, t_hi;
2879 if (lo >= hi)
2880 return;
2882 if (hi - lo < 32) {
2883 for (i = lo; i < hi; ++i)
2884 if (array [(i * 2)] > array [(i * 2) + 2])
2885 break;
2886 if (i == hi)
2887 /* Already sorted */
2888 return;
2891 msort_code_offsets_internal (array, lo, mid, scratch);
2892 msort_code_offsets_internal (array, mid + 1, hi, scratch);
2894 if (array [mid * 2] < array [(mid + 1) * 2])
2895 return;
2897 /* Merge */
2898 t_lo = lo;
2899 t_hi = mid + 1;
2900 for (i = lo; i <= hi; i ++) {
2901 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2902 scratch [(i * 2)] = array [t_lo * 2];
2903 scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2904 t_lo ++;
2905 } else {
2906 scratch [(i * 2)] = array [t_hi * 2];
2907 scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2908 t_hi ++;
2911 for (i = lo; i <= hi; ++i) {
2912 array [(i * 2)] = scratch [i * 2];
2913 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2917 static void
2918 msort_code_offsets (gint32 *array, int len)
2920 gint32 *scratch;
2922 scratch = g_new (gint32, len * 2);
2923 msort_code_offsets_internal (array, 0, len - 1, scratch);
2924 g_free (scratch);
2928 * mono_aot_find_jit_info:
2930 * In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
2931 * to the jit info tables.
2932 * FIXME: Large sizes in the lock free allocator
2934 MonoJitInfo *
2935 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2937 int pos, left, right, offset, offset1, offset2, code_len;
2938 int method_index, table_len;
2939 guint32 token;
2940 MonoAotModule *amodule = image->aot_module;
2941 MonoMethod *method = NULL;
2942 MonoJitInfo *jinfo;
2943 guint8 *code, *ex_info, *p;
2944 guint32 *table;
2945 int nmethods;
2946 gint32 *code_offsets;
2947 int offsets_len, i;
2948 gboolean async;
2950 if (!amodule)
2951 return NULL;
2953 nmethods = amodule->info.nmethods;
2955 if (domain != mono_get_root_domain ())
2956 /* FIXME: */
2957 return NULL;
2959 async = mono_thread_info_is_async_context ();
2961 offset = (guint8*)addr - amodule->code;
2963 /* Compute a sorted table mapping code offsets to method indexes. */
2964 if (!amodule->sorted_code_offsets) {
2965 // FIXME: async
2966 code_offsets = g_new0 (gint32, nmethods * 2);
2967 offsets_len = 0;
2968 for (i = 0; i < nmethods; ++i) {
2969 /* Skip the -1 entries to speed up sorting */
2970 if (amodule->code_offsets [i] == 0xffffffff)
2971 continue;
2972 code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2973 code_offsets [(offsets_len *2) + 1] = i;
2974 offsets_len ++;
2976 /* Use a merge sort as this is mostly sorted */
2977 msort_code_offsets (code_offsets, offsets_len);
2978 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2979 for (i = 0; i < offsets_len -1; ++i)
2980 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2982 amodule->sorted_code_offsets_len = offsets_len;
2983 mono_memory_barrier ();
2984 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2985 /* Somebody got in before us */
2986 g_free (code_offsets);
2989 code_offsets = amodule->sorted_code_offsets;
2990 offsets_len = amodule->sorted_code_offsets_len;
2992 if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
2993 return NULL;
2995 /* Binary search in the sorted_code_offsets table */
2996 left = 0;
2997 right = offsets_len;
2998 while (TRUE) {
2999 pos = (left + right) / 2;
3001 offset1 = code_offsets [(pos * 2)];
3002 if (pos + 1 == offsets_len)
3003 offset2 = amodule->code_end - amodule->code;
3004 else
3005 offset2 = code_offsets [(pos + 1) * 2];
3007 if (offset < offset1)
3008 right = pos;
3009 else if (offset >= offset2)
3010 left = pos + 1;
3011 else
3012 break;
3015 g_assert (offset >= code_offsets [(pos * 2)]);
3016 if (pos + 1 < offsets_len)
3017 g_assert (offset < code_offsets [((pos + 1) * 2)]);
3018 method_index = code_offsets [(pos * 2) + 1];
3020 /* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
3021 if (async) {
3022 JitInfoMap *table = amodule->async_jit_info_table;
3023 int len;
3025 if (table) {
3026 len = table [0].method_index;
3027 for (i = 1; i < len; ++i) {
3028 if (table [i].method_index == method_index)
3029 return table [i].jinfo;
3034 code = &amodule->code [amodule->code_offsets [method_index]];
3035 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
3037 if (pos == offsets_len - 1)
3038 code_len = amodule->code_end - code;
3039 else
3040 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
3042 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
3044 /* Might be a wrapper/extra method */
3045 if (!async) {
3046 if (amodule->extra_methods) {
3047 amodule_lock (amodule);
3048 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
3049 amodule_unlock (amodule);
3050 } else {
3051 method = NULL;
3054 if (!method) {
3055 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
3057 * This is hit for extra methods which are called directly, so they are
3058 * not in amodule->extra_methods.
3060 table_len = amodule->extra_method_info_offsets [0];
3061 table = amodule->extra_method_info_offsets + 1;
3062 left = 0;
3063 right = table_len;
3064 pos = 0;
3066 /* Binary search */
3067 while (TRUE) {
3068 pos = ((left + right) / 2);
3070 g_assert (pos < table_len);
3072 if (table [pos * 2] < method_index)
3073 left = pos + 1;
3074 else if (table [pos * 2] > method_index)
3075 right = pos;
3076 else
3077 break;
3080 p = amodule->blob + table [(pos * 2) + 1];
3081 method = decode_resolve_method_ref (amodule, p, &p);
3082 if (!method)
3083 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
3084 return NULL;
3085 } else {
3086 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
3087 method = mono_get_method (image, token, NULL);
3090 /* FIXME: */
3091 g_assert (method);
3094 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3096 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
3098 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
3099 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
3101 /* Add it to the normal JitInfo tables */
3102 if (async) {
3103 JitInfoMap *old_table, *new_table;
3104 int len;
3107 * Use a simple inmutable table with linear search to cache async jit info entries.
3108 * This assumes that the number of entries is small.
3110 while (TRUE) {
3111 /* Copy the table, adding a new entry at the end */
3112 old_table = amodule->async_jit_info_table;
3113 if (old_table)
3114 len = old_table[0].method_index;
3115 else
3116 len = 1;
3117 new_table = alloc0_jit_info_data (domain, (len + 1) * sizeof (JitInfoMap), async);
3118 if (old_table)
3119 memcpy (new_table, old_table, len * sizeof (JitInfoMap));
3120 new_table [0].method_index = len + 1;
3121 new_table [len].method_index = method_index;
3122 new_table [len].jinfo = jinfo;
3123 /* Publish it */
3124 mono_memory_barrier ();
3125 if (InterlockedCompareExchangePointer ((gpointer)&amodule->async_jit_info_table, new_table, old_table) == old_table)
3126 break;
3128 } else {
3129 mono_jit_info_table_add (domain, jinfo);
3132 return jinfo;
3135 static gboolean
3136 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
3138 guint8 *p = buf;
3139 gpointer *table;
3140 MonoImage *image;
3141 int i;
3143 switch (ji->type) {
3144 case MONO_PATCH_INFO_METHOD:
3145 case MONO_PATCH_INFO_METHOD_JUMP:
3146 case MONO_PATCH_INFO_ICALL_ADDR:
3147 case MONO_PATCH_INFO_METHOD_RGCTX:
3148 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
3149 MethodRef ref;
3150 gboolean res;
3152 res = decode_method_ref (aot_module, &ref, p, &p);
3153 if (!res)
3154 goto cleanup;
3156 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)) {
3157 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
3158 ji->type = MONO_PATCH_INFO_ABS;
3160 else {
3161 if (ref.method)
3162 ji->data.method = ref.method;
3163 else
3164 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
3165 g_assert (ji->data.method);
3166 mono_class_init (ji->data.method->klass);
3168 break;
3170 case MONO_PATCH_INFO_INTERNAL_METHOD:
3171 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3172 guint32 len = decode_value (p, &p);
3174 ji->data.name = (char*)p;
3175 p += len + 1;
3176 break;
3178 case MONO_PATCH_INFO_METHODCONST:
3179 /* Shared */
3180 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
3181 if (!ji->data.method)
3182 goto cleanup;
3183 break;
3184 case MONO_PATCH_INFO_VTABLE:
3185 case MONO_PATCH_INFO_CLASS:
3186 case MONO_PATCH_INFO_IID:
3187 case MONO_PATCH_INFO_ADJUSTED_IID:
3188 case MONO_PATCH_INFO_CLASS_INIT:
3189 /* Shared */
3190 ji->data.klass = decode_klass_ref (aot_module, p, &p);
3191 if (!ji->data.klass)
3192 goto cleanup;
3193 break;
3194 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3195 ji->data.del_tramp = mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
3196 ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p);
3197 if (!ji->data.del_tramp->klass)
3198 goto cleanup;
3199 if (decode_value (p, &p)) {
3200 ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
3201 if (!ji->data.del_tramp->method)
3202 goto cleanup;
3204 ji->data.del_tramp->virtual = decode_value (p, &p) ? TRUE : FALSE;
3205 break;
3206 case MONO_PATCH_INFO_IMAGE:
3207 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
3208 if (!ji->data.image)
3209 goto cleanup;
3210 break;
3211 case MONO_PATCH_INFO_FIELD:
3212 case MONO_PATCH_INFO_SFLDA:
3213 /* Shared */
3214 ji->data.field = decode_field_info (aot_module, p, &p);
3215 if (!ji->data.field)
3216 goto cleanup;
3217 break;
3218 case MONO_PATCH_INFO_SWITCH:
3219 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
3220 ji->data.table->table_size = decode_value (p, &p);
3221 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
3222 ji->data.table->table = (MonoBasicBlock**)table;
3223 for (i = 0; i < ji->data.table->table_size; i++)
3224 table [i] = (gpointer)(gssize)decode_value (p, &p);
3225 break;
3226 case MONO_PATCH_INFO_R4: {
3227 guint32 val;
3229 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
3230 val = decode_value (p, &p);
3231 *(float*)ji->data.target = *(float*)&val;
3232 break;
3234 case MONO_PATCH_INFO_R8: {
3235 guint32 val [2];
3236 guint64 v;
3238 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
3240 val [0] = decode_value (p, &p);
3241 val [1] = decode_value (p, &p);
3242 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
3243 *(double*)ji->data.target = *(double*)&v;
3244 break;
3246 case MONO_PATCH_INFO_LDSTR:
3247 image = load_image (aot_module, decode_value (p, &p), TRUE);
3248 if (!image)
3249 goto cleanup;
3250 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
3251 break;
3252 case MONO_PATCH_INFO_RVA:
3253 case MONO_PATCH_INFO_DECLSEC:
3254 case MONO_PATCH_INFO_LDTOKEN:
3255 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3256 /* Shared */
3257 image = load_image (aot_module, decode_value (p, &p), TRUE);
3258 if (!image)
3259 goto cleanup;
3260 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
3262 ji->data.token->has_context = decode_value (p, &p);
3263 if (ji->data.token->has_context) {
3264 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
3265 if (!res)
3266 goto cleanup;
3268 break;
3269 case MONO_PATCH_INFO_EXC_NAME:
3270 ji->data.klass = decode_klass_ref (aot_module, p, &p);
3271 if (!ji->data.klass)
3272 goto cleanup;
3273 ji->data.name = ji->data.klass->name;
3274 break;
3275 case MONO_PATCH_INFO_METHOD_REL:
3276 ji->data.offset = decode_value (p, &p);
3277 break;
3278 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3279 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3280 case MONO_PATCH_INFO_MONITOR_ENTER:
3281 case MONO_PATCH_INFO_MONITOR_EXIT:
3282 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3283 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3284 case MONO_PATCH_INFO_JIT_TLS_ID:
3285 break;
3286 case MONO_PATCH_INFO_RGCTX_FETCH: {
3287 gboolean res;
3288 MonoJumpInfoRgctxEntry *entry;
3289 guint32 offset, val;
3290 guint8 *p2;
3292 offset = decode_value (p, &p);
3293 val = decode_value (p, &p);
3295 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3296 p2 = aot_module->blob + offset;
3297 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
3298 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
3299 entry->info_type = (val >> 1) & 0xff;
3300 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3301 entry->data->type = (val >> 9) & 0xff;
3303 res = decode_patch (aot_module, mp, entry->data, p, &p);
3304 if (!res)
3305 goto cleanup;
3306 ji->data.rgctx_entry = entry;
3307 break;
3309 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3310 break;
3311 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
3312 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
3314 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
3315 imt_tramp->vt_offset = decode_value (p, &p);
3317 ji->data.imt_tramp = imt_tramp;
3318 break;
3320 case MONO_PATCH_INFO_SIGNATURE:
3321 ji->data.target = decode_signature (aot_module, p, &p);
3322 break;
3323 case MONO_PATCH_INFO_TLS_OFFSET:
3324 ji->data.target = GINT_TO_POINTER (decode_value (p, &p));
3325 break;
3326 case MONO_PATCH_INFO_GSHAREDVT_CALL: {
3327 MonoJumpInfoGSharedVtCall *info = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
3328 info->sig = decode_signature (aot_module, p, &p);
3329 g_assert (info->sig);
3330 info->method = decode_resolve_method_ref (aot_module, p, &p);
3331 g_assert (info->method);
3333 ji->data.target = info;
3334 break;
3336 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
3337 MonoGSharedVtMethodInfo *info = mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
3338 int i;
3340 info->method = decode_resolve_method_ref (aot_module, p, &p);
3341 g_assert (info->method);
3342 info->num_entries = decode_value (p, &p);
3343 info->count_entries = info->num_entries;
3344 info->entries = mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
3345 for (i = 0; i < info->num_entries; ++i) {
3346 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
3348 template->info_type = decode_value (p, &p);
3349 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
3350 case MONO_PATCH_INFO_CLASS: {
3351 MonoClass *klass = decode_klass_ref (aot_module, p, &p);
3352 if (!klass)
3353 goto cleanup;
3354 template->data = &klass->byval_arg;
3355 break;
3357 case MONO_PATCH_INFO_FIELD:
3358 template->data = decode_field_info (aot_module, p, &p);
3359 if (!template->data)
3360 goto cleanup;
3361 break;
3362 default:
3363 g_assert_not_reached ();
3364 break;
3367 ji->data.target = info;
3368 break;
3370 default:
3371 g_warning ("unhandled type %d", ji->type);
3372 g_assert_not_reached ();
3375 *endbuf = p;
3377 return TRUE;
3379 cleanup:
3380 return FALSE;
3383 static MonoJumpInfo*
3384 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
3385 guint32 **got_slots,
3386 guint8 *buf, guint8 **endbuf)
3388 MonoJumpInfo *patches;
3389 int pindex;
3390 guint8 *p;
3392 p = buf;
3394 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
3396 *got_slots = g_malloc (sizeof (guint32) * n_patches);
3398 for (pindex = 0; pindex < n_patches; ++pindex) {
3399 MonoJumpInfo *ji = &patches [pindex];
3400 guint8 *shared_p;
3401 gboolean res;
3402 guint32 got_offset;
3404 got_offset = decode_value (p, &p);
3406 if (aot_module->got [got_offset]) {
3407 /* Already loaded */
3408 //printf ("HIT!\n");
3409 } else {
3410 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
3412 ji->type = decode_value (shared_p, &shared_p);
3414 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
3415 if (!res)
3416 goto cleanup;
3419 (*got_slots) [pindex] = got_offset;
3422 *endbuf = p;
3423 return patches;
3425 cleanup:
3426 g_free (*got_slots);
3427 *got_slots = NULL;
3429 return NULL;
3432 static void
3433 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
3436 * Jump addresses cannot be patched by the trampoline code since it
3437 * does not have access to the caller's address. Instead, we collect
3438 * the addresses of the GOT slots pointing to a method, and patch
3439 * them after the method has been compiled.
3441 MonoJitDomainInfo *info = domain_jit_info (domain);
3442 GSList *list;
3444 mono_domain_lock (domain);
3445 if (!info->jump_target_got_slot_hash)
3446 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
3447 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
3448 list = g_slist_prepend (list, got_slot);
3449 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
3450 mono_domain_unlock (domain);
3454 * load_method:
3456 * Load the method identified by METHOD_INDEX from the AOT image. Return a
3457 * pointer to the native code of the method, or NULL if not found.
3458 * METHOD might not be set if the caller only has the image/token info.
3460 static gpointer
3461 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
3463 MonoClass *klass;
3464 gboolean from_plt = method == NULL;
3465 MonoMemPool *mp;
3466 int i, pindex, n_patches, used_strings;
3467 gboolean keep_patches = TRUE;
3468 guint8 *p;
3469 MonoJitInfo *jinfo = NULL;
3470 guint8 *code, *info;
3472 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
3473 return NULL;
3475 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
3476 /* Non shared AOT code can't be used in other appdomains */
3477 return NULL;
3479 if (amodule->out_of_date)
3480 return NULL;
3482 if (amodule->code_offsets [method_index] == 0xffffffff) {
3483 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3484 char *full_name;
3486 if (!method)
3487 method = mono_get_method (image, token, NULL);
3488 full_name = mono_method_full_name (method, TRUE);
3489 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: NOT FOUND: %s.", full_name);
3490 g_free (full_name);
3492 return NULL;
3495 code = &amodule->code [amodule->code_offsets [method_index]];
3497 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
3499 if (amodule->thumb_end && code < amodule->thumb_end && ((amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) == 0)) {
3500 /* Convert this into a thumb address */
3501 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
3502 code = &amodule->code [amodule->code_offsets [method_index] + 1];
3505 if (!amodule->methods_loaded) {
3506 amodule_lock (amodule);
3507 if (!amodule->methods_loaded) {
3508 guint32 *loaded;
3510 loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
3511 mono_memory_barrier ();
3512 amodule->methods_loaded = loaded;
3514 amodule_unlock (amodule);
3517 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
3518 return code;
3520 if (mono_last_aot_method != -1) {
3521 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
3522 return NULL;
3523 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
3524 if (!method)
3525 method = mono_get_method (image, token, NULL);
3526 if (method) {
3527 char *name = mono_method_full_name (method, TRUE);
3528 g_print ("LAST AOT METHOD: %s.\n", name);
3529 g_free (name);
3530 } else {
3531 g_print ("LAST AOT METHOD: %p %d\n", code, method_index);
3536 p = info;
3538 if (method) {
3539 klass = method->klass;
3540 decode_klass_ref (amodule, p, &p);
3541 } else {
3542 klass = decode_klass_ref (amodule, p, &p);
3545 if (amodule->info.opts & MONO_OPT_SHARED)
3546 used_strings = decode_value (p, &p);
3547 else
3548 used_strings = 0;
3550 for (i = 0; i < used_strings; i++) {
3551 guint token = decode_value (p, &p);
3552 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
3555 if (amodule->info.opts & MONO_OPT_SHARED)
3556 keep_patches = FALSE;
3558 n_patches = decode_value (p, &p);
3560 keep_patches = FALSE;
3562 if (n_patches) {
3563 MonoJumpInfo *patches;
3564 guint32 *got_slots;
3566 if (keep_patches)
3567 mp = domain->mp;
3568 else
3569 mp = mono_mempool_new ();
3571 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3572 if (patches == NULL)
3573 goto cleanup;
3575 for (pindex = 0; pindex < n_patches; ++pindex) {
3576 MonoJumpInfo *ji = &patches [pindex];
3578 if (!amodule->got [got_slots [pindex]]) {
3579 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
3580 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3581 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
3582 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3583 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
3585 ji->type = MONO_PATCH_INFO_NONE;
3588 g_free (got_slots);
3590 if (!keep_patches)
3591 mono_mempool_destroy (mp);
3594 if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
3595 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3597 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3598 char *full_name;
3600 if (!method)
3601 method = mono_get_method (image, token, NULL);
3603 full_name = mono_method_full_name (method, TRUE);
3605 if (!jinfo)
3606 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3608 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
3609 g_free (full_name);
3612 amodule_lock (amodule);
3614 InterlockedIncrement (&mono_jit_stats.methods_aot);
3616 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
3618 init_plt (amodule);
3620 if (method && method->wrapper_type)
3621 g_hash_table_insert (amodule->method_to_code, method, code);
3623 amodule_unlock (amodule);
3625 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3626 MonoJitInfo *jinfo;
3628 if (!method) {
3629 method = mono_get_method (image, token, NULL);
3630 g_assert (method);
3632 mono_profiler_method_jit (method);
3633 jinfo = mono_jit_info_table_find (domain, (char*)code);
3634 g_assert (jinfo);
3635 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3638 if (from_plt && klass && !klass->generic_container)
3639 mono_runtime_class_init (mono_class_vtable (domain, klass));
3641 return code;
3643 cleanup:
3644 /* FIXME: The space in domain->mp is wasted */
3645 if (amodule->info.opts & MONO_OPT_SHARED)
3646 /* No need to cache patches */
3647 mono_mempool_destroy (mp);
3649 if (jinfo)
3650 g_free (jinfo);
3652 return NULL;
3655 static guint32
3656 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
3658 guint32 table_size, entry_size, hash;
3659 guint32 *table, *entry;
3660 guint32 index;
3661 static guint32 n_extra_decodes;
3663 if (!amodule || amodule->out_of_date)
3664 return 0xffffff;
3666 table_size = amodule->extra_method_table [0];
3667 table = amodule->extra_method_table + 1;
3668 entry_size = 3;
3670 hash = mono_aot_method_hash (method) % table_size;
3672 entry = &table [hash * entry_size];
3674 if (entry [0] == 0)
3675 return 0xffffff;
3677 index = 0xffffff;
3678 while (TRUE) {
3679 guint32 key = entry [0];
3680 guint32 value = entry [1];
3681 guint32 next = entry [entry_size - 1];
3682 MonoMethod *m;
3683 guint8 *p, *orig_p;
3685 p = amodule->blob + key;
3686 orig_p = p;
3688 amodule_lock (amodule);
3689 if (!amodule->method_ref_to_method)
3690 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3691 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3692 amodule_unlock (amodule);
3693 if (!m) {
3694 m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3695 if (m) {
3696 amodule_lock (amodule);
3697 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3698 amodule_unlock (amodule);
3701 if (m == method) {
3702 index = value;
3703 break;
3706 /* Special case: wrappers of shared generic methods */
3707 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3708 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3709 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3710 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3712 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3713 index = value;
3714 break;
3718 /* Methods decoded needlessly */
3719 if (m) {
3720 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3721 n_extra_decodes ++;
3724 if (next != 0)
3725 entry = &table [next * entry_size];
3726 else
3727 break;
3730 return index;
3733 static void
3734 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3736 g_ptr_array_add ((GPtrArray*)user_data, value);
3740 * find_extra_method:
3742 * Try finding METHOD in the extra_method table in all AOT images.
3743 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3744 * module where the method was found.
3746 static guint32
3747 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3749 guint32 index;
3750 GPtrArray *modules;
3751 int i;
3753 /* Try the method's module first */
3754 *out_amodule = method->klass->image->aot_module;
3755 index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
3756 if (index != 0xffffff)
3757 return index;
3760 * Try all other modules.
3761 * This is needed because generic instances klass->image points to the image
3762 * containing the generic definition, but the native code is generated to the
3763 * AOT image which contains the reference.
3766 /* Make a copy to avoid doing the search inside the aot lock */
3767 modules = g_ptr_array_new ();
3768 mono_aot_lock ();
3769 g_hash_table_foreach (aot_modules, add_module_cb, modules);
3770 mono_aot_unlock ();
3772 index = 0xffffff;
3773 for (i = 0; i < modules->len; ++i) {
3774 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3776 if (amodule != method->klass->image->aot_module)
3777 index = find_extra_method_in_amodule (amodule, method);
3778 if (index != 0xffffff) {
3779 *out_amodule = amodule;
3780 break;
3784 g_ptr_array_free (modules, TRUE);
3786 return index;
3790 * mono_aot_get_method:
3792 * Return a pointer to the AOTed native code for METHOD if it can be found,
3793 * NULL otherwise.
3794 * On platforms with function pointers, this doesn't return a function pointer.
3796 gpointer
3797 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3799 MonoClass *klass = method->klass;
3800 guint32 method_index;
3801 MonoAotModule *amodule = klass->image->aot_module;
3802 guint8 *code;
3804 if (enable_aot_cache && !amodule && domain->entry_assembly && klass->image == mono_defaults.corlib) {
3805 /* This cannot be AOTed during startup, so do it now */
3806 if (!mscorlib_aot_loaded) {
3807 mscorlib_aot_loaded = TRUE;
3808 load_aot_module (klass->image->assembly, NULL);
3809 amodule = klass->image->aot_module;
3813 if (!amodule)
3814 return NULL;
3816 if (amodule->out_of_date)
3817 return NULL;
3819 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3820 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3821 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3822 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3823 return NULL;
3826 * Use the original method instead of its invoke-with-check wrapper.
3827 * This is not a problem when using full-aot, since it doesn't support
3828 * remoting.
3830 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3831 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3833 g_assert (klass->inited);
3835 /* Find method index */
3836 method_index = 0xffffff;
3837 if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
3839 * For generic methods, we store the fully shared instance in place of the
3840 * original method.
3842 method = mono_method_get_declaring_generic_method (method);
3843 method_index = mono_metadata_token_index (method->token) - 1;
3844 } else if (method->is_inflated || !method->token) {
3845 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3846 amodule_lock (amodule);
3847 code = g_hash_table_lookup (amodule->method_to_code, method);
3848 amodule_unlock (amodule);
3849 if (code)
3850 return code;
3852 method_index = find_extra_method (method, &amodule);
3854 * Special case the ICollection<T> wrappers for arrays, as they cannot
3855 * be statically enumerated, and each wrapper ends up calling the same
3856 * method in Array.
3858 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3859 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3861 code = mono_aot_get_method (domain, m);
3862 if (code)
3863 return code;
3867 * Special case Array.GetGenericValueImpl which is a generic icall.
3868 * Generic sharing currently can't handle it, but the icall returns data using
3869 * an out parameter, so the managed-to-native wrappers can share the same code.
3871 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3872 MonoMethod *m;
3873 MonoGenericContext ctx;
3874 MonoType *args [16];
3876 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3877 /* Avoid recursion */
3878 return NULL;
3880 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3881 g_assert (m);
3883 memset (&ctx, 0, sizeof (ctx));
3884 args [0] = &mono_defaults.object_class->byval_arg;
3885 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3887 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3890 * Get the code for the <object> instantiation which should be emitted into
3891 * the mscorlib aot image by the AOT compiler.
3893 code = mono_aot_get_method (domain, m);
3894 if (code)
3895 return code;
3898 /* Same for CompareExchange<T> and Exchange<T> */
3899 /* Same for Volatile.Read<T>/Write<T> */
3900 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib &&
3901 ((!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && (!strcmp (method->name, "CompareExchange") || !strcmp (method->name, "Exchange")) && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1])) ||
3902 (!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Volatile") && (!strcmp (method->name, "Read") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->ret))) ||
3903 (!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Volatile") && (!strcmp (method->name, "Write") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1]))))) {
3904 MonoMethod *m;
3905 MonoGenericContext ctx;
3906 MonoType *args [16];
3907 gpointer iter = NULL;
3909 while ((m = mono_class_get_methods (method->klass, &iter))) {
3910 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3911 break;
3913 g_assert (m);
3915 memset (&ctx, 0, sizeof (ctx));
3916 args [0] = &mono_defaults.object_class->byval_arg;
3917 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3919 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3921 /* Avoid recursion */
3922 if (method == m)
3923 return NULL;
3926 * Get the code for the <object> instantiation which should be emitted into
3927 * the mscorlib aot image by the AOT compiler.
3929 code = mono_aot_get_method (domain, m);
3930 if (code)
3931 return code;
3934 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
3935 /* Partial sharing */
3936 MonoMethod *shared;
3938 shared = mini_get_shared_method (method);
3939 method_index = find_extra_method (shared, &amodule);
3940 if (method_index != 0xffffff)
3941 method = shared;
3944 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
3945 /* gsharedvt */
3946 /* Use the all-vt shared method since this is what was AOTed */
3947 method_index = find_extra_method (mini_get_shared_method_full (method, TRUE, TRUE), &amodule);
3948 if (method_index != 0xffffff)
3949 method = mini_get_shared_method_full (method, TRUE, FALSE);
3952 if (method_index == 0xffffff) {
3953 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3954 char *full_name;
3956 full_name = mono_method_full_name (method, TRUE);
3957 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3958 g_free (full_name);
3960 return NULL;
3963 if (method_index == 0xffffff)
3964 return NULL;
3966 /* Needed by find_jit_info */
3967 amodule_lock (amodule);
3968 if (!amodule->extra_methods)
3969 amodule->extra_methods = g_hash_table_new (NULL, NULL);
3970 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3971 amodule_unlock (amodule);
3972 } else {
3973 /* Common case */
3974 method_index = mono_metadata_token_index (method->token) - 1;
3977 return load_method (domain, amodule, klass->image, method, method->token, method_index);
3981 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3982 * method.
3984 gpointer
3985 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3987 MonoAotModule *aot_module = image->aot_module;
3988 int method_index;
3990 if (!aot_module)
3991 return NULL;
3993 method_index = mono_metadata_token_index (token) - 1;
3995 return load_method (domain, aot_module, image, NULL, token, method_index);
3998 typedef struct {
3999 guint8 *addr;
4000 gboolean res;
4001 } IsGotEntryUserData;
4003 static void
4004 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
4006 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
4007 MonoAotModule *aot_module = (MonoAotModule*)value;
4009 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
4010 data->res = TRUE;
4013 gboolean
4014 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4016 IsGotEntryUserData user_data;
4018 if (!aot_modules)
4019 return FALSE;
4021 user_data.addr = addr;
4022 user_data.res = FALSE;
4023 mono_aot_lock ();
4024 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
4025 mono_aot_unlock ();
4027 return user_data.res;
4030 typedef struct {
4031 guint8 *addr;
4032 MonoAotModule *module;
4033 } FindAotModuleUserData;
4035 static void
4036 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
4038 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
4039 MonoAotModule *aot_module = (MonoAotModule*)value;
4041 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
4042 data->module = aot_module;
4045 static inline MonoAotModule*
4046 find_aot_module (guint8 *code)
4048 FindAotModuleUserData user_data;
4050 if (!aot_modules)
4051 return NULL;
4053 /* Reading these need no locking */
4054 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
4055 return NULL;
4057 user_data.addr = code;
4058 user_data.module = NULL;
4060 mono_aot_lock ();
4061 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
4062 mono_aot_unlock ();
4064 return user_data.module;
4067 void
4068 mono_aot_patch_plt_entry (guint8 *code, guint8 *plt_entry, gpointer *got, mgreg_t *regs, guint8 *addr)
4070 MonoAotModule *amodule;
4073 * Since AOT code is only used in the root domain,
4074 * mono_domain_get () != mono_get_root_domain () means the calling method
4075 * is AppDomain:InvokeInDomain, so this is the same check as in
4076 * mono_method_same_domain () but without loading the metadata for the method.
4078 if (mono_domain_get () == mono_get_root_domain ()) {
4079 if (!got) {
4080 amodule = find_aot_module (code);
4081 if (amodule)
4082 got = amodule->got;
4084 mono_arch_patch_plt_entry (plt_entry, got, regs, addr);
4089 * mono_aot_plt_resolve:
4091 * This function is called by the entries in the PLT to resolve the actual method that
4092 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
4093 * Returns NULL if the something cannot be loaded.
4095 gpointer
4096 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4098 #ifdef MONO_ARCH_AOT_SUPPORTED
4099 guint8 *p, *target, *plt_entry;
4100 MonoJumpInfo ji;
4101 MonoAotModule *module = (MonoAotModule*)aot_module;
4102 gboolean res, no_ftnptr = FALSE;
4103 MonoMemPool *mp;
4104 gboolean using_gsharedvt = FALSE;
4106 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
4108 p = &module->blob [plt_info_offset];
4110 ji.type = decode_value (p, &p);
4112 mp = mono_mempool_new_size (512);
4113 res = decode_patch (module, mp, &ji, p, &p);
4115 if (!res) {
4116 mono_mempool_destroy (mp);
4117 return NULL;
4120 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
4121 using_gsharedvt = TRUE;
4122 #endif
4125 * Avoid calling resolve_patch_target in the full-aot case if possible, since
4126 * it would create a trampoline, and we don't need that.
4127 * We could do this only if the method does not need the special handling
4128 * in mono_magic_trampoline ().
4130 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) &&
4131 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
4132 target = mono_jit_compile_method (ji.data.method);
4133 no_ftnptr = TRUE;
4134 } else {
4135 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
4139 * The trampoline expects us to return a function descriptor on platforms which use
4140 * it, but resolve_patch_target returns a direct function pointer for some type of
4141 * patches, so have to translate between the two.
4142 * FIXME: Clean this up, but how ?
4144 if (ji.type == MONO_PATCH_INFO_ABS || ji.type == MONO_PATCH_INFO_INTERNAL_METHOD || ji.type == MONO_PATCH_INFO_CLASS_INIT || ji.type == MONO_PATCH_INFO_ICALL_ADDR || ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR || ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
4145 /* These should already have a function descriptor */
4146 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4147 /* Our function descriptors have a 0 environment, gcc created ones don't */
4148 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
4149 g_assert (((gpointer*)target) [2] == 0);
4150 #endif
4151 /* Empty */
4152 } else if (!no_ftnptr) {
4153 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4154 g_assert (((gpointer*)target) [2] != 0);
4155 #endif
4156 target = mono_create_ftnptr (mono_domain_get (), target);
4159 mono_mempool_destroy (mp);
4161 /* Patch the PLT entry with target which might be the actual method not a trampoline */
4162 plt_entry = mono_aot_get_plt_entry (code);
4163 g_assert (plt_entry);
4164 mono_aot_patch_plt_entry (code, plt_entry, module->got, NULL, target);
4166 return target;
4167 #else
4168 g_assert_not_reached ();
4169 return NULL;
4170 #endif
4174 * init_plt:
4176 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
4177 * method in the module is loaded to avoid committing memory by writing to it.
4178 * LOCKING: Assumes the AMODULE lock is held.
4180 static void
4181 init_plt (MonoAotModule *amodule)
4183 int i;
4184 gpointer tramp;
4186 if (amodule->plt_inited)
4187 return;
4189 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
4192 * Initialize the PLT entries in the GOT to point to the default targets.
4195 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
4196 for (i = 1; i < amodule->info.plt_size; ++i)
4197 /* All the default entries point to the AOT trampoline */
4198 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
4200 amodule->plt_inited = TRUE;
4204 * mono_aot_get_plt_entry:
4206 * Return the address of the PLT entry called by the code at CODE if exists.
4208 guint8*
4209 mono_aot_get_plt_entry (guint8 *code)
4211 MonoAotModule *amodule = find_aot_module (code);
4212 guint8 *target = NULL;
4214 if (!amodule)
4215 return NULL;
4217 #ifdef TARGET_ARM
4218 if (amodule->thumb_end && code < amodule->thumb_end) {
4219 return mono_arm_get_thumb_plt_entry (code);
4221 #endif
4223 #ifdef MONO_ARCH_AOT_SUPPORTED
4224 target = mono_arch_get_call_target (code);
4225 #else
4226 g_assert_not_reached ();
4227 #endif
4229 #ifdef MONOTOUCH
4230 while (target != NULL) {
4231 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
4232 return target;
4234 // Add 4 since mono_arch_get_call_target assumes we're passing
4235 // the instruction after the actual branch instruction.
4236 target = mono_arch_get_call_target (target + 4);
4239 return NULL;
4240 #else
4241 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
4242 return target;
4243 else
4244 return NULL;
4245 #endif
4249 * mono_aot_get_plt_info_offset:
4251 * Return the PLT info offset belonging to the plt entry called by CODE.
4253 guint32
4254 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4256 guint8 *plt_entry = mono_aot_get_plt_entry (code);
4258 g_assert (plt_entry);
4260 /* The offset is embedded inside the code after the plt entry */
4261 #ifdef MONO_ARCH_AOT_SUPPORTED
4262 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
4263 #else
4264 g_assert_not_reached ();
4265 return 0;
4266 #endif
4269 static gpointer
4270 mono_create_ftnptr_malloc (guint8 *code)
4272 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4273 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
4275 ftnptr->code = code;
4276 ftnptr->toc = NULL;
4277 ftnptr->env = NULL;
4279 return ftnptr;
4280 #else
4281 return code;
4282 #endif
4286 * mono_aot_register_jit_icall:
4288 * Register a JIT icall which is called by trampolines in full-aot mode. This should
4289 * be called from mono_arch_init () during startup.
4291 void
4292 mono_aot_register_jit_icall (const char *name, gpointer addr)
4294 /* No need for locking */
4295 if (!aot_jit_icall_hash)
4296 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
4297 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
4301 * load_function_full:
4303 * Load the function named NAME from the aot image.
4305 static gpointer
4306 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
4308 char *symbol;
4309 guint8 *p;
4310 int n_patches, pindex;
4311 MonoMemPool *mp;
4312 gpointer code;
4313 guint32 info_offset;
4315 /* Load the code */
4317 symbol = g_strdup_printf ("%s", name);
4318 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
4319 g_free (symbol);
4320 if (!code)
4321 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
4323 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
4325 /* Load info */
4327 symbol = g_strdup_printf ("%s_p", name);
4328 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
4329 g_free (symbol);
4330 if (!p)
4331 /* Nothing to patch */
4332 return code;
4334 info_offset = *(guint32*)p;
4335 if (out_tinfo) {
4336 MonoTrampInfo *tinfo;
4337 guint32 code_size, uw_info_len, uw_offset;
4338 guint8 *uw_info;
4339 /* Construct a MonoTrampInfo from the data in the AOT image */
4341 p += sizeof (guint32);
4342 code_size = *(guint32*)p;
4343 p += sizeof (guint32);
4344 uw_offset = *(guint32*)p;
4345 uw_info = amodule->unwind_info + uw_offset;
4346 uw_info_len = decode_value (uw_info, &uw_info);
4348 tinfo = g_new0 (MonoTrampInfo, 1);
4349 tinfo->code = code;
4350 tinfo->code_size = code_size;
4351 tinfo->uw_info = uw_info;
4352 tinfo->uw_info_len = uw_info_len;
4354 *out_tinfo = tinfo;
4357 p = amodule->blob + info_offset;
4359 /* Similar to mono_aot_load_method () */
4361 n_patches = decode_value (p, &p);
4363 if (n_patches) {
4364 MonoJumpInfo *patches;
4365 guint32 *got_slots;
4367 mp = mono_mempool_new ();
4369 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
4370 g_assert (patches);
4372 for (pindex = 0; pindex < n_patches; ++pindex) {
4373 MonoJumpInfo *ji = &patches [pindex];
4374 gpointer target;
4376 if (amodule->got [got_slots [pindex]])
4377 continue;
4380 * When this code is executed, the runtime may not be initalized yet, so
4381 * resolve the patch info by hand.
4383 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4384 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
4385 target = mono_get_lmf_addr;
4386 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
4387 target = mono_thread_force_interruption_checkpoint;
4388 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
4389 target = mono_exception_from_token;
4390 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
4391 target = mono_get_throw_exception ();
4392 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
4393 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
4394 target = (gpointer)mono_get_trampoline_func (tramp_type2);
4395 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
4396 /* atoll is needed because the the offset is unsigned */
4397 guint32 slot;
4398 int res;
4400 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
4401 g_assert (res == 1);
4402 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4403 target = mono_create_ftnptr_malloc (target);
4404 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
4405 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
4406 target = mono_create_ftnptr_malloc (target);
4407 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
4408 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
4409 target = mono_create_ftnptr_malloc (target);
4410 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
4411 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
4412 target = mono_create_ftnptr_malloc (target);
4413 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
4414 target = mono_thread_get_and_clear_pending_exception;
4415 } else if (strstr (ji->data.name, "generic_trampoline_")) {
4416 target = mono_aot_get_trampoline (ji->data.name);
4417 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
4418 /* Registered by mono_arch_init () */
4419 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
4420 } else {
4421 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
4422 g_assert_not_reached ();
4423 target = NULL;
4425 } else {
4426 /* Hopefully the code doesn't have patches which need method or
4427 * domain to be set.
4429 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
4430 g_assert (target);
4433 amodule->got [got_slots [pindex]] = target;
4436 g_free (got_slots);
4438 mono_mempool_destroy (mp);
4441 return code;
4444 static gpointer
4445 load_function (MonoAotModule *amodule, const char *name)
4447 return load_function_full (amodule, name, NULL);
4451 * Return the trampoline identified by NAME from the mscorlib AOT file.
4452 * On ppc64, this returns a function descriptor.
4454 gpointer
4455 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
4457 MonoImage *image;
4458 MonoAotModule *amodule;
4460 image = mono_defaults.corlib;
4461 g_assert (image);
4463 amodule = image->aot_module;
4464 g_assert (amodule);
4466 return mono_create_ftnptr_malloc (load_function_full (amodule, name, out_tinfo));
4469 gpointer
4470 mono_aot_get_trampoline (const char *name)
4472 return mono_aot_get_trampoline_full (name, NULL);
4475 #ifdef MONOTOUCH
4476 #include <mach/mach.h>
4478 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
4479 /* these sizes are for ARM code, parametrize if porting to other architectures (see arch_emit_specific_trampoline_pages)
4480 * trampoline size is assumed to be 8 bytes below as well (8 is the minimum for 32 bit archs, since we need to store
4481 * two pointers for trampoline in the data page).
4482 * the minimum for the common code must be at least sizeof(TrampolinePage), since we store the page info at the
4483 * beginning of the data page.
4485 static const int trampolines_pages_code_offsets [MONO_AOT_TRAMP_NUM] = {16, 16, 72, 16};
4487 static unsigned char*
4488 get_new_trampoline_from_page (int tramp_type)
4490 MonoAotModule *amodule;
4491 MonoImage *image;
4492 TrampolinePage *page;
4493 int count;
4494 void *tpage;
4495 vm_address_t addr, taddr;
4496 kern_return_t ret;
4497 vm_prot_t prot, max_prot;
4498 int psize, specific_trampoline_size;
4499 unsigned char *code;
4501 specific_trampoline_size = 2 * sizeof (gpointer);
4503 mono_aot_page_lock ();
4504 page = trampoline_pages [tramp_type];
4505 if (page && page->trampolines < page->trampolines_end) {
4506 code = page->trampolines;
4507 page->trampolines += specific_trampoline_size;
4508 mono_aot_page_unlock ();
4509 return code;
4511 mono_aot_page_unlock ();
4512 psize = mono_pagesize ();
4513 /* the trampoline template page is in the mscorlib module */
4514 image = mono_defaults.corlib;
4515 g_assert (image);
4517 amodule = image->aot_module;
4518 g_assert (amodule);
4520 g_assert (amodule->info.tramp_page_size == psize);
4522 if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
4523 tpage = load_function (amodule, "specific_trampolines_page");
4524 else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
4525 tpage = load_function (amodule, "rgctx_trampolines_page");
4526 else if (tramp_type == MONO_AOT_TRAMP_IMT_THUNK)
4527 tpage = load_function (amodule, "imt_trampolines_page");
4528 else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
4529 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
4530 else
4531 g_error ("Incorrect tramp type for trampolines page");
4532 g_assert (tpage);
4533 /*g_warning ("loaded trampolines page at %x", tpage);*/
4535 /* avoid the unlikely case of looping forever */
4536 count = 40;
4537 page = NULL;
4538 while (page == NULL && count-- > 0) {
4539 addr = 0;
4540 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
4541 * while the second will contain the trampolines.
4543 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
4544 if (ret != KERN_SUCCESS) {
4545 g_error ("Cannot allocate memory for trampolines: %d", ret);
4546 break;
4548 /*g_warning ("allocated trampoline double page at %x", addr);*/
4549 /* replace the second page with a remapped trampoline page */
4550 taddr = addr + psize;
4551 vm_deallocate (mach_task_self (), taddr, psize);
4552 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
4553 if (ret != KERN_SUCCESS) {
4554 /* someone else got the page, try again */
4555 vm_deallocate (mach_task_self (), addr, psize);
4556 continue;
4558 /*g_warning ("remapped trampoline page at %x", taddr);*/
4560 mono_aot_page_lock ();
4561 page = trampoline_pages [tramp_type];
4562 /* some other thread already allocated, so use that to avoid wasting memory */
4563 if (page && page->trampolines < page->trampolines_end) {
4564 code = page->trampolines;
4565 page->trampolines += specific_trampoline_size;
4566 mono_aot_page_unlock ();
4567 vm_deallocate (mach_task_self (), addr, psize);
4568 vm_deallocate (mach_task_self (), taddr, psize);
4569 return code;
4571 page = (TrampolinePage*)addr;
4572 page->next = trampoline_pages [tramp_type];
4573 trampoline_pages [tramp_type] = page;
4574 #ifdef TARGET_ARM64
4575 page->trampolines = (void*)(taddr + amodule->info.tramp_page_code_offsets [tramp_type]);
4576 #else
4577 page->trampolines = (void*)(taddr + trampolines_pages_code_offsets [tramp_type]);
4578 #endif
4579 page->trampolines_end = (void*)(taddr + psize - 64);
4580 code = page->trampolines;
4581 page->trampolines += specific_trampoline_size;
4582 mono_aot_page_unlock ();
4583 return code;
4585 g_error ("Cannot allocate more trampoline pages: %d", ret);
4586 return NULL;
4589 #else
4590 static unsigned char*
4591 get_new_trampoline_from_page (int tramp_type)
4593 g_error ("Page trampolines not supported.");
4594 return NULL;
4596 #endif
4599 static gpointer
4600 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
4602 void *code;
4603 gpointer *data;
4605 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
4607 data = (gpointer*)((char*)code - mono_pagesize ());
4608 data [0] = arg;
4609 data [1] = tramp;
4610 /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4611 return code;
4615 static gpointer
4616 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
4618 void *code;
4619 gpointer *data;
4621 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
4623 data = (gpointer*)((char*)code - mono_pagesize ());
4624 data [0] = arg;
4625 data [1] = tramp;
4626 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4627 return code;
4631 static gpointer
4632 get_new_imt_trampoline_from_page (gpointer arg)
4634 void *code;
4635 gpointer *data;
4637 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT_THUNK);
4639 data = (gpointer*)((char*)code - mono_pagesize ());
4640 data [0] = arg;
4641 /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
4642 return code;
4646 static gpointer
4647 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
4649 void *code;
4650 gpointer *data;
4652 code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
4654 data = (gpointer*)((char*)code - mono_pagesize ());
4655 data [0] = arg;
4656 data [1] = tramp;
4657 /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4658 return code;
4661 /* Return a given kind of trampoline */
4662 static gpointer
4663 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
4665 MonoAotModule *amodule;
4666 int index, tramp_size;
4667 MonoImage *image;
4669 /* Currently, we keep all trampolines in the mscorlib AOT image */
4670 image = mono_defaults.corlib;
4671 g_assert (image);
4673 mono_aot_lock ();
4675 amodule = image->aot_module;
4676 g_assert (amodule);
4678 *out_amodule = amodule;
4680 #ifdef MONOTOUCH
4681 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
4682 #else
4683 #define MONOTOUCH_TRAMPOLINES_ERROR ""
4684 #endif
4685 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
4686 g_error ("Ran out of trampolines of type %d in '%s' (%d)%s\n",
4687 tramp_type, image->name, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
4689 index = amodule->trampoline_index [tramp_type] ++;
4691 mono_aot_unlock ();
4693 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
4695 tramp_size = amodule->info.trampoline_size [tramp_type];
4697 if (out_tramp_size)
4698 *out_tramp_size = tramp_size;
4700 return amodule->trampolines [tramp_type] + (index * tramp_size);
4704 * Return a specific trampoline from the AOT file.
4706 gpointer
4707 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4709 MonoAotModule *amodule;
4710 guint32 got_offset, tramp_size;
4711 guint8 *code, *tramp;
4712 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
4713 static gboolean inited;
4714 static guint32 num_trampolines;
4716 if (!inited) {
4717 mono_aot_lock ();
4719 if (!inited) {
4720 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
4721 inited = TRUE;
4724 mono_aot_unlock ();
4727 num_trampolines ++;
4729 if (!generic_trampolines [tramp_type]) {
4730 char *symbol;
4732 symbol = mono_get_generic_trampoline_name (tramp_type);
4733 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
4734 g_free (symbol);
4737 tramp = generic_trampolines [tramp_type];
4738 g_assert (tramp);
4740 if (USE_PAGE_TRAMPOLINES) {
4741 code = get_new_specific_trampoline_from_page (tramp, arg1);
4742 tramp_size = 8;
4743 } else {
4744 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
4746 amodule->got [got_offset] = tramp;
4747 amodule->got [got_offset + 1] = arg1;
4750 if (code_len)
4751 *code_len = tramp_size;
4753 return code;
4756 gpointer
4757 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4759 MonoAotModule *amodule;
4760 guint8 *code;
4761 guint32 got_offset;
4763 if (USE_PAGE_TRAMPOLINES) {
4764 code = get_new_rgctx_trampoline_from_page (addr, ctx);
4765 } else {
4766 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
4768 amodule->got [got_offset] = ctx;
4769 amodule->got [got_offset + 1] = addr;
4772 /* The caller expects an ftnptr */
4773 return mono_create_ftnptr (mono_domain_get (), code);
4776 gpointer
4777 mono_aot_get_unbox_trampoline (MonoMethod *method)
4779 guint32 method_index = mono_metadata_token_index (method->token) - 1;
4780 MonoAotModule *amodule;
4781 gpointer code;
4782 guint32 *ut, *ut_end, *entry;
4783 int low, high, entry_index;
4785 if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
4786 method_index = find_extra_method (method, &amodule);
4787 if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4788 MonoMethod *shared = mini_get_shared_method_full (method, TRUE, TRUE);
4789 method_index = find_extra_method (shared, &amodule);
4791 g_assert (method_index != 0xffffff);
4792 } else {
4793 amodule = method->klass->image->aot_module;
4794 g_assert (amodule);
4797 ut = amodule->unbox_trampolines;
4798 ut_end = amodule->unbox_trampolines_end;
4800 /* Do a binary search in the sorted table */
4801 code = NULL;
4802 low = 0;
4803 high = (ut_end - ut) / 2;
4804 while (low < high) {
4805 entry_index = (low + high) / 2;
4806 entry = &ut [(entry_index * 2)];
4807 if (entry [0] < method_index) {
4808 low = entry_index + 1;
4809 } else if (entry [0] > method_index) {
4810 high = entry_index;
4811 } else {
4812 if (amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES)
4813 code = get_arm_bl_target (entry + 1);
4814 else
4815 code = amodule->code + entry [1];
4816 break;
4819 g_assert (code);
4821 /* The caller expects an ftnptr */
4822 return mono_create_ftnptr (mono_domain_get (), code);
4825 gpointer
4826 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4828 char *symbol;
4829 gpointer code;
4830 MonoAotModule *amodule = mono_defaults.corlib->aot_module;
4831 guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
4832 static int count = 0;
4834 count ++;
4835 if (index >= amodule->info.num_rgctx_fetch_trampolines) {
4836 static gpointer addr;
4837 gpointer *info;
4840 * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
4842 if (!addr)
4843 addr = load_function (amodule, "rgctx_fetch_trampoline_general");
4844 info = mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
4845 info [0] = GUINT_TO_POINTER (slot);
4846 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4847 code = mono_aot_get_static_rgctx_trampoline (info, addr);
4848 return mono_create_ftnptr (mono_domain_get (), code);
4851 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
4852 code = load_function (mono_defaults.corlib->aot_module, symbol);
4853 g_free (symbol);
4854 /* The caller expects an ftnptr */
4855 return mono_create_ftnptr (mono_domain_get (), code);
4858 gpointer
4859 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4861 guint32 got_offset;
4862 gpointer code;
4863 gpointer *buf;
4864 int i, index, real_count;
4865 MonoAotModule *amodule;
4867 real_count = 0;
4868 for (i = 0; i < count; ++i) {
4869 MonoIMTCheckItem *item = imt_entries [i];
4871 if (item->is_equals)
4872 real_count ++;
4875 /* Save the entries into an array */
4876 buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
4877 index = 0;
4878 for (i = 0; i < count; ++i) {
4879 MonoIMTCheckItem *item = imt_entries [i];
4881 if (!item->is_equals)
4882 continue;
4884 g_assert (item->key);
4886 buf [(index * 2)] = item->key;
4887 if (item->has_target_code) {
4888 gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
4889 *p = item->value.target_code;
4890 buf [(index * 2) + 1] = p;
4891 } else {
4892 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
4894 index ++;
4896 buf [(index * 2)] = NULL;
4897 buf [(index * 2) + 1] = fail_tramp;
4899 if (USE_PAGE_TRAMPOLINES) {
4900 code = get_new_imt_trampoline_from_page (buf);
4901 } else {
4902 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
4904 amodule->got [got_offset] = buf;
4907 return code;
4910 gpointer
4911 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
4913 MonoAotModule *amodule;
4914 guint8 *code;
4915 guint32 got_offset;
4917 if (USE_PAGE_TRAMPOLINES) {
4918 code = get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
4919 } else {
4920 code = get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
4922 amodule->got [got_offset] = arg;
4923 amodule->got [got_offset + 1] = addr;
4926 /* The caller expects an ftnptr */
4927 return mono_create_ftnptr (mono_domain_get (), code);
4931 * mono_aot_set_make_unreadable:
4933 * Set whenever to make all mmaped memory unreadable. In conjuction with a
4934 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
4936 void
4937 mono_aot_set_make_unreadable (gboolean unreadable)
4939 static int inited;
4941 make_unreadable = unreadable;
4943 if (make_unreadable && !inited) {
4944 mono_counters_register ("AOT: pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
4948 typedef struct {
4949 MonoAotModule *module;
4950 guint8 *ptr;
4951 } FindMapUserData;
4953 static void
4954 find_map (gpointer key, gpointer value, gpointer user_data)
4956 MonoAotModule *module = (MonoAotModule*)value;
4957 FindMapUserData *data = (FindMapUserData*)user_data;
4959 if (!data->module)
4960 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4961 data->module = module;
4964 static MonoAotModule*
4965 find_module_for_addr (void *ptr)
4967 FindMapUserData data;
4969 if (!make_unreadable)
4970 return NULL;
4972 data.module = NULL;
4973 data.ptr = (guint8*)ptr;
4975 mono_aot_lock ();
4976 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4977 mono_aot_unlock ();
4979 return data.module;
4983 * mono_aot_is_pagefault:
4985 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4986 * within memory allocated by this module.
4988 gboolean
4989 mono_aot_is_pagefault (void *ptr)
4991 if (!make_unreadable)
4992 return FALSE;
4995 * Not signal safe, but SIGSEGV's are synchronous, and
4996 * this is only turned on by a MONO_DEBUG option.
4998 return find_module_for_addr (ptr) != NULL;
5002 * mono_aot_handle_pagefault:
5004 * Handle a pagefault caused by an unreadable page by making it readable again.
5006 void
5007 mono_aot_handle_pagefault (void *ptr)
5009 #ifndef PLATFORM_WIN32
5010 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
5011 int res;
5013 mono_aot_lock ();
5014 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
5015 g_assert (res == 0);
5017 n_pagefaults ++;
5018 mono_aot_unlock ();
5019 #endif
5022 #else
5023 /* AOT disabled */
5025 void
5026 mono_aot_init (void)
5030 gpointer
5031 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
5033 return NULL;
5036 gboolean
5037 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
5039 return FALSE;
5042 gboolean
5043 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
5045 return FALSE;
5048 gboolean
5049 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
5051 return FALSE;
5054 MonoJitInfo *
5055 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
5057 return NULL;
5060 gpointer
5061 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
5063 return NULL;
5066 guint8*
5067 mono_aot_get_plt_entry (guint8 *code)
5069 return NULL;
5072 gpointer
5073 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
5075 return NULL;
5078 void
5079 mono_aot_patch_plt_entry (guint8 *code, guint8 *plt_entry, gpointer *got, mgreg_t *regs, guint8 *addr)
5083 gpointer
5084 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
5086 return NULL;
5089 guint32
5090 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
5092 g_assert_not_reached ();
5094 return 0;
5097 gpointer
5098 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
5100 g_assert_not_reached ();
5101 return NULL;
5104 gpointer
5105 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
5107 g_assert_not_reached ();
5108 return NULL;
5111 gpointer
5112 mono_aot_get_trampoline (const char *name)
5114 g_assert_not_reached ();
5115 return NULL;
5118 gpointer
5119 mono_aot_get_unbox_trampoline (MonoMethod *method)
5121 g_assert_not_reached ();
5122 return NULL;
5125 gpointer
5126 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
5128 g_assert_not_reached ();
5129 return NULL;
5132 gpointer
5133 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
5135 g_assert_not_reached ();
5136 return NULL;
5139 guint8*
5140 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
5142 g_assert_not_reached ();
5143 return NULL;
5146 void
5147 mono_aot_register_jit_icall (const char *name, gpointer addr)
5151 #endif