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