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