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