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