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