Merge pull request #217 from QuickJack/master
[mono.git] / mono / mini / aot-runtime.c
1 /*
2  * aot-runtime.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  * Copyright 2003-2011 Novell, Inc.
10  * Copyright 2011 Xamarin, Inc.
11  */
12
13 #include "config.h"
14 #include <sys/types.h>
15 #ifdef HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18 #include <fcntl.h>
19 #include <string.h>
20 #ifdef HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #endif
23
24 #if HOST_WIN32
25 #include <winsock2.h>
26 #include <windows.h>
27 #endif
28
29 #ifdef HAVE_EXECINFO_H
30 #include <execinfo.h>
31 #endif
32
33 #include <errno.h>
34 #include <sys/stat.h>
35
36 #ifdef HAVE_SYS_WAIT_H
37 #include <sys/wait.h>  /* for WIFEXITED, WEXITSTATUS */
38 #endif
39
40 #include <mono/metadata/tabledefs.h>
41 #include <mono/metadata/class.h>
42 #include <mono/metadata/object.h>
43 #include <mono/metadata/tokentype.h>
44 #include <mono/metadata/appdomain.h>
45 #include <mono/metadata/debug-helpers.h>
46 #include <mono/metadata/assembly.h>
47 #include <mono/metadata/metadata-internals.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/gc-internal.h>
50 #include <mono/metadata/monitor.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/metadata/mono-endian.h>
53 #include <mono/utils/mono-logger-internal.h>
54 #include <mono/utils/mono-mmap.h>
55 #include "mono/utils/mono-compiler.h"
56 #include <mono/utils/mono-counters.h>
57
58 #include "mini.h"
59 #include "version.h"
60
61 #ifndef DISABLE_AOT
62
63 #ifdef TARGET_WIN32
64 #define SHARED_EXT ".dll"
65 #elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
66 #define SHARED_EXT ".dylib"
67 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
68 #define SHARED_EXT ".dylib"
69 #else
70 #define SHARED_EXT ".so"
71 #endif
72
73 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
74 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
75
76 typedef struct MonoAotModule {
77         char *aot_name;
78         /* Pointer to the Global Offset Table */
79         gpointer *got;
80         GHashTable *name_cache;
81         GHashTable *extra_methods;
82         /* Maps methods to their code */
83         GHashTable *method_to_code;
84         /* Maps pointers into the method info to the methods themselves */
85         GHashTable *method_ref_to_method;
86         MonoAssemblyName *image_names;
87         char **image_guids;
88         MonoAssembly *assembly;
89         MonoImage **image_table;
90         guint32 image_table_len;
91         gboolean out_of_date;
92         gboolean plt_inited;
93         guint8 *mem_begin;
94         guint8 *mem_end;
95         guint8 *code;
96         guint8 *code_end;
97         guint8 *plt;
98         guint8 *plt_end;
99         guint8 *blob;
100         gint32 *code_offsets;
101         /* This contains <offset, index> pairs sorted by offset */
102         /* This is needed because LLVM emitted methods can be in any order */
103         gint32 *sorted_code_offsets;
104         gint32 sorted_code_offsets_len;
105         guint32 *method_info_offsets;
106         guint32 *got_info_offsets;
107         guint32 *ex_info_offsets;
108         guint32 *class_info_offsets;
109         guint32 *methods_loaded;
110         guint16 *class_name_table;
111         guint32 *extra_method_table;
112         guint32 *extra_method_info_offsets;
113         guint32 *unbox_trampolines;
114         guint32 *unbox_trampolines_end;
115         guint8 *unwind_info;
116         guint8 *thumb_end;
117
118         /* Points to the mono EH data created by LLVM */
119         guint8 *mono_eh_frame;
120
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];
125
126         MonoAotFileInfo info;
127
128         gpointer *globals;
129         MonoDl *sofile;
130 } MonoAotModule;
131
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;
136
137 /* 
138  * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
139  * AOT modules registered by mono_aot_register_module ().
140  */
141 static GHashTable *static_aot_modules;
142
143 /*
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.
146  */
147 static GHashTable *ji_to_amodule;
148
149 /*
150  * Whenever to AOT compile loaded assemblies on demand and store them in
151  * a cache under $HOME/.mono/aot-cache.
152  */
153 static gboolean use_aot_cache = FALSE;
154
155 /*
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.
158  */
159 static gboolean spawn_compiler = TRUE;
160
161 /* For debugging */
162 static gint32 mono_last_aot_method = -1;
163
164 static gboolean make_unreadable = FALSE;
165 static guint32 name_table_accesses = 0;
166 static guint32 n_pagefaults = 0;
167
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;
171
172 static GHashTable *aot_jit_icall_hash;
173
174 static void
175 init_plt (MonoAotModule *info);
176
177 /*****************************************************/
178 /*                 AOT RUNTIME                       */
179 /*****************************************************/
180
181 /*
182  * load_image:
183  *
184  *   Load one of the images referenced by AMODULE. Returns NULL if the image is not
185  * found, and sets the loader error if SET_ERROR is TRUE.
186  */
187 static MonoImage *
188 load_image (MonoAotModule *amodule, int index, gboolean set_error)
189 {
190         MonoAssembly *assembly;
191         MonoImageOpenStatus status;
192
193         g_assert (index < amodule->image_table_len);
194
195         if (amodule->image_table [index])
196                 return amodule->image_table [index];
197         if (amodule->out_of_date)
198                 return NULL;
199
200         assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
201         if (!assembly) {
202                 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);
203                 amodule->out_of_date = TRUE;
204
205                 if (set_error) {
206                         char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
207                         mono_loader_set_error_assembly_load (full_name, FALSE);
208                         g_free (full_name);
209                 }
210                 return NULL;
211         }
212
213         if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
214                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s').\n", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
215                 amodule->out_of_date = TRUE;
216                 return NULL;
217         }
218
219         amodule->image_table [index] = assembly->image;
220         return assembly->image;
221 }
222
223 static inline gint32
224 decode_value (guint8 *ptr, guint8 **rptr)
225 {
226         guint8 b = *ptr;
227         gint32 len;
228         
229         if ((b & 0x80) == 0){
230                 len = b;
231                 ++ptr;
232         } else if ((b & 0x40) == 0){
233                 len = ((b & 0x3f) << 8 | ptr [1]);
234                 ptr += 2;
235         } else if (b != 0xff) {
236                 len = ((b & 0x1f) << 24) |
237                         (ptr [1] << 16) |
238                         (ptr [2] << 8) |
239                         ptr [3];
240                 ptr += 4;
241         }
242         else {
243                 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
244                 ptr += 5;
245         }
246         if (rptr)
247                 *rptr = ptr;
248
249         //printf ("DECODE: %d.\n", len);
250         return len;
251 }
252
253 /*
254  * mono_aot_get_method:
255  *
256  *   Decode an offset table emitted by emit_offset_table (), returning the INDEXth
257  * entry.
258  */
259 static guint32
260 mono_aot_get_offset (guint32 *table, int index)
261 {
262         int i, group, ngroups, index_entry_size;
263         int start_offset, offset, noffsets, group_size;
264         guint8 *data_start, *p;
265         guint32 *index32 = NULL;
266         guint16 *index16 = NULL;
267         
268         noffsets = table [0];
269         group_size = table [1];
270         ngroups = table [2];
271         index_entry_size = table [3];
272         group = index / group_size;
273
274         if (index_entry_size == 2) {
275                 index16 = (guint16*)&table [4];
276                 data_start = (guint8*)&index16 [ngroups];
277                 p = data_start + index16 [group];
278         } else {
279                 index32 = (guint32*)&table [4];
280                 data_start = (guint8*)&index32 [ngroups];
281                 p = data_start + index32 [group];
282         }
283
284         /* offset will contain the value of offsets [group * group_size] */
285         offset = start_offset = decode_value (p, &p);
286         for (i = group * group_size + 1; i <= index; ++i) {
287                 offset += decode_value (p, &p);
288         }
289
290         //printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
291
292         return offset;
293 }
294
295 static MonoMethod*
296 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
297
298 static MonoClass*
299 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
300
301 static MonoType*
302 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
303
304 static MonoGenericInst*
305 decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
306 {
307         int type_argc, i;
308         MonoType **type_argv;
309         MonoGenericInst *inst;
310         guint8 *p = buf;
311
312         type_argc = decode_value (p, &p);
313         type_argv = g_new0 (MonoType*, type_argc);
314
315         for (i = 0; i < type_argc; ++i) {
316                 MonoClass *pclass = decode_klass_ref (module, p, &p);
317                 if (!pclass) {
318                         g_free (type_argv);
319                         return NULL;
320                 }
321                 type_argv [i] = &pclass->byval_arg;
322         }
323
324         inst = mono_metadata_get_generic_inst (type_argc, type_argv);
325         g_free (type_argv);
326
327         *endbuf = p;
328
329         return inst;
330 }
331
332 static gboolean
333 decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
334 {
335         guint8 *p = buf;
336         guint8 *p2;
337         int argc;
338
339         p2 = p;
340         argc = decode_value (p, &p);
341         if (argc) {
342                 p = p2;
343                 ctx->class_inst = decode_generic_inst (module, p, &p);
344                 if (!ctx->class_inst)
345                         return FALSE;
346         }
347         p2 = p;
348         argc = decode_value (p, &p);
349         if (argc) {
350                 p = p2;
351                 ctx->method_inst = decode_generic_inst (module, p, &p);
352                 if (!ctx->method_inst)
353                         return FALSE;
354         }
355
356         *endbuf = p;
357         return TRUE;
358 }
359
360 static MonoClass*
361 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
362 {
363         MonoImage *image;
364         MonoClass *klass = NULL, *eklass;
365         guint32 token, rank, idx;
366         guint8 *p = buf;
367         int reftype;
368
369         reftype = decode_value (p, &p);
370         if (reftype == 0) {
371                 *endbuf = p;
372                 return NULL;
373         }
374
375         switch (reftype) {
376         case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
377                 idx = decode_value (p, &p);
378                 image = load_image (module, 0, TRUE);
379                 if (!image)
380                         return NULL;
381                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
382                 break;
383         case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
384                 idx = decode_value (p, &p);
385                 image = load_image (module, decode_value (p, &p), TRUE);
386                 if (!image)
387                         return NULL;
388                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
389                 break;
390         case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
391                 token = decode_value (p, &p);
392                 image = module->assembly->image;
393                 if (!image)
394                         return NULL;
395                 klass = mono_class_get (image, token);
396                 break;
397         case MONO_AOT_TYPEREF_GINST: {
398                 MonoClass *gclass;
399                 MonoGenericContext ctx;
400                 MonoType *type;
401
402                 gclass = decode_klass_ref (module, p, &p);
403                 if (!gclass)
404                         return NULL;
405                 g_assert (gclass->generic_container);
406
407                 memset (&ctx, 0, sizeof (ctx));
408                 ctx.class_inst = decode_generic_inst (module, p, &p);
409                 if (!ctx.class_inst)
410                         return NULL;
411                 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
412                 klass = mono_class_from_mono_type (type);
413                 mono_metadata_free_type (type);
414                 break;
415         }
416         case MONO_AOT_TYPEREF_VAR: {
417                 MonoType *t;
418                 MonoGenericContainer *container;
419                 int type = decode_value (p, &p);
420                 int num = decode_value (p, &p);
421                 gboolean is_method = decode_value (p, &p);
422
423                 if (is_method) {
424                         MonoMethod *method_def;
425                         g_assert (type == MONO_TYPE_MVAR);
426                         method_def = decode_resolve_method_ref (module, p, &p);
427                         if (!method_def)
428                                 return NULL;
429
430                         container = mono_method_get_generic_container (method_def);
431                 } else {
432                         MonoClass *class_def;
433                         g_assert (type == MONO_TYPE_VAR);
434                         class_def = decode_klass_ref (module, p, &p);
435                         if (!class_def)
436                                 return NULL;
437
438                         container = class_def->generic_container;
439                 }
440
441                 g_assert (container);
442
443                 // FIXME: Memory management
444                 t = g_new0 (MonoType, 1);
445                 t->type = type;
446                 t->data.generic_param = mono_generic_container_get_param (container, num);
447
448                 // FIXME: Maybe use types directly to avoid
449                 // the overhead of creating MonoClass-es
450                 klass = mono_class_from_mono_type (t);
451
452                 g_free (t);
453                 break;
454         }
455         case MONO_AOT_TYPEREF_ARRAY:
456                 /* Array */
457                 rank = decode_value (p, &p);
458                 eklass = decode_klass_ref (module, p, &p);
459                 klass = mono_array_class_get (eklass, rank);
460                 break;
461         case MONO_AOT_TYPEREF_PTR: {
462                 MonoType *t;
463
464                 t = decode_type (module, p, &p);
465                 if (!t)
466                         return NULL;
467                 klass = mono_class_from_mono_type (t);
468                 g_free (t);
469                 break;
470         }
471         case MONO_AOT_TYPEREF_BLOB_INDEX: {
472                 guint32 offset = decode_value (p, &p);
473                 guint8 *p2;
474
475                 p2 = module->blob + offset;
476                 klass = decode_klass_ref (module, p2, &p2);
477                 break;
478         }
479         default:
480                 g_assert_not_reached ();
481         }
482         g_assert (klass);
483         //printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
484         *endbuf = p;
485         return klass;
486 }
487
488 static MonoClassField*
489 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
490 {
491         MonoClass *klass = decode_klass_ref (module, buf, &buf);
492         guint32 token;
493         guint8 *p = buf;
494
495         if (!klass)
496                 return NULL;
497
498         token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
499
500         *endbuf = p;
501
502         return mono_class_get_field (klass, token);
503 }
504
505 /*
506  * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
507  * memory.
508  */
509 static MonoType*
510 decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
511 {
512         guint8 *p = buf;
513         MonoType *t;
514
515         t = g_malloc0 (sizeof (MonoType));
516
517         while (TRUE) {
518                 if (*p == MONO_TYPE_PINNED) {
519                         t->pinned = TRUE;
520                         ++p;
521                 } else if (*p == MONO_TYPE_BYREF) {
522                         t->byref = TRUE;
523                         ++p;
524                 } else {
525                         break;
526                 }
527         }
528
529         t->type = *p;
530         ++p;
531
532         switch (t->type) {
533         case MONO_TYPE_VOID:
534         case MONO_TYPE_BOOLEAN:
535         case MONO_TYPE_CHAR:
536         case MONO_TYPE_I1:
537         case MONO_TYPE_U1:
538         case MONO_TYPE_I2:
539         case MONO_TYPE_U2:
540         case MONO_TYPE_I4:
541         case MONO_TYPE_U4:
542         case MONO_TYPE_I8:
543         case MONO_TYPE_U8:
544         case MONO_TYPE_R4:
545         case MONO_TYPE_R8:
546         case MONO_TYPE_I:
547         case MONO_TYPE_U:
548         case MONO_TYPE_STRING:
549         case MONO_TYPE_OBJECT:
550         case MONO_TYPE_TYPEDBYREF:
551                 break;
552         case MONO_TYPE_VALUETYPE:
553         case MONO_TYPE_CLASS:
554                 t->data.klass = decode_klass_ref (module, p, &p);
555                 break;
556         case MONO_TYPE_SZARRAY:
557                 t->data.klass = decode_klass_ref (module, p, &p);
558
559                 if (!t->data.klass)
560                         return NULL;
561                 break;
562         case MONO_TYPE_PTR:
563                 t->data.type = decode_type (module, p, &p);
564                 break;
565         case MONO_TYPE_GENERICINST: {
566                 MonoClass *gclass;
567                 MonoGenericContext ctx;
568                 MonoType *type;
569                 MonoClass *klass;
570
571                 gclass = decode_klass_ref (module, p, &p);
572                 if (!gclass)
573                         return NULL;
574                 g_assert (gclass->generic_container);
575
576                 memset (&ctx, 0, sizeof (ctx));
577                 ctx.class_inst = decode_generic_inst (module, p, &p);
578                 if (!ctx.class_inst)
579                         return NULL;
580                 type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
581                 klass = mono_class_from_mono_type (type);
582                 t->data.generic_class = klass->generic_class;
583                 break;
584         }
585         case MONO_TYPE_ARRAY: {
586                 MonoArrayType *array;
587                 int i;
588
589                 // FIXME: memory management
590                 array = g_new0 (MonoArrayType, 1);
591                 array->eklass = decode_klass_ref (module, p, &p);
592                 if (!array->eklass)
593                         return NULL;
594                 array->rank = decode_value (p, &p);
595                 array->numsizes = decode_value (p, &p);
596
597                 if (array->numsizes)
598                         array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
599                 for (i = 0; i < array->numsizes; ++i)
600                         array->sizes [i] = decode_value (p, &p);
601
602                 array->numlobounds = decode_value (p, &p);
603                 if (array->numlobounds)
604                         array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
605                 for (i = 0; i < array->numlobounds; ++i)
606                         array->lobounds [i] = decode_value (p, &p);
607                 t->data.array = array;
608                 break;
609         }
610         default:
611                 g_assert_not_reached ();
612         }
613
614         *endbuf = p;
615
616         return t;
617 }
618
619 // FIXME: Error handling, memory management
620
621 static MonoMethodSignature*
622 decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
623 {
624         MonoMethodSignature *sig;
625         guint32 flags;
626         int i, param_count, call_conv;
627         guint8 *p = buf;
628         gboolean hasthis, explicit_this, has_gen_params;
629
630         flags = *p;
631         p ++;
632         has_gen_params = (flags & 0x10) != 0;
633         hasthis = (flags & 0x20) != 0;
634         explicit_this = (flags & 0x40) != 0;
635         call_conv = flags & 0x0F;
636
637         g_assert (!has_gen_params);
638
639         param_count = decode_value (p, &p);
640         if (target && param_count != target->param_count)
641                 return NULL;
642         sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
643         sig->param_count = param_count;
644         sig->sentinelpos = -1;
645         sig->hasthis = hasthis;
646         sig->explicit_this = explicit_this;
647         sig->call_convention = call_conv;
648         sig->param_count = param_count;
649         sig->ret = decode_type (module, p, &p);
650         for (i = 0; i < param_count; ++i) {
651                 if (*p == MONO_TYPE_SENTINEL) {
652                         g_assert (sig->call_convention == MONO_CALL_VARARG);
653                         sig->sentinelpos = i;
654                         p ++;
655                 }
656                 sig->params [i] = decode_type (module, p, &p);
657         }
658
659         if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
660                 sig->sentinelpos = sig->param_count;
661
662         *endbuf = p;
663
664         return sig;
665 }
666
667 static MonoMethodSignature*
668 decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
669 {
670         return decode_signature_with_target (module, NULL, buf, endbuf);
671 }
672
673 static gboolean
674 sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
675 {
676         MonoMethodSignature *sig;
677         gboolean res;
678         guint8 *p = buf;
679         
680         sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
681         res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
682         g_free (sig);
683         *endbuf = p;
684         return res;
685 }
686
687 /* Stores information returned by decode_method_ref () */
688 typedef struct {
689         MonoImage *image;
690         guint32 token;
691         MonoMethod *method;
692         gboolean no_aot_trampoline;
693 } MethodRef;
694
695 /*
696  * decode_method_ref_with_target:
697  *
698  *   Decode a method reference, storing the image/token into a MethodRef structure.
699  * This avoids loading metadata for the method if the caller does not need it. If the method has
700  * no token, then it is loaded from metadata and ref->method is set to the method instance.
701  * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
702  *  couldn't resolve to TARGET, and return FALSE.
703  * There are some kinds of method references which only support a non-null TARGET.
704  * This means that its not possible to decode this into a method, only to check
705  * that the method reference matches a given method. This is normally not a problem
706  * as these wrappers only occur in the extra_methods table, where we already have
707  * a method we want to lookup.
708  */
709 static gboolean
710 decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
711 {
712         guint32 image_index, value;
713         MonoImage *image = NULL;
714         guint8 *p = buf;
715
716         memset (ref, 0, sizeof (MethodRef));
717
718         value = decode_value (p, &p);
719         image_index = value >> 24;
720
721         if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
722                 ref->no_aot_trampoline = TRUE;
723                 value = decode_value (p, &p);
724                 image_index = value >> 24;
725         }
726
727         if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
728                 if (target && target->wrapper_type)
729                         return FALSE;
730         }
731
732         if (image_index == MONO_AOT_METHODREF_WRAPPER) {
733                 guint32 wrapper_type;
734
735                 wrapper_type = decode_value (p, &p);
736
737                 if (target && target->wrapper_type != wrapper_type)
738                         return FALSE;
739
740                 /* Doesn't matter */
741                 image = mono_defaults.corlib;
742
743                 switch (wrapper_type) {
744                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
745                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
746
747                         if (!m)
748                                 return FALSE;
749                         mono_class_init (m->klass);
750                         ref->method = mono_marshal_get_remoting_invoke_with_check (m);
751                         break;
752                 }
753                 case MONO_WRAPPER_PROXY_ISINST: {
754                         MonoClass *klass = decode_klass_ref (module, p, &p);
755                         if (!klass)
756                                 return FALSE;
757                         ref->method = mono_marshal_get_proxy_cancast (klass);
758                         break;
759                 }
760                 case MONO_WRAPPER_LDFLD:
761                 case MONO_WRAPPER_LDFLDA:
762                 case MONO_WRAPPER_STFLD:
763                 case MONO_WRAPPER_ISINST: {
764                         MonoClass *klass = decode_klass_ref (module, p, &p);
765                         if (!klass)
766                                 return FALSE;
767                         if (wrapper_type == MONO_WRAPPER_LDFLD)
768                                 ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
769                         else if (wrapper_type == MONO_WRAPPER_LDFLDA)
770                                 ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
771                         else if (wrapper_type == MONO_WRAPPER_STFLD)
772                                 ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
773                         else if (wrapper_type == MONO_WRAPPER_ISINST)
774                                 ref->method = mono_marshal_get_isinst (klass);
775                         else
776                                 g_assert_not_reached ();
777                         break;
778                 }
779                 case MONO_WRAPPER_LDFLD_REMOTE:
780                         ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
781                         break;
782                 case MONO_WRAPPER_STFLD_REMOTE:
783                         ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
784                         break;
785                 case MONO_WRAPPER_ALLOC: {
786                         int atype = decode_value (p, &p);
787
788                         ref->method = mono_gc_get_managed_allocator_by_type (atype);
789                         g_assert (ref->method);
790                         break;
791                 }
792                 case MONO_WRAPPER_WRITE_BARRIER:
793                         ref->method = mono_gc_get_write_barrier ();
794                         break;
795                 case MONO_WRAPPER_STELEMREF: {
796                         int subtype = decode_value (p, &p);
797
798                         if (subtype == WRAPPER_SUBTYPE_NONE) {
799                                 ref->method = mono_marshal_get_stelemref ();
800                         } else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
801                                 int kind;
802                                 WrapperInfo *info;
803                                 
804                                 kind = decode_value (p, &p);
805
806                                 /* Can't decode this */
807                                 g_assert (target);
808                                 if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
809                                         info = mono_marshal_get_wrapper_info (target);
810
811                                         g_assert (info);
812                                         if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
813                                                 ref->method = target;
814                                         else
815                                                 return FALSE;
816                                 } else {
817                                         return FALSE;
818                                 }
819                         } else {
820                                 g_assert_not_reached ();
821                         }
822                         break;
823                 }
824                 case MONO_WRAPPER_SYNCHRONIZED: {
825                         MonoMethod *m = decode_resolve_method_ref (module, p, &p);
826
827                         if (!m)
828                                 return FALSE;
829                         ref->method = mono_marshal_get_synchronized_wrapper (m);
830                         break;
831                 }
832                 case MONO_WRAPPER_UNKNOWN: {
833                         MonoMethodDesc *desc;
834                         MonoMethod *orig_method;
835                         int subtype = decode_value (p, &p);
836
837                         if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
838                                 MonoClass *klass = decode_klass_ref (module, p, &p);
839                                 
840                                 if (!klass)
841                                         return FALSE;
842
843                                 g_assert (target);
844                                 if (klass != target->klass)
845                                         return FALSE;
846
847                                 if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
848                                         if (strcmp (target->name, "PtrToStructure"))
849                                                 return FALSE;
850                                         ref->method = mono_marshal_get_ptr_to_struct (klass);
851                                 } else {
852                                         if (strcmp (target->name, "StructureToPtr"))
853                                                 return FALSE;
854                                         ref->method = mono_marshal_get_struct_to_ptr (klass);
855                                 }
856                         } else {
857                                 if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
858                                         desc = mono_method_desc_new ("Monitor:Enter", FALSE);
859                                 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
860                                         desc = mono_method_desc_new ("Monitor:Exit", FALSE);
861                                 else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
862                                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
863                                 else
864                                         g_assert_not_reached ();
865                                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
866                                 g_assert (orig_method);
867                                 mono_method_desc_free (desc);
868                                 ref->method = mono_monitor_get_fast_path (orig_method);
869                         }
870                         break;
871                 }
872                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
873                         int subtype = decode_value (p, &p);
874
875                         if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
876                                 int rank = decode_value (p, &p);
877                                 int elem_size = decode_value (p, &p);
878
879                                 ref->method = mono_marshal_get_array_address (rank, elem_size);
880                         } else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
881                                 WrapperInfo *info;
882                                 MonoMethod *m;
883
884                                 m = decode_resolve_method_ref (module, p, &p);
885                                 if (!m)
886                                         return FALSE;
887
888                                 g_assert (target);
889                                 g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
890
891                                 info = mono_marshal_get_wrapper_info (target);
892                                 if (info && info->subtype == subtype && info->d.string_ctor.method == m)
893                                         ref->method = target;
894                                 else
895                                         return FALSE;
896                         }
897                         break;
898                 }
899                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
900                         MonoMethod *m;
901                         int subtype = decode_value (p, &p);
902                         char *name;
903
904                         if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
905                                 g_assert (target);
906
907                                 name = (char*)p;
908                                 if (strcmp (target->name, name) != 0)
909                                         return FALSE;
910                                 ref->method = target;
911                         } else {
912                                 m = decode_resolve_method_ref (module, p, &p);
913
914                                 if (!m)
915                                         return FALSE;
916
917                                 /* This should only happen when looking for an extra method */
918                                 g_assert (target);
919                                 if (mono_marshal_method_from_wrapper (target) == m)
920                                         ref->method = target;
921                                 else
922                                         return FALSE;
923                         }
924                         break;
925                 }
926                 case MONO_WRAPPER_CASTCLASS: {
927                         int subtype = decode_value (p, &p);
928
929                         if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
930                                 ref->method = mono_marshal_get_castclass_with_cache ();
931                         else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
932                                 ref->method = mono_marshal_get_isinst_with_cache ();
933                         else
934                                 g_assert_not_reached ();
935                         break;
936                 }
937                 case MONO_WRAPPER_RUNTIME_INVOKE: {
938                         int subtype = decode_value (p, &p);
939
940                         g_assert (target);
941
942                         if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
943                                 if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
944                                         return FALSE;
945                                 ref->method = target;
946                         } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
947                                 /* Direct wrapper */
948                                 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
949
950                                 if (!m)
951                                         return FALSE;
952                                 ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
953                         } else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
954                                 /* Virtual direct wrapper */
955                                 MonoMethod *m = decode_resolve_method_ref (module, p, &p);
956
957                                 if (!m)
958                                         return FALSE;
959                                 ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
960                         } else {
961                                 if (sig_matches_target (module, target, p, &p))
962                                         ref->method = target;
963                                 else
964                                         return FALSE;
965                         }
966                         break;
967                 }
968                 case MONO_WRAPPER_DELEGATE_INVOKE:
969                 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
970                 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
971                         /*
972                          * These wrappers are associated with a signature, not with a method.
973                          * Since we can't decode them into methods, they need a target method.
974                          */
975                         g_assert (target);
976
977                         if (sig_matches_target (module, target, p, &p))
978                                 ref->method = target;
979                         else
980                                 return FALSE;
981                         break;
982                 }
983                 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
984                         MonoMethod *m;
985                         MonoClass *klass;
986
987                         m = decode_resolve_method_ref (module, p, &p);
988                         if (!m)
989                                 return FALSE;
990                         klass = decode_klass_ref (module, p, &p);
991                         if (!klass)
992                                 return FALSE;
993                         ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
994                         break;
995                 }
996                 default:
997                         g_assert_not_reached ();
998                 }
999         } else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
1000                 image_index = decode_value (p, &p);
1001                 ref->token = decode_value (p, &p);
1002
1003                 image = load_image (module, image_index, TRUE);
1004                 if (!image)
1005                         return FALSE;
1006         } else if (image_index == MONO_AOT_METHODREF_GINST) {
1007                 MonoClass *klass;
1008                 MonoGenericContext ctx;
1009
1010                 /* 
1011                  * These methods do not have a token which resolves them, so we 
1012                  * resolve them immediately.
1013                  */
1014                 klass = decode_klass_ref (module, p, &p);
1015                 if (!klass)
1016                         return FALSE;
1017
1018                 if (target && target->klass != klass)
1019                         return FALSE;
1020
1021                 image_index = decode_value (p, &p);
1022                 ref->token = decode_value (p, &p);
1023
1024                 image = load_image (module, image_index, TRUE);
1025                 if (!image)
1026                         return FALSE;
1027
1028                 ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
1029                 if (!ref->method)
1030                         return FALSE;
1031
1032                 memset (&ctx, 0, sizeof (ctx));
1033
1034                 if (FALSE && klass->generic_class) {
1035                         ctx.class_inst = klass->generic_class->context.class_inst;
1036                         ctx.method_inst = NULL;
1037  
1038                         ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1039                 }                       
1040
1041                 memset (&ctx, 0, sizeof (ctx));
1042
1043                 if (!decode_generic_context (module, &ctx, p, &p))
1044                         return FALSE;
1045
1046                 ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
1047         } else if (image_index == MONO_AOT_METHODREF_ARRAY) {
1048                 MonoClass *klass;
1049                 int method_type;
1050
1051                 klass = decode_klass_ref (module, p, &p);
1052                 if (!klass)
1053                         return FALSE;
1054                 method_type = decode_value (p, &p);
1055                 switch (method_type) {
1056                 case 0:
1057                         ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
1058                         break;
1059                 case 1:
1060                         ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
1061                         break;
1062                 case 2:
1063                         ref->method = mono_class_get_method_from_name (klass, "Get", -1);
1064                         break;
1065                 case 3:
1066                         ref->method = mono_class_get_method_from_name (klass, "Address", -1);
1067                         break;
1068                 case 4:
1069                         ref->method = mono_class_get_method_from_name (klass, "Set", -1);
1070                         break;
1071                 default:
1072                         g_assert_not_reached ();
1073                 }
1074         } else {
1075                 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1076                 ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1077
1078                 image = load_image (module, image_index, TRUE);
1079                 if (!image)
1080                         return FALSE;
1081         }
1082
1083         *endbuf = p;
1084
1085         ref->image = image;
1086
1087         return TRUE;
1088 }
1089
1090 static gboolean
1091 decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
1092 {
1093         return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
1094 }
1095
1096 /*
1097  * decode_resolve_method_ref_with_target:
1098  *
1099  *   Similar to decode_method_ref, but resolve and return the method itself.
1100  */
1101 static MonoMethod*
1102 decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
1103 {
1104         MethodRef ref;
1105         gboolean res;
1106
1107         res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
1108         if (!res)
1109                 return NULL;
1110         if (ref.method)
1111                 return ref.method;
1112         if (!ref.image)
1113                 return NULL;
1114         return mono_get_method (ref.image, ref.token, NULL);
1115 }
1116
1117 static MonoMethod*
1118 decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
1119 {
1120         return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
1121 }
1122
1123 static void
1124 create_cache_structure (void)
1125 {
1126         const char *home;
1127         char *tmp;
1128         int err;
1129
1130         home = g_get_home_dir ();
1131         if (!home)
1132                 return;
1133
1134         tmp = g_build_filename (home, ".mono", NULL);
1135         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1136                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1137 #ifdef HOST_WIN32
1138                 err = mkdir (tmp);
1139 #else
1140                 err = mkdir (tmp, 0777);
1141 #endif
1142                 if (err) {
1143                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1144                         g_free (tmp);
1145                         return;
1146                 }
1147         }
1148         g_free (tmp);
1149         tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
1150         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
1151                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
1152 #ifdef HOST_WIN32
1153                 err = mkdir (tmp);
1154 #else
1155                 err = mkdir (tmp, 0777);
1156 #endif
1157                 if (err) {
1158                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
1159                         g_free (tmp);
1160                         return;
1161                 }
1162         }
1163         g_free (tmp);
1164 }
1165
1166 /*
1167  * load_aot_module_from_cache:
1168  *
1169  *  Experimental code to AOT compile loaded assemblies on demand. 
1170  *
1171  * FIXME: 
1172  * - Add environment variable MONO_AOT_CACHE_OPTIONS
1173  * - Add options for controlling the cache size
1174  * - Handle full cache by deleting old assemblies lru style
1175  * - Add options for excluding assemblies during development
1176  * - Maybe add a threshold after an assembly is AOT compiled
1177  * - invoking a new mono process is a security risk
1178  * - recompile the AOT module if one of its dependencies changes
1179  */
1180 static MonoDl*
1181 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
1182 {
1183         char *fname, *cmd, *tmp2, *aot_options;
1184         const char *home;
1185         MonoDl *module;
1186         gboolean res;
1187         gchar *out, *err;
1188         gint exit_status;
1189
1190         *aot_name = NULL;
1191
1192         if (assembly->image->dynamic)
1193                 return NULL;
1194
1195         create_cache_structure ();
1196
1197         home = g_get_home_dir ();
1198
1199         tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
1200         fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
1201         *aot_name = fname;
1202         g_free (tmp2);
1203
1204         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
1205         module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1206
1207         if (!module) {
1208                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
1209
1210                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
1211
1212                 aot_options = g_strdup_printf ("outfile=%s", fname);
1213
1214                 if (spawn_compiler) {
1215                         /* FIXME: security */
1216                         /* FIXME: Has to pass the assembly loading path to the child process */
1217                         cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
1218
1219                         res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
1220
1221 #if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
1222                         if (res) {
1223                                 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
1224                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
1225                                 else
1226                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1227                                 g_free (out);
1228                                 g_free (err);
1229                         }
1230 #endif
1231                         g_free (cmd);
1232                 } else {
1233                         res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
1234                         if (!res) {
1235                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
1236                         } else {
1237                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
1238                         }
1239                 }
1240
1241                 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
1242
1243                 g_free (aot_options);
1244         }
1245
1246         return module;
1247 }
1248
1249 static void
1250 find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
1251 {
1252         if (globals) {
1253                 int global_index;
1254                 guint16 *table, *entry;
1255                 guint16 table_size;
1256                 guint32 hash;           
1257
1258                 /* The first entry points to the hash */
1259                 table = globals [0];
1260                 globals ++;
1261
1262                 table_size = table [0];
1263                 table ++;
1264
1265                 hash = mono_metadata_str_hash (name) % table_size;
1266
1267                 entry = &table [hash * 2];
1268
1269                 /* Search the hash for the index into the globals table */
1270                 global_index = -1;
1271                 while (entry [0] != 0) {
1272                         guint32 index = entry [0] - 1;
1273                         guint32 next = entry [1];
1274
1275                         //printf ("X: %s %s\n", (char*)globals [index * 2], name);
1276
1277                         if (!strcmp (globals [index * 2], name)) {
1278                                 global_index = index;
1279                                 break;
1280                         }
1281
1282                         if (next != 0) {
1283                                 entry = &table [next * 2];
1284                         } else {
1285                                 break;
1286                         }
1287                 }
1288
1289                 if (global_index != -1)
1290                         *value = globals [global_index * 2 + 1];
1291                 else
1292                         *value = NULL;
1293         } else {
1294                 char *err = mono_dl_symbol (module, name, value);
1295
1296                 if (err)
1297                         g_free (err);
1298         }
1299 }
1300
1301 static gboolean
1302 check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
1303 {
1304         char *build_info;
1305         char *msg = NULL;
1306         gboolean usable = TRUE;
1307         gboolean full_aot;
1308         guint8 *blob;
1309
1310         if (strcmp (assembly->image->guid, info->assembly_guid)) {
1311                 msg = g_strdup_printf ("doesn't match assembly");
1312                 usable = FALSE;
1313         }
1314
1315         build_info = mono_get_runtime_build_info ();
1316         if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
1317                 msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
1318                 usable = FALSE;
1319         }
1320         g_free (build_info);
1321
1322         full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
1323
1324         if (mono_aot_only && !full_aot) {
1325                 msg = g_strdup_printf ("not compiled with --aot=full");
1326                 usable = FALSE;
1327         }
1328         if (!mono_aot_only && full_aot) {
1329                 msg = g_strdup_printf ("compiled with --aot=full");
1330                 usable = FALSE;
1331         }
1332 #ifdef TARGET_ARM
1333         /* mono_arch_find_imt_method () requires this */
1334         if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
1335                 msg = g_strdup_printf ("compiled against LLVM");
1336                 usable = FALSE;
1337         }
1338         if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
1339                 msg = g_strdup_printf ("not compiled against LLVM");
1340                 usable = FALSE;
1341         }
1342 #endif
1343         if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
1344                 msg = g_strdup_printf ("not compiled for debugging");
1345                 usable = FALSE;
1346         }
1347
1348         blob = info->blob;
1349
1350         if (info->gc_name_index != -1) {
1351                 char *gc_name = (char*)&blob [info->gc_name_index];
1352                 const char *current_gc_name = mono_gc_get_gc_name ();
1353
1354                 if (strcmp (current_gc_name, gc_name) != 0) {
1355                         msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
1356                         usable = FALSE;
1357                 }
1358         }
1359
1360         *out_msg = msg;
1361         return usable;
1362 }
1363
1364 static void
1365 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1366 {
1367         char *aot_name;
1368         MonoAotModule *amodule;
1369         MonoDl *sofile;
1370         gboolean usable = TRUE;
1371         char *version_symbol = NULL;
1372         char *msg = NULL;
1373         gpointer *globals = NULL;
1374         MonoAotFileInfo *info = NULL;
1375         int i, version;
1376         guint8 *blob;
1377         gboolean do_load_image = TRUE;
1378
1379         if (mono_compile_aot)
1380                 return;
1381
1382         if (assembly->image->aot_module)
1383                 /* 
1384                  * Already loaded. This can happen because the assembly loading code might invoke
1385                  * the assembly load hooks multiple times for the same assembly.
1386                  */
1387                 return;
1388
1389         if (assembly->image->dynamic)
1390                 return;
1391
1392         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
1393                 return;
1394
1395         mono_aot_lock ();
1396         if (static_aot_modules)
1397                 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1398         else
1399                 info = NULL;
1400         mono_aot_unlock ();
1401
1402         if (info) {
1403                 /* Statically linked AOT module */
1404                 sofile = NULL;
1405                 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1406                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1407                 globals = info->globals;
1408         } else {
1409                 if (use_aot_cache)
1410                         sofile = load_aot_module_from_cache (assembly, &aot_name);
1411                 else {
1412                         char *err;
1413                         aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1414
1415                         sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1416
1417                         if (!sofile) {
1418                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1419                                 g_free (err);
1420                         }
1421                 }
1422         }
1423
1424         if (!sofile && !globals) {
1425                 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1426                         fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1427                         exit (1);
1428                 }
1429                 g_free (aot_name);
1430                 return;
1431         }
1432
1433         if (!info) {
1434                 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1435                 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1436         }
1437
1438         if (version_symbol) {
1439                 /* Old file format */
1440                 version = atoi (version_symbol);
1441         } else {
1442                 g_assert (info);
1443                 version = info->version;
1444         }
1445
1446         if (version != MONO_AOT_FILE_VERSION) {
1447                 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1448                 usable = FALSE;
1449         } else {
1450                 usable = check_usable (assembly, info, &msg);
1451         }
1452
1453         if (!usable) {
1454                 if (mono_aot_only) {
1455                         fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1456                         exit (1);
1457                 } else {
1458                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1459                 }
1460                 g_free (msg);
1461                 g_free (aot_name);
1462                 if (sofile)
1463                         mono_dl_close (sofile);
1464                 assembly->image->aot_module = NULL;
1465                 return;
1466         }
1467
1468         /* Sanity check */
1469         g_assert (info->double_align == __alignof__ (double));
1470         g_assert (info->long_align == __alignof__ (gint64));
1471
1472         blob = info->blob;
1473
1474         amodule = g_new0 (MonoAotModule, 1);
1475         amodule->aot_name = aot_name;
1476         amodule->assembly = assembly;
1477
1478         memcpy (&amodule->info, info, sizeof (*info));
1479
1480         amodule->got = amodule->info.got;
1481         amodule->got [0] = assembly->image;
1482         amodule->globals = globals;
1483         amodule->sofile = sofile;
1484         amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1485         amodule->blob = blob;
1486
1487         /* Read image table */
1488         {
1489                 guint32 table_len, i;
1490                 char *table = NULL;
1491
1492                 table = info->image_table;
1493                 g_assert (table);
1494
1495                 table_len = *(guint32*)table;
1496                 table += sizeof (guint32);
1497                 amodule->image_table = g_new0 (MonoImage*, table_len);
1498                 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1499                 amodule->image_guids = g_new0 (char*, table_len);
1500                 amodule->image_table_len = table_len;
1501                 for (i = 0; i < table_len; ++i) {
1502                         MonoAssemblyName *aname = &(amodule->image_names [i]);
1503
1504                         aname->name = g_strdup (table);
1505                         table += strlen (table) + 1;
1506                         amodule->image_guids [i] = g_strdup (table);
1507                         table += strlen (table) + 1;
1508                         if (table [0] != 0)
1509                                 aname->culture = g_strdup (table);
1510                         table += strlen (table) + 1;
1511                         memcpy (aname->public_key_token, table, strlen (table) + 1);
1512                         table += strlen (table) + 1;                    
1513
1514                         table = ALIGN_PTR_TO (table, 8);
1515                         aname->flags = *(guint32*)table;
1516                         table += 4;
1517                         aname->major = *(guint32*)table;
1518                         table += 4;
1519                         aname->minor = *(guint32*)table;
1520                         table += 4;
1521                         aname->build = *(guint32*)table;
1522                         table += 4;
1523                         aname->revision = *(guint32*)table;
1524                         table += 4;
1525                 }
1526         }
1527
1528         amodule->code_offsets = info->code_offsets;
1529         amodule->code = info->methods;
1530 #ifdef TARGET_ARM
1531         /* Mask out thumb interop bit */
1532         amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1533 #endif
1534         amodule->code_end = info->methods_end;
1535         amodule->method_info_offsets = info->method_info_offsets;
1536         amodule->ex_info_offsets = info->ex_info_offsets;
1537         amodule->class_info_offsets = info->class_info_offsets;
1538         amodule->class_name_table = info->class_name_table;
1539         amodule->extra_method_table = info->extra_method_table;
1540         amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1541         amodule->unbox_trampolines = info->unbox_trampolines;
1542         amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1543         amodule->got_info_offsets = info->got_info_offsets;
1544         amodule->unwind_info = info->unwind_info;
1545         amodule->mem_end = info->mem_end;
1546         amodule->mem_begin = amodule->code;
1547         amodule->plt = info->plt;
1548         amodule->plt_end = info->plt_end;
1549         amodule->mono_eh_frame = info->mono_eh_frame;
1550         amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1551         amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1552         amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1553         amodule->thumb_end = info->thumb_end;
1554
1555         if (make_unreadable) {
1556 #ifndef TARGET_WIN32
1557                 guint8 *addr;
1558                 guint8 *page_start, *page_end;
1559                 int err, len;
1560
1561                 addr = amodule->mem_begin;
1562                 len = amodule->mem_end - amodule->mem_begin;
1563
1564                 /* Round down in both directions to avoid modifying data which is not ours */
1565                 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1566                 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1567                 if (page_end > page_start) {
1568                         err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1569                         g_assert (err == 0);
1570                 }
1571 #endif
1572         }
1573
1574         mono_aot_lock ();
1575
1576         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1577         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1578
1579         g_hash_table_insert (aot_modules, assembly, amodule);
1580         mono_aot_unlock ();
1581
1582         mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1583
1584         assembly->image->aot_module = amodule;
1585
1586         if (mono_aot_only) {
1587                 if (mono_defaults.corlib) {
1588                         /* The second got slot contains the mscorlib got addr */
1589                         MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1590
1591                         amodule->got [1] = mscorlib_amodule->got;
1592                 } else {
1593                         amodule->got [1] = amodule->got;
1594                 }
1595         }
1596
1597         if (mono_gc_is_moving ()) {
1598                 MonoJumpInfo ji;
1599
1600                 memset (&ji, 0, sizeof (ji));
1601                 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1602
1603                 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1604         }
1605
1606         /*
1607          * Since we store methoddef and classdef tokens when referring to methods/classes in
1608          * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1609          * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1610          * non-lazily, since we can't handle out-of-date errors later.
1611          * The cached class info also depends on the exact assemblies.
1612          */
1613 #if defined(__native_client__)
1614         /* TODO: Don't 'load_image' on mscorlib due to a */
1615         /* recursive loading problem.  This should be    */
1616         /* removed if mscorlib is loaded from disk.      */
1617         if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1618                 do_load_image = TRUE;
1619         } else {
1620                 do_load_image = FALSE;
1621         }
1622 #endif
1623         if (do_load_image) {
1624                 for (i = 0; i < amodule->image_table_len; ++i)
1625                         load_image (amodule, i, FALSE);
1626         }
1627
1628         if (amodule->out_of_date) {
1629                 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);
1630                 if (mono_aot_only) {
1631                         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);
1632                         exit (1);
1633                 }
1634         }
1635         else
1636                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1637 }
1638
1639 /*
1640  * mono_aot_register_globals:
1641  *
1642  *   This is called by the ctor function in AOT images compiled with the
1643  * 'no-dlsym' option.
1644  */
1645 void
1646 mono_aot_register_globals (gpointer *globals)
1647 {
1648         g_assert_not_reached ();
1649 }
1650
1651 /*
1652  * mono_aot_register_module:
1653  *
1654  *   This should be called by embedding code to register AOT modules statically linked
1655  * into the executable. AOT_INFO should be the value of the 
1656  * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1657  */
1658 void
1659 mono_aot_register_module (gpointer *aot_info)
1660 {
1661         gpointer *globals;
1662         char *aname;
1663         MonoAotFileInfo *info = (gpointer)aot_info;
1664
1665         g_assert (info->version == MONO_AOT_FILE_VERSION);
1666
1667         globals = info->globals;
1668         g_assert (globals);
1669
1670         aname = info->assembly_name;
1671
1672         /* This could be called before startup */
1673         if (aot_modules)
1674                 mono_aot_lock ();
1675
1676         if (!static_aot_modules)
1677                 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1678
1679         g_hash_table_insert (static_aot_modules, aname, info);
1680
1681         if (aot_modules)
1682                 mono_aot_unlock ();
1683 }
1684
1685 void
1686 mono_aot_init (void)
1687 {
1688         InitializeCriticalSection (&aot_mutex);
1689         aot_modules = g_hash_table_new (NULL, NULL);
1690
1691         mono_install_assembly_load_hook (load_aot_module, NULL);
1692
1693         if (g_getenv ("MONO_LASTAOT"))
1694                 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1695         if (g_getenv ("MONO_AOT_CACHE"))
1696                 use_aot_cache = TRUE;
1697 }
1698
1699 void
1700 mono_aot_cleanup (void)
1701 {
1702         if (aot_jit_icall_hash)
1703                 g_hash_table_destroy (aot_jit_icall_hash);
1704         if (aot_modules)
1705                 g_hash_table_destroy (aot_modules);
1706 }
1707
1708 static gboolean
1709 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1710 {
1711         guint32 flags;
1712         MethodRef ref;
1713         gboolean res;
1714
1715         info->vtable_size = decode_value (buf, &buf);
1716         if (info->vtable_size == -1)
1717                 /* Generic type */
1718                 return FALSE;
1719         flags = decode_value (buf, &buf);
1720         info->ghcimpl = (flags >> 0) & 0x1;
1721         info->has_finalize = (flags >> 1) & 0x1;
1722         info->has_cctor = (flags >> 2) & 0x1;
1723         info->has_nested_classes = (flags >> 3) & 0x1;
1724         info->blittable = (flags >> 4) & 0x1;
1725         info->has_references = (flags >> 5) & 0x1;
1726         info->has_static_refs = (flags >> 6) & 0x1;
1727         info->no_special_static_fields = (flags >> 7) & 0x1;
1728         info->is_generic_container = (flags >> 8) & 0x1;
1729
1730         if (info->has_cctor) {
1731                 res = decode_method_ref (module, &ref, buf, &buf);
1732                 if (!res)
1733                         return FALSE;
1734                 info->cctor_token = ref.token;
1735         }
1736         if (info->has_finalize) {
1737                 res = decode_method_ref (module, &ref, buf, &buf);
1738                 if (!res)
1739                         return FALSE;
1740                 info->finalize_image = ref.image;
1741                 info->finalize_token = ref.token;
1742         }
1743
1744         info->instance_size = decode_value (buf, &buf);
1745         info->class_size = decode_value (buf, &buf);
1746         info->packing_size = decode_value (buf, &buf);
1747         info->min_align = decode_value (buf, &buf);
1748
1749         *endbuf = buf;
1750
1751         return TRUE;
1752 }       
1753
1754 gpointer
1755 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1756 {
1757         int i;
1758         MonoClass *klass = vtable->klass;
1759         MonoAotModule *amodule = klass->image->aot_module;
1760         guint8 *info, *p;
1761         MonoCachedClassInfo class_info;
1762         gboolean err;
1763         MethodRef ref;
1764         gboolean res;
1765
1766         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
1767                 return NULL;
1768
1769         info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1770         p = info;
1771
1772         err = decode_cached_class_info (amodule, &class_info, p, &p);
1773         if (!err)
1774                 return NULL;
1775
1776         for (i = 0; i < slot; ++i)
1777                 decode_method_ref (amodule, &ref, p, &p);
1778
1779         res = decode_method_ref (amodule, &ref, p, &p);
1780         if (!res)
1781                 return NULL;
1782         if (ref.no_aot_trampoline)
1783                 return NULL;
1784
1785         if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
1786                 return NULL;
1787
1788         return mono_aot_get_method_from_token (domain, ref.image, ref.token);
1789 }
1790
1791 gboolean
1792 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1793 {
1794         MonoAotModule *amodule = klass->image->aot_module;
1795         guint8 *p;
1796         gboolean err;
1797
1798         if (klass->rank || !amodule)
1799                 return FALSE;
1800
1801         p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1802
1803         err = decode_cached_class_info (amodule, res, p, &p);
1804         if (!err)
1805                 return FALSE;
1806
1807         return TRUE;
1808 }
1809
1810 /**
1811  * mono_aot_get_class_from_name:
1812  *
1813  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1814  * using a cache stored in the AOT file.
1815  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1816  *
1817  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
1818  * found.
1819  */
1820 gboolean
1821 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1822 {
1823         MonoAotModule *amodule = image->aot_module;
1824         guint16 *table, *entry;
1825         guint16 table_size;
1826         guint32 hash;
1827         char full_name_buf [1024];
1828         char *full_name;
1829         const char *name2, *name_space2;
1830         MonoTableInfo  *t;
1831         guint32 cols [MONO_TYPEDEF_SIZE];
1832         GHashTable *nspace_table;
1833
1834         if (!amodule || !amodule->class_name_table)
1835                 return FALSE;
1836
1837         mono_aot_lock ();
1838
1839         *klass = NULL;
1840
1841         /* First look in the cache */
1842         if (!amodule->name_cache)
1843                 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1844         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1845         if (nspace_table) {
1846                 *klass = g_hash_table_lookup (nspace_table, name);
1847                 if (*klass) {
1848                         mono_aot_unlock ();
1849                         return TRUE;
1850                 }
1851         }
1852
1853         table_size = amodule->class_name_table [0];
1854         table = amodule->class_name_table + 1;
1855
1856         if (name_space [0] == '\0')
1857                 full_name = g_strdup_printf ("%s", name);
1858         else {
1859                 if (strlen (name_space) + strlen (name) < 1000) {
1860                         sprintf (full_name_buf, "%s.%s", name_space, name);
1861                         full_name = full_name_buf;
1862                 } else {
1863                         full_name = g_strdup_printf ("%s.%s", name_space, name);
1864                 }
1865         }
1866         hash = mono_metadata_str_hash (full_name) % table_size;
1867         if (full_name != full_name_buf)
1868                 g_free (full_name);
1869
1870         entry = &table [hash * 2];
1871
1872         if (entry [0] != 0) {
1873                 t = &image->tables [MONO_TABLE_TYPEDEF];
1874
1875                 while (TRUE) {
1876                         guint32 index = entry [0];
1877                         guint32 next = entry [1];
1878                         guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
1879
1880                         name_table_accesses ++;
1881
1882                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
1883
1884                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
1885                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
1886
1887                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
1888                                 mono_aot_unlock ();
1889                                 *klass = mono_class_get (image, token);
1890
1891                                 /* Add to cache */
1892                                 if (*klass) {
1893                                         mono_aot_lock ();
1894                                         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1895                                         if (!nspace_table) {
1896                                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
1897                                                 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
1898                                         }
1899                                         g_hash_table_insert (nspace_table, (char*)name2, *klass);
1900                                         mono_aot_unlock ();
1901                                 }
1902                                 return TRUE;
1903                         }
1904
1905                         if (next != 0) {
1906                                 entry = &table [next * 2];
1907                         } else {
1908                                 break;
1909                         }
1910                 }
1911         }
1912
1913         mono_aot_unlock ();
1914         
1915         return TRUE;
1916 }
1917
1918 /*
1919  * decode_mono_eh_frame:
1920  *
1921  *   Decode the EH information emitted by our modified LLVM compiler and construct a
1922  * MonoJitInfo structure from it.
1923  * LOCKING: Acquires the domain lock.
1924  */
1925 static MonoJitInfo*
1926 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, 
1927                                                    MonoMethod *method, guint8 *code, 
1928                                                    MonoJitExceptionInfo *clauses, int num_clauses,
1929                                                    int extra_size, GSList **nesting,
1930                                                    int *this_reg, int *this_offset)
1931 {
1932         guint8 *p;
1933         guint8 *fde, *cie, *code_start, *code_end;
1934         int version, fde_count;
1935         gint32 *table;
1936         int i, j, pos, left, right, offset, offset1, offset2, code_len;
1937         MonoJitExceptionInfo *ei;
1938         guint32 fde_len, ei_len, nested_len, nindex;
1939         gpointer *type_info;
1940         MonoJitInfo *jinfo;
1941         MonoLLVMFDEInfo info;
1942
1943         g_assert (amodule->mono_eh_frame);
1944
1945         p = amodule->mono_eh_frame;
1946
1947         /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
1948
1949         /* Header */
1950         version = *p;
1951         g_assert (version == 1);
1952         p ++;
1953         p = ALIGN_PTR_TO (p, 4);
1954
1955         fde_count = *(guint32*)p;
1956         p += 4;
1957         table = (gint32*)p;
1958
1959         /* There is +1 entry in the table */
1960         cie = p + ((fde_count + 1) * 8);
1961
1962         /* Binary search in the table to find the entry for code */
1963         offset = code - amodule->mono_eh_frame;
1964
1965         left = 0;
1966         right = fde_count;
1967         while (TRUE) {
1968                 pos = (left + right) / 2;
1969
1970                 offset1 = table [(pos * 2)];
1971                 if (pos + 1 == fde_count)
1972                         /* FIXME: */
1973                         offset2 = amodule->code_end - amodule->code;
1974                 else
1975                         offset2 = table [(pos + 1) * 2];
1976
1977                 if (offset < offset1)
1978                         right = pos;
1979                 else if (offset >= offset2)
1980                         left = pos + 1;
1981                 else
1982                         break;
1983         }
1984
1985         code_start = amodule->mono_eh_frame + table [(pos * 2)];
1986         /* This won't overflow because there is +1 entry in the table */
1987         code_end = amodule->mono_eh_frame + table [(pos * 2) + 2];
1988         code_len = code_end - code_start;
1989
1990         g_assert (code >= code_start && code < code_end);
1991
1992         fde = amodule->mono_eh_frame + table [(pos * 2) + 1];   
1993         /* This won't overflow because there is +1 entry in the table */
1994         fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
1995
1996         mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
1997         ei = info.ex_info;
1998         ei_len = info.ex_info_len;
1999         type_info = info.type_info;
2000         *this_reg = info.this_reg;
2001         *this_offset = info.this_offset;
2002
2003         /* Count number of nested clauses */
2004         nested_len = 0;
2005         for (i = 0; i < ei_len; ++i) {
2006                 /* This might be unaligned */
2007                 gint32 cindex1 = read32 (type_info [i]);
2008                 GSList *l;
2009
2010                 for (l = nesting [cindex1]; l; l = l->next) {
2011                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2012
2013                         for (j = 0; j < ei_len; ++j) {
2014                                 gint32 cindex2 = read32 (type_info [j]);
2015
2016                                 if (cindex2 == nesting_cindex)
2017                                         nested_len ++;
2018                         }
2019                 }
2020         }
2021
2022         /*
2023          * LLVM might represent one IL region with multiple regions, so have to
2024          * allocate a new JI.
2025          */
2026         jinfo = 
2027                 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2028
2029         jinfo->code_size = code_len;
2030         jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2031         jinfo->method = method;
2032         jinfo->code_start = code;
2033         jinfo->domain_neutral = 0;
2034         /* This signals that used_regs points to a normal cached unwind info */
2035         jinfo->from_aot = 0;
2036         jinfo->num_clauses = ei_len + nested_len;
2037
2038         for (i = 0; i < ei_len; ++i) {
2039                 /*
2040                  * orig_jinfo contains the original IL exception info saved by the AOT
2041                  * compiler, we have to combine that with the information produced by LLVM
2042                  */
2043                 /* The type_info entries contain IL clause indexes */
2044                 int clause_index = read32 (type_info [i]);
2045                 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2046                 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2047
2048                 g_assert (clause_index < num_clauses);
2049                 jei->flags = orig_jei->flags;
2050                 jei->data.catch_class = orig_jei->data.catch_class;
2051
2052                 jei->try_start = ei [i].try_start;
2053                 jei->try_end = ei [i].try_end;
2054                 jei->handler_start = ei [i].handler_start;
2055
2056                 /* Make sure we transition to thumb when a handler starts */
2057                 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2058                         jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2059         }
2060
2061         /* See exception_cb () in mini-llvm.c as to why this is needed */
2062         nindex = ei_len;
2063         for (i = 0; i < ei_len; ++i) {
2064                 gint32 cindex1 = read32 (type_info [i]);
2065                 GSList *l;
2066
2067                 for (l = nesting [cindex1]; l; l = l->next) {
2068                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2069
2070                         for (j = 0; j < ei_len; ++j) {
2071                                 gint32 cindex2 = read32 (type_info [j]);
2072
2073                                 if (cindex2 == nesting_cindex) {
2074                                         /* 
2075                                          * The try interval comes from the nested clause, everything else from the
2076                                          * nesting clause.
2077                                          */
2078                                         memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2079                                         jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2080                                         jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2081                                         nindex ++;
2082                                 }
2083                         }
2084                 }
2085         }
2086         g_assert (nindex == ei_len + nested_len);
2087
2088         return jinfo;
2089 }
2090
2091 /*
2092  * LOCKING: Acquires the domain lock.
2093  */
2094 static MonoJitInfo*
2095 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, 
2096                                                          MonoMethod *method, guint8* ex_info, guint8 *addr,
2097                                                          guint8 *code, guint32 code_len)
2098 {
2099         int i, buf_len, num_clauses;
2100         MonoJitInfo *jinfo;
2101         guint used_int_regs, flags;
2102         gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2103         gboolean from_llvm, has_gc_map;
2104         guint8 *p;
2105         int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2106         int this_reg = 0, this_offset = 0;
2107
2108         /* Load the method info from the AOT file */
2109
2110         p = ex_info;
2111         flags = decode_value (p, &p);
2112         has_generic_jit_info = (flags & 1) != 0;
2113         has_dwarf_unwind_info = (flags & 2) != 0;
2114         has_clauses = (flags & 4) != 0;
2115         has_seq_points = (flags & 8) != 0;
2116         from_llvm = (flags & 16) != 0;
2117         has_try_block_holes = (flags & 32) != 0;
2118         has_gc_map = (flags & 64) != 0;
2119         has_arch_eh_jit_info = (flags & 128) != 0;
2120
2121         if (has_dwarf_unwind_info) {
2122                 guint32 offset;
2123
2124                 offset = decode_value (p, &p);
2125                 g_assert (offset < (1 << 30));
2126                 used_int_regs = offset;
2127         } else {
2128                 used_int_regs = decode_value (p, &p);
2129         }
2130         if (has_generic_jit_info)
2131                 generic_info_size = sizeof (MonoGenericJitInfo);
2132         else
2133                 generic_info_size = 0;
2134
2135         if (has_try_block_holes) {
2136                 num_holes = decode_value (p, &p);
2137                 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2138         } else {
2139                 num_holes = try_holes_info_size = 0;
2140         }
2141         /* Exception table */
2142         if (has_clauses)
2143                 num_clauses = decode_value (p, &p);
2144         else
2145                 num_clauses = 0;
2146         if (has_arch_eh_jit_info)
2147                 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2148         else
2149                 arch_eh_jit_info_size = 0;
2150
2151         if (from_llvm) {
2152                 MonoJitExceptionInfo *clauses;
2153                 GSList **nesting;
2154
2155                 /*
2156                  * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2157                  * section.
2158                  */
2159                 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2160                 nesting = g_new0 (GSList*, num_clauses);
2161
2162                 for (i = 0; i < num_clauses; ++i) {
2163                         MonoJitExceptionInfo *ei = &clauses [i];
2164
2165                         ei->flags = decode_value (p, &p);
2166
2167                         if (decode_value (p, &p))
2168                                 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2169
2170                         /* Read the list of nesting clauses */
2171                         while (TRUE) {
2172                                 int nesting_index = decode_value (p, &p);
2173                                 if (nesting_index == -1)
2174                                         break;
2175                                 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2176                         }
2177                 }
2178
2179                 jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size + arch_eh_jit_info_size, nesting, &this_reg, &this_offset);
2180                 jinfo->from_llvm = 1;
2181
2182                 g_free (clauses);
2183                 for (i = 0; i < num_clauses; ++i)
2184                         g_slist_free (nesting [i]);
2185                 g_free (nesting);
2186         } else {
2187                 jinfo = 
2188                         mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size);
2189                 jinfo->num_clauses = num_clauses;
2190
2191                 for (i = 0; i < jinfo->num_clauses; ++i) {
2192                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2193
2194                         ei->flags = decode_value (p, &p);
2195
2196                         ei->exvar_offset = decode_value (p, &p);
2197
2198                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2199                                 ei->data.filter = code + decode_value (p, &p);
2200                         else {
2201                                 if (decode_value (p, &p))
2202                                         ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2203                         }
2204
2205                         ei->try_start = code + decode_value (p, &p);
2206                         ei->try_end = code + decode_value (p, &p);
2207                         ei->handler_start = code + decode_value (p, &p);
2208                 }
2209
2210                 jinfo->code_size = code_len;
2211                 jinfo->used_regs = used_int_regs;
2212                 jinfo->method = method;
2213                 jinfo->code_start = code;
2214                 jinfo->domain_neutral = 0;
2215                 jinfo->from_aot = 1;
2216         }
2217
2218         if (has_generic_jit_info) {
2219                 MonoGenericJitInfo *gi;
2220
2221                 jinfo->has_generic_jit_info = 1;
2222
2223                 gi = mono_jit_info_get_generic_jit_info (jinfo);
2224                 g_assert (gi);
2225
2226                 gi->nlocs = decode_value (p, &p);
2227                 if (gi->nlocs) {
2228                         gi->locations = mono_domain_alloc0 (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2229                         for (i = 0; i < gi->nlocs; ++i) {
2230                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
2231
2232                                 entry->is_reg = decode_value (p, &p);
2233                                 entry->reg = decode_value (p, &p);
2234                                 if (!entry->is_reg)
2235                                         entry->offset = decode_value (p, &p);
2236                                 if (i > 0)
2237                                         entry->from = decode_value (p, &p);
2238                                 entry->to = decode_value (p, &p);
2239                         }
2240                 } else {
2241                         if (from_llvm) {
2242                                 gi->has_this = this_reg != -1;
2243                                 gi->this_reg = this_reg;
2244                                 gi->this_offset = this_offset;
2245                         } else {
2246                                 gi->has_this = decode_value (p, &p);
2247                                 gi->this_reg = decode_value (p, &p);
2248                                 gi->this_offset = decode_value (p, &p);
2249                         }
2250                 }
2251
2252                 /* This currently contains no data */
2253                 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2254
2255                 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
2256         }
2257
2258         if (has_try_block_holes) {
2259                 MonoTryBlockHoleTableJitInfo *table;
2260
2261                 jinfo->has_try_block_holes = 1;
2262
2263                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2264                 g_assert (table);
2265
2266                 table->num_holes = (guint16)num_holes;
2267                 for (i = 0; i < num_holes; ++i) {
2268                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2269                         hole->clause = decode_value (p, &p);
2270                         hole->length = decode_value (p, &p);
2271                         hole->offset = decode_value (p, &p);
2272                 }
2273         }
2274
2275         if (has_arch_eh_jit_info) {
2276                 MonoArchEHJitInfo *eh_info;
2277
2278                 jinfo->has_arch_eh_info = 1;
2279
2280                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2281                 eh_info->stack_size = decode_value (p, &p);
2282         }
2283
2284         if (has_seq_points) {
2285                 MonoSeqPointInfo *seq_points;
2286                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2287
2288                 int len = decode_value (p, &p);
2289
2290                 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2291                 seq_points->len = len;
2292                 last_il_offset = last_native_offset = 0;
2293                 for (i = 0; i < len; ++i) {
2294                         SeqPoint *sp = &seq_points->seq_points [i];
2295                         il_offset = last_il_offset + decode_value (p, &p);
2296                         native_offset = last_native_offset + decode_value (p, &p);
2297
2298                         sp->il_offset = il_offset;
2299                         sp->native_offset = native_offset;
2300                         
2301                         sp->next_len = decode_value (p, &p);
2302                         sp->next = g_new (int, sp->next_len);
2303                         for (j = 0; j < sp->next_len; ++j)
2304                                 sp->next [j] = decode_value (p, &p);
2305
2306                         last_il_offset = il_offset;
2307                         last_native_offset = native_offset;
2308                 }
2309
2310                 mono_domain_lock (domain);
2311                 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2312                 mono_domain_unlock (domain);
2313         }
2314
2315         /* Load debug info */
2316         buf_len = decode_value (p, &p);
2317         mono_debug_add_aot_method (domain, method, code, p, buf_len);
2318         p += buf_len;
2319
2320         if (has_gc_map) {
2321                 int map_size = decode_value (p, &p);
2322                 /* The GC map requires 4 bytes of alignment */
2323                 while ((guint64)(gsize)p % 4)
2324                         p ++;           
2325                 jinfo->gc_info = p;
2326                 p += map_size;
2327         }
2328
2329         if (amodule != jinfo->method->klass->image->aot_module) {
2330                 mono_aot_lock ();
2331                 if (!ji_to_amodule)
2332                         ji_to_amodule = g_hash_table_new (NULL, NULL);
2333                 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2334                 mono_aot_unlock ();             
2335         }
2336
2337         return jinfo;
2338 }
2339
2340 /*
2341  * mono_aot_get_unwind_info:
2342  *
2343  *   Return a pointer to the DWARF unwind info belonging to JI.
2344  */
2345 guint8*
2346 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2347 {
2348         MonoAotModule *amodule = ji->method->klass->image->aot_module;
2349         guint8 *p;
2350         guint8 *code = ji->code_start;
2351
2352         g_assert (amodule);
2353         g_assert (ji->from_aot);
2354
2355         if (!(code >= amodule->code && code <= amodule->code_end)) {
2356                 /* ji belongs to a different aot module than amodule */
2357                 mono_aot_lock ();
2358                 g_assert (ji_to_amodule);
2359                 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2360                 g_assert (amodule);
2361                 g_assert (code >= amodule->code && code <= amodule->code_end);
2362                 mono_aot_unlock ();
2363         }
2364
2365         p = amodule->unwind_info + ji->used_regs;
2366         *unwind_info_len = decode_value (p, &p);
2367         return p;
2368 }
2369
2370 static G_GNUC_UNUSED int
2371 compare_ints (const void *a, const void *b)
2372 {
2373         return *(gint32*)a - *(gint32*)b;
2374 }
2375
2376 static void
2377 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2378 {
2379         int mid = (lo + hi) / 2;
2380         int i, t_lo, t_hi;
2381
2382         if (lo >= hi)
2383                 return;
2384
2385         if (hi - lo < 32) {
2386                 for (i = lo; i < hi; ++i)
2387                         if (array [(i * 2)] > array [(i * 2) + 2])
2388                                 break;
2389                 if (i == hi)
2390                         /* Already sorted */
2391                         return;
2392         }
2393
2394         msort_code_offsets_internal (array, lo, mid, scratch);
2395         msort_code_offsets_internal (array, mid + 1, hi, scratch);
2396
2397         if (array [mid * 2] < array [(mid + 1) * 2])
2398                 return;
2399
2400         /* Merge */
2401         t_lo = lo;
2402         t_hi = mid + 1;
2403         for (i = lo; i <= hi; i ++) {
2404                 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2405                         scratch [(i * 2)] = array [t_lo * 2];
2406                         scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2407                         t_lo ++;
2408                 } else {
2409                         scratch [(i * 2)] = array [t_hi * 2];
2410                         scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2411                         t_hi ++;
2412                 }
2413         }
2414         for (i = lo; i <= hi; ++i) {
2415                 array [(i * 2)] = scratch [i * 2];
2416                 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2417         }
2418 }
2419
2420 static void
2421 msort_code_offsets (gint32 *array, int len)
2422 {
2423         gint32 *scratch;
2424
2425         scratch = g_new (gint32, len * 2);
2426         msort_code_offsets_internal (array, 0, len - 1, scratch);
2427         g_free (scratch);
2428 }
2429
2430 MonoJitInfo *
2431 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2432 {
2433         int pos, left, right, offset, offset1, offset2, code_len;
2434         int method_index, table_len, is_wrapper;
2435         guint32 token;
2436         MonoAotModule *amodule = image->aot_module;
2437         MonoMethod *method;
2438         MonoJitInfo *jinfo;
2439         guint8 *code, *ex_info, *p;
2440         guint32 *table;
2441         int nmethods = amodule->info.nmethods;
2442         gint32 *code_offsets;
2443         int offsets_len, i;
2444
2445         if (!amodule)
2446                 return NULL;
2447
2448         if (domain != mono_get_root_domain ())
2449                 /* FIXME: */
2450                 return NULL;
2451
2452         offset = (guint8*)addr - amodule->code;
2453
2454         /* Compute a sorted table mapping code offsets to method indexes. */
2455         if (!amodule->sorted_code_offsets) {
2456                 code_offsets = g_new0 (gint32, nmethods * 2);
2457                 offsets_len = 0;
2458                 for (i = 0; i < nmethods; ++i) {
2459                         /* Skip the -1 entries to speed up sorting */
2460                         if (amodule->code_offsets [i] == 0xffffffff)
2461                                 continue;
2462                         code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2463                         code_offsets [(offsets_len *2) + 1] = i;
2464                         offsets_len ++;
2465                 }
2466                 /* Use a merge sort as this is mostly sorted */
2467                 msort_code_offsets (code_offsets, offsets_len);
2468                 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2469                 for (i = 0; i < offsets_len -1; ++i)
2470                         g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2471
2472                 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2473                         /* Somebody got in before us */
2474                         g_free (code_offsets);
2475                 amodule->sorted_code_offsets_len = offsets_len;
2476         }
2477
2478         code_offsets = amodule->sorted_code_offsets;
2479         offsets_len = amodule->sorted_code_offsets_len;
2480
2481         /* Binary search in the sorted_code_offsets table */
2482         left = 0;
2483         right = offsets_len;
2484         while (TRUE) {
2485                 pos = (left + right) / 2;
2486
2487                 offset1 = code_offsets [(pos * 2)];
2488                 if (pos + 1 == offsets_len)
2489                         offset2 = amodule->code_end - amodule->code;
2490                 else
2491                         offset2 = code_offsets [(pos + 1) * 2];
2492
2493                 if (offset < offset1)
2494                         right = pos;
2495                 else if (offset >= offset2)
2496                         left = pos + 1;
2497                 else
2498                         break;
2499         }
2500
2501         g_assert (offset >= code_offsets [(pos * 2)]);
2502         if (pos + 1 < offsets_len)
2503                 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2504         method_index = code_offsets [(pos * 2) + 1];
2505
2506         code = &amodule->code [amodule->code_offsets [method_index]];
2507         ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2508
2509         if (pos == offsets_len - 1)
2510                 code_len = amodule->code_end - code;
2511         else
2512                 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2513
2514         g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2515
2516         /* Might be a wrapper/extra method */
2517         if (amodule->extra_methods) {
2518                 mono_aot_lock ();
2519                 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2520                 mono_aot_unlock ();
2521         } else {
2522                 method = NULL;
2523         }
2524
2525         if (!method) {
2526                 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2527                         /* 
2528                          * This is hit for extra methods which are called directly, so they are
2529                          * not in amodule->extra_methods.
2530                          */
2531                         table_len = amodule->extra_method_info_offsets [0];
2532                         table = amodule->extra_method_info_offsets + 1;
2533                         left = 0;
2534                         right = table_len;
2535                         pos = 0;
2536
2537                         /* Binary search */
2538                         while (TRUE) {
2539                                 pos = ((left + right) / 2);
2540
2541                                 g_assert (pos < table_len);
2542
2543                                 if (table [pos * 2] < method_index)
2544                                         left = pos + 1;
2545                                 else if (table [pos * 2] > method_index)
2546                                         right = pos;
2547                                 else
2548                                         break;
2549                         }
2550
2551                         p = amodule->blob + table [(pos * 2) + 1];
2552                         is_wrapper = decode_value (p, &p);
2553                         g_assert (!is_wrapper);
2554                         method = decode_resolve_method_ref (amodule, p, &p);
2555                         g_assert (method);
2556                 } else {
2557                         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2558                         method = mono_get_method (image, token, NULL);
2559                 }
2560         }
2561
2562         /* FIXME: */
2563         g_assert (method);
2564
2565         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2566         
2567         jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2568
2569         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2570         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2571
2572         /* Add it to the normal JitInfo tables */
2573         mono_jit_info_table_add (domain, jinfo);
2574         
2575         return jinfo;
2576 }
2577
2578 static gboolean
2579 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2580 {
2581         guint8 *p = buf;
2582         gpointer *table;
2583         MonoImage *image;
2584         int i;
2585
2586         switch (ji->type) {
2587         case MONO_PATCH_INFO_METHOD:
2588         case MONO_PATCH_INFO_METHOD_JUMP:
2589         case MONO_PATCH_INFO_ICALL_ADDR:
2590         case MONO_PATCH_INFO_METHOD_RGCTX: {
2591                 MethodRef ref;
2592                 gboolean res;
2593
2594                 res = decode_method_ref (aot_module, &ref, p, &p);
2595                 if (!res)
2596                         goto cleanup;
2597
2598                 if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
2599                         ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2600                         ji->type = MONO_PATCH_INFO_ABS;
2601                 }
2602                 else {
2603                         if (ref.method)
2604                                 ji->data.method = ref.method;
2605                         else
2606                                 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2607                         g_assert (ji->data.method);
2608                         mono_class_init (ji->data.method->klass);
2609                 }
2610                 break;
2611         }
2612         case MONO_PATCH_INFO_INTERNAL_METHOD:
2613         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2614                 guint32 len = decode_value (p, &p);
2615
2616                 ji->data.name = (char*)p;
2617                 p += len + 1;
2618                 break;
2619         }
2620         case MONO_PATCH_INFO_METHODCONST:
2621                 /* Shared */
2622                 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2623                 if (!ji->data.method)
2624                         goto cleanup;
2625                 break;
2626         case MONO_PATCH_INFO_VTABLE:
2627         case MONO_PATCH_INFO_CLASS:
2628         case MONO_PATCH_INFO_IID:
2629         case MONO_PATCH_INFO_ADJUSTED_IID:
2630                 /* Shared */
2631                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2632                 if (!ji->data.klass)
2633                         goto cleanup;
2634                 break;
2635         case MONO_PATCH_INFO_CLASS_INIT:
2636         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2637                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2638                 if (!ji->data.klass)
2639                         goto cleanup;
2640                 break;
2641         case MONO_PATCH_INFO_IMAGE:
2642                 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2643                 if (!ji->data.image)
2644                         goto cleanup;
2645                 break;
2646         case MONO_PATCH_INFO_FIELD:
2647         case MONO_PATCH_INFO_SFLDA:
2648                 /* Shared */
2649                 ji->data.field = decode_field_info (aot_module, p, &p);
2650                 if (!ji->data.field)
2651                         goto cleanup;
2652                 break;
2653         case MONO_PATCH_INFO_SWITCH:
2654                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2655                 ji->data.table->table_size = decode_value (p, &p);
2656                 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2657                 ji->data.table->table = (MonoBasicBlock**)table;
2658                 for (i = 0; i < ji->data.table->table_size; i++)
2659                         table [i] = (gpointer)(gssize)decode_value (p, &p);
2660                 break;
2661         case MONO_PATCH_INFO_R4: {
2662                 guint32 val;
2663                 
2664                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2665                 val = decode_value (p, &p);
2666                 *(float*)ji->data.target = *(float*)&val;
2667                 break;
2668         }
2669         case MONO_PATCH_INFO_R8: {
2670                 guint32 val [2];
2671                 guint64 v;
2672
2673                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2674
2675                 val [0] = decode_value (p, &p);
2676                 val [1] = decode_value (p, &p);
2677                 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2678                 *(double*)ji->data.target = *(double*)&v;
2679                 break;
2680         }
2681         case MONO_PATCH_INFO_LDSTR:
2682                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2683                 if (!image)
2684                         goto cleanup;
2685                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2686                 break;
2687         case MONO_PATCH_INFO_RVA:
2688         case MONO_PATCH_INFO_DECLSEC:
2689         case MONO_PATCH_INFO_LDTOKEN:
2690         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2691                 /* Shared */
2692                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2693                 if (!image)
2694                         goto cleanup;
2695                 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2696
2697                 ji->data.token->has_context = decode_value (p, &p);
2698                 if (ji->data.token->has_context) {
2699                         gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2700                         if (!res)
2701                                 goto cleanup;
2702                 }
2703                 break;
2704         case MONO_PATCH_INFO_EXC_NAME:
2705                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2706                 if (!ji->data.klass)
2707                         goto cleanup;
2708                 ji->data.name = ji->data.klass->name;
2709                 break;
2710         case MONO_PATCH_INFO_METHOD_REL:
2711                 ji->data.offset = decode_value (p, &p);
2712                 break;
2713         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2714         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2715         case MONO_PATCH_INFO_MONITOR_ENTER:
2716         case MONO_PATCH_INFO_MONITOR_EXIT:
2717         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
2718         case MONO_PATCH_INFO_CASTCLASS_CACHE:
2719                 break;
2720         case MONO_PATCH_INFO_RGCTX_FETCH: {
2721                 gboolean res;
2722                 MonoJumpInfoRgctxEntry *entry;
2723                 guint32 offset, val;
2724                 guint8 *p2;
2725
2726                 offset = decode_value (p, &p);
2727                 val = decode_value (p, &p);
2728
2729                 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2730                 p2 = aot_module->blob + offset;
2731                 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
2732                 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
2733                 entry->info_type = (val >> 1) & 0xff;
2734                 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2735                 entry->data->type = (val >> 9) & 0xff;
2736                 
2737                 res = decode_patch (aot_module, mp, entry->data, p, &p);
2738                 if (!res)
2739                         goto cleanup;
2740                 ji->data.rgctx_entry = entry;
2741                 break;
2742         }
2743         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2744                 break;
2745         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2746                 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2747
2748                 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2749                 imt_tramp->vt_offset = decode_value (p, &p);
2750                 
2751                 ji->data.imt_tramp = imt_tramp;
2752                 break;
2753         }
2754         case MONO_PATCH_INFO_SIGNATURE:
2755                 ji->data.target = decode_signature (aot_module, p, &p);
2756                 break;
2757         default:
2758                 g_warning ("unhandled type %d", ji->type);
2759                 g_assert_not_reached ();
2760         }
2761
2762         *endbuf = p;
2763
2764         return TRUE;
2765
2766  cleanup:
2767         return FALSE;
2768 }
2769
2770 static MonoJumpInfo*
2771 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
2772                                  guint32 **got_slots, 
2773                                  guint8 *buf, guint8 **endbuf)
2774 {
2775         MonoJumpInfo *patches;
2776         int pindex;
2777         guint8 *p;
2778
2779         p = buf;
2780
2781         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2782
2783         *got_slots = g_malloc (sizeof (guint32) * n_patches);
2784
2785         for (pindex = 0; pindex < n_patches; ++pindex) {
2786                 MonoJumpInfo *ji = &patches [pindex];
2787                 guint8 *shared_p;
2788                 gboolean res;
2789                 guint32 got_offset;
2790
2791                 got_offset = decode_value (p, &p);
2792
2793                 if (aot_module->got [got_offset]) {
2794                         /* Already loaded */
2795                         //printf ("HIT!\n");
2796                 } else {
2797                         shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
2798
2799                         ji->type = decode_value (shared_p, &shared_p);
2800
2801                         res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
2802                         if (!res)
2803                                 goto cleanup;
2804                 }
2805
2806                 (*got_slots) [pindex] = got_offset;
2807         }
2808
2809         *endbuf = p;
2810         return patches;
2811
2812  cleanup:
2813         g_free (*got_slots);
2814         *got_slots = NULL;
2815
2816         return NULL;
2817 }
2818
2819 static void
2820 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
2821 {
2822         /*
2823          * Jump addresses cannot be patched by the trampoline code since it
2824          * does not have access to the caller's address. Instead, we collect
2825          * the addresses of the GOT slots pointing to a method, and patch
2826          * them after the method has been compiled.
2827          */
2828         MonoJitDomainInfo *info = domain_jit_info (domain);
2829         GSList *list;
2830                 
2831         mono_domain_lock (domain);
2832         if (!info->jump_target_got_slot_hash)
2833                 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
2834         list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
2835         list = g_slist_prepend (list, got_slot);
2836         g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
2837         mono_domain_unlock (domain);
2838 }
2839
2840 /*
2841  * load_method:
2842  *
2843  *   Load the method identified by METHOD_INDEX from the AOT image. Return a
2844  * pointer to the native code of the method, or NULL if not found.
2845  * METHOD might not be set if the caller only has the image/token info.
2846  */
2847 static gpointer
2848 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
2849 {
2850         MonoClass *klass;
2851         gboolean from_plt = method == NULL;
2852         MonoMemPool *mp;
2853         int i, pindex, n_patches, used_strings;
2854         gboolean keep_patches = TRUE;
2855         guint8 *p;
2856         MonoJitInfo *jinfo = NULL;
2857         guint8 *code, *info;
2858
2859         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
2860                 return NULL;
2861
2862         if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
2863                 /* Non shared AOT code can't be used in other appdomains */
2864                 return NULL;
2865
2866         if (amodule->out_of_date)
2867                 return NULL;
2868
2869         if (amodule->code_offsets [method_index] == 0xffffffff) {
2870                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2871                         char *full_name;
2872
2873                         if (!method)
2874                                 method = mono_get_method (image, token, NULL);
2875                         full_name = mono_method_full_name (method, TRUE);
2876                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
2877                         g_free (full_name);
2878                 }
2879                 return NULL;
2880         }
2881
2882         code = &amodule->code [amodule->code_offsets [method_index]];
2883
2884         info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
2885
2886         if (amodule->thumb_end && code < amodule->thumb_end) {
2887                 /* Convert this into a thumb address */
2888                 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
2889                 code = &amodule->code [amodule->code_offsets [method_index] + 1];
2890         }
2891
2892         mono_aot_lock ();
2893         if (!amodule->methods_loaded)
2894                 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
2895         mono_aot_unlock ();
2896
2897         if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
2898                 return code;
2899
2900         if (mono_last_aot_method != -1) {
2901                 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
2902                                 return NULL;
2903                 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
2904                         if (!method)
2905                                 method = mono_get_method (image, token, NULL);
2906                         if (method) {
2907                                 char *name = mono_method_full_name (method, TRUE);
2908                                 printf ("LAST AOT METHOD: %s.\n", name);
2909                                 g_free (name);
2910                         } else {
2911                                 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
2912                         }
2913                 }
2914         }
2915
2916         p = info;
2917
2918         if (method) {
2919                 klass = method->klass;
2920                 decode_klass_ref (amodule, p, &p);
2921         } else {
2922                 klass = decode_klass_ref (amodule, p, &p);
2923         }
2924
2925         if (amodule->info.opts & MONO_OPT_SHARED)
2926                 used_strings = decode_value (p, &p);
2927         else
2928                 used_strings = 0;
2929
2930         for (i = 0; i < used_strings; i++) {
2931                 guint token = decode_value (p, &p);
2932                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
2933         }
2934
2935         if (amodule->info.opts & MONO_OPT_SHARED)       
2936                 keep_patches = FALSE;
2937
2938         n_patches = decode_value (p, &p);
2939
2940         keep_patches = FALSE;
2941
2942         if (n_patches) {
2943                 MonoJumpInfo *patches;
2944                 guint32 *got_slots;
2945
2946                 if (keep_patches)
2947                         mp = domain->mp;
2948                 else
2949                         mp = mono_mempool_new ();
2950
2951                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
2952                 if (patches == NULL)
2953                         goto cleanup;
2954
2955                 for (pindex = 0; pindex < n_patches; ++pindex) {
2956                         MonoJumpInfo *ji = &patches [pindex];
2957
2958                         if (!amodule->got [got_slots [pindex]]) {
2959                                 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
2960                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2961                                         amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
2962                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
2963                                         register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
2964                         }
2965                         ji->type = MONO_PATCH_INFO_NONE;
2966                 }
2967
2968                 g_free (got_slots);
2969
2970                 if (!keep_patches)
2971                         mono_mempool_destroy (mp);
2972         }
2973
2974         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
2975                 char *full_name;
2976
2977                 if (!method)
2978                         method = mono_get_method (image, token, NULL);
2979
2980                 full_name = mono_method_full_name (method, TRUE);
2981
2982                 if (!jinfo)
2983                         jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
2984
2985                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]\n", full_name, code, code + jinfo->code_size, info);
2986                 g_free (full_name);
2987         }
2988
2989         mono_aot_lock ();
2990
2991         InterlockedIncrement (&mono_jit_stats.methods_aot);
2992
2993         amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
2994
2995         init_plt (amodule);
2996
2997         if (method && method->wrapper_type)
2998                 g_hash_table_insert (amodule->method_to_code, method, code);
2999
3000         mono_aot_unlock ();
3001
3002         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3003                 MonoJitInfo *jinfo;
3004
3005                 if (!method) {
3006                         method = mono_get_method (image, token, NULL);
3007                         g_assert (method);
3008                 }
3009                 mono_profiler_method_jit (method);
3010                 jinfo = mono_jit_info_table_find (domain, (char*)code);
3011                 g_assert (jinfo);
3012                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3013         }
3014
3015         if (from_plt && klass && !klass->generic_container)
3016                 mono_runtime_class_init (mono_class_vtable (domain, klass));
3017
3018         return code;
3019
3020  cleanup:
3021         /* FIXME: The space in domain->mp is wasted */  
3022         if (amodule->info.opts & MONO_OPT_SHARED)
3023                 /* No need to cache patches */
3024                 mono_mempool_destroy (mp);
3025
3026         if (jinfo)
3027                 g_free (jinfo);
3028
3029         return NULL;
3030 }
3031
3032 static guint32
3033 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, const char *name)
3034 {
3035         guint32 table_size, entry_size, hash;
3036         guint32 *table, *entry;
3037         guint32 index;
3038         static guint32 n_extra_decodes;
3039
3040         if (!amodule || amodule->out_of_date)
3041                 return 0xffffff;
3042
3043         table_size = amodule->extra_method_table [0];
3044         table = amodule->extra_method_table + 1;
3045         entry_size = 3;
3046
3047         hash = mono_aot_method_hash (method) % table_size;
3048
3049         entry = &table [hash * entry_size];
3050
3051         if (entry [0] == 0)
3052                 return 0xffffff;
3053
3054         index = 0xffffff;
3055         while (TRUE) {
3056                 guint32 key = entry [0];
3057                 guint32 value = entry [1];
3058                 guint32 next = entry [entry_size - 1];
3059                 MonoMethod *m;
3060                 guint8 *p, *orig_p;
3061
3062                 p = amodule->blob + key;
3063                 orig_p = p;
3064
3065                 mono_aot_lock ();
3066                 if (!amodule->method_ref_to_method)
3067                         amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3068                 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3069                 mono_aot_unlock ();
3070                 if (!m) {
3071                         m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3072                         if (m) {
3073                                 mono_aot_lock ();
3074                                 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3075                                 mono_aot_unlock ();
3076                         }
3077                 }
3078                 if (m == method) {
3079                         index = value;
3080                         break;
3081                 }
3082
3083                 /* Special case: wrappers of shared generic methods */
3084                 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3085                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3086                         MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3087                         MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3088
3089                         if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3090                                 index = value;
3091                                 break;
3092                         }
3093                 }
3094
3095                 /* Methods decoded needlessly */
3096                 if (m) {
3097                         //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3098                         n_extra_decodes ++;
3099                 }
3100
3101                 if (next != 0)
3102                         entry = &table [next * entry_size];
3103                 else
3104                         break;
3105         }
3106
3107         return index;
3108 }
3109
3110 static void
3111 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3112 {
3113         g_ptr_array_add ((GPtrArray*)user_data, value);
3114 }
3115
3116 /*
3117  * find_extra_method:
3118  *
3119  *   Try finding METHOD in the extra_method table in all AOT images.
3120  * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3121  * module where the method was found.
3122  */
3123 static guint32
3124 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3125 {
3126         guint32 index;
3127         GPtrArray *modules;
3128         int i;
3129         char *name = NULL;
3130
3131         if (method->wrapper_type)
3132                 name = mono_aot_wrapper_name (method);
3133
3134         /* Try the method's module first */
3135         *out_amodule = method->klass->image->aot_module;
3136         index = find_extra_method_in_amodule (method->klass->image->aot_module, method, name);
3137         if (index != 0xffffff) {
3138                 g_free (name);
3139                 return index;
3140         }
3141
3142         /* 
3143          * Try all other modules.
3144          * This is needed because generic instances klass->image points to the image
3145          * containing the generic definition, but the native code is generated to the
3146          * AOT image which contains the reference.
3147          */
3148
3149         /* Make a copy to avoid doing the search inside the aot lock */
3150         modules = g_ptr_array_new ();
3151         mono_aot_lock ();
3152         g_hash_table_foreach (aot_modules, add_module_cb, modules);
3153         mono_aot_unlock ();
3154
3155         index = 0xffffff;
3156         for (i = 0; i < modules->len; ++i) {
3157                 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3158
3159                 if (amodule != method->klass->image->aot_module)
3160                         index = find_extra_method_in_amodule (amodule, method, name);
3161                 if (index != 0xffffff) {
3162                         *out_amodule = amodule;
3163                         break;
3164                 }
3165         }
3166         
3167         g_ptr_array_free (modules, TRUE);
3168
3169         g_free (name);
3170         return index;
3171 }
3172
3173 /*
3174  * mono_aot_get_method:
3175  *
3176  *   Return a pointer to the AOTed native code for METHOD if it can be found,
3177  * NULL otherwise.
3178  * On platforms with function pointers, this doesn't return a function pointer.
3179  */
3180 gpointer
3181 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3182 {
3183         MonoClass *klass = method->klass;
3184         guint32 method_index;
3185         MonoAotModule *amodule = klass->image->aot_module;
3186         guint8 *code;
3187
3188         if (!amodule)
3189                 return NULL;
3190
3191         if (amodule->out_of_date)
3192                 return NULL;
3193
3194         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3195                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3196                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3197                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3198                 return NULL;
3199
3200         /*
3201          * Use the original method instead of its invoke-with-check wrapper.
3202          * This is not a problem when using full-aot, since it doesn't support
3203          * remoting.
3204          */
3205         if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3206                 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3207
3208         g_assert (klass->inited);
3209
3210         /* Find method index */
3211         if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
3212                 /* 
3213                  * For generic methods, we store the fully shared instance in place of the
3214                  * original method.
3215                  */
3216                 method = mono_method_get_declaring_generic_method (method);
3217                 method_index = mono_metadata_token_index (method->token) - 1;
3218         } else if (method->is_inflated || !method->token) {
3219                 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3220                 mono_aot_lock ();
3221                 code = g_hash_table_lookup (amodule->method_to_code, method);
3222                 mono_aot_unlock ();
3223                 if (code)
3224                         return code;
3225
3226                 method_index = find_extra_method (method, &amodule);
3227                 /*
3228                  * Special case the ICollection<T> wrappers for arrays, as they cannot
3229                  * be statically enumerated, and each wrapper ends up calling the same
3230                  * method in Array.
3231                  */
3232                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3233                         MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3234
3235                         code = mono_aot_get_method (domain, m);
3236                         if (code) {
3237                                 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
3238                                         code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
3239                                         /* The call above returns an ftnptr */
3240                                         code = mono_get_addr_from_ftnptr (code);
3241                                 }
3242
3243                                 return code;
3244                         }
3245                 }
3246
3247                 /*
3248                  * Special case Array.GetGenericValueImpl which is a generic icall.
3249                  * Generic sharing currently can't handle it, but the icall returns data using
3250                  * an out parameter, so the managed-to-native wrappers can share the same code.
3251                  */
3252                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3253                         MonoMethod *m;
3254                         MonoGenericContext ctx;
3255                         MonoType *args [16];
3256
3257                         if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3258                                 /* Avoid recursion */
3259                                 return NULL;
3260
3261                         m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3262                         g_assert (m);
3263
3264                         memset (&ctx, 0, sizeof (ctx));
3265                         args [0] = &mono_defaults.object_class->byval_arg;
3266                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3267
3268                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3269
3270                         /* 
3271                          * Get the code for the <object> instantiation which should be emitted into
3272                          * the mscorlib aot image by the AOT compiler.
3273                          */
3274                         code = mono_aot_get_method (domain, m);
3275                         if (code)
3276                                 return code;
3277                 }
3278
3279                 /* Same for CompareExchange<T> and Exchange<T> */
3280                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && !strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && (!strcmp (method->name, "CompareExchange") || !strcmp (method->name, "Exchange")) && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1])) {
3281                         MonoMethod *m;
3282                         MonoGenericContext ctx;
3283                         MonoType *args [16];
3284                         gpointer iter = NULL;
3285
3286                         while ((m = mono_class_get_methods (method->klass, &iter))) {
3287                                 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3288                                         break;
3289                         }
3290                         g_assert (m);
3291
3292                         memset (&ctx, 0, sizeof (ctx));
3293                         args [0] = &mono_defaults.object_class->byval_arg;
3294                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3295
3296                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3297
3298                         /* Avoid recursion */
3299                         if (method == m)
3300                                 return NULL;
3301
3302                         /* 
3303                          * Get the code for the <object> instantiation which should be emitted into
3304                          * the mscorlib aot image by the AOT compiler.
3305                          */
3306                         code = mono_aot_get_method (domain, m);
3307                         if (code)
3308                                 return code;
3309                 }
3310
3311                 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
3312                         /* Partial sharing */
3313                         method_index = find_extra_method (mini_get_shared_method (method), &amodule);
3314                 }
3315
3316                 if (method_index == 0xffffff) {
3317                         if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3318                                 char *full_name;
3319
3320                                 full_name = mono_method_full_name (method, TRUE);
3321                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
3322                                 g_free (full_name);
3323                         }
3324                         return NULL;
3325                 }
3326
3327                 if (method_index == 0xffffff)
3328                         return NULL;
3329
3330                 /* Needed by find_jit_info */
3331                 mono_aot_lock ();
3332                 if (!amodule->extra_methods)
3333                         amodule->extra_methods = g_hash_table_new (NULL, NULL);
3334                 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3335                 mono_aot_unlock ();
3336         } else {
3337                 /* Common case */
3338                 method_index = mono_metadata_token_index (method->token) - 1;
3339         }
3340
3341         return load_method (domain, amodule, klass->image, method, method->token, method_index);
3342 }
3343
3344 /**
3345  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3346  * method.
3347  */
3348 gpointer
3349 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3350 {
3351         MonoAotModule *aot_module = image->aot_module;
3352         int method_index;
3353
3354         if (!aot_module)
3355                 return NULL;
3356
3357         method_index = mono_metadata_token_index (token) - 1;
3358
3359         return load_method (domain, aot_module, image, NULL, token, method_index);
3360 }
3361
3362 typedef struct {
3363         guint8 *addr;
3364         gboolean res;
3365 } IsGotEntryUserData;
3366
3367 static void
3368 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3369 {
3370         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3371         MonoAotModule *aot_module = (MonoAotModule*)value;
3372
3373         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3374                 data->res = TRUE;
3375 }
3376
3377 gboolean
3378 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3379 {
3380         IsGotEntryUserData user_data;
3381
3382         if (!aot_modules)
3383                 return FALSE;
3384
3385         user_data.addr = addr;
3386         user_data.res = FALSE;
3387         mono_aot_lock ();
3388         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3389         mono_aot_unlock ();
3390         
3391         return user_data.res;
3392 }
3393
3394 typedef struct {
3395         guint8 *addr;
3396         MonoAotModule *module;
3397 } FindAotModuleUserData;
3398
3399 static void
3400 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3401 {
3402         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3403         MonoAotModule *aot_module = (MonoAotModule*)value;
3404
3405         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3406                 data->module = aot_module;
3407 }
3408
3409 static inline MonoAotModule*
3410 find_aot_module (guint8 *code)
3411 {
3412         FindAotModuleUserData user_data;
3413
3414         if (!aot_modules)
3415                 return NULL;
3416
3417         /* Reading these need no locking */
3418         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3419                 return NULL;
3420
3421         user_data.addr = code;
3422         user_data.module = NULL;
3423                 
3424         mono_aot_lock ();
3425         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3426         mono_aot_unlock ();
3427         
3428         return user_data.module;
3429 }
3430
3431 void
3432 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3433 {
3434         /*
3435          * Since AOT code is only used in the root domain, 
3436          * mono_domain_get () != mono_get_root_domain () means the calling method
3437          * is AppDomain:InvokeInDomain, so this is the same check as in 
3438          * mono_method_same_domain () but without loading the metadata for the method.
3439          */
3440         if (mono_domain_get () == mono_get_root_domain ())
3441                 mono_arch_patch_plt_entry (code, got, regs, addr);
3442 }
3443
3444 /*
3445  * mono_aot_plt_resolve:
3446  *
3447  *   This function is called by the entries in the PLT to resolve the actual method that
3448  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3449  * Returns NULL if the something cannot be loaded.
3450  */
3451 gpointer
3452 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3453 {
3454 #ifdef MONO_ARCH_AOT_SUPPORTED
3455         guint8 *p, *target, *plt_entry;
3456         MonoJumpInfo ji;
3457         MonoAotModule *module = (MonoAotModule*)aot_module;
3458         gboolean res, no_ftnptr = FALSE;
3459         MonoMemPool *mp;
3460
3461         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3462
3463         p = &module->blob [plt_info_offset];
3464
3465         ji.type = decode_value (p, &p);
3466
3467         mp = mono_mempool_new_size (512);
3468         res = decode_patch (module, mp, &ji, p, &p);
3469
3470         if (!res) {
3471                 mono_mempool_destroy (mp);
3472                 return NULL;
3473         }
3474
3475         /* 
3476          * Avoid calling resolve_patch_target in the full-aot case if possible, since
3477          * it would create a trampoline, and we don't need that.
3478          * We could do this only if the method does not need the special handling
3479          * in mono_magic_trampoline ().
3480          */
3481         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) &&
3482                 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE)) {
3483                 target = mono_jit_compile_method (ji.data.method);
3484                 no_ftnptr = TRUE;
3485         } else {
3486                 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3487         }
3488
3489         /*
3490          * The trampoline expects us to return a function descriptor on platforms which use
3491          * it, but resolve_patch_target returns a direct function pointer for some type of
3492          * patches, so have to translate between the two.
3493          * FIXME: Clean this up, but how ?
3494          */
3495         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) {
3496                 /* These should already have a function descriptor */
3497 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3498                 /* Our function descriptors have a 0 environment, gcc created ones don't */
3499                 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3500                         g_assert (((gpointer*)target) [2] == 0);
3501 #endif
3502                 /* Empty */
3503         } else if (!no_ftnptr) {
3504 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3505                 g_assert (((gpointer*)target) [2] != 0);
3506 #endif
3507                 target = mono_create_ftnptr (mono_domain_get (), target);
3508         }
3509
3510         mono_mempool_destroy (mp);
3511
3512         /* Patch the PLT entry with target which might be the actual method not a trampoline */
3513         plt_entry = mono_aot_get_plt_entry (code);
3514         g_assert (plt_entry);
3515         mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3516
3517         return target;
3518 #else
3519         g_assert_not_reached ();
3520         return NULL;
3521 #endif
3522 }
3523
3524 /**
3525  * init_plt:
3526  *
3527  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
3528  * method in the module is loaded to avoid committing memory by writing to it.
3529  * LOCKING: Assumes the AOT lock is held.
3530  */
3531 static void
3532 init_plt (MonoAotModule *amodule)
3533 {
3534         int i;
3535         gpointer tramp;
3536
3537         if (amodule->plt_inited)
3538                 return;
3539
3540         tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3541
3542         /*
3543          * Initialize the PLT entries in the GOT to point to the default targets.
3544          */
3545
3546         tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3547          for (i = 1; i < amodule->info.plt_size; ++i)
3548                  /* All the default entries point to the AOT trampoline */
3549                  ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3550
3551         amodule->plt_inited = TRUE;
3552 }
3553
3554 /*
3555  * mono_aot_get_plt_entry:
3556  *
3557  *   Return the address of the PLT entry called by the code at CODE if exists.
3558  */
3559 guint8*
3560 mono_aot_get_plt_entry (guint8 *code)
3561 {
3562         MonoAotModule *amodule = find_aot_module (code);
3563         guint8 *target = NULL;
3564
3565         if (!amodule)
3566                 return NULL;
3567
3568 #ifdef TARGET_ARM
3569         if (amodule->thumb_end && code < amodule->thumb_end) {
3570                 return mono_arm_get_thumb_plt_entry (code);
3571         }
3572 #endif
3573
3574 #ifdef MONO_ARCH_AOT_SUPPORTED
3575         target = mono_arch_get_call_target (code);
3576 #else
3577         g_assert_not_reached ();
3578 #endif
3579
3580         if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3581                 return target;
3582         else
3583                 return NULL;
3584 }
3585
3586 /*
3587  * mono_aot_get_plt_info_offset:
3588  *
3589  *   Return the PLT info offset belonging to the plt entry called by CODE.
3590  */
3591 guint32
3592 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3593 {
3594         guint8 *plt_entry = mono_aot_get_plt_entry (code);
3595
3596         g_assert (plt_entry);
3597
3598         /* The offset is embedded inside the code after the plt entry */
3599 #ifdef MONO_ARCH_AOT_SUPPORTED
3600         return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3601 #else
3602         g_assert_not_reached ();
3603         return 0;
3604 #endif
3605 }
3606
3607 static gpointer
3608 mono_create_ftnptr_malloc (guint8 *code)
3609 {
3610 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3611         MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3612
3613         ftnptr->code = code;
3614         ftnptr->toc = NULL;
3615         ftnptr->env = NULL;
3616
3617         return ftnptr;
3618 #else
3619         return code;
3620 #endif
3621 }
3622
3623 /*
3624  * mono_aot_register_jit_icall:
3625  *
3626  *   Register a JIT icall which is called by trampolines in full-aot mode. This should
3627  * be called from mono_arch_init () during startup.
3628  */
3629 void
3630 mono_aot_register_jit_icall (const char *name, gpointer addr)
3631 {
3632         /* No need for locking */
3633         if (!aot_jit_icall_hash)
3634                 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3635         g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3636 }
3637
3638 /*
3639  * load_function:
3640  *
3641  *   Load the function named NAME from the aot image. 
3642  */
3643 static gpointer
3644 load_function (MonoAotModule *amodule, const char *name)
3645 {
3646         char *symbol;
3647         guint8 *p;
3648         int n_patches, pindex;
3649         MonoMemPool *mp;
3650         gpointer code;
3651
3652         /* Load the code */
3653
3654         symbol = g_strdup_printf ("%s", name);
3655         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3656         g_free (symbol);
3657         if (!code)
3658                 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3659
3660         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.\n", name, amodule->aot_name);
3661
3662         /* Load info */
3663
3664         symbol = g_strdup_printf ("%s_p", name);
3665         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3666         g_free (symbol);
3667         if (!p)
3668                 /* Nothing to patch */
3669                 return code;
3670
3671         p = amodule->blob + *(guint32*)p;
3672
3673         /* Similar to mono_aot_load_method () */
3674
3675         n_patches = decode_value (p, &p);
3676
3677         if (n_patches) {
3678                 MonoJumpInfo *patches;
3679                 guint32 *got_slots;
3680
3681                 mp = mono_mempool_new ();
3682
3683                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3684                 g_assert (patches);
3685
3686                 for (pindex = 0; pindex < n_patches; ++pindex) {
3687                         MonoJumpInfo *ji = &patches [pindex];
3688                         gpointer target;
3689
3690                         if (amodule->got [got_slots [pindex]])
3691                                 continue;
3692
3693                         /*
3694                          * When this code is executed, the runtime may not be initalized yet, so
3695                          * resolve the patch info by hand.
3696                          */
3697                         if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3698                                 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3699                                         target = mono_get_lmf_addr;
3700                                 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3701                                         target = mono_thread_force_interruption_checkpoint;
3702                                 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3703                                         target = mono_exception_from_token;
3704                                 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3705                                         target = mono_get_throw_exception ();
3706                                 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3707                                         int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3708                                         target = (gpointer)mono_get_trampoline_func (tramp_type2);
3709                                 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3710                                         /* atoll is needed because the the offset is unsigned */
3711                                         guint32 slot;
3712                                         int res;
3713
3714                                         res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3715                                         g_assert (res == 1);
3716                                         target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3717                                         target = mono_create_ftnptr_malloc (target);
3718                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3719                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3720                                         target = mono_create_ftnptr_malloc (target);
3721                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3722                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3723                                         target = mono_create_ftnptr_malloc (target);
3724                                 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3725                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3726                                         target = mono_create_ftnptr_malloc (target);
3727                                 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3728                                         target = mono_thread_get_and_clear_pending_exception;
3729                                 } else if (strstr (ji->data.name, "generic_trampoline_")) {
3730                                         target = mono_aot_get_trampoline (ji->data.name);
3731                                 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3732                                         /* Registered by mono_arch_init () */
3733                                         target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3734                                 } else {
3735                                         fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3736                                         g_assert_not_reached ();
3737                                         target = NULL;
3738                                 }
3739                         } else {
3740                                 /* Hopefully the code doesn't have patches which need method or 
3741                                  * domain to be set.
3742                                  */
3743                                 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
3744                                 g_assert (target);
3745                         }
3746
3747                         amodule->got [got_slots [pindex]] = target;
3748                 }
3749
3750                 g_free (got_slots);
3751
3752                 mono_mempool_destroy (mp);
3753         }
3754
3755         return code;
3756 }
3757
3758 /*
3759  * Return the trampoline identified by NAME from the mscorlib AOT file.
3760  * On ppc64, this returns a function descriptor.
3761  */
3762 gpointer
3763 mono_aot_get_trampoline (const char *name)
3764 {
3765         MonoImage *image;
3766         MonoAotModule *amodule;
3767
3768         image = mono_defaults.corlib;
3769         g_assert (image);
3770
3771         amodule = image->aot_module;
3772         g_assert (amodule);
3773
3774         return mono_create_ftnptr_malloc (load_function (amodule, name));
3775 }
3776
3777 /* Return a given kind of trampoline */
3778 static gpointer
3779 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
3780 {
3781         MonoAotModule *amodule;
3782         int index, tramp_size;
3783         MonoImage *image;
3784
3785         /* Currently, we keep all trampolines in the mscorlib AOT image */
3786         image = mono_defaults.corlib;
3787         g_assert (image);
3788
3789         mono_aot_lock ();
3790
3791         amodule = image->aot_module;
3792         g_assert (amodule);
3793
3794         *out_amodule = amodule;
3795
3796         if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type])
3797                 g_error ("Ran out of trampolines of type %d in '%s' (%d)\n", tramp_type, image->name, amodule->info.num_trampolines [tramp_type]);
3798
3799         index = amodule->trampoline_index [tramp_type] ++;
3800
3801         mono_aot_unlock ();
3802
3803         *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
3804
3805         tramp_size = amodule->info.trampoline_size [tramp_type];
3806
3807         if (out_tramp_size)
3808                 *out_tramp_size = tramp_size;
3809
3810         return amodule->trampolines [tramp_type] + (index * tramp_size);
3811 }
3812
3813 /*
3814  * Return a specific trampoline from the AOT file.
3815  */
3816 gpointer
3817 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
3818 {
3819         MonoAotModule *amodule;
3820         guint32 got_offset, tramp_size;
3821         guint8 *code, *tramp;
3822         static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
3823         static gboolean inited;
3824         static guint32 num_trampolines;
3825
3826         if (!inited) {
3827                 mono_aot_lock ();
3828
3829                 if (!inited) {
3830                         mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
3831                         inited = TRUE;
3832                 }
3833
3834                 mono_aot_unlock ();
3835         }
3836
3837         num_trampolines ++;
3838
3839         if (!generic_trampolines [tramp_type]) {
3840                 char *symbol;
3841
3842                 symbol = mono_get_generic_trampoline_name (tramp_type);
3843                 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
3844                 g_free (symbol);
3845         }
3846
3847         tramp = generic_trampolines [tramp_type];
3848         g_assert (tramp);
3849
3850         code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
3851
3852         amodule->got [got_offset] = tramp;
3853         amodule->got [got_offset + 1] = arg1;
3854
3855         if (code_len)
3856                 *code_len = tramp_size;
3857
3858         return code;
3859 }
3860
3861 gpointer
3862 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
3863 {
3864         MonoAotModule *amodule;
3865         guint8 *code;
3866         guint32 got_offset;
3867
3868         code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
3869
3870         amodule->got [got_offset] = ctx;
3871         amodule->got [got_offset + 1] = addr; 
3872
3873         /* The caller expects an ftnptr */
3874         return mono_create_ftnptr (mono_domain_get (), code);
3875 }
3876
3877 gpointer
3878 mono_aot_get_unbox_trampoline (MonoMethod *method)
3879 {
3880         guint32 method_index = mono_metadata_token_index (method->token) - 1;
3881         MonoAotModule *amodule;
3882         gpointer code;
3883         guint32 *ut, *ut_end, *entry;
3884         int low, high, entry_index;
3885
3886         if (method->is_inflated && !mono_method_is_generic_sharable_impl (method, FALSE)) {
3887                 method_index = find_extra_method (method, &amodule);
3888                 g_assert (method_index != 0xffffff);
3889         } else {
3890                 amodule = method->klass->image->aot_module;
3891                 g_assert (amodule);
3892         }
3893
3894         ut = amodule->unbox_trampolines;
3895         ut_end = amodule->unbox_trampolines_end;
3896
3897         /* Do a binary search in the sorted table */
3898         code = NULL;
3899         low = 0;
3900         high = (ut_end - ut) / 2;
3901         while (low < high) {
3902                 entry_index = (low + high) / 2;
3903                 entry = &ut [(entry_index * 2)];
3904                 if (entry [0] < method_index) {
3905                         low = entry_index + 1;
3906                 } else if (entry [0] > method_index) {
3907                         high = entry_index;
3908                 } else {
3909                         code = amodule->code + entry [1];
3910                         break;
3911                 }
3912         }
3913         g_assert (code);
3914
3915         /* The caller expects an ftnptr */
3916         return mono_create_ftnptr (mono_domain_get (), code);
3917 }
3918
3919 gpointer
3920 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
3921 {
3922         char *symbol;
3923         gpointer code;
3924
3925         symbol = mono_get_rgctx_fetch_trampoline_name (slot);
3926         code = load_function (mono_defaults.corlib->aot_module, symbol);
3927         g_free (symbol);
3928         /* The caller expects an ftnptr */
3929         return mono_create_ftnptr (mono_domain_get (), code);
3930 }
3931
3932 gpointer
3933 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
3934 {
3935         guint32 got_offset;
3936         gpointer code;
3937         gpointer *buf;
3938         int i, index, real_count;
3939         MonoAotModule *amodule;
3940
3941         code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
3942
3943         real_count = 0;
3944         for (i = 0; i < count; ++i) {
3945                 MonoIMTCheckItem *item = imt_entries [i];
3946
3947                 if (item->is_equals)
3948                         real_count ++;
3949         }
3950
3951         /* Save the entries into an array */
3952         buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
3953         index = 0;
3954         for (i = 0; i < count; ++i) {
3955                 MonoIMTCheckItem *item = imt_entries [i];               
3956
3957                 if (!item->is_equals)
3958                         continue;
3959
3960                 g_assert (item->key);
3961
3962                 buf [(index * 2)] = item->key;
3963                 if (item->has_target_code) {
3964                         gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
3965                         *p = item->value.target_code;
3966                         buf [(index * 2) + 1] = p;
3967                 } else {
3968                         buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
3969                 }
3970                 index ++;
3971         }
3972         buf [(index * 2)] = NULL;
3973         buf [(index * 2) + 1] = fail_tramp;
3974         
3975         amodule->got [got_offset] = buf;
3976
3977         return code;
3978 }
3979  
3980 /*
3981  * mono_aot_set_make_unreadable:
3982  *
3983  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
3984  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
3985  */
3986 void
3987 mono_aot_set_make_unreadable (gboolean unreadable)
3988 {
3989         static int inited;
3990
3991         make_unreadable = unreadable;
3992
3993         if (make_unreadable && !inited) {
3994                 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
3995         }               
3996 }
3997
3998 typedef struct {
3999         MonoAotModule *module;
4000         guint8 *ptr;
4001 } FindMapUserData;
4002
4003 static void
4004 find_map (gpointer key, gpointer value, gpointer user_data)
4005 {
4006         MonoAotModule *module = (MonoAotModule*)value;
4007         FindMapUserData *data = (FindMapUserData*)user_data;
4008
4009         if (!data->module)
4010                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4011                         data->module = module;
4012 }
4013
4014 static MonoAotModule*
4015 find_module_for_addr (void *ptr)
4016 {
4017         FindMapUserData data;
4018
4019         if (!make_unreadable)
4020                 return NULL;
4021
4022         data.module = NULL;
4023         data.ptr = (guint8*)ptr;
4024
4025         mono_aot_lock ();
4026         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4027         mono_aot_unlock ();
4028
4029         return data.module;
4030 }
4031
4032 /*
4033  * mono_aot_is_pagefault:
4034  *
4035  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4036  * within memory allocated by this module.
4037  */
4038 gboolean
4039 mono_aot_is_pagefault (void *ptr)
4040 {
4041         if (!make_unreadable)
4042                 return FALSE;
4043
4044         /* 
4045          * Not signal safe, but SIGSEGV's are synchronous, and
4046          * this is only turned on by a MONO_DEBUG option.
4047          */
4048         return find_module_for_addr (ptr) != NULL;
4049 }
4050
4051 /*
4052  * mono_aot_handle_pagefault:
4053  *
4054  *   Handle a pagefault caused by an unreadable page by making it readable again.
4055  */
4056 void
4057 mono_aot_handle_pagefault (void *ptr)
4058 {
4059 #ifndef PLATFORM_WIN32
4060         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
4061         int res;
4062
4063         mono_aot_lock ();
4064         res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
4065         g_assert (res == 0);
4066
4067         n_pagefaults ++;
4068         mono_aot_unlock ();
4069 #endif
4070 }
4071
4072 #else
4073 /* AOT disabled */
4074
4075 void
4076 mono_aot_init (void)
4077 {
4078 }
4079
4080 gpointer
4081 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
4082 {
4083         return NULL;
4084 }
4085
4086 gboolean
4087 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4088 {
4089         return FALSE;
4090 }
4091
4092 gboolean
4093 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4094 {
4095         return FALSE;
4096 }
4097
4098 gboolean
4099 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
4100 {
4101         return FALSE;
4102 }
4103
4104 MonoJitInfo *
4105 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
4106 {
4107         return NULL;
4108 }
4109
4110 gpointer
4111 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
4112 {
4113         return NULL;
4114 }
4115
4116 guint8*
4117 mono_aot_get_plt_entry (guint8 *code)
4118 {
4119         return NULL;
4120 }
4121
4122 gpointer
4123 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4124 {
4125         return NULL;
4126 }
4127
4128 void
4129 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
4130 {
4131 }
4132
4133 gpointer
4134 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
4135 {
4136         return NULL;
4137 }
4138
4139 guint32
4140 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4141 {
4142         g_assert_not_reached ();
4143
4144         return 0;
4145 }
4146
4147 gpointer
4148 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4149 {
4150         g_assert_not_reached ();
4151         return NULL;
4152 }
4153
4154 gpointer
4155 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4156 {
4157         g_assert_not_reached ();
4158         return NULL;
4159 }
4160
4161 gpointer
4162 mono_aot_get_trampoline (const char *name)
4163 {
4164         g_assert_not_reached ();
4165         return NULL;
4166 }
4167
4168 gpointer
4169 mono_aot_get_unbox_trampoline (MonoMethod *method)
4170 {
4171         g_assert_not_reached ();
4172         return NULL;
4173 }
4174
4175 gpointer
4176 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4177 {
4178         g_assert_not_reached ();
4179         return NULL;
4180 }
4181
4182 gpointer
4183 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4184 {
4185         g_assert_not_reached ();
4186         return NULL;
4187 }       
4188
4189 guint8*
4190 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
4191 {
4192         g_assert_not_reached ();
4193         return NULL;
4194 }
4195
4196 void
4197 mono_aot_register_jit_icall (const char *name, gpointer addr)
4198 {
4199 }
4200
4201 #endif