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