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