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