merge r98600
[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 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
734         int i;
735         MonoAotModule *aot_module;
736         MonoClass *klass = vtable->klass;
737         guint8 *info, *p;
738         MonoCachedClassInfo class_info;
739         gboolean err;
740
741         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !klass->image->assembly->aot_module)
742                 return FALSE;
743
744         mono_aot_lock ();
745
746         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
747         if (!aot_module) {
748                 mono_aot_unlock ();
749                 return FALSE;
750         }
751
752         info = &aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
753         p = info;
754
755         err = decode_cached_class_info (aot_module, &class_info, p, &p);
756         if (!err) {
757                 mono_aot_unlock ();
758                 return FALSE;
759         }
760
761         mono_aot_unlock ();
762
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         case MONO_PATCH_INFO_ICALL_ADDR: {
1158                 guint32 token;
1159
1160                 image = decode_method_ref (aot_module, &token, p, &p);
1161                 if (!image)
1162                         goto cleanup;
1163
1164 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
1165                 if ((ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (token) == MONO_TABLE_METHOD)) {
1166                         ji->data.target = mono_create_jit_trampoline_from_token (image, token);
1167                         ji->type = MONO_PATCH_INFO_ABS;
1168                 }
1169                 else {
1170                         ji->data.method = mono_get_method (image, token, NULL);
1171                         g_assert (ji->data.method);
1172                         mono_class_init (ji->data.method->klass);
1173                 }
1174 #else
1175                 ji->data.method = mono_get_method (image, token, NULL);
1176                 g_assert (ji->data.method);
1177                 mono_class_init (ji->data.method->klass);
1178 #endif
1179
1180                 break;
1181         }
1182         case MONO_PATCH_INFO_WRAPPER: {
1183                 guint32 wrapper_type;
1184
1185                 wrapper_type = decode_value (p, &p);
1186
1187                 switch (wrapper_type) {
1188                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
1189                         guint32 image_index, token, value;
1190
1191                         value = decode_value (p, &p);
1192                         image_index = value >> 24;
1193                         token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1194
1195                         image = load_image (aot_module, image_index);
1196                         if (!image)
1197                                 goto cleanup;
1198                         ji->data.method = mono_get_method (image, token, NULL);
1199                         g_assert (ji->data.method);
1200                         mono_class_init (ji->data.method->klass);
1201
1202                         ji->type = MONO_PATCH_INFO_METHOD;
1203                         ji->data.method = mono_marshal_get_remoting_invoke_with_check (ji->data.method);
1204                         break;
1205                 }
1206                 case MONO_WRAPPER_PROXY_ISINST: {
1207                         MonoClass *klass = decode_klass_ref (aot_module, p, &p);
1208                         if (!klass)
1209                                 goto cleanup;
1210                         ji->type = MONO_PATCH_INFO_METHOD;
1211                         ji->data.method = mono_marshal_get_proxy_cancast (klass);
1212                         break;
1213                 }
1214                 case MONO_WRAPPER_LDFLD:
1215                 case MONO_WRAPPER_LDFLDA:
1216                 case MONO_WRAPPER_STFLD:
1217                 case MONO_WRAPPER_ISINST: {
1218                         MonoClass *klass = decode_klass_ref (aot_module, p, &p);
1219                         if (!klass)
1220                                 goto cleanup;
1221                         ji->type = MONO_PATCH_INFO_METHOD;
1222                         if (wrapper_type == MONO_WRAPPER_LDFLD)
1223                                 ji->data.method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
1224                         else if (wrapper_type == MONO_WRAPPER_LDFLDA)
1225                                 ji->data.method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
1226                         else if (wrapper_type == MONO_WRAPPER_STFLD)
1227                                 ji->data.method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
1228                         else if (wrapper_type == MONO_WRAPPER_ISINST)
1229                                 ji->data.method = mono_marshal_get_isinst (klass);
1230                         else
1231                                 g_assert_not_reached ();
1232                         break;
1233                 }
1234                 case MONO_WRAPPER_LDFLD_REMOTE:
1235                         ji->data.method = mono_marshal_get_ldfld_remote_wrapper (NULL);
1236                         break;
1237                 case MONO_WRAPPER_STFLD_REMOTE:
1238                         ji->data.method = mono_marshal_get_stfld_remote_wrapper (NULL);
1239                         break;
1240                 case MONO_WRAPPER_ALLOC: {
1241                         int atype = decode_value (p, &p);
1242
1243                         ji->type = MONO_PATCH_INFO_METHOD;
1244                         ji->data.method = mono_gc_get_managed_allocator_by_type (atype);
1245                         break;
1246                 }
1247                 case MONO_WRAPPER_STELEMREF:
1248                         ji->type = MONO_PATCH_INFO_METHOD;
1249                         ji->data.method = mono_marshal_get_stelemref ();
1250                         break;
1251                 default:
1252                         g_assert_not_reached ();
1253                 }
1254                 break;
1255         }
1256         case MONO_PATCH_INFO_INTERNAL_METHOD: {
1257                 guint32 len = decode_value (p, &p);
1258
1259                 ji->data.name = (char*)p;
1260                 p += len + 1;
1261                 break;
1262         }
1263         case MONO_PATCH_INFO_VTABLE:
1264         case MONO_PATCH_INFO_CLASS:
1265         case MONO_PATCH_INFO_IID:
1266         case MONO_PATCH_INFO_ADJUSTED_IID:
1267                 *got_offset = decode_value (p, &p);
1268
1269                 if (aot_module->got [*got_offset]) {
1270                         /* Already loaded */
1271                         //printf ("HIT!\n");
1272                 } else {
1273                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1274                         ji->data.klass = decode_klass_ref (aot_module, tmp, &tmp);
1275                         if (!ji->data.klass)
1276                                 goto cleanup;
1277                 }
1278                 break;
1279         case MONO_PATCH_INFO_CLASS_INIT:
1280         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1281                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1282                 if (!ji->data.klass)
1283                         goto cleanup;
1284                 break;
1285         case MONO_PATCH_INFO_IMAGE:
1286                 ji->data.image = load_image (aot_module, decode_value (p, &p));
1287                 if (!ji->data.image)
1288                         goto cleanup;
1289                 break;
1290         case MONO_PATCH_INFO_FIELD:
1291         case MONO_PATCH_INFO_SFLDA:
1292                 *got_offset = decode_value (p, &p);
1293
1294                 if (aot_module->got [*got_offset]) {
1295                         /* Already loaded */
1296                         //printf ("HIT2!\n");
1297                 } else {
1298                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1299                         ji->data.field = decode_field_info (aot_module, tmp, &tmp);
1300                         if (!ji->data.field)
1301                                 goto cleanup;
1302                 }
1303                 break;
1304         case MONO_PATCH_INFO_SWITCH:
1305                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
1306                 ji->data.table->table_size = decode_value (p, &p);
1307                 table = g_new (gpointer, ji->data.table->table_size);
1308                 ji->data.table->table = (MonoBasicBlock**)table;
1309                 for (i = 0; i < ji->data.table->table_size; i++)
1310                         table [i] = (gpointer)(gssize)decode_value (p, &p);
1311                 break;
1312         case MONO_PATCH_INFO_R4: {
1313                 guint32 val;
1314                 
1315                 ji->data.target = mono_mempool_alloc0 (mp, sizeof (float));
1316                 val = decode_value (p, &p);
1317                 *(float*)ji->data.target = *(float*)&val;
1318                 break;
1319         }
1320         case MONO_PATCH_INFO_R8: {
1321                 guint32 val [2];
1322
1323                 ji->data.target = mono_mempool_alloc0 (mp, sizeof (double));
1324
1325                 val [0] = decode_value (p, &p);
1326                 val [1] = decode_value (p, &p);
1327                 *(double*)ji->data.target = *(double*)val;
1328                 break;
1329         }
1330         case MONO_PATCH_INFO_LDSTR:
1331                 image = load_image (aot_module, decode_value (p, &p));
1332                 if (!image)
1333                         goto cleanup;
1334                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
1335                 break;
1336         case MONO_PATCH_INFO_RVA:
1337         case MONO_PATCH_INFO_DECLSEC:
1338         case MONO_PATCH_INFO_LDTOKEN:
1339         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1340                 *got_offset = decode_value (p, &p);
1341
1342                 if (aot_module->got [*got_offset]) {
1343                         /* Already loaded */
1344                 } else {
1345                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1346                         image = load_image (aot_module, decode_value (tmp, &tmp));
1347                         if (!image)
1348                                 goto cleanup;
1349                         ji->data.token = mono_jump_info_token_new (mp, image, decode_value (tmp, &tmp));
1350                 }
1351                 break;
1352         case MONO_PATCH_INFO_EXC_NAME:
1353                 ji->data.klass = decode_klass_ref (aot_module, p, &p);
1354                 if (!ji->data.klass)
1355                         goto cleanup;
1356                 ji->data.name = ji->data.klass->name;
1357                 break;
1358         case MONO_PATCH_INFO_METHOD_REL:
1359                 ji->data.offset = decode_value (p, &p);
1360                 break;
1361         default:
1362                 g_warning ("unhandled type %d", ji->type);
1363                 g_assert_not_reached ();
1364         }
1365
1366         *endbuf = p;
1367
1368         return TRUE;
1369
1370  cleanup:
1371         return FALSE;
1372 }
1373
1374 static MonoJumpInfo*
1375 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
1376                                  guint32 got_index, guint32 **got_slots, 
1377                                  guint8 *buf, guint8 **endbuf)
1378 {
1379         MonoJumpInfo *patches;
1380         MonoJumpInfo *patch_info = NULL;
1381         int pindex;
1382         guint32 last_offset;
1383         guint8 *p;
1384
1385         p = buf;
1386
1387         /* First load the type + offset table */
1388         last_offset = 0;
1389         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
1390
1391         for (pindex = 0; pindex < n_patches; ++pindex) {                
1392                 MonoJumpInfo *ji = &patches [pindex];
1393
1394                 ji->type = *p;
1395                 p ++;
1396
1397                 //printf ("T: %d O: %d.\n", ji->type, ji->ip.i);
1398                 ji->next = patch_info;
1399                 patch_info = ji;
1400         }
1401
1402         *got_slots = g_malloc (sizeof (guint32) * n_patches);
1403         memset (*got_slots, 0xff, sizeof (guint32) * n_patches);
1404
1405         /* Then load the other data */
1406         for (pindex = 0; pindex < n_patches; ++pindex) {
1407                 MonoJumpInfo *ji = &patches [pindex];
1408
1409                 if (!decode_patch_info (aot_module, mp, ji, p, &p, (*got_slots) + pindex))
1410                         goto cleanup;
1411
1412                 if ((*got_slots) [pindex] == 0xffffffff)
1413                         (*got_slots) [pindex] = got_index ++;
1414         }
1415
1416         *endbuf = p;
1417         return patches;
1418
1419  cleanup:
1420         g_free (*got_slots);
1421         *got_slots = NULL;
1422
1423         return NULL;
1424 }
1425  
1426 static gpointer
1427 mono_aot_get_method_inner (MonoDomain *domain, MonoMethod *method)
1428 {
1429         MonoClass *klass = method->klass;
1430         MonoAssembly *ass = klass->image->assembly;
1431         MonoDl *module = ass->aot_module;
1432         guint32 method_index = mono_metadata_token_index (method->token) - 1;
1433         guint8 *code, *info;
1434         MonoAotModule *aot_module;
1435
1436         if (!module)
1437                 return NULL;
1438
1439         if (!method->token)
1440                 return NULL;
1441
1442         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1443                 return NULL;
1444
1445         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1446                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1447                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1448                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1449                 return NULL;
1450         
1451         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1452
1453         g_assert (klass->inited);
1454
1455         if ((domain != mono_get_root_domain ()) && (!(aot_module->opts & MONO_OPT_SHARED)))
1456                 /* Non shared AOT code can't be used in other appdomains */
1457                 return NULL;
1458
1459         if (aot_module->out_of_date)
1460                 return NULL;
1461
1462         if (method->is_inflated) {
1463                 if (!mono_method_is_generic_sharable_impl (method))
1464                         return NULL;
1465                 method = mono_method_get_declaring_generic_method (method);
1466         }
1467
1468         if (aot_module->code_offsets [method_index] == 0xffffffff) {
1469                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1470                         char *full_name = mono_method_full_name (method, TRUE);
1471                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
1472                         g_free (full_name);
1473                 }
1474                 return NULL;
1475         }
1476
1477         code = &aot_module->code [aot_module->code_offsets [method_index]];
1478         info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1479
1480         if (!aot_module->methods_loaded)
1481                 aot_module->methods_loaded = g_new0 (guint32, klass->image->tables [MONO_TABLE_METHOD].rows + 1);
1482
1483         if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1484                 return code;
1485
1486         if (mono_last_aot_method != -1) {
1487                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1488                                 return NULL;
1489                 else
1490                         if (mono_jit_stats.methods_aot == mono_last_aot_method)
1491                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", klass->name_space, klass->name, method->name);
1492         }
1493
1494         return mono_aot_load_method (domain, aot_module, method, code, info);
1495 }
1496
1497 static gpointer
1498 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info)
1499 {
1500         MonoClass *klass = method->klass;
1501         MonoJumpInfo *patch_info = NULL;
1502         MonoMemPool *mp;
1503         int i, pindex, got_index = 0, n_patches, used_strings;
1504         gboolean non_got_patches, keep_patches = TRUE;
1505         guint32 method_index = mono_metadata_token_index (method->token) - 1;
1506         guint8 *p, *ex_info;
1507         MonoJitInfo *jinfo = NULL;
1508
1509         p = info;
1510         decode_klass_ref (aot_module, p, &p);
1511
1512         if (!use_loaded_code) {
1513                 guint8 *code2;
1514
1515                 if (!jinfo) {
1516                         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1517                         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1518                 }
1519
1520                 code2 = mono_code_manager_reserve (domain->code_mp, jinfo->code_size);
1521                 memcpy (code2, code, jinfo->code_size);
1522                 mono_arch_flush_icache (code2, jinfo->code_size);
1523                 code = code2;
1524         }
1525
1526         if (aot_module->opts & MONO_OPT_SHARED)
1527                 used_strings = decode_value (p, &p);
1528         else
1529                 used_strings = 0;
1530
1531         for (i = 0; i < used_strings; i++) {
1532                 guint token = decode_value (p, &p);
1533                 mono_ldstr (mono_get_root_domain (), klass->image, mono_metadata_token_index (token));
1534         }
1535
1536         if (aot_module->opts & MONO_OPT_SHARED) 
1537                 keep_patches = FALSE;
1538
1539         n_patches = decode_value (p, &p);
1540
1541         keep_patches = FALSE;
1542
1543         if (n_patches) {
1544                 MonoJumpInfo *patches;
1545                 guint32 *got_slots;
1546
1547                 if (keep_patches)
1548                         mp = domain->mp;
1549                 else
1550                         mp = mono_mempool_new ();
1551
1552                 got_index = decode_value (p, &p);
1553
1554                 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1555                 if (patches == NULL)
1556                         goto cleanup;
1557
1558                 /* Do this outside the lock to avoid deadlocks */
1559                 mono_aot_unlock ();
1560                 non_got_patches = FALSE;
1561                 for (pindex = 0; pindex < n_patches; ++pindex) {
1562                         MonoJumpInfo *ji = &patches [pindex];
1563
1564                         if (is_got_patch (ji->type)) {
1565                                 if (!aot_module->got [got_slots [pindex]])
1566                                         aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
1567                                 ji->type = MONO_PATCH_INFO_NONE;
1568                         }
1569                         else
1570                                 non_got_patches = TRUE;
1571                 }
1572                 if (non_got_patches) {
1573                         if (!jinfo) {
1574                                 ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1575                                 jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1576                         }
1577
1578                         mono_arch_flush_icache (code, jinfo->code_size);
1579                         make_writable (code, jinfo->code_size);
1580                         mono_arch_patch_code (method, domain, code, patch_info, TRUE);
1581                 }
1582                 mono_aot_lock ();
1583
1584                 g_free (got_slots);
1585
1586                 if (!keep_patches)
1587                         mono_mempool_destroy (mp);
1588         }
1589
1590         mono_jit_stats.methods_aot++;
1591
1592         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1593                 char *full_name = mono_method_full_name (method, TRUE);
1594
1595                 if (!jinfo) {
1596                         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1597                         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1598                 }
1599
1600                 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);
1601                 g_free (full_name);
1602         }
1603
1604         aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1605
1606         init_plt (aot_module);
1607
1608         return code;
1609
1610  cleanup:
1611         /* FIXME: The space in domain->mp is wasted */  
1612         if (aot_module->opts & MONO_OPT_SHARED)
1613                 /* No need to cache patches */
1614                 mono_mempool_destroy (mp);
1615
1616         if (jinfo)
1617                 g_free (jinfo);
1618
1619         return NULL;
1620 }
1621
1622 gpointer
1623 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
1624 {
1625         gpointer code;
1626
1627         mono_aot_lock ();
1628         code = mono_aot_get_method_inner (domain, method);
1629         mono_aot_unlock ();
1630
1631         return code;
1632 }
1633
1634 static gpointer
1635 mono_aot_get_method_from_token_inner (MonoDomain *domain, MonoImage *image, guint32 token, MonoClass **klass)
1636 {
1637         MonoAssembly *ass = image->assembly;
1638         MonoMemPool *mp;
1639         int i, method_index, pindex, got_index, n_patches, used_strings;
1640         gboolean keep_patches = TRUE;
1641         guint8 *p;
1642         MonoDl *module = ass->aot_module;
1643         guint8 *code = NULL;
1644         guint8 *info;
1645         MonoAotModule *aot_module;
1646
1647         *klass = NULL;
1648
1649         if (!module)
1650                 return NULL;
1651
1652         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1653                 return NULL;
1654
1655         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1656
1657         if (domain != mono_get_root_domain ())
1658                 return NULL;
1659
1660         if (aot_module->out_of_date)
1661                 return NULL;
1662
1663         if (aot_module->code_offsets [mono_metadata_token_index (token) - 1] == 0xffffffff) {
1664                 return NULL;
1665         }
1666
1667         method_index = mono_metadata_token_index (token) - 1;
1668         code = &aot_module->code [aot_module->code_offsets [method_index]];
1669         info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1670
1671         if (!aot_module->methods_loaded)
1672                 aot_module->methods_loaded = g_new0 (guint32, image->tables [MONO_TABLE_METHOD].rows + 1);
1673
1674         if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1675                 return code;
1676
1677         if (mono_last_aot_method != -1) {
1678                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1679                                 return NULL;
1680                 else
1681                         if (mono_jit_stats.methods_aot == mono_last_aot_method) {
1682                                 MonoMethod *method = mono_get_method (image, token, NULL);
1683                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", method->klass->name_space, method->klass->name, method->name);
1684                         }
1685         }
1686
1687         p = info;
1688         *klass = decode_klass_ref (aot_module, p, &p);
1689
1690         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1691                 MonoMethod *method = mono_get_method (image, token, NULL);
1692                 char *full_name = mono_method_full_name (method, TRUE);
1693                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p %p\n", full_name, code, info);
1694                 g_free (full_name);
1695         }
1696
1697         if (aot_module->opts & MONO_OPT_SHARED)
1698                 used_strings = decode_value (p, &p);
1699         else
1700                 used_strings = 0;
1701
1702         for (i = 0; i < used_strings; i++) {
1703                 guint string_token = decode_value (p, &p);
1704                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (string_token));
1705         }
1706
1707         if (aot_module->opts & MONO_OPT_SHARED) 
1708                 keep_patches = FALSE;
1709
1710         keep_patches = FALSE;
1711
1712         n_patches = decode_value (p, &p);
1713
1714         if (n_patches) {
1715                 MonoJumpInfo *patches;
1716                 guint32 *got_slots;
1717
1718                 if (keep_patches)
1719                         mp = domain->mp;
1720                 else
1721                         mp = mono_mempool_new ();
1722
1723                 got_index = decode_value (p, &p);
1724
1725                 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1726                 if (patches == NULL)
1727                         goto cleanup;
1728
1729                 /* Do this outside the lock to avoid deadlocks */
1730                 mono_aot_unlock ();
1731
1732                 for (pindex = 0; pindex < n_patches; ++pindex) {
1733                         MonoJumpInfo *ji = &patches [pindex];
1734
1735                         if (is_got_patch (ji->type)) {
1736                                 if (!aot_module->got [got_slots [pindex]])
1737                                         aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (NULL, domain, code, ji, TRUE);
1738                                 ji->type = MONO_PATCH_INFO_NONE;
1739                         }
1740                 }
1741
1742                 mono_aot_lock ();
1743
1744                 g_free (got_slots);
1745
1746                 if (!keep_patches)
1747                         mono_mempool_destroy (mp);
1748         }
1749
1750         mono_jit_stats.methods_aot++;
1751
1752         aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1753
1754         init_plt (aot_module);
1755
1756         return code;
1757
1758  cleanup:
1759         /* FIXME: The space in domain->mp is wasted */  
1760         if (aot_module->opts & MONO_OPT_SHARED)
1761                 /* No need to cache patches */
1762                 mono_mempool_destroy (mp);
1763
1764         return NULL;
1765 }
1766
1767 /**
1768  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
1769  * method.
1770  */
1771 gpointer
1772 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
1773 {
1774         gpointer res;   
1775         MonoClass *klass;
1776
1777         mono_aot_lock ();
1778         res = mono_aot_get_method_from_token_inner (domain, image, token, &klass);
1779         mono_aot_unlock ();
1780
1781         if (!res)
1782                 return NULL;
1783
1784         if (klass)
1785                 mono_runtime_class_init (mono_class_vtable (domain, klass));
1786
1787         return res;
1788 }
1789
1790 typedef struct {
1791         guint8 *addr;
1792         gboolean res;
1793 } IsGotEntryUserData;
1794
1795 static void
1796 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
1797 {
1798         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
1799         MonoAotModule *aot_module = (MonoAotModule*)value;
1800
1801         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->got_size)))
1802                 data->res = TRUE;
1803 }
1804
1805 gboolean
1806 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
1807 {
1808         IsGotEntryUserData user_data;
1809
1810         if (!aot_modules)
1811                 return FALSE;
1812
1813         user_data.addr = addr;
1814         user_data.res = FALSE;
1815         mono_aot_lock ();
1816         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
1817         mono_aot_unlock ();
1818         
1819         return user_data.res;
1820 }
1821
1822 typedef struct {
1823         guint8 *addr;
1824         MonoAotModule *module;
1825 } FindAotModuleUserData;
1826
1827 static void
1828 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
1829 {
1830         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
1831         MonoAotModule *aot_module = (MonoAotModule*)value;
1832
1833         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
1834                 data->module = aot_module;
1835 }
1836
1837 static inline MonoAotModule*
1838 find_aot_module (guint8 *code)
1839 {
1840         FindAotModuleUserData user_data;
1841
1842         if (!aot_modules)
1843                 return NULL;
1844
1845         /* Reading these need no locking */
1846         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
1847                 return NULL;
1848
1849         user_data.addr = code;
1850         user_data.module = NULL;
1851                 
1852         mono_aot_lock ();
1853         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
1854         mono_aot_unlock ();
1855         
1856         return user_data.module;
1857 }
1858
1859 /*
1860  * mono_aot_set_make_unreadable:
1861  *
1862  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
1863  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
1864  */
1865 void
1866 mono_aot_set_make_unreadable (gboolean unreadable)
1867 {
1868         make_unreadable = unreadable;
1869 }
1870
1871 typedef struct {
1872         MonoAotModule *module;
1873         guint8 *ptr;
1874 } FindMapUserData;
1875
1876 static void
1877 find_map (gpointer key, gpointer value, gpointer user_data)
1878 {
1879         MonoAotModule *module = (MonoAotModule*)value;
1880         FindMapUserData *data = (FindMapUserData*)user_data;
1881
1882         if (!data->module)
1883                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
1884                         data->module = module;
1885 }
1886
1887 static MonoAotModule*
1888 find_module_for_addr (void *ptr)
1889 {
1890         FindMapUserData data;
1891
1892         if (!make_unreadable)
1893                 return NULL;
1894
1895         data.module = NULL;
1896         data.ptr = (guint8*)ptr;
1897
1898         mono_aot_lock ();
1899         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
1900         mono_aot_unlock ();
1901
1902         return data.module;
1903 }
1904
1905 /*
1906  * mono_aot_is_pagefault:
1907  *
1908  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
1909  * within memory allocated by this module.
1910  */
1911 gboolean
1912 mono_aot_is_pagefault (void *ptr)
1913 {
1914         if (!make_unreadable)
1915                 return FALSE;
1916
1917         return find_module_for_addr (ptr) != NULL;
1918 }
1919
1920 /*
1921  * mono_aot_handle_pagefault:
1922  *
1923  *   Handle a pagefault caused by an unreadable page by making it readable again.
1924  */
1925 void
1926 mono_aot_handle_pagefault (void *ptr)
1927 {
1928 #ifndef PLATFORM_WIN32
1929         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), PAGESIZE);
1930         int res;
1931
1932         mono_aot_lock ();
1933         res = mprotect (start, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
1934         g_assert (res == 0);
1935
1936         n_pagefaults ++;
1937         mono_aot_unlock ();
1938
1939 #if 0
1940  {
1941         void *array [256];
1942         char **names;
1943         int i, size;
1944
1945         printf ("\nNative stacktrace:\n\n");
1946
1947         size = backtrace (array, 256);
1948         names = backtrace_symbols (array, size);
1949         for (i =0; i < size; ++i) {
1950                 printf ("\t%s\n", names [i]);
1951         }
1952         free (names);
1953  }
1954 #endif
1955
1956 #endif
1957 }
1958
1959 /*
1960  * mono_aot_plt_resolve:
1961  *
1962  *   This function is called by the entries in the PLT to resolve the actual method that
1963  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
1964  */
1965 gpointer
1966 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
1967 {
1968 #ifdef MONO_ARCH_AOT_SUPPORTED
1969         guint8 *p, *target, *plt_entry;
1970         MonoJumpInfo ji;
1971         MonoAotModule *module = (MonoAotModule*)aot_module;
1972         gboolean res;
1973
1974         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
1975
1976         p = &module->plt_info [plt_info_offset];
1977
1978         ji.type = decode_value (p, &p);
1979
1980         res = decode_patch_info (module, NULL, &ji, p, &p, NULL);
1981         // FIXME: Error handling (how ?)
1982         g_assert (res);
1983
1984         target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
1985
1986         /* Patch the PLT entry with target which might be the actual method not a trampoline */
1987         plt_entry = mono_aot_get_plt_entry (code);
1988         g_assert (plt_entry);
1989         mono_arch_patch_plt_entry (plt_entry, target);
1990
1991         return target;
1992 #else
1993         g_assert_not_reached ();
1994         return NULL;
1995 #endif
1996 }
1997
1998 /**
1999  * init_plt:
2000  *
2001  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
2002  * method in the module is loaded to avoid committing memory by writing to it.
2003  * LOCKING: Assumes the AOT lock is held.
2004  */
2005 static void
2006 init_plt (MonoAotModule *info)
2007 {
2008 #ifdef MONO_ARCH_AOT_SUPPORTED
2009 #ifdef __i386__
2010         guint8 *buf = info->plt;
2011 #elif defined(__x86_64__)
2012         int i, n_entries;
2013 #elif defined(__arm__)
2014         int i, n_entries;
2015 #endif
2016         gpointer tramp;
2017
2018         if (info->plt_inited)
2019                 return;
2020
2021         tramp = mono_arch_create_specific_trampoline (info, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
2022
2023 #ifdef __i386__
2024         /* Initialize the first PLT entry */
2025         make_writable (info->plt, info->plt_end - info->plt);
2026         x86_jump_code (buf, tramp);
2027 #elif defined(__x86_64__)
2028         /*
2029          * Initialize the entries in the plt_jump_table to point to the default targets.
2030          */
2031          n_entries = info->plt_jump_table_size / sizeof (gpointer);
2032
2033          /* The first entry points to the AOT trampoline */
2034          ((gpointer*)info->plt_jump_table)[0] = tramp;
2035          for (i = 1; i < n_entries; ++i)
2036                  /* Each PLT entry is 16 bytes long, the default entry begins at offset 6 */
2037                  ((gpointer*)info->plt_jump_table)[i] = info->plt + (i * 16) + 6;
2038 #elif defined(__arm__)
2039          /* Initialize the first PLT entry */
2040          make_writable (info->plt, info->plt_end - info->plt);
2041          ((guint32*)info->plt)[1] = (guint32)tramp;
2042
2043          n_entries = ((guint8*)info->plt_end - (guint8*)info->plt) / 8;
2044
2045          /* 
2046           * Initialize the jump targets embedded inside the PLT entries to the default
2047           * targets.
2048           */
2049          for (i = 1; i < n_entries; ++i)
2050                  /* Each PLT entry is 8 bytes long, the jump target is at offset 4 */
2051                  /* Each default PLT target is 12 bytes long */
2052                  ((guint32*)info->plt)[(i * 2) + 1] = (guint8*)info->plt_end + ((i - 1) * 12);
2053 #else
2054         g_assert_not_reached ();
2055 #endif
2056
2057         info->plt_inited = TRUE;
2058 #endif
2059 }
2060
2061 /*
2062  * mono_aot_get_plt_entry:
2063  *
2064  *   Return the address of the PLT entry called by the code at CODE if exists.
2065  */
2066 guint8*
2067 mono_aot_get_plt_entry (guint8 *code)
2068 {
2069         MonoAotModule *aot_module = find_aot_module (code);
2070 #if defined(__arm__)
2071         guint32 ins;
2072 #endif
2073
2074         if (!aot_module)
2075                 return NULL;
2076
2077 #if defined(__i386__) || defined(__x86_64__)
2078         if (code [-5] == 0xe8) {
2079                 guint32 disp = *(guint32*)(code - 4);
2080                 guint8 *target = code + disp;
2081
2082                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2083                         return target;
2084         }
2085 #elif defined(__arm__)
2086         ins = ((guint32*)(gpointer)code) [-1];
2087
2088         /* Should be a 'bl' */
2089         if ((((ins >> 25) & 0x7) == 0x5) && (((ins >> 24) & 0x1) == 0x1)) {
2090                 gint32 disp = ((gint32)ins) & 0xffffff;
2091                 guint8 *target = code - 4 + 8 + (disp * 4);
2092
2093                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
2094                         return target;
2095         }               
2096 #else
2097         g_assert_not_reached ();
2098 #endif
2099
2100         return NULL;
2101 }
2102
2103 /*
2104  * mono_aot_get_n_pagefaults:
2105  *
2106  *   Return the number of times handle_pagefault is called.
2107  */
2108 guint32
2109 mono_aot_get_n_pagefaults (void)
2110 {
2111         return n_pagefaults;
2112 }
2113
2114 #else
2115 /* AOT disabled */
2116
2117 void
2118 mono_aot_init (void)
2119 {
2120 }
2121
2122 gpointer
2123 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
2124 {
2125         return NULL;
2126 }
2127
2128 gboolean
2129 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
2130 {
2131         return FALSE;
2132 }
2133
2134 gboolean
2135 mono_aot_init_vtable (MonoVTable *vtable)
2136 {
2137         return FALSE;
2138 }
2139
2140 gboolean
2141 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
2142 {
2143         return FALSE;
2144 }
2145
2146 gboolean
2147 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
2148 {
2149         return FALSE;
2150 }
2151
2152 MonoJitInfo *
2153 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
2154 {
2155         return NULL;
2156 }
2157
2158 gpointer
2159 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
2160 {
2161         return NULL;
2162 }
2163
2164 gboolean
2165 mono_aot_is_pagefault (void *ptr)
2166 {
2167         return FALSE;
2168 }
2169
2170 void
2171 mono_aot_set_make_unreadable (gboolean unreadable)
2172 {
2173 }
2174
2175 guint32
2176 mono_aot_get_n_pagefaults (void)
2177 {
2178         return 0;
2179 }
2180
2181 void
2182 mono_aot_handle_pagefault (void *ptr)
2183 {
2184 }
2185
2186 guint8*
2187 mono_aot_get_plt_entry (guint8 *code)
2188 {
2189         return NULL;
2190 }
2191
2192 gpointer
2193 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
2194 {
2195         return NULL;
2196 }
2197
2198 gpointer
2199 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
2200 {
2201         return NULL;
2202 }
2203 #endif