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