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