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