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