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