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