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