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