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