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