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