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