New test.
[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 (assembly->aot_module)
444                 /* 
445                  * Already loaded. This can happen because the assembly loading code might invoke
446                  * the assembly load hooks multiple times for the same assembly.
447                  */
448                 return;
449
450         if (use_aot_cache)
451                 assembly->aot_module = load_aot_module_from_cache (assembly, &aot_name);
452         else {
453                 aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);
454
455                 assembly->aot_module = g_module_open (aot_name, G_MODULE_BIND_LAZY);
456
457                 if (!assembly->aot_module) {
458                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, g_module_error ());
459                 }
460         }
461
462         if (!assembly->aot_module) {
463                 g_free (aot_name);
464                 return;
465         }
466
467         g_module_symbol (assembly->aot_module, "mono_assembly_guid", (gpointer *) &saved_guid);
468         g_module_symbol (assembly->aot_module, "mono_aot_version", (gpointer *) &aot_version);
469         g_module_symbol (assembly->aot_module, "mono_aot_opt_flags", (gpointer *)&opt_flags);
470
471         if (!aot_version || strcmp (aot_version, MONO_AOT_FILE_VERSION)) {
472                 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);
473                 usable = FALSE;
474         }
475         else {
476                 if (!saved_guid || strcmp (assembly->image->guid, saved_guid)) {
477                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is out of date.\n", aot_name);
478                         usable = FALSE;
479                 }
480         }
481
482         if (!usable) {
483                 g_free (aot_name);
484                 g_module_close (assembly->aot_module);
485                 assembly->aot_module = NULL;
486                 return;
487         }
488
489         g_module_symbol (assembly->aot_module, "got_addr", (gpointer *)&got_addr);
490         g_assert (got_addr);
491         got = (gpointer*)*got_addr;
492         g_assert (got);
493         g_module_symbol (assembly->aot_module, "got_size", (gpointer *)&got_size_ptr);
494         g_assert (got_size_ptr);
495
496         info = g_new0 (MonoAotModule, 1);
497         info->aot_name = aot_name;
498         info->got = got;
499         info->got_size = *got_size_ptr;
500         info->got [0] = assembly->image;
501
502         sscanf (opt_flags, "%d", &info->opts);
503
504         /* Read image table */
505         {
506                 guint32 table_len, i;
507                 char *table = NULL;
508
509                 g_module_symbol (assembly->aot_module, "mono_image_table", (gpointer *)&table);
510                 g_assert (table);
511
512                 table_len = *(guint32*)table;
513                 table += sizeof (guint32);
514                 info->image_table = g_new0 (MonoImage*, table_len);
515                 info->image_names = g_new0 (MonoAssemblyName, table_len);
516                 info->image_guids = g_new0 (char*, table_len);
517                 info->image_table_len = table_len;
518                 for (i = 0; i < table_len; ++i) {
519                         MonoAssemblyName *aname = &(info->image_names [i]);
520
521                         aname->name = g_strdup (table);
522                         table += strlen (table) + 1;
523                         info->image_guids [i] = g_strdup (table);
524                         table += strlen (table) + 1;
525                         if (table [0] != 0)
526                                 aname->culture = g_strdup (table);
527                         table += strlen (table) + 1;
528                         memcpy (aname->public_key_token, table, strlen (table) + 1);
529                         table += strlen (table) + 1;                    
530
531                         table = ALIGN_PTR_TO (table, 8);
532                         aname->flags = *(guint32*)table;
533                         table += 4;
534                         aname->major = *(guint32*)table;
535                         table += 4;
536                         aname->minor = *(guint32*)table;
537                         table += 4;
538                         aname->build = *(guint32*)table;
539                         table += 4;
540                         aname->revision = *(guint32*)table;
541                         table += 4;
542                 }
543         }
544
545         /* Read method and method_info tables */
546         g_module_symbol (assembly->aot_module, "method_offsets", (gpointer*)&info->code_offsets);
547         g_module_symbol (assembly->aot_module, "methods", (gpointer*)&info->code);
548         g_module_symbol (assembly->aot_module, "methods_end", (gpointer*)&info->code_end);
549         g_module_symbol (assembly->aot_module, "method_info_offsets", (gpointer*)&info->method_info_offsets);
550         g_module_symbol (assembly->aot_module, "method_info", (gpointer*)&info->method_info);
551         g_module_symbol (assembly->aot_module, "ex_info_offsets", (gpointer*)&info->ex_info_offsets);
552         g_module_symbol (assembly->aot_module, "ex_info", (gpointer*)&info->ex_info);
553         g_module_symbol (assembly->aot_module, "method_order", (gpointer*)&info->method_order);
554         g_module_symbol (assembly->aot_module, "method_order_end", (gpointer*)&info->method_order_end);
555         g_module_symbol (assembly->aot_module, "class_info", (gpointer*)&info->class_info);
556         g_module_symbol (assembly->aot_module, "class_info_offsets", (gpointer*)&info->class_info_offsets);
557         g_module_symbol (assembly->aot_module, "class_name_table", (gpointer *)&info->class_name_table);
558         g_module_symbol (assembly->aot_module, "got_info", (gpointer*)&info->got_info);
559         g_module_symbol (assembly->aot_module, "got_info_offsets", (gpointer*)&info->got_info_offsets);
560         g_module_symbol (assembly->aot_module, "mem_end", (gpointer*)&info->mem_end);
561
562         info->mem_begin = info->code;
563
564         g_module_symbol (assembly->aot_module, "plt", (gpointer*)&info->plt);
565         g_module_symbol (assembly->aot_module, "plt_end", (gpointer*)&info->plt_end);
566         g_module_symbol (assembly->aot_module, "plt_info", (gpointer*)&info->plt_info);
567
568         g_module_symbol (assembly->aot_module, "plt_jump_table_addr", (gpointer *)&plt_jump_table_addr);
569         g_assert (plt_jump_table_addr);
570         info->plt_jump_table = (guint8*)*plt_jump_table_addr;
571         g_assert (info->plt_jump_table);
572
573         g_module_symbol (assembly->aot_module, "plt_jump_table_size", (gpointer *)&plt_jump_table_size);
574         g_assert (plt_jump_table_size);
575         info->plt_jump_table_size = *plt_jump_table_size;
576
577         if (make_unreadable) {
578 #ifndef PLATFORM_WIN32
579                 guint8 *addr;
580                 guint8 *page_start;
581                 int pages, err, len;
582
583                 addr = info->mem_begin;
584                 len = info->mem_end - info->mem_begin;
585
586                 /* Round down in both directions to avoid modifying data which is not ours */
587                 page_start = (guint8 *) (((gssize) (addr)) & ~ (PAGESIZE - 1)) + PAGESIZE;
588                 pages = ((addr + len - page_start + PAGESIZE - 1) / PAGESIZE) - 1;
589                 err = mprotect (page_start, pages * PAGESIZE, 0);
590                 g_assert (err == 0);
591 #endif
592         }
593
594         mono_aot_lock ();
595
596         aot_code_low_addr = MIN (aot_code_low_addr, (gsize)info->code);
597         aot_code_high_addr = MAX (aot_code_high_addr, (gsize)info->code_end);
598
599         g_hash_table_insert (aot_modules, assembly, info);
600         mono_aot_unlock ();
601
602         mono_jit_info_add_aot_module (assembly->image, info->code, info->code_end);
603
604         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
605 }
606
607 void
608 mono_aot_init (void)
609 {
610         InitializeCriticalSection (&aot_mutex);
611         aot_modules = g_hash_table_new (NULL, NULL);
612
613         mono_install_assembly_load_hook (load_aot_module, NULL);
614
615         if (getenv ("MONO_LASTAOT"))
616                 mono_last_aot_method = atoi (getenv ("MONO_LASTAOT"));
617         if (getenv ("MONO_AOT_CACHE"))
618                 use_aot_cache = TRUE;
619 }
620
621 static gboolean
622 decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
623 {
624         guint32 flags;
625
626         info->vtable_size = decode_value (buf, &buf);
627         flags = decode_value (buf, &buf);
628         info->ghcimpl = (flags >> 0) & 0x1;
629         info->has_finalize = (flags >> 1) & 0x1;
630         info->has_cctor = (flags >> 2) & 0x1;
631         info->has_nested_classes = (flags >> 3) & 0x1;
632         info->blittable = (flags >> 4) & 0x1;
633         info->has_references = (flags >> 5) & 0x1;
634         info->has_static_refs = (flags >> 6) & 0x1;
635         info->no_special_static_fields = (flags >> 7) & 0x1;
636
637         if (info->has_cctor) {
638                 MonoImage *cctor_image = decode_method_ref (module, &info->cctor_token, buf, &buf);
639                 if (!cctor_image)
640                         return FALSE;
641         }
642         if (info->has_finalize) {
643                 info->finalize_image = decode_method_ref (module, &info->finalize_token, buf, &buf);
644                 if (!info->finalize_image)
645                         return FALSE;
646         }
647
648         info->instance_size = decode_value (buf, &buf);
649         info->class_size = decode_value (buf, &buf);
650         info->packing_size = decode_value (buf, &buf);
651         info->min_align = decode_value (buf, &buf);
652
653         *endbuf = buf;
654
655         return TRUE;
656 }       
657
658 gboolean
659 mono_aot_init_vtable (MonoVTable *vtable)
660 {
661         int i;
662         MonoAotModule *aot_module;
663         MonoClass *klass = vtable->klass;
664         guint8 *info, *p;
665         MonoCachedClassInfo class_info;
666         gboolean err;
667
668         if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !klass->image->assembly->aot_module)
669                 return FALSE;
670
671         mono_aot_lock ();
672
673         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
674         if (!aot_module) {
675                 mono_aot_unlock ();
676                 return FALSE;
677         }
678
679         info = &aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
680         p = info;
681
682         err = decode_cached_class_info (aot_module, &class_info, p, &p);
683         if (!err) {
684                 mono_aot_unlock ();
685                 return FALSE;
686         }
687
688         //printf ("VT0: %s.%s %d\n", klass->name_space, klass->name, vtable_size);
689         for (i = 0; i < class_info.vtable_size; ++i) {
690                 guint32 image_index, token, value;
691                 MonoImage *image;
692 #ifndef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
693                 MonoMethod *m;
694 #endif
695
696                 vtable->vtable [i] = 0;
697
698                 value = decode_value (p, &p);
699                 if (!value)
700                         continue;
701
702                 image_index = value >> 24;
703                 token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
704
705                 image = load_image (aot_module, image_index);
706                 if (!image) {
707                         mono_aot_unlock ();
708                         return FALSE;
709                 }
710
711 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
712                 vtable->vtable [i] = mono_create_jit_trampoline_from_token (image, token);
713 #else
714                 m = mono_get_method (image, token, NULL);
715                 g_assert (m);
716
717                 //printf ("M: %d %p %s\n", i, &(vtable->vtable [i]), mono_method_full_name (m, TRUE));
718                 vtable->vtable [i] = mono_create_jit_trampoline (m);
719 #endif
720         }
721
722         mono_aot_unlock ();
723
724         return TRUE;
725 }
726
727 gboolean
728 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
729 {
730         MonoAotModule *aot_module;
731         guint8 *p;
732         gboolean err;
733
734         if (klass->rank || !klass->image->assembly->aot_module)
735                 return FALSE;
736
737         mono_aot_lock ();
738
739         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, klass->image->assembly);
740         if (!aot_module) {
741                 mono_aot_unlock ();
742                 return FALSE;
743         }
744
745         p = (guint8*)&aot_module->class_info [aot_module->class_info_offsets [mono_metadata_token_index (klass->type_token) - 1]];
746
747         err = decode_cached_class_info (aot_module, res, p, &p);
748         if (!err) {
749                 mono_aot_unlock ();
750                 return FALSE;
751         }
752
753         mono_aot_unlock ();
754
755         return TRUE;
756 }
757
758 /**
759  * mono_aot_get_class_from_name:
760  *
761  *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
762  * using a cache stored in the AOT file.
763  * Stores the resulting class in *KLASS if found, stores NULL otherwise.
764  *
765  * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
766  * found.
767  */
768 gboolean
769 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
770 {
771         MonoAotModule *aot_module;
772         guint32 *table, *entry;
773         guint32 table_size, hash;
774         char full_name_buf [1024];
775         char *full_name;
776         const char *name2, *name_space2;
777         MonoTableInfo  *t;
778         guint32 cols [MONO_TYPEDEF_SIZE];
779
780         if (!aot_modules)
781                 return FALSE;
782
783         mono_aot_lock ();
784
785         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, image->assembly);
786         if (!aot_module || !aot_module->class_name_table) {
787                 mono_aot_unlock ();
788                 return FALSE;
789         }
790
791         *klass = NULL;
792
793         table_size = aot_module->class_name_table [0];
794         table = aot_module->class_name_table + 1;
795
796         if (name_space [0] == '\0')
797                 full_name = g_strdup_printf ("%s", name);
798         else {
799                 if (strlen (name_space) + strlen (name) < 1000) {
800                         sprintf (full_name_buf, "%s.%s", name_space, name);
801                         full_name = full_name_buf;
802                 } else {
803                         full_name = g_strdup_printf ("%s.%s", name_space, name);
804                 }
805         }
806         hash = g_str_hash (full_name) % table_size;
807         if (full_name != full_name_buf)
808                 g_free (full_name);
809
810         entry = &table [hash * 2];
811
812         if (entry [0] != 0) {
813                 t = &image->tables [MONO_TABLE_TYPEDEF];
814
815                 while (TRUE) {
816                         guint32 token = entry [0];
817                         guint32 next = entry [1];
818                         guint32 index = mono_metadata_token_index (token);
819
820                         name_table_accesses ++;
821
822                         mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
823
824                         name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
825                         name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
826
827                         if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
828                                 mono_aot_unlock ();
829                                 *klass = mono_class_get (image, token);
830                                 return TRUE;
831                         }
832
833                         if (next != 0) {
834                                 entry = &table [next * 2];
835                         } else {
836                                 break;
837                         }
838                 }
839         }
840
841         mono_aot_unlock ();
842         
843         return TRUE;
844 }
845
846 static MonoJitInfo*
847 decode_exception_debug_info (MonoAotModule *aot_module, MonoDomain *domain, 
848                                                          MonoMethod *method, guint8* ex_info, guint8 *code)
849 {
850         int i, buf_len;
851         MonoJitInfo *jinfo;
852         guint code_len, used_int_regs;
853         guint8 *p;
854         MonoMethodHeader *header;
855
856         header = mono_method_get_header (method);
857
858         /* Load the method info from the AOT file */
859
860         p = ex_info;
861         code_len = decode_value (p, &p);
862         used_int_regs = decode_value (p, &p);
863
864         /* Exception table */
865         if (header->num_clauses) {
866                 jinfo = 
867                         mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo) + (sizeof (MonoJitExceptionInfo) * header->num_clauses));
868                 jinfo->num_clauses = header->num_clauses;
869
870                 for (i = 0; i < header->num_clauses; ++i) {
871                         MonoExceptionClause *ec = &header->clauses [i];                         
872                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
873
874                         ei->flags = ec->flags;
875                         ei->exvar_offset = decode_value (p, &p);
876
877                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
878                                 ei->data.filter = code + decode_value (p, &p);
879                         else
880                                 ei->data.catch_class = ec->data.catch_class;
881
882                         ei->try_start = code + decode_value (p, &p);
883                         ei->try_end = code + decode_value (p, &p);
884                         ei->handler_start = code + decode_value (p, &p);
885                 }
886         }
887         else
888                 jinfo = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
889
890         jinfo->code_size = code_len;
891         jinfo->used_regs = used_int_regs;
892         jinfo->method = method;
893         jinfo->code_start = code;
894         jinfo->domain_neutral = 0;
895
896         /* Load debug info */
897         buf_len = decode_value (p, &p);
898         mono_debug_add_aot_method (domain, method, code, p, buf_len);
899         
900         return jinfo;
901 }
902
903 MonoJitInfo *
904 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
905 {
906         MonoAssembly *ass = image->assembly;
907         GModule *module = ass->aot_module;
908         int pos, left, right, offset, offset1, offset2, last_offset, new_offset, page_index, method_index, table_len;
909         guint32 token;
910         MonoAotModule *aot_module;
911         MonoMethod *method;
912         MonoJitInfo *jinfo;
913         guint8 *code, *ex_info;
914         guint32 *table, *ptr;
915         gboolean found;
916
917         if (!module)
918                 return NULL;
919
920         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
921
922         if (domain != mono_get_root_domain ())
923                 /* FIXME: */
924                 return NULL;
925
926         offset = (guint8*)addr - aot_module->code;
927
928         /* First search through the index */
929         ptr = aot_module->method_order;
930         last_offset = 0;
931         page_index = 0;
932         found = FALSE;
933
934         if (*ptr == 0xffffff)
935                 return NULL;
936         ptr ++;
937
938         while (*ptr != 0xffffff) {
939                 guint32 method_index = ptr [0];
940                 new_offset = aot_module->code_offsets [method_index];
941
942                 if (offset >= last_offset && offset < new_offset) {
943                         found = TRUE;
944                         break;
945                 }
946
947                 ptr ++;
948                 last_offset = new_offset;
949                 page_index ++;
950         }
951
952         /* Skip rest of index */
953         while (*ptr != 0xffffff)
954                 ptr ++;
955         ptr ++;
956
957         table = ptr;
958         table_len = aot_module->method_order_end - table;
959
960         g_assert (table <= aot_module->method_order_end);
961
962         if (found) {
963                 left = (page_index * 1024);
964                 right = left + 1024;
965
966                 if (right > table_len)
967                         right = table_len;
968
969                 offset1 = aot_module->code_offsets [table [left]];
970                 g_assert (offset1 <= offset);
971
972                 //printf ("Found in index: 0x%x 0x%x 0x%x\n", offset, last_offset, new_offset);
973         }
974         else {
975                 //printf ("Not found in index: 0x%x\n", offset);
976                 left = 0;
977                 right = table_len;
978         }
979
980         /* Binary search inside the method_order table to find the method */
981         while (TRUE) {
982                 pos = (left + right) / 2;
983
984                 g_assert (table + pos <= aot_module->method_order_end);
985
986                 //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]]);
987
988                 offset1 = aot_module->code_offsets [table [pos]];
989                 if (table + pos + 1 >= aot_module->method_order_end)
990                         offset2 = aot_module->code_end - aot_module->code;
991                 else
992                         offset2 = aot_module->code_offsets [table [pos + 1]];
993
994                 if (offset < offset1)
995                         right = pos;
996                 else if (offset >= offset2)
997                         left = pos + 1;
998                 else
999                         break;
1000         }
1001
1002         method_index = table [pos];
1003
1004         token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
1005         method = mono_get_method (image, token, NULL);
1006
1007         /* FIXME: */
1008         g_assert (method);
1009
1010         //printf ("F: %s\n", mono_method_full_name (method, TRUE));
1011
1012         code = &aot_module->code [aot_module->code_offsets [method_index]];
1013         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [method_index]];
1014
1015         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1016
1017         g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
1018         g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);
1019
1020         /* Add it to the normal JitInfo tables */
1021         mono_jit_info_table_add (domain, jinfo);
1022         
1023         return jinfo;
1024 }
1025
1026 static gboolean
1027 decode_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf, guint32 *got_offset)
1028 {
1029         guint8 *p = buf;
1030         gpointer *table;
1031         MonoImage *image;
1032         int i;
1033
1034         switch (ji->type) {
1035         case MONO_PATCH_INFO_METHOD:
1036         case MONO_PATCH_INFO_METHODCONST:
1037         case MONO_PATCH_INFO_METHOD_JUMP: {
1038                 guint32 image_index, token, value;
1039
1040                 value = decode_value (p, &p);
1041                 image_index = value >> 24;
1042                 token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1043
1044                 image = load_image (aot_module, image_index);
1045                 if (!image)
1046                         goto cleanup;
1047
1048 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
1049                 if (ji->type == MONO_PATCH_INFO_METHOD) {
1050                         ji->data.target = mono_create_jit_trampoline_from_token (image, token);
1051                         ji->type = MONO_PATCH_INFO_ABS;
1052                 }
1053                 else {
1054                         ji->data.method = mono_get_method (image, token, NULL);
1055                         g_assert (ji->data.method);
1056                         mono_class_init (ji->data.method->klass);
1057                 }
1058 #else
1059                 ji->data.method = mono_get_method (image, token, NULL);
1060                 g_assert (ji->data.method);
1061                 mono_class_init (ji->data.method->klass);
1062 #endif
1063
1064                 break;
1065         }
1066         case MONO_PATCH_INFO_WRAPPER: {
1067                 guint32 wrapper_type;
1068
1069                 wrapper_type = decode_value (p, &p);
1070
1071                 switch (wrapper_type) {
1072                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
1073                         guint32 image_index, token, value;
1074
1075                         value = decode_value (p, &p);
1076                         image_index = value >> 24;
1077                         token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
1078
1079                         image = load_image (aot_module, image_index);
1080                         if (!image)
1081                                 goto cleanup;
1082                         ji->data.method = mono_get_method (image, token, NULL);
1083                         g_assert (ji->data.method);
1084                         mono_class_init (ji->data.method->klass);
1085
1086                         ji->type = MONO_PATCH_INFO_METHOD;
1087                         ji->data.method = mono_marshal_get_remoting_invoke_with_check (ji->data.method);
1088                         break;
1089                 }
1090                 case MONO_WRAPPER_PROXY_ISINST: {
1091                         MonoClass *klass = decode_klass_info (aot_module, p, &p);
1092                         if (!klass)
1093                                 goto cleanup;
1094                         ji->type = MONO_PATCH_INFO_METHOD;
1095                         ji->data.method = mono_marshal_get_proxy_cancast (klass);
1096                         break;
1097                 }
1098                 case MONO_WRAPPER_LDFLD:
1099                 case MONO_WRAPPER_LDFLDA:
1100                 case MONO_WRAPPER_STFLD:
1101                 case MONO_WRAPPER_LDFLD_REMOTE:
1102                 case MONO_WRAPPER_STFLD_REMOTE:
1103                 case MONO_WRAPPER_ISINST: {
1104                         MonoClass *klass = decode_klass_info (aot_module, p, &p);
1105                         if (!klass)
1106                                 goto cleanup;
1107                         ji->type = MONO_PATCH_INFO_METHOD;
1108                         if (wrapper_type == MONO_WRAPPER_LDFLD)
1109                                 ji->data.method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
1110                         else if (wrapper_type == MONO_WRAPPER_LDFLDA)
1111                                 ji->data.method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
1112                         else if (wrapper_type == MONO_WRAPPER_STFLD)
1113                                 ji->data.method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
1114                         else if (wrapper_type == MONO_WRAPPER_LDFLD_REMOTE)
1115                                 ji->data.method = mono_marshal_get_ldfld_remote_wrapper (klass);
1116                         else if (wrapper_type == MONO_WRAPPER_STFLD_REMOTE)
1117                                 ji->data.method = mono_marshal_get_stfld_remote_wrapper (klass);
1118                         else if (wrapper_type == MONO_WRAPPER_ISINST)
1119                                 ji->data.method = mono_marshal_get_isinst (klass);
1120                         else
1121                                 g_assert_not_reached ();
1122                         break;
1123                 }
1124                 case MONO_WRAPPER_STELEMREF:
1125                         ji->type = MONO_PATCH_INFO_METHOD;
1126                         ji->data.method = mono_marshal_get_stelemref ();
1127                         break;
1128                 default:
1129                         g_assert_not_reached ();
1130                 }
1131                 break;
1132         }
1133         case MONO_PATCH_INFO_INTERNAL_METHOD: {
1134                 guint32 len = decode_value (p, &p);
1135
1136                 ji->data.name = (char*)p;
1137                 p += len + 1;
1138                 break;
1139         }
1140         case MONO_PATCH_INFO_VTABLE:
1141         case MONO_PATCH_INFO_CLASS:
1142         case MONO_PATCH_INFO_IID:
1143         case MONO_PATCH_INFO_ADJUSTED_IID:
1144                 *got_offset = decode_value (p, &p);
1145
1146                 if (aot_module->got [*got_offset]) {
1147                         /* Already loaded */
1148                         //printf ("HIT!\n");
1149                 } else {
1150                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1151                         ji->data.klass = decode_klass_info (aot_module, tmp, &tmp);
1152                         if (!ji->data.klass)
1153                                 goto cleanup;
1154                 }
1155                 break;
1156         case MONO_PATCH_INFO_CLASS_INIT:
1157                 ji->data.klass = decode_klass_info (aot_module, p, &p);
1158                 if (!ji->data.klass)
1159                         goto cleanup;
1160                 break;
1161         case MONO_PATCH_INFO_IMAGE:
1162                 ji->data.image = load_image (aot_module, decode_value (p, &p));
1163                 if (!ji->data.image)
1164                         goto cleanup;
1165                 break;
1166         case MONO_PATCH_INFO_FIELD:
1167         case MONO_PATCH_INFO_SFLDA:
1168                 *got_offset = decode_value (p, &p);
1169
1170                 if (aot_module->got [*got_offset]) {
1171                         /* Already loaded */
1172                         //printf ("HIT2!\n");
1173                 } else {
1174                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1175                         ji->data.field = decode_field_info (aot_module, tmp, &tmp);
1176                         if (!ji->data.field)
1177                                 goto cleanup;
1178                 }
1179                 break;
1180         case MONO_PATCH_INFO_SWITCH:
1181                 ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
1182                 ji->data.table->table_size = decode_value (p, &p);
1183                 table = g_new (gpointer, ji->data.table->table_size);
1184                 ji->data.table->table = (MonoBasicBlock**)table;
1185                 for (i = 0; i < ji->data.table->table_size; i++)
1186                         table [i] = (gpointer)(gssize)decode_value (p, &p);
1187                 break;
1188         case MONO_PATCH_INFO_R4: {
1189                 guint32 val;
1190                 
1191                 ji->data.target = mono_mempool_alloc0 (mp, sizeof (float));
1192                 val = decode_value (p, &p);
1193                 *(float*)ji->data.target = *(float*)&val;
1194                 break;
1195         }
1196         case MONO_PATCH_INFO_R8: {
1197                 guint32 val [2];
1198
1199                 ji->data.target = mono_mempool_alloc0 (mp, sizeof (double));
1200
1201                 val [0] = decode_value (p, &p);
1202                 val [1] = decode_value (p, &p);
1203                 *(double*)ji->data.target = *(double*)val;
1204                 break;
1205         }
1206         case MONO_PATCH_INFO_LDSTR:
1207                 image = load_image (aot_module, decode_value (p, &p));
1208                 if (!image)
1209                         goto cleanup;
1210                 ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
1211                 break;
1212         case MONO_PATCH_INFO_DECLSEC:
1213         case MONO_PATCH_INFO_LDTOKEN:
1214         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1215                 *got_offset = decode_value (p, &p);
1216
1217                 if (aot_module->got [*got_offset]) {
1218                         /* Already loaded */
1219                 } else {
1220                         guint8 *tmp = aot_module->got_info + aot_module->got_info_offsets [*got_offset];
1221                         image = load_image (aot_module, decode_value (tmp, &tmp));
1222                         if (!image)
1223                                 goto cleanup;
1224                         ji->data.token = mono_jump_info_token_new (mp, image, decode_value (tmp, &tmp));
1225                 }
1226                 break;
1227         case MONO_PATCH_INFO_EXC_NAME:
1228                 ji->data.klass = decode_klass_info (aot_module, p, &p);
1229                 if (!ji->data.klass)
1230                         goto cleanup;
1231                 ji->data.name = ji->data.klass->name;
1232                 break;
1233         case MONO_PATCH_INFO_METHOD_REL:
1234                 ji->data.offset = decode_value (p, &p);
1235                 break;
1236         default:
1237                 g_warning ("unhandled type %d", ji->type);
1238                 g_assert_not_reached ();
1239         }
1240
1241         *endbuf = p;
1242
1243         return TRUE;
1244
1245  cleanup:
1246         return FALSE;
1247 }
1248
1249 static MonoJumpInfo*
1250 load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
1251                                  guint32 got_index, guint32 **got_slots, 
1252                                  guint8 *buf, guint8 **endbuf)
1253 {
1254         MonoJumpInfo *patches;
1255         MonoJumpInfo *patch_info = NULL;
1256         int pindex;
1257         guint32 last_offset;
1258         guint8 *p;
1259
1260         p = buf;
1261
1262         /* First load the type + offset table */
1263         last_offset = 0;
1264         patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
1265
1266         for (pindex = 0; pindex < n_patches; ++pindex) {                
1267                 MonoJumpInfo *ji = &patches [pindex];
1268
1269                 ji->type = *p;
1270                 p ++;
1271
1272                 //printf ("T: %d O: %d.\n", ji->type, ji->ip.i);
1273                 ji->next = patch_info;
1274                 patch_info = ji;
1275         }
1276
1277         *got_slots = g_malloc (sizeof (guint32) * n_patches);
1278         memset (*got_slots, 0xff, sizeof (guint32) * n_patches);
1279
1280         /* Then load the other data */
1281         for (pindex = 0; pindex < n_patches; ++pindex) {
1282                 MonoJumpInfo *ji = &patches [pindex];
1283
1284                 if (!decode_patch_info (aot_module, mp, ji, p, &p, (*got_slots) + pindex))
1285                         goto cleanup;
1286
1287                 if ((*got_slots) [pindex] == 0xffffffff)
1288                         (*got_slots) [pindex] = got_index ++;
1289         }
1290
1291         *endbuf = p;
1292         return patches;
1293
1294  cleanup:
1295         g_free (*got_slots);
1296         *got_slots = NULL;
1297
1298         return NULL;
1299 }
1300  
1301 static MonoJitInfo *
1302 mono_aot_get_method_inner (MonoDomain *domain, MonoMethod *method)
1303 {
1304         MonoClass *klass = method->klass;
1305         MonoAssembly *ass = klass->image->assembly;
1306         GModule *module = ass->aot_module;
1307         guint8 *code, *info, *ex_info;
1308         MonoAotModule *aot_module;
1309
1310         if (!module)
1311                 return NULL;
1312
1313         if (!method->token)
1314                 return NULL;
1315
1316         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1317                 return NULL;
1318
1319         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1320                 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1321                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1322                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1323                 return NULL;
1324         
1325         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1326
1327         g_assert (klass->inited);
1328
1329         if ((domain != mono_get_root_domain ()) && (!(aot_module->opts & MONO_OPT_SHARED)))
1330                 /* Non shared AOT code can't be used in other appdomains */
1331                 return NULL;
1332
1333         if (aot_module->out_of_date)
1334                 return NULL;
1335
1336         if (aot_module->code_offsets [mono_metadata_token_index (method->token) - 1] == 0xffffffff) {
1337                 if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1338                         char *full_name = mono_method_full_name (method, TRUE);
1339                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
1340                         g_free (full_name);
1341                 }
1342                 return NULL;
1343         }
1344
1345         code = &aot_module->code [aot_module->code_offsets [mono_metadata_token_index (method->token) - 1]];
1346         info = &aot_module->method_info [aot_module->method_info_offsets [mono_metadata_token_index (method->token) - 1]];
1347         ex_info = &aot_module->ex_info [aot_module->ex_info_offsets [mono_metadata_token_index (method->token) - 1]];
1348
1349         if (mono_last_aot_method != -1) {
1350                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1351                                 return NULL;
1352                 else
1353                         if (mono_jit_stats.methods_aot == mono_last_aot_method)
1354                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", klass->name_space, klass->name, method->name);
1355         }
1356
1357         return mono_aot_load_method (domain, aot_module, method, code, info, ex_info);
1358 }
1359
1360 static MonoJitInfo*
1361 mono_aot_load_method (MonoDomain *domain, MonoAotModule *aot_module, MonoMethod *method, guint8 *code, guint8 *info, guint8* ex_info)
1362 {
1363         MonoClass *klass = method->klass;
1364         MonoJumpInfo *patch_info = NULL;
1365         MonoJitInfo *jinfo;
1366         MonoMemPool *mp;
1367         int i, pindex, got_index = 0, n_patches, used_strings;
1368         gboolean non_got_patches, keep_patches = TRUE;
1369         guint8 *p;
1370
1371         jinfo = decode_exception_debug_info (aot_module, domain, method, ex_info, code);
1372
1373         p = info;
1374         decode_klass_info (aot_module, p, &p);
1375
1376         if (!use_loaded_code) {
1377                 guint8 *code2;
1378                 code2 = mono_code_manager_reserve (domain->code_mp, jinfo->code_size);
1379                 memcpy (code2, code, jinfo->code_size);
1380                 mono_arch_flush_icache (code2, jinfo->code_size);
1381                 code = code2;
1382         }
1383
1384         if (aot_module->opts & MONO_OPT_SHARED)
1385                 used_strings = decode_value (p, &p);
1386         else
1387                 used_strings = 0;
1388
1389         for (i = 0; i < used_strings; i++) {
1390                 guint token = decode_value (p, &p);
1391                 mono_ldstr (mono_get_root_domain (), klass->image, mono_metadata_token_index (token));
1392         }
1393
1394         if (aot_module->opts & MONO_OPT_SHARED) 
1395                 keep_patches = FALSE;
1396
1397         n_patches = decode_value (p, &p);
1398
1399         keep_patches = FALSE;
1400
1401         if (n_patches) {
1402                 MonoJumpInfo *patches;
1403                 guint32 *got_slots;
1404
1405                 if (keep_patches)
1406                         mp = domain->mp;
1407                 else
1408                         mp = mono_mempool_new ();
1409
1410                 got_index = decode_value (p, &p);
1411
1412                 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1413                 if (patches == NULL)
1414                         goto cleanup;
1415
1416                 /* Do this outside the lock to avoid deadlocks */
1417                 mono_aot_unlock ();
1418                 non_got_patches = FALSE;
1419                 for (pindex = 0; pindex < n_patches; ++pindex) {
1420                         MonoJumpInfo *ji = &patches [pindex];
1421
1422                         if (is_got_patch (ji->type)) {
1423                                 if (!aot_module->got [got_slots [pindex]])
1424                                         aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
1425                                 ji->type = MONO_PATCH_INFO_NONE;
1426                         }
1427                         else
1428                                 non_got_patches = TRUE;
1429                 }
1430                 if (non_got_patches) {
1431                         mono_arch_flush_icache (code, jinfo->code_size);
1432                         make_writable (code, jinfo->code_size);
1433                         mono_arch_patch_code (method, domain, code, patch_info, TRUE);
1434                 }
1435                 mono_aot_lock ();
1436
1437                 g_free (got_slots);
1438
1439                 if (!keep_patches)
1440                         mono_mempool_destroy (mp);
1441         }
1442
1443         mono_jit_stats.methods_aot++;
1444
1445         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1446                 char *full_name = mono_method_full_name (method, TRUE);
1447                 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);
1448                 g_free (full_name);
1449         }
1450
1451         init_plt (aot_module);
1452
1453         return jinfo;
1454
1455  cleanup:
1456         /* FIXME: The space in domain->mp is wasted */  
1457         if (aot_module->opts & MONO_OPT_SHARED)
1458                 /* No need to cache patches */
1459                 mono_mempool_destroy (mp);
1460
1461         return NULL;
1462 }
1463
1464 MonoJitInfo*
1465 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
1466 {
1467         MonoJitInfo *info;
1468
1469         mono_aot_lock ();
1470         info = mono_aot_get_method_inner (domain, method);
1471         mono_aot_unlock ();
1472
1473         /* Do this outside the lock */
1474         if (info) {
1475                 mono_jit_info_table_add (domain, info);
1476                 return info;
1477         }
1478         else
1479                 return NULL;
1480 }
1481
1482 static gpointer
1483 mono_aot_get_method_from_token_inner (MonoDomain *domain, MonoImage *image, guint32 token, MonoClass **klass)
1484 {
1485         MonoAssembly *ass = image->assembly;
1486         MonoMemPool *mp;
1487         int i, method_index, pindex, got_index, n_patches, used_strings;
1488         gboolean keep_patches = TRUE;
1489         guint8 *p;
1490         GModule *module = ass->aot_module;
1491         guint8 *code = NULL;
1492         guint8 *info;
1493         MonoAotModule *aot_module;
1494
1495         *klass = NULL;
1496
1497         if (!module)
1498                 return NULL;
1499
1500         if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
1501                 return NULL;
1502
1503         aot_module = (MonoAotModule*) g_hash_table_lookup (aot_modules, ass);
1504
1505         if (domain != mono_get_root_domain ())
1506                 return NULL;
1507
1508         if (aot_module->out_of_date)
1509                 return NULL;
1510
1511         if (aot_module->code_offsets [mono_metadata_token_index (token) - 1] == 0xffffffff) {
1512                 return NULL;
1513         }
1514
1515         method_index = mono_metadata_token_index (token) - 1;
1516         code = &aot_module->code [aot_module->code_offsets [method_index]];
1517         info = &aot_module->method_info [aot_module->method_info_offsets [method_index]];
1518
1519         if (!aot_module->methods_loaded)
1520                 aot_module->methods_loaded = g_new0 (guint32, image->tables [MONO_TABLE_METHOD].rows + 1);
1521
1522         if ((aot_module->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
1523                 return code;
1524
1525         if (mono_last_aot_method != -1) {
1526                 if (mono_jit_stats.methods_aot > mono_last_aot_method)
1527                                 return NULL;
1528                 else
1529                         if (mono_jit_stats.methods_aot == mono_last_aot_method) {
1530                                 MonoMethod *method = mono_get_method (image, token, NULL);
1531                                 printf ("LAST AOT METHOD: %s.%s.%s.\n", method->klass->name_space, method->klass->name, method->name);
1532                         }
1533         }
1534
1535         p = info;
1536         *klass = decode_klass_info (aot_module, p, &p);
1537
1538         if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
1539                 MonoMethod *method = mono_get_method (image, token, NULL);
1540                 char *full_name = mono_method_full_name (method, TRUE);
1541                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND AOT compiled code for %s %p %p\n", full_name, code, info);
1542                 g_free (full_name);
1543         }
1544
1545         if (aot_module->opts & MONO_OPT_SHARED)
1546                 used_strings = decode_value (p, &p);
1547         else
1548                 used_strings = 0;
1549
1550         for (i = 0; i < used_strings; i++) {
1551                 guint string_token = decode_value (p, &p);
1552                 mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (string_token));
1553         }
1554
1555         if (aot_module->opts & MONO_OPT_SHARED) 
1556                 keep_patches = FALSE;
1557
1558         keep_patches = FALSE;
1559
1560         n_patches = decode_value (p, &p);
1561
1562         if (n_patches) {
1563                 MonoJumpInfo *patches;
1564                 guint32 *got_slots;
1565
1566                 if (keep_patches)
1567                         mp = domain->mp;
1568                 else
1569                         mp = mono_mempool_new ();
1570
1571                 got_index = decode_value (p, &p);
1572
1573                 patches = load_patch_info (aot_module, mp, n_patches, got_index, &got_slots, p, &p);
1574                 if (patches == NULL)
1575                         goto cleanup;
1576
1577                 /* Do this outside the lock to avoid deadlocks */
1578                 mono_aot_unlock ();
1579
1580                 for (pindex = 0; pindex < n_patches; ++pindex) {
1581                         MonoJumpInfo *ji = &patches [pindex];
1582
1583                         if (is_got_patch (ji->type)) {
1584                                 if (!aot_module->got [got_slots [pindex]])
1585                                         aot_module->got [got_slots [pindex]] = mono_resolve_patch_target (NULL, domain, code, ji, TRUE);
1586                                 ji->type = MONO_PATCH_INFO_NONE;
1587                         }
1588                 }
1589
1590                 mono_aot_lock ();
1591
1592                 g_free (got_slots);
1593
1594                 if (!keep_patches)
1595                         mono_mempool_destroy (mp);
1596         }
1597
1598         mono_jit_stats.methods_aot++;
1599
1600         aot_module->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
1601
1602         init_plt (aot_module);
1603
1604         return code;
1605
1606  cleanup:
1607         /* FIXME: The space in domain->mp is wasted */  
1608         if (aot_module->opts & MONO_OPT_SHARED)
1609                 /* No need to cache patches */
1610                 mono_mempool_destroy (mp);
1611
1612         return NULL;
1613 }
1614
1615 /**
1616  * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
1617  * method.
1618  */
1619 gpointer
1620 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
1621 {
1622         gpointer res;   
1623         MonoClass *klass;
1624
1625         mono_aot_lock ();
1626         res = mono_aot_get_method_from_token_inner (domain, image, token, &klass);
1627         mono_aot_unlock ();
1628
1629         if (!res)
1630                 return NULL;
1631
1632         if (klass)
1633                 mono_runtime_class_init (mono_class_vtable (domain, klass));
1634
1635         return res;
1636 }
1637
1638 typedef struct {
1639         guint8 *addr;
1640         gboolean res;
1641 } IsGotEntryUserData;
1642
1643 static void
1644 check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
1645 {
1646         IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
1647         MonoAotModule *aot_module = (MonoAotModule*)value;
1648
1649         if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->got_size)))
1650                 data->res = TRUE;
1651 }
1652
1653 gboolean
1654 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
1655 {
1656         IsGotEntryUserData user_data;
1657
1658         if (!aot_modules)
1659                 return FALSE;
1660
1661         user_data.addr = addr;
1662         user_data.res = FALSE;
1663         mono_aot_lock ();
1664         g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
1665         mono_aot_unlock ();
1666         
1667         return user_data.res;
1668 }
1669
1670 typedef struct {
1671         guint8 *addr;
1672         MonoAotModule *module;
1673 } FindAotModuleUserData;
1674
1675 static void
1676 find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
1677 {
1678         FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
1679         MonoAotModule *aot_module = (MonoAotModule*)value;
1680
1681         if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
1682                 data->module = aot_module;
1683 }
1684
1685 static inline MonoAotModule*
1686 find_aot_module (guint8 *code)
1687 {
1688         FindAotModuleUserData user_data;
1689
1690         if (!aot_modules)
1691                 return NULL;
1692
1693         /* Reading these need no locking */
1694         if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
1695                 return NULL;
1696
1697         user_data.addr = code;
1698         user_data.module = NULL;
1699                 
1700         mono_aot_lock ();
1701         g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
1702         mono_aot_unlock ();
1703         
1704         return user_data.module;
1705 }
1706
1707 /*
1708  * mono_aot_set_make_unreadable:
1709  *
1710  *   Set whenever to make all mmaped memory unreadable. In conjuction with a
1711  * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
1712  */
1713 void
1714 mono_aot_set_make_unreadable (gboolean unreadable)
1715 {
1716         make_unreadable = unreadable;
1717 }
1718
1719 typedef struct {
1720         MonoAotModule *module;
1721         guint8 *ptr;
1722 } FindMapUserData;
1723
1724 static void
1725 find_map (gpointer key, gpointer value, gpointer user_data)
1726 {
1727         MonoAotModule *module = (MonoAotModule*)value;
1728         FindMapUserData *data = (FindMapUserData*)user_data;
1729
1730         if (!data->module)
1731                 if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
1732                         data->module = module;
1733 }
1734
1735 static MonoAotModule*
1736 find_module_for_addr (void *ptr)
1737 {
1738         FindMapUserData data;
1739
1740         if (!make_unreadable)
1741                 return NULL;
1742
1743         data.module = NULL;
1744         data.ptr = (guint8*)ptr;
1745
1746         mono_aot_lock ();
1747         g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
1748         mono_aot_unlock ();
1749
1750         return data.module;
1751 }
1752
1753 /*
1754  * mono_aot_is_pagefault:
1755  *
1756  *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
1757  * within memory allocated by this module.
1758  */
1759 gboolean
1760 mono_aot_is_pagefault (void *ptr)
1761 {
1762         if (!make_unreadable)
1763                 return FALSE;
1764
1765         return find_module_for_addr (ptr) != NULL;
1766 }
1767
1768 /*
1769  * mono_aot_handle_pagefault:
1770  *
1771  *   Handle a pagefault caused by an unreadable page by making it readable again.
1772  */
1773 void
1774 mono_aot_handle_pagefault (void *ptr)
1775 {
1776 #ifndef PLATFORM_WIN32
1777         guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), PAGESIZE);
1778         int res;
1779
1780         mono_aot_lock ();
1781         res = mprotect (start, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
1782         g_assert (res == 0);
1783
1784         n_pagefaults ++;
1785         mono_aot_unlock ();
1786 #endif
1787 }
1788
1789 /*
1790  * aot_dyn_resolve:
1791  *
1792  *   This function is called by the entries in the PLT to resolve the actual method that
1793  * needs to be called. It returns a trampoline to the method and patches the PLT entry.
1794  */
1795 gpointer
1796 mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
1797 {
1798 #ifdef MONO_ARCH_HAVE_PIC_AOT
1799         guint8 *p, *target, *plt_entry;
1800         MonoJumpInfo ji;
1801         MonoAotModule *module = (MonoAotModule*)aot_module;
1802         gboolean res;
1803
1804         //printf ("DYN: %p %d\n", aot_module, plt_info_offset);
1805
1806         p = &module->plt_info [plt_info_offset];
1807
1808         ji.type = decode_value (p, &p);
1809
1810         res = decode_patch_info (module, NULL, &ji, p, &p, NULL);
1811         // FIXME: Error handling (how ?)
1812         g_assert (res);
1813
1814         target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
1815
1816         /* Patch the PLT entry with target which might be the actual method not a trampoline */
1817         plt_entry = mono_aot_get_plt_entry (code);
1818         g_assert (plt_entry);
1819         mono_arch_patch_plt_entry (plt_entry, target);
1820
1821         return target;
1822 #else
1823         g_assert_not_reached ();
1824         return NULL;
1825 #endif
1826 }
1827
1828 /**
1829  * init_plt:
1830  *
1831  *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
1832  * method in the module is loaded to avoid committing memory by writing to it.
1833  * LOCKING: Assumes the AOT lock is held.
1834  */
1835 static void
1836 init_plt (MonoAotModule *info)
1837 {
1838 #ifdef MONO_ARCH_HAVE_PIC_AOT
1839 #ifdef __i386__
1840         guint8 *buf = info->plt;
1841 #endif
1842 #if defined(__x86_64__)
1843         int i, n_entries;
1844 #endif
1845         gpointer tramp;
1846
1847         if (info->plt_inited)
1848                 return;
1849
1850         tramp = mono_arch_create_specific_trampoline (info, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);
1851
1852 #ifdef __i386__
1853         /* Initialize the first PLT entry */
1854         make_writable (info->plt, info->plt_end - info->plt);
1855         x86_jump_code (buf, tramp);
1856 #elif defined(__x86_64__)
1857         /*
1858          * Initialize the entries in the plt_jump_table to point to the default targets.
1859          */
1860          n_entries = info->plt_jump_table_size / sizeof (gpointer);
1861
1862          /* The first entry points to the AOT trampoline */
1863          ((gpointer*)info->plt_jump_table)[0] = tramp;
1864          for (i = 1; i < n_entries; ++i)
1865                  /* Each PLT entry is 16 bytes long, the default entry begins at offset 6 */
1866                  ((gpointer*)info->plt_jump_table)[i] = info->plt + (i * 16) + 6;
1867 #else
1868         g_assert_not_reached ();
1869 #endif
1870
1871         info->plt_inited = TRUE;
1872 #endif
1873 }
1874
1875 /*
1876  * mono_aot_get_plt_entry:
1877  *
1878  *   Return the address of the PLT entry called by the code at CODE if exists.
1879  */
1880 guint8*
1881 mono_aot_get_plt_entry (guint8 *code)
1882 {
1883         MonoAotModule *aot_module = find_aot_module (code);
1884
1885         if (!aot_module)
1886                 return NULL;
1887
1888 #if defined(__i386__) || defined(__x86_64__)
1889         if (code [-5] == 0xe8) {
1890                 guint32 disp = *(guint32*)(code - 4);
1891                 guint8 *target = code + disp;
1892
1893                 if ((target >= (guint8*)(aot_module->plt)) && (target < (guint8*)(aot_module->plt_end)))
1894                         return target;
1895         }
1896 #endif
1897
1898         return NULL;
1899 }
1900
1901 /*
1902  * mono_aot_get_n_pagefaults:
1903  *
1904  *   Return the number of times handle_pagefault is called.
1905  */
1906 guint32
1907 mono_aot_get_n_pagefaults (void)
1908 {
1909         return n_pagefaults;
1910 }
1911
1912 #else
1913 /* AOT disabled */
1914
1915 void
1916 mono_aot_init (void)
1917 {
1918 }
1919
1920 MonoJitInfo*
1921 mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
1922 {
1923         return NULL;
1924 }
1925
1926 gboolean
1927 mono_aot_is_got_entry (guint8 *code, guint8 *addr)
1928 {
1929         return FALSE;
1930 }
1931
1932 gboolean
1933 mono_aot_init_vtable (MonoVTable *vtable)
1934 {
1935         return FALSE;
1936 }
1937
1938 gboolean
1939 mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
1940 {
1941         return FALSE;
1942 }
1943
1944 gboolean
1945 mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
1946 {
1947         return FALSE;
1948 }
1949
1950 MonoJitInfo *
1951 mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
1952 {
1953         return NULL;
1954 }
1955
1956 gpointer
1957 mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
1958 {
1959         return NULL;
1960 }
1961
1962 gboolean
1963 mono_aot_is_pagefault (void *ptr)
1964 {
1965         return FALSE;
1966 }
1967
1968 void
1969 mono_aot_set_make_unreadable (gboolean unreadable)
1970 {
1971 }
1972
1973 guint32
1974 mono_aot_get_n_pagefaults (void)
1975 {
1976         return 0;
1977 }
1978
1979 void
1980 mono_aot_handle_pagefault (void *ptr)
1981 {
1982 }
1983
1984 guint8*
1985 mono_aot_get_plt_entry (guint8 *code)
1986 {
1987         return NULL;
1988 }
1989
1990 #endif