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