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