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