2010-04-19 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / mini / aot-runtime.c
blobf15bee6bb5b726b299b880f0eea55c1611d9a091
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 */
11 #include "config.h"
12 #include <sys/types.h>
13 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16 #include <fcntl.h>
17 #include <string.h>
18 #ifdef HAVE_SYS_MMAN_H
19 #include <sys/mman.h>
20 #endif
22 #if HOST_WIN32
23 #include <winsock2.h>
24 #include <windows.h>
25 #endif
27 #ifdef HAVE_EXECINFO_H
28 #include <execinfo.h>
29 #endif
31 #include <errno.h>
32 #include <sys/stat.h>
34 #ifdef HAVE_SYS_WAIT_H
35 #include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
36 #endif
38 #ifdef HAVE_DL_ITERATE_PHDR
39 #include <link.h>
40 #endif
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/class.h>
44 #include <mono/metadata/object.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/metadata/assembly.h>
49 #include <mono/metadata/metadata-internals.h>
50 #include <mono/metadata/marshal.h>
51 #include <mono/metadata/gc-internal.h>
52 #include <mono/metadata/monitor.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include "mono/utils/mono-compiler.h"
57 #include <mono/utils/mono-counters.h>
59 #include "mini.h"
60 #include "version.h"
62 #ifndef DISABLE_AOT
64 #ifdef TARGET_WIN32
65 #define SHARED_EXT ".dll"
66 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
67 #define SHARED_EXT ".dylib"
68 #else
69 #define SHARED_EXT ".so"
70 #endif
72 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
73 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
75 typedef struct MonoAotModule {
76 char *aot_name;
77 /* Pointer to the Global Offset Table */
78 gpointer *got;
79 GHashTable *name_cache;
80 GHashTable *extra_methods;
81 /* Maps methods to their code */
82 GHashTable *method_to_code;
83 /* Maps pointers into the method info to the methods themselves */
84 GHashTable *method_ref_to_method;
85 MonoAssemblyName *image_names;
86 char **image_guids;
87 MonoAssembly *assembly;
88 MonoImage **image_table;
89 guint32 image_table_len;
90 gboolean out_of_date;
91 gboolean plt_inited;
92 guint8 *mem_begin;
93 guint8 *mem_end;
94 guint8 *code;
95 guint8 *code_end;
96 guint8 *plt;
97 guint8 *plt_end;
98 guint8 *blob;
99 gint32 *code_offsets;
100 /* This contains <offset, index> pairs sorted by offset */
101 /* This is needed because LLVM emitted methods can be in any order */
102 gint32 *sorted_code_offsets;
103 gint32 sorted_code_offsets_len;
104 guint32 *method_info_offsets;
105 guint32 *got_info_offsets;
106 guint32 *ex_info_offsets;
107 guint32 *class_info_offsets;
108 guint32 *methods_loaded;
109 guint16 *class_name_table;
110 guint32 *extra_method_table;
111 guint32 *extra_method_info_offsets;
112 guint8 *unwind_info;
114 /* Points to the GNU .eh_frame_hdr section, if it exists */
115 guint8 *eh_frame_hdr;
117 /* Points to the .ARM.exidx section, if it exists */
118 guint8 *arm_exidx;
119 guint32 arm_exidx_size;
121 /* Points to the trampolines */
122 guint8 *trampolines [MONO_AOT_TRAMP_NUM];
123 /* The first unused trampoline of each kind */
124 guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
126 MonoAotFileInfo info;
128 gpointer *globals;
129 MonoDl *sofile;
130 } MonoAotModule;
132 static GHashTable *aot_modules;
133 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
134 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
135 static CRITICAL_SECTION aot_mutex;
138 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
139 * AOT modules registered by mono_aot_register_module ().
141 static GHashTable *static_aot_modules;
144 * Maps MonoJitInfo* to the aot module they belong to, this can be different
145 * from ji->method->klass->image's aot module for generic instances.
147 static GHashTable *ji_to_amodule;
150 * Whenever to AOT compile loaded assemblies on demand and store them in
151 * a cache under $HOME/.mono/aot-cache.
153 static gboolean use_aot_cache = FALSE;
156 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
157 * use_aot_cache is TRUE.
159 static gboolean spawn_compiler = TRUE;
161 /* For debugging */
162 static gint32 mono_last_aot_method = -1;
164 static gboolean make_unreadable = FALSE;
165 static guint32 name_table_accesses = 0;
166 static guint32 n_pagefaults = 0;
168 /* Used to speed-up find_aot_module () */
169 static gsize aot_code_low_addr = (gssize)-1;
170 static gsize aot_code_high_addr = 0;
172 static void
173 init_plt (MonoAotModule *info);
175 /*****************************************************/
176 /* AOT RUNTIME */
177 /*****************************************************/
180 * load_image:
182 * Load one of the images referenced by AMODULE. Returns NULL if the image is not
183 * found, and sets the loader error if SET_ERROR is TRUE.
185 static MonoImage *
186 load_image (MonoAotModule *amodule, int index, gboolean set_error)
188 MonoAssembly *assembly;
189 MonoImageOpenStatus status;
191 g_assert (index < amodule->image_table_len);
193 if (amodule->image_table [index])
194 return amodule->image_table [index];
195 if (amodule->out_of_date)
196 return NULL;
198 assembly = mono_assembly_load (&amodule->image_names [index], NULL, &status);
199 if (!assembly) {
200 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);
201 amodule->out_of_date = TRUE;
203 if (set_error) {
204 char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
205 mono_loader_set_error_assembly_load (full_name, FALSE);
206 g_free (full_name);
208 return NULL;
211 if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
212 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date (Older than dependency %s).\n", amodule->aot_name, amodule->image_names [index].name);
213 amodule->out_of_date = TRUE;
214 return NULL;
217 amodule->image_table [index] = assembly->image;
218 return assembly->image;
221 static inline gint32
222 decode_value (guint8 *ptr, guint8 **rptr)
224 guint8 b = *ptr;
225 gint32 len;
227 if ((b & 0x80) == 0){
228 len = b;
229 ++ptr;
230 } else if ((b & 0x40) == 0){
231 len = ((b & 0x3f) << 8 | ptr [1]);
232 ptr += 2;
233 } else if (b != 0xff) {
234 len = ((b & 0x1f) << 24) |
235 (ptr [1] << 16) |
236 (ptr [2] << 8) |
237 ptr [3];
238 ptr += 4;
240 else {
241 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
242 ptr += 5;
244 if (rptr)
245 *rptr = ptr;
247 //printf ("DECODE: %d.\n", len);
248 return len;
252 * mono_aot_get_method:
254 * Decode an offset table emitted by emit_offset_table (), returning the INDEXth
255 * entry.
257 static guint32
258 mono_aot_get_offset (guint32 *table, int index)
260 int i, group, ngroups, index_entry_size;
261 int start_offset, offset, noffsets, group_size;
262 guint8 *data_start, *p;
263 guint32 *index32 = NULL;
264 guint16 *index16 = NULL;
266 noffsets = table [0];
267 group_size = table [1];
268 ngroups = table [2];
269 index_entry_size = table [3];
270 group = index / group_size;
272 if (index_entry_size == 2) {
273 index16 = (guint16*)&table [4];
274 data_start = (guint8*)&index16 [ngroups];
275 p = data_start + index16 [group];
276 } else {
277 index32 = (guint32*)&table [4];
278 data_start = (guint8*)&index32 [ngroups];
279 p = data_start + index32 [group];
282 /* offset will contain the value of offsets [group * group_size] */
283 offset = start_offset = decode_value (p, &p);
284 for (i = group * group_size + 1; i <= index; ++i) {
285 offset += decode_value (p, &p);
288 //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
290 return offset;
293 static MonoMethod*
294 decode_method_ref_2 (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
296 static MonoClass*
297 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
299 static MonoGenericInst*
300 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
302 int type_argc, i;
303 MonoType **type_argv;
304 MonoGenericInst *inst;
305 guint8 *p = buf;
307 type_argc = decode_value (p, &p);
308 type_argv = g_new0 (MonoType*, type_argc);
310 for (i = 0; i < type_argc; ++i) {
311 MonoClass *pclass = decode_klass_ref (module, p, &p);
312 if (!pclass) {
313 g_free (type_argv);
314 return NULL;
316 type_argv [i] = &pclass->byval_arg;
319 inst = mono_metadata_get_generic_inst (type_argc, type_argv);
320 g_free (type_argv);
322 *endbuf = p;
324 return inst;
327 static gboolean
328 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
330 gboolean has_class_inst, has_method_inst;
331 guint8 *p = buf;
333 has_class_inst = decode_value (p, &p);
334 if (has_class_inst) {
335 ctx->class_inst = decode_generic_inst (module, p, &p);
336 if (!ctx->class_inst)
337 return FALSE;
339 has_method_inst = decode_value (p, &p);
340 if (has_method_inst) {
341 ctx->method_inst = decode_generic_inst (module, p, &p);
342 if (!ctx->method_inst)
343 return FALSE;
346 *endbuf = p;
347 return TRUE;
350 static MonoClass*
351 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
353 MonoImage *image;
354 MonoClass *klass, *eklass;
355 guint32 token, rank;
356 guint8 *p = buf;
358 token = decode_value (p, &p);
359 if (token == 0) {
360 *endbuf = p;
361 return NULL;
363 if (mono_metadata_token_table (token) == 0) {
364 image = load_image (module, decode_value (p, &p), TRUE);
365 if (!image)
366 return NULL;
367 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token);
368 } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
369 if (token == MONO_TOKEN_TYPE_SPEC) {
370 MonoTypeEnum type = decode_value (p, &p);
372 if (type == MONO_TYPE_GENERICINST) {
373 MonoClass *gclass;
374 MonoGenericContext ctx;
375 MonoType *type;
377 gclass = decode_klass_ref (module, p, &p);
378 if (!gclass)
379 return NULL;
380 g_assert (gclass->generic_container);
382 memset (&ctx, 0, sizeof (ctx));
383 ctx.class_inst = decode_generic_inst (module, p, &p);
384 if (!ctx.class_inst)
385 return NULL;
386 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
387 klass = mono_class_from_mono_type (type);
388 mono_metadata_free_type (type);
389 } else if ((type == MONO_TYPE_VAR) || (type == MONO_TYPE_MVAR)) {
390 MonoType *t;
391 MonoGenericContainer *container;
393 int num = decode_value (p, &p);
394 gboolean is_method = decode_value (p, &p);
396 if (is_method) {
397 MonoMethod *method_def;
398 g_assert (type == MONO_TYPE_MVAR);
399 method_def = decode_method_ref_2 (module, p, &p);
400 if (!method_def)
401 return NULL;
403 container = mono_method_get_generic_container (method_def);
404 } else {
405 MonoClass *class_def;
406 g_assert (type == MONO_TYPE_VAR);
407 class_def = decode_klass_ref (module, p, &p);
408 if (!class_def)
409 return NULL;
411 container = class_def->generic_container;
414 g_assert (container);
416 // FIXME: Memory management
417 t = g_new0 (MonoType, 1);
418 t->type = type;
419 t->data.generic_param = mono_generic_container_get_param (container, num);
421 // FIXME: Maybe use types directly to avoid
422 // the overhead of creating MonoClass-es
423 klass = mono_class_from_mono_type (t);
425 g_free (t);
426 } else {
427 g_assert_not_reached ();
429 } else {
430 image = load_image (module, decode_value (p, &p), TRUE);
431 if (!image)
432 return NULL;
433 klass = mono_class_get (image, token);
435 } else if (token == MONO_TOKEN_TYPE_DEF) {
436 /* Array */
437 image = load_image (module, decode_value (p, &p), TRUE);
438 if (!image)
439 return NULL;
440 rank = decode_value (p, &p);
441 eklass = decode_klass_ref (module, p, &p);
442 klass = mono_array_class_get (eklass, rank);
443 } else {
444 g_assert_not_reached ();
446 g_assert (klass);
448 *endbuf = p;
449 return klass;
452 static MonoClassField*
453 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
455 MonoClass *klass = decode_klass_ref (module, buf, &buf);
456 guint32 token;
457 guint8 *p = buf;
459 if (!klass)
460 return NULL;
462 token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
464 *endbuf = p;
466 return mono_class_get_field (klass, token);
470 * can_method_ref_match_method:
472 * Determine if calling decode_method_ref_2 on P could return the same method as
473 * METHOD. This is an optimization to avoid calling decode_method_ref_2 () which
474 * would create MonoMethods which are not needed etc.
476 static gboolean
477 can_method_ref_match_method (MonoAotModule *module, guint8 *buf, MonoMethod *method)
479 guint8 *p = buf;
480 guint32 image_index, value;
482 /* Keep this in sync with decode_method_ref () */
483 value = decode_value (p, &p);
484 image_index = value >> 24;
486 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
487 guint32 wrapper_type;
489 if (!method->wrapper_type)
490 return FALSE;
492 wrapper_type = decode_value (p, &p);
494 if (method->wrapper_type != wrapper_type)
495 return FALSE;
496 } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) {
497 return FALSE;
498 } else if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
499 if (method->wrapper_type)
500 return FALSE;
503 return TRUE;
507 * decode_method_ref:
509 * Decode a method reference, and return its image and token. This avoids loading
510 * metadata for the method if the caller does not need it. If the method has no token,
511 * then it is loaded from metadata and METHOD is set to the method instance.
513 static MonoImage*
514 decode_method_ref (MonoAotModule *module, guint32 *token, MonoMethod **method, gboolean *no_aot_trampoline, guint8 *buf, guint8 **endbuf)
516 guint32 image_index, value;
517 MonoImage *image = NULL;
518 guint8 *p = buf;
520 if (method)
521 *method = NULL;
522 if (no_aot_trampoline)
523 *no_aot_trampoline = FALSE;
525 value = decode_value (p, &p);
526 image_index = value >> 24;
528 if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
529 if (no_aot_trampoline)
530 *no_aot_trampoline = TRUE;
531 value = decode_value (p, &p);
532 image_index = value >> 24;
535 if (image_index == MONO_AOT_METHODREF_WRAPPER) {
536 guint32 wrapper_type;
538 wrapper_type = decode_value (p, &p);
540 /* Doesn't matter */
541 image = mono_defaults.corlib;
543 switch (wrapper_type) {
544 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
545 MonoMethod *m = decode_method_ref_2 (module, p, &p);
547 if (!m)
548 return NULL;
549 mono_class_init (m->klass);
550 *method = mono_marshal_get_remoting_invoke_with_check (m);
551 break;
553 case MONO_WRAPPER_PROXY_ISINST: {
554 MonoClass *klass = decode_klass_ref (module, p, &p);
555 if (!klass)
556 return NULL;
557 *method = mono_marshal_get_proxy_cancast (klass);
558 break;
560 case MONO_WRAPPER_LDFLD:
561 case MONO_WRAPPER_LDFLDA:
562 case MONO_WRAPPER_STFLD:
563 case MONO_WRAPPER_ISINST: {
564 MonoClass *klass = decode_klass_ref (module, p, &p);
565 if (!klass)
566 return NULL;
567 if (wrapper_type == MONO_WRAPPER_LDFLD)
568 *method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
569 else if (wrapper_type == MONO_WRAPPER_LDFLDA)
570 *method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
571 else if (wrapper_type == MONO_WRAPPER_STFLD)
572 *method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
573 else if (wrapper_type == MONO_WRAPPER_ISINST)
574 *method = mono_marshal_get_isinst (klass);
575 else
576 g_assert_not_reached ();
577 break;
579 case MONO_WRAPPER_LDFLD_REMOTE:
580 *method = mono_marshal_get_ldfld_remote_wrapper (NULL);
581 break;
582 case MONO_WRAPPER_STFLD_REMOTE:
583 *method = mono_marshal_get_stfld_remote_wrapper (NULL);
584 break;
585 case MONO_WRAPPER_ALLOC: {
586 int atype = decode_value (p, &p);
588 *method = mono_gc_get_managed_allocator_by_type (atype);
589 break;
591 case MONO_WRAPPER_WRITE_BARRIER:
592 *method = mono_gc_get_write_barrier ();
593 break;
594 case MONO_WRAPPER_STELEMREF:
595 *method = mono_marshal_get_stelemref ();
596 break;
597 case MONO_WRAPPER_SYNCHRONIZED: {
598 MonoMethod *m = decode_method_ref_2 (module, p, &p);
600 if (!m)
601 return NULL;
602 *method = mono_marshal_get_synchronized_wrapper (m);
603 break;
605 case MONO_WRAPPER_UNKNOWN: {
606 MonoMethodDesc *desc;
607 MonoMethod *orig_method;
608 int subtype = decode_value (p, &p);
610 if (subtype == MONO_AOT_WRAPPER_MONO_ENTER)
611 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
612 else if (subtype == MONO_AOT_WRAPPER_MONO_EXIT)
613 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
614 else
615 g_assert_not_reached ();
616 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
617 g_assert (orig_method);
618 mono_method_desc_free (desc);
619 *method = mono_monitor_get_fast_path (orig_method);
620 break;
622 case MONO_WRAPPER_RUNTIME_INVOKE: {
623 /* Direct wrapper */
624 MonoMethod *m = decode_method_ref_2 (module, p, &p);
626 if (!m)
627 return NULL;
628 *method = mono_marshal_get_runtime_invoke (m, FALSE);
629 break;
631 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
632 int subtype = decode_value (p, &p);
634 if (subtype == MONO_AOT_WRAPPER_ELEMENT_ADDR) {
635 int rank = decode_value (p, &p);
636 int elem_size = decode_value (p, &p);
638 *method = mono_marshal_get_array_address (rank, elem_size);
639 } else {
640 g_assert_not_reached ();
642 break;
644 default:
645 g_assert_not_reached ();
647 } else if (image_index == MONO_AOT_METHODREF_WRAPPER_NAME) {
648 /* Can't decode these */
649 g_assert_not_reached ();
650 } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
651 image_index = decode_value (p, &p);
652 *token = decode_value (p, &p);
654 image = load_image (module, image_index, TRUE);
655 if (!image)
656 return NULL;
657 } else if (image_index == MONO_AOT_METHODREF_GINST) {
658 MonoClass *klass;
659 MonoGenericContext ctx;
662 * These methods do not have a token which resolves them, so we
663 * resolve them immediately.
665 klass = decode_klass_ref (module, p, &p);
666 if (!klass)
667 return NULL;
669 image_index = decode_value (p, &p);
670 *token = decode_value (p, &p);
672 image = load_image (module, image_index, TRUE);
673 if (!image)
674 return NULL;
676 *method = mono_get_method_full (image, *token, NULL, NULL);
677 if (!(*method))
678 return NULL;
680 memset (&ctx, 0, sizeof (ctx));
682 if (FALSE && klass->generic_class) {
683 ctx.class_inst = klass->generic_class->context.class_inst;
684 ctx.method_inst = NULL;
686 *method = mono_class_inflate_generic_method_full (*method, klass, &ctx);
689 memset (&ctx, 0, sizeof (ctx));
691 if (!decode_generic_context (module, &ctx, p, &p))
692 return NULL;
694 *method = mono_class_inflate_generic_method_full (*method, klass, &ctx);
695 } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
696 MonoClass *klass;
697 int method_type;
699 klass = decode_klass_ref (module, p, &p);
700 if (!klass)
701 return NULL;
702 method_type = decode_value (p, &p);
703 *token = 0;
704 switch (method_type) {
705 case 0:
706 *method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
707 break;
708 case 1:
709 *method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
710 break;
711 case 2:
712 *method = mono_class_get_method_from_name (klass, "Get", -1);
713 break;
714 case 3:
715 *method = mono_class_get_method_from_name (klass, "Address", -1);
716 break;
717 case 4:
718 *method = mono_class_get_method_from_name (klass, "Set", -1);
719 break;
720 default:
721 g_assert_not_reached ();
723 } else {
724 g_assert (image_index < MONO_AOT_METHODREF_MIN);
725 *token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
727 image = load_image (module, image_index, TRUE);
728 if (!image)
729 return NULL;
732 *endbuf = p;
734 return image;
738 * decode_method_ref_2:
740 * Similar to decode_method_ref, but resolve and return the method itself.
742 static MonoMethod*
743 decode_method_ref_2 (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
745 MonoMethod *method;
746 guint32 token;
747 MonoImage *image = decode_method_ref (module, &token, &method, NULL, buf, endbuf);
749 if (method)
750 return method;
751 if (!image)
752 return NULL;
753 method = mono_get_method (image, token, NULL);
754 return method;
757 G_GNUC_UNUSED
758 static void
759 make_writable (guint8* addr, guint32 len)
761 guint8 *page_start;
762 int pages, err;
764 if (mono_aot_only)
765 g_error ("Attempt to make AOT memory writable while running in aot-only mode.\n");
767 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1));
768 pages = (addr + len - page_start + mono_pagesize () - 1) / mono_pagesize ();
770 err = mono_mprotect (page_start, pages * mono_pagesize (), MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_EXEC);
771 g_assert (err == 0);
774 static void
775 create_cache_structure (void)
777 const char *home;
778 char *tmp;
779 int err;
781 home = g_get_home_dir ();
782 if (!home)
783 return;
785 tmp = g_build_filename (home, ".mono", NULL);
786 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
787 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
788 #ifdef HOST_WIN32
789 err = mkdir (tmp);
790 #else
791 err = mkdir (tmp, 0777);
792 #endif
793 if (err) {
794 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
795 g_free (tmp);
796 return;
799 g_free (tmp);
800 tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
801 if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
802 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
803 #ifdef HOST_WIN32
804 err = mkdir (tmp);
805 #else
806 err = mkdir (tmp, 0777);
807 #endif
808 if (err) {
809 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
810 g_free (tmp);
811 return;
814 g_free (tmp);
818 * load_aot_module_from_cache:
820 * Experimental code to AOT compile loaded assemblies on demand.
822 * FIXME:
823 * - Add environment variable MONO_AOT_CACHE_OPTIONS
824 * - Add options for controlling the cache size
825 * - Handle full cache by deleting old assemblies lru style
826 * - Add options for excluding assemblies during development
827 * - Maybe add a threshold after an assembly is AOT compiled
828 * - invoking a new mono process is a security risk
829 * - recompile the AOT module if one of its dependencies changes
831 static MonoDl*
832 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
834 char *fname, *cmd, *tmp2, *aot_options;
835 const char *home;
836 MonoDl *module;
837 gboolean res;
838 gchar *out, *err;
839 gint exit_status;
841 *aot_name = NULL;
843 if (assembly->image->dynamic)
844 return NULL;
846 create_cache_structure ();
848 home = g_get_home_dir ();
850 tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
851 fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
852 *aot_name = fname;
853 g_free (tmp2);
855 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
856 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
858 if (!module) {
859 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
861 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
863 aot_options = g_strdup_printf ("outfile=%s", fname);
865 if (spawn_compiler) {
866 /* FIXME: security */
867 /* FIXME: Has to pass the assembly loading path to the child process */
868 cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
870 res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
872 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
873 if (res) {
874 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
875 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
876 else
877 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
878 g_free (out);
879 g_free (err);
881 #endif
882 g_free (cmd);
883 } else {
884 res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
885 if (!res) {
886 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
887 } else {
888 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
892 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
894 g_free (aot_options);
897 return module;
900 static void
901 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
903 if (globals) {
904 int global_index;
905 guint16 *table, *entry;
906 guint16 table_size;
907 guint32 hash;
909 /* The first entry points to the hash */
910 table = globals [0];
911 globals ++;
913 table_size = table [0];
914 table ++;
916 hash = mono_metadata_str_hash (name) % table_size;
918 entry = &table [hash * 2];
920 /* Search the hash for the index into the globals table */
921 global_index = -1;
922 while (entry [0] != 0) {
923 guint32 index = entry [0] - 1;
924 guint32 next = entry [1];
926 //printf ("X: %s %s\n", (char*)globals [index * 2], name);
928 if (!strcmp (globals [index * 2], name)) {
929 global_index = index;
930 break;
933 if (next != 0) {
934 entry = &table [next * 2];
935 } else {
936 break;
940 if (global_index != -1)
941 *value = globals [global_index * 2 + 1];
942 else
943 *value = NULL;
944 } else {
945 char *err = mono_dl_symbol (module, name, value);
947 if (err)
948 g_free (err);
952 #ifndef SHT_ARM_EXIDX
953 #define SHT_ARM_EXIDX 0x70000001
954 #endif
956 #if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME)
957 static int
958 dl_callback (struct dl_phdr_info *info, size_t size, void *data)
960 int j;
961 MonoAotModule *amodule = data;
963 if (!strcmp (amodule->aot_name, info->dlpi_name)) {
964 for (j = 0; j < info->dlpi_phnum; j++) {
965 if (info->dlpi_phdr [j].p_type == PT_GNU_EH_FRAME)
966 amodule->eh_frame_hdr = (guint8*)(info->dlpi_addr + info->dlpi_phdr [j].p_vaddr);
967 if (info->dlpi_phdr [j].p_type == SHT_ARM_EXIDX) {
968 amodule->arm_exidx = (guint8*)(info->dlpi_addr + info->dlpi_phdr [j].p_vaddr);
969 amodule->arm_exidx_size = info->dlpi_phdr [j].p_filesz;
972 return 1;
973 } else {
974 return 0;
977 #endif
979 static void
980 load_aot_module (MonoAssembly *assembly, gpointer user_data)
982 char *aot_name;
983 MonoAotModule *amodule;
984 MonoDl *sofile;
985 gboolean usable = TRUE;
986 char *saved_guid = NULL;
987 char *aot_version = NULL;
988 char *runtime_version, *build_info;
989 char *opt_flags = NULL;
990 gpointer *globals;
991 gboolean full_aot = FALSE;
992 MonoAotFileInfo *file_info = NULL;
993 int i;
994 gpointer *got_addr;
996 if (mono_compile_aot)
997 return;
999 if (assembly->image->aot_module)
1001 * Already loaded. This can happen because the assembly loading code might invoke
1002 * the assembly load hooks multiple times for the same assembly.
1004 return;
1006 if (assembly->image->dynamic)
1007 return;
1009 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
1010 return;
1012 mono_aot_lock ();
1013 if (static_aot_modules)
1014 globals = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1015 else
1016 globals = NULL;
1017 mono_aot_unlock ();
1019 if (globals) {
1020 /* Statically linked AOT module */
1021 sofile = NULL;
1022 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1023 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1024 } else {
1025 if (use_aot_cache)
1026 sofile = load_aot_module_from_cache (assembly, &aot_name);
1027 else {
1028 char *err;
1029 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1031 sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1033 if (!sofile) {
1034 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1035 g_free (err);
1040 if (!sofile && !globals) {
1041 if (mono_aot_only) {
1042 fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1043 exit (1);
1045 g_free (aot_name);
1046 return;
1049 find_symbol (sofile, globals, "mono_assembly_guid", (gpointer *) &saved_guid);
1050 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &aot_version);
1051 find_symbol (sofile, globals, "mono_aot_opt_flags", (gpointer *)&opt_flags);
1052 find_symbol (sofile, globals, "mono_runtime_version", (gpointer *)&runtime_version);
1053 find_symbol (sofile, globals, "mono_aot_got_addr", (gpointer *)&got_addr);
1055 if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
1056 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s has wrong file format version (expected %s got %s)\n", aot_name, MONO_AOT_FILE_VERSION, aot_version);
1057 usable = FALSE;
1059 else {
1060 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
1061 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
1062 usable = FALSE;
1066 build_info = mono_get_runtime_build_info ();
1067 if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, build_info)))) {
1068 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled against runtime version '%s' while this runtime has version '%s'.\n", aot_name, runtime_version, build_info);
1069 usable = FALSE;
1071 g_free (build_info);
1073 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&file_info);
1074 g_assert (file_info);
1076 full_aot = ((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1078 if (mono_aot_only && !full_aot) {
1079 fprintf (stderr, "Can't use AOT image '%s' in aot-only mode because it is not compiled with --aot=full.\n", aot_name);
1080 exit (1);
1082 if (!mono_aot_only && full_aot) {
1083 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with --aot=full.\n", aot_name);
1084 usable = FALSE;
1087 if ((((MonoAotFileInfo*)file_info)->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1088 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is compiled with LLVM.\n", aot_name);
1089 usable = FALSE;
1092 if (!usable) {
1093 if (mono_aot_only) {
1094 fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode.\n", aot_name);
1095 exit (1);
1097 g_free (aot_name);
1098 if (sofile)
1099 mono_dl_close (sofile);
1100 assembly->image->aot_module = NULL;
1101 return;
1104 amodule = g_new0 (MonoAotModule, 1);
1105 amodule->aot_name = aot_name;
1106 amodule->assembly = assembly;
1108 memcpy (&amodule->info, file_info, sizeof (*file_info));
1110 amodule->got = *got_addr;
1111 amodule->got [0] = assembly->image;
1112 amodule->globals = globals;
1113 amodule->sofile = sofile;
1114 amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1116 /* Read image table */
1118 guint32 table_len, i;
1119 char *table = NULL;
1121 find_symbol (sofile, globals, "mono_image_table", (gpointer *)&table);
1122 g_assert (table);
1124 table_len = *(guint32*)table;
1125 table += sizeof (guint32);
1126 amodule->image_table = g_new0 (MonoImage*, table_len);
1127 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1128 amodule->image_guids = g_new0 (char*, table_len);
1129 amodule->image_table_len = table_len;
1130 for (i = 0; i < table_len; ++i) {
1131 MonoAssemblyName *aname = &(amodule->image_names [i]);
1133 aname->name = g_strdup (table);
1134 table += strlen (table) + 1;
1135 amodule->image_guids [i] = g_strdup (table);
1136 table += strlen (table) + 1;
1137 if (table [0] != 0)
1138 aname->culture = g_strdup (table);
1139 table += strlen (table) + 1;
1140 memcpy (aname->public_key_token, table, strlen (table) + 1);
1141 table += strlen (table) + 1;
1143 table = ALIGN_PTR_TO (table, 8);
1144 aname->flags = *(guint32*)table;
1145 table += 4;
1146 aname->major = *(guint32*)table;
1147 table += 4;
1148 aname->minor = *(guint32*)table;
1149 table += 4;
1150 aname->build = *(guint32*)table;
1151 table += 4;
1152 aname->revision = *(guint32*)table;
1153 table += 4;
1157 /* Read method and method_info tables */
1158 find_symbol (sofile, globals, "code_offsets", (gpointer*)&amodule->code_offsets);
1159 find_symbol (sofile, globals, "methods", (gpointer*)&amodule->code);
1160 find_symbol (sofile, globals, "methods_end", (gpointer*)&amodule->code_end);
1161 find_symbol (sofile, globals, "method_info_offsets", (gpointer*)&amodule->method_info_offsets);
1162 find_symbol (sofile, globals, "ex_info_offsets", (gpointer*)&amodule->ex_info_offsets);
1163 find_symbol (sofile, globals, "blob", (gpointer*)&amodule->blob);
1164 find_symbol (sofile, globals, "class_info_offsets", (gpointer*)&amodule->class_info_offsets);
1165 find_symbol (sofile, globals, "class_name_table", (gpointer *)&amodule->class_name_table);
1166 find_symbol (sofile, globals, "extra_method_table", (gpointer *)&amodule->extra_method_table);
1167 find_symbol (sofile, globals, "extra_method_info_offsets", (gpointer *)&amodule->extra_method_info_offsets);
1168 find_symbol (sofile, globals, "got_info_offsets", (gpointer*)&amodule->got_info_offsets);
1169 find_symbol (sofile, globals, "specific_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC]));
1170 find_symbol (sofile, globals, "static_rgctx_trampolines", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX]));
1171 find_symbol (sofile, globals, "imt_thunks", (gpointer*)&(amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK]));
1172 find_symbol (sofile, globals, "unwind_info", (gpointer)&amodule->unwind_info);
1173 find_symbol (sofile, globals, "mem_end", (gpointer*)&amodule->mem_end);
1175 amodule->mem_begin = amodule->code;
1177 find_symbol (sofile, globals, "plt", (gpointer*)&amodule->plt);
1178 find_symbol (sofile, globals, "plt_end", (gpointer*)&amodule->plt_end);
1180 if (make_unreadable) {
1181 #ifndef TARGET_WIN32
1182 guint8 *addr;
1183 guint8 *page_start, *page_end;
1184 int err, len;
1186 addr = amodule->mem_begin;
1187 len = amodule->mem_end - amodule->mem_begin;
1189 /* Round down in both directions to avoid modifying data which is not ours */
1190 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1191 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1192 if (page_end > page_start) {
1193 err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1194 g_assert (err == 0);
1196 #endif
1199 mono_aot_lock ();
1201 aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1202 aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1204 g_hash_table_insert (aot_modules, assembly, amodule);
1205 mono_aot_unlock ();
1207 mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1209 assembly->image->aot_module = amodule;
1211 #if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME)
1212 /* Lookup the address of the .eh_frame_hdr () section if available */
1213 dl_iterate_phdr (dl_callback, amodule);
1214 #endif
1216 if (mono_aot_only) {
1217 if (mono_defaults.corlib) {
1218 /* The second got slot contains the mscorlib got addr */
1219 MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1221 amodule->got [1] = mscorlib_amodule->got;
1222 } else {
1223 amodule->got [1] = amodule->got;
1228 * Since we store methoddef and classdef tokens when referring to methods/classes in
1229 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1230 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1231 * non-lazily, since we can't handle out-of-date errors later.
1232 * The cached class info also depends on the exact assemblies.
1234 for (i = 0; i < amodule->image_table_len; ++i)
1235 load_image (amodule, i, FALSE);
1237 if (amodule->out_of_date) {
1238 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);
1239 if (mono_aot_only) {
1240 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);
1241 exit (1);
1244 else
1245 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1249 * mono_aot_register_globals:
1251 * This is called by the ctor function in AOT images compiled with the
1252 * 'no-dlsym' option.
1254 void
1255 mono_aot_register_globals (gpointer *globals)
1257 g_assert_not_reached ();
1261 * mono_aot_register_module:
1263 * This should be called by embedding code to register AOT modules statically linked
1264 * into the executable. AOT_INFO should be the value of the
1265 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1267 void
1268 mono_aot_register_module (gpointer *aot_info)
1270 gpointer *globals;
1271 char *aname;
1273 globals = aot_info;
1274 g_assert (globals);
1276 /* Determine the assembly name */
1277 find_symbol (NULL, globals, "mono_aot_assembly_name", (gpointer*)&aname);
1278 g_assert (aname);
1280 /* This could be called before startup */
1281 if (aot_modules)
1282 mono_aot_lock ();
1284 if (!static_aot_modules)
1285 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1287 g_hash_table_insert (static_aot_modules, aname, globals);
1289 if (aot_modules)
1290 mono_aot_unlock ();
1293 void
1294 mono_aot_init (void)
1296 InitializeCriticalSection (&aot_mutex);
1297 aot_modules = g_hash_table_new (NULL, NULL);
1299 mono_install_assembly_load_hook (load_aot_module, NULL);
1301 if (g_getenv ("MONO_LASTAOT"))
1302 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1303 if (g_getenv ("MONO_AOT_CACHE"))
1304 use_aot_cache = TRUE;
1307 static gboolean
1308 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1310 guint32 flags;
1312 info->vtable_size = decode_value (buf, &buf);
1313 if (info->vtable_size == -1)
1314 /* Generic type */
1315 return FALSE;
1316 flags = decode_value (buf, &buf);
1317 info->ghcimpl = (flags >> 0) & 0x1;
1318 info->has_finalize = (flags >> 1) & 0x1;
1319 info->has_cctor = (flags >> 2) & 0x1;
1320 info->has_nested_classes = (flags >> 3) & 0x1;
1321 info->blittable = (flags >> 4) & 0x1;
1322 info->has_references = (flags >> 5) & 0x1;
1323 info->has_static_refs = (flags >> 6) & 0x1;
1324 info->no_special_static_fields = (flags >> 7) & 0x1;
1325 info->is_generic_container = (flags >> 8) & 0x1;
1327 if (info->has_cctor) {
1328 MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, NULL, NULL, buf, &buf);
1329 if (!cctor_image)
1330 return FALSE;
1332 if (info->has_finalize) {
1333 info->finalize_image = decode_method_ref (module, &info->finalize_token, NULL, NULL, buf, &buf);
1334 if (!info->finalize_image)
1335 return FALSE;
1338 info->instance_size = decode_value (buf, &buf);
1339 info->class_size = decode_value (buf, &buf);
1340 info->packing_size = decode_value (buf, &buf);
1341 info->min_align = decode_value (buf, &buf);
1343 *endbuf = buf;
1345 return TRUE;
1348 gpointer
1349 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1351 int i;
1352 MonoClass *klass = vtable->klass;
1353 MonoAotModule *aot_module = klass->image->aot_module;
1354 guint8 *info, *p;
1355 MonoCachedClassInfo class_info;
1356 gboolean err;
1357 guint32 token;
1358 MonoImage *image;
1359 gboolean no_aot_trampoline;
1361 if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !aot_module)
1362 return NULL;
1364 info = &aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1365 p = info;
1367 err = decode_cached_class_info (aot_module, &class_info, p, &p);
1368 if (!err)
1369 return NULL;
1371 for (i = 0; i < slot; ++i)
1372 decode_method_ref (aot_module, &token, NULL, NULL, p, &p);
1374 image = decode_method_ref (aot_module, &token, NULL, &no_aot_trampoline, p, &p);
1375 if (!image)
1376 return NULL;
1377 if (no_aot_trampoline)
1378 return NULL;
1380 if (mono_metadata_token_index (token) == 0)
1381 return NULL;
1383 return mono_aot_get_method_from_token (domain, image, token);
1386 gboolean
1387 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1389 MonoAotModule *aot_module = klass->image->aot_module;
1390 guint8 *p;
1391 gboolean err;
1393 if (klass->rank || !aot_module)
1394 return FALSE;
1396 p = (guint8*)&aot_module->blob [mono_aot_get_offset (aot_module->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1398 err = decode_cached_class_info (aot_module, res, p, &p);
1399 if (!err)
1400 return FALSE;
1402 return TRUE;
1406 * mono_aot_get_class_from_name:
1408 * Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1409 * using a cache stored in the AOT file.
1410 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1412 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
1413 * found.
1415 gboolean
1416 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1418 MonoAotModule *aot_module = image->aot_module;
1419 guint16 *table, *entry;
1420 guint16 table_size;
1421 guint32 hash;
1422 char full_name_buf [1024];
1423 char *full_name;
1424 const char *name2, *name_space2;
1425 MonoTableInfo *t;
1426 guint32 cols [MONO_TYPEDEF_SIZE];
1427 GHashTable *nspace_table;
1429 if (!aot_module || !aot_module->class_name_table)
1430 return FALSE;
1432 mono_aot_lock ();
1434 *klass = NULL;
1436 /* First look in the cache */
1437 if (!aot_module->name_cache)
1438 aot_module->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1439 nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
1440 if (nspace_table) {
1441 *klass = g_hash_table_lookup (nspace_table, name);
1442 if (*klass) {
1443 mono_aot_unlock ();
1444 return TRUE;
1448 table_size = aot_module->class_name_table [0];
1449 table = aot_module->class_name_table + 1;
1451 if (name_space [0] == '\0')
1452 full_name = g_strdup_printf ("%s", name);
1453 else {
1454 if (strlen (name_space) + strlen (name) < 1000) {
1455 sprintf (full_name_buf, "%s.%s", name_space, name);
1456 full_name = full_name_buf;
1457 } else {
1458 full_name = g_strdup_printf ("%s.%s", name_space, name);
1461 hash = mono_metadata_str_hash (full_name) % table_size;
1462 if (full_name != full_name_buf)
1463 g_free (full_name);
1465 entry = &table [hash * 2];
1467 if (entry [0] != 0) {
1468 t = &image->tables [MONO_TABLE_TYPEDEF];
1470 while (TRUE) {
1471 guint32 index = entry [0];
1472 guint32 next = entry [1];
1473 guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1475 name_table_accesses ++;
1477 mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1479 name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1480 name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1482 if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1483 mono_aot_unlock ();
1484 *klass = mono_class_get (image, token);
1486 /* Add to cache */
1487 if (*klass) {
1488 mono_aot_lock ();
1489 nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
1490 if (!nspace_table) {
1491 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1492 g_hash_table_insert (aot_module->name_cache, (char*)name_space2, nspace_table);
1494 g_hash_table_insert (nspace_table, (char*)name2, *klass);
1495 mono_aot_unlock ();
1497 return TRUE;
1500 if (next != 0) {
1501 entry = &table [next * 2];
1502 } else {
1503 break;
1508 mono_aot_unlock ();
1510 return TRUE;
1513 #define DW_EH_PE_omit 0xff
1514 #define DW_EH_PE_uleb128 0x01
1515 #define DW_EH_PE_udata2 0x02
1516 #define DW_EH_PE_udata4 0x03
1517 #define DW_EH_PE_udata8 0x04
1518 #define DW_EH_PE_sleb128 0x09
1519 #define DW_EH_PE_sdata2 0x0A
1520 #define DW_EH_PE_sdata4 0x0B
1521 #define DW_EH_PE_sdata8 0x0C
1523 #define DW_EH_PE_absptr 0x00
1524 #define DW_EH_PE_pcrel 0x10
1525 #define DW_EH_PE_datarel 0x30
1526 #define DW_EH_PE_omit 0xff
1528 typedef struct
1530 guint8 version;
1531 guint8 eh_frame_ptr_enc;
1532 guint8 fde_count_enc;
1533 guint8 table_enc;
1534 guint8 rest;
1535 } eh_frame_hdr;
1538 * decode_eh_frame:
1540 * Decode the exception handling information in the .eh_frame section of the AOT
1541 * file belong to CODE, and construct a MonoJitInfo structure from it.
1542 * LOCKING: Acquires the domain lock.
1544 static G_GNUC_UNUSED MonoJitInfo*
1545 decode_eh_frame (MonoAotModule *amodule, MonoDomain *domain,
1546 MonoMethod *method, guint8 *code, MonoJitInfo *orig_jinfo,
1547 int extra_size)
1549 eh_frame_hdr *hdr;
1550 guint8 *p;
1551 guint8 *eh_frame, *unwind_info;
1552 guint32 eh_frame_ptr;
1553 int fde_count;
1554 gint32 *table;
1555 int i, pos, left, right, offset, offset1, offset2;
1556 guint32 unw_len, code_len;
1557 MonoJitExceptionInfo *ei;
1558 guint32 ei_len;
1559 gpointer *type_info;
1560 MonoJitInfo *jinfo;
1562 g_assert (amodule->eh_frame_hdr);
1564 // http://refspecs.freestandards.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html
1565 hdr = (eh_frame_hdr*)amodule->eh_frame_hdr;
1566 g_assert (hdr->version == 1);
1567 g_assert (hdr->eh_frame_ptr_enc == (DW_EH_PE_pcrel | DW_EH_PE_sdata4));
1568 g_assert (hdr->fde_count_enc == DW_EH_PE_udata4);
1569 g_assert (hdr->table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4));
1571 p = &(hdr->rest);
1572 eh_frame_ptr = *(guint32*)p;
1573 p += 4;
1574 fde_count = *(guint32*)p;
1575 p += 4;
1576 table = (gint32*)p;
1578 /* Binary search in the table to find the entry for code */
1579 offset = code - amodule->eh_frame_hdr;
1581 left = 0;
1582 right = fde_count;
1583 while (TRUE) {
1584 pos = (left + right) / 2;
1586 offset1 = table [(pos * 2)];
1587 if (pos + 1 == fde_count)
1588 /* FIXME: */
1589 offset2 = amodule->code_end - amodule->code;
1590 else
1591 offset2 = table [(pos + 1) * 2];
1593 if (offset < offset1)
1594 right = pos;
1595 else if (offset >= offset2)
1596 left = pos + 1;
1597 else
1598 break;
1601 g_assert (code >= amodule->eh_frame_hdr + table [(pos * 2)]);
1602 if (pos < fde_count)
1603 g_assert (code < amodule->eh_frame_hdr + table [(pos * 2) + 2]);
1605 eh_frame = amodule->eh_frame_hdr + table [(pos * 2) + 1];
1607 unwind_info = mono_unwind_decode_fde (eh_frame, &unw_len, &code_len, &ei, &ei_len, &type_info);
1610 * LLVM might represent one IL region with multiple regions, so have to
1611 * allocate a new JI.
1613 if (ei_len) {
1614 jinfo =
1615 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * ei_len) + extra_size);
1616 } else {
1617 jinfo = orig_jinfo;
1620 jinfo->code_size = code_len;
1621 jinfo->used_regs = mono_cache_unwind_info (unwind_info, unw_len);
1622 jinfo->method = method;
1623 jinfo->code_start = code;
1624 jinfo->domain_neutral = 0;
1625 /* This signals that used_regs points to a normal cached unwind info */
1626 jinfo->from_aot = 0;
1627 jinfo->num_clauses = ei_len;
1629 for (i = 0; i < ei_len; ++i) {
1631 * orig_jinfo contains the original IL exception info saved by the AOT
1632 * compiler, we have to combine that with the information produced by LLVM
1634 /* The type_info entries contain IL clause indexes */
1635 int clause_index = *(gint32*)type_info [i];
1636 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
1637 MonoJitExceptionInfo *orig_jei = &orig_jinfo->clauses [clause_index];
1639 g_assert (clause_index < orig_jinfo->num_clauses);
1640 jei->flags = orig_jei->flags;
1641 jei->data.catch_class = orig_jei->data.catch_class;
1643 jei->try_start = ei [i].try_start;
1644 jei->try_end = ei [i].try_end;
1645 jei->handler_start = ei [i].handler_start;
1648 return jinfo;
1651 #ifdef TARGET_ARM
1653 /* The offsets in the table are 31 bits long, have to extend them to 32 */
1654 #define EXTEND_PREL31(val) ((((gint32)(val)) << 1) >> 1)
1656 static inline guint32
1657 decode_uleb128 (guint8 *buf, guint8 **endbuf)
1659 guint8 *p = buf;
1660 guint32 res = 0;
1661 int shift = 0;
1663 while (TRUE) {
1664 guint8 b = *p;
1665 p ++;
1667 res = res | (((int)(b & 0x7f)) << shift);
1668 if (!(b & 0x80))
1669 break;
1670 shift += 7;
1673 *endbuf = p;
1675 return res;
1678 static GSList*
1679 decode_arm_eh_ops (guint8 *unwind_ops, int nops)
1681 int i, vsp_reg, vsp_offset;
1682 GSList *ops;
1683 gint32 *reg_offsets;
1686 * Have to convert the ARM unwind info into DWARF unwind info.
1687 * The ARM unwind info specifies a simple set of instructions which need to be
1688 * executed during unwinding. It manipulates a virtual stack pointer (vsp). The
1689 * connection with DWARF unwind info is the following: after all ARM unwind
1690 * opcodes have been executed, the stack should be completely unwound, i.e.
1691 * vsp == DWARF CFA. This allows us to construct the DWARF opcodes corresponding
1692 * to the ARM opcodes.
1693 * The ARM unwind info is not instruction precise, i. e. it can't handle
1694 * async exceptions etc.
1696 /* The reg used to compute the initial value of vsp */
1697 vsp_reg = ARMREG_SP;
1698 /* The offset between vsp_reg and the CFA */
1699 vsp_offset = 0;
1701 /* The register save offsets from the initial value of vsp */
1702 reg_offsets = g_new0 (gint32, 16);
1703 for (i = 0; i < 16; ++i)
1704 reg_offsets [i] = -1;
1706 /* section 9.3 in the ehabi doc */
1707 for (i = 0; i < nops; ++i) {
1708 guint8 op = unwind_ops [i];
1710 if ((op >> 6) == 0) {
1711 /* vsp = vsp + (xxxxxx << 2) + 4. */
1712 vsp_offset += ((op & 0x3f) << 2) + 4;
1713 } else if ((op >> 6) == 1) {
1714 /* vsp = vsp - (xxxxxx << 2) - 4. */
1715 vsp_offset -= ((op & 0x3f) << 2) + 4;
1716 } else if (op == 0xb2) {
1717 /* vsp = vsp = vsp + 0x204 + (uleb128 << 2) */
1718 guint8 *p = unwind_ops + i + 1;
1719 guint32 v = decode_uleb128 (p, &p);
1721 vsp_offset += 0x204 + (v << 2);
1722 i = (p - unwind_ops) - 1;
1723 } else if (op >= 0x80 && op <= 0x8f) {
1724 /* pop registers */
1725 guint8 op2;
1726 GSList *regs;
1727 int j;
1729 g_assert (i + 1 < nops);
1730 op2 = unwind_ops [i + 1];
1732 regs = NULL;
1733 for (j = 0; j < 8; ++j)
1734 if (op2 & (0x1 << j))
1735 regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R4 + j));
1736 for (j = 0; j < 4; ++j)
1737 if (op & (0x1 << j))
1738 regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R12 + j));
1739 g_assert (regs);
1741 for (j = 0; j < g_slist_length (regs); ++j)
1742 reg_offsets [GPOINTER_TO_UINT (g_slist_nth (regs, j)->data)] = vsp_offset + (j * 4);
1744 vsp_offset += g_slist_length (regs) * 4;
1746 g_slist_free (regs);
1748 i ++;
1749 } else if (op >= 0xa8 && op <= 0xaf) {
1750 GSList *regs;
1751 int j;
1753 /* pop r4-r[4 + nnn], r14 */
1755 regs = NULL;
1756 for (j = 0; j <= (op & 0x7); ++j)
1757 regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R4 + j));
1758 regs = g_slist_append (regs, GUINT_TO_POINTER (ARMREG_R14));
1760 for (j = 0; j < g_slist_length (regs); ++j)
1761 reg_offsets [GPOINTER_TO_UINT (g_slist_nth (regs, j)->data)] = vsp_offset + (j * 4);
1763 vsp_offset += g_slist_length (regs) * 4;
1765 g_slist_free (regs);
1766 } else if (op == 0xb0) {
1767 /* finish */
1768 break;
1769 } else if (op >= 0x90 && op <= 0x9f && op != 0x9d && op != 0x9f) {
1770 /* vsp = <reg> */
1771 vsp_reg = op & 0xf;
1772 vsp_offset = 0;
1773 } else {
1774 int j;
1776 for (j = 0; j < nops; ++j)
1777 printf ("%x ", unwind_ops [j]);
1778 printf (" / %d\n", i);
1779 g_assert_not_reached ();
1783 ops = NULL;
1785 /* vsp_reg + vsp_offset = CFA */
1786 mono_add_unwind_op_def_cfa (ops, (guint8*)NULL, (guint8*)NULL, vsp_reg, vsp_offset);
1788 for (i = 0; i < 16; ++i) {
1789 if (reg_offsets [i] != -1)
1790 /* The reg is saved at vsp_reg + reg_offset [i] == CFA - (vsp_offset - reg_offset [i]) */
1791 mono_add_unwind_op_offset (ops, (guint8*)NULL, (guint8*)NULL, i, - (vsp_offset - reg_offsets [i]));
1794 return ops;
1798 * decode_arm_exidx:
1800 * Decode the exception handling information in the .ARM.exidx section of the AOT
1801 * file belong to CODE, and construct a MonoJitInfo structure from it.
1802 * LOCKING: Acquires the domain lock.
1804 static void
1805 decode_arm_exidx (MonoAotModule *amodule, MonoDomain *domain,
1806 MonoMethod *method, guint8 *code, guint32 code_len, MonoJitInfo *jinfo)
1808 guint32 *table;
1809 guint8 *base, *code1, *code2;
1810 int i, pos, left, right, offset, offset1, offset2, count, nwords, nops;
1811 guint32 entry;
1812 guint8 unwind_ops [64];
1813 GSList *ops;
1814 guint8 *unwind_info;
1815 guint32 unw_len;
1817 g_assert (amodule->arm_exidx);
1819 table = (guint32*)amodule->arm_exidx;
1822 * The table format is described in:
1823 * infocenter.arm.com/help/topic/com.arm.doc.../IHI0038A_ehabi.pdf
1826 base = amodule->arm_exidx;
1827 count = amodule->arm_exidx_size / 8;
1829 /* Binary search in the table to find the entry for code */
1830 offset = code - base;
1832 left = 0;
1833 right = count;
1834 while (TRUE) {
1835 pos = (left + right) / 2;
1837 if (left == right)
1838 break;
1840 offset1 = EXTEND_PREL31 (table [(pos * 2)]);
1841 code1 = (guint8*)&(table [pos * 2]) + offset1;
1842 if (pos + 1 == count)
1843 /* FIXME: */
1844 offset2 = amodule->code_end - amodule->code;
1845 else
1846 offset2 = EXTEND_PREL31 (table [(pos + 1) * 2]);
1847 code2 = (guint8*)&(table [(pos + 1) * 2]) + offset2;
1849 if (code < code1)
1850 right = pos;
1851 else if (code >= code2)
1852 left = pos + 1;
1853 else
1854 break;
1857 if (code >= code1) {
1859 * The linker might merge duplicate unwind table entries, so
1860 * offset1 and offset2 might point to another method, but this is not a problem.
1862 code1 = (guint8*)&(table [pos * 2]) + offset1;
1863 code2 = (guint8*)&(table [(pos + 1) * 2]) + offset2;
1865 g_assert (code >= code1);
1866 if (pos < count)
1867 g_assert (code < code2);
1869 entry = table [(pos * 2) + 1];
1871 /* inline entry, compact model, personality routine 0 */
1872 if ((entry & 0xff000000) == 0x80000000) {
1873 nops = 3;
1874 unwind_ops [0] = (entry & 0x00ff0000) >> 16;
1875 unwind_ops [1] = (entry & 0x0000ff00) >> 8;
1876 unwind_ops [2] = (entry & 0x000000ff) >> 0;
1878 ops = decode_arm_eh_ops (unwind_ops, nops);
1879 } else if ((entry & 0x80000000) == 0) {
1880 /* non-inline entry */
1881 guint8 *data = (guint8*)&table [(pos * 2) + 1] + EXTEND_PREL31 (entry);
1883 entry = ((guint32*)data) [0];
1885 /* compact model, personality routine 1 */
1886 g_assert ((entry & 0xff000000) == 0x81000000);
1888 nwords = (entry & 0x00ff0000) >> 16;
1889 nops = nwords * 4 + 2;
1890 g_assert (nops < 64);
1892 unwind_ops [0] = (entry & 0x0000ff00) >> 8;
1893 unwind_ops [1] = (entry & 0x000000ff) >> 0;
1895 for (i = 0; i < nwords; ++i) {
1896 entry = ((guint32*)data) [1 + i];
1897 unwind_ops [(i * 4) + 2] = (entry & 0xff000000) >> 24;
1898 unwind_ops [(i * 4) + 2 + 1] = (entry & 0x00ff0000) >> 16;
1899 unwind_ops [(i * 4) + 2 + 2] = (entry & 0x0000ff00) >> 8;
1900 unwind_ops [(i * 4) + 2 + 3] = (entry & 0x000000ff) >> 0;
1903 ops = decode_arm_eh_ops (unwind_ops, nops);
1904 } else {
1905 NOT_IMPLEMENTED;
1908 unwind_info = mono_unwind_ops_encode (ops, &unw_len);
1909 } else {
1910 /* The method has no unwind info */
1911 unwind_info = NULL;
1912 unw_len = 0;
1915 jinfo->code_size = code_len;
1916 jinfo->used_regs = mono_cache_unwind_info (unwind_info, unw_len);
1917 jinfo->method = method;
1918 jinfo->code_start = code;
1919 jinfo->domain_neutral = 0;
1920 /* This signals that used_regs points to a normal cached unwind info */
1921 jinfo->from_aot = 0;
1923 #endif
1926 * LOCKING: Acquires the domain lock.
1928 static MonoJitInfo*
1929 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
1930 MonoMethod *method, guint8* ex_info, guint8 *addr,
1931 guint8 *code, guint32 code_len)
1933 int i, buf_len;
1934 MonoJitInfo *jinfo;
1935 guint used_int_regs, flags;
1936 gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes;
1937 gboolean from_llvm;
1938 guint8 *p;
1939 int generic_info_size, try_holes_info_size, num_holes;
1941 /* Load the method info from the AOT file */
1943 p = ex_info;
1944 flags = decode_value (p, &p);
1945 has_generic_jit_info = (flags & 1) != 0;
1946 has_dwarf_unwind_info = (flags & 2) != 0;
1947 has_clauses = (flags & 4) != 0;
1948 has_seq_points = (flags & 8) != 0;
1949 from_llvm = (flags & 16) != 0;
1950 has_try_block_holes = (flags & 32) != 0;
1952 if (has_dwarf_unwind_info) {
1953 guint32 offset;
1955 offset = decode_value (p, &p);
1956 g_assert (offset < (1 << 30));
1957 used_int_regs = offset;
1958 } else {
1959 used_int_regs = decode_value (p, &p);
1961 if (has_generic_jit_info)
1962 generic_info_size = sizeof (MonoGenericJitInfo);
1963 else
1964 generic_info_size = 0;
1966 if (has_try_block_holes) {
1967 num_holes = decode_value (p, &p);
1968 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
1969 } else {
1970 num_holes = try_holes_info_size = 0;
1972 /* Exception table */
1973 if (has_clauses) {
1974 int num_clauses = decode_value (p, &p);
1976 jinfo =
1977 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size);
1978 jinfo->num_clauses = num_clauses;
1980 for (i = 0; i < num_clauses; ++i) {
1981 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
1983 ei->flags = decode_value (p, &p);
1985 if (from_llvm) {
1986 if (decode_value (p, &p))
1987 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
1989 /* The rest of the info is in the DWARF EH section */
1990 continue;
1993 ei->exvar_offset = decode_value (p, &p);
1995 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
1996 ei->data.filter = code + decode_value (p, &p);
1997 else {
1998 if (decode_value (p, &p))
1999 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2002 ei->try_start = code + decode_value (p, &p);
2003 ei->try_end = code + decode_value (p, &p);
2004 ei->handler_start = code + decode_value (p, &p);
2007 else {
2008 jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + generic_info_size + try_holes_info_size);
2011 if (from_llvm) {
2012 /* LLVM compiled method */
2013 /* The info is in the .eh_frame section */
2014 #ifdef TARGET_ARM
2015 decode_arm_exidx (amodule, domain, method, code, code_len, jinfo);
2016 #else
2017 jinfo = decode_eh_frame (amodule, domain, method, code, jinfo, generic_info_size);
2018 #endif
2019 jinfo->from_llvm = 1;
2020 } else {
2021 jinfo->code_size = code_len;
2022 jinfo->used_regs = used_int_regs;
2023 jinfo->method = method;
2024 jinfo->code_start = code;
2025 jinfo->domain_neutral = 0;
2026 jinfo->from_aot = 1;
2029 if (has_generic_jit_info) {
2030 MonoGenericJitInfo *gi;
2032 jinfo->has_generic_jit_info = 1;
2034 gi = mono_jit_info_get_generic_jit_info (jinfo);
2035 g_assert (gi);
2037 gi->has_this = decode_value (p, &p);
2038 gi->this_reg = decode_value (p, &p);
2039 gi->this_offset = decode_value (p, &p);
2041 /* This currently contains no data */
2042 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2044 jinfo->method = decode_method_ref_2 (amodule, p, &p);
2047 if (has_try_block_holes) {
2048 MonoTryBlockHoleTableJitInfo *table;
2050 jinfo->has_try_block_holes = 1;
2052 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2053 g_assert (table);
2055 table->num_holes = (guint16)num_holes;
2056 for (i = 0; i < num_holes; ++i) {
2057 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2058 hole->clause = decode_value (p, &p);
2059 hole->length = decode_value (p, &p);
2060 hole->offset = decode_value (p, &p);
2064 if (has_seq_points) {
2065 MonoSeqPointInfo *seq_points;
2066 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2068 int len = decode_value (p, &p);
2070 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2071 seq_points->len = len;
2072 last_il_offset = last_native_offset = 0;
2073 for (i = 0; i < len; ++i) {
2074 SeqPoint *sp = &seq_points->seq_points [i];
2075 il_offset = last_il_offset + decode_value (p, &p);
2076 native_offset = last_native_offset + decode_value (p, &p);
2078 sp->il_offset = il_offset;
2079 sp->native_offset = native_offset;
2081 sp->next_len = decode_value (p, &p);
2082 sp->next = g_new (int, sp->next_len);
2083 for (j = 0; j < sp->next_len; ++j)
2084 sp->next [j] = decode_value (p, &p);
2086 last_il_offset = il_offset;
2087 last_native_offset = native_offset;
2090 mono_domain_lock (domain);
2091 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2092 mono_domain_unlock (domain);
2095 /* Load debug info */
2096 buf_len = decode_value (p, &p);
2097 mono_debug_add_aot_method (domain, method, code, p, buf_len);
2099 if (amodule != jinfo->method->klass->image->aot_module) {
2100 mono_aot_lock ();
2101 if (!ji_to_amodule)
2102 ji_to_amodule = g_hash_table_new (NULL, NULL);
2103 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2104 mono_aot_unlock ();
2107 return jinfo;
2111 * mono_aot_get_unwind_info:
2113 * Return a pointer to the DWARF unwind info belonging to JI.
2115 guint8*
2116 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2118 MonoAotModule *amodule = ji->method->klass->image->aot_module;
2119 guint8 *p;
2120 guint8 *code = ji->code_start;
2122 g_assert (amodule);
2123 g_assert (ji->from_aot);
2125 if (!(code >= amodule->code && code <= amodule->code_end)) {
2126 /* ji belongs to a different aot module than amodule */
2127 mono_aot_lock ();
2128 g_assert (ji_to_amodule);
2129 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2130 g_assert (amodule);
2131 g_assert (code >= amodule->code && code <= amodule->code_end);
2132 mono_aot_unlock ();
2135 p = amodule->unwind_info + ji->used_regs;
2136 *unwind_info_len = decode_value (p, &p);
2137 return p;
2140 static G_GNUC_UNUSED int
2141 compare_ints (const void *a, const void *b)
2143 return *(gint32*)a - *(gint32*)b;
2146 static void
2147 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2149 int mid = (lo + hi) / 2;
2150 int i, t_lo, t_hi;
2152 if (lo >= hi)
2153 return;
2155 if (hi - lo < 32) {
2156 for (i = lo; i < hi; ++i)
2157 if (array [(i * 2)] > array [(i * 2) + 2])
2158 break;
2159 if (i == hi)
2160 /* Already sorted */
2161 return;
2164 msort_code_offsets_internal (array, lo, mid, scratch);
2165 msort_code_offsets_internal (array, mid + 1, hi, scratch);
2167 if (array [mid * 2] < array [(mid + 1) * 2])
2168 return;
2170 /* Merge */
2171 t_lo = lo;
2172 t_hi = mid + 1;
2173 for (i = lo; i <= hi; i ++) {
2174 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2175 scratch [(i * 2)] = array [t_lo * 2];
2176 scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2177 t_lo ++;
2178 } else {
2179 scratch [(i * 2)] = array [t_hi * 2];
2180 scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2181 t_hi ++;
2184 for (i = lo; i <= hi; ++i) {
2185 array [(i * 2)] = scratch [i * 2];
2186 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2190 static void
2191 msort_code_offsets (gint32 *array, int len)
2193 gint32 *scratch;
2195 scratch = g_new (gint32, len * 2);
2196 msort_code_offsets_internal (array, 0, len - 1, scratch);
2197 g_free (scratch);
2200 MonoJitInfo *
2201 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2203 int pos, left, right, offset, offset1, offset2, code_len;
2204 int method_index, table_len, is_wrapper;
2205 guint32 token;
2206 MonoAotModule *amodule = image->aot_module;
2207 MonoMethod *method;
2208 MonoJitInfo *jinfo;
2209 guint8 *code, *ex_info, *p;
2210 guint32 *table;
2211 int nmethods = amodule->info.nmethods;
2212 gint32 *code_offsets;
2213 int offsets_len, i;
2215 if (!amodule)
2216 return NULL;
2218 if (domain != mono_get_root_domain ())
2219 /* FIXME: */
2220 return NULL;
2222 offset = (guint8*)addr - amodule->code;
2224 /* Compute a sorted table mapping code offsets to method indexes. */
2225 if (!amodule->sorted_code_offsets) {
2227 code_offsets = g_new0 (gint32, nmethods * 2);
2228 offsets_len = 0;
2229 for (i = 0; i < nmethods; ++i) {
2230 /* Skip the -1 entries to speed up sorting */
2231 if (amodule->code_offsets [i] == 0xffffffff)
2232 continue;
2233 code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2234 code_offsets [(offsets_len *2) + 1] = i;
2235 offsets_len ++;
2237 /* Use a merge sort as this is mostly sorted */
2238 msort_code_offsets (code_offsets, offsets_len);
2239 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2240 for (i = 0; i < offsets_len -1; ++i)
2241 g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2243 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2244 /* Somebody got in before us */
2245 g_free (code_offsets);
2246 amodule->sorted_code_offsets_len = offsets_len;
2249 code_offsets = amodule->sorted_code_offsets;
2250 offsets_len = amodule->sorted_code_offsets_len;
2252 /* Binary search in the sorted_code_offsets table */
2253 left = 0;
2254 right = offsets_len;
2255 while (TRUE) {
2256 pos = (left + right) / 2;
2258 offset1 = code_offsets [(pos * 2)];
2259 if (pos + 1 == offsets_len)
2260 offset2 = amodule->code_end - amodule->code;
2261 else
2262 offset2 = code_offsets [(pos + 1) * 2];
2264 if (offset < offset1)
2265 right = pos;
2266 else if (offset >= offset2)
2267 left = pos + 1;
2268 else
2269 break;
2272 g_assert (offset >= code_offsets [(pos * 2)]);
2273 if (pos + 1 < offsets_len)
2274 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2275 method_index = code_offsets [(pos * 2) + 1];
2277 code = &amodule->code [amodule->code_offsets [method_index]];
2278 ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2280 if (pos == offsets_len - 1)
2281 code_len = amodule->code_end - code;
2282 else
2283 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2285 g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2287 /* Might be a wrapper/extra method */
2288 if (amodule->extra_methods) {
2289 mono_aot_lock ();
2290 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2291 mono_aot_unlock ();
2292 } else {
2293 method = NULL;
2296 if (!method) {
2297 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2299 * This is hit for extra methods which are called directly, so they are
2300 * not in amodule->extra_methods.
2302 table_len = amodule->extra_method_info_offsets [0];
2303 table = amodule->extra_method_info_offsets + 1;
2304 left = 0;
2305 right = table_len;
2306 pos = 0;
2308 /* Binary search */
2309 while (TRUE) {
2310 pos = ((left + right) / 2);
2312 g_assert (pos < table_len);
2314 if (table [pos * 2] < method_index)
2315 left = pos + 1;
2316 else if (table [pos * 2] > method_index)
2317 right = pos;
2318 else
2319 break;
2322 p = amodule->blob + table [(pos * 2) + 1];
2323 is_wrapper = decode_value (p, &p);
2324 g_assert (!is_wrapper);
2325 method = decode_method_ref_2 (amodule, p, &p);
2326 g_assert (method);
2327 } else {
2328 token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2329 method = mono_get_method (image, token, NULL);
2333 /* FIXME: */
2334 g_assert (method);
2336 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2338 jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2340 g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2341 g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2343 /* Add it to the normal JitInfo tables */
2344 mono_jit_info_table_add (domain, jinfo);
2346 return jinfo;
2349 static gboolean
2350 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2352 guint8 *p = buf;
2353 gpointer *table;
2354 MonoImage *image;
2355 int i;
2357 switch (ji->type) {
2358 case MONO_PATCH_INFO_METHOD:
2359 case MONO_PATCH_INFO_METHOD_JUMP:
2360 case MONO_PATCH_INFO_ICALL_ADDR:
2361 case MONO_PATCH_INFO_METHOD_RGCTX: {
2362 guint32 token;
2363 MonoMethod *method;
2364 gboolean no_aot_trampoline;
2366 image = decode_method_ref (aot_module, &token, &method, &no_aot_trampoline, p, &p);
2367 if (!image)
2368 goto cleanup;
2370 if (!method && !mono_aot_only && !no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) {
2371 ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (image, token));
2372 ji->type = MONO_PATCH_INFO_ABS;
2374 else {
2375 if (method)
2376 ji->data.method = method;
2377 else
2378 ji->data.method = mono_get_method (image, token, NULL);
2379 g_assert (ji->data.method);
2380 mono_class_init (ji->data.method->klass);
2382 break;
2384 case MONO_PATCH_INFO_INTERNAL_METHOD:
2385 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2386 guint32 len = decode_value (p, &p);
2388 ji->data.name = (char*)p;
2389 p += len + 1;
2390 break;
2392 case MONO_PATCH_INFO_METHODCONST:
2393 /* Shared */
2394 ji->data.method = decode_method_ref_2 (aot_module, p, &p);
2395 if (!ji->data.method)
2396 goto cleanup;
2397 break;
2398 case MONO_PATCH_INFO_VTABLE:
2399 case MONO_PATCH_INFO_CLASS:
2400 case MONO_PATCH_INFO_IID:
2401 case MONO_PATCH_INFO_ADJUSTED_IID:
2402 /* Shared */
2403 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2404 if (!ji->data.klass)
2405 goto cleanup;
2406 break;
2407 case MONO_PATCH_INFO_CLASS_INIT:
2408 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2409 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2410 if (!ji->data.klass)
2411 goto cleanup;
2412 break;
2413 case MONO_PATCH_INFO_IMAGE:
2414 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2415 if (!ji->data.image)
2416 goto cleanup;
2417 break;
2418 case MONO_PATCH_INFO_FIELD:
2419 case MONO_PATCH_INFO_SFLDA:
2420 /* Shared */
2421 ji->data.field = decode_field_info (aot_module, p, &p);
2422 if (!ji->data.field)
2423 goto cleanup;
2424 break;
2425 case MONO_PATCH_INFO_SWITCH:
2426 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2427 ji->data.table->table_size = decode_value (p, &p);
2428 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2429 ji->data.table->table = (MonoBasicBlock**)table;
2430 for (i = 0; i < ji->data.table->table_size; i++)
2431 table [i] = (gpointer)(gssize)decode_value (p, &p);
2432 break;
2433 case MONO_PATCH_INFO_R4: {
2434 guint32 val;
2436 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2437 val = decode_value (p, &p);
2438 *(float*)ji->data.target = *(float*)&val;
2439 break;
2441 case MONO_PATCH_INFO_R8: {
2442 guint32 val [2];
2443 guint64 v;
2445 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2447 val [0] = decode_value (p, &p);
2448 val [1] = decode_value (p, &p);
2449 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2450 *(double*)ji->data.target = *(double*)&v;
2451 break;
2453 case MONO_PATCH_INFO_LDSTR:
2454 image = load_image (aot_module, decode_value (p, &p), TRUE);
2455 if (!image)
2456 goto cleanup;
2457 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2458 break;
2459 case MONO_PATCH_INFO_RVA:
2460 case MONO_PATCH_INFO_DECLSEC:
2461 case MONO_PATCH_INFO_LDTOKEN:
2462 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2463 /* Shared */
2464 image = load_image (aot_module, decode_value (p, &p), TRUE);
2465 if (!image)
2466 goto cleanup;
2467 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2469 ji->data.token->has_context = decode_value (p, &p);
2470 if (ji->data.token->has_context) {
2471 gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2472 if (!res)
2473 goto cleanup;
2475 break;
2476 case MONO_PATCH_INFO_EXC_NAME:
2477 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2478 if (!ji->data.klass)
2479 goto cleanup;
2480 ji->data.name = ji->data.klass->name;
2481 break;
2482 case MONO_PATCH_INFO_METHOD_REL:
2483 ji->data.offset = decode_value (p, &p);
2484 break;
2485 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2486 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2487 case MONO_PATCH_INFO_MONITOR_ENTER:
2488 case MONO_PATCH_INFO_MONITOR_EXIT:
2489 break;
2490 case MONO_PATCH_INFO_RGCTX_FETCH: {
2491 gboolean res;
2492 MonoJumpInfoRgctxEntry *entry;
2494 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2495 entry->method = decode_method_ref_2 (aot_module, p, &p);
2496 entry->in_mrgctx = decode_value (p, &p);
2497 entry->info_type = decode_value (p, &p);
2498 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2499 entry->data->type = decode_value (p, &p);
2501 res = decode_patch (aot_module, mp, entry->data, p, &p);
2502 if (!res)
2503 goto cleanup;
2504 ji->data.rgctx_entry = entry;
2505 break;
2507 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2508 break;
2509 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2510 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2512 imt_tramp->method = decode_method_ref_2 (aot_module, p, &p);
2513 imt_tramp->vt_offset = decode_value (p, &p);
2515 ji->data.imt_tramp = imt_tramp;
2516 break;
2518 default:
2519 g_warning ("unhandled type %d", ji->type);
2520 g_assert_not_reached ();
2523 *endbuf = p;
2525 return TRUE;
2527 cleanup:
2528 return FALSE;
2531 static MonoJumpInfo*
2532 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches,
2533 guint32 **got_slots,
2534 guint8 *buf, guint8 **endbuf)
2536 MonoJumpInfo *patches;
2537 int pindex;
2538 guint8 *p;
2540 p = buf;
2542 patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2544 *got_slots = g_malloc (sizeof (guint32) * n_patches);
2546 for (pindex = 0; pindex < n_patches; ++pindex) {
2547 MonoJumpInfo *ji = &patches [pindex];
2548 guint8 *shared_p;
2549 gboolean res;
2550 guint32 got_offset;
2552 got_offset = decode_value (p, &p);
2554 if (aot_module->got [got_offset]) {
2555 /* Already loaded */
2556 //printf ("HIT!\n");
2557 } else {
2558 shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2560 ji->type = decode_value (shared_p, &shared_p);
2562 res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2563 if (!res)
2564 goto cleanup;
2567 (*got_slots) [pindex] = got_offset;
2570 *endbuf = p;
2571 return patches;
2573 cleanup:
2574 g_free (*got_slots);
2575 *got_slots = NULL;
2577 return NULL;
2580 static void
2581 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2584 * Jump addresses cannot be patched by the trampoline code since it
2585 * does not have access to the caller's address. Instead, we collect
2586 * the addresses of the GOT slots pointing to a method, and patch
2587 * them after the method has been compiled.
2589 MonoJitDomainInfo *info = domain_jit_info (domain);
2590 GSList *list;
2592 mono_domain_lock (domain);
2593 if (!info->jump_target_got_slot_hash)
2594 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2595 list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2596 list = g_slist_prepend (list, got_slot);
2597 g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2598 mono_domain_unlock (domain);
2602 * load_method:
2604 * Load the method identified by METHOD_INDEX from the AOT image. Return a
2605 * pointer to the native code of the method, or NULL if not found.
2606 * METHOD might not be set if the caller only has the image/token info.
2608 static gpointer
2609 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2611 MonoClass *klass;
2612 gboolean from_plt = method == NULL;
2613 MonoMemPool *mp;
2614 int i, pindex, n_patches, used_strings;
2615 gboolean keep_patches = TRUE;
2616 guint8 *p;
2617 MonoJitInfo *jinfo = NULL;
2618 guint8 *code, *info;
2620 if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2621 return NULL;
2623 if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2624 /* Non shared AOT code can't be used in other appdomains */
2625 return NULL;
2627 if (amodule->out_of_date)
2628 return NULL;
2630 if (amodule->code_offsets [method_index] == 0xffffffff) {
2631 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2632 char *full_name;
2634 if (!method)
2635 method = mono_get_method (image, token, NULL);
2636 full_name = mono_method_full_name (method, TRUE);
2637 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2638 g_free (full_name);
2640 return NULL;
2643 code = &amodule->code [amodule->code_offsets [method_index]];
2645 info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2647 mono_aot_lock ();
2648 if (!amodule->methods_loaded)
2649 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods + 1);
2650 mono_aot_unlock ();
2652 if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2653 return code;
2655 if (mono_last_aot_method != -1) {
2656 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2657 return NULL;
2658 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2659 if (!method)
2660 method = mono_get_method (image, token, NULL);
2661 if (method) {
2662 char *name = mono_method_full_name (method, TRUE);
2663 printf ("LAST AOT METHOD: %s.\n", name);
2664 g_free (name);
2665 } else {
2666 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2671 p = info;
2673 if (method) {
2674 klass = method->klass;
2675 decode_klass_ref (amodule, p, &p);
2676 } else {
2677 klass = decode_klass_ref (amodule, p, &p);
2680 if (amodule->info.opts & MONO_OPT_SHARED)
2681 used_strings = decode_value (p, &p);
2682 else
2683 used_strings = 0;
2685 for (i = 0; i < used_strings; i++) {
2686 guint token = decode_value (p, &p);
2687 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2690 if (amodule->info.opts & MONO_OPT_SHARED)
2691 keep_patches = FALSE;
2693 n_patches = decode_value (p, &p);
2695 keep_patches = FALSE;
2697 if (n_patches) {
2698 MonoJumpInfo *patches;
2699 guint32 *got_slots;
2701 if (keep_patches)
2702 mp = domain->mp;
2703 else
2704 mp = mono_mempool_new ();
2706 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2707 if (patches == NULL)
2708 goto cleanup;
2710 for (pindex = 0; pindex < n_patches; ++pindex) {
2711 MonoJumpInfo *ji = &patches [pindex];
2713 if (!amodule->got [got_slots [pindex]]) {
2714 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
2715 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2716 amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
2717 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2718 register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
2720 ji->type = MONO_PATCH_INFO_NONE;
2723 g_free (got_slots);
2725 if (!keep_patches)
2726 mono_mempool_destroy (mp);
2729 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2730 char *full_name;
2732 if (!method)
2733 method = mono_get_method (image, token, NULL);
2735 full_name = mono_method_full_name (method, TRUE);
2737 if (!jinfo)
2738 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
2740 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p - %p %p\n", full_name, code, code + jinfo->code_size, info);
2741 g_free (full_name);
2744 mono_aot_lock ();
2746 mono_jit_stats.methods_aot++;
2748 amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
2750 init_plt (amodule);
2752 if (method && method->wrapper_type)
2753 g_hash_table_insert (amodule->method_to_code, method, code);
2755 mono_aot_unlock ();
2757 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
2758 MonoJitInfo *jinfo;
2760 if (!method) {
2761 method = mono_get_method (image, token, NULL);
2762 g_assert (method);
2764 mono_profiler_method_jit (method);
2765 jinfo = mono_jit_info_table_find (domain, (char*)code);
2766 g_assert (jinfo);
2767 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
2770 if (from_plt && klass && !klass->generic_container)
2771 mono_runtime_class_init (mono_class_vtable (domain, klass));
2773 return code;
2775 cleanup:
2776 /* FIXME: The space in domain->mp is wasted */
2777 if (amodule->info.opts & MONO_OPT_SHARED)
2778 /* No need to cache patches */
2779 mono_mempool_destroy (mp);
2781 if (jinfo)
2782 g_free (jinfo);
2784 return NULL;
2787 static guint32
2788 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name)
2790 guint32 table_size, entry_size, hash;
2791 guint32 *table, *entry;
2792 guint32 index;
2793 static guint32 n_extra_decodes;
2795 if (!amodule)
2796 return 0xffffff;
2798 table_size = amodule->extra_method_table [0];
2799 table = amodule->extra_method_table + 1;
2800 entry_size = 3;
2802 hash = mono_aot_method_hash (method) % table_size;
2804 entry = &table [hash * entry_size];
2806 if (entry [0] == 0)
2807 return 0xffffff;
2809 index = 0xffffff;
2810 while (TRUE) {
2811 guint32 key = entry [0];
2812 guint32 value = entry [1];
2813 guint32 next = entry [entry_size - 1];
2814 MonoMethod *m;
2815 guint8 *p;
2816 int is_wrapper_name;
2818 p = amodule->blob + key;
2819 is_wrapper_name = decode_value (p, &p);
2820 if (is_wrapper_name) {
2821 int wrapper_type = decode_value (p, &p);
2822 if (wrapper_type == method->wrapper_type && !strcmp (name, (char*)p)) {
2823 index = value;
2824 break;
2826 } else if (can_method_ref_match_method (amodule, p, method)) {
2827 mono_aot_lock ();
2828 if (!amodule->method_ref_to_method)
2829 amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
2830 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
2831 mono_aot_unlock ();
2832 if (!m) {
2833 guint8 *orig_p = p;
2834 m = decode_method_ref_2 (amodule, p, &p);
2835 if (m) {
2836 mono_aot_lock ();
2837 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
2838 mono_aot_unlock ();
2841 if (m == method) {
2842 index = value;
2843 break;
2846 /* Special case: wrappers of shared generic methods */
2847 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
2848 method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
2849 MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
2850 MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
2852 if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
2853 index = value;
2854 break;
2858 /* Methods decoded needlessly */
2860 if (m)
2861 printf ("%d %s %s\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE));
2863 n_extra_decodes ++;
2866 if (next != 0)
2867 entry = &table [next * entry_size];
2868 else
2869 break;
2872 return index;
2875 static void
2876 add_module_cb (gpointer key, gpointer value, gpointer user_data)
2878 g_ptr_array_add ((GPtrArray*)user_data, value);
2882 * find_extra_method:
2884 * Try finding METHOD in the extra_method table in all AOT images.
2885 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
2886 * module where the method was found.
2888 static guint32
2889 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
2891 guint32 index;
2892 GPtrArray *modules;
2893 int i;
2894 char *name = NULL;
2896 if (method->wrapper_type)
2897 name = mono_aot_wrapper_name (method);
2899 /* Try the method's module first */
2900 *out_amodule = method->klass->image->aot_module;
2901 index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name);
2902 if (index != 0xffffff) {
2903 g_free (name);
2904 return index;
2908 * Try all other modules.
2909 * This is needed because generic instances klass->image points to the image
2910 * containing the generic definition, but the native code is generated to the
2911 * AOT image which contains the reference.
2914 /* Make a copy to avoid doing the search inside the aot lock */
2915 modules = g_ptr_array_new ();
2916 mono_aot_lock ();
2917 g_hash_table_foreach (aot_modules, add_module_cb, modules);
2918 mono_aot_unlock ();
2920 index = 0xffffff;
2921 for (i = 0; i < modules->len; ++i) {
2922 MonoAotModule *amodule = g_ptr_array_index (modules, i);
2924 if (amodule != method->klass->image->aot_module)
2925 index = find_extra_method_in_amodule (amodule, method, name);
2926 if (index != 0xffffff) {
2927 *out_amodule = amodule;
2928 break;
2932 g_ptr_array_free (modules, TRUE);
2934 g_free (name);
2935 return index;
2939 * mono_aot_get_method:
2941 * Return a pointer to the AOTed native code for METHOD if it can be found,
2942 * NULL otherwise.
2943 * On platforms with function pointers, this doesn't return a function pointer.
2945 gpointer
2946 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2948 MonoClass *klass = method->klass;
2949 guint32 method_index;
2950 MonoAotModule *amodule = klass->image->aot_module;
2951 guint8 *code;
2953 if (!amodule)
2954 return NULL;
2956 if (amodule->out_of_date)
2957 return NULL;
2959 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2960 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2961 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2962 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2963 return NULL;
2966 * Use the original method instead of its invoke-with-check wrapper.
2967 * This is not a problem when using full-aot, since it doesn't support
2968 * remoting.
2970 if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
2971 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
2973 g_assert (klass->inited);
2975 /* Find method index */
2976 if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
2978 * For generic methods, we store the fully shared instance in place of the
2979 * original method.
2981 method = mono_method_get_declaring_generic_method (method);
2982 method_index = mono_metadata_token_index (method->token) - 1;
2983 } else if (method->is_inflated || !method->token) {
2984 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
2985 mono_aot_lock ();
2986 code = g_hash_table_lookup (amodule->method_to_code, method);
2987 mono_aot_unlock ();
2988 if (code)
2989 return code;
2991 method_index = find_extra_method (method, &amodule);
2993 * Special case the ICollection<T> wrappers for arrays, as they cannot
2994 * be statically enumerated, and each wrapper ends up calling the same
2995 * method in Array.
2997 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
2998 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3000 code = mono_aot_get_method (domain, m);
3001 if (code) {
3002 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
3003 code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
3004 /* The call above returns an ftnptr */
3005 code = mono_get_addr_from_ftnptr (code);
3008 return code;
3013 * Special case Array.GetGenericValueImpl which is a generic icall.
3014 * Generic sharing currently can't handle it, but the icall returns data using
3015 * an out parameter, so the managed-to-native wrappers can share the same code.
3017 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3018 MonoMethod *m;
3019 MonoGenericContext ctx;
3020 MonoType *args [16];
3022 if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3023 /* Avoid recursion */
3024 return NULL;
3026 m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3027 g_assert (m);
3029 memset (&ctx, 0, sizeof (ctx));
3030 args [0] = &mono_defaults.object_class->byval_arg;
3031 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3033 m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3036 * Get the code for the <object> instantiation which should be emitted into
3037 * the mscorlib aot image by the AOT compiler.
3039 code = mono_aot_get_method (domain, m);
3040 if (code)
3041 return code;
3044 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
3045 /* Partial sharing */
3046 method_index = find_extra_method (mini_get_shared_method (method), &amodule);
3049 if (method_index == 0xffffff) {
3050 if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3051 char *full_name;
3053 full_name = mono_method_full_name (method, TRUE);
3054 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
3055 g_free (full_name);
3057 return NULL;
3060 if (method_index == 0xffffff)
3061 return NULL;
3063 /* Needed by find_jit_info */
3064 mono_aot_lock ();
3065 if (!amodule->extra_methods)
3066 amodule->extra_methods = g_hash_table_new (NULL, NULL);
3067 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3068 mono_aot_unlock ();
3069 } else {
3070 /* Common case */
3071 method_index = mono_metadata_token_index (method->token) - 1;
3074 return load_method (domain, amodule, klass->image, method, method->token, method_index);
3078 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3079 * method.
3081 gpointer
3082 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3084 MonoAotModule *aot_module = image->aot_module;
3085 int method_index;
3087 if (!aot_module)
3088 return NULL;
3090 method_index = mono_metadata_token_index (token) - 1;
3092 return load_method (domain, aot_module, image, NULL, token, method_index);
3095 typedef struct {
3096 guint8 *addr;
3097 gboolean res;
3098 } IsGotEntryUserData;
3100 static void
3101 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3103 IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3104 MonoAotModule *aot_module = (MonoAotModule*)value;
3106 if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3107 data->res = TRUE;
3110 gboolean
3111 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3113 IsGotEntryUserData user_data;
3115 if (!aot_modules)
3116 return FALSE;
3118 user_data.addr = addr;
3119 user_data.res = FALSE;
3120 mono_aot_lock ();
3121 g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3122 mono_aot_unlock ();
3124 return user_data.res;
3127 typedef struct {
3128 guint8 *addr;
3129 MonoAotModule *module;
3130 } FindAotModuleUserData;
3132 static void
3133 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3135 FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3136 MonoAotModule *aot_module = (MonoAotModule*)value;
3138 if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3139 data->module = aot_module;
3142 static inline MonoAotModule*
3143 find_aot_module (guint8 *code)
3145 FindAotModuleUserData user_data;
3147 if (!aot_modules)
3148 return NULL;
3150 /* Reading these need no locking */
3151 if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3152 return NULL;
3154 user_data.addr = code;
3155 user_data.module = NULL;
3157 mono_aot_lock ();
3158 g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3159 mono_aot_unlock ();
3161 return user_data.module;
3164 void
3165 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3168 * Since AOT code is only used in the root domain,
3169 * mono_domain_get () != mono_get_root_domain () means the calling method
3170 * is AppDomain:InvokeInDomain, so this is the same check as in
3171 * mono_method_same_domain () but without loading the metadata for the method.
3173 if (mono_domain_get () == mono_get_root_domain ())
3174 mono_arch_patch_plt_entry (code, got, regs, addr);
3178 * mono_aot_plt_resolve:
3180 * This function is called by the entries in the PLT to resolve the actual method that
3181 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3182 * Returns NULL if the something cannot be loaded.
3184 gpointer
3185 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3187 #ifdef MONO_ARCH_AOT_SUPPORTED
3188 guint8 *p, *target, *plt_entry;
3189 MonoJumpInfo ji;
3190 MonoAotModule *module = (MonoAotModule*)aot_module;
3191 gboolean res, no_ftnptr = FALSE;
3192 MonoMemPool *mp;
3194 //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3196 p = &module->blob [plt_info_offset];
3198 ji.type = decode_value (p, &p);
3200 mp = mono_mempool_new_size (512);
3201 res = decode_patch (module, mp, &ji, p, &p);
3203 if (!res) {
3204 mono_mempool_destroy (mp);
3205 return NULL;
3209 * Avoid calling resolve_patch_target in the full-aot case if possible, since
3210 * it would create a trampoline, and we don't need that.
3211 * We could do this only if the method does not need the special handling
3212 * in mono_magic_trampoline ().
3214 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) &&
3215 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
3216 target = mono_jit_compile_method (ji.data.method);
3217 no_ftnptr = TRUE;
3218 } else {
3219 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3223 * The trampoline expects us to return a function descriptor on platforms which use
3224 * it, but resolve_patch_target returns a direct function pointer for some type of
3225 * patches, so have to translate between the two.
3226 * FIXME: Clean this up, but how ?
3228 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) {
3229 /* These should already have a function descriptor */
3230 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3231 /* Our function descriptors have a 0 environment, gcc created ones don't */
3232 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3233 g_assert (((gpointer*)target) [2] == 0);
3234 #endif
3235 /* Empty */
3236 } else if (!no_ftnptr) {
3237 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3238 g_assert (((gpointer*)target) [2] != 0);
3239 #endif
3240 target = mono_create_ftnptr (mono_domain_get (), target);
3243 mono_mempool_destroy (mp);
3245 /* Patch the PLT entry with target which might be the actual method not a trampoline */
3246 plt_entry = mono_aot_get_plt_entry (code);
3247 g_assert (plt_entry);
3248 mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3250 return target;
3251 #else
3252 g_assert_not_reached ();
3253 return NULL;
3254 #endif
3258 * init_plt:
3260 * Initialize the PLT table of the AOT module. Called lazily when the first AOT
3261 * method in the module is loaded to avoid committing memory by writing to it.
3262 * LOCKING: Assumes the AOT lock is held.
3264 static void
3265 init_plt (MonoAotModule *amodule)
3267 #ifndef MONO_CROSS_COMPILE
3269 #ifdef MONO_ARCH_AOT_SUPPORTED
3270 #ifdef __i386__
3271 guint8 *buf = amodule->plt;
3272 #elif defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__)
3273 int i;
3274 gpointer plt_0;
3275 #endif
3276 gpointer tramp;
3278 if (amodule->plt_inited)
3279 return;
3281 tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3283 #ifdef __i386__
3284 /* Initialize the first PLT entry */
3285 make_writable (amodule->plt, amodule->plt_end - amodule->plt);
3286 x86_jump_code (buf, tramp);
3287 #elif defined(__x86_64__) || defined(__arm__) || defined(__mono_ppc__)
3289 * Initialize the PLT entries in the GOT to point to the default targets.
3292 tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3293 plt_0 = mono_create_ftnptr (mono_domain_get (), amodule->plt);
3294 /* The first entry points to the AOT trampoline */
3295 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base] = tramp;
3296 for (i = 1; i < amodule->info.plt_size; ++i)
3297 /* All the default entries point to the first entry */
3298 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = plt_0;
3299 #else
3300 g_assert_not_reached ();
3301 #endif
3303 amodule->plt_inited = TRUE;
3304 #endif
3306 #endif /* MONO_CROSS_COMPILE */
3310 * mono_aot_get_plt_entry:
3312 * Return the address of the PLT entry called by the code at CODE if exists.
3314 guint8*
3315 mono_aot_get_plt_entry (guint8 *code)
3317 MonoAotModule *aot_module = find_aot_module (code);
3318 #if defined(__arm__) || defined(__mono_ppc__)
3319 guint32 ins;
3320 #endif
3322 if (!aot_module)
3323 return NULL;
3325 #if defined(__i386__) || defined(__x86_64__)
3326 if (code [-5] == 0xe8) {
3327 guint32 disp = *(guint32*)(code - 4);
3328 guint8 *target = code + disp;
3330 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
3331 return target;
3333 #elif defined(__arm__)
3334 ins = ((guint32*)(gpointer)code) [-1];
3336 /* Should be a 'bl' */
3337 if ((((ins >> 25) & 0x7) == 0x5) && (((ins >> 24) & 0x1) == 0x1)) {
3338 gint32 disp = ((gint32)ins) & 0xffffff;
3339 guint8 *target = code - 4 + 8 + (disp * 4);
3341 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
3342 return target;
3344 #elif defined(__mono_ppc__)
3345 /* Should be a bl */
3346 ins = ((guint32*)(gpointer)code) [-1];
3348 if ((ins >> 26 == 18) && ((ins & 1) == 1) && ((ins & 2) == 0)) {
3349 gint32 disp = (((gint32)ins) >> 2) & 0xffffff;
3350 guint8 *target = code - 4 + (disp * 4);
3352 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
3353 return target;
3355 #else
3356 g_assert_not_reached ();
3357 #endif
3359 return NULL;
3363 * mono_aot_get_plt_info_offset:
3365 * Return the PLT info offset belonging to the plt entry called by CODE.
3367 guint32
3368 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3370 guint8 *plt_entry = mono_aot_get_plt_entry (code);
3372 g_assert (plt_entry);
3374 /* The offset is embedded inside the code after the plt entry */
3375 #if defined(__i386__)
3376 return *(guint32*)(plt_entry + 5);
3377 #elif defined(__x86_64__)
3378 return *(guint32*)(plt_entry + 6);
3379 #elif defined(__arm__)
3380 /* The offset is stored as the 4th word of the plt entry */
3381 return ((guint32*)plt_entry) [3];
3382 #elif defined(__mono_ppc__)
3383 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3384 return ((guint32*)plt_entry) [8];
3385 #else
3386 return ((guint32*)plt_entry) [6];
3387 #endif
3388 #else
3389 g_assert_not_reached ();
3390 return 0;
3391 #endif
3394 static gpointer
3395 mono_create_ftnptr_malloc (guint8 *code)
3397 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3398 MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3400 ftnptr->code = code;
3401 ftnptr->toc = NULL;
3402 ftnptr->env = NULL;
3404 return ftnptr;
3405 #else
3406 return code;
3407 #endif
3411 * load_function:
3413 * Load the function named NAME from the aot image.
3415 static gpointer
3416 load_function (MonoAotModule *amodule, const char *name)
3418 char *symbol;
3419 guint8 *p;
3420 int n_patches, pindex;
3421 MonoMemPool *mp;
3422 gpointer code;
3424 /* Load the code */
3426 symbol = g_strdup_printf ("%s", name);
3427 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3428 g_free (symbol);
3429 if (!code)
3430 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3432 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
3434 /* Load info */
3436 symbol = g_strdup_printf ("%s_p", name);
3437 find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3438 g_free (symbol);
3439 if (!p)
3440 /* Nothing to patch */
3441 return code;
3443 p = amodule->blob + *(guint32*)p;
3445 /* Similar to mono_aot_load_method () */
3447 n_patches = decode_value (p, &p);
3449 if (n_patches) {
3450 MonoJumpInfo *patches;
3451 guint32 *got_slots;
3453 mp = mono_mempool_new ();
3455 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3456 g_assert (patches);
3458 for (pindex = 0; pindex < n_patches; ++pindex) {
3459 MonoJumpInfo *ji = &patches [pindex];
3460 gpointer target;
3462 if (amodule->got [got_slots [pindex]])
3463 continue;
3466 * When this code is executed, the runtime may not be initalized yet, so
3467 * resolve the patch info by hand.
3469 if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3470 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3471 target = mono_get_lmf_addr;
3472 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3473 target = mono_thread_force_interruption_checkpoint;
3474 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3475 target = mono_exception_from_token;
3476 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3477 target = mono_get_throw_exception ();
3478 #ifdef __x86_64__
3479 } else if (!strcmp (ji->data.name, "mono_amd64_throw_exception")) {
3480 target = mono_amd64_throw_exception;
3481 #endif
3482 #ifdef __x86_64__
3483 } else if (!strcmp (ji->data.name, "mono_amd64_get_original_ip")) {
3484 target = mono_amd64_get_original_ip;
3485 #endif
3486 #ifdef __arm__
3487 } else if (!strcmp (ji->data.name, "mono_arm_throw_exception")) {
3488 target = mono_arm_throw_exception;
3489 } else if (!strcmp (ji->data.name, "mono_arm_throw_exception_by_token")) {
3490 target = mono_arm_throw_exception_by_token;
3491 #endif
3492 #ifdef __mono_ppc__
3493 } else if (!strcmp (ji->data.name, "mono_ppc_throw_exception")) {
3494 target = mono_ppc_throw_exception;
3495 #endif
3496 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3497 int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3498 target = (gpointer)mono_get_trampoline_func (tramp_type2);
3499 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3500 /* atoll is needed because the the offset is unsigned */
3501 guint32 slot;
3502 int res;
3504 res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3505 g_assert (res == 1);
3506 target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3507 target = mono_create_ftnptr_malloc (target);
3508 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3509 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3510 target = mono_create_ftnptr_malloc (target);
3511 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3512 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3513 target = mono_create_ftnptr_malloc (target);
3514 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3515 target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3516 target = mono_create_ftnptr_malloc (target);
3517 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3518 target = mono_thread_get_and_clear_pending_exception;
3519 } else {
3520 fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3521 g_assert_not_reached ();
3522 target = NULL;
3524 } else {
3525 /* Hopefully the code doesn't have patches which need method or
3526 * domain to be set.
3528 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3529 g_assert (target);
3532 amodule->got [got_slots [pindex]] = target;
3535 g_free (got_slots);
3537 mono_mempool_destroy (mp);
3540 return code;
3544 * Return the piece of code identified by NAME from the mscorlib AOT file.
3545 * On ppc64, this returns a function descriptor.
3547 gpointer
3548 mono_aot_get_named_code (const char *name)
3550 MonoImage *image;
3551 MonoAotModule *amodule;
3553 image = mono_defaults.corlib;
3554 g_assert (image);
3556 amodule = image->aot_module;
3557 g_assert (amodule);
3559 return mono_create_ftnptr_malloc (load_function (amodule, name));
3562 /* Return a given kind of trampoline */
3563 static gpointer
3564 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3566 MonoAotModule *amodule;
3567 int index, tramp_size;
3568 MonoImage *image;
3570 /* Currently, we keep all trampolines in the mscorlib AOT image */
3571 image = mono_defaults.corlib;
3572 g_assert (image);
3574 mono_aot_lock ();
3576 amodule = image->aot_module;
3577 g_assert (amodule);
3579 *out_amodule = amodule;
3581 if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3582 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3584 index = amodule->trampoline_index [tramp_type] ++;
3586 mono_aot_unlock ();
3588 *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3590 tramp_size = amodule->info.trampoline_size [tramp_type];
3592 if (out_tramp_size)
3593 *out_tramp_size = tramp_size;
3595 return amodule->trampolines [tramp_type] + (index * tramp_size);
3599 * Return a specific trampoline from the AOT file.
3601 gpointer
3602 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3604 MonoAotModule *amodule;
3605 guint32 got_offset, tramp_size;
3606 guint8 *code, *tramp;
3607 static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3608 static gboolean inited;
3609 static guint32 num_trampolines;
3611 if (!inited) {
3612 mono_aot_lock ();
3614 if (!inited) {
3615 mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3616 inited = TRUE;
3619 mono_aot_unlock ();
3622 num_trampolines ++;
3624 if (!generic_trampolines [tramp_type]) {
3625 char *symbol;
3627 symbol = g_strdup_printf ("generic_trampoline_%d", tramp_type);
3628 generic_trampolines [tramp_type] = mono_aot_get_named_code (symbol);
3629 g_free (symbol);
3632 tramp = generic_trampolines [tramp_type];
3633 g_assert (tramp);
3635 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3637 amodule->got [got_offset] = tramp;
3638 amodule->got [got_offset + 1] = arg1;
3640 if (code_len)
3641 *code_len = tramp_size;
3643 return code;
3646 gpointer
3647 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3649 MonoAotModule *amodule;
3650 guint8 *code;
3651 guint32 got_offset;
3653 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3655 amodule->got [got_offset] = ctx;
3656 amodule->got [got_offset + 1] = addr;
3658 /* The caller expects an ftnptr */
3659 return mono_create_ftnptr (mono_domain_get (), code);
3662 gpointer
3663 mono_aot_get_unbox_trampoline (MonoMethod *method)
3665 guint32 method_index = mono_metadata_token_index (method->token) - 1;
3666 MonoAotModule *amodule;
3667 char *symbol;
3668 gpointer code;
3670 if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3671 guint32 index = find_extra_method (method, &amodule);
3672 g_assert (index != 0xffffff);
3674 symbol = g_strdup_printf ("ut_e_%d", index);
3675 } else {
3676 amodule = method->klass->image->aot_module;
3677 g_assert (amodule);
3679 symbol = g_strdup_printf ("ut_%d", method_index);
3681 code = load_function (amodule, symbol);
3682 g_free (symbol);
3684 /* The caller expects an ftnptr */
3685 return mono_create_ftnptr (mono_domain_get (), code);
3688 gpointer
3689 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3691 char *symbol;
3692 gpointer code;
3694 symbol = g_strdup_printf ("rgctx_fetch_trampoline_%u", slot);
3695 code = load_function (mono_defaults.corlib->aot_module, symbol);
3696 g_free (symbol);
3697 /* The caller expects an ftnptr */
3698 return mono_create_ftnptr (mono_domain_get (), code);
3701 gpointer
3702 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3704 guint32 got_offset;
3705 gpointer code;
3706 gpointer *buf;
3707 int i;
3708 MonoAotModule *amodule;
3710 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
3712 /* Save the entries into an array */
3713 buf = mono_domain_alloc (domain, (count + 1) * 2 * sizeof (gpointer));
3714 for (i = 0; i < count; ++i) {
3715 MonoIMTCheckItem *item = imt_entries [i];
3717 g_assert (item->key);
3718 /* FIXME: */
3719 g_assert (!item->has_target_code);
3721 buf [(i * 2)] = item->key;
3722 buf [(i * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
3724 buf [(count * 2)] = NULL;
3725 buf [(count * 2) + 1] = fail_tramp;
3727 amodule->got [got_offset] = buf;
3729 return code;
3733 * mono_aot_set_make_unreadable:
3735 * Set whenever to make all mmaped memory unreadable. In conjuction with a
3736 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
3738 void
3739 mono_aot_set_make_unreadable (gboolean unreadable)
3741 static int inited;
3743 make_unreadable = unreadable;
3745 if (make_unreadable && !inited) {
3746 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
3750 typedef struct {
3751 MonoAotModule *module;
3752 guint8 *ptr;
3753 } FindMapUserData;
3755 static void
3756 find_map (gpointer key, gpointer value, gpointer user_data)
3758 MonoAotModule *module = (MonoAotModule*)value;
3759 FindMapUserData *data = (FindMapUserData*)user_data;
3761 if (!data->module)
3762 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
3763 data->module = module;
3766 static MonoAotModule*
3767 find_module_for_addr (void *ptr)
3769 FindMapUserData data;
3771 if (!make_unreadable)
3772 return NULL;
3774 data.module = NULL;
3775 data.ptr = (guint8*)ptr;
3777 mono_aot_lock ();
3778 g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
3779 mono_aot_unlock ();
3781 return data.module;
3785 * mono_aot_is_pagefault:
3787 * Should be called from a SIGSEGV signal handler to find out whenever @ptr is
3788 * within memory allocated by this module.
3790 gboolean
3791 mono_aot_is_pagefault (void *ptr)
3793 if (!make_unreadable)
3794 return FALSE;
3797 * Not signal safe, but SIGSEGV's are synchronous, and
3798 * this is only turned on by a MONO_DEBUG option.
3800 return find_module_for_addr (ptr) != NULL;
3804 * mono_aot_handle_pagefault:
3806 * Handle a pagefault caused by an unreadable page by making it readable again.
3808 void
3809 mono_aot_handle_pagefault (void *ptr)
3811 #ifndef PLATFORM_WIN32
3812 guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
3813 int res;
3815 mono_aot_lock ();
3816 res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
3817 g_assert (res == 0);
3819 n_pagefaults ++;
3820 mono_aot_unlock ();
3821 #endif
3824 #else
3825 /* AOT disabled */
3827 void
3828 mono_aot_init (void)
3832 gpointer
3833 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3835 return NULL;
3838 gboolean
3839 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3841 return FALSE;
3844 gboolean
3845 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
3847 return FALSE;
3850 gboolean
3851 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
3853 return FALSE;
3856 MonoJitInfo *
3857 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
3859 return NULL;
3862 gpointer
3863 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3865 return NULL;
3868 guint8*
3869 mono_aot_get_plt_entry (guint8 *code)
3871 return NULL;
3874 gpointer
3875 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3877 return NULL;
3880 void
3881 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3885 gpointer
3886 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
3888 return NULL;
3891 guint32
3892 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3894 g_assert_not_reached ();
3896 return 0;
3899 gpointer
3900 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3902 g_assert_not_reached ();
3903 return NULL;
3906 gpointer
3907 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3909 g_assert_not_reached ();
3910 return NULL;
3913 gpointer
3914 mono_aot_get_named_code (const char *name)
3916 g_assert_not_reached ();
3917 return NULL;
3920 gpointer
3921 mono_aot_get_unbox_trampoline (MonoMethod *method)
3923 g_assert_not_reached ();
3924 return NULL;
3927 gpointer
3928 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3930 g_assert_not_reached ();
3931 return NULL;
3934 gpointer
3935 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3937 g_assert_not_reached ();
3938 return NULL;
3941 guint8*
3942 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
3944 g_assert_not_reached ();
3945 return NULL;
3948 #endif