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