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