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