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