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