Implement partial generic methods
[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 static void
1495 load_aot_module (MonoAssembly *assembly, gpointer user_data)
1496 {
1497         char *aot_name;
1498         MonoAotModule *amodule;
1499         MonoDl *sofile;
1500         gboolean usable = TRUE;
1501         char *version_symbol = NULL;
1502         char *msg = NULL;
1503         gpointer *globals = NULL;
1504         MonoAotFileInfo *info = NULL;
1505         int i, version;
1506         guint8 *blob;
1507         gboolean do_load_image = TRUE;
1508
1509         if (mono_compile_aot)
1510                 return;
1511
1512         if (assembly->image->aot_module)
1513                 /* 
1514                  * Already loaded. This can happen because the assembly loading code might invoke
1515                  * the assembly load hooks multiple times for the same assembly.
1516                  */
1517                 return;
1518
1519         if (assembly->image->dynamic || assembly->ref_only)
1520                 return;
1521
1522         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
1523                 return;
1524
1525         mono_aot_lock ();
1526         if (static_aot_modules)
1527                 info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
1528         else
1529                 info = NULL;
1530         mono_aot_unlock ();
1531
1532         if (info) {
1533                 /* Statically linked AOT module */
1534                 sofile = NULL;
1535                 aot_name = g_strdup_printf ("%s", assembly->aname.name);
1536                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
1537                 globals = info->globals;
1538         } else {
1539                 if (use_aot_cache)
1540                         sofile = load_aot_module_from_cache (assembly, &aot_name);
1541                 else {
1542                         char *err;
1543                         aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
1544
1545                         sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
1546
1547                         if (!sofile) {
1548                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
1549                                 g_free (err);
1550                         }
1551                 }
1552         }
1553
1554         if (!sofile && !globals) {
1555                 if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
1556                         fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
1557                         exit (1);
1558                 }
1559                 g_free (aot_name);
1560                 return;
1561         }
1562
1563         if (!info) {
1564                 find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
1565                 find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
1566         }
1567
1568         if (version_symbol) {
1569                 /* Old file format */
1570                 version = atoi (version_symbol);
1571         } else {
1572                 g_assert (info);
1573                 version = info->version;
1574         }
1575
1576         if (version != MONO_AOT_FILE_VERSION) {
1577                 msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
1578                 usable = FALSE;
1579         } else {
1580                 usable = check_usable (assembly, info, &msg);
1581         }
1582
1583         if (!usable) {
1584                 if (mono_aot_only) {
1585                         fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
1586                         exit (1);
1587                 } else {
1588                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
1589                 }
1590                 g_free (msg);
1591                 g_free (aot_name);
1592                 if (sofile)
1593                         mono_dl_close (sofile);
1594                 assembly->image->aot_module = NULL;
1595                 return;
1596         }
1597
1598         /* Sanity check */
1599         g_assert (info->double_align == __alignof__ (double));
1600         g_assert (info->long_align == __alignof__ (gint64));
1601
1602         blob = info->blob;
1603
1604         amodule = g_new0 (MonoAotModule, 1);
1605         amodule->aot_name = aot_name;
1606         amodule->assembly = assembly;
1607
1608         memcpy (&amodule->info, info, sizeof (*info));
1609
1610         amodule->got = amodule->info.got;
1611         amodule->got [0] = assembly->image;
1612         amodule->globals = globals;
1613         amodule->sofile = sofile;
1614         amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
1615         amodule->blob = blob;
1616
1617         /* Read image table */
1618         {
1619                 guint32 table_len, i;
1620                 char *table = NULL;
1621
1622                 table = info->image_table;
1623                 g_assert (table);
1624
1625                 table_len = *(guint32*)table;
1626                 table += sizeof (guint32);
1627                 amodule->image_table = g_new0 (MonoImage*, table_len);
1628                 amodule->image_names = g_new0 (MonoAssemblyName, table_len);
1629                 amodule->image_guids = g_new0 (char*, table_len);
1630                 amodule->image_table_len = table_len;
1631                 for (i = 0; i < table_len; ++i) {
1632                         MonoAssemblyName *aname = &(amodule->image_names [i]);
1633
1634                         aname->name = g_strdup (table);
1635                         table += strlen (table) + 1;
1636                         amodule->image_guids [i] = g_strdup (table);
1637                         table += strlen (table) + 1;
1638                         if (table [0] != 0)
1639                                 aname->culture = g_strdup (table);
1640                         table += strlen (table) + 1;
1641                         memcpy (aname->public_key_token, table, strlen (table) + 1);
1642                         table += strlen (table) + 1;                    
1643
1644                         table = ALIGN_PTR_TO (table, 8);
1645                         aname->flags = *(guint32*)table;
1646                         table += 4;
1647                         aname->major = *(guint32*)table;
1648                         table += 4;
1649                         aname->minor = *(guint32*)table;
1650                         table += 4;
1651                         aname->build = *(guint32*)table;
1652                         table += 4;
1653                         aname->revision = *(guint32*)table;
1654                         table += 4;
1655                 }
1656         }
1657
1658         amodule->code_offsets = info->code_offsets;
1659 #ifdef MONOTOUCH
1660         amodule->method_addresses = info->method_addresses;
1661 #endif
1662         amodule->code = info->methods;
1663 #ifdef TARGET_ARM
1664         /* Mask out thumb interop bit */
1665         amodule->code = (void*)((mgreg_t)amodule->code & ~1);
1666 #endif
1667         amodule->code_end = info->methods_end;
1668         amodule->method_info_offsets = info->method_info_offsets;
1669         amodule->ex_info_offsets = info->ex_info_offsets;
1670         amodule->class_info_offsets = info->class_info_offsets;
1671         amodule->class_name_table = info->class_name_table;
1672         amodule->extra_method_table = info->extra_method_table;
1673         amodule->extra_method_info_offsets = info->extra_method_info_offsets;
1674         amodule->unbox_trampolines = info->unbox_trampolines;
1675         amodule->unbox_trampolines_end = info->unbox_trampolines_end;
1676         amodule->got_info_offsets = info->got_info_offsets;
1677         amodule->unwind_info = info->unwind_info;
1678         amodule->mem_end = info->mem_end;
1679         amodule->mem_begin = amodule->code;
1680         amodule->plt = info->plt;
1681         amodule->plt_end = info->plt_end;
1682         amodule->mono_eh_frame = info->mono_eh_frame;
1683         amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
1684         amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
1685         amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
1686         amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = info->gsharedvt_arg_trampolines;
1687         amodule->thumb_end = info->thumb_end;
1688
1689 #ifdef MONOTOUCH
1690         if (info->flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) {
1691                 /* Compute code_offsets from the method addresses */
1692                 amodule->code_offsets = g_malloc0 (amodule->info.nmethods * sizeof (gint32));
1693                 for (i = 0; i < amodule->info.nmethods; ++i) {
1694                         if (!amodule->method_addresses [i])
1695                                 amodule->code_offsets [i] = 0xffffffff;
1696                         else
1697                                 amodule->code_offsets [i] = (char*)amodule->method_addresses [i] - (char*)amodule->code;
1698                 }
1699         }
1700 #endif
1701
1702         if (make_unreadable) {
1703 #ifndef TARGET_WIN32
1704                 guint8 *addr;
1705                 guint8 *page_start, *page_end;
1706                 int err, len;
1707
1708                 addr = amodule->mem_begin;
1709                 len = amodule->mem_end - amodule->mem_begin;
1710
1711                 /* Round down in both directions to avoid modifying data which is not ours */
1712                 page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
1713                 page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
1714                 if (page_end > page_start) {
1715                         err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
1716                         g_assert (err == 0);
1717                 }
1718 #endif
1719         }
1720
1721         mono_aot_lock ();
1722
1723         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
1724         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);
1725
1726         g_hash_table_insert (aot_modules, assembly, amodule);
1727         mono_aot_unlock ();
1728
1729         mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);
1730
1731         assembly->image->aot_module = amodule;
1732
1733         if (mono_aot_only) {
1734                 char *code;
1735                 find_symbol (amodule->sofile, amodule->globals, "specific_trampolines_page", (gpointer *)&code);
1736                 amodule->use_page_trampolines = code != NULL;
1737                 /*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
1738                 if (mono_defaults.corlib) {
1739                         /* The second got slot contains the mscorlib got addr */
1740                         MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
1741
1742                         amodule->got [1] = mscorlib_amodule->got;
1743                 } else {
1744                         amodule->got [1] = amodule->got;
1745                 }
1746         }
1747
1748         if (mono_gc_is_moving ()) {
1749                 MonoJumpInfo ji;
1750
1751                 memset (&ji, 0, sizeof (ji));
1752                 ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
1753
1754                 amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
1755         }
1756
1757         /*
1758          * Since we store methoddef and classdef tokens when referring to methods/classes in
1759          * referenced assemblies, we depend on the exact versions of the referenced assemblies.
1760          * MS calls this 'hard binding'. This means we have to load all referenced assemblies
1761          * non-lazily, since we can't handle out-of-date errors later.
1762          * The cached class info also depends on the exact assemblies.
1763          */
1764 #if defined(__native_client__)
1765         /* TODO: Don't 'load_image' on mscorlib due to a */
1766         /* recursive loading problem.  This should be    */
1767         /* removed if mscorlib is loaded from disk.      */
1768         if (strncmp(assembly->aname.name, "mscorlib", 8)) {
1769                 do_load_image = TRUE;
1770         } else {
1771                 do_load_image = FALSE;
1772         }
1773 #endif
1774         if (do_load_image) {
1775                 for (i = 0; i < amodule->image_table_len; ++i)
1776                         load_image (amodule, i, FALSE);
1777         }
1778
1779         if (amodule->out_of_date) {
1780                 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);
1781                 if (mono_aot_only) {
1782                         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);
1783                         exit (1);
1784                 }
1785         }
1786         else
1787                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
1788 }
1789
1790 /*
1791  * mono_aot_register_globals:
1792  *
1793  *   This is called by the ctor function in AOT images compiled with the
1794  * 'no-dlsym' option.
1795  */
1796 void
1797 mono_aot_register_globals (gpointer *globals)
1798 {
1799         g_assert_not_reached ();
1800 }
1801
1802 /*
1803  * mono_aot_register_module:
1804  *
1805  *   This should be called by embedding code to register AOT modules statically linked
1806  * into the executable. AOT_INFO should be the value of the 
1807  * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
1808  */
1809 void
1810 mono_aot_register_module (gpointer *aot_info)
1811 {
1812         gpointer *globals;
1813         char *aname;
1814         MonoAotFileInfo *info = (gpointer)aot_info;
1815
1816         g_assert (info->version == MONO_AOT_FILE_VERSION);
1817
1818         globals = info->globals;
1819         g_assert (globals);
1820
1821         aname = info->assembly_name;
1822
1823         /* This could be called before startup */
1824         if (aot_modules)
1825                 mono_aot_lock ();
1826
1827         if (!static_aot_modules)
1828                 static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
1829
1830         g_hash_table_insert (static_aot_modules, aname, info);
1831
1832         if (aot_modules)
1833                 mono_aot_unlock ();
1834 }
1835
1836 void
1837 mono_aot_init (void)
1838 {
1839         InitializeCriticalSection (&aot_mutex);
1840         InitializeCriticalSection (&aot_page_mutex);
1841         aot_modules = g_hash_table_new (NULL, NULL);
1842
1843         mono_install_assembly_load_hook (load_aot_module, NULL);
1844
1845         if (g_getenv ("MONO_LASTAOT"))
1846                 mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
1847         if (g_getenv ("MONO_AOT_CACHE"))
1848                 use_aot_cache = TRUE;
1849 }
1850
1851 void
1852 mono_aot_cleanup (void)
1853 {
1854         if (aot_jit_icall_hash)
1855                 g_hash_table_destroy (aot_jit_icall_hash);
1856         if (aot_modules)
1857                 g_hash_table_destroy (aot_modules);
1858 }
1859
1860 static gboolean
1861 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
1862 {
1863         guint32 flags;
1864         MethodRef ref;
1865         gboolean res;
1866
1867         info->vtable_size = decode_value (buf, &buf);
1868         if (info->vtable_size == -1)
1869                 /* Generic type */
1870                 return FALSE;
1871         flags = decode_value (buf, &buf);
1872         info->ghcimpl = (flags >> 0) & 0x1;
1873         info->has_finalize = (flags >> 1) & 0x1;
1874         info->has_cctor = (flags >> 2) & 0x1;
1875         info->has_nested_classes = (flags >> 3) & 0x1;
1876         info->blittable = (flags >> 4) & 0x1;
1877         info->has_references = (flags >> 5) & 0x1;
1878         info->has_static_refs = (flags >> 6) & 0x1;
1879         info->no_special_static_fields = (flags >> 7) & 0x1;
1880         info->is_generic_container = (flags >> 8) & 0x1;
1881
1882         if (info->has_cctor) {
1883                 res = decode_method_ref (module, &ref, buf, &buf);
1884                 if (!res)
1885                         return FALSE;
1886                 info->cctor_token = ref.token;
1887         }
1888         if (info->has_finalize) {
1889                 res = decode_method_ref (module, &ref, buf, &buf);
1890                 if (!res)
1891                         return FALSE;
1892                 info->finalize_image = ref.image;
1893                 info->finalize_token = ref.token;
1894         }
1895
1896         info->instance_size = decode_value (buf, &buf);
1897         info->class_size = decode_value (buf, &buf);
1898         info->packing_size = decode_value (buf, &buf);
1899         info->min_align = decode_value (buf, &buf);
1900
1901         *endbuf = buf;
1902
1903         return TRUE;
1904 }       
1905
1906 gpointer
1907 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
1908 {
1909         int i;
1910         MonoClass *klass = vtable->klass;
1911         MonoAotModule *amodule = klass->image->aot_module;
1912         guint8 *info, *p;
1913         MonoCachedClassInfo class_info;
1914         gboolean err;
1915         MethodRef ref;
1916         gboolean res;
1917
1918         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
1919                 return NULL;
1920
1921         info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1922         p = info;
1923
1924         err = decode_cached_class_info (amodule, &class_info, p, &p);
1925         if (!err)
1926                 return NULL;
1927
1928         for (i = 0; i < slot; ++i)
1929                 decode_method_ref (amodule, &ref, p, &p);
1930
1931         res = decode_method_ref (amodule, &ref, p, &p);
1932         if (!res)
1933                 return NULL;
1934         if (ref.no_aot_trampoline)
1935                 return NULL;
1936
1937         if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
1938                 return NULL;
1939
1940         return mono_aot_get_method_from_token (domain, ref.image, ref.token);
1941 }
1942
1943 gboolean
1944 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1945 {
1946         MonoAotModule *amodule = klass->image->aot_module;
1947         guint8 *p;
1948         gboolean err;
1949
1950         if (klass->rank || !amodule)
1951                 return FALSE;
1952
1953         p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
1954
1955         err = decode_cached_class_info (amodule, res, p, &p);
1956         if (!err)
1957                 return FALSE;
1958
1959         return TRUE;
1960 }
1961
1962 /**
1963  * mono_aot_get_class_from_name:
1964  *
1965  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
1966  * using a cache stored in the AOT file.
1967  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
1968  *
1969  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
1970  * found.
1971  */
1972 gboolean
1973 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1974 {
1975         MonoAotModule *amodule = image->aot_module;
1976         guint16 *table, *entry;
1977         guint16 table_size;
1978         guint32 hash;
1979         char full_name_buf [1024];
1980         char *full_name;
1981         const char *name2, *name_space2;
1982         MonoTableInfo  *t;
1983         guint32 cols [MONO_TYPEDEF_SIZE];
1984         GHashTable *nspace_table;
1985
1986         if (!amodule || !amodule->class_name_table)
1987                 return FALSE;
1988
1989         mono_aot_lock ();
1990
1991         *klass = NULL;
1992
1993         /* First look in the cache */
1994         if (!amodule->name_cache)
1995                 amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
1996         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
1997         if (nspace_table) {
1998                 *klass = g_hash_table_lookup (nspace_table, name);
1999                 if (*klass) {
2000                         mono_aot_unlock ();
2001                         return TRUE;
2002                 }
2003         }
2004
2005         table_size = amodule->class_name_table [0];
2006         table = amodule->class_name_table + 1;
2007
2008         if (name_space [0] == '\0')
2009                 full_name = g_strdup_printf ("%s", name);
2010         else {
2011                 if (strlen (name_space) + strlen (name) < 1000) {
2012                         sprintf (full_name_buf, "%s.%s", name_space, name);
2013                         full_name = full_name_buf;
2014                 } else {
2015                         full_name = g_strdup_printf ("%s.%s", name_space, name);
2016                 }
2017         }
2018         hash = mono_metadata_str_hash (full_name) % table_size;
2019         if (full_name != full_name_buf)
2020                 g_free (full_name);
2021
2022         entry = &table [hash * 2];
2023
2024         if (entry [0] != 0) {
2025                 t = &image->tables [MONO_TABLE_TYPEDEF];
2026
2027                 while (TRUE) {
2028                         guint32 index = entry [0];
2029                         guint32 next = entry [1];
2030                         guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
2031
2032                         name_table_accesses ++;
2033
2034                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
2035
2036                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
2037                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
2038
2039                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
2040                                 mono_aot_unlock ();
2041                                 *klass = mono_class_get (image, token);
2042
2043                                 /* Add to cache */
2044                                 if (*klass) {
2045                                         mono_aot_lock ();
2046                                         nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
2047                                         if (!nspace_table) {
2048                                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
2049                                                 g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
2050                                         }
2051                                         g_hash_table_insert (nspace_table, (char*)name2, *klass);
2052                                         mono_aot_unlock ();
2053                                 }
2054                                 return TRUE;
2055                         }
2056
2057                         if (next != 0) {
2058                                 entry = &table [next * 2];
2059                         } else {
2060                                 break;
2061                         }
2062                 }
2063         }
2064
2065         mono_aot_unlock ();
2066         
2067         return TRUE;
2068 }
2069
2070 /*
2071  * decode_mono_eh_frame:
2072  *
2073  *   Decode the EH information emitted by our modified LLVM compiler and construct a
2074  * MonoJitInfo structure from it.
2075  * LOCKING: Acquires the domain lock.
2076  */
2077 static MonoJitInfo*
2078 decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, 
2079                                                    MonoMethod *method, guint8 *code, 
2080                                                    MonoJitExceptionInfo *clauses, int num_clauses,
2081                                                    int extra_size, GSList **nesting,
2082                                                    int *this_reg, int *this_offset)
2083 {
2084         guint8 *p;
2085         guint8 *fde, *cie, *code_start, *code_end;
2086         int version, fde_count;
2087         gint32 *table;
2088         int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
2089         MonoJitExceptionInfo *ei;
2090         guint32 fde_len, ei_len, nested_len, nindex;
2091         gpointer *type_info;
2092         MonoJitInfo *jinfo;
2093         MonoLLVMFDEInfo info;
2094
2095         g_assert (amodule->mono_eh_frame);
2096
2097         p = amodule->mono_eh_frame;
2098
2099         /* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
2100
2101         /* Header */
2102         version = *p;
2103         g_assert (version == 1 || version == 2);
2104         p ++;
2105         if (version == 2) {
2106                 func_encoding = *p;
2107                 p ++;
2108         } else {
2109                 func_encoding = DW_EH_PE_pcrel;
2110         }
2111         p = ALIGN_PTR_TO (p, 4);
2112
2113         fde_count = *(guint32*)p;
2114         p += 4;
2115         table = (gint32*)p;
2116
2117         /* There is +1 entry in the table */
2118         cie = p + ((fde_count + 1) * 8);
2119
2120         /* Binary search in the table to find the entry for code */
2121         if (func_encoding == DW_EH_PE_absptr) {
2122                 /*
2123                  * Table entries are encoded as DW_EH_PE_absptr, because the ios linker can move functions inside object files to make thumb work,
2124                  * so the offsets between two symbols in the text segment are not assembler constant.
2125                  */
2126                 g_assert (sizeof(gpointer) == 4);
2127                 offset = GPOINTER_TO_INT (code);
2128         } else {
2129                 /* Table entries are encoded as DW_EH_PE_pcrel relative to mono_eh_frame */
2130                 offset = code - amodule->mono_eh_frame;
2131         }
2132
2133         left = 0;
2134         right = fde_count;
2135         while (TRUE) {
2136                 pos = (left + right) / 2;
2137
2138                 offset1 = table [(pos * 2)];
2139                 if (pos + 1 == fde_count) {
2140                         if (func_encoding == DW_EH_PE_absptr)
2141                                 offset2 = GPOINTER_TO_INT (amodule->code_end);
2142                         else
2143                                 offset2 = amodule->code_end - amodule->code;
2144                 } else {
2145                         offset2 = table [(pos + 1) * 2];
2146                 }
2147
2148                 if (offset < offset1)
2149                         right = pos;
2150                 else if (offset >= offset2)
2151                         left = pos + 1;
2152                 else
2153                         break;
2154         }
2155
2156         if (func_encoding == DW_EH_PE_absptr) {
2157                 code_start = (gpointer)(gsize)table [(pos * 2)];
2158                 code_end = (gpointer)(gsize)table [(pos * 2) + 2];
2159         } else {
2160                 code_start = amodule->mono_eh_frame + table [(pos * 2)];
2161                 /* This won't overflow because there is +1 entry in the table */
2162                 code_end = amodule->mono_eh_frame + table [(pos * 2) + 2];
2163         }
2164         code_len = code_end - code_start;
2165
2166         g_assert (code >= code_start && code < code_end);
2167
2168         if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
2169                 /* Clear thumb flag */
2170                 code_start = (guint8*)(((mgreg_t)code_start) & ~1);
2171
2172         fde = amodule->mono_eh_frame + table [(pos * 2) + 1];   
2173         /* This won't overflow because there is +1 entry in the table */
2174         fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
2175
2176         mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
2177         ei = info.ex_info;
2178         ei_len = info.ex_info_len;
2179         type_info = info.type_info;
2180         *this_reg = info.this_reg;
2181         *this_offset = info.this_offset;
2182
2183         /* Count number of nested clauses */
2184         nested_len = 0;
2185         for (i = 0; i < ei_len; ++i) {
2186                 /* This might be unaligned */
2187                 gint32 cindex1 = read32 (type_info [i]);
2188                 GSList *l;
2189
2190                 for (l = nesting [cindex1]; l; l = l->next) {
2191                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2192
2193                         for (j = 0; j < ei_len; ++j) {
2194                                 gint32 cindex2 = read32 (type_info [j]);
2195
2196                                 if (cindex2 == nesting_cindex)
2197                                         nested_len ++;
2198                         }
2199                 }
2200         }
2201
2202         /*
2203          * LLVM might represent one IL region with multiple regions, so have to
2204          * allocate a new JI.
2205          */
2206         jinfo = 
2207                 mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);
2208
2209         jinfo->code_size = code_len;
2210         jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
2211         jinfo->method = method;
2212         jinfo->code_start = code;
2213         jinfo->domain_neutral = 0;
2214         /* This signals that used_regs points to a normal cached unwind info */
2215         jinfo->from_aot = 0;
2216         jinfo->num_clauses = ei_len + nested_len;
2217
2218         for (i = 0; i < ei_len; ++i) {
2219                 /*
2220                  * orig_jinfo contains the original IL exception info saved by the AOT
2221                  * compiler, we have to combine that with the information produced by LLVM
2222                  */
2223                 /* The type_info entries contain IL clause indexes */
2224                 int clause_index = read32 (type_info [i]);
2225                 MonoJitExceptionInfo *jei = &jinfo->clauses [i];
2226                 MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
2227
2228                 g_assert (clause_index < num_clauses);
2229                 jei->flags = orig_jei->flags;
2230                 jei->data.catch_class = orig_jei->data.catch_class;
2231
2232                 jei->try_start = ei [i].try_start;
2233                 jei->try_end = ei [i].try_end;
2234                 jei->handler_start = ei [i].handler_start;
2235
2236                 /* Make sure we transition to thumb when a handler starts */
2237                 if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
2238                         jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
2239         }
2240
2241         /* See exception_cb () in mini-llvm.c as to why this is needed */
2242         nindex = ei_len;
2243         for (i = 0; i < ei_len; ++i) {
2244                 gint32 cindex1 = read32 (type_info [i]);
2245                 GSList *l;
2246
2247                 for (l = nesting [cindex1]; l; l = l->next) {
2248                         gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
2249
2250                         for (j = 0; j < ei_len; ++j) {
2251                                 gint32 cindex2 = read32 (type_info [j]);
2252
2253                                 if (cindex2 == nesting_cindex) {
2254                                         /* 
2255                                          * The try interval comes from the nested clause, everything else from the
2256                                          * nesting clause.
2257                                          */
2258                                         memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
2259                                         jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
2260                                         jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
2261                                         nindex ++;
2262                                 }
2263                         }
2264                 }
2265         }
2266         g_assert (nindex == ei_len + nested_len);
2267
2268         return jinfo;
2269 }
2270
2271 /*
2272  * LOCKING: Acquires the domain lock.
2273  */
2274 static MonoJitInfo*
2275 decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, 
2276                                                          MonoMethod *method, guint8* ex_info, guint8 *addr,
2277                                                          guint8 *code, guint32 code_len)
2278 {
2279         int i, buf_len, num_clauses;
2280         MonoJitInfo *jinfo;
2281         guint used_int_regs, flags;
2282         gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
2283         gboolean from_llvm, has_gc_map;
2284         guint8 *p;
2285         int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
2286         int this_reg = 0, this_offset = 0;
2287
2288         /* Load the method info from the AOT file */
2289
2290         p = ex_info;
2291         flags = decode_value (p, &p);
2292         has_generic_jit_info = (flags & 1) != 0;
2293         has_dwarf_unwind_info = (flags & 2) != 0;
2294         has_clauses = (flags & 4) != 0;
2295         has_seq_points = (flags & 8) != 0;
2296         from_llvm = (flags & 16) != 0;
2297         has_try_block_holes = (flags & 32) != 0;
2298         has_gc_map = (flags & 64) != 0;
2299         has_arch_eh_jit_info = (flags & 128) != 0;
2300
2301         if (has_dwarf_unwind_info) {
2302                 guint32 offset;
2303
2304                 offset = decode_value (p, &p);
2305                 g_assert (offset < (1 << 30));
2306                 used_int_regs = offset;
2307         } else {
2308                 used_int_regs = decode_value (p, &p);
2309         }
2310         if (has_generic_jit_info)
2311                 generic_info_size = sizeof (MonoGenericJitInfo);
2312         else
2313                 generic_info_size = 0;
2314
2315         if (has_try_block_holes) {
2316                 num_holes = decode_value (p, &p);
2317                 try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
2318         } else {
2319                 num_holes = try_holes_info_size = 0;
2320         }
2321         /* Exception table */
2322         if (has_clauses)
2323                 num_clauses = decode_value (p, &p);
2324         else
2325                 num_clauses = 0;
2326         if (has_arch_eh_jit_info)
2327                 arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
2328         else
2329                 arch_eh_jit_info_size = 0;
2330
2331         if (from_llvm) {
2332                 MonoJitExceptionInfo *clauses;
2333                 GSList **nesting;
2334
2335                 /*
2336                  * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
2337                  * section.
2338                  */
2339                 clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
2340                 nesting = g_new0 (GSList*, num_clauses);
2341
2342                 for (i = 0; i < num_clauses; ++i) {
2343                         MonoJitExceptionInfo *ei = &clauses [i];
2344
2345                         ei->flags = decode_value (p, &p);
2346
2347                         if (decode_value (p, &p))
2348                                 ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2349
2350                         /* Read the list of nesting clauses */
2351                         while (TRUE) {
2352                                 int nesting_index = decode_value (p, &p);
2353                                 if (nesting_index == -1)
2354                                         break;
2355                                 nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
2356                         }
2357                 }
2358
2359                 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);
2360                 jinfo->from_llvm = 1;
2361
2362                 g_free (clauses);
2363                 for (i = 0; i < num_clauses; ++i)
2364                         g_slist_free (nesting [i]);
2365                 g_free (nesting);
2366         } else {
2367                 jinfo = 
2368                         mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size);
2369                 jinfo->num_clauses = num_clauses;
2370
2371                 for (i = 0; i < jinfo->num_clauses; ++i) {
2372                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2373
2374                         ei->flags = decode_value (p, &p);
2375
2376                         ei->exvar_offset = decode_value (p, &p);
2377
2378                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
2379                                 ei->data.filter = code + decode_value (p, &p);
2380                         else {
2381                                 if (decode_value (p, &p))
2382                                         ei->data.catch_class = decode_klass_ref (amodule, p, &p);
2383                         }
2384
2385                         ei->try_start = code + decode_value (p, &p);
2386                         ei->try_end = code + decode_value (p, &p);
2387                         ei->handler_start = code + decode_value (p, &p);
2388                 }
2389
2390                 jinfo->code_size = code_len;
2391                 jinfo->used_regs = used_int_regs;
2392                 jinfo->method = method;
2393                 jinfo->code_start = code;
2394                 jinfo->domain_neutral = 0;
2395                 jinfo->from_aot = 1;
2396         }
2397
2398         if (has_generic_jit_info) {
2399                 MonoGenericJitInfo *gi;
2400
2401                 jinfo->has_generic_jit_info = 1;
2402
2403                 gi = mono_jit_info_get_generic_jit_info (jinfo);
2404                 g_assert (gi);
2405
2406                 gi->nlocs = decode_value (p, &p);
2407                 if (gi->nlocs) {
2408                         gi->locations = mono_domain_alloc0 (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2409                         for (i = 0; i < gi->nlocs; ++i) {
2410                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
2411
2412                                 entry->is_reg = decode_value (p, &p);
2413                                 entry->reg = decode_value (p, &p);
2414                                 if (!entry->is_reg)
2415                                         entry->offset = decode_value (p, &p);
2416                                 if (i > 0)
2417                                         entry->from = decode_value (p, &p);
2418                                 entry->to = decode_value (p, &p);
2419                         }
2420                 } else {
2421                         if (from_llvm) {
2422                                 gi->has_this = this_reg != -1;
2423                                 gi->this_reg = this_reg;
2424                                 gi->this_offset = this_offset;
2425                         } else {
2426                                 gi->has_this = decode_value (p, &p);
2427                                 gi->this_reg = decode_value (p, &p);
2428                                 gi->this_offset = decode_value (p, &p);
2429                         }
2430                 }
2431
2432                 jinfo->method = decode_resolve_method_ref (amodule, p, &p);
2433
2434                 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2435                 if (decode_value (p, &p)) {
2436                         /* gsharedvt */
2437                         int i, n;
2438                         MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
2439
2440                         n = decode_value (p, &p);
2441                         if (n) {
2442                                 gsctx->var_is_vt = g_new0 (gboolean, n);
2443                                 for (i = 0; i < n; ++i)
2444                                         gsctx->var_is_vt [i] = decode_value (p, &p);
2445                         }
2446                         n = decode_value (p, &p);
2447                         if (n) {
2448                                 gsctx->mvar_is_vt = g_new0 (gboolean, n);
2449                                 for (i = 0; i < n; ++i)
2450                                         gsctx->mvar_is_vt [i] = decode_value (p, &p);
2451                         }
2452                 }
2453         }
2454
2455         if (has_try_block_holes) {
2456                 MonoTryBlockHoleTableJitInfo *table;
2457
2458                 jinfo->has_try_block_holes = 1;
2459
2460                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2461                 g_assert (table);
2462
2463                 table->num_holes = (guint16)num_holes;
2464                 for (i = 0; i < num_holes; ++i) {
2465                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
2466                         hole->clause = decode_value (p, &p);
2467                         hole->length = decode_value (p, &p);
2468                         hole->offset = decode_value (p, &p);
2469                 }
2470         }
2471
2472         if (has_arch_eh_jit_info) {
2473                 MonoArchEHJitInfo *eh_info;
2474
2475                 jinfo->has_arch_eh_info = 1;
2476
2477                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
2478                 eh_info->stack_size = decode_value (p, &p);
2479         }
2480
2481         if (has_seq_points) {
2482                 MonoSeqPointInfo *seq_points;
2483                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
2484
2485                 int len = decode_value (p, &p);
2486
2487                 seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
2488                 seq_points->len = len;
2489                 last_il_offset = last_native_offset = 0;
2490                 for (i = 0; i < len; ++i) {
2491                         SeqPoint *sp = &seq_points->seq_points [i];
2492                         il_offset = last_il_offset + decode_value (p, &p);
2493                         native_offset = last_native_offset + decode_value (p, &p);
2494
2495                         sp->il_offset = il_offset;
2496                         sp->native_offset = native_offset;
2497                         
2498                         sp->next_len = decode_value (p, &p);
2499                         sp->next = g_new (int, sp->next_len);
2500                         for (j = 0; j < sp->next_len; ++j)
2501                                 sp->next [j] = decode_value (p, &p);
2502
2503                         last_il_offset = il_offset;
2504                         last_native_offset = native_offset;
2505                 }
2506
2507                 mono_domain_lock (domain);
2508                 g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
2509                 mono_domain_unlock (domain);
2510         }
2511
2512         /* Load debug info */
2513         buf_len = decode_value (p, &p);
2514         mono_debug_add_aot_method (domain, method, code, p, buf_len);
2515         p += buf_len;
2516
2517         if (has_gc_map) {
2518                 int map_size = decode_value (p, &p);
2519                 /* The GC map requires 4 bytes of alignment */
2520                 while ((guint64)(gsize)p % 4)
2521                         p ++;           
2522                 jinfo->gc_info = p;
2523                 p += map_size;
2524         }
2525
2526         if (amodule != jinfo->method->klass->image->aot_module) {
2527                 mono_aot_lock ();
2528                 if (!ji_to_amodule)
2529                         ji_to_amodule = g_hash_table_new (NULL, NULL);
2530                 g_hash_table_insert (ji_to_amodule, jinfo, amodule);
2531                 mono_aot_unlock ();             
2532         }
2533
2534         return jinfo;
2535 }
2536
2537 /*
2538  * mono_aot_get_unwind_info:
2539  *
2540  *   Return a pointer to the DWARF unwind info belonging to JI.
2541  */
2542 guint8*
2543 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
2544 {
2545         MonoAotModule *amodule = ji->method->klass->image->aot_module;
2546         guint8 *p;
2547         guint8 *code = ji->code_start;
2548
2549         g_assert (amodule);
2550         g_assert (ji->from_aot);
2551
2552         if (!(code >= amodule->code && code <= amodule->code_end)) {
2553                 /* ji belongs to a different aot module than amodule */
2554                 mono_aot_lock ();
2555                 g_assert (ji_to_amodule);
2556                 amodule = g_hash_table_lookup (ji_to_amodule, ji);
2557                 g_assert (amodule);
2558                 g_assert (code >= amodule->code && code <= amodule->code_end);
2559                 mono_aot_unlock ();
2560         }
2561
2562         p = amodule->unwind_info + ji->used_regs;
2563         *unwind_info_len = decode_value (p, &p);
2564         return p;
2565 }
2566
2567 static G_GNUC_UNUSED int
2568 compare_ints (const void *a, const void *b)
2569 {
2570         return *(gint32*)a - *(gint32*)b;
2571 }
2572
2573 static void
2574 msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
2575 {
2576         int mid = (lo + hi) / 2;
2577         int i, t_lo, t_hi;
2578
2579         if (lo >= hi)
2580                 return;
2581
2582         if (hi - lo < 32) {
2583                 for (i = lo; i < hi; ++i)
2584                         if (array [(i * 2)] > array [(i * 2) + 2])
2585                                 break;
2586                 if (i == hi)
2587                         /* Already sorted */
2588                         return;
2589         }
2590
2591         msort_code_offsets_internal (array, lo, mid, scratch);
2592         msort_code_offsets_internal (array, mid + 1, hi, scratch);
2593
2594         if (array [mid * 2] < array [(mid + 1) * 2])
2595                 return;
2596
2597         /* Merge */
2598         t_lo = lo;
2599         t_hi = mid + 1;
2600         for (i = lo; i <= hi; i ++) {
2601                 if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
2602                         scratch [(i * 2)] = array [t_lo * 2];
2603                         scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
2604                         t_lo ++;
2605                 } else {
2606                         scratch [(i * 2)] = array [t_hi * 2];
2607                         scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
2608                         t_hi ++;
2609                 }
2610         }
2611         for (i = lo; i <= hi; ++i) {
2612                 array [(i * 2)] = scratch [i * 2];
2613                 array [(i * 2) + 1] = scratch [(i * 2) + 1];
2614         }
2615 }
2616
2617 static void
2618 msort_code_offsets (gint32 *array, int len)
2619 {
2620         gint32 *scratch;
2621
2622         scratch = g_new (gint32, len * 2);
2623         msort_code_offsets_internal (array, 0, len - 1, scratch);
2624         g_free (scratch);
2625 }
2626
2627 MonoJitInfo *
2628 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2629 {
2630         int pos, left, right, offset, offset1, offset2, code_len;
2631         int method_index, table_len;
2632         guint32 token;
2633         MonoAotModule *amodule = image->aot_module;
2634         MonoMethod *method;
2635         MonoJitInfo *jinfo;
2636         guint8 *code, *ex_info, *p;
2637         guint32 *table;
2638         int nmethods = amodule->info.nmethods;
2639         gint32 *code_offsets;
2640         int offsets_len, i;
2641
2642         if (!amodule)
2643                 return NULL;
2644
2645         if (domain != mono_get_root_domain ())
2646                 /* FIXME: */
2647                 return NULL;
2648
2649         offset = (guint8*)addr - amodule->code;
2650
2651         /* Compute a sorted table mapping code offsets to method indexes. */
2652         if (!amodule->sorted_code_offsets) {
2653                 code_offsets = g_new0 (gint32, nmethods * 2);
2654                 offsets_len = 0;
2655                 for (i = 0; i < nmethods; ++i) {
2656                         /* Skip the -1 entries to speed up sorting */
2657                         if (amodule->code_offsets [i] == 0xffffffff)
2658                                 continue;
2659                         code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
2660                         code_offsets [(offsets_len *2) + 1] = i;
2661                         offsets_len ++;
2662                 }
2663                 /* Use a merge sort as this is mostly sorted */
2664                 msort_code_offsets (code_offsets, offsets_len);
2665                 //qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
2666                 for (i = 0; i < offsets_len -1; ++i)
2667                         g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);
2668
2669                 amodule->sorted_code_offsets_len = offsets_len;
2670                 mono_memory_barrier ();
2671                 if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
2672                         /* Somebody got in before us */
2673                         g_free (code_offsets);
2674         }
2675
2676         code_offsets = amodule->sorted_code_offsets;
2677         offsets_len = amodule->sorted_code_offsets_len;
2678
2679         if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
2680                 return NULL;
2681
2682         /* Binary search in the sorted_code_offsets table */
2683         left = 0;
2684         right = offsets_len;
2685         while (TRUE) {
2686                 pos = (left + right) / 2;
2687
2688                 offset1 = code_offsets [(pos * 2)];
2689                 if (pos + 1 == offsets_len)
2690                         offset2 = amodule->code_end - amodule->code;
2691                 else
2692                         offset2 = code_offsets [(pos + 1) * 2];
2693
2694                 if (offset < offset1)
2695                         right = pos;
2696                 else if (offset >= offset2)
2697                         left = pos + 1;
2698                 else
2699                         break;
2700         }
2701
2702         g_assert (offset >= code_offsets [(pos * 2)]);
2703         if (pos + 1 < offsets_len)
2704                 g_assert (offset < code_offsets [((pos + 1) * 2)]);
2705         method_index = code_offsets [(pos * 2) + 1];
2706
2707         code = &amodule->code [amodule->code_offsets [method_index]];
2708         ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
2709
2710         if (pos == offsets_len - 1)
2711                 code_len = amodule->code_end - code;
2712         else
2713                 code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];
2714
2715         g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
2716
2717         /* Might be a wrapper/extra method */
2718         if (amodule->extra_methods) {
2719                 mono_aot_lock ();
2720                 method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
2721                 mono_aot_unlock ();
2722         } else {
2723                 method = NULL;
2724         }
2725
2726         if (!method) {
2727                 if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
2728                         /* 
2729                          * This is hit for extra methods which are called directly, so they are
2730                          * not in amodule->extra_methods.
2731                          */
2732                         table_len = amodule->extra_method_info_offsets [0];
2733                         table = amodule->extra_method_info_offsets + 1;
2734                         left = 0;
2735                         right = table_len;
2736                         pos = 0;
2737
2738                         /* Binary search */
2739                         while (TRUE) {
2740                                 pos = ((left + right) / 2);
2741
2742                                 g_assert (pos < table_len);
2743
2744                                 if (table [pos * 2] < method_index)
2745                                         left = pos + 1;
2746                                 else if (table [pos * 2] > method_index)
2747                                         right = pos;
2748                                 else
2749                                         break;
2750                         }
2751
2752                         p = amodule->blob + table [(pos * 2) + 1];
2753                         method = decode_resolve_method_ref (amodule, p, &p);
2754                         if (!method)
2755                                 /* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
2756                                 return NULL;
2757                 } else {
2758                         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
2759                         method = mono_get_method (image, token, NULL);
2760                 }
2761         }
2762
2763         /* FIXME: */
2764         g_assert (method);
2765
2766         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2767         
2768         jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);
2769
2770         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
2771         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
2772
2773         /* Add it to the normal JitInfo tables */
2774         mono_jit_info_table_add (domain, jinfo);
2775         
2776         return jinfo;
2777 }
2778
2779 static gboolean
2780 decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
2781 {
2782         guint8 *p = buf;
2783         gpointer *table;
2784         MonoImage *image;
2785         int i;
2786
2787         switch (ji->type) {
2788         case MONO_PATCH_INFO_METHOD:
2789         case MONO_PATCH_INFO_METHOD_JUMP:
2790         case MONO_PATCH_INFO_ICALL_ADDR:
2791         case MONO_PATCH_INFO_METHOD_RGCTX: {
2792                 MethodRef ref;
2793                 gboolean res;
2794
2795                 res = decode_method_ref (aot_module, &ref, p, &p);
2796                 if (!res)
2797                         goto cleanup;
2798
2799                 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)) {
2800                         ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
2801                         ji->type = MONO_PATCH_INFO_ABS;
2802                 }
2803                 else {
2804                         if (ref.method)
2805                                 ji->data.method = ref.method;
2806                         else
2807                                 ji->data.method = mono_get_method (ref.image, ref.token, NULL);
2808                         g_assert (ji->data.method);
2809                         mono_class_init (ji->data.method->klass);
2810                 }
2811                 break;
2812         }
2813         case MONO_PATCH_INFO_INTERNAL_METHOD:
2814         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2815                 guint32 len = decode_value (p, &p);
2816
2817                 ji->data.name = (char*)p;
2818                 p += len + 1;
2819                 break;
2820         }
2821         case MONO_PATCH_INFO_METHODCONST:
2822                 /* Shared */
2823                 ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
2824                 if (!ji->data.method)
2825                         goto cleanup;
2826                 break;
2827         case MONO_PATCH_INFO_VTABLE:
2828         case MONO_PATCH_INFO_CLASS:
2829         case MONO_PATCH_INFO_IID:
2830         case MONO_PATCH_INFO_ADJUSTED_IID:
2831                 /* Shared */
2832                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2833                 if (!ji->data.klass)
2834                         goto cleanup;
2835                 break;
2836         case MONO_PATCH_INFO_CLASS_INIT:
2837         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2838                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2839                 if (!ji->data.klass)
2840                         goto cleanup;
2841                 break;
2842         case MONO_PATCH_INFO_IMAGE:
2843                 ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
2844                 if (!ji->data.image)
2845                         goto cleanup;
2846                 break;
2847         case MONO_PATCH_INFO_FIELD:
2848         case MONO_PATCH_INFO_SFLDA:
2849                 /* Shared */
2850                 ji->data.field = decode_field_info (aot_module, p, &p);
2851                 if (!ji->data.field)
2852                         goto cleanup;
2853                 break;
2854         case MONO_PATCH_INFO_SWITCH:
2855                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
2856                 ji->data.table->table_size = decode_value (p, &p);
2857                 table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
2858                 ji->data.table->table = (MonoBasicBlock**)table;
2859                 for (i = 0; i < ji->data.table->table_size; i++)
2860                         table [i] = (gpointer)(gssize)decode_value (p, &p);
2861                 break;
2862         case MONO_PATCH_INFO_R4: {
2863                 guint32 val;
2864                 
2865                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
2866                 val = decode_value (p, &p);
2867                 *(float*)ji->data.target = *(float*)&val;
2868                 break;
2869         }
2870         case MONO_PATCH_INFO_R8: {
2871                 guint32 val [2];
2872                 guint64 v;
2873
2874                 ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));
2875
2876                 val [0] = decode_value (p, &p);
2877                 val [1] = decode_value (p, &p);
2878                 v = ((guint64)val [1] << 32) | ((guint64)val [0]);
2879                 *(double*)ji->data.target = *(double*)&v;
2880                 break;
2881         }
2882         case MONO_PATCH_INFO_LDSTR:
2883                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2884                 if (!image)
2885                         goto cleanup;
2886                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
2887                 break;
2888         case MONO_PATCH_INFO_RVA:
2889         case MONO_PATCH_INFO_DECLSEC:
2890         case MONO_PATCH_INFO_LDTOKEN:
2891         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2892                 /* Shared */
2893                 image = load_image (aot_module, decode_value (p, &p), TRUE);
2894                 if (!image)
2895                         goto cleanup;
2896                 ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
2897
2898                 ji->data.token->has_context = decode_value (p, &p);
2899                 if (ji->data.token->has_context) {
2900                         gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
2901                         if (!res)
2902                                 goto cleanup;
2903                 }
2904                 break;
2905         case MONO_PATCH_INFO_EXC_NAME:
2906                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
2907                 if (!ji->data.klass)
2908                         goto cleanup;
2909                 ji->data.name = ji->data.klass->name;
2910                 break;
2911         case MONO_PATCH_INFO_METHOD_REL:
2912                 ji->data.offset = decode_value (p, &p);
2913                 break;
2914         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2915         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2916         case MONO_PATCH_INFO_MONITOR_ENTER:
2917         case MONO_PATCH_INFO_MONITOR_EXIT:
2918         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
2919         case MONO_PATCH_INFO_CASTCLASS_CACHE:
2920         case MONO_PATCH_INFO_JIT_TLS_ID:
2921                 break;
2922         case MONO_PATCH_INFO_RGCTX_FETCH: {
2923                 gboolean res;
2924                 MonoJumpInfoRgctxEntry *entry;
2925                 guint32 offset, val;
2926                 guint8 *p2;
2927
2928                 offset = decode_value (p, &p);
2929                 val = decode_value (p, &p);
2930
2931                 entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2932                 p2 = aot_module->blob + offset;
2933                 entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
2934                 entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
2935                 entry->info_type = (val >> 1) & 0xff;
2936                 entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2937                 entry->data->type = (val >> 9) & 0xff;
2938                 
2939                 res = decode_patch (aot_module, mp, entry->data, p, &p);
2940                 if (!res)
2941                         goto cleanup;
2942                 ji->data.rgctx_entry = entry;
2943                 break;
2944         }
2945         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2946                 break;
2947         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
2948                 MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));
2949
2950                 imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
2951                 imt_tramp->vt_offset = decode_value (p, &p);
2952                 
2953                 ji->data.imt_tramp = imt_tramp;
2954                 break;
2955         }
2956         case MONO_PATCH_INFO_SIGNATURE:
2957                 ji->data.target = decode_signature (aot_module, p, &p);
2958                 break;
2959         case MONO_PATCH_INFO_GSHAREDVT_CALL: {
2960                 MonoJumpInfoGSharedVtCall *info = g_new0 (MonoJumpInfoGSharedVtCall, 1);
2961                 info->sig = decode_signature (aot_module, p, &p);
2962                 g_assert (info->sig);
2963                 info->method = decode_resolve_method_ref (aot_module, p, &p);
2964                 g_assert (info->method);
2965
2966                 ji->data.target = info;
2967                 break;
2968         }
2969         default:
2970                 g_warning ("unhandled type %d", ji->type);
2971                 g_assert_not_reached ();
2972         }
2973
2974         *endbuf = p;
2975
2976         return TRUE;
2977
2978  cleanup:
2979         return FALSE;
2980 }
2981
2982 static MonoJumpInfo*
2983 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
2984                                  guint32 **got_slots, 
2985                                  guint8 *buf, guint8 **endbuf)
2986 {
2987         MonoJumpInfo *patches;
2988         int pindex;
2989         guint8 *p;
2990
2991         p = buf;
2992
2993         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
2994
2995         *got_slots = g_malloc (sizeof (guint32) * n_patches);
2996
2997         for (pindex = 0; pindex < n_patches; ++pindex) {
2998                 MonoJumpInfo *ji = &patches [pindex];
2999                 guint8 *shared_p;
3000                 gboolean res;
3001                 guint32 got_offset;
3002
3003                 got_offset = decode_value (p, &p);
3004
3005                 if (aot_module->got [got_offset]) {
3006                         /* Already loaded */
3007                         //printf ("HIT!\n");
3008                 } else {
3009                         shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);
3010
3011                         ji->type = decode_value (shared_p, &shared_p);
3012
3013                         res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
3014                         if (!res)
3015                                 goto cleanup;
3016                 }
3017
3018                 (*got_slots) [pindex] = got_offset;
3019         }
3020
3021         *endbuf = p;
3022         return patches;
3023
3024  cleanup:
3025         g_free (*got_slots);
3026         *got_slots = NULL;
3027
3028         return NULL;
3029 }
3030
3031 static void
3032 register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
3033 {
3034         /*
3035          * Jump addresses cannot be patched by the trampoline code since it
3036          * does not have access to the caller's address. Instead, we collect
3037          * the addresses of the GOT slots pointing to a method, and patch
3038          * them after the method has been compiled.
3039          */
3040         MonoJitDomainInfo *info = domain_jit_info (domain);
3041         GSList *list;
3042                 
3043         mono_domain_lock (domain);
3044         if (!info->jump_target_got_slot_hash)
3045                 info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
3046         list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
3047         list = g_slist_prepend (list, got_slot);
3048         g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
3049         mono_domain_unlock (domain);
3050 }
3051
3052 /*
3053  * load_method:
3054  *
3055  *   Load the method identified by METHOD_INDEX from the AOT image. Return a
3056  * pointer to the native code of the method, or NULL if not found.
3057  * METHOD might not be set if the caller only has the image/token info.
3058  */
3059 static gpointer
3060 load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
3061 {
3062         MonoClass *klass;
3063         gboolean from_plt = method == NULL;
3064         MonoMemPool *mp;
3065         int i, pindex, n_patches, used_strings;
3066         gboolean keep_patches = TRUE;
3067         guint8 *p;
3068         MonoJitInfo *jinfo = NULL;
3069         guint8 *code, *info;
3070
3071         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
3072                 return NULL;
3073
3074         if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
3075                 /* Non shared AOT code can't be used in other appdomains */
3076                 return NULL;
3077
3078         if (amodule->out_of_date)
3079                 return NULL;
3080
3081         if (amodule->code_offsets [method_index] == 0xffffffff) {
3082                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3083                         char *full_name;
3084
3085                         if (!method)
3086                                 method = mono_get_method (image, token, NULL);
3087                         full_name = mono_method_full_name (method, TRUE);
3088                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
3089                         g_free (full_name);
3090                 }
3091                 return NULL;
3092         }
3093
3094         code = &amodule->code [amodule->code_offsets [method_index]];
3095
3096         info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
3097
3098         if (amodule->thumb_end && code < amodule->thumb_end && ((amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) == 0)) {
3099                 /* Convert this into a thumb address */
3100                 g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
3101                 code = &amodule->code [amodule->code_offsets [method_index] + 1];
3102         }
3103
3104         mono_aot_lock ();
3105         if (!amodule->methods_loaded)
3106                 amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
3107         mono_aot_unlock ();
3108
3109         if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
3110                 return code;
3111
3112         if (mono_last_aot_method != -1) {
3113                 if (mono_jit_stats.methods_aot >= mono_last_aot_method)
3114                                 return NULL;
3115                 else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
3116                         if (!method)
3117                                 method = mono_get_method (image, token, NULL);
3118                         if (method) {
3119                                 char *name = mono_method_full_name (method, TRUE);
3120                                 printf ("LAST AOT METHOD: %s.\n", name);
3121                                 g_free (name);
3122                         } else {
3123                                 printf ("LAST AOT METHOD: %p %d\n", code, method_index);
3124                         }
3125                 }
3126         }
3127
3128         p = info;
3129
3130         if (method) {
3131                 klass = method->klass;
3132                 decode_klass_ref (amodule, p, &p);
3133         } else {
3134                 klass = decode_klass_ref (amodule, p, &p);
3135         }
3136
3137         if (amodule->info.opts & MONO_OPT_SHARED)
3138                 used_strings = decode_value (p, &p);
3139         else
3140                 used_strings = 0;
3141
3142         for (i = 0; i < used_strings; i++) {
3143                 guint token = decode_value (p, &p);
3144                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
3145         }
3146
3147         if (amodule->info.opts & MONO_OPT_SHARED)       
3148                 keep_patches = FALSE;
3149
3150         n_patches = decode_value (p, &p);
3151
3152         keep_patches = FALSE;
3153
3154         if (n_patches) {
3155                 MonoJumpInfo *patches;
3156                 guint32 *got_slots;
3157
3158                 if (keep_patches)
3159                         mp = domain->mp;
3160                 else
3161                         mp = mono_mempool_new ();
3162
3163                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3164                 if (patches == NULL)
3165                         goto cleanup;
3166
3167                 for (pindex = 0; pindex < n_patches; ++pindex) {
3168                         MonoJumpInfo *ji = &patches [pindex];
3169
3170                         if (!amodule->got [got_slots [pindex]]) {
3171                                 amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
3172                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3173                                         amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
3174                                 if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
3175                                         register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
3176                         }
3177                         ji->type = MONO_PATCH_INFO_NONE;
3178                 }
3179
3180                 g_free (got_slots);
3181
3182                 if (!keep_patches)
3183                         mono_mempool_destroy (mp);
3184         }
3185
3186         if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
3187                 jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3188
3189         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3190                 char *full_name;
3191
3192                 if (!method)
3193                         method = mono_get_method (image, token, NULL);
3194
3195                 full_name = mono_method_full_name (method, TRUE);
3196
3197                 if (!jinfo)
3198                         jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);
3199
3200                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
3201                 g_free (full_name);
3202         }
3203
3204         mono_aot_lock ();
3205
3206         InterlockedIncrement (&mono_jit_stats.methods_aot);
3207
3208         amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
3209
3210         init_plt (amodule);
3211
3212         if (method && method->wrapper_type)
3213                 g_hash_table_insert (amodule->method_to_code, method, code);
3214
3215         mono_aot_unlock ();
3216
3217         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
3218                 MonoJitInfo *jinfo;
3219
3220                 if (!method) {
3221                         method = mono_get_method (image, token, NULL);
3222                         g_assert (method);
3223                 }
3224                 mono_profiler_method_jit (method);
3225                 jinfo = mono_jit_info_table_find (domain, (char*)code);
3226                 g_assert (jinfo);
3227                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3228         }
3229
3230         if (from_plt && klass && !klass->generic_container)
3231                 mono_runtime_class_init (mono_class_vtable (domain, klass));
3232
3233         return code;
3234
3235  cleanup:
3236         /* FIXME: The space in domain->mp is wasted */  
3237         if (amodule->info.opts & MONO_OPT_SHARED)
3238                 /* No need to cache patches */
3239                 mono_mempool_destroy (mp);
3240
3241         if (jinfo)
3242                 g_free (jinfo);
3243
3244         return NULL;
3245 }
3246
3247 static guint32
3248 find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
3249 {
3250         guint32 table_size, entry_size, hash;
3251         guint32 *table, *entry;
3252         guint32 index;
3253         static guint32 n_extra_decodes;
3254
3255         if (!amodule || amodule->out_of_date)
3256                 return 0xffffff;
3257
3258         table_size = amodule->extra_method_table [0];
3259         table = amodule->extra_method_table + 1;
3260         entry_size = 3;
3261
3262         hash = mono_aot_method_hash (method) % table_size;
3263
3264         entry = &table [hash * entry_size];
3265
3266         if (entry [0] == 0)
3267                 return 0xffffff;
3268
3269         index = 0xffffff;
3270         while (TRUE) {
3271                 guint32 key = entry [0];
3272                 guint32 value = entry [1];
3273                 guint32 next = entry [entry_size - 1];
3274                 MonoMethod *m;
3275                 guint8 *p, *orig_p;
3276
3277                 p = amodule->blob + key;
3278                 orig_p = p;
3279
3280                 mono_aot_lock ();
3281                 if (!amodule->method_ref_to_method)
3282                         amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
3283                 m = g_hash_table_lookup (amodule->method_ref_to_method, p);
3284                 mono_aot_unlock ();
3285                 if (!m) {
3286                         m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
3287                         if (m) {
3288                                 mono_aot_lock ();
3289                                 g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
3290                                 mono_aot_unlock ();
3291                         }
3292                 }
3293                 if (m == method) {
3294                         index = value;
3295                         break;
3296                 }
3297
3298                 /* Special case: wrappers of shared generic methods */
3299                 if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
3300                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
3301                         MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
3302                         MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
3303
3304                         if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
3305                                 index = value;
3306                                 break;
3307                         }
3308                 }
3309
3310                 /* Methods decoded needlessly */
3311                 if (m) {
3312                         //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
3313                         n_extra_decodes ++;
3314                 }
3315
3316                 if (next != 0)
3317                         entry = &table [next * entry_size];
3318                 else
3319                         break;
3320         }
3321
3322         return index;
3323 }
3324
3325 static void
3326 add_module_cb (gpointer key, gpointer value, gpointer user_data)
3327 {
3328         g_ptr_array_add ((GPtrArray*)user_data, value);
3329 }
3330
3331 /*
3332  * find_extra_method:
3333  *
3334  *   Try finding METHOD in the extra_method table in all AOT images.
3335  * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
3336  * module where the method was found.
3337  */
3338 static guint32
3339 find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
3340 {
3341         guint32 index;
3342         GPtrArray *modules;
3343         int i;
3344
3345         /* Try the method's module first */
3346         *out_amodule = method->klass->image->aot_module;
3347         index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
3348         if (index != 0xffffff)
3349                 return index;
3350
3351         /* 
3352          * Try all other modules.
3353          * This is needed because generic instances klass->image points to the image
3354          * containing the generic definition, but the native code is generated to the
3355          * AOT image which contains the reference.
3356          */
3357
3358         /* Make a copy to avoid doing the search inside the aot lock */
3359         modules = g_ptr_array_new ();
3360         mono_aot_lock ();
3361         g_hash_table_foreach (aot_modules, add_module_cb, modules);
3362         mono_aot_unlock ();
3363
3364         index = 0xffffff;
3365         for (i = 0; i < modules->len; ++i) {
3366                 MonoAotModule *amodule = g_ptr_array_index (modules, i);
3367
3368                 if (amodule != method->klass->image->aot_module)
3369                         index = find_extra_method_in_amodule (amodule, method);
3370                 if (index != 0xffffff) {
3371                         *out_amodule = amodule;
3372                         break;
3373                 }
3374         }
3375         
3376         g_ptr_array_free (modules, TRUE);
3377
3378         return index;
3379 }
3380
3381 /*
3382  * mono_aot_get_method:
3383  *
3384  *   Return a pointer to the AOTed native code for METHOD if it can be found,
3385  * NULL otherwise.
3386  * On platforms with function pointers, this doesn't return a function pointer.
3387  */
3388 gpointer
3389 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
3390 {
3391         MonoClass *klass = method->klass;
3392         guint32 method_index;
3393         MonoAotModule *amodule = klass->image->aot_module;
3394         guint8 *code;
3395
3396         if (!amodule)
3397                 return NULL;
3398
3399         if (amodule->out_of_date)
3400                 return NULL;
3401
3402         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3403                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3404                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3405                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3406                 return NULL;
3407
3408         /*
3409          * Use the original method instead of its invoke-with-check wrapper.
3410          * This is not a problem when using full-aot, since it doesn't support
3411          * remoting.
3412          */
3413         if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3414                 return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));
3415
3416         g_assert (klass->inited);
3417
3418         /* Find method index */
3419         if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE)) {
3420                 /* 
3421                  * For generic methods, we store the fully shared instance in place of the
3422                  * original method.
3423                  */
3424                 method = mono_method_get_declaring_generic_method (method);
3425                 method_index = mono_metadata_token_index (method->token) - 1;
3426         } else if (method->is_inflated || !method->token) {
3427                 /* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
3428                 mono_aot_lock ();
3429                 code = g_hash_table_lookup (amodule->method_to_code, method);
3430                 mono_aot_unlock ();
3431                 if (code)
3432                         return code;
3433
3434                 method_index = find_extra_method (method, &amodule);
3435                 /*
3436                  * Special case the ICollection<T> wrappers for arrays, as they cannot
3437                  * be statically enumerated, and each wrapper ends up calling the same
3438                  * method in Array.
3439                  */
3440                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
3441                         MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3442
3443                         code = mono_aot_get_method (domain, m);
3444                         if (code) {
3445                                 if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
3446                                         code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
3447                                         /* The call above returns an ftnptr */
3448                                         code = mono_get_addr_from_ftnptr (code);
3449                                 }
3450
3451                                 return code;
3452                         }
3453                 }
3454
3455                 /*
3456                  * Special case Array.GetGenericValueImpl which is a generic icall.
3457                  * Generic sharing currently can't handle it, but the icall returns data using
3458                  * an out parameter, so the managed-to-native wrappers can share the same code.
3459                  */
3460                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
3461                         MonoMethod *m;
3462                         MonoGenericContext ctx;
3463                         MonoType *args [16];
3464
3465                         if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
3466                                 /* Avoid recursion */
3467                                 return NULL;
3468
3469                         m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
3470                         g_assert (m);
3471
3472                         memset (&ctx, 0, sizeof (ctx));
3473                         args [0] = &mono_defaults.object_class->byval_arg;
3474                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3475
3476                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3477
3478                         /* 
3479                          * Get the code for the <object> instantiation which should be emitted into
3480                          * the mscorlib aot image by the AOT compiler.
3481                          */
3482                         code = mono_aot_get_method (domain, m);
3483                         if (code)
3484                                 return code;
3485                 }
3486
3487                 /* Same for CompareExchange<T> and Exchange<T> */
3488                 /* Same for Volatile.Read<T>/Write<T> */
3489                 if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && 
3490                         ((!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])) ||
3491                          (!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))) ||
3492                          (!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]))))) {
3493                         MonoMethod *m;
3494                         MonoGenericContext ctx;
3495                         MonoType *args [16];
3496                         gpointer iter = NULL;
3497
3498                         while ((m = mono_class_get_methods (method->klass, &iter))) {
3499                                 if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
3500                                         break;
3501                         }
3502                         g_assert (m);
3503
3504                         memset (&ctx, 0, sizeof (ctx));
3505                         args [0] = &mono_defaults.object_class->byval_arg;
3506                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3507
3508                         m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);
3509
3510                         /* Avoid recursion */
3511                         if (method == m)
3512                                 return NULL;
3513
3514                         /* 
3515                          * Get the code for the <object> instantiation which should be emitted into
3516                          * the mscorlib aot image by the AOT compiler.
3517                          */
3518                         code = mono_aot_get_method (domain, m);
3519                         if (code)
3520                                 return code;
3521                 }
3522
3523                 if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, TRUE)) {
3524                         /* gsharedvt */
3525                         /* Use the all-vt shared method since this is what was AOTed */
3526                         method_index = find_extra_method (mini_get_shared_method_full (method, TRUE, TRUE), &amodule);
3527                         if (method_index != 0xffffff)
3528                                 method = mini_get_shared_method_full (method, TRUE, FALSE);
3529                 }
3530
3531                 if (method_index == 0xffffff) {
3532                         if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
3533                                 char *full_name;
3534
3535                                 full_name = mono_method_full_name (method, TRUE);
3536                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
3537                                 g_free (full_name);
3538                         }
3539                         return NULL;
3540                 }
3541
3542                 if (method_index == 0xffffff)
3543                         return NULL;
3544
3545                 /* Needed by find_jit_info */
3546                 mono_aot_lock ();
3547                 if (!amodule->extra_methods)
3548                         amodule->extra_methods = g_hash_table_new (NULL, NULL);
3549                 g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
3550                 mono_aot_unlock ();
3551         } else {
3552                 /* Common case */
3553                 method_index = mono_metadata_token_index (method->token) - 1;
3554         }
3555
3556         return load_method (domain, amodule, klass->image, method, method->token, method_index);
3557 }
3558
3559 /**
3560  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
3561  * method.
3562  */
3563 gpointer
3564 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
3565 {
3566         MonoAotModule *aot_module = image->aot_module;
3567         int method_index;
3568
3569         if (!aot_module)
3570                 return NULL;
3571
3572         method_index = mono_metadata_token_index (token) - 1;
3573
3574         return load_method (domain, aot_module, image, NULL, token, method_index);
3575 }
3576
3577 typedef struct {
3578         guint8 *addr;
3579         gboolean res;
3580 } IsGotEntryUserData;
3581
3582 static void
3583 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
3584 {
3585         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
3586         MonoAotModule *aot_module = (MonoAotModule*)value;
3587
3588         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
3589                 data->res = TRUE;
3590 }
3591
3592 gboolean
3593 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
3594 {
3595         IsGotEntryUserData user_data;
3596
3597         if (!aot_modules)
3598                 return FALSE;
3599
3600         user_data.addr = addr;
3601         user_data.res = FALSE;
3602         mono_aot_lock ();
3603         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
3604         mono_aot_unlock ();
3605         
3606         return user_data.res;
3607 }
3608
3609 typedef struct {
3610         guint8 *addr;
3611         MonoAotModule *module;
3612 } FindAotModuleUserData;
3613
3614 static void
3615 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
3616 {
3617         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
3618         MonoAotModule *aot_module = (MonoAotModule*)value;
3619
3620         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
3621                 data->module = aot_module;
3622 }
3623
3624 static inline MonoAotModule*
3625 find_aot_module (guint8 *code)
3626 {
3627         FindAotModuleUserData user_data;
3628
3629         if (!aot_modules)
3630                 return NULL;
3631
3632         /* Reading these need no locking */
3633         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
3634                 return NULL;
3635
3636         user_data.addr = code;
3637         user_data.module = NULL;
3638                 
3639         mono_aot_lock ();
3640         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
3641         mono_aot_unlock ();
3642         
3643         return user_data.module;
3644 }
3645
3646 void
3647 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
3648 {
3649         /*
3650          * Since AOT code is only used in the root domain, 
3651          * mono_domain_get () != mono_get_root_domain () means the calling method
3652          * is AppDomain:InvokeInDomain, so this is the same check as in 
3653          * mono_method_same_domain () but without loading the metadata for the method.
3654          */
3655         if (mono_domain_get () == mono_get_root_domain ())
3656                 mono_arch_patch_plt_entry (code, got, regs, addr);
3657 }
3658
3659 /*
3660  * mono_aot_plt_resolve:
3661  *
3662  *   This function is called by the entries in the PLT to resolve the actual method that
3663  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
3664  * Returns NULL if the something cannot be loaded.
3665  */
3666 gpointer
3667 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
3668 {
3669 #ifdef MONO_ARCH_AOT_SUPPORTED
3670         guint8 *p, *target, *plt_entry;
3671         MonoJumpInfo ji;
3672         MonoAotModule *module = (MonoAotModule*)aot_module;
3673         gboolean res, no_ftnptr = FALSE;
3674         MonoMemPool *mp;
3675         gboolean using_gsharedvt = FALSE;
3676
3677         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
3678
3679         p = &module->blob [plt_info_offset];
3680
3681         ji.type = decode_value (p, &p);
3682
3683         mp = mono_mempool_new_size (512);
3684         res = decode_patch (module, mp, &ji, p, &p);
3685
3686         if (!res) {
3687                 mono_mempool_destroy (mp);
3688                 return NULL;
3689         }
3690
3691 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
3692         using_gsharedvt = TRUE;
3693 #endif
3694
3695         /* 
3696          * Avoid calling resolve_patch_target in the full-aot case if possible, since
3697          * it would create a trampoline, and we don't need that.
3698          * We could do this only if the method does not need the special handling
3699          * in mono_magic_trampoline ().
3700          */
3701         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) &&
3702                 !mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
3703                 target = mono_jit_compile_method (ji.data.method);
3704                 no_ftnptr = TRUE;
3705         } else {
3706                 target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
3707         }
3708
3709         /*
3710          * The trampoline expects us to return a function descriptor on platforms which use
3711          * it, but resolve_patch_target returns a direct function pointer for some type of
3712          * patches, so have to translate between the two.
3713          * FIXME: Clean this up, but how ?
3714          */
3715         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) {
3716                 /* These should already have a function descriptor */
3717 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3718                 /* Our function descriptors have a 0 environment, gcc created ones don't */
3719                 if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
3720                         g_assert (((gpointer*)target) [2] == 0);
3721 #endif
3722                 /* Empty */
3723         } else if (!no_ftnptr) {
3724 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3725                 g_assert (((gpointer*)target) [2] != 0);
3726 #endif
3727                 target = mono_create_ftnptr (mono_domain_get (), target);
3728         }
3729
3730         mono_mempool_destroy (mp);
3731
3732         /* Patch the PLT entry with target which might be the actual method not a trampoline */
3733         plt_entry = mono_aot_get_plt_entry (code);
3734         g_assert (plt_entry);
3735         mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
3736
3737         return target;
3738 #else
3739         g_assert_not_reached ();
3740         return NULL;
3741 #endif
3742 }
3743
3744 /**
3745  * init_plt:
3746  *
3747  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
3748  * method in the module is loaded to avoid committing memory by writing to it.
3749  * LOCKING: Assumes the AOT lock is held.
3750  */
3751 static void
3752 init_plt (MonoAotModule *amodule)
3753 {
3754         int i;
3755         gpointer tramp;
3756
3757         if (amodule->plt_inited)
3758                 return;
3759
3760         tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
3761
3762         /*
3763          * Initialize the PLT entries in the GOT to point to the default targets.
3764          */
3765
3766         tramp = mono_create_ftnptr (mono_domain_get (), tramp);
3767          for (i = 1; i < amodule->info.plt_size; ++i)
3768                  /* All the default entries point to the AOT trampoline */
3769                  ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
3770
3771         amodule->plt_inited = TRUE;
3772 }
3773
3774 /*
3775  * mono_aot_get_plt_entry:
3776  *
3777  *   Return the address of the PLT entry called by the code at CODE if exists.
3778  */
3779 guint8*
3780 mono_aot_get_plt_entry (guint8 *code)
3781 {
3782         MonoAotModule *amodule = find_aot_module (code);
3783         guint8 *target = NULL;
3784
3785         if (!amodule)
3786                 return NULL;
3787
3788 #ifdef TARGET_ARM
3789         if (amodule->thumb_end && code < amodule->thumb_end) {
3790                 return mono_arm_get_thumb_plt_entry (code);
3791         }
3792 #endif
3793
3794 #ifdef MONO_ARCH_AOT_SUPPORTED
3795         target = mono_arch_get_call_target (code);
3796 #else
3797         g_assert_not_reached ();
3798 #endif
3799
3800 #ifdef MONOTOUCH
3801         while (target != NULL) {
3802                 if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3803                         return target;
3804                 
3805                 // Add 4 since mono_arch_get_call_target assumes we're passing
3806                 // the instruction after the actual branch instruction.
3807                 target = mono_arch_get_call_target (target + 4);
3808         }
3809
3810         return NULL;
3811 #else
3812         if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
3813                 return target;
3814         else
3815                 return NULL;
3816 #endif
3817 }
3818
3819 /*
3820  * mono_aot_get_plt_info_offset:
3821  *
3822  *   Return the PLT info offset belonging to the plt entry called by CODE.
3823  */
3824 guint32
3825 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
3826 {
3827         guint8 *plt_entry = mono_aot_get_plt_entry (code);
3828
3829         g_assert (plt_entry);
3830
3831         /* The offset is embedded inside the code after the plt entry */
3832 #ifdef MONO_ARCH_AOT_SUPPORTED
3833         return mono_arch_get_plt_info_offset (plt_entry, regs, code);
3834 #else
3835         g_assert_not_reached ();
3836         return 0;
3837 #endif
3838 }
3839
3840 static gpointer
3841 mono_create_ftnptr_malloc (guint8 *code)
3842 {
3843 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3844         MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
3845
3846         ftnptr->code = code;
3847         ftnptr->toc = NULL;
3848         ftnptr->env = NULL;
3849
3850         return ftnptr;
3851 #else
3852         return code;
3853 #endif
3854 }
3855
3856 /*
3857  * mono_aot_register_jit_icall:
3858  *
3859  *   Register a JIT icall which is called by trampolines in full-aot mode. This should
3860  * be called from mono_arch_init () during startup.
3861  */
3862 void
3863 mono_aot_register_jit_icall (const char *name, gpointer addr)
3864 {
3865         /* No need for locking */
3866         if (!aot_jit_icall_hash)
3867                 aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
3868         g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
3869 }
3870
3871 /*
3872  * load_function_full:
3873  *
3874  *   Load the function named NAME from the aot image. 
3875  */
3876 static gpointer
3877 load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
3878 {
3879         char *symbol;
3880         guint8 *p;
3881         int n_patches, pindex;
3882         MonoMemPool *mp;
3883         gpointer code;
3884         guint32 info_offset;
3885
3886         /* Load the code */
3887
3888         symbol = g_strdup_printf ("%s", name);
3889         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
3890         g_free (symbol);
3891         if (!code)
3892                 g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
3893
3894         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
3895
3896         /* Load info */
3897
3898         symbol = g_strdup_printf ("%s_p", name);
3899         find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
3900         g_free (symbol);
3901         if (!p)
3902                 /* Nothing to patch */
3903                 return code;
3904
3905         info_offset = *(guint32*)p;
3906         if (out_tinfo) {
3907                 MonoTrampInfo *tinfo;
3908                 guint32 code_size, uw_info_len, uw_offset;
3909                 guint8 *uw_info;
3910                 /* Construct a MonoTrampInfo from the data in the AOT image */
3911
3912                 p += sizeof (guint32);
3913                 code_size = *(guint32*)p;
3914                 p += sizeof (guint32);
3915                 uw_offset = *(guint32*)p;
3916                 uw_info = amodule->unwind_info + uw_offset;
3917                 uw_info_len = decode_value (uw_info, &uw_info);
3918
3919                 tinfo = g_new0 (MonoTrampInfo, 1);
3920                 tinfo->code = code;
3921                 tinfo->code_size = code_size;
3922                 tinfo->uw_info = uw_info;
3923                 tinfo->uw_info_len = uw_info_len;
3924
3925                 *out_tinfo = tinfo;
3926         }
3927
3928         p = amodule->blob + info_offset;
3929
3930         /* Similar to mono_aot_load_method () */
3931
3932         n_patches = decode_value (p, &p);
3933
3934         if (n_patches) {
3935                 MonoJumpInfo *patches;
3936                 guint32 *got_slots;
3937
3938                 mp = mono_mempool_new ();
3939
3940                 patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
3941                 g_assert (patches);
3942
3943                 for (pindex = 0; pindex < n_patches; ++pindex) {
3944                         MonoJumpInfo *ji = &patches [pindex];
3945                         gpointer target;
3946
3947                         if (amodule->got [got_slots [pindex]])
3948                                 continue;
3949
3950                         /*
3951                          * When this code is executed, the runtime may not be initalized yet, so
3952                          * resolve the patch info by hand.
3953                          */
3954                         if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
3955                                 if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
3956                                         target = mono_get_lmf_addr;
3957                                 } else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
3958                                         target = mono_thread_force_interruption_checkpoint;
3959                                 } else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
3960                                         target = mono_exception_from_token;
3961                                 } else if (!strcmp (ji->data.name, "mono_throw_exception")) {
3962                                         target = mono_get_throw_exception ();
3963                                 } else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
3964                                         int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
3965                                         target = (gpointer)mono_get_trampoline_func (tramp_type2);
3966                                 } else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
3967                                         /* atoll is needed because the the offset is unsigned */
3968                                         guint32 slot;
3969                                         int res;
3970
3971                                         res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
3972                                         g_assert (res == 1);
3973                                         target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
3974                                         target = mono_create_ftnptr_malloc (target);
3975                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
3976                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
3977                                         target = mono_create_ftnptr_malloc (target);
3978                                 } else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
3979                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
3980                                         target = mono_create_ftnptr_malloc (target);
3981                                 } else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
3982                                         target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
3983                                         target = mono_create_ftnptr_malloc (target);
3984                                 } else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
3985                                         target = mono_thread_get_and_clear_pending_exception;
3986                                 } else if (strstr (ji->data.name, "generic_trampoline_")) {
3987                                         target = mono_aot_get_trampoline (ji->data.name);
3988                                 } else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
3989                                         /* Registered by mono_arch_init () */
3990                                         target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
3991                                 } else {
3992                                         fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
3993                                         g_assert_not_reached ();
3994                                         target = NULL;
3995                                 }
3996                         } else {
3997                                 /* Hopefully the code doesn't have patches which need method or 
3998                                  * domain to be set.
3999                                  */
4000                                 target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
4001                                 g_assert (target);
4002                         }
4003
4004                         amodule->got [got_slots [pindex]] = target;
4005                 }
4006
4007                 g_free (got_slots);
4008
4009                 mono_mempool_destroy (mp);
4010         }
4011
4012         return code;
4013 }
4014
4015 static gpointer
4016 load_function (MonoAotModule *amodule, const char *name)
4017 {
4018         return load_function_full (amodule, name, NULL);
4019 }
4020
4021 /*
4022  * Return the trampoline identified by NAME from the mscorlib AOT file.
4023  * On ppc64, this returns a function descriptor.
4024  */
4025 gpointer
4026 mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
4027 {
4028         MonoImage *image;
4029         MonoAotModule *amodule;
4030
4031         image = mono_defaults.corlib;
4032         g_assert (image);
4033
4034         amodule = image->aot_module;
4035         g_assert (amodule);
4036
4037         return mono_create_ftnptr_malloc (load_function_full (amodule, name, out_tinfo));
4038 }
4039
4040 gpointer
4041 mono_aot_get_trampoline (const char *name)
4042 {
4043         return mono_aot_get_trampoline_full (name, NULL);
4044 }
4045
4046 #ifdef MONOTOUCH
4047 #include <mach/mach.h>
4048
4049 static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
4050 /* these sizes are for ARM code, parametrize if porting to other architectures (see arch_emit_specific_trampoline_pages)
4051  * trampoline size is assumed to be 8 bytes below as well (8 is the minimum for 32 bit archs, since we need to store
4052  * two pointers for trampoline in the data page).
4053  * the minimum for the common code must be at least sizeof(TrampolinePage), since we store the page info at the
4054  * beginning of the data page.
4055  */
4056 static const int trampolines_pages_code_offsets [MONO_AOT_TRAMP_NUM] = {16, 16, 72, 16};
4057
4058 static unsigned char*
4059 get_new_trampoline_from_page (int tramp_type)
4060 {
4061         MonoAotModule *amodule;
4062         MonoImage *image;
4063         TrampolinePage *page;
4064         int count;
4065         void *tpage;
4066         vm_address_t addr, taddr;
4067         kern_return_t ret;
4068         vm_prot_t prot, max_prot;
4069         int psize;
4070         unsigned char *code;
4071
4072         mono_aot_page_lock ();
4073         page = trampoline_pages [tramp_type];
4074         if (page && page->trampolines < page->trampolines_end) {
4075                 code = page->trampolines;
4076                 page->trampolines += 8;
4077                 mono_aot_page_unlock ();
4078                 return code;
4079         }
4080         mono_aot_page_unlock ();
4081         psize = mono_pagesize ();
4082         /* the trampoline template page is in the mscorlib module */
4083         image = mono_defaults.corlib;
4084         g_assert (image);
4085
4086         amodule = image->aot_module;
4087         g_assert (amodule);
4088
4089         if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
4090                 tpage = load_function (amodule, "specific_trampolines_page");
4091         else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
4092                 tpage = load_function (amodule, "rgctx_trampolines_page");
4093         else if (tramp_type == MONO_AOT_TRAMP_IMT_THUNK)
4094                 tpage = load_function (amodule, "imt_trampolines_page");
4095         else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
4096                 tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
4097         else
4098                 g_error ("Incorrect tramp type for trampolines page");
4099         g_assert (tpage);
4100         /*g_warning ("loaded trampolines page at %x", tpage);*/
4101
4102         /* avoid the unlikely case of looping forever */
4103         count = 40;
4104         page = NULL;
4105         while (page == NULL && count-- > 0) {
4106                 addr = 0;
4107                 /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
4108                  * while the second will contain the trampolines.
4109                  */
4110                 ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
4111                 if (ret != KERN_SUCCESS) {
4112                         g_error ("Cannot allocate memory for trampolines: %d", ret);
4113                         break;
4114                 }
4115                 /*g_warning ("allocated trampoline double page at %x", addr);*/
4116                 /* replace the second page with a remapped trampoline page */
4117                 taddr = addr + psize;
4118                 vm_deallocate (mach_task_self (), taddr, psize);
4119                 ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
4120                 if (ret != KERN_SUCCESS) {
4121                         /* someone else got the page, try again  */
4122                         vm_deallocate (mach_task_self (), addr, psize);
4123                         continue;
4124                 }
4125                 /*g_warning ("remapped trampoline page at %x", taddr);*/
4126
4127                 mono_aot_page_lock ();
4128                 page = trampoline_pages [tramp_type];
4129                 /* some other thread already allocated, so use that to avoid wasting memory */
4130                 if (page && page->trampolines < page->trampolines_end) {
4131                         code = page->trampolines;
4132                         page->trampolines += 8;
4133                         mono_aot_page_unlock ();
4134                         vm_deallocate (mach_task_self (), addr, psize);
4135                         vm_deallocate (mach_task_self (), taddr, psize);
4136                         return code;
4137                 }
4138                 page = (TrampolinePage*)addr;
4139                 page->next = trampoline_pages [tramp_type];
4140                 trampoline_pages [tramp_type] = page;
4141                 page->trampolines = (void*)(taddr + trampolines_pages_code_offsets [tramp_type]);
4142                 page->trampolines_end = (void*)(taddr + psize);
4143                 code = page->trampolines;
4144                 page->trampolines += 8;
4145                 mono_aot_page_unlock ();
4146                 return code;
4147         }
4148         g_error ("Cannot allocate more trampoline pages: %d", ret);
4149         return NULL;
4150 }
4151
4152 #else
4153 static unsigned char*
4154 get_new_trampoline_from_page (int tramp_type)
4155 {
4156         g_error ("Page trampolines not supported.");
4157         return NULL;
4158 }
4159 #endif
4160
4161
4162 static gpointer
4163 get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
4164 {
4165         void *code;
4166         gpointer *data;
4167
4168         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
4169
4170         data = (gpointer*)((char*)code - mono_pagesize ());
4171         data [0] = arg;
4172         data [1] = tramp;
4173         /*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4174         return code;
4175
4176 }
4177
4178 static gpointer
4179 get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
4180 {
4181         void *code;
4182         gpointer *data;
4183
4184         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
4185
4186         data = (gpointer*)((char*)code - mono_pagesize ());
4187         data [0] = arg;
4188         data [1] = tramp;
4189         /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4190         return code;
4191
4192 }
4193
4194 static gpointer
4195 get_new_imt_trampoline_from_page (gpointer arg)
4196 {
4197         void *code;
4198         gpointer *data;
4199
4200         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT_THUNK);
4201
4202         data = (gpointer*)((char*)code - mono_pagesize ());
4203         data [0] = arg;
4204         /*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
4205         return code;
4206
4207 }
4208
4209 static gpointer
4210 get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
4211 {
4212         void *code;
4213         gpointer *data;
4214
4215         code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
4216
4217         data = (gpointer*)((char*)code - mono_pagesize ());
4218         data [0] = arg;
4219         data [1] = tramp;
4220         /*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
4221         return code;
4222 }
4223
4224 /* Return a given kind of trampoline */
4225 static gpointer
4226 get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
4227 {
4228         MonoAotModule *amodule;
4229         int index, tramp_size;
4230         MonoImage *image;
4231
4232         /* Currently, we keep all trampolines in the mscorlib AOT image */
4233         image = mono_defaults.corlib;
4234         g_assert (image);
4235
4236         mono_aot_lock ();
4237
4238         amodule = image->aot_module;
4239         g_assert (amodule);
4240
4241         *out_amodule = amodule;
4242
4243 #ifdef MONOTOUCH
4244 #define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instruction on how to fix this condition"
4245 #else
4246 #define MONOTOUCH_TRAMPOLINES_ERROR ""
4247 #endif
4248         if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
4249                 g_error ("Ran out of trampolines of type %d in '%s' (%d)%s\n", 
4250                                  tramp_type, image->name, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
4251         }
4252         index = amodule->trampoline_index [tramp_type] ++;
4253
4254         mono_aot_unlock ();
4255
4256         *got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
4257
4258         tramp_size = amodule->info.trampoline_size [tramp_type];
4259
4260         if (out_tramp_size)
4261                 *out_tramp_size = tramp_size;
4262
4263         return amodule->trampolines [tramp_type] + (index * tramp_size);
4264 }
4265
4266 /*
4267  * Return a specific trampoline from the AOT file.
4268  */
4269 gpointer
4270 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4271 {
4272         MonoAotModule *amodule;
4273         guint32 got_offset, tramp_size;
4274         guint8 *code, *tramp;
4275         static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
4276         static gboolean inited;
4277         static guint32 num_trampolines;
4278
4279         if (!inited) {
4280                 mono_aot_lock ();
4281
4282                 if (!inited) {
4283                         mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
4284                         inited = TRUE;
4285                 }
4286
4287                 mono_aot_unlock ();
4288         }
4289
4290         num_trampolines ++;
4291
4292         if (!generic_trampolines [tramp_type]) {
4293                 char *symbol;
4294
4295                 symbol = mono_get_generic_trampoline_name (tramp_type);
4296                 generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
4297                 g_free (symbol);
4298         }
4299
4300         tramp = generic_trampolines [tramp_type];
4301         g_assert (tramp);
4302
4303         if (USE_PAGE_TRAMPOLINES) {
4304                 code = get_new_specific_trampoline_from_page (tramp, arg1);
4305                 tramp_size = 8;
4306         } else {
4307                 code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
4308
4309                 amodule->got [got_offset] = tramp;
4310                 amodule->got [got_offset + 1] = arg1;
4311         }
4312
4313         if (code_len)
4314                 *code_len = tramp_size;
4315
4316         return code;
4317 }
4318
4319 gpointer
4320 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4321 {
4322         MonoAotModule *amodule;
4323         guint8 *code;
4324         guint32 got_offset;
4325
4326         if (USE_PAGE_TRAMPOLINES) {
4327                 code = get_new_rgctx_trampoline_from_page (addr, ctx);
4328         } else {
4329                 code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
4330
4331                 amodule->got [got_offset] = ctx;
4332                 amodule->got [got_offset + 1] = addr; 
4333         }
4334
4335         /* The caller expects an ftnptr */
4336         return mono_create_ftnptr (mono_domain_get (), code);
4337 }
4338
4339 gpointer
4340 mono_aot_get_unbox_trampoline (MonoMethod *method)
4341 {
4342         guint32 method_index = mono_metadata_token_index (method->token) - 1;
4343         MonoAotModule *amodule;
4344         gpointer code;
4345         guint32 *ut, *ut_end, *entry;
4346         int low, high, entry_index;
4347
4348         if (method->is_inflated && !mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE)) {
4349                 method_index = find_extra_method (method, &amodule);
4350                 if (method_index == 0xffffff && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, TRUE)) {
4351                         MonoMethod *shared = mini_get_shared_method_full (method, TRUE, TRUE);
4352                         method_index = find_extra_method (shared, &amodule);
4353                 }
4354                 g_assert (method_index != 0xffffff);
4355         } else {
4356                 amodule = method->klass->image->aot_module;
4357                 g_assert (amodule);
4358         }
4359
4360         ut = amodule->unbox_trampolines;
4361         ut_end = amodule->unbox_trampolines_end;
4362
4363         /* Do a binary search in the sorted table */
4364         code = NULL;
4365         low = 0;
4366         high = (ut_end - ut) / 2;
4367         while (low < high) {
4368                 entry_index = (low + high) / 2;
4369                 entry = &ut [(entry_index * 2)];
4370                 if (entry [0] < method_index) {
4371                         low = entry_index + 1;
4372                 } else if (entry [0] > method_index) {
4373                         high = entry_index;
4374                 } else {
4375                         if (amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES)
4376                                 code = (gpointer)(gsize)entry [1];
4377                         else
4378                                 code = amodule->code + entry [1];
4379                         break;
4380                 }
4381         }
4382         g_assert (code);
4383
4384         /* The caller expects an ftnptr */
4385         return mono_create_ftnptr (mono_domain_get (), code);
4386 }
4387
4388 gpointer
4389 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4390 {
4391         char *symbol;
4392         gpointer code;
4393         MonoAotModule *amodule = mono_defaults.corlib->aot_module;
4394         guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
4395         static int count = 0;
4396
4397         count ++;
4398         if (index >= amodule->info.num_rgctx_fetch_trampolines) {
4399                 static gpointer addr;
4400                 gpointer *info;
4401
4402                 /*
4403                  * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
4404                  */
4405                 if (!addr)
4406                         addr = load_function (amodule, "rgctx_fetch_trampoline_general");
4407                 info = mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
4408                 info [0] = GUINT_TO_POINTER (slot);
4409                 info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
4410                 code = mono_aot_get_static_rgctx_trampoline (info, addr);
4411                 return mono_create_ftnptr (mono_domain_get (), code);
4412         }
4413
4414         symbol = mono_get_rgctx_fetch_trampoline_name (slot);
4415         code = load_function (mono_defaults.corlib->aot_module, symbol);
4416         g_free (symbol);
4417         /* The caller expects an ftnptr */
4418         return mono_create_ftnptr (mono_domain_get (), code);
4419 }
4420
4421 gpointer
4422 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4423 {
4424         guint32 got_offset;
4425         gpointer code;
4426         gpointer *buf;
4427         int i, index, real_count;
4428         MonoAotModule *amodule;
4429
4430         real_count = 0;
4431         for (i = 0; i < count; ++i) {
4432                 MonoIMTCheckItem *item = imt_entries [i];
4433
4434                 if (item->is_equals)
4435                         real_count ++;
4436         }
4437
4438         /* Save the entries into an array */
4439         buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
4440         index = 0;
4441         for (i = 0; i < count; ++i) {
4442                 MonoIMTCheckItem *item = imt_entries [i];               
4443
4444                 if (!item->is_equals)
4445                         continue;
4446
4447                 g_assert (item->key);
4448
4449                 buf [(index * 2)] = item->key;
4450                 if (item->has_target_code) {
4451                         gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
4452                         *p = item->value.target_code;
4453                         buf [(index * 2) + 1] = p;
4454                 } else {
4455                         buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
4456                 }
4457                 index ++;
4458         }
4459         buf [(index * 2)] = NULL;
4460         buf [(index * 2) + 1] = fail_tramp;
4461         
4462         if (USE_PAGE_TRAMPOLINES) {
4463                 code = get_new_imt_trampoline_from_page (buf);
4464         } else {
4465                 code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);
4466
4467                 amodule->got [got_offset] = buf;
4468         }
4469
4470         return code;
4471 }
4472
4473 gpointer
4474 mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
4475 {
4476         MonoAotModule *amodule;
4477         guint8 *code;
4478         guint32 got_offset;
4479
4480         if (USE_PAGE_TRAMPOLINES) {
4481                 code = get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
4482         } else {
4483                 code = get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
4484
4485                 amodule->got [got_offset] = arg;
4486                 amodule->got [got_offset + 1] = addr; 
4487         }
4488
4489         /* The caller expects an ftnptr */
4490         return mono_create_ftnptr (mono_domain_get (), code);
4491 }
4492  
4493 /*
4494  * mono_aot_set_make_unreadable:
4495  *
4496  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
4497  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
4498  */
4499 void
4500 mono_aot_set_make_unreadable (gboolean unreadable)
4501 {
4502         static int inited;
4503
4504         make_unreadable = unreadable;
4505
4506         if (make_unreadable && !inited) {
4507                 mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
4508         }               
4509 }
4510
4511 typedef struct {
4512         MonoAotModule *module;
4513         guint8 *ptr;
4514 } FindMapUserData;
4515
4516 static void
4517 find_map (gpointer key, gpointer value, gpointer user_data)
4518 {
4519         MonoAotModule *module = (MonoAotModule*)value;
4520         FindMapUserData *data = (FindMapUserData*)user_data;
4521
4522         if (!data->module)
4523                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
4524                         data->module = module;
4525 }
4526
4527 static MonoAotModule*
4528 find_module_for_addr (void *ptr)
4529 {
4530         FindMapUserData data;
4531
4532         if (!make_unreadable)
4533                 return NULL;
4534
4535         data.module = NULL;
4536         data.ptr = (guint8*)ptr;
4537
4538         mono_aot_lock ();
4539         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
4540         mono_aot_unlock ();
4541
4542         return data.module;
4543 }
4544
4545 /*
4546  * mono_aot_is_pagefault:
4547  *
4548  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
4549  * within memory allocated by this module.
4550  */
4551 gboolean
4552 mono_aot_is_pagefault (void *ptr)
4553 {
4554         if (!make_unreadable)
4555                 return FALSE;
4556
4557         /* 
4558          * Not signal safe, but SIGSEGV's are synchronous, and
4559          * this is only turned on by a MONO_DEBUG option.
4560          */
4561         return find_module_for_addr (ptr) != NULL;
4562 }
4563
4564 /*
4565  * mono_aot_handle_pagefault:
4566  *
4567  *   Handle a pagefault caused by an unreadable page by making it readable again.
4568  */
4569 void
4570 mono_aot_handle_pagefault (void *ptr)
4571 {
4572 #ifndef PLATFORM_WIN32
4573         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
4574         int res;
4575
4576         mono_aot_lock ();
4577         res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
4578         g_assert (res == 0);
4579
4580         n_pagefaults ++;
4581         mono_aot_unlock ();
4582 #endif
4583 }
4584
4585 #else
4586 /* AOT disabled */
4587
4588 void
4589 mono_aot_init (void)
4590 {
4591 }
4592
4593 gpointer
4594 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
4595 {
4596         return NULL;
4597 }
4598
4599 gboolean
4600 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
4601 {
4602         return FALSE;
4603 }
4604
4605 gboolean
4606 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
4607 {
4608         return FALSE;
4609 }
4610
4611 gboolean
4612 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
4613 {
4614         return FALSE;
4615 }
4616
4617 MonoJitInfo *
4618 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
4619 {
4620         return NULL;
4621 }
4622
4623 gpointer
4624 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
4625 {
4626         return NULL;
4627 }
4628
4629 guint8*
4630 mono_aot_get_plt_entry (guint8 *code)
4631 {
4632         return NULL;
4633 }
4634
4635 gpointer
4636 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
4637 {
4638         return NULL;
4639 }
4640
4641 void
4642 mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
4643 {
4644 }
4645
4646 gpointer
4647 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
4648 {
4649         return NULL;
4650 }
4651
4652 guint32
4653 mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
4654 {
4655         g_assert_not_reached ();
4656
4657         return 0;
4658 }
4659
4660 gpointer
4661 mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
4662 {
4663         g_assert_not_reached ();
4664         return NULL;
4665 }
4666
4667 gpointer
4668 mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
4669 {
4670         g_assert_not_reached ();
4671         return NULL;
4672 }
4673
4674 gpointer
4675 mono_aot_get_trampoline (const char *name)
4676 {
4677         g_assert_not_reached ();
4678         return NULL;
4679 }
4680
4681 gpointer
4682 mono_aot_get_unbox_trampoline (MonoMethod *method)
4683 {
4684         g_assert_not_reached ();
4685         return NULL;
4686 }
4687
4688 gpointer
4689 mono_aot_get_lazy_fetch_trampoline (guint32 slot)
4690 {
4691         g_assert_not_reached ();
4692         return NULL;
4693 }
4694
4695 gpointer
4696 mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
4697 {
4698         g_assert_not_reached ();
4699         return NULL;
4700 }       
4701
4702 guint8*
4703 mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
4704 {
4705         g_assert_not_reached ();
4706         return NULL;
4707 }
4708
4709 void
4710 mono_aot_register_jit_icall (const char *name, gpointer addr)
4711 {
4712 }
4713
4714 #endif