Change the way unbox trampolines are handled in AOT. Instead of emitting a global...
[mono-project/dkf.git] / mono / mini / aot-runtime.c
blob0fd244e9fb84b1198cb901bf77f9854600df9100
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 #ifdef HAVE_DL_ITERATE_PHDR
41 #include <link.h>
42 #endif
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/class.h>
46 #include <mono/metadata/object.h>
47 #include <mono/metadata/tokentype.h>
48 #include <mono/metadata/appdomain.h>
49 #include <mono/metadata/debug-helpers.h>
50 #include <mono/metadata/assembly.h>
51 #include <mono/metadata/metadata-internals.h>
52 #include <mono/metadata/marshal.h>
53 #include <mono/metadata/gc-internal.h>
54 #include <mono/metadata/monitor.h>
55 #include <mono/metadata/threads-types.h>
56 #include <mono/metadata/mono-endian.h>
57 #include <mono/utils/mono-logger-internal.h>
58 #include <mono/utils/mono-mmap.h>
59 #include "mono/utils/mono-compiler.h"
60 #include <mono/utils/mono-counters.h>
62 #include "mini.h"
63 #include "version.h"
65 #ifndef DISABLE_AOT
67 #ifdef TARGET_WIN32
68 #define SHARED_EXT ".dll"
69 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
70 #define SHARED_EXT ".dylib"
71 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
72 #define SHARED_EXT ".dylib"
73 #else
74 #define SHARED_EXT ".so"
75 #endif
77 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
78 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
80 typedef struct MonoAotModule {
81 char *aot_name;
82 /* Pointer to the Global Offset Table */
83 gpointer *got;
84 GHashTable *name_cache;
85 GHashTable *extra_methods;
86 /* Maps methods to their code */
87 GHashTable *method_to_code;
88 /* Maps pointers into the method info to the methods themselves */
89 GHashTable *method_ref_to_method;
90 MonoAssemblyName *image_names;
91 char **image_guids;
92 MonoAssembly *assembly;
93 MonoImage **image_table;
94 guint32 image_table_len;
95 gboolean out_of_date;
96 gboolean plt_inited;
97 guint8 *mem_begin;
98 guint8 *mem_end;
99 guint8 *code;
100 guint8 *code_end;
101 guint8 *plt;
102 guint8 *plt_end;
103 guint8 *blob;
104 gint32 *code_offsets;
105 /* This contains <offset, index> pairs sorted by offset */
106 /* This is needed because LLVM emitted methods can be in any order */
107 gint32 *sorted_code_offsets;
108 gint32 sorted_code_offsets_len;
109 guint32 *method_info_offsets;
110 guint32 *got_info_offsets;
111 guint32 *ex_info_offsets;
112 guint32 *class_info_offsets;
113 guint32 *methods_loaded;
114 guint16 *class_name_table;
115 guint32 *extra_method_table;
116 guint32 *extra_method_info_offsets;
117 guint32 *unbox_trampolines;
118 guint32 *unbox_trampolines_end;
119 guint8 *unwind_info;
120 guint8 *thumb_end;
122 /* Points to the mono EH data created by LLVM */
123 guint8 *mono_eh_frame;
125 /* Points to the trampolines */
126 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
127 /* The first unused trampoline of each kind */
128 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
130 MonoAotFileInfo info;
132 gpointer *globals;
133 MonoDl *sofile;
134 } MonoAotModule;
136 static GHashTable *aot_modules;
137 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
138 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
139 static CRITICAL_SECTION aot_mutex;
142 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
143 * AOT modules registered by mono_aot_register_module ().
145 static GHashTable *static_aot_modules;
148 * Maps MonoJitInfo* to the aot module they belong to, this can be different
149 * from ji->method->klass->image's aot module for generic instances.
151 static GHashTable *ji_to_amodule;
154 * Whenever to AOT compile loaded assemblies on demand and store them in
155 * a cache under $HOME/.mono/aot-cache.
157 static gboolean use_aot_cache = FALSE;
160 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
161 * use_aot_cache is TRUE.
163 static gboolean spawn_compiler = TRUE;
165 /* For debugging */
166 static gint32 mono_last_aot_method = -1;
168 static gboolean make_unreadable = FALSE;
169 static guint32 name_table_accesses = 0;
170 static guint32 n_pagefaults = 0;
172 /* Used to speed-up find_aot_module () */
173 static gsize aot_code_low_addr = (gssize)-1;
174 static gsize aot_code_high_addr = 0;
176 static GHashTable *aot_jit_icall_hash;
178 static void
179 init_plt (MonoAotModule *info);
181 /*****************************************************/
182 /* AOT RUNTIME */
183 /*****************************************************/
186 * load_image:
188 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
189 * found, and sets the loader error if SET_ERROR is TRUE.
191 static MonoImage *
192 load_image (MonoAotModule *amodule, int index, gboolean set_error)
194 MonoAssembly *assembly;
195 MonoImageOpenStatus status;
197 g_assert (index < amodule->image_table_len);
199 if (amodule->image_table [index])
200 return amodule->image_table [index];
201 if (amodule->out_of_date)
202 return NULL;
204 assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
205 if (!assembly) {
206 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);
207 amodule->out_of_date = TRUE;
209 if (set_error) {
210 char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
211 mono_loader_set_error_assembly_load (full_name, FALSE);
212 g_free (full_name);
214 return NULL;
217 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
218 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);
219 amodule->out_of_date = TRUE;
220 return NULL;
223 amodule->image_table [index] = assembly->image;
224 return assembly->image;
227 static inline gint32
228 decode_value (guint8 *ptr, guint8 **rptr)
230 guint8 b = *ptr;
231 gint32 len;
233 if ((b & 0x80) == 0){
234 len = b;
235 ++ptr;
236 } else if ((b & 0x40) == 0){
237 len = ((b & 0x3f) << 8 | ptr [1]);
238 ptr += 2;
239 } else if (b != 0xff) {
240 len = ((b & 0x1f) << 24) |
241 (ptr [1] << 16) |
242 (ptr [2] << 8) |
243 ptr [3];
244 ptr += 4;
246 else {
247 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
248 ptr += 5;
250 if (rptr)
251 *rptr = ptr;
253 //printf ("DECODE: %d.\n", len);
254 return len;
258 * mono_aot_get_method:
260 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
261 * entry.
263 static guint32
264 mono_aot_get_offset (guint32 *table, int index)
266 int i, group, ngroups, index_entry_size;
267 int start_offset, offset, noffsets, group_size;
268 guint8 *data_start, *p;
269 guint32 *index32 = NULL;
270 guint16 *index16 = NULL;
272 noffsets = table [0];
273 group_size = table [1];
274 ngroups = table [2];
275 index_entry_size = table [3];
276 group = index / group_size;
278 if (index_entry_size == 2) {
279 index16 = (guint16*)&table [4];
280 data_start = (guint8*)&index16 [ngroups];
281 p = data_start + index16 [group];
282 } else {
283 index32 = (guint32*)&table [4];
284 data_start = (guint8*)&index32 [ngroups];
285 p = data_start + index32 [group];
288 /* offset will contain the value of offsets [group * group_size] */
289 offset = start_offset = decode_value (p, &p);
290 for (i = group * group_size + 1; i <= index; ++i) {
291 offset += decode_value (p, &p);
294 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
296 return offset;
299 static MonoMethod*
300 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
302 static MonoClass*
303 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
305 static MonoGenericInst*
306 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
308 int type_argc, i;
309 MonoType **type_argv;
310 MonoGenericInst *inst;
311 guint8 *p = buf;
313 type_argc = decode_value (p, &p);
314 type_argv = g_new0 (MonoType*, type_argc);
316 for (i = 0; i < type_argc; ++i) {
317 MonoClass *pclass = decode_klass_ref (module, p, &p);
318 if (!pclass) {
319 g_free (type_argv);
320 return NULL;
322 type_argv [i] = &pclass->byval_arg;
325 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
326 g_free (type_argv);
328 *endbuf = p;
330 return inst;
333 static gboolean
334 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
336 gboolean has_class_inst, has_method_inst;
337 guint8 *p = buf;
339 has_class_inst = decode_value (p, &p);
340 if (has_class_inst) {
341 ctx->class_inst = decode_generic_inst (module, p, &p);
342 if (!ctx->class_inst)
343 return FALSE;
345 has_method_inst = decode_value (p, &p);
346 if (has_method_inst) {
347 ctx->method_inst = decode_generic_inst (module, p, &p);
348 if (!ctx->method_inst)
349 return FALSE;
352 *endbuf = p;
353 return TRUE;
356 static MonoClass*
357 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
359 MonoImage *image;
360 MonoClass *klass, *eklass;
361 guint32 token, rank;
362 guint8 *p = buf;
364 token = decode_value (p, &p);
365 if (token == 0) {
366 *endbuf = p;
367 return NULL;
369 if (mono_metadata_token_table (token) == 0) {
370 image = load_image (module, decode_value (p, &p), TRUE);
371 if (!image)
372 return NULL;
373 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token);
374 } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
375 if (token == MONO_TOKEN_TYPE_SPEC) {
376 MonoTypeEnum type = decode_value (p, &p);
378 if (type == MONO_TYPE_GENERICINST) {
379 MonoClass *gclass;
380 MonoGenericContext ctx;
381 MonoType *type;
383 gclass = decode_klass_ref (module, p, &p);
384 if (!gclass)
385 return NULL;
386 g_assert (gclass->generic_container);
388 memset (&ctx, 0, sizeof (ctx));
389 ctx.class_inst = decode_generic_inst (module, p, &p);
390 if (!ctx.class_inst)
391 return NULL;
392 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
393 klass = mono_class_from_mono_type (type);
394 mono_metadata_free_type (type);
395 } else if ((type == MONO_TYPE_VAR) || (type == MONO_TYPE_MVAR)) {
396 MonoType *t;
397 MonoGenericContainer *container;
399 int num = decode_value (p, &p);
400 gboolean is_method = decode_value (p, &p);
402 if (is_method) {
403 MonoMethod *method_def;
404 g_assert (type == MONO_TYPE_MVAR);
405 method_def = decode_resolve_method_ref (module, p, &p);
406 if (!method_def)
407 return NULL;
409 container = mono_method_get_generic_container (method_def);
410 } else {
411 MonoClass *class_def;
412 g_assert (type == MONO_TYPE_VAR);
413 class_def = decode_klass_ref (module, p, &p);
414 if (!class_def)
415 return NULL;
417 container = class_def->generic_container;
420 g_assert (container);
422 // FIXME: Memory management
423 t = g_new0 (MonoType, 1);
424 t->type = type;
425 t->data.generic_param = mono_generic_container_get_param (container, num);
427 // FIXME: Maybe use types directly to avoid
428 // the overhead of creating MonoClass-es
429 klass = mono_class_from_mono_type (t);
431 g_free (t);
432 } else {
433 g_assert_not_reached ();
435 } else {
436 image = load_image (module, decode_value (p, &p), TRUE);
437 if (!image)
438 return NULL;
439 klass = mono_class_get (image, token);
441 } else if (token == MONO_TOKEN_TYPE_DEF) {
442 /* Array */
443 image = load_image (module, decode_value (p, &p), TRUE);
444 if (!image)
445 return NULL;
446 rank = decode_value (p, &p);
447 eklass = decode_klass_ref (module, p, &p);
448 klass = mono_array_class_get (eklass, rank);
449 } else {
450 g_assert_not_reached ();
452 g_assert (klass);
454 *endbuf = p;
455 return klass;
458 static MonoClassField*
459 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
461 MonoClass *klass = decode_klass_ref (module, buf, &buf);
462 guint32 token;
463 guint8 *p = buf;
465 if (!klass)
466 return NULL;
468 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
470 *endbuf = p;
472 return mono_class_get_field (klass, token);
475 /* Stores information returned by decode_method_ref () */
476 typedef struct {
477 MonoImage *image;
478 guint32 token;
479 MonoMethod *method;
480 gboolean no_aot_trampoline;
481 } MethodRef;
484 * decode_method_ref_with_target:
486 * Decode a method reference, storing the image/token into a MethodRef structure.
487 * This avoids loading metadata for the method if the caller does not need it. If the method has
488 * no token, then it is loaded from metadata and ref->method is set to the method instance.
489 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method couldn't resolve to TARGET, and return FALSE.
491 static gboolean
492 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
494 guint32 image_index, value;
495 MonoImage *image = NULL;
496 guint8 *p = buf;
498 memset (ref, 0, sizeof (MethodRef));
500 value = decode_value (p, &p);
501 image_index = value >> 24;
503 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
504 ref->no_aot_trampoline = TRUE;
505 value = decode_value (p, &p);
506 image_index = value >> 24;
509 if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
510 if (target && target->wrapper_type)
511 return FALSE;
514 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
515 guint32 wrapper_type;
517 wrapper_type = decode_value (p, &p);
519 if (target && target->wrapper_type != wrapper_type)
520 return FALSE;
522 /* Doesn't matter */
523 image = mono_defaults.corlib;
525 switch (wrapper_type) {
526 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
527 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
529 if (!m)
530 return FALSE;
531 mono_class_init (m->klass);
532 ref->method = mono_marshal_get_remoting_invoke_with_check (m);
533 break;
535 case MONO_WRAPPER_PROXY_ISINST: {
536 MonoClass *klass = decode_klass_ref (module, p, &p);
537 if (!klass)
538 return FALSE;
539 ref->method = mono_marshal_get_proxy_cancast (klass);
540 break;
542 case MONO_WRAPPER_LDFLD:
543 case MONO_WRAPPER_LDFLDA:
544 case MONO_WRAPPER_STFLD:
545 case MONO_WRAPPER_ISINST: {
546 MonoClass *klass = decode_klass_ref (module, p, &p);
547 if (!klass)
548 return FALSE;
549 if (wrapper_type == MONO_WRAPPER_LDFLD)
550 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
551 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
552 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
553 else if (wrapper_type == MONO_WRAPPER_STFLD)
554 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
555 else if (wrapper_type == MONO_WRAPPER_ISINST)
556 ref->method = mono_marshal_get_isinst (klass);
557 else
558 g_assert_not_reached ();
559 break;
561 case MONO_WRAPPER_LDFLD_REMOTE:
562 ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
563 break;
564 case MONO_WRAPPER_STFLD_REMOTE:
565 ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
566 break;
567 case MONO_WRAPPER_ALLOC: {
568 int atype = decode_value (p, &p);
570 ref->method = mono_gc_get_managed_allocator_by_type (atype);
571 g_assert (ref->method);
572 break;
574 case MONO_WRAPPER_WRITE_BARRIER:
575 ref->method = mono_gc_get_write_barrier ();
576 break;
577 case MONO_WRAPPER_STELEMREF:
578 ref->method = mono_marshal_get_stelemref ();
579 break;
580 case MONO_WRAPPER_SYNCHRONIZED: {
581 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
583 if (!m)
584 return FALSE;
585 ref->method = mono_marshal_get_synchronized_wrapper (m);
586 break;
588 case MONO_WRAPPER_UNKNOWN: {
589 MonoMethodDesc *desc;
590 MonoMethod *orig_method;
591 int subtype = decode_value (p, &p);
593 if (subtype == MONO_AOT_WRAPPER_PTR_TO_STRUCTURE || subtype == MONO_AOT_WRAPPER_STRUCTURE_TO_PTR) {
594 MonoClass *klass = decode_klass_ref (module, p, &p);
596 if (!klass)
597 return FALSE;
599 g_assert (target);
600 if (klass != target->klass)
601 return FALSE;
603 if (subtype == MONO_AOT_WRAPPER_PTR_TO_STRUCTURE) {
604 if (strcmp (target->name, "PtrToStructure"))
605 return FALSE;
606 ref->method = mono_marshal_get_ptr_to_struct (klass);
607 } else {
608 if (strcmp (target->name, "StructureToPtr"))
609 return FALSE;
610 ref->method = mono_marshal_get_struct_to_ptr (klass);
612 } else {
613 if (subtype == MONO_AOT_WRAPPER_MONITOR_ENTER)
614 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
615 else if (subtype == MONO_AOT_WRAPPER_MONITOR_EXIT)
616 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
617 else if (subtype == MONO_AOT_WRAPPER_MONITOR_ENTER_V4)
618 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
619 else
620 g_assert_not_reached ();
621 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
622 g_assert (orig_method);
623 mono_method_desc_free (desc);
624 ref->method = mono_monitor_get_fast_path (orig_method);
626 break;
628 case MONO_WRAPPER_RUNTIME_INVOKE: {
629 /* Direct wrapper */
630 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
632 if (!m)
633 return FALSE;
634 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
635 break;
637 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
638 int subtype = decode_value (p, &p);
640 if (subtype == MONO_AOT_WRAPPER_ELEMENT_ADDR) {
641 int rank = decode_value (p, &p);
642 int elem_size = decode_value (p, &p);
644 ref->method = mono_marshal_get_array_address (rank, elem_size);
645 } else {
646 g_assert_not_reached ();
648 break;
650 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
651 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
653 if (!m)
654 return FALSE;
656 /* This should only happen when looking for an extra method */
657 g_assert (target);
658 if (mono_marshal_method_from_wrapper (target) == m)
659 ref->method = target;
660 else
661 return FALSE;
662 break;
664 case MONO_WRAPPER_CASTCLASS: {
665 int subtype = decode_value (p, &p);
667 if (subtype == MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE)
668 ref->method = mono_marshal_get_castclass_with_cache ();
669 else if (subtype == MONO_AOT_WRAPPER_ISINST_WITH_CACHE)
670 ref->method = mono_marshal_get_isinst_with_cache ();
671 else
672 g_assert_not_reached ();
673 break;
675 default:
676 g_assert_not_reached ();
678 } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) {
679 if (target)
680 return FALSE;
681 /* Can't decode these */
682 g_assert_not_reached ();
683 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
684 image_index = decode_value (p, &p);
685 ref->token = decode_value (p, &p);
687 image = load_image (module, image_index, TRUE);
688 if (!image)
689 return FALSE;
690 } else if (image_index == MONO_AOT_METHODREF_GINST) {
691 MonoClass *klass;
692 MonoGenericContext ctx;
695 * These methods do not have a token which resolves them, so we
696 * resolve them immediately.
698 klass = decode_klass_ref (module, p, &p);
699 if (!klass)
700 return FALSE;
702 if (target && target->klass != klass)
703 return FALSE;
705 image_index = decode_value (p, &p);
706 ref->token = decode_value (p, &p);
708 image = load_image (module, image_index, TRUE);
709 if (!image)
710 return FALSE;
712 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
713 if (!ref->method)
714 return FALSE;
716 memset (&ctx, 0, sizeof (ctx));
718 if (FALSE && klass->generic_class) {
719 ctx.class_inst = klass->generic_class->context.class_inst;
720 ctx.method_inst = NULL;
722 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
725 memset (&ctx, 0, sizeof (ctx));
727 if (!decode_generic_context (module, &ctx, p, &p))
728 return FALSE;
730 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
731 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
732 MonoClass *klass;
733 int method_type;
735 klass = decode_klass_ref (module, p, &p);
736 if (!klass)
737 return FALSE;
738 method_type = decode_value (p, &p);
739 switch (method_type) {
740 case 0:
741 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
742 break;
743 case 1:
744 ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
745 break;
746 case 2:
747 ref->method = mono_class_get_method_from_name (klass, "Get", -1);
748 break;
749 case 3:
750 ref->method = mono_class_get_method_from_name (klass, "Address", -1);
751 break;
752 case 4:
753 ref->method = mono_class_get_method_from_name (klass, "Set", -1);
754 break;
755 default:
756 g_assert_not_reached ();
758 } else {
759 g_assert (image_index < MONO_AOT_METHODREF_MIN);
760 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
762 image = load_image (module, image_index, TRUE);
763 if (!image)
764 return FALSE;
767 *endbuf = p;
769 ref->image = image;
771 return TRUE;
774 static gboolean
775 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
777 return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
781 * decode_resolve_method_ref_with_target:
783 * Similar to decode_method_ref, but resolve and return the method itself.
785 static MonoMethod*
786 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
788 MethodRef ref;
789 gboolean res;
791 res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
792 if (!res)
793 return NULL;
794 if (ref.method)
795 return ref.method;
796 if (!ref.image)
797 return NULL;
798 return mono_get_method (ref.image, ref.token, NULL);
801 static MonoMethod*
802 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
804 return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
807 static void
808 create_cache_structure (void)
810 const char *home;
811 char *tmp;
812 int err;
814 home = g_get_home_dir ();
815 if (!home)
816 return;
818 tmp = g_build_filename (home, ".mono", NULL);
819 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
820 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
821 #ifdef HOST_WIN32
822 err = mkdir (tmp);
823 #else
824 err = mkdir (tmp, 0777);
825 #endif
826 if (err) {
827 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
828 g_free (tmp);
829 return;
832 g_free (tmp);
833 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
834 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
835 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
836 #ifdef HOST_WIN32
837 err = mkdir (tmp);
838 #else
839 err = mkdir (tmp, 0777);
840 #endif
841 if (err) {
842 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
843 g_free (tmp);
844 return;
847 g_free (tmp);
851 * load_aot_module_from_cache:
853 * Experimental code to AOT compile loaded assemblies on demand.
855 * FIXME:
856 * - Add environment variable MONO_AOT_CACHE_OPTIONS
857 * - Add options for controlling the cache size
858 * - Handle full cache by deleting old assemblies lru style
859 * - Add options for excluding assemblies during development
860 * - Maybe add a threshold after an assembly is AOT compiled
861 * - invoking a new mono process is a security risk
862 * - recompile the AOT module if one of its dependencies changes
864 static MonoDl*
865 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
867 char *fname, *cmd, *tmp2, *aot_options;
868 const char *home;
869 MonoDl *module;
870 gboolean res;
871 gchar *out, *err;
872 gint exit_status;
874 *aot_name = NULL;
876 if (assembly->image->dynamic)
877 return NULL;
879 create_cache_structure ();
881 home = g_get_home_dir ();
883 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
884 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
885 *aot_name = fname;
886 g_free (tmp2);
888 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
889 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
891 if (!module) {
892 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
894 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
896 aot_options = g_strdup_printf ("outfile=%s", fname);
898 if (spawn_compiler) {
899 /* FIXME: security */
900 /* FIXME: Has to pass the assembly loading path to the child process */
901 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
903 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
905 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
906 if (res) {
907 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
908 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
909 else
910 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
911 g_free (out);
912 g_free (err);
914 #endif
915 g_free (cmd);
916 } else {
917 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
918 if (!res) {
919 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
920 } else {
921 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
925 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
927 g_free (aot_options);
930 return module;
933 static void
934 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
936 if (globals) {
937 int global_index;
938 guint16 *table, *entry;
939 guint16 table_size;
940 guint32 hash;
942 /* The first entry points to the hash */
943 table = globals [0];
944 globals ++;
946 table_size = table [0];
947 table ++;
949 hash = mono_metadata_str_hash (name) % table_size;
951 entry = &table [hash * 2];
953 /* Search the hash for the index into the globals table */
954 global_index = -1;
955 while (entry [0] != 0) {
956 guint32 index = entry [0] - 1;
957 guint32 next = entry [1];
959 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
961 if (!strcmp (globals [index * 2], name)) {
962 global_index = index;
963 break;
966 if (next != 0) {
967 entry = &table [next * 2];
968 } else {
969 break;
973 if (global_index != -1)
974 *value = globals [global_index * 2 + 1];
975 else
976 *value = NULL;
977 } else {
978 char *err = mono_dl_symbol (module, name, value);
980 if (err)
981 g_free (err);
985 static gboolean
986 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
988 char *build_info;
989 char *msg = NULL;
990 gboolean usable = TRUE;
991 gboolean full_aot;
992 guint8 *blob;
994 if (strcmp (assembly->image->guid, info->assembly_guid)) {
995 msg = g_strdup_printf ("doesn't match assembly");
996 usable = FALSE;
999 build_info = mono_get_runtime_build_info ();
1000 if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1001 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1002 usable = FALSE;
1004 g_free (build_info);
1006 full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1008 if (mono_aot_only && !full_aot) {
1009 msg = g_strdup_printf ("not compiled with --aot=full");
1010 usable = FALSE;
1012 if (!mono_aot_only && full_aot) {
1013 msg = g_strdup_printf ("compiled with --aot=full");
1014 usable = FALSE;
1016 #ifdef TARGET_ARM
1017 /* mono_arch_find_imt_method () requires this */
1018 if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1019 msg = g_strdup_printf ("compiled against LLVM");
1020 usable = FALSE;
1022 if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1023 msg = g_strdup_printf ("not compiled against LLVM");
1024 usable = FALSE;
1026 #endif
1027 if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1028 msg = g_strdup_printf ("not compiled for debugging");
1029 usable = FALSE;
1032 blob = info->blob;
1034 if (info->gc_name_index != -1) {
1035 char *gc_name = (char*)&blob [info->gc_name_index];
1036 const char *current_gc_name = mono_gc_get_gc_name ();
1038 if (strcmp (current_gc_name, gc_name) != 0) {
1039 msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1040 usable = FALSE;
1044 *out_msg = msg;
1045 return usable;
1048 static void
1049 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1051 char *aot_name;
1052 MonoAotModule *amodule;
1053 MonoDl *sofile;
1054 gboolean usable = TRUE;
1055 char *version_symbol = NULL;
1056 char *msg = NULL;
1057 gpointer *globals = NULL;
1058 MonoAotFileInfo *info = NULL;
1059 int i, version;
1060 guint8 *blob;
1061 gboolean do_load_image = TRUE;
1063 if (mono_compile_aot)
1064 return;
1066 if (assembly->image->aot_module)
1068 * Already loaded. This can happen because the assembly loading code might invoke
1069 * the assembly load hooks multiple times for the same assembly.
1071 return;
1073 if (assembly->image->dynamic)
1074 return;
1076 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
1077 return;
1079 mono_aot_lock ();
1080 if (static_aot_modules)
1081 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1082 else
1083 info = NULL;
1084 mono_aot_unlock ();
1086 if (info) {
1087 /* Statically linked AOT module */
1088 sofile = NULL;
1089 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1090 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1091 globals = info->globals;
1092 } else {
1093 if (use_aot_cache)
1094 sofile = load_aot_module_from_cache (assembly, &aot_name);
1095 else {
1096 char *err;
1097 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1099 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1101 if (!sofile) {
1102 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1103 g_free (err);
1108 if (!sofile && !globals) {
1109 if (mono_aot_only) {
1110 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1111 exit (1);
1113 g_free (aot_name);
1114 return;
1117 if (!info) {
1118 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1119 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1122 if (version_symbol) {
1123 /* Old file format */
1124 version = atoi (version_symbol);
1125 } else {
1126 g_assert (info);
1127 version = info->version;
1130 if (version != MONO_AOT_FILE_VERSION) {
1131 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1132 usable = FALSE;
1133 } else {
1134 usable = check_usable (assembly, info, &msg);
1137 if (!usable) {
1138 if (mono_aot_only) {
1139 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1140 exit (1);
1141 } else {
1142 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1144 g_free (msg);
1145 g_free (aot_name);
1146 if (sofile)
1147 mono_dl_close (sofile);
1148 assembly->image->aot_module = NULL;
1149 return;
1152 /* Sanity check */
1153 g_assert (info->double_align == __alignof__ (double));
1154 g_assert (info->long_align == __alignof__ (gint64));
1156 blob = info->blob;
1158 amodule = g_new0 (MonoAotModule, 1);
1159 amodule->aot_name = aot_name;
1160 amodule->assembly = assembly;
1162 memcpy (&amodule->info, info, sizeof (*info));
1164 amodule->got = amodule->info.got;
1165 amodule->got [0] = assembly->image;
1166 amodule->globals = globals;
1167 amodule->sofile = sofile;
1168 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1169 amodule->blob = blob;
1171 /* Read image table */
1173 guint32 table_len, i;
1174 char *table = NULL;
1176 table = info->image_table;
1177 g_assert (table);
1179 table_len = *(guint32*)table;
1180 table += sizeof (guint32);
1181 amodule->image_table = g_new0 (MonoImage*, table_len);
1182 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1183 amodule->image_guids = g_new0 (char*, table_len);
1184 amodule->image_table_len = table_len;
1185 for (i = 0; i < table_len; ++i) {
1186 MonoAssemblyName *aname = &(amodule->image_names [i]);
1188 aname->name = g_strdup (table);
1189 table += strlen (table) + 1;
1190 amodule->image_guids [i] = g_strdup (table);
1191 table += strlen (table) + 1;
1192 if (table [0] != 0)
1193 aname->culture = g_strdup (table);
1194 table += strlen (table) + 1;
1195 memcpy (aname->public_key_token, table, strlen (table) + 1);
1196 table += strlen (table) + 1;
1198 table = ALIGN_PTR_TO (table, 8);
1199 aname->flags = *(guint32*)table;
1200 table += 4;
1201 aname->major = *(guint32*)table;
1202 table += 4;
1203 aname->minor = *(guint32*)table;
1204 table += 4;
1205 aname->build = *(guint32*)table;
1206 table += 4;
1207 aname->revision = *(guint32*)table;
1208 table += 4;
1212 amodule->code_offsets = info->code_offsets;
1213 amodule->code = info->methods;
1214 #ifdef TARGET_ARM
1215 /* Mask out thumb interop bit */
1216 amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1217 #endif
1218 amodule->code_end = info->methods_end;
1219 amodule->method_info_offsets = info->method_info_offsets;
1220 amodule->ex_info_offsets = info->ex_info_offsets;
1221 amodule->class_info_offsets = info->class_info_offsets;
1222 amodule->class_name_table = info->class_name_table;
1223 amodule->extra_method_table = info->extra_method_table;
1224 amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1225 amodule->unbox_trampolines = info->unbox_trampolines;
1226 amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1227 amodule->got_info_offsets = info->got_info_offsets;
1228 amodule->unwind_info = info->unwind_info;
1229 amodule->mem_end = info->mem_end;
1230 amodule->mem_begin = amodule->code;
1231 amodule->plt = info->plt;
1232 amodule->plt_end = info->plt_end;
1233 amodule->mono_eh_frame = info->mono_eh_frame;
1234 amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1235 amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1236 amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1237 amodule->thumb_end = info->thumb_end;
1239 if (make_unreadable) {
1240 #ifndef TARGET_WIN32
1241 guint8 *addr;
1242 guint8 *page_start, *page_end;
1243 int err, len;
1245 addr = amodule->mem_begin;
1246 len = amodule->mem_end - amodule->mem_begin;
1248 /* Round down in both directions to avoid modifying data which is not ours */
1249 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1250 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1251 if (page_end > page_start) {
1252 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1253 g_assert (err == 0);
1255 #endif
1258 mono_aot_lock ();
1260 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1261 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1263 g_hash_table_insert (aot_modules, assembly, amodule);
1264 mono_aot_unlock ();
1266 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1268 assembly->image->aot_module = amodule;
1270 if (mono_aot_only) {
1271 if (mono_defaults.corlib) {
1272 /* The second got slot contains the mscorlib got addr */
1273 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1275 amodule->got [1] = mscorlib_amodule->got;
1276 } else {
1277 amodule->got [1] = amodule->got;
1281 if (mono_gc_is_moving ()) {
1282 MonoJumpInfo ji;
1284 memset (&ji, 0, sizeof (ji));
1285 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1287 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1291 * Since we store methoddef and classdef tokens when referring to methods/classes in
1292 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1293 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1294 * non-lazily, since we can't handle out-of-date errors later.
1295 * The cached class info also depends on the exact assemblies.
1297 #if defined(__native_client__)
1298 /* TODO: Don't 'load_image' on mscorlib due to a */
1299 /* recursive loading problem. This should be */
1300 /* removed if mscorlib is loaded from disk. */
1301 if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1302 do_load_image = TRUE;
1303 } else {
1304 do_load_image = FALSE;
1306 #endif
1307 if (do_load_image) {
1308 for (i = 0; i < amodule->image_table_len; ++i)
1309 load_image (amodule, i, FALSE);
1312 if (amodule->out_of_date) {
1313 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);
1314 if (mono_aot_only) {
1315 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);
1316 exit (1);
1319 else
1320 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1324 * mono_aot_register_globals:
1326 * This is called by the ctor function in AOT images compiled with the
1327 * 'no-dlsym' option.
1329 void
1330 mono_aot_register_globals (gpointer *globals)
1332 g_assert_not_reached ();
1336 * mono_aot_register_module:
1338 * This should be called by embedding code to register AOT modules statically linked
1339 * into the executable. AOT_INFO should be the value of the
1340 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1342 void
1343 mono_aot_register_module (gpointer *aot_info)
1345 gpointer *globals;
1346 char *aname;
1347 MonoAotFileInfo *info = (gpointer)aot_info;
1349 g_assert (info->version == MONO_AOT_FILE_VERSION);
1351 globals = info->globals;
1352 g_assert (globals);
1354 aname = info->assembly_name;
1356 /* This could be called before startup */
1357 if (aot_modules)
1358 mono_aot_lock ();
1360 if (!static_aot_modules)
1361 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1363 g_hash_table_insert (static_aot_modules, aname, info);
1365 if (aot_modules)
1366 mono_aot_unlock ();
1369 void
1370 mono_aot_init (void)
1372 InitializeCriticalSection (&aot_mutex);
1373 aot_modules = g_hash_table_new (NULL, NULL);
1375 mono_install_assembly_load_hook (load_aot_module, NULL);
1377 if (g_getenv ("MONO_LASTAOT"))
1378 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1379 if (g_getenv ("MONO_AOT_CACHE"))
1380 use_aot_cache = TRUE;
1383 void
1384 mono_aot_cleanup (void)
1386 if (aot_jit_icall_hash)
1387 g_hash_table_destroy (aot_jit_icall_hash);
1388 if (aot_modules)
1389 g_hash_table_destroy (aot_modules);
1392 static gboolean
1393 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1395 guint32 flags;
1396 MethodRef ref;
1397 gboolean res;
1399 info->vtable_size = decode_value (buf, &buf);
1400 if (info->vtable_size == -1)
1401 /* Generic type */
1402 return FALSE;
1403 flags = decode_value (buf, &buf);
1404 info->ghcimpl = (flags >> 0) & 0x1;
1405 info->has_finalize = (flags >> 1) & 0x1;
1406 info->has_cctor = (flags >> 2) & 0x1;
1407 info->has_nested_classes = (flags >> 3) & 0x1;
1408 info->blittable = (flags >> 4) & 0x1;
1409 info->has_references = (flags >> 5) & 0x1;
1410 info->has_static_refs = (flags >> 6) & 0x1;
1411 info->no_special_static_fields = (flags >> 7) & 0x1;
1412 info->is_generic_container = (flags >> 8) & 0x1;
1414 if (info->has_cctor) {
1415 res = decode_method_ref (module, &ref, buf, &buf);
1416 if (!res)
1417 return FALSE;
1418 info->cctor_token = ref.token;
1420 if (info->has_finalize) {
1421 res = decode_method_ref (module, &ref, buf, &buf);
1422 if (!res)
1423 return FALSE;
1424 info->finalize_image = ref.image;
1425 info->finalize_token = ref.token;
1428 info->instance_size = decode_value (buf, &buf);
1429 info->class_size = decode_value (buf, &buf);
1430 info->packing_size = decode_value (buf, &buf);
1431 info->min_align = decode_value (buf, &buf);
1433 *endbuf = buf;
1435 return TRUE;
1438 gpointer
1439 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1441 int i;
1442 MonoClass *klass = vtable->klass;
1443 MonoAotModule *amodule = klass->image->aot_module;
1444 guint8 *info, *p;
1445 MonoCachedClassInfo class_info;
1446 gboolean err;
1447 MethodRef ref;
1448 gboolean res;
1450 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
1451 return NULL;
1453 info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1454 p = info;
1456 err = decode_cached_class_info (amodule, &class_info, p, &p);
1457 if (!err)
1458 return NULL;
1460 for (i = 0; i < slot; ++i)
1461 decode_method_ref (amodule, &ref, p, &p);
1463 res = decode_method_ref (amodule, &ref, p, &p);
1464 if (!res)
1465 return NULL;
1466 if (ref.no_aot_trampoline)
1467 return NULL;
1469 if (mono_metadata_token_index (ref.token) == 0)
1470 return NULL;
1472 return mono_aot_get_method_from_token (domain, ref.image, ref.token);
1475 gboolean
1476 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1478 MonoAotModule *amodule = klass->image->aot_module;
1479 guint8 *p;
1480 gboolean err;
1482 if (klass->rank || !amodule)
1483 return FALSE;
1485 p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1487 err = decode_cached_class_info (amodule, res, p, &p);
1488 if (!err)
1489 return FALSE;
1491 return TRUE;
1495 * mono_aot_get_class_from_name:
1497 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1498 * using a cache stored in the AOT file.
1499 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1501 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
1502 * found.
1504 gboolean
1505 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1507 MonoAotModule *amodule = image->aot_module;
1508 guint16 *table, *entry;
1509 guint16 table_size;
1510 guint32 hash;
1511 char full_name_buf [1024];
1512 char *full_name;
1513 const char *name2, *name_space2;
1514 MonoTableInfo *t;
1515 guint32 cols [MONO_TYPEDEF_SIZE];
1516 GHashTable *nspace_table;
1518 if (!amodule || !amodule->class_name_table)
1519 return FALSE;
1521 mono_aot_lock ();
1523 *klass = NULL;
1525 /* First look in the cache */
1526 if (!amodule->name_cache)
1527 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1528 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1529 if (nspace_table) {
1530 *klass = g_hash_table_lookup (nspace_table, name);
1531 if (*klass) {
1532 mono_aot_unlock ();
1533 return TRUE;
1537 table_size = amodule->class_name_table [0];
1538 table = amodule->class_name_table + 1;
1540 if (name_space [0] == '\0')
1541 full_name = g_strdup_printf ("%s", name);
1542 else {
1543 if (strlen (name_space) + strlen (name) < 1000) {
1544 sprintf (full_name_buf, "%s.%s", name_space, name);
1545 full_name = full_name_buf;
1546 } else {
1547 full_name = g_strdup_printf ("%s.%s", name_space, name);
1550 hash = mono_metadata_str_hash (full_name) % table_size;
1551 if (full_name != full_name_buf)
1552 g_free (full_name);
1554 entry = &table [hash * 2];
1556 if (entry [0] != 0) {
1557 t = &image->tables [MONO_TABLE_TYPEDEF];
1559 while (TRUE) {
1560 guint32 index = entry [0];
1561 guint32 next = entry [1];
1562 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1564 name_table_accesses ++;
1566 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1568 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1569 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1571 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1572 mono_aot_unlock ();
1573 *klass = mono_class_get (image, token);
1575 /* Add to cache */
1576 if (*klass) {
1577 mono_aot_lock ();
1578 nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1579 if (!nspace_table) {
1580 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1581 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
1583 g_hash_table_insert (nspace_table, (char*)name2, *klass);
1584 mono_aot_unlock ();
1586 return TRUE;
1589 if (next != 0) {
1590 entry = &table [next * 2];
1591 } else {
1592 break;
1597 mono_aot_unlock ();
1599 return TRUE;
1603 * decode_mono_eh_frame:
1605 * Decode the EH information emitted by our modified LLVM compiler and construct a
1606 * MonoJitInfo structure from it.
1607 * LOCKING: Acquires the domain lock.
1609 static MonoJitInfo*
1610 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
1611 MonoMethod *method, guint8 *code,
1612 MonoJitExceptionInfo *clauses, int num_clauses,
1613 int extra_size, GSList **nesting,
1614 int *this_reg, int *this_offset)
1616 guint8 *p;
1617 guint8 *fde, *cie, *code_start, *code_end;
1618 int version, fde_count;
1619 gint32 *table;
1620 int i, j, pos, left, right, offset, offset1, offset2, code_len;
1621 MonoJitExceptionInfo *ei;
1622 guint32 fde_len, ei_len, nested_len, nindex;
1623 gpointer *type_info;
1624 MonoJitInfo *jinfo;
1625 MonoLLVMFDEInfo info;
1627 g_assert (amodule->mono_eh_frame);
1629 p = amodule->mono_eh_frame;
1631 /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
1633 /* Header */
1634 version = *p;
1635 g_assert (version == 1);
1636 p ++;
1637 p = ALIGN_PTR_TO (p, 4);
1639 fde_count = *(guint32*)p;
1640 p += 4;
1641 table = (gint32*)p;
1643 /* There is +1 entry in the table */
1644 cie = p + ((fde_count + 1) * 8);
1646 /* Binary search in the table to find the entry for code */
1647 offset = code - amodule->mono_eh_frame;
1649 left = 0;
1650 right = fde_count;
1651 while (TRUE) {
1652 pos = (left + right) / 2;
1654 offset1 = table [(pos * 2)];
1655 if (pos + 1 == fde_count)
1656 /* FIXME: */
1657 offset2 = amodule->code_end - amodule->code;
1658 else
1659 offset2 = table [(pos + 1) * 2];
1661 if (offset < offset1)
1662 right = pos;
1663 else if (offset >= offset2)
1664 left = pos + 1;
1665 else
1666 break;
1669 code_start = amodule->mono_eh_frame + table [(pos * 2)];
1670 /* This won't overflow because there is +1 entry in the table */
1671 code_end = amodule->mono_eh_frame + table [(pos * 2) + 2];
1672 code_len = code_end - code_start;
1674 g_assert (code >= code_start && code < code_end);
1676 fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
1677 /* This won't overflow because there is +1 entry in the table */
1678 fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
1680 mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
1681 ei = info.ex_info;
1682 ei_len = info.ex_info_len;
1683 type_info = info.type_info;
1684 *this_reg = info.this_reg;
1685 *this_offset = info.this_offset;
1687 /* Count number of nested clauses */
1688 nested_len = 0;
1689 for (i = 0; i < ei_len; ++i) {
1690 /* This might be unaligned */
1691 gint32 cindex1 = read32 (type_info [i]);
1692 GSList *l;
1694 for (l = nesting [cindex1]; l; l = l->next) {
1695 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
1697 for (j = 0; j < ei_len; ++j) {
1698 gint32 cindex2 = read32 (type_info [j]);
1700 if (cindex2 == nesting_cindex)
1701 nested_len ++;
1707 * LLVM might represent one IL region with multiple regions, so have to
1708 * allocate a new JI.
1710 jinfo =
1711 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
1713 jinfo->code_size = code_len;
1714 jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
1715 jinfo->method = method;
1716 jinfo->code_start = code;
1717 jinfo->domain_neutral = 0;
1718 /* This signals that used_regs points to a normal cached unwind info */
1719 jinfo->from_aot = 0;
1720 jinfo->num_clauses = ei_len + nested_len;
1722 for (i = 0; i < ei_len; ++i) {
1724 * orig_jinfo contains the original IL exception info saved by the AOT
1725 * compiler, we have to combine that with the information produced by LLVM
1727 /* The type_info entries contain IL clause indexes */
1728 int clause_index = read32 (type_info [i]);
1729 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
1730 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
1732 g_assert (clause_index < num_clauses);
1733 jei->flags = orig_jei->flags;
1734 jei->data.catch_class = orig_jei->data.catch_class;
1736 jei->try_start = ei [i].try_start;
1737 jei->try_end = ei [i].try_end;
1738 jei->handler_start = ei [i].handler_start;
1740 /* Make sure we transition to thumb when a handler starts */
1741 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
1742 jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
1745 /* See exception_cb () in mini-llvm.c as to why this is needed */
1746 nindex = ei_len;
1747 for (i = 0; i < ei_len; ++i) {
1748 gint32 cindex1 = read32 (type_info [i]);
1749 GSList *l;
1751 for (l = nesting [cindex1]; l; l = l->next) {
1752 gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
1754 for (j = 0; j < ei_len; ++j) {
1755 gint32 cindex2 = read32 (type_info [j]);
1757 if (cindex2 == nesting_cindex) {
1759 * The try interval comes from the nested clause, everything else from the
1760 * nesting clause.
1762 memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
1763 jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
1764 jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
1765 nindex ++;
1770 g_assert (nindex == ei_len + nested_len);
1772 return jinfo;
1776 * LOCKING: Acquires the domain lock.
1778 static MonoJitInfo*
1779 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
1780 MonoMethod *method, guint8* ex_info, guint8 *addr,
1781 guint8 *code, guint32 code_len)
1783 int i, buf_len, num_clauses;
1784 MonoJitInfo *jinfo;
1785 guint used_int_regs, flags;
1786 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes;
1787 gboolean from_llvm, has_gc_map;
1788 guint8 *p;
1789 int generic_info_size, try_holes_info_size, num_holes, this_reg = 0, this_offset = 0;
1791 /* Load the method info from the AOT file */
1793 p = ex_info;
1794 flags = decode_value (p, &p);
1795 has_generic_jit_info = (flags & 1) != 0;
1796 has_dwarf_unwind_info = (flags & 2) != 0;
1797 has_clauses = (flags & 4) != 0;
1798 has_seq_points = (flags & 8) != 0;
1799 from_llvm = (flags & 16) != 0;
1800 has_try_block_holes = (flags & 32) != 0;
1801 has_gc_map = (flags & 64) != 0;
1803 if (has_dwarf_unwind_info) {
1804 guint32 offset;
1806 offset = decode_value (p, &p);
1807 g_assert (offset < (1 << 30));
1808 used_int_regs = offset;
1809 } else {
1810 used_int_regs = decode_value (p, &p);
1812 if (has_generic_jit_info)
1813 generic_info_size = sizeof (MonoGenericJitInfo);
1814 else
1815 generic_info_size = 0;
1817 if (has_try_block_holes) {
1818 num_holes = decode_value (p, &p);
1819 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
1820 } else {
1821 num_holes = try_holes_info_size = 0;
1823 /* Exception table */
1824 if (has_clauses)
1825 num_clauses = decode_value (p, &p);
1826 else
1827 num_clauses = 0;
1829 if (from_llvm) {
1830 MonoJitExceptionInfo *clauses;
1831 GSList **nesting;
1834 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
1835 * section.
1837 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
1838 nesting = g_new0 (GSList*, num_clauses);
1840 for (i = 0; i < num_clauses; ++i) {
1841 MonoJitExceptionInfo *ei = &clauses [i];
1843 ei->flags = decode_value (p, &p);
1845 if (decode_value (p, &p))
1846 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1848 /* Read the list of nesting clauses */
1849 while (TRUE) {
1850 int nesting_index = decode_value (p, &p);
1851 if (nesting_index == -1)
1852 break;
1853 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
1857 jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size, nesting, &this_reg, &this_offset);
1858 jinfo->from_llvm = 1;
1860 g_free (clauses);
1861 for (i = 0; i < num_clauses; ++i)
1862 g_slist_free (nesting [i]);
1863 g_free (nesting);
1864 } else {
1865 jinfo =
1866 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size);
1867 jinfo->num_clauses = num_clauses;
1869 for (i = 0; i < jinfo->num_clauses; ++i) {
1870 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
1872 ei->flags = decode_value (p, &p);
1874 ei->exvar_offset = decode_value (p, &p);
1876 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
1877 ei->data.filter = code + decode_value (p, &p);
1878 else {
1879 if (decode_value (p, &p))
1880 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1883 ei->try_start = code + decode_value (p, &p);
1884 ei->try_end = code + decode_value (p, &p);
1885 ei->handler_start = code + decode_value (p, &p);
1888 jinfo->code_size = code_len;
1889 jinfo->used_regs = used_int_regs;
1890 jinfo->method = method;
1891 jinfo->code_start = code;
1892 jinfo->domain_neutral = 0;
1893 jinfo->from_aot = 1;
1896 if (has_generic_jit_info) {
1897 MonoGenericJitInfo *gi;
1899 jinfo->has_generic_jit_info = 1;
1901 gi = mono_jit_info_get_generic_jit_info (jinfo);
1902 g_assert (gi);
1904 if (from_llvm) {
1905 gi->has_this = this_reg != -1;
1906 gi->this_reg = this_reg;
1907 gi->this_offset = this_offset;
1908 } else {
1909 gi->has_this = decode_value (p, &p);
1910 gi->this_reg = decode_value (p, &p);
1911 gi->this_offset = decode_value (p, &p);
1914 /* This currently contains no data */
1915 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
1917 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
1920 if (has_try_block_holes) {
1921 MonoTryBlockHoleTableJitInfo *table;
1923 jinfo->has_try_block_holes = 1;
1925 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
1926 g_assert (table);
1928 table->num_holes = (guint16)num_holes;
1929 for (i = 0; i < num_holes; ++i) {
1930 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
1931 hole->clause = decode_value (p, &p);
1932 hole->length = decode_value (p, &p);
1933 hole->offset = decode_value (p, &p);
1937 if (has_seq_points) {
1938 MonoSeqPointInfo *seq_points;
1939 int il_offset, native_offset, last_il_offset, last_native_offset, j;
1941 int len = decode_value (p, &p);
1943 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
1944 seq_points->len = len;
1945 last_il_offset = last_native_offset = 0;
1946 for (i = 0; i < len; ++i) {
1947 SeqPoint *sp = &seq_points->seq_points [i];
1948 il_offset = last_il_offset + decode_value (p, &p);
1949 native_offset = last_native_offset + decode_value (p, &p);
1951 sp->il_offset = il_offset;
1952 sp->native_offset = native_offset;
1954 sp->next_len = decode_value (p, &p);
1955 sp->next = g_new (int, sp->next_len);
1956 for (j = 0; j < sp->next_len; ++j)
1957 sp->next [j] = decode_value (p, &p);
1959 last_il_offset = il_offset;
1960 last_native_offset = native_offset;
1963 mono_domain_lock (domain);
1964 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
1965 mono_domain_unlock (domain);
1968 /* Load debug info */
1969 buf_len = decode_value (p, &p);
1970 mono_debug_add_aot_method (domain, method, code, p, buf_len);
1971 p += buf_len;
1973 if (has_gc_map) {
1974 int map_size = decode_value (p, &p);
1975 /* The GC map requires 4 bytes of alignment */
1976 while ((guint64)(gsize)p % 4)
1977 p ++;
1978 jinfo->gc_info = p;
1979 p += map_size;
1982 if (amodule != jinfo->method->klass->image->aot_module) {
1983 mono_aot_lock ();
1984 if (!ji_to_amodule)
1985 ji_to_amodule = g_hash_table_new (NULL, NULL);
1986 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
1987 mono_aot_unlock ();
1990 return jinfo;
1994 * mono_aot_get_unwind_info:
1996 * Return a pointer to the DWARF unwind info belonging to JI.
1998 guint8*
1999 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2001 MonoAotModule *amodule = ji->method->klass->image->aot_module;
2002 guint8 *p;
2003 guint8 *code = ji->code_start;
2005 g_assert (amodule);
2006 g_assert (ji->from_aot);
2008 if (!(code >= amodule->code && code <= amodule->code_end)) {
2009 /* ji belongs to a different aot module than amodule */
2010 mono_aot_lock ();
2011 g_assert (ji_to_amodule);
2012 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2013 g_assert (amodule);
2014 g_assert (code >= amodule->code && code <= amodule->code_end);
2015 mono_aot_unlock ();
2018 p = amodule->unwind_info + ji->used_regs;
2019 *unwind_info_len = decode_value (p, &p);
2020 return p;
2023 static G_GNUC_UNUSED int
2024 compare_ints (const void *a, const void *b)
2026 return *(gint32*)a - *(gint32*)b;
2029 static void
2030 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2032 int mid = (lo + hi) / 2;
2033 int i, t_lo, t_hi;
2035 if (lo >= hi)
2036 return;
2038 if (hi - lo < 32) {
2039 for (i = lo; i < hi; ++i)
2040 if (array [(i * 2)] > array [(i * 2) + 2])
2041 break;
2042 if (i == hi)
2043 /* Already sorted */
2044 return;
2047 msort_code_offsets_internal (array, lo, mid, scratch);
2048 msort_code_offsets_internal (array, mid + 1, hi, scratch);
2050 if (array [mid * 2] < array [(mid + 1) * 2])
2051 return;
2053 /* Merge */
2054 t_lo = lo;
2055 t_hi = mid + 1;
2056 for (i = lo; i <= hi; i ++) {
2057 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2058 scratch [(i * 2)] = array [t_lo * 2];
2059 scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2060 t_lo ++;
2061 } else {
2062 scratch [(i * 2)] = array [t_hi * 2];
2063 scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2064 t_hi ++;
2067 for (i = lo; i <= hi; ++i) {
2068 array [(i * 2)] = scratch [i * 2];
2069 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2073 static void
2074 msort_code_offsets (gint32 *array, int len)
2076 gint32 *scratch;
2078 scratch = g_new (gint32, len * 2);
2079 msort_code_offsets_internal (array, 0, len - 1, scratch);
2080 g_free (scratch);
2083 MonoJitInfo *
2084 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2086 int pos, left, right, offset, offset1, offset2, code_len;
2087 int method_index, table_len, is_wrapper;
2088 guint32 token;
2089 MonoAotModule *amodule = image->aot_module;
2090 MonoMethod *method;
2091 MonoJitInfo *jinfo;
2092 guint8 *code, *ex_info, *p;
2093 guint32 *table;
2094 int nmethods = amodule->info.nmethods;
2095 gint32 *code_offsets;
2096 int offsets_len, i;
2098 if (!amodule)
2099 return NULL;
2101 if (domain != mono_get_root_domain ())
2102 /* FIXME: */
2103 return NULL;
2105 offset = (guint8*)addr - amodule->code;
2107 /* Compute a sorted table mapping code offsets to method indexes. */
2108 if (!amodule->sorted_code_offsets) {
2109 code_offsets = g_new0 (gint32, nmethods * 2);
2110 offsets_len = 0;
2111 for (i = 0; i < nmethods; ++i) {
2112 /* Skip the -1 entries to speed up sorting */
2113 if (amodule->code_offsets [i] == 0xffffffff)
2114 continue;
2115 code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2116 code_offsets [(offsets_len *2) + 1] = i;
2117 offsets_len ++;
2119 /* Use a merge sort as this is mostly sorted */
2120 msort_code_offsets (code_offsets, offsets_len);
2121 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2122 for (i = 0; i < offsets_len -1; ++i)
2123 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2125 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2126 /* Somebody got in before us */
2127 g_free (code_offsets);
2128 amodule->sorted_code_offsets_len = offsets_len;
2131 code_offsets = amodule->sorted_code_offsets;
2132 offsets_len = amodule->sorted_code_offsets_len;
2134 /* Binary search in the sorted_code_offsets table */
2135 left = 0;
2136 right = offsets_len;
2137 while (TRUE) {
2138 pos = (left + right) / 2;
2140 offset1 = code_offsets [(pos * 2)];
2141 if (pos + 1 == offsets_len)
2142 offset2 = amodule->code_end - amodule->code;
2143 else
2144 offset2 = code_offsets [(pos + 1) * 2];
2146 if (offset < offset1)
2147 right = pos;
2148 else if (offset >= offset2)
2149 left = pos + 1;
2150 else
2151 break;
2154 g_assert (offset >= code_offsets [(pos * 2)]);
2155 if (pos + 1 < offsets_len)
2156 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2157 method_index = code_offsets [(pos * 2) + 1];
2159 code = &amodule->code [amodule->code_offsets [method_index]];
2160 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2162 if (pos == offsets_len - 1)
2163 code_len = amodule->code_end - code;
2164 else
2165 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2167 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2169 /* Might be a wrapper/extra method */
2170 if (amodule->extra_methods) {
2171 mono_aot_lock ();
2172 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2173 mono_aot_unlock ();
2174 } else {
2175 method = NULL;
2178 if (!method) {
2179 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2181 * This is hit for extra methods which are called directly, so they are
2182 * not in amodule->extra_methods.
2184 table_len = amodule->extra_method_info_offsets [0];
2185 table = amodule->extra_method_info_offsets + 1;
2186 left = 0;
2187 right = table_len;
2188 pos = 0;
2190 /* Binary search */
2191 while (TRUE) {
2192 pos = ((left + right) / 2);
2194 g_assert (pos < table_len);
2196 if (table [pos * 2] < method_index)
2197 left = pos + 1;
2198 else if (table [pos * 2] > method_index)
2199 right = pos;
2200 else
2201 break;
2204 p = amodule->blob + table [(pos * 2) + 1];
2205 is_wrapper = decode_value (p, &p);
2206 g_assert (!is_wrapper);
2207 method = decode_resolve_method_ref (amodule, p, &p);
2208 g_assert (method);
2209 } else {
2210 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2211 method = mono_get_method (image, token, NULL);
2215 /* FIXME: */
2216 g_assert (method);
2218 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2220 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2222 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2223 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2225 /* Add it to the normal JitInfo tables */
2226 mono_jit_info_table_add (domain, jinfo);
2228 return jinfo;
2231 static gboolean
2232 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2234 guint8 *p = buf;
2235 gpointer *table;
2236 MonoImage *image;
2237 int i;
2239 switch (ji->type) {
2240 case MONO_PATCH_INFO_METHOD:
2241 case MONO_PATCH_INFO_METHOD_JUMP:
2242 case MONO_PATCH_INFO_ICALL_ADDR:
2243 case MONO_PATCH_INFO_METHOD_RGCTX: {
2244 MethodRef ref;
2245 gboolean res;
2247 res = decode_method_ref (aot_module, &ref, p, &p);
2248 if (!res)
2249 goto cleanup;
2251 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)) {
2252 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2253 ji->type = MONO_PATCH_INFO_ABS;
2255 else {
2256 if (ref.method)
2257 ji->data.method = ref.method;
2258 else
2259 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2260 g_assert (ji->data.method);
2261 mono_class_init (ji->data.method->klass);
2263 break;
2265 case MONO_PATCH_INFO_INTERNAL_METHOD:
2266 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2267 guint32 len = decode_value (p, &p);
2269 ji->data.name = (char*)p;
2270 p += len + 1;
2271 break;
2273 case MONO_PATCH_INFO_METHODCONST:
2274 /* Shared */
2275 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2276 if (!ji->data.method)
2277 goto cleanup;
2278 break;
2279 case MONO_PATCH_INFO_VTABLE:
2280 case MONO_PATCH_INFO_CLASS:
2281 case MONO_PATCH_INFO_IID:
2282 case MONO_PATCH_INFO_ADJUSTED_IID:
2283 /* Shared */
2284 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2285 if (!ji->data.klass)
2286 goto cleanup;
2287 break;
2288 case MONO_PATCH_INFO_CLASS_INIT:
2289 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2290 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2291 if (!ji->data.klass)
2292 goto cleanup;
2293 break;
2294 case MONO_PATCH_INFO_IMAGE:
2295 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2296 if (!ji->data.image)
2297 goto cleanup;
2298 break;
2299 case MONO_PATCH_INFO_FIELD:
2300 case MONO_PATCH_INFO_SFLDA:
2301 /* Shared */
2302 ji->data.field = decode_field_info (aot_module, p, &p);
2303 if (!ji->data.field)
2304 goto cleanup;
2305 break;
2306 case MONO_PATCH_INFO_SWITCH:
2307 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2308 ji->data.table->table_size = decode_value (p, &p);
2309 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2310 ji->data.table->table = (MonoBasicBlock**)table;
2311 for (i = 0; i < ji->data.table->table_size; i++)
2312 table [i] = (gpointer)(gssize)decode_value (p, &p);
2313 break;
2314 case MONO_PATCH_INFO_R4: {
2315 guint32 val;
2317 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2318 val = decode_value (p, &p);
2319 *(float*)ji->data.target = *(float*)&val;
2320 break;
2322 case MONO_PATCH_INFO_R8: {
2323 guint32 val [2];
2324 guint64 v;
2326 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2328 val [0] = decode_value (p, &p);
2329 val [1] = decode_value (p, &p);
2330 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2331 *(double*)ji->data.target = *(double*)&v;
2332 break;
2334 case MONO_PATCH_INFO_LDSTR:
2335 image = load_image (aot_module, decode_value (p, &p), TRUE);
2336 if (!image)
2337 goto cleanup;
2338 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2339 break;
2340 case MONO_PATCH_INFO_RVA:
2341 case MONO_PATCH_INFO_DECLSEC:
2342 case MONO_PATCH_INFO_LDTOKEN:
2343 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2344 /* Shared */
2345 image = load_image (aot_module, decode_value (p, &p), TRUE);
2346 if (!image)
2347 goto cleanup;
2348 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2350 ji->data.token->has_context = decode_value (p, &p);
2351 if (ji->data.token->has_context) {
2352 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2353 if (!res)
2354 goto cleanup;
2356 break;
2357 case MONO_PATCH_INFO_EXC_NAME:
2358 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2359 if (!ji->data.klass)
2360 goto cleanup;
2361 ji->data.name = ji->data.klass->name;
2362 break;
2363 case MONO_PATCH_INFO_METHOD_REL:
2364 ji->data.offset = decode_value (p, &p);
2365 break;
2366 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2367 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2368 case MONO_PATCH_INFO_MONITOR_ENTER:
2369 case MONO_PATCH_INFO_MONITOR_EXIT:
2370 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
2371 case MONO_PATCH_INFO_CASTCLASS_CACHE:
2372 break;
2373 case MONO_PATCH_INFO_RGCTX_FETCH: {
2374 gboolean res;
2375 MonoJumpInfoRgctxEntry *entry;
2377 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2378 entry->method = decode_resolve_method_ref (aot_module, p, &p);
2379 entry->in_mrgctx = decode_value (p, &p);
2380 entry->info_type = decode_value (p, &p);
2381 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2382 entry->data->type = decode_value (p, &p);
2384 res = decode_patch (aot_module, mp, entry->data, p, &p);
2385 if (!res)
2386 goto cleanup;
2387 ji->data.rgctx_entry = entry;
2388 break;
2390 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2391 break;
2392 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2393 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2395 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2396 imt_tramp->vt_offset = decode_value (p, &p);
2398 ji->data.imt_tramp = imt_tramp;
2399 break;
2401 default:
2402 g_warning ("unhandled type %d", ji->type);
2403 g_assert_not_reached ();
2406 *endbuf = p;
2408 return TRUE;
2410 cleanup:
2411 return FALSE;
2414 static MonoJumpInfo*
2415 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
2416 guint32 **got_slots,
2417 guint8 *buf, guint8 **endbuf)
2419 MonoJumpInfo *patches;
2420 int pindex;
2421 guint8 *p;
2423 p = buf;
2425 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2427 *got_slots = g_malloc (sizeof (guint32) * n_patches);
2429 for (pindex = 0; pindex < n_patches; ++pindex) {
2430 MonoJumpInfo *ji = &patches [pindex];
2431 guint8 *shared_p;
2432 gboolean res;
2433 guint32 got_offset;
2435 got_offset = decode_value (p, &p);
2437 if (aot_module->got [got_offset]) {
2438 /* Already loaded */
2439 //printf ("HIT!\n");
2440 } else {
2441 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2443 ji->type = decode_value (shared_p, &shared_p);
2445 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2446 if (!res)
2447 goto cleanup;
2450 (*got_slots) [pindex] = got_offset;
2453 *endbuf = p;
2454 return patches;
2456 cleanup:
2457 g_free (*got_slots);
2458 *got_slots = NULL;
2460 return NULL;
2463 static void
2464 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2467 * Jump addresses cannot be patched by the trampoline code since it
2468 * does not have access to the caller's address. Instead, we collect
2469 * the addresses of the GOT slots pointing to a method, and patch
2470 * them after the method has been compiled.
2472 MonoJitDomainInfo *info = domain_jit_info (domain);
2473 GSList *list;
2475 mono_domain_lock (domain);
2476 if (!info->jump_target_got_slot_hash)
2477 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2478 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2479 list = g_slist_prepend (list, got_slot);
2480 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2481 mono_domain_unlock (domain);
2485 * load_method:
2487 * Load the method identified by METHOD_INDEX from the AOT image. Return a
2488 * pointer to the native code of the method, or NULL if not found.
2489 * METHOD might not be set if the caller only has the image/token info.
2491 static gpointer
2492 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2494 MonoClass *klass;
2495 gboolean from_plt = method == NULL;
2496 MonoMemPool *mp;
2497 int i, pindex, n_patches, used_strings;
2498 gboolean keep_patches = TRUE;
2499 guint8 *p;
2500 MonoJitInfo *jinfo = NULL;
2501 guint8 *code, *info;
2503 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2504 return NULL;
2506 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2507 /* Non shared AOT code can't be used in other appdomains */
2508 return NULL;
2510 if (amodule->out_of_date)
2511 return NULL;
2513 if (amodule->code_offsets [method_index] == 0xffffffff) {
2514 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2515 char *full_name;
2517 if (!method)
2518 method = mono_get_method (image, token, NULL);
2519 full_name = mono_method_full_name (method, TRUE);
2520 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2521 g_free (full_name);
2523 return NULL;
2526 code = &amodule->code [amodule->code_offsets [method_index]];
2528 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2530 if (amodule->thumb_end && code < amodule->thumb_end) {
2531 /* Convert this into a thumb address */
2532 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
2533 code = &amodule->code [amodule->code_offsets [method_index] + 1];
2536 mono_aot_lock ();
2537 if (!amodule->methods_loaded)
2538 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
2539 mono_aot_unlock ();
2541 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2542 return code;
2544 if (mono_last_aot_method != -1) {
2545 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2546 return NULL;
2547 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2548 if (!method)
2549 method = mono_get_method (image, token, NULL);
2550 if (method) {
2551 char *name = mono_method_full_name (method, TRUE);
2552 printf ("LAST AOT METHOD: %s.\n", name);
2553 g_free (name);
2554 } else {
2555 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2560 p = info;
2562 if (method) {
2563 klass = method->klass;
2564 decode_klass_ref (amodule, p, &p);
2565 } else {
2566 klass = decode_klass_ref (amodule, p, &p);
2569 if (amodule->info.opts & MONO_OPT_SHARED)
2570 used_strings = decode_value (p, &p);
2571 else
2572 used_strings = 0;
2574 for (i = 0; i < used_strings; i++) {
2575 guint token = decode_value (p, &p);
2576 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2579 if (amodule->info.opts & MONO_OPT_SHARED)
2580 keep_patches = FALSE;
2582 n_patches = decode_value (p, &p);
2584 keep_patches = FALSE;
2586 if (n_patches) {
2587 MonoJumpInfo *patches;
2588 guint32 *got_slots;
2590 if (keep_patches)
2591 mp = domain->mp;
2592 else
2593 mp = mono_mempool_new ();
2595 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2596 if (patches == NULL)
2597 goto cleanup;
2599 for (pindex = 0; pindex < n_patches; ++pindex) {
2600 MonoJumpInfo *ji = &patches [pindex];
2602 if (!amodule->got [got_slots [pindex]]) {
2603 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
2604 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2605 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
2606 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2607 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
2609 ji->type = MONO_PATCH_INFO_NONE;
2612 g_free (got_slots);
2614 if (!keep_patches)
2615 mono_mempool_destroy (mp);
2618 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2619 char *full_name;
2621 if (!method)
2622 method = mono_get_method (image, token, NULL);
2624 full_name = mono_method_full_name (method, TRUE);
2626 if (!jinfo)
2627 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
2629 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]\n", full_name, code, code + jinfo->code_size, info);
2630 g_free (full_name);
2633 mono_aot_lock ();
2635 InterlockedIncrement (&mono_jit_stats.methods_aot);
2637 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
2639 init_plt (amodule);
2641 if (method && method->wrapper_type)
2642 g_hash_table_insert (amodule->method_to_code, method, code);
2644 mono_aot_unlock ();
2646 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
2647 MonoJitInfo *jinfo;
2649 if (!method) {
2650 method = mono_get_method (image, token, NULL);
2651 g_assert (method);
2653 mono_profiler_method_jit (method);
2654 jinfo = mono_jit_info_table_find (domain, (char*)code);
2655 g_assert (jinfo);
2656 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
2659 if (from_plt && klass && !klass->generic_container)
2660 mono_runtime_class_init (mono_class_vtable (domain, klass));
2662 return code;
2664 cleanup:
2665 /* FIXME: The space in domain->mp is wasted */
2666 if (amodule->info.opts & MONO_OPT_SHARED)
2667 /* No need to cache patches */
2668 mono_mempool_destroy (mp);
2670 if (jinfo)
2671 g_free (jinfo);
2673 return NULL;
2676 static guint32
2677 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name)
2679 guint32 table_size, entry_size, hash;
2680 guint32 *table, *entry;
2681 guint32 index;
2682 static guint32 n_extra_decodes;
2684 if (!amodule)
2685 return 0xffffff;
2687 table_size = amodule->extra_method_table [0];
2688 table = amodule->extra_method_table + 1;
2689 entry_size = 3;
2691 hash = mono_aot_method_hash (method) % table_size;
2693 entry = &table [hash * entry_size];
2695 if (entry [0] == 0)
2696 return 0xffffff;
2698 index = 0xffffff;
2699 while (TRUE) {
2700 guint32 key = entry [0];
2701 guint32 value = entry [1];
2702 guint32 next = entry [entry_size - 1];
2703 MonoMethod *m;
2704 guint8 *p;
2705 int is_wrapper_name;
2707 p = amodule->blob + key;
2708 is_wrapper_name = decode_value (p, &p);
2709 if (is_wrapper_name) {
2710 int wrapper_type = decode_value (p, &p);
2711 if (wrapper_type == method->wrapper_type && !strcmp (name, (char*)p)) {
2712 index = value;
2713 break;
2715 } else {
2716 guint8 *orig_p = p;
2718 mono_aot_lock ();
2719 if (!amodule->method_ref_to_method)
2720 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
2721 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
2722 mono_aot_unlock ();
2723 if (!m) {
2724 m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
2725 if (m) {
2726 mono_aot_lock ();
2727 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
2728 mono_aot_unlock ();
2731 if (m == method) {
2732 index = value;
2733 break;
2736 /* Special case: wrappers of shared generic methods */
2737 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
2738 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
2739 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
2740 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
2742 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
2743 index = value;
2744 break;
2748 /* Methods decoded needlessly */
2749 if (m) {
2750 //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
2751 n_extra_decodes ++;
2755 if (next != 0)
2756 entry = &table [next * entry_size];
2757 else
2758 break;
2761 return index;
2764 static void
2765 add_module_cb (gpointer key, gpointer value, gpointer user_data)
2767 g_ptr_array_add ((GPtrArray*)user_data, value);
2771 * find_extra_method:
2773 * Try finding METHOD in the extra_method table in all AOT images.
2774 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
2775 * module where the method was found.
2777 static guint32
2778 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
2780 guint32 index;
2781 GPtrArray *modules;
2782 int i;
2783 char *name = NULL;
2785 if (method->wrapper_type)
2786 name = mono_aot_wrapper_name (method);
2788 /* Try the method's module first */
2789 *out_amodule = method->klass->image->aot_module;
2790 index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name);
2791 if (index != 0xffffff) {
2792 g_free (name);
2793 return index;
2797 * Try all other modules.
2798 * This is needed because generic instances klass->image points to the image
2799 * containing the generic definition, but the native code is generated to the
2800 * AOT image which contains the reference.
2803 /* Make a copy to avoid doing the search inside the aot lock */
2804 modules = g_ptr_array_new ();
2805 mono_aot_lock ();
2806 g_hash_table_foreach (aot_modules, add_module_cb, modules);
2807 mono_aot_unlock ();
2809 index = 0xffffff;
2810 for (i = 0; i < modules->len; ++i) {
2811 MonoAotModule *amodule = g_ptr_array_index (modules, i);
2813 if (amodule != method->klass->image->aot_module)
2814 index = find_extra_method_in_amodule (amodule, method, name);
2815 if (index != 0xffffff) {
2816 *out_amodule = amodule;
2817 break;
2821 g_ptr_array_free (modules, TRUE);
2823 g_free (name);
2824 return index;
2828 * mono_aot_get_method:
2830 * Return a pointer to the AOTed native code for METHOD if it can be found,
2831 * NULL otherwise.
2832 * On platforms with function pointers, this doesn't return a function pointer.
2834 gpointer
2835 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2837 MonoClass *klass = method->klass;
2838 guint32 method_index;
2839 MonoAotModule *amodule = klass->image->aot_module;
2840 guint8 *code;
2842 if (!amodule)
2843 return NULL;
2845 if (amodule->out_of_date)
2846 return NULL;
2848 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2849 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2850 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2851 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2852 return NULL;
2855 * Use the original method instead of its invoke-with-check wrapper.
2856 * This is not a problem when using full-aot, since it doesn't support
2857 * remoting.
2859 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
2860 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
2862 g_assert (klass->inited);
2864 /* Find method index */
2865 if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
2867 * For generic methods, we store the fully shared instance in place of the
2868 * original method.
2870 method = mono_method_get_declaring_generic_method (method);
2871 method_index = mono_metadata_token_index (method->token) - 1;
2872 } else if (method->is_inflated || !method->token) {
2873 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
2874 mono_aot_lock ();
2875 code = g_hash_table_lookup (amodule->method_to_code, method);
2876 mono_aot_unlock ();
2877 if (code)
2878 return code;
2880 method_index = find_extra_method (method, &amodule);
2882 * Special case the ICollection<T> wrappers for arrays, as they cannot
2883 * be statically enumerated, and each wrapper ends up calling the same
2884 * method in Array.
2886 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
2887 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2889 code = mono_aot_get_method (domain, m);
2890 if (code) {
2891 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
2892 code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
2893 /* The call above returns an ftnptr */
2894 code = mono_get_addr_from_ftnptr (code);
2897 return code;
2902 * Special case Array.GetGenericValueImpl which is a generic icall.
2903 * Generic sharing currently can't handle it, but the icall returns data using
2904 * an out parameter, so the managed-to-native wrappers can share the same code.
2906 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
2907 MonoMethod *m;
2908 MonoGenericContext ctx;
2909 MonoType *args [16];
2911 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
2912 /* Avoid recursion */
2913 return NULL;
2915 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
2916 g_assert (m);
2918 memset (&ctx, 0, sizeof (ctx));
2919 args [0] = &mono_defaults.object_class->byval_arg;
2920 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2922 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
2925 * Get the code for the <object> instantiation which should be emitted into
2926 * the mscorlib aot image by the AOT compiler.
2928 code = mono_aot_get_method (domain, m);
2929 if (code)
2930 return code;
2933 /* Same for CompareExchange<T> and Exchange<T> */
2934 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !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])) {
2935 MonoMethod *m;
2936 MonoGenericContext ctx;
2937 MonoType *args [16];
2938 gpointer iter = NULL;
2940 while ((m = mono_class_get_methods (method->klass, &iter))) {
2941 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
2942 break;
2944 g_assert (m);
2946 memset (&ctx, 0, sizeof (ctx));
2947 args [0] = &mono_defaults.object_class->byval_arg;
2948 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2950 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
2952 /* Avoid recursion */
2953 if (method == m)
2954 return NULL;
2957 * Get the code for the <object> instantiation which should be emitted into
2958 * the mscorlib aot image by the AOT compiler.
2960 code = mono_aot_get_method (domain, m);
2961 if (code)
2962 return code;
2965 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
2966 /* Partial sharing */
2967 method_index = find_extra_method (mini_get_shared_method (method), &amodule);
2970 if (method_index == 0xffffff) {
2971 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2972 char *full_name;
2974 full_name = mono_method_full_name (method, TRUE);
2975 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2976 g_free (full_name);
2978 return NULL;
2981 if (method_index == 0xffffff)
2982 return NULL;
2984 /* Needed by find_jit_info */
2985 mono_aot_lock ();
2986 if (!amodule->extra_methods)
2987 amodule->extra_methods = g_hash_table_new (NULL, NULL);
2988 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
2989 mono_aot_unlock ();
2990 } else {
2991 /* Common case */
2992 method_index = mono_metadata_token_index (method->token) - 1;
2995 return load_method (domain, amodule, klass->image, method, method->token, method_index);
2999 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3000 * method.
3002 gpointer
3003 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3005 MonoAotModule *aot_module = image->aot_module;
3006 int method_index;
3008 if (!aot_module)
3009 return NULL;
3011 method_index = mono_metadata_token_index (token) - 1;
3013 return load_method (domain, aot_module, image, NULL, token, method_index);
3016 typedef struct {
3017 guint8 *addr;
3018 gboolean res;
3019 } IsGotEntryUserData;
3021 static void
3022 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3024 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3025 MonoAotModule *aot_module = (MonoAotModule*)value;
3027 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3028 data->res = TRUE;
3031 gboolean
3032 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3034 IsGotEntryUserData user_data;
3036 if (!aot_modules)
3037 return FALSE;
3039 user_data.addr = addr;
3040 user_data.res = FALSE;
3041 mono_aot_lock ();
3042 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3043 mono_aot_unlock ();
3045 return user_data.res;
3048 typedef struct {
3049 guint8 *addr;
3050 MonoAotModule *module;
3051 } FindAotModuleUserData;
3053 static void
3054 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3056 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3057 MonoAotModule *aot_module = (MonoAotModule*)value;
3059 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3060 data->module = aot_module;
3063 static inline MonoAotModule*
3064 find_aot_module (guint8 *code)
3066 FindAotModuleUserData user_data;
3068 if (!aot_modules)
3069 return NULL;
3071 /* Reading these need no locking */
3072 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3073 return NULL;
3075 user_data.addr = code;
3076 user_data.module = NULL;
3078 mono_aot_lock ();
3079 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3080 mono_aot_unlock ();
3082 return user_data.module;
3085 void
3086 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3089 * Since AOT code is only used in the root domain,
3090 * mono_domain_get () != mono_get_root_domain () means the calling method
3091 * is AppDomain:InvokeInDomain, so this is the same check as in
3092 * mono_method_same_domain () but without loading the metadata for the method.
3094 if (mono_domain_get () == mono_get_root_domain ())
3095 mono_arch_patch_plt_entry (code, got, regs, addr);
3099 * mono_aot_plt_resolve:
3101 * This function is called by the entries in the PLT to resolve the actual method that
3102 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3103 * Returns NULL if the something cannot be loaded.
3105 gpointer
3106 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3108 #ifdef MONO_ARCH_AOT_SUPPORTED
3109 guint8 *p, *target, *plt_entry;
3110 MonoJumpInfo ji;
3111 MonoAotModule *module = (MonoAotModule*)aot_module;
3112 gboolean res, no_ftnptr = FALSE;
3113 MonoMemPool *mp;
3115 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3117 p = &module->blob [plt_info_offset];
3119 ji.type = decode_value (p, &p);
3121 mp = mono_mempool_new_size (512);
3122 res = decode_patch (module, mp, &ji, p, &p);
3124 if (!res) {
3125 mono_mempool_destroy (mp);
3126 return NULL;
3130 * Avoid calling resolve_patch_target in the full-aot case if possible, since
3131 * it would create a trampoline, and we don't need that.
3132 * We could do this only if the method does not need the special handling
3133 * in mono_magic_trampoline ().
3135 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) &&
3136 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
3137 target = mono_jit_compile_method (ji.data.method);
3138 no_ftnptr = TRUE;
3139 } else {
3140 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3144 * The trampoline expects us to return a function descriptor on platforms which use
3145 * it, but resolve_patch_target returns a direct function pointer for some type of
3146 * patches, so have to translate between the two.
3147 * FIXME: Clean this up, but how ?
3149 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) {
3150 /* These should already have a function descriptor */
3151 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3152 /* Our function descriptors have a 0 environment, gcc created ones don't */
3153 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3154 g_assert (((gpointer*)target) [2] == 0);
3155 #endif
3156 /* Empty */
3157 } else if (!no_ftnptr) {
3158 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3159 g_assert (((gpointer*)target) [2] != 0);
3160 #endif
3161 target = mono_create_ftnptr (mono_domain_get (), target);
3164 mono_mempool_destroy (mp);
3166 /* Patch the PLT entry with target which might be the actual method not a trampoline */
3167 plt_entry = mono_aot_get_plt_entry (code);
3168 g_assert (plt_entry);
3169 mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3171 return target;
3172 #else
3173 g_assert_not_reached ();
3174 return NULL;
3175 #endif
3179 * init_plt:
3181 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
3182 * method in the module is loaded to avoid committing memory by writing to it.
3183 * LOCKING: Assumes the AOT lock is held.
3185 static void
3186 init_plt (MonoAotModule *amodule)
3188 int i;
3189 gpointer tramp;
3191 if (amodule->plt_inited)
3192 return;
3194 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3197 * Initialize the PLT entries in the GOT to point to the default targets.
3200 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3201 for (i = 1; i < amodule->info.plt_size; ++i)
3202 /* All the default entries point to the AOT trampoline */
3203 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3205 amodule->plt_inited = TRUE;
3209 * mono_aot_get_plt_entry:
3211 * Return the address of the PLT entry called by the code at CODE if exists.
3213 guint8*
3214 mono_aot_get_plt_entry (guint8 *code)
3216 MonoAotModule *amodule = find_aot_module (code);
3217 guint8 *target = NULL;
3219 if (!amodule)
3220 return NULL;
3222 #ifdef TARGET_ARM
3223 if (amodule->thumb_end && code < amodule->thumb_end) {
3224 return mono_arm_get_thumb_plt_entry (code);
3226 #endif
3228 #ifdef MONO_ARCH_AOT_SUPPORTED
3229 target = mono_arch_get_call_target (code);
3230 #else
3231 g_assert_not_reached ();
3232 #endif
3234 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3235 return target;
3236 else
3237 return NULL;
3241 * mono_aot_get_plt_info_offset:
3243 * Return the PLT info offset belonging to the plt entry called by CODE.
3245 guint32
3246 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3248 guint8 *plt_entry = mono_aot_get_plt_entry (code);
3250 g_assert (plt_entry);
3252 /* The offset is embedded inside the code after the plt entry */
3253 #ifdef MONO_ARCH_AOT_SUPPORTED
3254 return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3255 #else
3256 g_assert_not_reached ();
3257 return 0;
3258 #endif
3261 static gpointer
3262 mono_create_ftnptr_malloc (guint8 *code)
3264 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3265 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3267 ftnptr->code = code;
3268 ftnptr->toc = NULL;
3269 ftnptr->env = NULL;
3271 return ftnptr;
3272 #else
3273 return code;
3274 #endif
3278 * mono_aot_register_jit_icall:
3280 * Register a JIT icall which is called by trampolines in full-aot mode. This should
3281 * be called from mono_arch_init () during startup.
3283 void
3284 mono_aot_register_jit_icall (const char *name, gpointer addr)
3286 /* No need for locking */
3287 if (!aot_jit_icall_hash)
3288 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3289 g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3293 * load_function:
3295 * Load the function named NAME from the aot image.
3297 static gpointer
3298 load_function (MonoAotModule *amodule, const char *name)
3300 char *symbol;
3301 guint8 *p;
3302 int n_patches, pindex;
3303 MonoMemPool *mp;
3304 gpointer code;
3306 /* Load the code */
3308 symbol = g_strdup_printf ("%s", name);
3309 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3310 g_free (symbol);
3311 if (!code)
3312 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3314 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
3316 /* Load info */
3318 symbol = g_strdup_printf ("%s_p", name);
3319 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3320 g_free (symbol);
3321 if (!p)
3322 /* Nothing to patch */
3323 return code;
3325 p = amodule->blob + *(guint32*)p;
3327 /* Similar to mono_aot_load_method () */
3329 n_patches = decode_value (p, &p);
3331 if (n_patches) {
3332 MonoJumpInfo *patches;
3333 guint32 *got_slots;
3335 mp = mono_mempool_new ();
3337 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3338 g_assert (patches);
3340 for (pindex = 0; pindex < n_patches; ++pindex) {
3341 MonoJumpInfo *ji = &patches [pindex];
3342 gpointer target;
3344 if (amodule->got [got_slots [pindex]])
3345 continue;
3348 * When this code is executed, the runtime may not be initalized yet, so
3349 * resolve the patch info by hand.
3351 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3352 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3353 target = mono_get_lmf_addr;
3354 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3355 target = mono_thread_force_interruption_checkpoint;
3356 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3357 target = mono_exception_from_token;
3358 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3359 target = mono_get_throw_exception ();
3360 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3361 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3362 target = (gpointer)mono_get_trampoline_func (tramp_type2);
3363 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3364 /* atoll is needed because the the offset is unsigned */
3365 guint32 slot;
3366 int res;
3368 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3369 g_assert (res == 1);
3370 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3371 target = mono_create_ftnptr_malloc (target);
3372 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3373 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3374 target = mono_create_ftnptr_malloc (target);
3375 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3376 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3377 target = mono_create_ftnptr_malloc (target);
3378 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3379 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3380 target = mono_create_ftnptr_malloc (target);
3381 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3382 target = mono_thread_get_and_clear_pending_exception;
3383 } else if (strstr (ji->data.name, "generic_trampoline_")) {
3384 target = mono_aot_get_trampoline (ji->data.name);
3385 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3386 /* Registered by mono_arch_init () */
3387 target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3388 } else {
3389 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3390 g_assert_not_reached ();
3391 target = NULL;
3393 } else {
3394 /* Hopefully the code doesn't have patches which need method or
3395 * domain to be set.
3397 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3398 g_assert (target);
3401 amodule->got [got_slots [pindex]] = target;
3404 g_free (got_slots);
3406 mono_mempool_destroy (mp);
3409 return code;
3413 * Return the trampoline identified by NAME from the mscorlib AOT file.
3414 * On ppc64, this returns a function descriptor.
3416 gpointer
3417 mono_aot_get_trampoline (const char *name)
3419 MonoImage *image;
3420 MonoAotModule *amodule;
3422 image = mono_defaults.corlib;
3423 g_assert (image);
3425 amodule = image->aot_module;
3426 g_assert (amodule);
3428 return mono_create_ftnptr_malloc (load_function (amodule, name));
3431 /* Return a given kind of trampoline */
3432 static gpointer
3433 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3435 MonoAotModule *amodule;
3436 int index, tramp_size;
3437 MonoImage *image;
3439 /* Currently, we keep all trampolines in the mscorlib AOT image */
3440 image = mono_defaults.corlib;
3441 g_assert (image);
3443 mono_aot_lock ();
3445 amodule = image->aot_module;
3446 g_assert (amodule);
3448 *out_amodule = amodule;
3450 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3451 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3453 index = amodule->trampoline_index [tramp_type] ++;
3455 mono_aot_unlock ();
3457 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3459 tramp_size = amodule->info.trampoline_size [tramp_type];
3461 if (out_tramp_size)
3462 *out_tramp_size = tramp_size;
3464 return amodule->trampolines [tramp_type] + (index * tramp_size);
3468 * Return a specific trampoline from the AOT file.
3470 gpointer
3471 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3473 MonoAotModule *amodule;
3474 guint32 got_offset, tramp_size;
3475 guint8 *code, *tramp;
3476 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3477 static gboolean inited;
3478 static guint32 num_trampolines;
3480 if (!inited) {
3481 mono_aot_lock ();
3483 if (!inited) {
3484 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3485 inited = TRUE;
3488 mono_aot_unlock ();
3491 num_trampolines ++;
3493 if (!generic_trampolines [tramp_type]) {
3494 char *symbol;
3496 symbol = mono_get_generic_trampoline_name (tramp_type);
3497 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
3498 g_free (symbol);
3501 tramp = generic_trampolines [tramp_type];
3502 g_assert (tramp);
3504 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3506 amodule->got [got_offset] = tramp;
3507 amodule->got [got_offset + 1] = arg1;
3509 if (code_len)
3510 *code_len = tramp_size;
3512 return code;
3515 gpointer
3516 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3518 MonoAotModule *amodule;
3519 guint8 *code;
3520 guint32 got_offset;
3522 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3524 amodule->got [got_offset] = ctx;
3525 amodule->got [got_offset + 1] = addr;
3527 /* The caller expects an ftnptr */
3528 return mono_create_ftnptr (mono_domain_get (), code);
3531 gpointer
3532 mono_aot_get_unbox_trampoline (MonoMethod *method)
3534 guint32 method_index = mono_metadata_token_index (method->token) - 1;
3535 MonoAotModule *amodule;
3536 gpointer code;
3537 guint32 *ut, *ut_end, *entry;
3538 int low, high, entry_index;
3540 if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3541 method_index = find_extra_method (method, &amodule);
3542 g_assert (method_index != 0xffffff);
3543 } else {
3544 amodule = method->klass->image->aot_module;
3545 g_assert (amodule);
3548 ut = amodule->unbox_trampolines;
3549 ut_end = amodule->unbox_trampolines_end;
3551 /* Do a binary search in the sorted table */
3552 code = NULL;
3553 low = 0;
3554 high = (ut_end - ut) / 2;
3555 while (low < high) {
3556 entry_index = (low + high) / 2;
3557 entry = &ut [(entry_index * 2)];
3558 if (entry [0] < method_index) {
3559 low = entry_index + 1;
3560 } else if (entry [0] > method_index) {
3561 high = entry_index;
3562 } else {
3563 code = amodule->code + entry [1];
3564 break;
3567 g_assert (code);
3569 /* The caller expects an ftnptr */
3570 return mono_create_ftnptr (mono_domain_get (), code);
3573 gpointer
3574 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3576 char *symbol;
3577 gpointer code;
3579 symbol = mono_get_rgctx_fetch_trampoline_name (slot);
3580 code = load_function (mono_defaults.corlib->aot_module, symbol);
3581 g_free (symbol);
3582 /* The caller expects an ftnptr */
3583 return mono_create_ftnptr (mono_domain_get (), code);
3586 gpointer
3587 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3589 guint32 got_offset;
3590 gpointer code;
3591 gpointer *buf;
3592 int i, index, real_count;
3593 MonoAotModule *amodule;
3595 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
3597 real_count = 0;
3598 for (i = 0; i < count; ++i) {
3599 MonoIMTCheckItem *item = imt_entries [i];
3601 if (item->is_equals)
3602 real_count ++;
3605 /* Save the entries into an array */
3606 buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
3607 index = 0;
3608 for (i = 0; i < count; ++i) {
3609 MonoIMTCheckItem *item = imt_entries [i];
3611 if (!item->is_equals)
3612 continue;
3614 g_assert (item->key);
3616 buf [(index * 2)] = item->key;
3617 if (item->has_target_code) {
3618 gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
3619 *p = item->value.target_code;
3620 buf [(index * 2) + 1] = p;
3621 } else {
3622 buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
3624 index ++;
3626 buf [(index * 2)] = NULL;
3627 buf [(index * 2) + 1] = fail_tramp;
3629 amodule->got [got_offset] = buf;
3631 return code;
3635 * mono_aot_set_make_unreadable:
3637 * Set whenever to make all mmaped memory unreadable. In conjuction with a
3638 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
3640 void
3641 mono_aot_set_make_unreadable (gboolean unreadable)
3643 static int inited;
3645 make_unreadable = unreadable;
3647 if (make_unreadable && !inited) {
3648 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
3652 typedef struct {
3653 MonoAotModule *module;
3654 guint8 *ptr;
3655 } FindMapUserData;
3657 static void
3658 find_map (gpointer key, gpointer value, gpointer user_data)
3660 MonoAotModule *module = (MonoAotModule*)value;
3661 FindMapUserData *data = (FindMapUserData*)user_data;
3663 if (!data->module)
3664 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
3665 data->module = module;
3668 static MonoAotModule*
3669 find_module_for_addr (void *ptr)
3671 FindMapUserData data;
3673 if (!make_unreadable)
3674 return NULL;
3676 data.module = NULL;
3677 data.ptr = (guint8*)ptr;
3679 mono_aot_lock ();
3680 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
3681 mono_aot_unlock ();
3683 return data.module;
3687 * mono_aot_is_pagefault:
3689 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
3690 * within memory allocated by this module.
3692 gboolean
3693 mono_aot_is_pagefault (void *ptr)
3695 if (!make_unreadable)
3696 return FALSE;
3699 * Not signal safe, but SIGSEGV's are synchronous, and
3700 * this is only turned on by a MONO_DEBUG option.
3702 return find_module_for_addr (ptr) != NULL;
3706 * mono_aot_handle_pagefault:
3708 * Handle a pagefault caused by an unreadable page by making it readable again.
3710 void
3711 mono_aot_handle_pagefault (void *ptr)
3713 #ifndef PLATFORM_WIN32
3714 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
3715 int res;
3717 mono_aot_lock ();
3718 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
3719 g_assert (res == 0);
3721 n_pagefaults ++;
3722 mono_aot_unlock ();
3723 #endif
3726 #else
3727 /* AOT disabled */
3729 void
3730 mono_aot_init (void)
3734 gpointer
3735 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3737 return NULL;
3740 gboolean
3741 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3743 return FALSE;
3746 gboolean
3747 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
3749 return FALSE;
3752 gboolean
3753 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
3755 return FALSE;
3758 MonoJitInfo *
3759 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3761 return NULL;
3764 gpointer
3765 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3767 return NULL;
3770 guint8*
3771 mono_aot_get_plt_entry (guint8 *code)
3773 return NULL;
3776 gpointer
3777 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3779 return NULL;
3782 void
3783 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3787 gpointer
3788 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
3790 return NULL;
3793 guint32
3794 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3796 g_assert_not_reached ();
3798 return 0;
3801 gpointer
3802 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3804 g_assert_not_reached ();
3805 return NULL;
3808 gpointer
3809 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3811 g_assert_not_reached ();
3812 return NULL;
3815 gpointer
3816 mono_aot_get_trampoline (const char *name)
3818 g_assert_not_reached ();
3819 return NULL;
3822 gpointer
3823 mono_aot_get_unbox_trampoline (MonoMethod *method)
3825 g_assert_not_reached ();
3826 return NULL;
3829 gpointer
3830 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3832 g_assert_not_reached ();
3833 return NULL;
3836 gpointer
3837 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3839 g_assert_not_reached ();
3840 return NULL;
3843 guint8*
3844 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3846 g_assert_not_reached ();
3847 return NULL;
3850 void
3851 mono_aot_register_jit_icall (const char *name, gpointer addr)
3855 #endif