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