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