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