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