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