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