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