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