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