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