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