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