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