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