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