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