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