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