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