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