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