for TARGET_J2EE only:
[mono.git] / mono / mini / aot-runtime.c
1 /*
2  * aot.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 #ifndef PLATFORM_WIN32
19 #include <sys/mman.h>
20 #else
21 #include <winsock2.h>
22 #include <windows.h>
23 #endif
24
25 #ifdef HAVE_EXECINFO_H
26 #include <execinfo.h>
27 #endif
28
29 #include <errno.h>
30 #include <sys/stat.h>
31 #include <limits.h>    /* for PAGESIZE */
32 #ifndef PAGESIZE
33 #define PAGESIZE 4096
34 #endif
35
36 #ifdef HAVE_SYS_WAIT_H
37 #include <sys/wait.h>  /* for WIFEXITED, WEXITSTATUS */
38 #endif
39
40 #include <mono/metadata/tabledefs.h>
41 #include <mono/metadata/class.h>
42 #include <mono/metadata/object.h>
43 #include <mono/metadata/tokentype.h>
44 #include <mono/metadata/appdomain.h>
45 #include <mono/metadata/debug-helpers.h>
46 #include <mono/metadata/assembly.h>
47 #include <mono/metadata/metadata-internals.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/gc-internal.h>
50 #include <mono/utils/mono-logger.h>
51 #include "mono/utils/mono-compiler.h"
52
53 #include "mini.h"
54 #include "version.h"
55
56 #ifndef DISABLE_AOT
57
58 #ifdef PLATFORM_WIN32
59 #define SHARED_EXT ".dll"
60 #elif defined(__ppc__) && defined(__MACH__)
61 #define SHARED_EXT ".dylib"
62 #else
63 #define SHARED_EXT ".so"
64 #endif
65
66 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
67 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
68
69 typedef struct MonoAotModule {
70         char *aot_name;
71         /* Optimization flags used to compile the module */
72         guint32 opts;
73         /* Pointer to the Global Offset Table */
74         gpointer *got;
75         guint32 got_size;
76         GHashTable *name_cache;
77         MonoAssemblyName *image_names;
78         char **image_guids;
79         MonoImage **image_table;
80         guint32 image_table_len;
81         gboolean out_of_date;
82         gboolean plt_inited;
83         guint8 *mem_begin;
84         guint8 *mem_end;
85         guint8 *code;
86         guint8 *code_end;
87         guint8 *plt;
88         guint8 *plt_end;
89         guint8 *plt_info;
90         guint8 *plt_jump_table;
91         guint32 plt_jump_table_size;
92         guint32 *code_offsets;
93         guint8 *method_info;
94         guint32 *method_info_offsets;
95         guint8 *got_info;
96         guint32 *got_info_offsets;
97         guint8 *ex_info;
98         guint32 *ex_info_offsets;
99         guint32 *method_order;
100         guint32 *method_order_end;
101         guint8 *class_info;
102         guint32 *class_info_offsets;
103         guint32 *methods_loaded;
104         guint16 *class_name_table;
105 } MonoAotModule;
106
107 static GHashTable *aot_modules;
108 #define mono_aot_lock() EnterCriticalSection (&aot_mutex)
109 #define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
110 static CRITICAL_SECTION aot_mutex;
111
112 /*
113  * Disabling this will make a copy of the loaded code and use the copy instead 
114  * of the original. This will place the caller and the callee close to each 
115  * other in memory, possibly improving cache behavior. Since the original
116  * code is in copy-on-write memory, this will not increase the memory usage
117  * of the runtime.
118  */
119 static gboolean use_loaded_code = TRUE;
120
121 /*
122  * Whenever to AOT compile loaded assemblies on demand and store them in
123  * a cache under $HOME/.mono/aot-cache.
124  */
125 static gboolean use_aot_cache = FALSE;
126
127 /*
128  * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
129  * use_aot_cache is TRUE.
130  */
131 static gboolean spawn_compiler = TRUE;
132
133 /* For debugging */
134 static gint32 mono_last_aot_method = -1;
135
136 static gboolean make_unreadable = FALSE;
137 static guint32 n_pagefaults = 0;
138 static guint32 name_table_accesses = 0;
139
140 /* Used to speed-up find_aot_module () */
141 static gsize aot_code_low_addr = (gssize)-1;
142 static gsize aot_code_high_addr = 0;
143
144 static gpointer
145 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info);
146
147 static void
148 init_plt (MonoAotModule *info);
149
150 static inline gboolean 
151 is_got_patch (MonoJumpInfoType patch_type)
152 {
153         return TRUE;
154 }
155
156 /*****************************************************/
157 /*                 AOT RUNTIME                       */
158 /*****************************************************/
159
160 static MonoImage *
161 load_image (MonoAotModule *module, int index)
162 {
163         MonoAssembly *assembly;
164         MonoImageOpenStatus status;
165
166         g_assert (index < module->image_table_len);
167
168         if (module->image_table [index])
169                 return module->image_table [index];
170         if (module->out_of_date)
171                 return NULL;
172
173         assembly = mono_assembly_load (&module->image_names [index], NULL, &status);
174         if (!assembly) {
175                 module->out_of_date = TRUE;
176                 return NULL;
177         }
178
179         if (strcmp (assembly->image->guid, module->image_guids [index])) {
180                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date (Older than dependency %s).\n", module->aot_name, module->image_names [index].name);
181                 module->out_of_date = TRUE;
182                 return NULL;
183         }
184
185         module->image_table [index] = assembly->image;
186         return assembly->image;
187 }
188
189
190 static inline gint32
191 decode_value (guint8 *ptr, guint8 **rptr)
192 {
193         guint8 b = *ptr;
194         gint32 len;
195         
196         if ((b & 0x80) == 0){
197                 len = b;
198                 ++ptr;
199         } else if ((b & 0x40) == 0){
200                 len = ((b & 0x3f) << 8 | ptr [1]);
201                 ptr += 2;
202         } else if (b != 0xff) {
203                 len = ((b & 0x1f) << 24) |
204                         (ptr [1] << 16) |
205                         (ptr [2] << 8) |
206                         ptr [3];
207                 ptr += 4;
208         }
209         else {
210                 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
211                 ptr += 5;
212         }
213         if (rptr)
214                 *rptr = ptr;
215
216         //printf ("DECODE: %d.\n", len);
217         return len;
218 }
219
220 static MonoClass*
221 decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
222 {
223         MonoImage *image;
224         MonoClass *klass, *eklass;
225         guint32 token, rank;
226
227         token = decode_value (buf, &buf);
228         if (token == 0) {
229                 *endbuf = buf;
230                 return NULL;
231         }
232         if (mono_metadata_token_table (token) == 0) {
233                 image = load_image (module, decode_value (buf, &buf));
234                 if (!image)
235                         return NULL;
236                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + token);
237         } else if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
238                 if (token == MONO_TOKEN_TYPE_SPEC) {
239                         MonoClass *gclass;
240                         int i;
241                         MonoGenericContext ctx;
242                         MonoGenericInst inst;
243
244                         gclass = decode_klass_ref (module, buf, &buf);
245                         g_assert (gclass->generic_container);
246
247                         memset (&ctx, 0, sizeof (ctx));
248                         memset (&inst, 0, sizeof (inst));
249                         ctx.class_inst = &inst;
250                         inst.type_argc = decode_value (buf, &buf);
251                         inst.type_argv = g_new0 (MonoType*, inst.type_argc);
252                         for (i = 0; i < inst.type_argc; ++i) {
253                                 MonoClass *pclass = decode_klass_ref (module, buf, &buf);
254                                 if (!pclass) {
255                                         g_free (inst.type_argv);
256                                         return NULL;
257                                 }
258                                 inst.type_argv [i] = &pclass->byval_arg;
259                         }
260                         klass = mono_class_from_mono_type (mono_class_inflate_generic_type (&gclass->byval_arg, &ctx));
261                 } else {
262                         image = load_image (module, decode_value (buf, &buf));
263                         if (!image)
264                                 return NULL;
265                         klass = mono_class_get (image, token);
266                 }
267         } else if (token == MONO_TOKEN_TYPE_DEF) {
268                 /* Array */
269                 image = load_image (module, decode_value (buf, &buf));
270                 if (!image)
271                         return NULL;
272                 rank = decode_value (buf, &buf);
273                 eklass = decode_klass_ref (module, buf, &buf);
274                 klass = mono_array_class_get (eklass, rank);
275         } else {
276                 g_assert_not_reached ();
277         }
278         g_assert (klass);
279         mono_class_init (klass);
280
281         *endbuf = buf;
282         return klass;
283 }
284
285 static MonoClassField*
286 decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
287 {
288         MonoClass *klass = decode_klass_ref (module, buf, &buf);
289         guint32 token;
290
291         if (!klass)
292                 return NULL;
293
294         token = MONO_TOKEN_FIELD_DEF + decode_value (buf, &buf);
295
296         *endbuf = buf;
297
298         return mono_class_get_field (klass, token);
299 }
300
301 static inline MonoImage*
302 decode_method_ref (MonoAotModule *module, guint32 *token, guint8 *buf, guint8 **endbuf)
303 {
304         guint32 image_index, value;
305         MonoImage *image;
306
307         value = decode_value (buf, &buf);
308         image_index = value >> 24;
309         *token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
310
311         if (image_index == 255) {
312                 /* Methodspec */
313                 image_index = decode_value (buf, &buf);
314                 *token = decode_value (buf, &buf);
315         }
316
317         *endbuf = buf;
318
319         image = load_image (module, image_index);
320         if (!image)
321                 return NULL;
322         else
323                 return image;
324 }
325
326 G_GNUC_UNUSED
327 static void
328 make_writable (guint8* addr, guint32 len)
329 {
330 #ifndef PLATFORM_WIN32
331         guint8 *page_start;
332         int pages, err;
333
334         page_start = (guint8 *) (((gssize) (addr)) & ~ (PAGESIZE - 1));
335         pages = (addr + len - page_start + PAGESIZE - 1) / PAGESIZE;
336         err = mprotect (page_start, pages * PAGESIZE, PROT_READ | PROT_WRITE | PROT_EXEC);
337         g_assert (err == 0);
338 #else
339         {
340                 DWORD oldp;
341                 g_assert (VirtualProtect (addr, len, PAGE_EXECUTE_READWRITE, &oldp) != 0);
342         }
343 #endif
344 }
345
346 static void
347 create_cache_structure (void)
348 {
349         const char *home;
350         char *tmp;
351         int err;
352
353         home = g_get_home_dir ();
354         if (!home)
355                 return;
356
357         tmp = g_build_filename (home, ".mono", NULL);
358         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
359                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
360 #ifdef PLATFORM_WIN32
361                 err = mkdir (tmp);
362 #else
363                 err = mkdir (tmp, 0777);
364 #endif
365                 if (err) {
366                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
367                         g_free (tmp);
368                         return;
369                 }
370         }
371         g_free (tmp);
372         tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
373         if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
374                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
375 #ifdef PLATFORM_WIN32
376                 err = mkdir (tmp);
377 #else
378                 err = mkdir (tmp, 0777);
379 #endif
380                 if (err) {
381                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
382                         g_free (tmp);
383                         return;
384                 }
385         }
386         g_free (tmp);
387 }
388
389 /*
390  * load_aot_module_from_cache:
391  *
392  *  Experimental code to AOT compile loaded assemblies on demand. 
393  *
394  * FIXME: 
395  * - Add environment variable MONO_AOT_CACHE_OPTIONS
396  * - Add options for controlling the cache size
397  * - Handle full cache by deleting old assemblies lru style
398  * - Add options for excluding assemblies during development
399  * - Maybe add a threshold after an assembly is AOT compiled
400  * - invoking a new mono process is a security risk
401  * - recompile the AOT module if one of its dependencies changes
402  */
403 static MonoDl*
404 load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
405 {
406         char *fname, *cmd, *tmp2, *aot_options;
407         const char *home;
408         MonoDl *module;
409         gboolean res;
410         gchar *out, *err;
411         gint exit_status;
412
413         *aot_name = NULL;
414
415         if (assembly->image->dynamic)
416                 return NULL;
417
418         create_cache_structure ();
419
420         home = g_get_home_dir ();
421
422         tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
423         fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
424         *aot_name = fname;
425         g_free (tmp2);
426
427         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
428         module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
429
430         if (!module) {
431                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");
432
433                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);
434
435                 aot_options = g_strdup_printf ("outfile=%s", fname);
436
437                 if (spawn_compiler) {
438                         /* FIXME: security */
439                         /* FIXME: Has to pass the assembly loading path to the child process */
440                         cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);
441
442                         res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);
443
444 #if !defined(PLATFORM_WIN32) && !defined(__ppc__) && !defined(__powerpc__)
445                         if (res) {
446                                 if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
447                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
448                                 else
449                                         mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
450                                 g_free (out);
451                                 g_free (err);
452                         }
453 #endif
454                         g_free (cmd);
455                 } else {
456                         res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
457                         if (!res) {
458                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
459                         } else {
460                                 mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
461                         }
462                 }
463
464                 module = mono_dl_open (fname, MONO_DL_LAZY, NULL);
465
466                 g_free (aot_options);
467         }
468
469         return module;
470 }
471
472 static void
473 load_aot_module (MonoAssembly *assembly, gpointer user_data)
474 {
475         char *aot_name;
476         MonoAotModule *info;
477         gboolean usable = TRUE;
478         char *saved_guid = NULL;
479         char *aot_version = NULL;
480         char *runtime_version;
481         char *opt_flags = NULL;
482         gpointer *plt_jump_table_addr = NULL;
483         guint32 *plt_jump_table_size = NULL;
484         gpointer *got_addr = NULL;
485         gpointer *got = NULL;
486         guint32 *got_size_ptr = NULL;
487         int i;
488
489         if (mono_compile_aot)
490                 return;
491
492         if (assembly->aot_module)
493                 /* 
494                  * Already loaded. This can happen because the assembly loading code might invoke
495                  * the assembly load hooks multiple times for the same assembly.
496                  */
497                 return;
498
499         if (use_aot_cache)
500                 assembly->aot_module = load_aot_module_from_cache (assembly, &aot_name);
501         else {
502                 char *err;
503                 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
504
505                 assembly->aot_module = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
506
507                 if (!assembly->aot_module) {
508                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
509                         g_free (err);
510                 }
511         }
512
513         if (!assembly->aot_module) {
514                 g_free (aot_name);
515                 return;
516         }
517
518         mono_dl_symbol (assembly->aot_module, "mono_assembly_guid", (gpointer *) &saved_guid);
519         mono_dl_symbol (assembly->aot_module, "mono_aot_version", (gpointer *) &aot_version);
520         mono_dl_symbol (assembly->aot_module, "mono_aot_opt_flags", (gpointer *)&opt_flags);
521         mono_dl_symbol (assembly->aot_module, "mono_runtime_version", (gpointer *)&runtime_version);
522
523         if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
524                 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);
525                 usable = FALSE;
526         }
527         else {
528                 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
529                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
530                         usable = FALSE;
531                 }
532         }
533
534         if (!runtime_version || ((strlen (runtime_version) > 0 && strcmp (runtime_version, FULL_VERSION)))) {
535                 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, FULL_VERSION);
536                 usable = FALSE;
537         }
538
539         if (!usable) {
540                 g_free (aot_name);
541                 mono_dl_close (assembly->aot_module);
542                 assembly->aot_module = NULL;
543                 return;
544         }
545
546         mono_dl_symbol (assembly->aot_module, "got_addr", (gpointer *)&got_addr);
547         g_assert (got_addr);
548         got = (gpointer*)*got_addr;
549         g_assert (got);
550         mono_dl_symbol (assembly->aot_module, "got_size", (gpointer *)&got_size_ptr);
551         g_assert (got_size_ptr);
552
553         info = g_new0 (MonoAotModule, 1);
554         info->aot_name = aot_name;
555         info->got = got;
556         info->got_size = *got_size_ptr;
557         info->got [0] = assembly->image;
558
559         sscanf (opt_flags, "%d", &info->opts);
560
561         /* Read image table */
562         {
563                 guint32 table_len, i;
564                 char *table = NULL;
565
566                 mono_dl_symbol (assembly->aot_module, "mono_image_table", (gpointer *)&table);
567                 g_assert (table);
568
569                 table_len = *(guint32*)table;
570                 table += sizeof (guint32);
571                 info->image_table = g_new0 (MonoImage*, table_len);
572                 info->image_names = g_new0 (MonoAssemblyName, table_len);
573                 info->image_guids = g_new0 (char*, table_len);
574                 info->image_table_len = table_len;
575                 for (i = 0; i < table_len; ++i) {
576                         MonoAssemblyName *aname = &(info->image_names [i]);
577
578                         aname->name = g_strdup (table);
579                         table += strlen (table) + 1;
580                         info->image_guids [i] = g_strdup (table);
581                         table += strlen (table) + 1;
582                         if (table [0] != 0)
583                                 aname->culture = g_strdup (table);
584                         table += strlen (table) + 1;
585                         memcpy (aname->public_key_token, table, strlen (table) + 1);
586                         table += strlen (table) + 1;                    
587
588                         table = ALIGN_PTR_TO (table, 8);
589                         aname->flags = *(guint32*)table;
590                         table += 4;
591                         aname->major = *(guint32*)table;
592                         table += 4;
593                         aname->minor = *(guint32*)table;
594                         table += 4;
595                         aname->build = *(guint32*)table;
596                         table += 4;
597                         aname->revision = *(guint32*)table;
598                         table += 4;
599                 }
600         }
601
602         /* Read method and method_info tables */
603         mono_dl_symbol (assembly->aot_module, "method_offsets", (gpointer*)&info->code_offsets);
604         mono_dl_symbol (assembly->aot_module, "methods", (gpointer*)&info->code);
605         mono_dl_symbol (assembly->aot_module, "methods_end", (gpointer*)&info->code_end);
606         mono_dl_symbol (assembly->aot_module, "method_info_offsets", (gpointer*)&info->method_info_offsets);
607         mono_dl_symbol (assembly->aot_module, "method_info", (gpointer*)&info->method_info);
608         mono_dl_symbol (assembly->aot_module, "ex_info_offsets", (gpointer*)&info->ex_info_offsets);
609         mono_dl_symbol (assembly->aot_module, "ex_info", (gpointer*)&info->ex_info);
610         mono_dl_symbol (assembly->aot_module, "method_order", (gpointer*)&info->method_order);
611         mono_dl_symbol (assembly->aot_module, "method_order_end", (gpointer*)&info->method_order_end);
612         mono_dl_symbol (assembly->aot_module, "class_info", (gpointer*)&info->class_info);
613         mono_dl_symbol (assembly->aot_module, "class_info_offsets", (gpointer*)&info->class_info_offsets);
614         mono_dl_symbol (assembly->aot_module, "class_name_table", (gpointer *)&info->class_name_table);
615         mono_dl_symbol (assembly->aot_module, "got_info", (gpointer*)&info->got_info);
616         mono_dl_symbol (assembly->aot_module, "got_info_offsets", (gpointer*)&info->got_info_offsets);
617         mono_dl_symbol (assembly->aot_module, "mem_end", (gpointer*)&info->mem_end);
618
619         info->mem_begin = info->code;
620
621         mono_dl_symbol (assembly->aot_module, "plt", (gpointer*)&info->plt);
622         mono_dl_symbol (assembly->aot_module, "plt_end", (gpointer*)&info->plt_end);
623         mono_dl_symbol (assembly->aot_module, "plt_info", (gpointer*)&info->plt_info);
624
625         mono_dl_symbol (assembly->aot_module, "plt_jump_table_addr", (gpointer *)&plt_jump_table_addr);
626         g_assert (plt_jump_table_addr);
627         info->plt_jump_table = (guint8*)*plt_jump_table_addr;
628         g_assert (info->plt_jump_table);
629
630         mono_dl_symbol (assembly->aot_module, "plt_jump_table_size", (gpointer *)&plt_jump_table_size);
631         g_assert (plt_jump_table_size);
632         info->plt_jump_table_size = *plt_jump_table_size;
633
634         if (make_unreadable) {
635 #ifndef PLATFORM_WIN32
636                 guint8 *addr;
637                 guint8 *page_start;
638                 int pages, err, len;
639
640                 addr = info->mem_begin;
641                 len = info->mem_end - info->mem_begin;
642
643                 /* Round down in both directions to avoid modifying data which is not ours */
644                 page_start = (guint8 *) (((gssize) (addr)) & ~ (PAGESIZE - 1)) + PAGESIZE;
645                 pages = ((addr + len - page_start + PAGESIZE - 1) / PAGESIZE) - 1;
646                 err = mprotect (page_start, pages * PAGESIZE, 0);
647                 g_assert (err == 0);
648 #endif
649         }
650
651         mono_aot_lock ();
652
653         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)info->code);
654         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)info->code_end);
655
656         g_hash_table_insert (aot_modules, assembly, info);
657         mono_aot_unlock ();
658
659         mono_jit_info_add_aot_module (assembly->image, info->code, info->code_end);
660
661         /*
662          * Since we store methoddef and classdef tokens when referring to methods/classes in
663          * referenced assemblies, we depend on the exact versions of the referenced assemblies.
664          * MS calls this 'hard binding'. This means we have to load all referenced assemblies
665          * non-lazily, since we can't handle out-of-date errors later.
666          */
667         for (i = 0; i < info->image_table_len; ++i)
668                 load_image (info, i);
669
670         if (info->out_of_date)
671                 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);
672         else
673                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
674 }
675
676 void
677 mono_aot_init (void)
678 {
679         InitializeCriticalSection (&aot_mutex);
680         aot_modules = g_hash_table_new (NULL, NULL);
681
682         mono_install_assembly_load_hook (load_aot_module, NULL);
683
684         if (getenv ("MONO_LASTAOT"))
685                 mono_last_aot_method = atoi (getenv ("MONO_LASTAOT"));
686         if (getenv ("MONO_AOT_CACHE"))
687                 use_aot_cache = TRUE;
688 }
689
690 static gboolean
691 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
692 {
693         guint32 flags;
694
695         info->vtable_size = decode_value (buf, &buf);
696         if (info->vtable_size == -1)
697                 /* Generic type */
698                 return FALSE;
699         flags = decode_value (buf, &buf);
700         info->ghcimpl = (flags >> 0) & 0x1;
701         info->has_finalize = (flags >> 1) & 0x1;
702         info->has_cctor = (flags >> 2) & 0x1;
703         info->has_nested_classes = (flags >> 3) & 0x1;
704         info->blittable = (flags >> 4) & 0x1;
705         info->has_references = (flags >> 5) & 0x1;
706         info->has_static_refs = (flags >> 6) & 0x1;
707         info->no_special_static_fields = (flags >> 7) & 0x1;
708
709         if (info->has_cctor) {
710                 MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, buf, &buf);
711                 if (!cctor_image)
712                         return FALSE;
713         }
714         if (info->has_finalize) {
715                 info->finalize_image = decode_method_ref (module, &info->finalize_token, buf, &buf);
716                 if (!info->finalize_image)
717                         return FALSE;
718         }
719
720         info->instance_size = decode_value (buf, &buf);
721         info->class_size = decode_value (buf, &buf);
722         info->packing_size = decode_value (buf, &buf);
723         info->min_align = decode_value (buf, &buf);
724
725         *endbuf = buf;
726
727         return TRUE;
728 }       
729
730 gboolean
731 mono_aot_init_vtable (MonoVTable *vtable)
732 {
733         int i;
734         MonoAotModule *aot_module;
735         MonoClass *klass = vtable->klass;
736         guint8 *info, *p;
737         MonoCachedClassInfo class_info;
738         gboolean err;
739
740         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !klass->image->assembly->aot_module)
741                 return FALSE;
742
743         mono_aot_lock ();
744
745         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
746         if (!aot_module) {
747                 mono_aot_unlock ();
748                 return FALSE;
749         }
750
751         info = &aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
752         p = info;
753
754         err = decode_cached_class_info (aot_module, &class_info, p, &p);
755         if (!err) {
756                 mono_aot_unlock ();
757                 return FALSE;
758         }
759
760         mono_aot_unlock ();
761
762 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
763         //printf ("VT0: %s.%s %d\n", klass->name_space, klass->name, vtable_size);
764         for (i = 0; i < class_info.vtable_size; ++i) {
765                 vtable->vtable [i] = mini_get_vtable_trampoline ();
766         }
767
768         return TRUE;
769 #else
770         return FALSE;
771 #endif
772 }
773
774 gpointer
775 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
776 {
777         int i;
778         MonoAotModule *aot_module;
779         MonoClass *klass = vtable->klass;
780         guint8 *info, *p;
781         MonoCachedClassInfo class_info;
782         gboolean err;
783         guint32 token;
784         MonoImage *image;
785
786         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !klass->image->assembly->aot_module)
787                 return NULL;
788
789         mono_aot_lock ();
790
791         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
792         if (!aot_module) {
793                 mono_aot_unlock ();
794                 return NULL;
795         }
796
797         info = &aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
798         p = info;
799
800         err = decode_cached_class_info (aot_module, &class_info, p, &p);
801         if (!err) {
802                 mono_aot_unlock ();
803                 return NULL;
804         }
805
806         for (i = 0; i < slot; ++i)
807                 decode_method_ref (aot_module, &token, p, &p);
808
809         image = decode_method_ref (aot_module, &token, p, &p);
810         if (!image) {
811                 mono_aot_unlock ();
812                 return NULL;
813         }
814
815         mono_aot_unlock ();
816
817         return mono_aot_get_method_from_token (domain, image, token);
818 }
819
820 gboolean
821 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
822 {
823         MonoAotModule *aot_module;
824         guint8 *p;
825         gboolean err;
826
827         if (klass->rank || !klass->image->assembly->aot_module)
828                 return FALSE;
829
830         mono_aot_lock ();
831
832         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
833         if (!aot_module) {
834                 mono_aot_unlock ();
835                 return FALSE;
836         }
837
838         p = (guint8*)&aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
839
840         err = decode_cached_class_info (aot_module, res, p, &p);
841         if (!err) {
842                 mono_aot_unlock ();
843                 return FALSE;
844         }
845
846         mono_aot_unlock ();
847
848         return TRUE;
849 }
850
851 /**
852  * mono_aot_get_class_from_name:
853  *
854  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
855  * using a cache stored in the AOT file.
856  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
857  *
858  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
859  * found.
860  */
861 gboolean
862 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
863 {
864         MonoAotModule *aot_module;
865         guint16 *table, *entry;
866         guint16 table_size;
867         guint32 hash;
868         char full_name_buf [1024];
869         char *full_name;
870         const char *name2, *name_space2;
871         MonoTableInfo  *t;
872         guint32 cols [MONO_TYPEDEF_SIZE];
873         GHashTable *nspace_table;
874
875         if (!aot_modules)
876                 return FALSE;
877
878         mono_aot_lock ();
879
880         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, image->assembly);
881         if (!aot_module || !aot_module->class_name_table) {
882                 mono_aot_unlock ();
883                 return FALSE;
884         }
885
886         *klass = NULL;
887
888         /* First look in the cache */
889         if (!aot_module->name_cache)
890                 aot_module->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
891         nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
892         if (nspace_table) {
893                 *klass = g_hash_table_lookup (nspace_table, name);
894                 if (*klass) {
895                         mono_aot_unlock ();
896                         return TRUE;
897                 }
898         }
899
900         table_size = aot_module->class_name_table [0];
901         table = aot_module->class_name_table + 1;
902
903         if (name_space [0] == '\0')
904                 full_name = g_strdup_printf ("%s", name);
905         else {
906                 if (strlen (name_space) + strlen (name) < 1000) {
907                         sprintf (full_name_buf, "%s.%s", name_space, name);
908                         full_name = full_name_buf;
909                 } else {
910                         full_name = g_strdup_printf ("%s.%s", name_space, name);
911                 }
912         }
913         hash = g_str_hash (full_name) % table_size;
914         if (full_name != full_name_buf)
915                 g_free (full_name);
916
917         entry = &table [hash * 2];
918
919         if (entry [0] != 0) {
920                 t = &image->tables [MONO_TABLE_TYPEDEF];
921
922                 while (TRUE) {
923                         guint32 index = entry [0];
924                         guint32 next = entry [1];
925                         guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
926
927                         name_table_accesses ++;
928
929                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
930
931                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
932                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
933
934                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
935                                 mono_aot_unlock ();
936                                 *klass = mono_class_get (image, token);
937
938                                 /* Add to cache */
939                                 if (*klass) {
940                                         mono_aot_lock ();
941                                         nspace_table = g_hash_table_lookup (aot_module->name_cache, name_space);
942                                         if (!nspace_table) {
943                                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
944                                                 g_hash_table_insert (aot_module->name_cache, (char*)name_space2, nspace_table);
945                                         }
946                                         g_hash_table_insert (nspace_table, (char*)name2, *klass);
947                                         mono_aot_unlock ();
948                                 }
949                                 return TRUE;
950                         }
951
952                         if (next != 0) {
953                                 entry = &table [next * 2];
954                         } else {
955                                 break;
956                         }
957                 }
958         }
959
960         mono_aot_unlock ();
961         
962         return TRUE;
963 }
964
965 static MonoJitInfo*
966 decode_exception_debug_info (MonoAotModule *aot_module, MonoDomain *domain, 
967                                                          MonoMethod *method, guint8* ex_info, guint8 *code)
968 {
969         int i, buf_len;
970         MonoJitInfo *jinfo;
971         guint code_len, used_int_regs;
972         guint8 *p;
973         MonoMethodHeader *header;
974
975         header = mono_method_get_header (method);
976
977         /* Load the method info from the AOT file */
978
979         p = ex_info;
980         code_len = decode_value (p, &p);
981         used_int_regs = decode_value (p, &p);
982
983         /* Exception table */
984         if (header->num_clauses) {
985                 jinfo = 
986                         mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo) + (sizeof (MonoJitExceptionInfo) * header->num_clauses));
987                 jinfo->num_clauses = header->num_clauses;
988
989                 for (i = 0; i < header->num_clauses; ++i) {
990                         MonoExceptionClause *ec = &header->clauses [i];                         
991                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
992
993                         ei->flags = ec->flags;
994                         ei->exvar_offset = decode_value (p, &p);
995
996                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
997                                 ei->data.filter = code + decode_value (p, &p);
998                         else
999                                 ei->data.catch_class = ec->data.catch_class;
1000
1001                         ei->try_start = code + decode_value (p, &p);
1002                         ei->try_end = code + decode_value (p, &p);
1003                         ei->handler_start = code + decode_value (p, &p);
1004                 }
1005         }
1006         else
1007                 jinfo = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
1008
1009         jinfo->code_size = code_len;
1010         jinfo->used_regs = used_int_regs;
1011         jinfo->method = method;
1012         jinfo->code_start = code;
1013         jinfo->domain_neutral = 0;
1014
1015         /* Load debug info */
1016         buf_len = decode_value (p, &p);
1017         mono_debug_add_aot_method (domain, method, code, p, buf_len);
1018         
1019         return jinfo;
1020 }
1021
1022 MonoJitInfo *
1023 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
1024 {
1025         MonoAssembly *ass = image->assembly;
1026         MonoDl *module = ass->aot_module;
1027         int pos, left, right, offset, offset1, offset2, last_offset, new_offset, page_index, method_index, table_len;
1028         guint32 token;
1029         MonoAotModule *aot_module;
1030         MonoMethod *method;
1031         MonoJitInfo *jinfo;
1032         guint8 *code, *ex_info;
1033         guint32 *table, *ptr;
1034         gboolean found;
1035
1036         if (!module)
1037                 return NULL;
1038
1039         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1040
1041         if (domain != mono_get_root_domain ())
1042                 /* FIXME: */
1043                 return NULL;
1044
1045         offset = (guint8*)addr - aot_module->code;
1046
1047         /* First search through the index */
1048         ptr = aot_module->method_order;
1049         last_offset = 0;
1050         page_index = 0;
1051         found = FALSE;
1052
1053         if (*ptr == 0xffffff)
1054                 return NULL;
1055         ptr ++;
1056
1057         while (*ptr != 0xffffff) {
1058                 guint32 method_index = ptr [0];
1059                 new_offset = aot_module->code_offsets [method_index];
1060
1061                 if (offset >= last_offset && offset < new_offset) {
1062                         found = TRUE;
1063                         break;
1064                 }
1065
1066                 ptr ++;
1067                 last_offset = new_offset;
1068                 page_index ++;
1069         }
1070
1071         /* Skip rest of index */
1072         while (*ptr != 0xffffff)
1073                 ptr ++;
1074         ptr ++;
1075
1076         table = ptr;
1077         table_len = aot_module->method_order_end - table;
1078
1079         g_assert (table <= aot_module->method_order_end);
1080
1081         if (found) {
1082                 left = (page_index * 1024);
1083                 right = left + 1024;
1084
1085                 if (right > table_len)
1086                         right = table_len;
1087
1088                 offset1 = aot_module->code_offsets [table [left]];
1089                 g_assert (offset1 <= offset);
1090
1091                 //printf ("Found in index: 0x%x 0x%x 0x%x\n", offset, last_offset, new_offset);
1092         }
1093         else {
1094                 //printf ("Not found in index: 0x%x\n", offset);
1095                 left = 0;
1096                 right = table_len;
1097         }
1098
1099         /* Binary search inside the method_order table to find the method */
1100         while (TRUE) {
1101                 pos = (left + right) / 2;
1102
1103                 g_assert (table + pos <= aot_module->method_order_end);
1104
1105                 //printf ("Pos: %5d < %5d < %5d Offset: 0x%05x < 0x%05x < 0x%05x\n", left, pos, right, aot_module->code_offsets [table [left]], offset, aot_module->code_offsets [table [right]]);
1106
1107                 offset1 = aot_module->code_offsets [table [pos]];
1108                 if (table + pos + 1 >= aot_module->method_order_end)
1109                         offset2 = aot_module->code_end - aot_module->code;
1110                 else
1111                         offset2 = aot_module->code_offsets [table [pos + 1]];
1112
1113                 if (offset < offset1)
1114                         right = pos;
1115                 else if (offset >= offset2)
1116                         left = pos + 1;
1117                 else
1118                         break;
1119         }
1120
1121         method_index = table [pos];
1122
1123         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
1124         method = mono_get_method (image, token, NULL);
1125
1126         /* FIXME: */
1127         g_assert (method);
1128
1129         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
1130
1131         code = &aot_module->code [aot_module->code_offsets [method_index]];
1132         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [method_index]];
1133
1134         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1135
1136         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
1137         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
1138
1139         /* Add it to the normal JitInfo tables */
1140         mono_jit_info_table_add (domain, jinfo);
1141         
1142         return jinfo;
1143 }
1144
1145 static gboolean
1146 decode_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf, guint32 *got_offset)
1147 {
1148         guint8 *p = buf;
1149         gpointer *table;
1150         MonoImage *image;
1151         int i;
1152
1153         switch (ji->type) {
1154         case MONO_PATCH_INFO_METHOD:
1155         case MONO_PATCH_INFO_METHODCONST:
1156         case MONO_PATCH_INFO_METHOD_JUMP: {
1157                 guint32 token;
1158
1159                 image = decode_method_ref (aot_module, &token, p, &p);
1160                 if (!image)
1161                         goto cleanup;
1162
1163 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
1164                 if ((ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) {
1165                         ji->data.target = mono_create_jit_trampoline_from_token (image, token);
1166                         ji->type = MONO_PATCH_INFO_ABS;
1167                 }
1168                 else {
1169                         ji->data.method = mono_get_method (image, token, NULL);
1170                         g_assert (ji->data.method);
1171                         mono_class_init (ji->data.method->klass);
1172                 }
1173 #else
1174                 ji->data.method = mono_get_method (image, token, NULL);
1175                 g_assert (ji->data.method);
1176                 mono_class_init (ji->data.method->klass);
1177 #endif
1178
1179                 break;
1180         }
1181         case MONO_PATCH_INFO_WRAPPER: {
1182                 guint32 wrapper_type;
1183
1184                 wrapper_type = decode_value (p, &p);
1185
1186                 switch (wrapper_type) {
1187                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
1188                         guint32 image_index, token, value;
1189
1190                         value = decode_value (p, &p);
1191                         image_index = value >> 24;
1192                         token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1193
1194                         image = load_image (aot_module, image_index);
1195                         if (!image)
1196                                 goto cleanup;
1197                         ji->data.method = mono_get_method (image, token, NULL);
1198                         g_assert (ji->data.method);
1199                         mono_class_init (ji->data.method->klass);
1200
1201                         ji->type = MONO_PATCH_INFO_METHOD;
1202                         ji->data.method = mono_marshal_get_remoting_invoke_with_check (ji->data.method);
1203                         break;
1204                 }
1205                 case MONO_WRAPPER_PROXY_ISINST: {
1206                         MonoClass *klass = decode_klass_ref (aot_module, p, &p);
1207                         if (!klass)
1208                                 goto cleanup;
1209                         ji->type = MONO_PATCH_INFO_METHOD;
1210                         ji->data.method = mono_marshal_get_proxy_cancast (klass);
1211                         break;
1212                 }
1213                 case MONO_WRAPPER_LDFLD:
1214                 case MONO_WRAPPER_LDFLDA:
1215                 case MONO_WRAPPER_STFLD:
1216                 case MONO_WRAPPER_LDFLD_REMOTE:
1217                 case MONO_WRAPPER_STFLD_REMOTE:
1218                 case MONO_WRAPPER_ISINST: {
1219                         MonoClass *klass = decode_klass_ref (aot_module, p, &p);
1220                         if (!klass)
1221                                 goto cleanup;
1222                         ji->type = MONO_PATCH_INFO_METHOD;
1223                         if (wrapper_type == MONO_WRAPPER_LDFLD)
1224                                 ji->data.method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
1225                         else if (wrapper_type == MONO_WRAPPER_LDFLDA)
1226                                 ji->data.method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
1227                         else if (wrapper_type == MONO_WRAPPER_STFLD)
1228                                 ji->data.method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
1229                         else if (wrapper_type == MONO_WRAPPER_LDFLD_REMOTE)
1230                                 ji->data.method = mono_marshal_get_ldfld_remote_wrapper (klass);
1231                         else if (wrapper_type == MONO_WRAPPER_STFLD_REMOTE)
1232                                 ji->data.method = mono_marshal_get_stfld_remote_wrapper (klass);
1233                         else if (wrapper_type == MONO_WRAPPER_ISINST)
1234                                 ji->data.method = mono_marshal_get_isinst (klass);
1235                         else
1236                                 g_assert_not_reached ();
1237                         break;
1238                 }
1239                 case MONO_WRAPPER_ALLOC: {
1240                         int atype = decode_value (p, &p);
1241
1242                         ji->type = MONO_PATCH_INFO_METHOD;
1243                         ji->data.method = mono_gc_get_managed_allocator_by_type (atype);
1244                         break;
1245                 }
1246                 case MONO_WRAPPER_STELEMREF:
1247                         ji->type = MONO_PATCH_INFO_METHOD;
1248                         ji->data.method = mono_marshal_get_stelemref ();
1249                         break;
1250                 default:
1251                         g_assert_not_reached ();
1252                 }
1253                 break;
1254         }
1255         case MONO_PATCH_INFO_INTERNAL_METHOD: {
1256                 guint32 len = decode_value (p, &p);
1257
1258                 ji->data.name = (char*)p;
1259                 p += len + 1;
1260                 break;
1261         }
1262         case MONO_PATCH_INFO_VTABLE:
1263         case MONO_PATCH_INFO_CLASS:
1264         case MONO_PATCH_INFO_IID:
1265         case MONO_PATCH_INFO_ADJUSTED_IID:
1266                 *got_offset = decode_value (p, &p);
1267
1268                 if (aot_module->got [*got_offset]) {
1269                         /* Already loaded */
1270                         //printf ("HIT!\n");
1271                 } else {
1272                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1273                         ji->data.klass = decode_klass_ref (aot_module, tmp, &tmp);
1274                         if (!ji->data.klass)
1275                                 goto cleanup;
1276                 }
1277                 break;
1278         case MONO_PATCH_INFO_CLASS_INIT:
1279         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1280                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1281                 if (!ji->data.klass)
1282                         goto cleanup;
1283                 break;
1284         case MONO_PATCH_INFO_IMAGE:
1285                 ji->data.image = load_image (aot_module, decode_value (p, &p));
1286                 if (!ji->data.image)
1287                         goto cleanup;
1288                 break;
1289         case MONO_PATCH_INFO_FIELD:
1290         case MONO_PATCH_INFO_SFLDA:
1291                 *got_offset = decode_value (p, &p);
1292
1293                 if (aot_module->got [*got_offset]) {
1294                         /* Already loaded */
1295                         //printf ("HIT2!\n");
1296                 } else {
1297                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1298                         ji->data.field = decode_field_info (aot_module, tmp, &tmp);
1299                         if (!ji->data.field)
1300                                 goto cleanup;
1301                 }
1302                 break;
1303         case MONO_PATCH_INFO_SWITCH:
1304                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
1305                 ji->data.table->table_size = decode_value (p, &p);
1306                 table = g_new (gpointer, ji->data.table->table_size);
1307                 ji->data.table->table = (MonoBasicBlock**)table;
1308                 for (i = 0; i < ji->data.table->table_size; i++)
1309                         table [i] = (gpointer)(gssize)decode_value (p, &p);
1310                 break;
1311         case MONO_PATCH_INFO_R4: {
1312                 guint32 val;
1313                 
1314                 ji->data.target = mono_mempool_alloc0 (mp, sizeof (float));
1315                 val = decode_value (p, &p);
1316                 *(float*)ji->data.target = *(float*)&val;
1317                 break;
1318         }
1319         case MONO_PATCH_INFO_R8: {
1320                 guint32 val [2];
1321
1322                 ji->data.target = mono_mempool_alloc0 (mp, sizeof (double));
1323
1324                 val [0] = decode_value (p, &p);
1325                 val [1] = decode_value (p, &p);
1326                 *(double*)ji->data.target = *(double*)val;
1327                 break;
1328         }
1329         case MONO_PATCH_INFO_LDSTR:
1330                 image = load_image (aot_module, decode_value (p, &p));
1331                 if (!image)
1332                         goto cleanup;
1333                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
1334                 break;
1335         case MONO_PATCH_INFO_RVA:
1336         case MONO_PATCH_INFO_DECLSEC:
1337         case MONO_PATCH_INFO_LDTOKEN:
1338         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1339                 *got_offset = decode_value (p, &p);
1340
1341                 if (aot_module->got [*got_offset]) {
1342                         /* Already loaded */
1343                 } else {
1344                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1345                         image = load_image (aot_module, decode_value (tmp, &tmp));
1346                         if (!image)
1347                                 goto cleanup;
1348                         ji->data.token = mono_jump_info_token_new (mp, image, decode_value (tmp, &tmp));
1349                 }
1350                 break;
1351         case MONO_PATCH_INFO_EXC_NAME:
1352                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1353                 if (!ji->data.klass)
1354                         goto cleanup;
1355                 ji->data.name = ji->data.klass->name;
1356                 break;
1357         case MONO_PATCH_INFO_METHOD_REL:
1358                 ji->data.offset = decode_value (p, &p);
1359                 break;
1360         default:
1361                 g_warning ("unhandled type %d", ji->type);
1362                 g_assert_not_reached ();
1363         }
1364
1365         *endbuf = p;
1366
1367         return TRUE;
1368
1369  cleanup:
1370         return FALSE;
1371 }
1372
1373 static MonoJumpInfo*
1374 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
1375                                  guint32 got_index, guint32 **got_slots, 
1376                                  guint8 *buf, guint8 **endbuf)
1377 {
1378         MonoJumpInfo *patches;
1379         MonoJumpInfo *patch_info = NULL;
1380         int pindex;
1381         guint32 last_offset;
1382         guint8 *p;
1383
1384         p = buf;
1385
1386         /* First load the type + offset table */
1387         last_offset = 0;
1388         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
1389
1390         for (pindex = 0; pindex < n_patches; ++pindex) {                
1391                 MonoJumpInfo *ji = &patches [pindex];
1392
1393                 ji->type = *p;
1394                 p ++;
1395
1396                 //printf ("T: %d O: %d.\n", ji->type, ji->ip.i);
1397                 ji->next = patch_info;
1398                 patch_info = ji;
1399         }
1400
1401         *got_slots = g_malloc (sizeof (guint32) * n_patches);
1402         memset (*got_slots, 0xff, sizeof (guint32) * n_patches);
1403
1404         /* Then load the other data */
1405         for (pindex = 0; pindex < n_patches; ++pindex) {
1406                 MonoJumpInfo *ji = &patches [pindex];
1407
1408                 if (!decode_patch_info (aot_module, mp, ji, p, &p, (*got_slots) + pindex))
1409                         goto cleanup;
1410
1411                 if ((*got_slots) [pindex] == 0xffffffff)
1412                         (*got_slots) [pindex] = got_index ++;
1413         }
1414
1415         *endbuf = p;
1416         return patches;
1417
1418  cleanup:
1419         g_free (*got_slots);
1420         *got_slots = NULL;
1421
1422         return NULL;
1423 }
1424  
1425 static gpointer
1426 mono_aot_get_method_inner (MonoDomain *domain, MonoMethod *method)
1427 {
1428         MonoClass *klass = method->klass;
1429         MonoAssembly *ass = klass->image->assembly;
1430         MonoDl *module = ass->aot_module;
1431         guint32 method_index = mono_metadata_token_index (method->token) - 1;
1432         guint8 *code, *info;
1433         MonoAotModule *aot_module;
1434
1435         if (!module)
1436                 return NULL;
1437
1438         if (!method->token)
1439                 return NULL;
1440
1441         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1442                 return NULL;
1443
1444         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1445                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1446                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1447                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1448                 return NULL;
1449         
1450         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1451
1452         g_assert (klass->inited);
1453
1454         if ((domain != mono_get_root_domain ()) && (!(aot_module->opts & MONO_OPT_SHARED)))
1455                 /* Non shared AOT code can't be used in other appdomains */
1456                 return NULL;
1457
1458         if (aot_module->out_of_date)
1459                 return NULL;
1460
1461         if (method->is_inflated) {
1462                 if (!mono_method_is_generic_sharable_impl (method))
1463                         return NULL;
1464                 method = mono_method_get_declaring_generic_method (method);
1465         }
1466
1467         if (aot_module->code_offsets [method_index] == 0xffffffff) {
1468                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1469                         char *full_name = mono_method_full_name (method, TRUE);
1470                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
1471                         g_free (full_name);
1472                 }
1473                 return NULL;
1474         }
1475
1476         code = &aot_module->code [aot_module->code_offsets [method_index]];
1477         info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1478
1479         if (!aot_module->methods_loaded)
1480                 aot_module->methods_loaded = g_new0 (guint32, klass->image->tables [MONO_TABLE_METHOD].rows + 1);
1481
1482         if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1483                 return code;
1484
1485         if (mono_last_aot_method != -1) {
1486                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1487                                 return NULL;
1488                 else
1489                         if (mono_jit_stats.methods_aot == mono_last_aot_method)
1490                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", klass->name_space, klass->name, method->name);
1491         }
1492
1493         return mono_aot_load_method (domain, aot_module, method, code, info);
1494 }
1495
1496 static gpointer
1497 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info)
1498 {
1499         MonoClass *klass = method->klass;
1500         MonoJumpInfo *patch_info = NULL;
1501         MonoMemPool *mp;
1502         int i, pindex, got_index = 0, n_patches, used_strings;
1503         gboolean non_got_patches, keep_patches = TRUE;
1504         guint32 method_index = mono_metadata_token_index (method->token) - 1;
1505         guint8 *p, *ex_info;
1506         MonoJitInfo *jinfo = NULL;
1507
1508         p = info;
1509         decode_klass_ref (aot_module, p, &p);
1510
1511         if (!use_loaded_code) {
1512                 guint8 *code2;
1513
1514                 if (!jinfo) {
1515                         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1516                         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1517                 }
1518
1519                 code2 = mono_code_manager_reserve (domain->code_mp, jinfo->code_size);
1520                 memcpy (code2, code, jinfo->code_size);
1521                 mono_arch_flush_icache (code2, jinfo->code_size);
1522                 code = code2;
1523         }
1524
1525         if (aot_module->opts & MONO_OPT_SHARED)
1526                 used_strings = decode_value (p, &p);
1527         else
1528                 used_strings = 0;
1529
1530         for (i = 0; i < used_strings; i++) {
1531                 guint token = decode_value (p, &p);
1532                 mono_ldstr (mono_get_root_domain (), klass->image, mono_metadata_token_index (token));
1533         }
1534
1535         if (aot_module->opts & MONO_OPT_SHARED) 
1536                 keep_patches = FALSE;
1537
1538         n_patches = decode_value (p, &p);
1539
1540         keep_patches = FALSE;
1541
1542         if (n_patches) {
1543                 MonoJumpInfo *patches;
1544                 guint32 *got_slots;
1545
1546                 if (keep_patches)
1547                         mp = domain->mp;
1548                 else
1549                         mp = mono_mempool_new ();
1550
1551                 got_index = decode_value (p, &p);
1552
1553                 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1554                 if (patches == NULL)
1555                         goto cleanup;
1556
1557                 /* Do this outside the lock to avoid deadlocks */
1558                 mono_aot_unlock ();
1559                 non_got_patches = FALSE;
1560                 for (pindex = 0; pindex < n_patches; ++pindex) {
1561                         MonoJumpInfo *ji = &patches [pindex];
1562
1563                         if (is_got_patch (ji->type)) {
1564                                 if (!aot_module->got [got_slots [pindex]])
1565                                         aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
1566                                 ji->type = MONO_PATCH_INFO_NONE;
1567                         }
1568                         else
1569                                 non_got_patches = TRUE;
1570                 }
1571                 if (non_got_patches) {
1572                         if (!jinfo) {
1573                                 ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1574                                 jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1575                         }
1576
1577                         mono_arch_flush_icache (code, jinfo->code_size);
1578                         make_writable (code, jinfo->code_size);
1579                         mono_arch_patch_code (method, domain, code, patch_info, TRUE);
1580                 }
1581                 mono_aot_lock ();
1582
1583                 g_free (got_slots);
1584
1585                 if (!keep_patches)
1586                         mono_mempool_destroy (mp);
1587         }
1588
1589         mono_jit_stats.methods_aot++;
1590
1591         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1592                 char *full_name = mono_method_full_name (method, TRUE);
1593
1594                 if (!jinfo) {
1595                         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1596                         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1597                 }
1598
1599                 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);
1600                 g_free (full_name);
1601         }
1602
1603         aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1604
1605         init_plt (aot_module);
1606
1607         return code;
1608
1609  cleanup:
1610         /* FIXME: The space in domain->mp is wasted */  
1611         if (aot_module->opts & MONO_OPT_SHARED)
1612                 /* No need to cache patches */
1613                 mono_mempool_destroy (mp);
1614
1615         if (jinfo)
1616                 g_free (jinfo);
1617
1618         return NULL;
1619 }
1620
1621 gpointer
1622 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
1623 {
1624         gpointer code;
1625
1626         mono_aot_lock ();
1627         code = mono_aot_get_method_inner (domain, method);
1628         mono_aot_unlock ();
1629
1630         return code;
1631 }
1632
1633 static gpointer
1634 mono_aot_get_method_from_token_inner (MonoDomain *domain, MonoImage *image, guint32 token, MonoClass **klass)
1635 {
1636         MonoAssembly *ass = image->assembly;
1637         MonoMemPool *mp;
1638         int i, method_index, pindex, got_index, n_patches, used_strings;
1639         gboolean keep_patches = TRUE;
1640         guint8 *p;
1641         MonoDl *module = ass->aot_module;
1642         guint8 *code = NULL;
1643         guint8 *info;
1644         MonoAotModule *aot_module;
1645
1646         *klass = NULL;
1647
1648         if (!module)
1649                 return NULL;
1650
1651         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1652                 return NULL;
1653
1654         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1655
1656         if (domain != mono_get_root_domain ())
1657                 return NULL;
1658
1659         if (aot_module->out_of_date)
1660                 return NULL;
1661
1662         if (aot_module->code_offsets [mono_metadata_token_index (token) - 1] == 0xffffffff) {
1663                 return NULL;
1664         }
1665
1666         method_index = mono_metadata_token_index (token) - 1;
1667         code = &aot_module->code [aot_module->code_offsets [method_index]];
1668         info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1669
1670         if (!aot_module->methods_loaded)
1671                 aot_module->methods_loaded = g_new0 (guint32, image->tables [MONO_TABLE_METHOD].rows + 1);
1672
1673         if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1674                 return code;
1675
1676         if (mono_last_aot_method != -1) {
1677                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1678                                 return NULL;
1679                 else
1680                         if (mono_jit_stats.methods_aot == mono_last_aot_method) {
1681                                 MonoMethod *method = mono_get_method (image, token, NULL);
1682                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", method->klass->name_space, method->klass->name, method->name);
1683                         }
1684         }
1685
1686         p = info;
1687         *klass = decode_klass_ref (aot_module, p, &p);
1688
1689         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1690                 MonoMethod *method = mono_get_method (image, token, NULL);
1691                 char *full_name = mono_method_full_name (method, TRUE);
1692                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p %p\n", full_name, code, info);
1693                 g_free (full_name);
1694         }
1695
1696         if (aot_module->opts & MONO_OPT_SHARED)
1697                 used_strings = decode_value (p, &p);
1698         else
1699                 used_strings = 0;
1700
1701         for (i = 0; i < used_strings; i++) {
1702                 guint string_token = decode_value (p, &p);
1703                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (string_token));
1704         }
1705
1706         if (aot_module->opts & MONO_OPT_SHARED) 
1707                 keep_patches = FALSE;
1708
1709         keep_patches = FALSE;
1710
1711         n_patches = decode_value (p, &p);
1712
1713         if (n_patches) {
1714                 MonoJumpInfo *patches;
1715                 guint32 *got_slots;
1716
1717                 if (keep_patches)
1718                         mp = domain->mp;
1719                 else
1720                         mp = mono_mempool_new ();
1721
1722                 got_index = decode_value (p, &p);
1723
1724                 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1725                 if (patches == NULL)
1726                         goto cleanup;
1727
1728                 /* Do this outside the lock to avoid deadlocks */
1729                 mono_aot_unlock ();
1730
1731                 for (pindex = 0; pindex < n_patches; ++pindex) {
1732                         MonoJumpInfo *ji = &patches [pindex];
1733
1734                         if (is_got_patch (ji->type)) {
1735                                 if (!aot_module->got [got_slots [pindex]])
1736                                         aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (NULL, domain, code, ji, TRUE);
1737                                 ji->type = MONO_PATCH_INFO_NONE;
1738                         }
1739                 }
1740
1741                 mono_aot_lock ();
1742
1743                 g_free (got_slots);
1744
1745                 if (!keep_patches)
1746                         mono_mempool_destroy (mp);
1747         }
1748
1749         mono_jit_stats.methods_aot++;
1750
1751         aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1752
1753         init_plt (aot_module);
1754
1755         return code;
1756
1757  cleanup:
1758         /* FIXME: The space in domain->mp is wasted */  
1759         if (aot_module->opts & MONO_OPT_SHARED)
1760                 /* No need to cache patches */
1761                 mono_mempool_destroy (mp);
1762
1763         return NULL;
1764 }
1765
1766 /**
1767  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
1768  * method.
1769  */
1770 gpointer
1771 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
1772 {
1773         gpointer res;   
1774         MonoClass *klass;
1775
1776         mono_aot_lock ();
1777         res = mono_aot_get_method_from_token_inner (domain, image, token, &klass);
1778         mono_aot_unlock ();
1779
1780         if (!res)
1781                 return NULL;
1782
1783         if (klass)
1784                 mono_runtime_class_init (mono_class_vtable (domain, klass));
1785
1786         return res;
1787 }
1788
1789 typedef struct {
1790         guint8 *addr;
1791         gboolean res;
1792 } IsGotEntryUserData;
1793
1794 static void
1795 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
1796 {
1797         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
1798         MonoAotModule *aot_module = (MonoAotModule*)value;
1799
1800         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->got_size)))
1801                 data->res = TRUE;
1802 }
1803
1804 gboolean
1805 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
1806 {
1807         IsGotEntryUserData user_data;
1808
1809         if (!aot_modules)
1810                 return FALSE;
1811
1812         user_data.addr = addr;
1813         user_data.res = FALSE;
1814         mono_aot_lock ();
1815         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
1816         mono_aot_unlock ();
1817         
1818         return user_data.res;
1819 }
1820
1821 typedef struct {
1822         guint8 *addr;
1823         MonoAotModule *module;
1824 } FindAotModuleUserData;
1825
1826 static void
1827 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
1828 {
1829         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
1830         MonoAotModule *aot_module = (MonoAotModule*)value;
1831
1832         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
1833                 data->module = aot_module;
1834 }
1835
1836 static inline MonoAotModule*
1837 find_aot_module (guint8 *code)
1838 {
1839         FindAotModuleUserData user_data;
1840
1841         if (!aot_modules)
1842                 return NULL;
1843
1844         /* Reading these need no locking */
1845         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
1846                 return NULL;
1847
1848         user_data.addr = code;
1849         user_data.module = NULL;
1850                 
1851         mono_aot_lock ();
1852         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
1853         mono_aot_unlock ();
1854         
1855         return user_data.module;
1856 }
1857
1858 /*
1859  * mono_aot_set_make_unreadable:
1860  *
1861  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
1862  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
1863  */
1864 void
1865 mono_aot_set_make_unreadable (gboolean unreadable)
1866 {
1867         make_unreadable = unreadable;
1868 }
1869
1870 typedef struct {
1871         MonoAotModule *module;
1872         guint8 *ptr;
1873 } FindMapUserData;
1874
1875 static void
1876 find_map (gpointer key, gpointer value, gpointer user_data)
1877 {
1878         MonoAotModule *module = (MonoAotModule*)value;
1879         FindMapUserData *data = (FindMapUserData*)user_data;
1880
1881         if (!data->module)
1882                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
1883                         data->module = module;
1884 }
1885
1886 static MonoAotModule*
1887 find_module_for_addr (void *ptr)
1888 {
1889         FindMapUserData data;
1890
1891         if (!make_unreadable)
1892                 return NULL;
1893
1894         data.module = NULL;
1895         data.ptr = (guint8*)ptr;
1896
1897         mono_aot_lock ();
1898         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
1899         mono_aot_unlock ();
1900
1901         return data.module;
1902 }
1903
1904 /*
1905  * mono_aot_is_pagefault:
1906  *
1907  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
1908  * within memory allocated by this module.
1909  */
1910 gboolean
1911 mono_aot_is_pagefault (void *ptr)
1912 {
1913         if (!make_unreadable)
1914                 return FALSE;
1915
1916         return find_module_for_addr (ptr) != NULL;
1917 }
1918
1919 /*
1920  * mono_aot_handle_pagefault:
1921  *
1922  *   Handle a pagefault caused by an unreadable page by making it readable again.
1923  */
1924 void
1925 mono_aot_handle_pagefault (void *ptr)
1926 {
1927 #ifndef PLATFORM_WIN32
1928         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), PAGESIZE);
1929         int res;
1930
1931         mono_aot_lock ();
1932         res = mprotect (start, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
1933         g_assert (res == 0);
1934
1935         n_pagefaults ++;
1936         mono_aot_unlock ();
1937
1938 #if 0
1939  {
1940         void *array [256];
1941         char **names;
1942         int i, size;
1943
1944         printf ("\nNative stacktrace:\n\n");
1945
1946         size = backtrace (array, 256);
1947         names = backtrace_symbols (array, size);
1948         for (i =0; i < size; ++i) {
1949                 printf ("\t%s\n", names [i]);
1950         }
1951         free (names);
1952  }
1953 #endif
1954
1955 #endif
1956 }
1957
1958 /*
1959  * mono_aot_plt_resolve:
1960  *
1961  *   This function is called by the entries in the PLT to resolve the actual method that
1962  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
1963  */
1964 gpointer
1965 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
1966 {
1967 #ifdef MONO_ARCH_AOT_SUPPORTED
1968         guint8 *p, *target, *plt_entry;
1969         MonoJumpInfo ji;
1970         MonoAotModule *module = (MonoAotModule*)aot_module;
1971         gboolean res;
1972
1973         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
1974
1975         p = &module->plt_info [plt_info_offset];
1976
1977         ji.type = decode_value (p, &p);
1978
1979         res = decode_patch_info (module, NULL, &ji, p, &p, NULL);
1980         // FIXME: Error handling (how ?)
1981         g_assert (res);
1982
1983         target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
1984
1985         /* Patch the PLT entry with target which might be the actual method not a trampoline */
1986         plt_entry = mono_aot_get_plt_entry (code);
1987         g_assert (plt_entry);
1988         mono_arch_patch_plt_entry (plt_entry, target);
1989
1990         return target;
1991 #else
1992         g_assert_not_reached ();
1993         return NULL;
1994 #endif
1995 }
1996
1997 /**
1998  * init_plt:
1999  *
2000  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
2001  * method in the module is loaded to avoid committing memory by writing to it.
2002  * LOCKING: Assumes the AOT lock is held.
2003  */
2004 static void
2005 init_plt (MonoAotModule *info)
2006 {
2007 #ifdef MONO_ARCH_AOT_SUPPORTED
2008 #ifdef __i386__
2009         guint8 *buf = info->plt;
2010 #elif defined(__x86_64__)
2011         int i, n_entries;
2012 #elif defined(__arm__)
2013         int i, n_entries;
2014 #endif
2015         gpointer tramp;
2016
2017         if (info->plt_inited)
2018                 return;
2019
2020         tramp = mono_arch_create_specific_trampoline (info, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
2021
2022 #ifdef __i386__
2023         /* Initialize the first PLT entry */
2024         make_writable (info->plt, info->plt_end - info->plt);
2025         x86_jump_code (buf, tramp);
2026 #elif defined(__x86_64__)
2027         /*
2028          * Initialize the entries in the plt_jump_table to point to the default targets.
2029          */
2030          n_entries = info->plt_jump_table_size / sizeof (gpointer);
2031
2032          /* The first entry points to the AOT trampoline */
2033          ((gpointer*)info->plt_jump_table)[0] = tramp;
2034          for (i = 1; i < n_entries; ++i)
2035                  /* Each PLT entry is 16 bytes long, the default entry begins at offset 6 */
2036                  ((gpointer*)info->plt_jump_table)[i] = info->plt + (i * 16) + 6;
2037 #elif defined(__arm__)
2038          /* Initialize the first PLT entry */
2039          make_writable (info->plt, info->plt_end - info->plt);
2040          ((guint32*)info->plt)[1] = (guint32)tramp;
2041
2042          n_entries = ((guint8*)info->plt_end - (guint8*)info->plt) / 8;
2043
2044          /* 
2045           * Initialize the jump targets embedded inside the PLT entries to the default
2046           * targets.
2047           */
2048          for (i = 1; i < n_entries; ++i)
2049                  /* Each PLT entry is 8 bytes long, the jump target is at offset 4 */
2050                  /* Each default PLT target is 12 bytes long */
2051                  ((guint32*)info->plt)[(i * 2) + 1] = (guint8*)info->plt_end + ((i - 1) * 12);
2052 #else
2053         g_assert_not_reached ();
2054 #endif
2055
2056         info->plt_inited = TRUE;
2057 #endif
2058 }
2059
2060 /*
2061  * mono_aot_get_plt_entry:
2062  *
2063  *   Return the address of the PLT entry called by the code at CODE if exists.
2064  */
2065 guint8*
2066 mono_aot_get_plt_entry (guint8 *code)
2067 {
2068         MonoAotModule *aot_module = find_aot_module (code);
2069
2070         if (!aot_module)
2071                 return NULL;
2072
2073 #if defined(__i386__) || defined(__x86_64__)
2074         if (code [-5] == 0xe8) {
2075                 guint32 disp = *(guint32*)(code - 4);
2076                 guint8 *target = code + disp;
2077
2078                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2079                         return target;
2080         }
2081 #elif defined(__arm__)
2082         guint32 ins = ((guint32*)code) [-1];
2083
2084         /* Should be a 'bl' */
2085         if ((((ins >> 25) & 0x7) == 0x5) && (((ins >> 24) & 0x1) == 0x1)) {
2086                 gint32 disp = ((gint32)ins) & 0xffffff;
2087                 guint8 *target = code - 4 + 8 + (disp * 4);
2088
2089                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2090                         return target;
2091         }               
2092 #else
2093         g_assert_not_reached ();
2094 #endif
2095
2096         return NULL;
2097 }
2098
2099 /*
2100  * mono_aot_get_n_pagefaults:
2101  *
2102  *   Return the number of times handle_pagefault is called.
2103  */
2104 guint32
2105 mono_aot_get_n_pagefaults (void)
2106 {
2107         return n_pagefaults;
2108 }
2109
2110 #else
2111 /* AOT disabled */
2112
2113 void
2114 mono_aot_init (void)
2115 {
2116 }
2117
2118 gpointer
2119 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2120 {
2121         return NULL;
2122 }
2123
2124 gboolean
2125 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
2126 {
2127         return FALSE;
2128 }
2129
2130 gboolean
2131 mono_aot_init_vtable (MonoVTable *vtable)
2132 {
2133         return FALSE;
2134 }
2135
2136 gboolean
2137 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2138 {
2139         return FALSE;
2140 }
2141
2142 gboolean
2143 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2144 {
2145         return FALSE;
2146 }
2147
2148 MonoJitInfo *
2149 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2150 {
2151         return NULL;
2152 }
2153
2154 gpointer
2155 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
2156 {
2157         return NULL;
2158 }
2159
2160 gboolean
2161 mono_aot_is_pagefault (void *ptr)
2162 {
2163         return FALSE;
2164 }
2165
2166 void
2167 mono_aot_set_make_unreadable (gboolean unreadable)
2168 {
2169 }
2170
2171 guint32
2172 mono_aot_get_n_pagefaults (void)
2173 {
2174         return 0;
2175 }
2176
2177 void
2178 mono_aot_handle_pagefault (void *ptr)
2179 {
2180 }
2181
2182 guint8*
2183 mono_aot_get_plt_entry (guint8 *code)
2184 {
2185         return NULL;
2186 }
2187
2188 gpointer
2189 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
2190 {
2191         return NULL;
2192 }
2193
2194 gpointer
2195 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
2196 {
2197         return NULL;
2198 }
2199 #endif