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