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