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