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