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