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