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