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