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